content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This file is generated from the fsx-2018-03-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.FSx.Model { /// <summary> /// The Lustre configuration for the file system being created. /// </summary> public partial class CreateFileSystemLustreConfiguration { private AutoImportPolicyType _autoImportPolicy; private int? _automaticBackupRetentionDays; private bool? _copyTagsToBackups; private string _dailyAutomaticBackupStartTime; private DataCompressionType _dataCompressionType; private LustreDeploymentType _deploymentType; private DriveCacheType _driveCacheType; private string _exportPath; private int? _importedFileChunkSize; private string _importPath; private int? _perUnitStorageThroughput; private string _weeklyMaintenanceStartTime; /// <summary> /// Gets and sets the property AutoImportPolicy. /// <para> /// (Optional) When you create your file system, your existing S3 objects appear as file /// and directory listings. Use this property to choose how Amazon FSx keeps your file /// and directory listings up to date as you add or modify objects in your linked S3 bucket. /// <code>AutoImportPolicy</code> can have the following values: /// </para> /// <ul> <li> /// <para> /// <code>NONE</code> - (Default) AutoImport is off. Amazon FSx only updates file and /// directory listings from the linked S3 bucket when the file system is created. FSx /// does not update file and directory listings for any new or changed objects after choosing /// this option. /// </para> /// </li> <li> /// <para> /// <code>NEW</code> - AutoImport is on. Amazon FSx automatically imports directory listings /// of any new objects added to the linked S3 bucket that do not currently exist in the /// FSx file system. /// </para> /// </li> <li> /// <para> /// <code>NEW_CHANGED</code> - AutoImport is on. Amazon FSx automatically imports file /// and directory listings of any new objects added to the S3 bucket and any existing /// objects that are changed in the S3 bucket after you choose this option. /// </para> /// </li> </ul> /// <para> /// For more information, see <a href="https://docs.aws.amazon.com/fsx/latest/LustreGuide/autoimport-data-repo.html">Automatically /// import updates from your S3 bucket</a>. /// </para> /// </summary> public AutoImportPolicyType AutoImportPolicy { get { return this._autoImportPolicy; } set { this._autoImportPolicy = value; } } // Check to see if AutoImportPolicy property is set internal bool IsSetAutoImportPolicy() { return this._autoImportPolicy != null; } /// <summary> /// Gets and sets the property AutomaticBackupRetentionDays. /// </summary> [AWSProperty(Min=0, Max=90)] public int AutomaticBackupRetentionDays { get { return this._automaticBackupRetentionDays.GetValueOrDefault(); } set { this._automaticBackupRetentionDays = value; } } // Check to see if AutomaticBackupRetentionDays property is set internal bool IsSetAutomaticBackupRetentionDays() { return this._automaticBackupRetentionDays.HasValue; } /// <summary> /// Gets and sets the property CopyTagsToBackups. /// <para> /// (Optional) Not available to use with file systems that are linked to a data repository. /// A boolean flag indicating whether tags for the file system should be copied to backups. /// The default value is false. If it's set to true, all file system tags are copied to /// all automatic and user-initiated backups when the user doesn't specify any backup-specific /// tags. If this value is true, and you specify one or more backup tags, only the specified /// tags are copied to backups. If you specify one or more tags when creating a user-initiated /// backup, no tags are copied from the file system, regardless of this value. /// </para> /// /// <para> /// For more information, see <a href="https://docs.aws.amazon.com/fsx/latest/LustreGuide/using-backups-fsx.html">Working /// with backups</a>. /// </para> /// </summary> public bool CopyTagsToBackups { get { return this._copyTagsToBackups.GetValueOrDefault(); } set { this._copyTagsToBackups = value; } } // Check to see if CopyTagsToBackups property is set internal bool IsSetCopyTagsToBackups() { return this._copyTagsToBackups.HasValue; } /// <summary> /// Gets and sets the property DailyAutomaticBackupStartTime. /// </summary> [AWSProperty(Min=5, Max=5)] public string DailyAutomaticBackupStartTime { get { return this._dailyAutomaticBackupStartTime; } set { this._dailyAutomaticBackupStartTime = value; } } // Check to see if DailyAutomaticBackupStartTime property is set internal bool IsSetDailyAutomaticBackupStartTime() { return this._dailyAutomaticBackupStartTime != null; } /// <summary> /// Gets and sets the property DataCompressionType. /// <para> /// Sets the data compression configuration for the file system. <code>DataCompressionType</code> /// can have the following values: /// </para> /// <ul> <li> /// <para> /// <code>NONE</code> - (Default) Data compression is turned off when the file system /// is created. /// </para> /// </li> <li> /// <para> /// <code>LZ4</code> - Data compression is turned on with the LZ4 algorithm. /// </para> /// </li> </ul> /// <para> /// For more information, see <a href="https://docs.aws.amazon.com/fsx/latest/LustreGuide/data-compression.html">Lustre /// data compression</a>. /// </para> /// </summary> public DataCompressionType DataCompressionType { get { return this._dataCompressionType; } set { this._dataCompressionType = value; } } // Check to see if DataCompressionType property is set internal bool IsSetDataCompressionType() { return this._dataCompressionType != null; } /// <summary> /// Gets and sets the property DeploymentType. /// <para> /// Choose <code>SCRATCH_1</code> and <code>SCRATCH_2</code> deployment types when you /// need temporary storage and shorter-term processing of data. The <code>SCRATCH_2</code> /// deployment type provides in-transit encryption of data and higher burst throughput /// capacity than <code>SCRATCH_1</code>. /// </para> /// /// <para> /// Choose <code>PERSISTENT_1</code> deployment type for longer-term storage and workloads /// and encryption of data in transit. To learn more about deployment types, see <a href="https://docs.aws.amazon.com/fsx/latest/LustreGuide/lustre-deployment-types.html"> /// FSx for Lustre Deployment Options</a>. /// </para> /// /// <para> /// Encryption of data in-transit is automatically enabled when you access a <code>SCRATCH_2</code> /// or <code>PERSISTENT_1</code> file system from Amazon EC2 instances that <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/data- /// protection.html">support this feature</a>. (Default = <code>SCRATCH_1</code>) /// </para> /// /// <para> /// Encryption of data in-transit for <code>SCRATCH_2</code> and <code>PERSISTENT_1</code> /// deployment types is supported when accessed from supported instance types in supported /// Amazon Web Services Regions. To learn more, <a href="https://docs.aws.amazon.com/fsx/latest/LustreGuide/encryption-in-transit-fsxl.html">Encrypting /// Data in Transit</a>. /// </para> /// </summary> public LustreDeploymentType DeploymentType { get { return this._deploymentType; } set { this._deploymentType = value; } } // Check to see if DeploymentType property is set internal bool IsSetDeploymentType() { return this._deploymentType != null; } /// <summary> /// Gets and sets the property DriveCacheType. /// <para> /// The type of drive cache used by PERSISTENT_1 file systems that are provisioned with /// HDD storage devices. This parameter is required when storage type is HDD. Set to <code>READ</code>, /// improve the performance for frequently accessed files and allows 20% of the total /// storage capacity of the file system to be cached. /// </para> /// /// <para> /// This parameter is required when <code>StorageType</code> is set to HDD. /// </para> /// </summary> public DriveCacheType DriveCacheType { get { return this._driveCacheType; } set { this._driveCacheType = value; } } // Check to see if DriveCacheType property is set internal bool IsSetDriveCacheType() { return this._driveCacheType != null; } /// <summary> /// Gets and sets the property ExportPath. /// <para> /// (Optional) The path in Amazon S3 where the root of your Amazon FSx file system is /// exported. The path must use the same Amazon S3 bucket as specified in ImportPath. /// You can provide an optional prefix to which new and changed data is to be exported /// from your Amazon FSx for Lustre file system. If an <code>ExportPath</code> value is /// not provided, Amazon FSx sets a default export path, <code>s3://import-bucket/FSxLustre[creation-timestamp]</code>. /// The timestamp is in UTC format, for example <code>s3://import-bucket/FSxLustre20181105T222312Z</code>. /// </para> /// /// <para> /// The Amazon S3 export bucket must be the same as the import bucket specified by <code>ImportPath</code>. /// If you only specify a bucket name, such as <code>s3://import-bucket</code>, you get /// a 1:1 mapping of file system objects to S3 bucket objects. This mapping means that /// the input data in S3 is overwritten on export. If you provide a custom prefix in the /// export path, such as <code>s3://import-bucket/[custom-optional-prefix]</code>, Amazon /// FSx exports the contents of your file system to that export prefix in the Amazon S3 /// bucket. /// </para> /// </summary> [AWSProperty(Min=3, Max=4357)] public string ExportPath { get { return this._exportPath; } set { this._exportPath = value; } } // Check to see if ExportPath property is set internal bool IsSetExportPath() { return this._exportPath != null; } /// <summary> /// Gets and sets the property ImportedFileChunkSize. /// <para> /// (Optional) For files imported from a data repository, this value determines the stripe /// count and maximum amount of data per file (in MiB) stored on a single physical disk. /// The maximum number of disks that a single file can be striped across is limited by /// the total number of disks that make up the file system. /// </para> /// /// <para> /// The default chunk size is 1,024 MiB (1 GiB) and can go as high as 512,000 MiB (500 /// GiB). Amazon S3 objects have a maximum size of 5 TB. /// </para> /// </summary> [AWSProperty(Min=1, Max=512000)] public int ImportedFileChunkSize { get { return this._importedFileChunkSize.GetValueOrDefault(); } set { this._importedFileChunkSize = value; } } // Check to see if ImportedFileChunkSize property is set internal bool IsSetImportedFileChunkSize() { return this._importedFileChunkSize.HasValue; } /// <summary> /// Gets and sets the property ImportPath. /// <para> /// (Optional) The path to the Amazon S3 bucket (including the optional prefix) that you're /// using as the data repository for your Amazon FSx for Lustre file system. The root /// of your FSx for Lustre file system will be mapped to the root of the Amazon S3 bucket /// you select. An example is <code>s3://import-bucket/optional-prefix</code>. If you /// specify a prefix after the Amazon S3 bucket name, only object keys with that prefix /// are loaded into the file system. /// </para> /// </summary> [AWSProperty(Min=3, Max=4357)] public string ImportPath { get { return this._importPath; } set { this._importPath = value; } } // Check to see if ImportPath property is set internal bool IsSetImportPath() { return this._importPath != null; } /// <summary> /// Gets and sets the property PerUnitStorageThroughput. /// <para> /// Required for the <code>PERSISTENT_1</code> deployment type, describes the amount /// of read and write throughput for each 1 tebibyte of storage, in MB/s/TiB. File system /// throughput capacity is calculated by multiplying file system storage capacity (TiB) /// by the PerUnitStorageThroughput (MB/s/TiB). For a 2.4 TiB file system, provisioning /// 50 MB/s/TiB of PerUnitStorageThroughput yields 120 MB/s of file system throughput. /// You pay for the amount of throughput that you provision. /// </para> /// /// <para> /// Valid values for SSD storage: 50, 100, 200. Valid values for HDD storage: 12, 40. /// </para> /// </summary> [AWSProperty(Min=12, Max=200)] public int PerUnitStorageThroughput { get { return this._perUnitStorageThroughput.GetValueOrDefault(); } set { this._perUnitStorageThroughput = value; } } // Check to see if PerUnitStorageThroughput property is set internal bool IsSetPerUnitStorageThroughput() { return this._perUnitStorageThroughput.HasValue; } /// <summary> /// Gets and sets the property WeeklyMaintenanceStartTime. /// <para> /// (Optional) The preferred start time to perform weekly maintenance, formatted d:HH:MM /// in the UTC time zone, where d is the weekday number, from 1 through 7, beginning with /// Monday and ending with Sunday. /// </para> /// </summary> [AWSProperty(Min=7, Max=7)] public string WeeklyMaintenanceStartTime { get { return this._weeklyMaintenanceStartTime; } set { this._weeklyMaintenanceStartTime = value; } } // Check to see if WeeklyMaintenanceStartTime property is set internal bool IsSetWeeklyMaintenanceStartTime() { return this._weeklyMaintenanceStartTime != null; } } }
42.958763
179
0.613511
[ "Apache-2.0" ]
EbstaLimited/aws-sdk-net
sdk/src/Services/FSx/Generated/Model/CreateFileSystemLustreConfiguration.cs
16,674
C#
namespace PX.HMRC.Browser { /// <summary> /// Browser display mode /// </summary> public enum DisplayMode { /// <summary> /// visible /// </summary> Visible, /// <summary> /// hidden /// </summary> Hidden } }
17.470588
28
0.434343
[ "MIT" ]
mPisano/MTDCompliance
PX.HMRC/Browser/DisplayMode.cs
299
C#
using KLineEdCmdApp.Controller; using KLineEdCmdAppTest.TestSupport; using Xunit; namespace KLineEdCmdAppTest.ViewTests { public class PropsEditViewTest : IClassFixture<ModelPropsEditViewFixture> { private readonly ModelPropsEditViewFixture _fixture; public PropsEditViewTest(ModelPropsEditViewFixture fixture) { _fixture = fixture; } [Fact] public void SetupTest() { Assert.True(_fixture.View.Ready); Assert.Equal(27, _fixture.View.WindowHeight); // Assert.Equal(90, _fixture.View.WindowWidth); } [Fact] public void OnUpdateTest() { Assert.Equal(TestConst.UnitTestNone, _fixture.Error); Assert.True(_fixture.Model.Ready); Assert.True(_fixture.View.Ready); _fixture.Model.SetEditorHelpLine(PropsEditingController.EditorHelpText); Assert.False(_fixture.View.IsErrorState()); } } }
25.74359
84
0.63745
[ "MIT" ]
wpqs/GenDotNetCmdApps
KLineEd/KLineEdCmdAppTest/ViewTests/PropsEditViewTest.cs
1,006
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Watson { internal class PendingResponse { #region Public-Members /// <summary> /// The time at which the response expires. /// </summary> public DateTime Expiration; /// <summary> /// The response message. /// </summary> public Message ResponseMessage; #endregion #region Private-Members #endregion #region Constructors-and-Factories /// <summary> /// Initialize the object. /// </summary> /// <param name="expiration">The time at which the response expires.</param> /// <param name="msg">The response message.</param> public PendingResponse(DateTime expiration, Message msg) { Expiration = expiration; ResponseMessage = msg; } #endregion #region Public-Methods #endregion #region Private-Methods #endregion } }
20.301887
84
0.562268
[ "MIT" ]
euclid47/WatsonMesh
WatsonMesh/Helpers/PendingResponse.cs
1,078
C#
using Assets.StarSystem.Generation.Planet; using System.Collections.Generic; namespace Assets.Utils { public class RegionStack { private List<Region> regions; public RegionStack() { regions = new List<Region>(); } public void Add(Region region) { if (!region.processing) { RemoveChildrenAndParentsFromStack(region); regions.Add(region); } } private void RemoveChildrenAndParentsFromStack(Region region) { Region parent = region.parent; while (parent != null) { if (regions.Contains(parent)) regions.Remove(parent); parent = parent.parent; } RemoveChildren(region); } private void RemoveChildren(Region region) { if (regions.Contains(region)) { regions.Remove(region); } if (region.IsLeaf) return; for (int i = 0; i < region.children.Length; i++) { RemoveChildren(region.children[i]); } } public int Count { get { return regions.Count; } } public Region Remove() { if (regions.Count == 0) return null; Region last = null; lock (regions) { int index = regions.Count - 1; last = regions[index]; regions.RemoveAt(index); } return last; } } }
25.03125
69
0.480649
[ "MIT" ]
breinsp/unity-persistent-universe
Assets/Utils/RegionStack.cs
1,604
C#
namespace CarDealer.Services.Implementations { using System.Collections.Generic; using System.Linq; using Contracts; using Data; using Models; public class SaleService : ISaleService { private readonly CarDealerDbContext db; public SaleService(CarDealerDbContext db) { this.db = db; } public IEnumerable<SaleModel> Index() { var sales = this.db.Sales .Select(s => new SaleModel { Make = s.Car.Make, Model = s.Car.Model, TravelledDistance = s.Car.TravelledDistance, Customer = s.Customer.Name, Price = s.Car.Parts.Sum(p => p.Part.Price), Discount = s.Discount + (s.Customer.IsYoungDriver ? 5 : 0) }) .ToList(); return sales; } public IEnumerable<SaleModel> Index(int id) { var sale = this.db.Sales .Where(s => s.Id == id) .Select(s => new SaleModel { Make = s.Car.Make, Model = s.Car.Model, TravelledDistance = s.Car.TravelledDistance, Customer = s.Customer.Name, Price = s.Car.Parts.Sum(p => p.Part.Price), Discount = s.Discount + (s.Customer.IsYoungDriver ? 5 : 0) }) .ToList(); return sale; } public IEnumerable<SaleModel> Discounted() { var sales = this.db.Sales .Select(s => new SaleModel { Make = s.Car.Make, Model = s.Car.Model, TravelledDistance = s.Car.TravelledDistance, Customer = s.Customer.Name, Price = s.Car.Parts.Sum(p => p.Part.Price), Discount = s.Discount + (s.Customer.IsYoungDriver ? 5 : 0) }) .Where(s => s.Discount > 0) .ToList(); return sales; } public IEnumerable<SaleModel> Discounted(double percentage) { var sales = this.db.Sales .Select(s => new SaleModel { Make = s.Car.Make, Model = s.Car.Model, TravelledDistance = s.Car.TravelledDistance, Customer = s.Customer.Name, Price = s.Car.Parts.Sum(p => p.Part.Price), Discount = s.Discount + (s.Customer.IsYoungDriver ? 5 : 0) }) .Where(s => s.Discount == percentage) .ToList(); return sales; } } }
31.865169
78
0.449224
[ "MIT" ]
sevdalin/Software-University-SoftUni
C# MVC Frameworks - ASP.NET Core/02. ASP.NET Core - Essentials/CarDealer.Web/CarDealer.Services/Implementations/SaleService.cs
2,838
C#
using NUnit.Framework; namespace BooCompiler.Tests.TypeSystem.Reflection { [TestFixture] public class NullableImplicitConversionOperatorsTest : AbstractTypeSystemTest { [Test] public void ImplicitConversionFromNullableToValue() { RunInCompilerContextEnvironment(delegate { var nullableDouble = TypeSystemServices.Map(typeof(double?)); var doubleType = TypeSystemServices.Map(typeof(double)); var conversionOperator = TypeSystemServices.FindExplicitConversionOperator(nullableDouble, doubleType); Assert.IsNotNull(conversionOperator); }); } } }
30.095238
114
0.726266
[ "BSD-3-Clause" ]
Code-distancing/boo
tests/BooCompiler.Tests/TypeSystem/Reflection/NullableImplicitConversionOperatorsTest.cs
632
C#
using System; namespace CUSTIS.NetCore.Lightbox.Utils { /// <summary> Сериализация и десерилазиация объектов </summary> /// <remarks> Интерфейс понадобился, поскольку разные потребители сидят на разных версиях Newtonsoft.JSON </remarks> public interface ISerializer { /// <summary> Десериализовать </summary> object? Deserialize(string value, Type type); /// <summary> Сериализовать </summary> string Serialize(object? value); } }
32.266667
120
0.688017
[ "Apache-2.0" ]
CUSTIS-public/CUSTIS.NetCore.Lightbox
src/CUSTIS.NetCore.Lightbox/Utils/ISerializer.cs
613
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace System.Fabric.BackupRestore.Enums { /// <summary> /// List types of Backup Schedule Available /// </summary> public enum BackupScheduleType { /// <summary> /// Invalid value /// </summary> Invalid, /// <summary> /// Type to set a Scheduled backup happening at particular time /// </summary> TimeBased, /// <summary> /// Type to set a frequency based schedule happening at fixed regular interval /// </summary> FrequencyBased } /// <summary> /// List types of Retention Available /// </summary> public enum RetentionPolicyType { /// <summary> /// Describes the retention of backup where we can specify a duration of time to retain backups. /// </summary> Basic } /// <summary> /// Describes the schedule of running a Backup /// </summary> public enum BackupScheduleFrequency { /// <summary> /// Invalid value /// </summary> Invalid, /// <summary> /// Setting the frequency to Daily of running a scheduled type backup /// </summary> Daily, /// <summary> /// Setting the frequency to Weekly of running a scheduled type backup /// </summary> Weekly } /// <summary> /// Describes the frequency of running a frequency type Backup /// </summary> public enum BackupScheduleInterval { /// <summary> /// Invalid value /// </summary> Invalid, /// <summary> /// Setting the frequency to Hours interval of running a frequency type backup /// </summary> Hours, /// <summary> /// Setting the frequency to Minute interval of running a frequency type backup /// </summary> Minutes } /// <summary> /// Describes the frequency of Retaining a Backup /// </summary> public enum RetentionDurationType { /// <summary> /// Setting the frequency Retaining to Days /// </summary> Days, /// <summary> /// Setting the frequency Retaining to Weeks /// </summary> Weeks, /// <summary> /// Setting the frequency Retaining to Months /// </summary> Months } /// <summary> /// Describes the Storage type for saving the backups /// </summary> public enum BackupStorageType { /// <summary> /// Invalid value /// </summary> Invalid, /// <summary> /// Setting the storage type to file share type /// </summary> FileShare, /// <summary> /// Setting the storage type to azure blob storage type /// </summary> AzureBlobStore, /// <summary> /// Setting the storage type to dSMS manaed Azure storage type /// </summary> DsmsAzureBlobStore } /// <summary> /// Describes the Details of Backup Taken /// </summary> public enum BackupOptionType { /// <summary> /// Invalid value /// </summary> Invalid, /// <summary> /// Defines a full Backup /// </summary> Full, /// <summary> /// Defines a Incremental Backup /// </summary> Incremental, } /// <summary> /// Specifies the Backup Protection Level /// </summary> public enum BackupPolicyScopeType { /// <summary> /// Invalid value /// </summary> Invalid, /// <summary> /// Indicates that backup has been applied at current level /// </summary> Partition, /// <summary> /// Indicates the backup has been applied at Service Level /// </summary> Service, /// <summary> /// Indicates the backup has been applied at Application Level /// </summary> Application } /// <summary> /// Specifies the Backup Entity Kind /// </summary> public enum BackupEntityKind { /// <summary> /// Indicates that enitity is Invalid /// </summary> Invalid, /// <summary> /// Indicates that Entity is Partition /// </summary> Partition, /// <summary> /// Indicates that Entity is Service /// </summary> Service, /// <summary> /// Indicates that Entity is Application /// </summary> Application } /// <summary> /// Represents the current state of a Restore Request /// </summary> public enum RestoreState { /// <summary> /// Restore requested is Invalid /// </summary> Invalid, /// <summary> /// Request is Accepted /// </summary> Accepted, /// <summary> /// Restore is in Process /// </summary> RestoreInProgress, /// <summary> /// Restore Completed with Success /// </summary> Success, /// <summary> /// Restore Completed with Error /// </summary> Failure, /// <summary> /// Restore Requested has timeout /// </summary> Timeout, } /// <summary> /// Represents the current state of a Backup Request /// </summary> public enum BackupState { /// <summary> /// Backup requested is Invalid /// </summary> Invalid, /// <summary> /// Backup Request of Partition is Accepted /// </summary> Accepted, /// <summary> /// Backup Request of Partition is in Process /// </summary> BackupInProgress, /// <summary> /// Backup Request of Partition completed with Success /// </summary> Success, /// <summary> /// Backup Request of Partition completed with Error /// </summary> Failure, /// <summary> /// Backup Request of Partition has timeout /// </summary> Timeout } }
26.185484
104
0.509085
[ "MIT" ]
AndreyTretyak/service-fabric
src/prod/src/managed/FabricBRS/src/System/Fabric/BackupRestore/BackupRestoreTypes/EnumTypes.cs
6,494
C#
// Enables the following conditional switch here // to prevent test cases from making any edits. //#define DRY_RUN using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using WikiClientLibrary.Client; using WikiClientLibrary.Pages; using WikiClientLibrary.Pages.Queries.Properties; using WikiClientLibrary.Sites; using WikiClientLibrary.Tests.UnitTestProject1.Fixtures; using WikiClientLibrary.Wikia; using WikiClientLibrary.Wikia.Sites; using Xunit; using Xunit.Abstractions; namespace WikiClientLibrary.Tests.UnitTestProject1 { public class UnitTestsBase : IAsyncDisposable { public UnitTestsBase(ITestOutputHelper output) { if (output == null) throw new ArgumentNullException(nameof(output)); Output = output; OutputLoggerFactory = new LoggerFactory(); OutputLoggerFactory.AddProvider(new TestOutputLoggerProvider(Output)); } public LoggerFactory OutputLoggerFactory { get; } public ITestOutputHelper Output { get; } protected void WriteOutput(object? value) { WriteOutput(value == null ? "<null>" : value.ToString()); } protected void WriteOutput(string? message) { Output.WriteLine(message); } protected void WriteOutput(string format, params object?[] args) { WriteOutput(string.Format(format, args)); } protected void ShallowTrace(object? obj, int depth = 2) { var rawTrace = Utility.DumpObject(obj, depth); #if ENV_CI_BUILD // We don't want to abuse CI logs. const int MAX_TRACE_LENGTH = 5000; if (rawTrace.Length > MAX_TRACE_LENGTH) { rawTrace = rawTrace.Substring(0, MAX_TRACE_LENGTH) + "… [+" + (rawTrace.Length - MAX_TRACE_LENGTH) + " chars]"; } #endif Output.WriteLine(rawTrace); } protected virtual ValueTask DisposeAsync(bool disposing) => default; /// <inheritdoc /> public async ValueTask DisposeAsync() { await DisposeAsync(true); GC.SuppressFinalize(this); } } public class WikiSiteTestsBase : UnitTestsBase { public WikiSiteTestsBase(ITestOutputHelper output, WikiSiteProvider wikiSiteProvider) : base(output) { WikiSiteProvider = wikiSiteProvider; } protected WikiSiteProvider WikiSiteProvider { get; } protected void SiteNeedsLogin(string endpointUrl) => WikiSiteProvider.SiteNeedsLogin(endpointUrl); /// <summary> /// Creates a <see cref="WikiSite"/> instance with a dedicated <see cref="WikiClient"/> instance. /// </summary> /// <remarks>This method can be handy for you to maul a certain WikiClient without affecting other WikiSite instances.</remarks> protected Task<WikiSite> CreateIsolatedWikiSiteAsync(string apiEndpoint, bool noLogin = false) { var isolatedClient = WikiSiteProvider.CreateWikiClient(); isolatedClient.Logger = OutputLoggerFactory.CreateLogger<WikiClient>(); return WikiSiteProvider.CreateWikiSiteAsync(isolatedClient, apiEndpoint, OutputLoggerFactory, noLogin); } /// <summary> /// Create or get a wiki site from local cache. /// </summary> public Task<WikiSite> GetWikiSiteAsync(string endpointUrl) => WikiSiteProvider.GetWikiSiteAsync(endpointUrl, OutputLoggerFactory); protected void TracePages(IReadOnlyCollection<WikiPage> pages) { const string lineFormat = "{0,-20} {1,10} {2,10} {3,10} {4,10}"; #if ENV_CI_BUILD const int ITEMS_LIMIT = 10; #else const int ITEMS_LIMIT = int.MaxValue; #endif WriteOutput("{0} pages.", pages.Count); WriteOutput(lineFormat, "Title", "Length", "Last Revision", "Last Touched", "Children"); foreach (var page in pages.Take(ITEMS_LIMIT)) { var childrenField = ""; var cat = page.GetPropertyGroup<CategoryInfoPropertyGroup>(); if (cat != null) childrenField = $"{cat.MembersCount}(sub:{cat.SubcategoriesCount})"; WriteOutput(lineFormat, page.Title, page.ContentLength, page.LastRevisionId, page.LastTouched, childrenField); if (page.Content != null) WriteOutput(page.Content.Length > 100 ? page.Content.Substring(0, 100) + "..." : page.Content); } if (pages.Count > ITEMS_LIMIT) { WriteOutput("[+{0} pages]", pages.Count - ITEMS_LIMIT); } } /// <summary> /// Asserts that modifications to wiki site can be done in unit tests. /// </summary> protected static void AssertModify() { #if DRY_RUN throw new SkipException("Remove #define DRY_RUN to perform edit tests."); #endif } protected Task<WikiSite> WpEnSiteAsync => GetWikiSiteAsync(Endpoints.WikipediaEn); protected Task<WikiSite> WpTest2SiteAsync => GetWikiSiteAsync(Endpoints.WikipediaTest2); protected Task<WikiaSite> WikiaTestSiteAsync { get { async Task<WikiaSite> Cast() { return (WikiaSite)await GetWikiSiteAsync(Endpoints.WikiaTest); } return Cast(); } } protected Task<WikiSite> TFWikiSiteAsync => GetWikiSiteAsync(Endpoints.TFWiki); protected Task<WikiSite> WpLzhSiteAsync => GetWikiSiteAsync(Endpoints.WikipediaLzh); protected Task<WikiSite> WpBetaSiteAsync => GetWikiSiteAsync(Endpoints.WikipediaBetaEn); protected Task<WikiSite> WikimediaCommonsBetaSiteAsync => GetWikiSiteAsync(Endpoints.WikimediaCommonsBeta); protected Task<WikiSite> WikidataSiteAsync => GetWikiSiteAsync(Endpoints.Wikidata); protected Task<WikiSite> WikidataTestSiteAsync => GetWikiSiteAsync(Endpoints.WikidataTest); protected Task<WikiSite> WikiSiteFromNameAsync(string sitePropertyName) { static async Task<TDest> CastAsync<TSource, TDest>(Task<TSource> sourceTask) where TSource : class where TDest : class { return (TDest)(object)await sourceTask; } var task = GetType() .GetProperty(sitePropertyName, BindingFlags.NonPublic | BindingFlags.Instance) !.GetValue(this); if (task is Task<WikiSite> ws) return ws; if (task is Task<WikiaSite> was) return CastAsync<WikiaSite, WikiSite>(was); throw new NotSupportedException(); } protected WikiClient CreateWikiClient() { var client = WikiSiteProvider.CreateWikiClient(); client.Logger = OutputLoggerFactory.CreateLogger<WikiClient>(); return client; } } }
35.990099
138
0.633838
[ "Apache-2.0" ]
CXuesong/WikiClientLibrary
UnitTestProject1/WikiSiteTestsBase.cs
7,274
C#
using System; using Xunit; using SpatialLite.Gps.Geometries; using SpatialLite.Core.API; namespace Tests.SpatialLite.Gps.Geometries { public class GpsPointTests { #region Test data double _xOrdinate = 3.5; double _yOrdinate = 4.2; double _zOrdinate = 10.5; Coordinate _coordinate; #endregion public GpsPointTests() { _coordinate = new Coordinate(_xOrdinate, _yOrdinate, _zOrdinate); } #region Constructor tests #region Constructor() tests [Fact] public void Constructor__CreatesPointWithEmptyPositionAndNullTimestamp() { var target = new GpsPoint(); Assert.Equal(Coordinate.Empty, target.Position); Assert.Null(target.Timestamp); } #endregion #region Constructor(Coordinate) tests [Fact] public void Constructor_Coordinate_CreatesPointWithPositionAndNullTimestamp() { var target = new GpsPoint(_coordinate); Assert.Equal(_coordinate, target.Position); Assert.Null(target.Timestamp); } #endregion #region Constructor(Coordinate, Timestamp) tests [Fact] public void Constructor_Coordinate_CreatesPointWithPositionAndTimestamp() { var timestamp = DateTime.Now; var target = new GpsPoint(_coordinate, timestamp); Assert.Equal(_coordinate, target.Position); Assert.Equal(timestamp, target.Timestamp); } #endregion #region Constructor(Lon, Lat, Elevation, Timestamp) tests [Fact] public void Constructor_LonLatElevationTimestamp_CreatesPointWithPositionAndTimestamp() { var timestamp = DateTime.Now; var target = new GpsPoint(_xOrdinate, _yOrdinate, _zOrdinate, timestamp); Assert.Equal(_coordinate, target.Position); Assert.Equal(timestamp, target.Timestamp); } #endregion #endregion } }
25.2
97
0.638889
[ "MIT" ]
CptGasse/SpatialLITE
src/Tests.SpatialLite.Gps/Geometries/GpsPointTests.cs
2,018
C#
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Udd.Api.Models; namespace Udd.Api.Infrastructure { public class UddDbContext : DbContext { public DbSet<City> Cities { get; set; } public UddDbContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfigurationsFromAssembly(typeof(UddDbContext).Assembly); } } }
23.875
88
0.696335
[ "MIT" ]
AnLong98/UDD
Udd.Api/Infrastructure/UddDbContext.cs
575
C#
using System; using System.Linq.Expressions; namespace Magento.RestApi.Core { /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> public interface IChangeTracking<T> : IChangeTracking { /// <summary> /// /// </summary> /// <param name="expression"></param> /// <typeparam name="P"></typeparam> /// <returns></returns> bool HasChanged<P>(Expression<Func<T, P>> expression); /// <summary> /// /// </summary> /// <param name="expression"></param> /// <typeparam name="P"></typeparam> /// <returns></returns> P GetValue<P>(Expression<Func<T, P>> expression); /// <summary> /// /// </summary> /// <param name="expression"></param> /// <param name="value"></param> /// <typeparam name="P"></typeparam> void SetValue<P>(Expression<Func<T, P>> expression, P value); /// <summary> /// /// </summary> /// <param name="expression"></param> /// <typeparam name="P"></typeparam> /// <returns></returns> Property<P> GetProperty<P>(Expression<Func<T, P>> expression); } /// <summary> /// /// </summary> public interface IChangeTracking { /// <summary> /// /// </summary> /// <returns></returns> bool HasChanged(); /// <summary> /// /// </summary> void StartTracking(); } }
26.465517
70
0.480782
[ "MIT" ]
Trendays/Magento-RestApi
Magento.RestApi/Core/IChangeTracking.cs
1,537
C#
using System; using System.Data; namespace DbUp.SQLite.Helpers { /// <summary> /// A database connection wrapper to manage underlying connection as a shared connection /// during database upgrade. /// <remarks> /// if underlying connection is already opened then it will be kept as opened and will not be closed /// otherwise it will be opened when object is created and closed when object is disposed /// however it will not be disposed /// </remarks> /// </summary> public class SharedConnection : IDbConnection { readonly bool connectionAlreadyOpenned; readonly IDbConnection connection; /// <summary> /// Constructs a new instance /// </summary> public SharedConnection(IDbConnection dbConnection) { if (dbConnection == null) throw new NullReferenceException("database connection is null"); connection = dbConnection; if (connection.State == ConnectionState.Open) connectionAlreadyOpenned = true; else connection.Open(); } public IDbTransaction BeginTransaction(IsolationLevel il) { return connection.BeginTransaction(il); } public IDbTransaction BeginTransaction() { return connection.BeginTransaction(); } public void ChangeDatabase(string databaseName) { connection.ChangeDatabase(databaseName); } public void Close() { // shared underlying connection is not closed } public string ConnectionString { get => connection.ConnectionString; set => connection.ConnectionString = value; } public int ConnectionTimeout => connection.ConnectionTimeout; public IDbCommand CreateCommand() { return connection.CreateCommand(); } public string Database => connection.Database; public void Open() { if (connection.State == ConnectionState.Closed) connection.Open(); } public ConnectionState State => connection.State; public void Dispose() { // shared underlying connection is not disposed } public void DoClose() { // if shared underlying connection is opened by this object // it will be closed here, otherwise the connection is not closed if (!connectionAlreadyOpenned && connection.State == ConnectionState.Open) { connection.Close(); } } } }
28.978723
105
0.585169
[ "MIT" ]
slamballx/DbUp
src/dbup-sqlite/Helpers/SharedConnection.cs
2,726
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.IO.Packaging; using System.Xml.Linq; namespace DocumentFormat.OpenXml.Packaging { /// <summary> /// A class that holds information about invalid relationships in <see cref="PackagePart"/> instances. /// </summary> public abstract class RelationshipErrorHandler { private const string RelationshipsTagName = "Relationships"; private const string RelationshipTagName = "Relationship"; private const string RelationshipNamespaceUri = "http://schemas.openxmlformats.org/package/2006/relationships"; private const string TargetAttributeName = "Target"; private const string TargetModeAttributeName = "TargetMode"; private const string IdAttributeName = "Id"; /// <summary> /// Create a <see cref="RelationshipErrorHandler"/> that simply rewrites the invalid target Uri. /// </summary> /// <param name="rewriter">The delegate used to rewrite the Uri.</param> /// <returns>A factory function for use in <see cref="OpenSettings.RelationshipErrorHandlerFactory"/>.</returns> public static Func<OpenXmlPackage, RelationshipErrorHandler> CreateRewriterFactory(Rewriter rewriter) { var handler = new DelegateRelationshipErrorHandler(rewriter); return _ => handler; } /// <summary> /// Delegate to be used for simple rewriting of malformed Uris. /// </summary> /// <param name="partUri">Uri of the part with the invalid relationship.</param> /// <param name="id">Id of relationship</param> /// <param name="uri">Invalid <see cref="Uri"/></param> /// <returns>Rewritten string if available, otherwise <c>null</c>.</returns> public delegate string Rewriter(Uri partUri, string? id, string? uri); /// <summary> /// Rewrites an invalid URI with a valid one in order to correctly open a package. /// </summary> /// <param name="partUri">Uri of the part with the invalid relationship.</param> /// <param name="id">Id of relationship</param> /// <param name="uri">Invalid <see cref="Uri"/></param> /// <returns>Rewritten string if available, otherwise <c>null</c>.</returns> public abstract string Rewrite(Uri partUri, string? id, string? uri); /// <summary> /// Callback for after a package has been completely loaded and all rewritting has occurred. /// </summary> public virtual void OnPackageLoaded() { } internal void Handle(Package package) { if (package is null) { throw new ArgumentNullException(nameof(package)); } if ((package.FileOpenAccess & FileAccess.ReadWrite) != FileAccess.ReadWrite) { throw new OpenXmlPackageException(ExceptionMessages.PackageAccessModeIsReadonly); } foreach (var part in package.GetParts()) { if (part.Uri.OriginalString.EndsWith(".rels", StringComparison.OrdinalIgnoreCase)) { var doc = WalkRelationships(part); if (doc is not null) { using var stream = part.GetStream(FileMode.Open, FileAccess.Write); doc.Save(stream); } } } } private XDocument? WalkRelationships(PackagePart part) { using var stream = part.GetStream(FileMode.Open, FileAccess.Read); using var reader = new StreamReader(stream); var doc = XDocument.Load(reader); var changed = false; if (doc.Root is null) { return null; } if (string.Equals(RelationshipsTagName, doc.Root.Name.LocalName, StringComparison.Ordinal) && string.Equals(RelationshipNamespaceUri, doc.Root.Name.Namespace.NamespaceName, StringComparison.Ordinal)) { foreach (var child in doc.Root.Descendants(XName.Get(RelationshipTagName, RelationshipNamespaceUri))) { if (ValidateLink(part, child)) { changed = true; } } } return changed ? doc : null; } private bool ValidateLink(PackagePart part, XElement child) { if (!EnumHelper.TryParse<TargetMode>(child.Attribute(TargetModeAttributeName)?.Value, out var targetMode)) { return false; } if (targetMode != TargetMode.External) { return false; } var target = child.Attribute(TargetAttributeName)?.Value; if (!string.IsNullOrEmpty(target) && Uri.TryCreate(target, UriHelper.RelativeOrAbsolute, out _)) { return false; } var id = child.Attribute(IdAttributeName)?.Value; var updated = Rewrite(part.Uri, id, target); if (updated is null) { return false; } if (!Uri.TryCreate(updated, UriHelper.RelativeOrAbsolute, out _)) { throw new InvalidOperationException(ExceptionMessages.InvalidUriProvided); } child.SetAttributeValue(TargetAttributeName, updated); return true; } private class DelegateRelationshipErrorHandler : RelationshipErrorHandler { private readonly Rewriter _rewriter; public DelegateRelationshipErrorHandler(Rewriter rewriter) { _rewriter = rewriter; } public override string Rewrite(Uri partUri, string? id, string? uri) => _rewriter(partUri, id, uri); } } }
36.975904
124
0.583904
[ "MIT" ]
Muppets/Open-XML-SDK
src/DocumentFormat.OpenXml/Packaging/RelationshipErrorHandler.cs
6,140
C#
using Autofac; using EmailSender.EmailServices; using FakeItEasy; using Xunit; namespace EmailSender.Tests { public class When_an_email_is_sent { public When_an_email_is_sent() { TestHelper = new TestHelper(); FakeEmailSender = A.Fake<IEmailSender>(); Container = TestHelper.Register((c) => FakeEmailSender); } public IContainer Container { get; set; } public TestHelper TestHelper { set; get; } public IEmailSender FakeEmailSender { set; get; } [Fact] public void It_should_be_delivered() { //Arrange var fromEmailAddress = "from@email.com"; var toEmailAddress = "to@email.com"; var emailSender = Container.Resolve<IEmailSender>(); //Act emailSender.SendEmail(fromEmailAddress); //Assert A.CallTo(() => FakeEmailSender.SendEmail(null)).WithAnyArguments().MustHaveHappened(); } } }
28.083333
98
0.598417
[ "MIT" ]
TorontoTestDrivenDevelopment/MockBootCamp-IntroductoryTDDWithActorSystem
13/EmailSender/EmailSender.Tests/When_an_email_is_sent.cs
1,013
C#
using System; using System.Collections.Generic; using System.Text; namespace SaTeatar.Model.Models { public class mPoslaneObavijesti { public int PoslanaObavijestId { get; set; } public int KupacId { get; set; } public int PrestavaId { get; set; } public DateTime VrijemeSlanja { get; set; } public string Poruka { get; set; } public bool Procitano { get; set; } public DateTime DatumVazenja { get; set; } } }
27.611111
52
0.615694
[ "MIT" ]
eminafit/SaTeatar
SaTeatar/SaTeatar.Model/Models/mPoslaneObavijesti.cs
499
C#
using System; namespace Hookr.Web.Backend.Operations.Queries.Auth { public class RefreshSessionQuery { public Guid RefreshToken { get; set; } } }
18.555556
51
0.682635
[ "Apache-2.0" ]
mrlldd/hookr-rent-service
Hookr/Web/Hookr.Web.Backend/Operations/Queries/Auth/RefreshSessionQuery.cs
167
C#
/* Sniperkit-Bot - Status: analyzed */ using GVFS.Common.FileSystem; using GVFS.Common.Tracing; using Microsoft.Win32; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; namespace GVFS.Common.Git { public class GitProcess { private const int HResultEHANDLE = -2147024890; // 0x80070006 E_HANDLE private static readonly Encoding UTF8NoBOM = new UTF8Encoding(false); private static bool failedToSetEncoding = false; private object executionLock = new object(); private string gitBinPath; private string workingDirectoryRoot; private string dotGitRoot; private string gvfsHooksRoot; static GitProcess() { // If the encoding is UTF8, .Net's default behavior will include a BOM // We need to use the BOM-less encoding because Git doesn't understand it if (Console.InputEncoding.CodePage == UTF8NoBOM.CodePage) { try { Console.InputEncoding = UTF8NoBOM; } catch (IOException ex) when (ex.HResult == HResultEHANDLE) { // If the standard input for a console is redirected / not available, // then we might not be able to set the InputEncoding here. // In practice, this can happen if we attempt to run a GitProcess from within a Service, // such as GVFS.Service. // Record that we failed to set the encoding, but do not quite the process. // This means that git commands that use stdin will not work, but // for our scenarios, we do not expect these calls at this this time. // We will check and fail if we attempt to write to stdin in in a git call below. GitProcess.failedToSetEncoding = true; } } } public GitProcess(Enlistment enlistment) : this(enlistment.GitBinPath, enlistment.WorkingDirectoryRoot, enlistment.GVFSHooksRoot) { } public GitProcess(string gitBinPath, string workingDirectoryRoot, string gvfsHooksRoot) { if (string.IsNullOrWhiteSpace(gitBinPath)) { throw new ArgumentException(nameof(gitBinPath)); } this.gitBinPath = gitBinPath; this.workingDirectoryRoot = workingDirectoryRoot; this.gvfsHooksRoot = gvfsHooksRoot; if (this.workingDirectoryRoot != null) { this.dotGitRoot = Path.Combine(this.workingDirectoryRoot, GVFSConstants.DotGit.Root); } } public static Result Init(Enlistment enlistment) { return new GitProcess(enlistment).InvokeGitOutsideEnlistment("init \"" + enlistment.WorkingDirectoryRoot + "\""); } public static Result Version(Enlistment enlistment) { return new GitProcess(enlistment).InvokeGitOutsideEnlistment("--version"); } public static Result GetFromGlobalConfig(string gitBinPath, string settingName) { return new GitProcess(gitBinPath, workingDirectoryRoot: null, gvfsHooksRoot: null).InvokeGitOutsideEnlistment("config --global " + settingName); } public static Result GetFromSystemConfig(string gitBinPath, string settingName) { return new GitProcess(gitBinPath, workingDirectoryRoot: null, gvfsHooksRoot: null).InvokeGitOutsideEnlistment("config --system " + settingName); } public virtual void RevokeCredential(string repoUrl) { this.InvokeGitOutsideEnlistment( "credential reject", stdin => stdin.Write("url=" + repoUrl + "\n\n"), null); } public virtual bool TryGetCredentials( ITracer tracer, string repoUrl, out string username, out string password) { username = null; password = null; using (ITracer activity = tracer.StartActivity("TryGetCredentials", EventLevel.Informational)) { Result gitCredentialOutput = this.InvokeGitAgainstDotGitFolder( "credential fill", stdin => stdin.Write("url=" + repoUrl + "\n\n"), parseStdOutLine: null); if (gitCredentialOutput.HasErrors) { EventMetadata errorData = new EventMetadata(); tracer.RelatedWarning( errorData, "Git could not get credentials: " + gitCredentialOutput.Errors, Keywords.Network | Keywords.Telemetry); return false; } username = ParseValue(gitCredentialOutput.Output, "username="); password = ParseValue(gitCredentialOutput.Output, "password="); bool success = username != null && password != null; EventMetadata metadata = new EventMetadata(); metadata.Add("Success", success); if (!success) { metadata.Add("Output", gitCredentialOutput.Output); } activity.Stop(metadata); return success; } } public bool IsValidRepo() { Result result = this.InvokeGitAgainstDotGitFolder("rev-parse --show-toplevel"); return !result.HasErrors; } public Result RevParse(string gitRef) { return this.InvokeGitAgainstDotGitFolder("rev-parse " + gitRef); } public Result GetCurrentBranchName() { return this.InvokeGitAgainstDotGitFolder("name-rev --name-only HEAD"); } public void DeleteFromLocalConfig(string settingName) { this.InvokeGitAgainstDotGitFolder("config --local --unset-all " + settingName); } public Result SetInLocalConfig(string settingName, string value, bool replaceAll = false) { return this.InvokeGitAgainstDotGitFolder(string.Format( "config --local {0} \"{1}\" \"{2}\"", replaceAll ? "--replace-all " : string.Empty, settingName, value)); } public Result AddInLocalConfig(string settingName, string value) { return this.InvokeGitAgainstDotGitFolder(string.Format( "config --local --add {0} {1}", settingName, value)); } public bool TryGetAllConfig(bool localOnly, out Dictionary<string, GitConfigSetting> configSettings) { string localParameter = localOnly ? "--local" : string.Empty; Result result = this.InvokeGitAgainstDotGitFolder("config --list " + localParameter); if (result.HasErrors) { configSettings = null; return false; } configSettings = GitConfigHelper.ParseKeyValues(result.Output); return true; } /// <summary> /// Get the config value give a setting name /// </summary> /// <param name="settingName">The name of the config setting</param> /// <param name="forceOutsideEnlistment"> /// If false, will run the call from inside the enlistment if the working dir found, /// otherwise it will run it from outside the enlistment. /// </param> /// <returns>The value found for the setting.</returns> public virtual Result GetFromConfig(string settingName, bool forceOutsideEnlistment = false, PhysicalFileSystem fileSystem = null) { string command = string.Format("config {0}", settingName); fileSystem = fileSystem ?? new PhysicalFileSystem(); // This method is called at clone time, so the physical repo may not exist yet. return fileSystem.DirectoryExists(this.workingDirectoryRoot) && !forceOutsideEnlistment ? this.InvokeGitAgainstDotGitFolder(command) : this.InvokeGitOutsideEnlistment(command); } public Result GetFromLocalConfig(string settingName) { return this.InvokeGitAgainstDotGitFolder("config --local " + settingName); } /// <summary> /// Safely gets the config value give a setting name /// </summary> /// <param name="settingName">The name of the config setting</param> /// <param name="forceOutsideEnlistment"> /// If false, will run the call from inside the enlistment if the working dir found, /// otherwise it will run it from outside the enlistment. /// </param> /// <param value>The value found for the config setting.</param> /// <returns>True if the config call was successful, false otherwise.</returns> public bool TryGetFromConfig(string settingName, bool forceOutsideEnlistment, out string value, PhysicalFileSystem fileSystem = null) { value = null; try { Result result = this.GetFromConfig(settingName, forceOutsideEnlistment, fileSystem); if (!result.HasErrors) { value = result.Output; return true; } } catch { } return false; } public Result GetOriginUrl() { return this.InvokeGitAgainstDotGitFolder("config --local remote.origin.url"); } public Result DiffTree(string sourceTreeish, string targetTreeish, Action<string> onResult) { return this.InvokeGitAgainstDotGitFolder("diff-tree -r -t " + sourceTreeish + " " + targetTreeish, null, onResult); } public Result CreateBranchWithUpstream(string branchToCreate, string upstreamBranch) { return this.InvokeGitAgainstDotGitFolder("branch " + branchToCreate + " --track " + upstreamBranch); } public Result ForceCheckout(string target) { return this.InvokeGitInWorkingDirectoryRoot("checkout -f " + target, useReadObjectHook: false); } public Result Status(bool allowObjectDownloads) { return this.InvokeGitInWorkingDirectoryRoot("status", useReadObjectHook: allowObjectDownloads); } public Result UnpackObjects(Stream packFileStream) { return this.InvokeGitAgainstDotGitFolder( "unpack-objects", stdin => { packFileStream.CopyTo(stdin.BaseStream); stdin.Write('\n'); }, null); } /// <summary> /// Write a new commit graph in the specified pack directory. Crawl the given pack- /// indexes for commits and then close under everything reachable or exists in the /// previous graph file. /// /// This will update the graph-head file to point to the new commit graph and delete /// any expired graph files that previously existed. /// </summary> public Result WriteCommitGraph(string objectDir, List<string> packs) { string command = "commit-graph write --stdin-packs --append --object-dir \"" + objectDir + "\""; return this.InvokeGitInWorkingDirectoryRoot( command, useReadObjectHook: true, writeStdIn: writer => { foreach (string packIndex in packs) { writer.WriteLine(packIndex); } // We need to close stdin or else the process will not terminate. writer.Close(); }); } public Result IndexPack(string packfilePath, string idxOutputPath) { return this.InvokeGitAgainstDotGitFolder($"index-pack -o \"{idxOutputPath}\" \"{packfilePath}\""); } /// <summary> /// Write a new multi-pack-index (MIDX) in the specified pack directory. /// /// This will update the midx-head file to point to the new MIDX file. /// /// If no new packfiles are found, then this is a no-op. /// </summary> public Result WriteMultiPackIndex(string packDir) { // We override the config settings so we keep writing the MIDX file even if it is disabled for reads. return this.InvokeGitAgainstDotGitFolder("-c core.midx=true midx --write --update-head --pack-dir \"" + packDir + "\""); } public Result RemoteAdd(string remoteName, string url) { return this.InvokeGitAgainstDotGitFolder("remote add " + remoteName + " " + url); } public Result CatFileGetType(string objectId) { return this.InvokeGitAgainstDotGitFolder("cat-file -t " + objectId); } public Result LsTree(string treeish, Action<string> parseStdOutLine, bool recursive, bool showAllTrees = false) { return this.InvokeGitAgainstDotGitFolder( "ls-tree " + (recursive ? "-r " : string.Empty) + (showAllTrees ? "-t " : string.Empty) + treeish, null, parseStdOutLine); } public Result SetUpstream(string branchName, string upstream) { return this.InvokeGitAgainstDotGitFolder("branch --set-upstream-to=" + upstream + " " + branchName); } public Result UpdateBranchSymbolicRef(string refToUpdate, string targetRef) { return this.InvokeGitAgainstDotGitFolder("symbolic-ref " + refToUpdate + " " + targetRef); } public Result UpdateBranchSha(string refToUpdate, string targetSha) { // If oldCommitResult doesn't fail, then the branch exists and update-ref will want the old sha Result oldCommitResult = this.RevParse(refToUpdate); string oldSha = string.Empty; if (!oldCommitResult.HasErrors) { oldSha = oldCommitResult.Output.TrimEnd('\n'); } return this.InvokeGitAgainstDotGitFolder("update-ref --no-deref " + refToUpdate + " " + targetSha + " " + oldSha); } public Result ReadTree(string treeIsh) { return this.InvokeGitAgainstDotGitFolder("read-tree " + treeIsh); } public Process GetGitProcess(string command, string workingDirectory, string dotGitDirectory, bool useReadObjectHook, bool redirectStandardError) { ProcessStartInfo processInfo = new ProcessStartInfo(this.gitBinPath); processInfo.WorkingDirectory = workingDirectory; processInfo.UseShellExecute = false; processInfo.RedirectStandardInput = true; processInfo.RedirectStandardOutput = true; processInfo.RedirectStandardError = redirectStandardError; processInfo.WindowStyle = ProcessWindowStyle.Hidden; processInfo.CreateNoWindow = true; processInfo.StandardOutputEncoding = UTF8NoBOM; processInfo.StandardErrorEncoding = UTF8NoBOM; // Removing trace variables that might change git output and break parsing // List of environment variables: https://git-scm.com/book/gr/v2/Git-Internals-Environment-Variables foreach (string key in processInfo.EnvironmentVariables.Keys.Cast<string>() .Where(x => x.StartsWith("GIT_TRACE", StringComparison.OrdinalIgnoreCase)) .ToList()) { processInfo.EnvironmentVariables.Remove(key); } processInfo.EnvironmentVariables["GIT_TERMINAL_PROMPT"] = "0"; processInfo.EnvironmentVariables["GCM_VALIDATE"] = "0"; processInfo.EnvironmentVariables["PATH"] = string.Join( ";", this.gitBinPath, this.gvfsHooksRoot ?? string.Empty); if (!useReadObjectHook) { command = "-c " + GitConfigSetting.CoreVirtualizeObjectsName + "=false " + command; } if (!string.IsNullOrEmpty(dotGitDirectory)) { command = "--git-dir=\"" + dotGitDirectory + "\" " + command; } processInfo.Arguments = command; Process executingProcess = new Process(); executingProcess.StartInfo = processInfo; return executingProcess; } protected virtual Result InvokeGitImpl( string command, string workingDirectory, string dotGitDirectory, bool useReadObjectHook, Action<StreamWriter> writeStdIn, Action<string> parseStdOutLine, int timeoutMs) { if (failedToSetEncoding && writeStdIn != null) { return new Result(string.Empty, "Attempting to use to stdin, but the process does not have the right input encodings set.", Result.GenericFailureCode); } try { // From https://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx // To avoid deadlocks, use asynchronous read operations on at least one of the streams. // Do not perform a synchronous read to the end of both redirected streams. using (Process executingProcess = this.GetGitProcess(command, workingDirectory, dotGitDirectory, useReadObjectHook, redirectStandardError: true)) { StringBuilder output = new StringBuilder(); StringBuilder errors = new StringBuilder(); executingProcess.ErrorDataReceived += (sender, args) => { if (args.Data != null) { errors.Append(args.Data + "\n"); } }; executingProcess.OutputDataReceived += (sender, args) => { if (args.Data != null) { if (parseStdOutLine != null) { parseStdOutLine(args.Data); } else { output.Append(args.Data + "\n"); } } }; lock (this.executionLock) { executingProcess.Start(); if (writeStdIn != null) { writeStdIn(executingProcess.StandardInput); } executingProcess.BeginOutputReadLine(); executingProcess.BeginErrorReadLine(); if (!executingProcess.WaitForExit(timeoutMs)) { executingProcess.Kill(); return new Result(output.ToString(), "Operation timed out: " + errors.ToString(), Result.GenericFailureCode); } } return new Result(output.ToString(), errors.ToString(), executingProcess.ExitCode); } } catch (Win32Exception e) { return new Result(string.Empty, e.Message, Result.GenericFailureCode); } } private static string ParseValue(string contents, string prefix) { int startIndex = contents.IndexOf(prefix) + prefix.Length; if (startIndex >= 0 && startIndex < contents.Length) { int endIndex = contents.IndexOf('\n', startIndex); if (endIndex >= 0 && endIndex < contents.Length) { return contents .Substring(startIndex, endIndex - startIndex) .Trim('\r'); } } return null; } /// <summary> /// Invokes git.exe without a working directory set. /// </summary> /// <remarks> /// For commands where git doesn't need to be (or can't be) run from inside an enlistment. /// eg. 'git init' or 'git version' /// </remarks> private Result InvokeGitOutsideEnlistment(string command) { return this.InvokeGitOutsideEnlistment(command, null, null); } private Result InvokeGitOutsideEnlistment( string command, Action<StreamWriter> writeStdIn, Action<string> parseStdOutLine, int timeout = -1) { return this.InvokeGitImpl( command, workingDirectory: Environment.SystemDirectory, dotGitDirectory: null, useReadObjectHook: false, writeStdIn: writeStdIn, parseStdOutLine: parseStdOutLine, timeoutMs: timeout); } /// <summary> /// Invokes git.exe from an enlistment's repository root /// </summary> private Result InvokeGitInWorkingDirectoryRoot( string command, bool useReadObjectHook, Action<StreamWriter> writeStdIn = null) { return this.InvokeGitImpl( command, workingDirectory: this.workingDirectoryRoot, dotGitDirectory: null, useReadObjectHook: useReadObjectHook, writeStdIn: writeStdIn, parseStdOutLine: null, timeoutMs: -1); } /// <summary> /// Invokes git.exe against an enlistment's .git folder. /// This method should be used only with git-commands that ignore the working directory /// </summary> private Result InvokeGitAgainstDotGitFolder(string command) { return this.InvokeGitAgainstDotGitFolder(command, null, null); } private Result InvokeGitAgainstDotGitFolder( string command, Action<StreamWriter> writeStdIn, Action<string> parseStdOutLine) { // This git command should not need/use the working directory of the repo. // Run git.exe in Environment.SystemDirectory to ensure the git.exe process // does not touch the working directory return this.InvokeGitImpl( command, workingDirectory: Environment.SystemDirectory, dotGitDirectory: this.dotGitRoot, useReadObjectHook: false, writeStdIn: writeStdIn, parseStdOutLine: parseStdOutLine, timeoutMs: -1); } public class Result { public const int SuccessCode = 0; public const int GenericFailureCode = 1; public Result(string output, string errors, int returnCode) { this.Output = output; this.Errors = errors; this.ReturnCode = returnCode; } public string Output { get; } public string Errors { get; } public int ReturnCode { get; } public bool HasErrors { get { return this.ReturnCode != SuccessCode; } } } } }
39.903537
168
0.543876
[ "MIT" ]
sniperkit/snk.fork.VFSForGit
GVFS/GVFS.Common/Git/GitProcess.cs
24,820
C#
using Quilt4Net.Core.Interfaces; using Tharga.Toolkit.Console.Commands.Base; namespace Quilt4Net.Sample.Console.Commands.User { internal class GetUserInfoCommand : ActionCommandBase { private readonly IQuilt4NetClient _client; public GetUserInfoCommand(IQuilt4NetClient client) : base("Info", "Get info about the user.") { _client = client; } public override bool CanExecute(out string reasonMessage) { reasonMessage = string.Empty; if (!_client.Actions.User.IsAuthorized) reasonMessage = "Not Authorized"; return _client.Actions.User.IsAuthorized; } public override void Invoke(string[] param) { var response = _client.Actions.User.GetUserInfoAsync().Result; OutputInformation(response.Email); } } }
29.866667
74
0.629464
[ "MIT" ]
Quilt4/Quilt4Net
Quilt4Net.Sample.Console/Commands/User/GetUserInfoCommand.cs
896
C#
/************************************************************************** * ================================= * CLR版本 :4.0.30319.42000 * 命名空间 :Memoyu.Mbill.WebApi.Aop.Filter * 文件名称 :LocalExceptionFilter.cs * ================================= * 创 建 者 :Memoyu * 创建日期 :2021-01-03 20:53:07 * 邮箱 :mmy6076@outlook.com * 功能描述 : ***************************************************************************/ using Memoyu.Mbill.Application.Contracts.Exceptions; using Memoyu.Mbill.ToolKits.Base; using Memoyu.Mbill.ToolKits.Base.Enum.Base; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System; namespace Memoyu.Mbill.WebApi.Aop.Filter { /// <summary> /// 出现异常时,如KnownException业务异常,会先执行方法过滤器 (LogActionFilterAttribute)的OnActionExecuted才会执行此异常过滤器。 /// </summary> public class LocalExceptionFilter : IExceptionFilter { private readonly ILogger _logger; private readonly IWebHostEnvironment _environment; public LocalExceptionFilter(ILogger<LocalExceptionFilter> logger, IWebHostEnvironment environment) { _logger = logger; _environment = environment; } public void OnException(ExceptionContext context) { if (context.Exception is KnownException exception) { ServiceResult result = new ServiceResult { Code = exception.GetErrorCode(), Message = exception.Message }; _logger.LogWarning(JsonConvert.SerializeObject(result)); HandlerException(context, result, exception.GetStatusCode()); return; } string error = "异常信息:"; void ReadException(Exception ex) { error += $"{ex.Message} | {ex.StackTrace} | {ex.InnerException}"; if (ex.InnerException != null) { ReadException(ex.InnerException); } } ReadException(context.Exception); _logger.LogError(error); ServiceResult response = new ServiceResult { Code= ServiceResultCode.UnknownError, Message = _environment.IsDevelopment() ? error : "服务器正忙,请稍后再试." }; HandlerException(context, response, StatusCodes.Status500InternalServerError); } private void HandlerException(ExceptionContext context, ServiceResult response, int statusCode) { context.Result = new JsonResult(response) { StatusCode = statusCode, ContentType = "application/json", }; context.ExceptionHandled = true; } } }
33.348315
106
0.560647
[ "MIT" ]
BlazorHub/mbill_service
src/Memoyu.Mbill.WebApi/Aop/Filter/LocalExceptionFilter.cs
3,132
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Input { /// <summary> /// Generic Input Action Rule for raising actions based on specific criteria. /// </summary> [Serializable] public struct InputActionRuleDigital : IInputActionRule<bool> { /// <summary> /// Constructor. /// </summary> /// <param name="baseAction">The Base Action that the rule will listen to.</param> /// <param name="ruleAction">The Action to raise if the criteria is met.</param> /// <param name="criteria">The criteria to check against for determining if the action should be raised.</param> public InputActionRuleDigital(MixedRealityInputAction baseAction, MixedRealityInputAction ruleAction, bool criteria) { this.baseAction = baseAction; this.ruleAction = ruleAction; this.criteria = criteria; } [SerializeField] [Tooltip("The Base Action that the rule will listen to.")] private MixedRealityInputAction baseAction; /// <inheritdoc /> public MixedRealityInputAction BaseAction => baseAction; [SerializeField] [Tooltip("The Action to raise if the criteria is met.")] private MixedRealityInputAction ruleAction; /// <inheritdoc /> public MixedRealityInputAction RuleAction => ruleAction; [SerializeField] [Tooltip("The criteria to check against for determining if the action should be raised.")] private bool criteria; /// <inheritdoc /> public bool Criteria => criteria; } }
35
124
0.653061
[ "MIT" ]
AdrianaMusic/MixedRealityToolkit-Unity
Assets/MRTK/Core/Definitions/InputSystem/InputActionRuleDigital.cs
1,717
C#
using Nandaka.Model.Registers; namespace Nandaka.Core.Registers { // do not change name for this class (source generator) public sealed class LocalDeviceRegisterFactory : IRegisterFactory { public IReadOnlyRegister<T> CreateReadOnly<T>(int address, T defaultValue = default) where T: struct { return new Register<T>(address, RegisterType.WriteRequest, defaultValue); } public IRegister<T> Create<T>(int address, T defaultValue = default) where T: struct { return new Register<T>(address, RegisterType.ReadRequest, defaultValue); } } }
32.55
93
0.64977
[ "MIT" ]
Vlbager/Nandaka
Nandaka.Core/Registers/Factory/LocalDeviceRegisterFactory.cs
653
C#
using System; namespace Project2 { public class Class2 { public static void ReferencedMethod() { } } }
11.166667
47
0.574627
[ "MIT" ]
OptiNav/ReferenceAnalyzer
test_samples/two_references_one_unused/Project2/Class2.cs
136
C#
namespace StoicGoose.Emulation.Sound { public class AswanSoundController : SoundControllerCommon { public override byte MaxMasterVolume => 2; public override int NumChannels => 4; /* REG_SND_9697 */ protected ushort unknown9697; /* REG_SND_9899 */ protected ushort unknown9899; public AswanSoundController(MemoryReadDelegate memoryRead, int rate, int outChannels) : base(memoryRead, rate, outChannels) { } public override void ResetRegisters() { base.ResetRegisters(); unknown9697 = 0; unknown9899 = 0; } public override int[] GenerateSample() { channelSampleBuffers[0].Add((short)(channel1.IsEnabled ? (channel1.OutputLeft & 0x07FF) << 5 : 0)); channelSampleBuffers[0].Add((short)(channel1.IsEnabled ? (channel1.OutputRight & 0x07FF) << 5 : 0)); channelSampleBuffers[1].Add((short)(channel2.IsEnabled ? (channel2.OutputLeft & 0x07FF) << 5 : 0)); channelSampleBuffers[1].Add((short)(channel2.IsEnabled ? (channel2.OutputRight & 0x07FF) << 5 : 0)); channelSampleBuffers[2].Add((short)(channel3.IsEnabled ? (channel3.OutputLeft & 0x07FF) << 5 : 0)); channelSampleBuffers[2].Add((short)(channel3.IsEnabled ? (channel3.OutputRight & 0x07FF) << 5 : 0)); channelSampleBuffers[3].Add((short)(channel4.IsEnabled ? (channel4.OutputLeft & 0x07FF) << 5 : 0)); channelSampleBuffers[3].Add((short)(channel4.IsEnabled ? (channel4.OutputRight & 0x07FF) << 5 : 0)); var mixedLeft = 0; if (channel1.IsEnabled) mixedLeft += channel1.OutputLeft; if (channel2.IsEnabled) mixedLeft += channel2.OutputLeft; if (channel3.IsEnabled) mixedLeft += channel3.OutputLeft; if (channel4.IsEnabled) mixedLeft += channel4.OutputLeft; mixedLeft = (mixedLeft & 0x07FF) << 5; var mixedRight = 0; if (channel1.IsEnabled) mixedRight += channel1.OutputRight; if (channel2.IsEnabled) mixedRight += channel2.OutputRight; if (channel3.IsEnabled) mixedRight += channel3.OutputRight; if (channel4.IsEnabled) mixedRight += channel4.OutputRight; mixedRight = (mixedRight & 0x07FF) << 5; return new[] { mixedLeft, mixedRight }; } public override byte ReadRegister(ushort register) { return register switch { /* REG_SND_9697 (low) */ 0x96 => (byte)((unknown9697 >> 0) & 0b11111111), /* REG_SND_9697 (high) */ 0x97 => (byte)((unknown9697 >> 8) & 0b00000011), /* REG_SND_9899 (low) */ 0x98 => (byte)((unknown9899 >> 0) & 0b11111111), /* REG_SND_9899 (high) */ 0x99 => (byte)((unknown9899 >> 8) & 0b00000011), /* REG_SND_9A */ 0x9A => 0b111, /* REG_SND_9B */ 0x9B => 0b11111110, /* REG_SND_9C */ 0x9C => 0b11111111, /* REG_SND_9D */ 0x9D => 0b11111111, /* Fall through to common */ _ => base.ReadRegister(register) }; } public override void WriteRegister(ushort register, byte value) { switch (register) { case 0x96: /* REG_SND_9697 (low) */ unknown9697 = (ushort)((unknown9697 & 0x0300) | (value << 0)); break; case 0x97: /* REG_SND_9697 (high) */ unknown9697 = (ushort)((unknown9697 & 0x00FF) | (value << 8)); break; case 0x98: /* REG_SND_9899 (low) */ unknown9899 = (ushort)((unknown9899 & 0x0300) | (value << 0)); break; case 0x99: /* REG_SND_9899 (high) */ unknown9899 = (ushort)((unknown9899 & 0x00FF) | (value << 8)); break; case 0x9A: case 0x9B: case 0x9C: case 0x9D: /* REG_SND_9x */ break; default: /* Fall through to common */ base.WriteRegister(register, value); break; } } } }
31.121739
129
0.650182
[ "MIT" ]
xdanieldzd/StoicGoose
StoicGoose/Emulation/Sound/AswanSoundController.cs
3,581
C#
using System; using Nefarius.ViGEm.Client.Exceptions; using Nefarius.ViGEm.Client.Targets; using Nefarius.ViGEm.Client.Targets.Xbox360; namespace RB4InstrumentMapper.Parsing { class VigemMapper : IDeviceMapper { /// <summary> /// The device to map to. /// </summary> private IXbox360Controller device; /// <summary> /// Whether or not feedback has been received to indicate that the device has connected. /// </summary> private bool deviceConnected = false; private int prevInputSeqCount = -1; private int prevVirtualKeySeqCount = -1; /// <summary> /// Creates a new VigemMapper. /// </summary> public VigemMapper() { device = VigemStatic.CreateDevice(); device.FeedbackReceived += ReceiveUserIndex; try { device.Connect(); } catch (VigemNoFreeSlotException ex) { device = null; throw new ParseException("ViGEmBus device slots are full.", ex); } device.AutoSubmitReport = false; } /// <summary> /// Performs cleanup on object finalization. /// </summary> ~VigemMapper() { Close(); } /// <summary> /// Temporary event handler for logging the user index of a ViGEm device. /// </summary> void ReceiveUserIndex(object sender, Xbox360FeedbackReceivedEventArgs args) { // Device has connected deviceConnected = true; // Log the user index Console.WriteLine($"Created new ViGEmBus device with user index {args.LedNumber}"); // Unregister the event handler (sender as IXbox360Controller).FeedbackReceived -= ReceiveUserIndex; } /// <summary> /// Parses an input report. /// </summary> public void ParseInput(ReadOnlySpan<byte> data, byte length, byte sequenceCount) { // Don't parse the same report twice if (sequenceCount == prevInputSeqCount) { return; } else { prevInputSeqCount = sequenceCount; } if (!deviceConnected) { // Device has not connected yet return; } switch (length) { case Length.Input_Guitar: ParseGuitar(data); break; case Length.Input_Drums: ParseDrums(data); break; default: // Don't parse unknown button data return; } // Send data device.SubmitReport(); } /// <summary> /// Parses common button data from an input report. /// </summary> private void ParseCoreButtons(ushort buttons) { // Menu device.SetButtonState(Xbox360Button.Start, (buttons & GamepadButton.Menu) != 0); // Options device.SetButtonState(Xbox360Button.Back, (buttons & GamepadButton.Options) != 0); // Dpad device.SetButtonState(Xbox360Button.Up, (buttons & GamepadButton.DpadUp) != 0); device.SetButtonState(Xbox360Button.Down, (buttons & GamepadButton.DpadDown) != 0); device.SetButtonState(Xbox360Button.Left, (buttons & GamepadButton.DpadLeft) != 0); device.SetButtonState(Xbox360Button.Right, (buttons & GamepadButton.DpadRight) != 0); // Other buttons are not mapped here since they may have specific uses } /// <summary> /// Parses guitar input data from an input report. /// </summary> private void ParseGuitar(ReadOnlySpan<byte> data) { // Buttons ParseCoreButtons(data.GetUInt16BE(GuitarOffset.Buttons)); // Frets byte frets = data[GuitarOffset.UpperFrets]; frets |= data[GuitarOffset.LowerFrets]; device.SetButtonState(Xbox360Button.A, (frets & GuitarFret.Green) != 0); device.SetButtonState(Xbox360Button.B, (frets & GuitarFret.Red) != 0); device.SetButtonState(Xbox360Button.Y, (frets & GuitarFret.Yellow) != 0); device.SetButtonState(Xbox360Button.X, (frets & GuitarFret.Blue) != 0); device.SetButtonState(Xbox360Button.LeftShoulder, (frets & GuitarFret.Orange) != 0); // Whammy device.SetAxisValue(Xbox360Axis.RightThumbX, data[GuitarOffset.WhammyBar].ScaleToInt16()); // Tilt device.SetAxisValue(Xbox360Axis.RightThumbY, data[GuitarOffset.Tilt].ScaleToInt16()); // Pickup Switch device.SetSliderValue(Xbox360Slider.LeftTrigger, data[GuitarOffset.PickupSwitch]); } /// <summary> /// Parses drums input data from an input report. /// </summary> private void ParseDrums(ReadOnlySpan<byte> data) { // Buttons ParseCoreButtons(data.GetUInt16BE(DrumOffset.Buttons)); // Pads and cymbals byte redPad = (byte)(data[DrumOffset.PadVels] >> 4); byte yellowPad = (byte)(data[DrumOffset.PadVels] & DrumPadVel.Yellow); byte bluePad = (byte)(data[DrumOffset.PadVels + 1] >> 4); byte greenPad = (byte)(data[DrumOffset.PadVels + 1] & DrumPadVel.Green); byte yellowCym = (byte)(data[DrumOffset.CymbalVels] >> 4); byte blueCym = (byte)(data[DrumOffset.CymbalVels] & DrumPadVel.Blue); byte greenCym = (byte)(data[DrumOffset.CymbalVels + 1] >> 4); // Color flags device.SetButtonState(Xbox360Button.B, (redPad) != 0); device.SetButtonState(Xbox360Button.Y, (yellowPad | yellowCym) != 0); device.SetButtonState(Xbox360Button.X, (bluePad | blueCym) != 0); device.SetButtonState(Xbox360Button.A, (greenPad | greenCym) != 0); // Pad flag device.SetButtonState(Xbox360Button.RightThumb, (redPad | yellowPad | bluePad | greenPad) != 0); // Cymbal flag device.SetButtonState(Xbox360Button.RightShoulder, (yellowCym | blueCym | greenCym) != 0); // Velocities device.SetAxisValue( Xbox360Axis.LeftThumbX, ByteToVelocity(redPad) ); device.SetAxisValue( Xbox360Axis.LeftThumbY, ByteToVelocityNegative((byte)(yellowPad | yellowCym)) ); device.SetAxisValue( Xbox360Axis.RightThumbX, ByteToVelocity((byte)(bluePad | blueCym)) ); device.SetAxisValue( Xbox360Axis.RightThumbY, ByteToVelocityNegative((byte)(greenPad | greenCym)) ); /// <summary> /// Scales a byte to a drums velocity value. /// </summary> short ByteToVelocity(byte value) { // Scale the value to fill the byte value = (byte)(value * 0x11); return (short)( // Bitwise invert to flip the value, then shift down one to exclude the sign bit (~value.ScaleToUInt16()) >> 1 ); } /// <summary> /// Scales a byte to a negative drums velocity value. /// </summary> short ByteToVelocityNegative(byte value) { // Scale the value to fill the byte value = (byte)(value * 0x11); return (short)( // Bitwise invert to flip the value, then shift down one to exclude the sign bit, then add our own ((~value.ScaleToUInt16()) >> 1) | 0x8000 ); } } /// <summary> /// Parses a virtual key report. /// </summary> public void ParseVirtualKey(ReadOnlySpan<byte> data, byte length, byte sequenceCount) { // Don't parse the same report twice if (sequenceCount == prevVirtualKeySeqCount) { return; } else { prevVirtualKeySeqCount = sequenceCount; } // Only respond to the Left Windows keycode, as this is what the guide button reports. if (data[KeycodeOffset.Keycode] == Keycodes.LeftWin) { device.SetButtonState(Xbox360Button.Guide, data[KeycodeOffset.PressedState] != 0); device.SubmitReport(); } } /// <summary> /// Performs cleanup for the object. /// </summary> public void Close() { // Reset report try { device.ResetReport(); } catch {} try { device.SubmitReport(); } catch {} // Disconnect device try { device?.Disconnect(); } catch {} device = null; } } }
34.824627
118
0.532412
[ "MIT" ]
TheNathannator/RB4InstrumentMapper
PacketParsing/VigemMapper.cs
9,333
C#
using System; using System.Runtime.Serialization; namespace Exodrifter.Rumor.Engine { /// <summary> /// This type may be returned from a node to indicate some condition that /// should happen before execution may continue. /// </summary> [Serializable] public abstract class Yield : ISerializable { public bool Finished { get; protected set; } public double Elapsed { get; protected set; } public Yield() { Finished = false; Elapsed = 0; } public virtual void Advance() { } public virtual void Update(Rumor rumor, double delta) { Elapsed += delta; } public virtual void Choose() { } #region Serialization public Yield(SerializationInfo info, StreamingContext context) { Finished = info.GetValue<bool>("finished"); Elapsed = info.GetValue<double>("elapsed"); } public virtual void GetObjectData (SerializationInfo info, StreamingContext context) { info.AddValue<bool>("finished", Finished); info.AddValue<double>("elapsed", Elapsed); } #endregion } /// <summary> /// Yield execution until Rumor is advanced. /// </summary> [Serializable] public class ForAdvance : Yield, ISerializable { public ForAdvance() { } public override void Advance() { Finished = true; } #region Serialization public ForAdvance(SerializationInfo info, StreamingContext context) : base(info, context) { } #endregion } /// <summary> /// Yield execution until Rumor is advanced. /// </summary> [Serializable] public class ForSeconds : Yield, ISerializable { private readonly double time; public ForSeconds(double seconds) { time = seconds; } public override void Update(Rumor rumor, double delta) { base.Update(rumor, delta); Finished = Elapsed >= time; } #region Serialization public ForSeconds(SerializationInfo info, StreamingContext context) : base(info, context) { time = info.GetValue<double>("time"); } public override void GetObjectData (SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue<double>("time", time); } #endregion } /// <summary> /// Yield execution until Rumor is advanced. /// </summary> [Serializable] public class ForChoose : Yield, ISerializable { public double? Timeout { get; private set; } private readonly MoveType? moveType; private readonly string label; public ForChoose(double? timeout, MoveType? moveType, string label) { Timeout = timeout; this.moveType = moveType; this.label = label; } public override void Update(Rumor rumor, double delta) { base.Update(rumor, delta); if (Timeout.HasValue) { Finished = Elapsed >= Timeout.Value; if (Finished) { switch (moveType) { case MoveType.Jump: rumor.Jump(label); break; case MoveType.Call: rumor.Call(label); break; } rumor.State.ClearChoices(); } } } public override void Choose() { Finished = true; } #region Serialization public ForChoose(SerializationInfo info, StreamingContext context) : base(info, context) { Timeout = info.GetValue<double?>("timeout"); moveType = info.GetValue<MoveType?>("moveType"); label = info.GetValue<string>("label"); } public override void GetObjectData (SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue<double?>("timeout", Timeout); info.AddValue<MoveType?>("moveType", moveType); info.AddValue<string>("label", label); } #endregion } }
20.597701
74
0.676897
[ "MIT" ]
exodrifter/unity-rumor
Engine/Yield.cs
3,586
C#
using System; using NpcService.Ai.NpcType; namespace NpcService.Ai.NpcCitizen { public class Buffer50 : Citizen { } }
13.1
35
0.70229
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
dr3dd/L2Interlude
NpcService/Ai/NpcCitizen/Buffer50.cs
131
C#
using Abp.AspNetCore.Mvc.Controllers; using Abp.IdentityFramework; using Microsoft.AspNetCore.Identity; namespace ShopManage.Controllers { public abstract class ShopManageControllerBase: AbpController { protected ShopManageControllerBase() { LocalizationSourceName = ShopManageConsts.LocalizationSourceName; } protected void CheckErrors(IdentityResult identityResult) { identityResult.CheckErrors(LocalizationManager); } } }
25.55
77
0.712329
[ "MIT" ]
DSOY/ShopManage
aspnet-core/src/ShopManage.Web.Core/Controllers/ShopManageControllerBase.cs
511
C#
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // <auto-generated> // This file contains automatically generated unit tests. // Do NOT modify this file manually. // // When Pex is invoked again, // it might remove or update any previously generated unit tests. // // If the contents of this file becomes outdated, e.g. if it does not // compile anymore, you may delete this file and invoke Pex again. // </auto-generated> using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.Pex.Framework.Generated; using System.Diagnostics.Contracts; using Microsoft.Pex.Engine.Exceptions; public partial class ClassWithProtocolTest { [TestMethod] [PexGeneratedBy(typeof(global::ClassWithProtocolTest))] [PexRaisedContractException(PexExceptionState.Expected)] public void DataGet01() { try { if (!PexContract.HasRequiredRuntimeContracts (typeof(global::ClassWithProtocol), (PexRuntimeContractsFlags)4223)) Assert.Inconclusive ("assembly assembly Samples is not instrumented with runtime contracts"); global::ClassWithProtocol classWithProtocol; classWithProtocol = global::ClassWithProtocolFactory.Create((string)null, (string)null, 0); this.DataGet(classWithProtocol); throw new AssertFailedException(); } catch(Exception ex) { if (!PexContract.IsContractException(ex)) throw ex; } } }
44.122807
463
0.75507
[ "MIT" ]
Acidburn0zzz/CodeContracts
Microsoft.Research/RegressionTest/PostMSI/Samples/Samples.Tests/ClassWithProtocolTest.DataGet.g.cs
2,515
C#
using Material.Blazor.Internal; using System; using System.Threading.Tasks; namespace Material.Blazor { /// <summary> /// Settings for an individual snackbar notification determining all aspects controlling /// it's markup and behaviour. All parameters are optional with defaults defined in /// the <see cref="MBSnackbarServiceConfiguration"/> that you define when creating the snackbar service. /// </summary> public class MBSnackbarSettings { /// <summary> /// The action that is performed when the button in the snackbar is clicked (optional. if set, <see cref="ActionText"/> must also be set). /// </summary> public Action Action { get; set; } /// <summary> /// The text to display in the action button in the snackbar (optional. if set, <see cref="Action"/> must also be set). /// </summary> public string ActionText { get; set; } /// <summary> /// By default, snackbars are centered horizontally within the viewport. /// On larger screens, they can optionally be displayed on the leading edge of the screen (the left side in LTR, or the right side in RTL) by setting this property to true. /// Default: false. /// </summary> public bool? Leading { get; set; } /// <summary> /// Action buttons with long text should be positioned below the label instead of alongside it. /// This can be accomplished by setting this property to true. /// Default: false. /// </summary> public bool? Stacked { get; set; } /// <summary> /// The message to be displayed in the snackbar. /// </summary> public string Message { get; set; } /// <summary> /// Snackbars are intended to dismiss on their own after a few seconds, but a dedicated dismiss icon may be optionally included as well for accessibility purposes. /// By default, a dismiss icon is displayed. This can be disabled by setting this property to false. /// </summary> public MBNotifierCloseMethod? CloseMethod { get; set; } private int? timeout; /// <summary> /// The snackbar's timeout in milliseconds. /// Minimum value is 4000 (4 seconds), maximum value is 10000 (10s). /// Use -1 to disable. /// </summary> public int? Timeout { get => timeout; set => timeout = value switch { null => null, _ => Math.Max(4000, Math.Min(value.Value, 10000)) }; } /// <summary> /// The snackbar service's configuration. /// </summary> internal MBSnackbarServiceConfiguration Configuration { get; set; } internal int AppliedTimeout => AppliedCloseMethod == MBNotifierCloseMethod.DismissButton ? -1 : Timeout is not null ? Timeout.Value : Configuration?.Timeout ?? MBSnackbarServiceConfiguration.DefaultTimeout; internal Action AppliedAction => Action; // No default action through Configuration. internal string AppliedActionText => ActionText; // No default action through Configuration. internal bool AppliedLeading => Leading is not null ? Leading.Value : Configuration?.Leading ?? MBSnackbarServiceConfiguration.DefaultLeading; internal bool AppliedStacked => Stacked is not null ? Stacked.Value : Configuration?.Stacked ?? MBSnackbarServiceConfiguration.DefaultStacked; internal string AppliedMessage => Message is not null ? Message : string.Empty; internal MBNotifierCloseMethod AppliedCloseMethod => CloseMethod is not null ? CloseMethod.Value : Configuration?.CloseMethod ?? MBSnackbarServiceConfiguration.DefaultCloseMethod; internal Func<SnackbarInstance, Task> OnClose { get; set; } internal bool Closed { get; set; } } }
42.898876
214
0.661865
[ "MIT" ]
HannahKiekens/Material.Blazor
Material.Blazor/Model/Snackbar/MBSnackbarSettings.cs
3,820
C#
/********************************************************************************** * FrwSimpleWinCRUD https://github.com/frwsoftware/FrwSimpleWinCRUD * The Open-Source Library for most quick WinForm CRUD application creation * MIT License Copyright (c) 2016 FrwSoftware * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. **********************************************************************************/ using System; using System.IO; using System.Reflection; using log4net; using log4net.Config; using System.Windows.Forms; using System.Text; namespace FrwSoftware { public class EventLogEventArgs : EventArgs { public string Message { get; set; } public Exception Exception { get; set; } } public delegate void EventLogEventHandler(object sender, EventLogEventArgs e); //strategy // logError // minor errors are output only to the log (in fact, this is analogous to simply calling the logger) // eventError // errors of background rectification, which do not prevent further execution of the program, are output to the log and system of events with indication in the status line // processError // interactive errors in the process of user actions are output to the log and message box // this output is not allowed in background processes // the handlers of such errors should be on the self-level top level of the user operation // this also prevents multiple input of a message public class Log { private ILog log4net = null;//todo static or not? private static bool configured = false; public Log() { configureLogs(); log4net = LogManager.GetLogger(typeof(Log)); } public Log(string module_name) { configureLogs(); log4net = LogManager.GetLogger(module_name); } static public Log GetLogger() { return new Log(); } static public Log GetLogger(string module_name) { return new Log(module_name); } static public void CloseAndFlush() { } #region enabled_properties public bool isDebugEnabled { get { if (log4net != null) { return log4net.IsDebugEnabled; } else { return false; } } } public bool isInfoEnabled { get { if (log4net != null) { return log4net.IsInfoEnabled; } else { return false; } } } public bool isWarnEnabled { get { if (log4net != null) { return log4net.IsWarnEnabled; } else { return false; } } } #endregion private static void configureLogs() { if (configured == false) { lock (typeof(Log)) { if (configured == false) { configureLog4net(); configured = true; } } } } private static void configureLog4net() { string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6); FileInfo logConfig = new FileInfo(path + "\\" + "logConfig.xml"); if (logConfig.Exists) { XmlConfigurator.Configure(logConfig);//This file path is relative to the application base directory (AppDomain.CurrentDomain.BaseDirectory). } else { BasicConfigurator.Configure(); } } #region log functions public void Info(string message) { if (log4net != null) log4net.Info(message); } public void Debug(string message) { if (log4net != null) log4net.Debug(message); } public void Fatal(string message) { if (log4net != null) log4net.Fatal(message); } public void Fatal(string message, Exception e) { if (log4net != null) log4net.Fatal(message, e); } public void Error(string message) { if (log4net != null) log4net.Error(message); } public void Error(string message, Exception e) { if (log4net != null) log4net.Error(message, e); } public void Warn(string message) { if (log4net != null) log4net.Warn(message); } public void Warn(string message, Exception e) { if (log4net != null) log4net.Warn(message, e); } #endregion #region trace utils static Log log = null; static public event EventLogEventHandler EventLogEvent; //static public //A group of methods that output a message to the log static public void LogError(string message) { fullProcessError(message, null, true, false, false); } static public void LogError(string message, Exception e = null) { fullProcessError(message, e, true, false, false); } static public void LogError(Exception e) { fullProcessError(null, e, true, false, false); } //A group of methods that output a message to the log and to the event system static public void EventError(string message) { fullProcessError(message, null, true, false, true); } static public void EventError(string message, Exception e) { fullProcessError(message, e, true, false, true); } static public void EventError(Exception e) { fullProcessError(null, e, true, false, true); } //A group of methods that output a message to the log and to the messagebox static public void ShowError(string message) { fullProcessError(message, null, true, true, false); } static public void ShowError(string message, Exception e) { fullProcessError(message, e, true, true, false); } static public void ShowError(Exception e) { fullProcessError(null, e, true, true, false); } static private void fullProcessError(string message, Exception e, bool writeToLog, bool showMessageBox, bool writeToEventLog) { if (message == null) { message = ""; } if (e != null) { if (e is System.Runtime.InteropServices.COMException) { int hr = ((System.Runtime.InteropServices.COMException)e).ErrorCode; message = message + String.Format(" COM error.\nHRESULT = {0}\n{1}", hr, e.Message); } else { message = message + e.Message; } } if (writeToLog) { if (log == null) { log = Log.GetLogger(); } log.Error(message, e); } if (writeToEventLog) { if (EventLogEvent != null) { EventLogEvent(null, new EventLogEventArgs() { Message = message, Exception = e }); } } if (showMessageBox) { MessageBox.Show(message, FrwUtilsRes.Log_Error_In_Work, MessageBoxButtons.OK, MessageBoxIcon.Error); } } static public void ProcessDebug(string message) { if (log == null) { log = Log.GetLogger(); } log.Debug(message); } public static string PropertyList(object obj) { var props = obj.GetType().GetProperties(); var sb = new StringBuilder(); foreach (var p in props) { sb.AppendLine(p.Name + ": " + p.GetValue(obj, null)); } return sb.ToString(); } #endregion } }
30.939189
175
0.508408
[ "MIT" ]
frwsoftware/FrwSimpleWinCRUD
FrwSimpleJsonORM/Utils/Log.cs
9,160
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using HackTheClimate.Data; using HackTheClimate.Services.Similarity; namespace HackTheClimate.Services { public class SimilarityService { private static Dictionary<string, double> _precomputed; private readonly EntityRecognitionService _entityRecognitionService; private readonly TopicBasedSimilarityService _topicBasedSimilarityService; public SimilarityService(EntityRecognitionService entityRecognitionService, TopicBasedSimilarityService topicBasedSimilarityService) { _entityRecognitionService = entityRecognitionService; _topicBasedSimilarityService = topicBasedSimilarityService; } public async Task<IEnumerable<(string Id, double SimilarityScore)>> GetMostSimilarLegislationIds(Legislation a) { if (_precomputed == null || !_precomputed.Any()) { _precomputed = new Dictionary<string, double>(); var assembly = Assembly.GetExecutingAssembly(); await using var stream = assembly.GetManifestResourceStream("HackTheClimate.Services.precomputedSimilarities.csv"); using var reader = new StreamReader(stream, Encoding.UTF8); { var result = await reader.ReadToEndAsync(); var lines = result.Split("\n"); foreach (var line in lines) if (!string.IsNullOrEmpty(line)) { var cells = line.Split(','); var key = cells[0] + "," + cells[1]; var value = double.Parse(cells[2]); _precomputed.Add(key, value); } } } return _precomputed.Where(p => p.Key.Contains(a.Id)).OrderBy(p => p.Value).Take(10) .Select(p => (p.Key, p.Value)); } public SimilarityResult CalculateSimilarity(Legislation a, Legislation b, SimilarityWeights weights) { var keywordSimilarity = ListSimilarity(a.Keywords, b.Keywords); var sectorSimilarity = ListSimilarity(a.Sectors, b.Sectors); var frameworksSimilarity = ListSimilarity(a.Frameworks, b.Frameworks); var instrumentsSimilarity = ListSimilarity(a.Instruments, b.Instruments); var naturalHazardsSimilarity = ListSimilarity(a.NaturalHazards, b.NaturalHazards); var documentTypesSimilarity = ListSimilarity(a.DocumentTypes, b.DocumentTypes); var responsesSimilarity = ListSimilarity(a.Responses, b.Responses); var locationSimilarity = PropertySimilarity(a.Geography, b.Geography); var typeSimilarity = PropertySimilarity(a.Type, b.Type); var entitySkillSimilarity = EntityCategorySimilarity(a, b, "Skill"); var entityProductSimilarity = EntityCategorySimilarity(a, b, "Product"); var entityEventSimilarity = EntityCategorySimilarity(a, b, "Event"); var entityLocationSimilarity = EntityCategorySimilarity(a, b, "Location"); var topicSimilarity = _topicBasedSimilarityService.CalculateSimilarity(a, b); return new SimilarityResult { SimilarityScore = (weights.KeywordWeight * keywordSimilarity.Score + weights.SectorWeight * sectorSimilarity.Score + weights.FrameworkWeight * frameworksSimilarity.Score + weights.InstrumentWeight * instrumentsSimilarity.Score + weights.NaturalHazardWeight * naturalHazardsSimilarity.Score + weights.DocumentTypeWeight * documentTypesSimilarity.Score + weights.ResponseWeight * responsesSimilarity.Score + weights.LocationWeight * locationSimilarity + weights.TypeWeight * typeSimilarity + weights.EntityProductWeight * entityProductSimilarity.Score + weights.EntitySkillWeight * entitySkillSimilarity.Score + weights.EntityEventWeight * entityEventSimilarity.Score + weights.EntityLocationWeight * entityLocationSimilarity.Score + weights.TopicWeight * topicSimilarity.Score) / weights.TotalWeight(), KeywordSimilarity = keywordSimilarity, SectorsSimilarity = keywordSimilarity, FrameworksSimilarity = frameworksSimilarity, InstrumentsSimilarity = instrumentsSimilarity, NaturalHazardsSimilarity = naturalHazardsSimilarity, DocumentTypesSimilarity = documentTypesSimilarity, ResponsesSimilarity = responsesSimilarity, TypeSimilarity = typeSimilarity, LocationSimilarity = locationSimilarity, SkillEntitiesSimilarity = entitySkillSimilarity, ProductEntitiesSimilarity = entityProductSimilarity, EventEntitiesSimilarity = entityEventSimilarity, LocationEntitiesSimilarity = entityLocationSimilarity, TopicSimilarity = topicSimilarity }; } private ListSimilarityResult<string> EntityCategorySimilarity(Legislation a, Legislation b, string category) { var entitiesSkillA = _entityRecognitionService.GetEntitiesForCategory(a, category); var entitiesSkillB = _entityRecognitionService.GetEntitiesForCategory(b, category); var rawListSimilarity = ListSimilarity(entitiesSkillA, entitiesSkillB); // As there is usually a big number of entities, the similarities are usually very low. // Thus boosting the value, in case of matches. // See https://www.wolframalpha.com/input/?i=plot+1-e%5E%28-5x%29+where+x%3D0+to+1 rawListSimilarity.Score = 1 - Math.Pow(Math.E, -4 * rawListSimilarity.Score); return rawListSimilarity; } private static int PropertySimilarity<T>(T a, T b) { return a.Equals(b) ? 1 : 0; } private static ListSimilarityResult<T> ListSimilarity<T>(ICollection<T> a, ICollection<T> b) { var matches = GetMatchingEntries(a, b); double totalEntries = a.Count + b.Count; var score = totalEntries > 0 ? matches.Count * 2 / totalEntries : 0; return new ListSimilarityResult<T> { Score = score, Overlap = matches, NoMatchA = a.Count - matches.Count, NoMatchB = b.Count - matches.Count }; } private static ICollection<T> GetMatchingEntries<T>(ICollection<T> a, ICollection<T> b) { var matches = new List<T>(); foreach (var keyword in a) if (b.Contains(keyword)) matches.Add(keyword); return matches; } } public class ListSimilarityResult<T> { public double Score { get; set; } public IEnumerable<T> Overlap { get; set; } public int NoMatchA { get; set; } public int NoMatchB { get; set; } public ListSimilarityResult<string> ToStringResult() { return new ListSimilarityResult<string> { Score = Score, Overlap = Overlap.Select(e => e.ToString()), NoMatchA = NoMatchA, NoMatchB = NoMatchB }; } } public class SimilarityResult { public double SimilarityScore { get; set; } public ListSimilarityResult<string> KeywordSimilarity { get; set; } public ListSimilarityResult<string> SectorsSimilarity { get; set; } public ListSimilarityResult<Frameworks> FrameworksSimilarity { get; set; } public ListSimilarityResult<string> InstrumentsSimilarity { get; set; } public ListSimilarityResult<string> NaturalHazardsSimilarity { get; set; } public ListSimilarityResult<string> DocumentTypesSimilarity { get; set; } public ListSimilarityResult<string> ResponsesSimilarity { get; set; } public ListSimilarityResult<string> SkillEntitiesSimilarity { get; set; } public ListSimilarityResult<string> ProductEntitiesSimilarity { get; set; } public ListSimilarityResult<string> EventEntitiesSimilarity { get; set; } public ListSimilarityResult<string> LocationEntitiesSimilarity { get; set; } public ListSimilarityResult<string> TopicSimilarity { get; set; } public int LocationSimilarity { get; set; } public int TypeSimilarity { get; set; } } }
50.198925
141
0.600621
[ "MIT" ]
Zuehlke/hack-the-climate
solution/HackTheClimate/Services/SimilarityService.cs
9,339
C#
using Serenity.Services; using System.Collections.Generic; namespace MultiTenancy.Administration { public class TranslationUpdateRequest : ServiceRequest { public string TargetLanguageID { get; set; } public Dictionary<string, string> Translations { get; set; } } }
25.583333
69
0.697068
[ "Unlicense" ]
pratikto/MultiTenancy
MultiTenancy/MultiTenancy.Web/Modules/Administration/Translation/TranslationUpdateRequest.cs
309
C#
using FFImageLoading; using CloudMusic.CustomForms; using Xamarin.Forms; namespace CloudMusic.Views { public partial class ScrollVideoPage : ContentPage { public ScrollVideoPage() { InitializeComponent(); } protected override void OnAppearing() { base.OnAppearing(); listview.ScrollStateChanged += Listview_ScrollStateChanged; } protected override void OnDisappearing() { base.OnDisappearing(); listview.ScrollStateChanged -= Listview_ScrollStateChanged; } private void Listview_ScrollStateChanged(object sender, CustomForms.ScrollStateChangedEventArgs e) { switch (e.CurScrollState) { case ScrollStateChangedEventArgs.ScrollState.Running: ImageService.Instance.SetPauseWork(true); break; case ScrollStateChangedEventArgs.ScrollState.Idle: ImageService.Instance.SetPauseWork(false); break; } } } }
28.275
106
0.587091
[ "MIT" ]
851265601/Xamarin-CloudMusic
CloudMusic/Views/ScrollVideoPage.xaml.cs
1,133
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Routing; namespace Web.Core.Routing.Apps { public class TagAdminRouter { public static void Initialize(IRouteBuilder routes) { routes.MapRoute( name: "admin_tag_list", template: "admin/blog/tag/list/", defaults: new { controller = "TagAdmin", action = "List" } ); routes.MapRoute( name: "admin_tag_create", template: "admin/blog/tag/create/", defaults: new { controller = "TagAdmin", action = "Create" } ); routes.MapRoute( name: "admin_tag_edit", template: "admin/blog/tag/edit/{id}/", defaults: new { controller = "TagAdmin", action = "Edit" } ); routes.MapRoute( name: "admin_tag_delete", template: "admin/blog/tag/delete/{id}/", defaults: new { controller = "TagAdmin", action = "Delete" } ); } } }
30.416667
76
0.506849
[ "MIT" ]
snicoper/BlogNet
src/Web/Core/Routing/Apps/TagAdminRouter.cs
1,097
C#
using Aggregator.Core.Interfaces; namespace Aggregator.Core.Facade { public class ProjectPropertyWrapper : IProjectProperty { public string Name { get; set; } public string Value { get; set; } } }
19
58
0.666667
[ "Apache-2.0" ]
DanielBMann9000/tfsaggregator-webhooks
Aggregator.Core/Facade/ProjectPropertyWrapper.cs
230
C#
using System; using UnityEngine; namespace Caxapexac.Common.Sharp.Editor.Attributes.Fields { /// <summary> /// Field will be Read-Only in Playmode /// </summary> [AttributeUsage(AttributeTargets.Field)] public class ReadOnlyPlaymodeAttribute : PropertyAttribute { } }
21.285714
62
0.701342
[ "MIT" ]
caxapexac/CommonUnity
Caxapexac.Common.Unity/Editor/Attributes/FieldsAccessibility/ReadOnlyPlaymodeAttribute.cs
300
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Auto.ImageTree { public class DirectoryScanInfo { public DirectoryInfo Directory { get; internal set; } public Exception Exception { get; internal set; } } }
20.6875
61
0.719033
[ "MIT" ]
AwkwardCauliflower/Swag
Auto.ImageTree/DirectoryScanInfo.cs
333
C#
namespace EventTraceKit.VsExtension { using System; using Microsoft.VisualStudio.Shell; public static class CommonControlBrushes { private static readonly Guid Category = new Guid("C01072A1-A915-4ABF-89B7-E2F9E8EC4C7F"); private static ThemeResourceKey buttonBackgroundKey; private static ThemeResourceKey buttonForegroundKey; private static ThemeResourceKey buttonBorderBackgroundKey; private static ThemeResourceKey buttonDefaultBackgroundKey; private static ThemeResourceKey buttonDefaultForegroundKey; private static ThemeResourceKey buttonDisabledBackgroundKey; private static ThemeResourceKey buttonDisabledForegroundKey; private static ThemeResourceKey buttonFocusedBackgroundKey; private static ThemeResourceKey buttonFocusedForegroundKey; private static ThemeResourceKey buttonHoverBackgroundKey; private static ThemeResourceKey buttonHoverForegroundKey; private static ThemeResourceKey buttonPressedBackgroundKey; private static ThemeResourceKey buttonPressedForegroundKey; private static ThemeResourceKey buttonBorderDefaultBackgroundKey; private static ThemeResourceKey buttonBorderDisabledBackgroundKey; private static ThemeResourceKey buttonBorderFocusedBackgroundKey; private static ThemeResourceKey buttonBorderHoverBackgroundKey; private static ThemeResourceKey buttonBorderPressedBackgroundKey; private static ThemeResourceKey checkBoxBackgroundBackgroundKey; private static ThemeResourceKey checkBoxBackgroundDisabledBackgroundKey; private static ThemeResourceKey checkBoxBackgroundFocusedBackgroundKey; private static ThemeResourceKey checkBoxBackgroundHoverBackgroundKey; private static ThemeResourceKey checkBoxBackgroundPressedBackgroundKey; private static ThemeResourceKey checkBoxBorderBackgroundKey; private static ThemeResourceKey checkBoxBorderDisabledBackgroundKey; private static ThemeResourceKey checkBoxBorderFocusedBackgroundKey; private static ThemeResourceKey checkBoxBorderHoverBackgroundKey; private static ThemeResourceKey checkBoxBorderPressedBackgroundKey; private static ThemeResourceKey checkBoxGlyphBackgroundKey; private static ThemeResourceKey checkBoxGlyphDisabledBackgroundKey; private static ThemeResourceKey checkBoxGlyphFocusedBackgroundKey; private static ThemeResourceKey checkBoxGlyphHoverBackgroundKey; private static ThemeResourceKey checkBoxGlyphPressedBackgroundKey; private static ThemeResourceKey checkBoxTextBackgroundKey; private static ThemeResourceKey checkBoxTextDisabledBackgroundKey; private static ThemeResourceKey checkBoxTextFocusedBackgroundKey; private static ThemeResourceKey checkBoxTextHoverBackgroundKey; private static ThemeResourceKey checkBoxTextPressedBackgroundKey; private static ThemeResourceKey comboBoxBackgroundBackgroundKey; private static ThemeResourceKey comboBoxBackgroundDisabledBackgroundKey; private static ThemeResourceKey comboBoxBackgroundFocusedBackgroundKey; private static ThemeResourceKey comboBoxBackgroundHoverBackgroundKey; private static ThemeResourceKey comboBoxBackgroundPressedBackgroundKey; private static ThemeResourceKey comboBoxBorderBackgroundKey; private static ThemeResourceKey comboBoxBorderDisabledBackgroundKey; private static ThemeResourceKey comboBoxBorderFocusedBackgroundKey; private static ThemeResourceKey comboBoxBorderHoverBackgroundKey; private static ThemeResourceKey comboBoxBorderPressedBackgroundKey; private static ThemeResourceKey comboBoxGlyphBackgroundBackgroundKey; private static ThemeResourceKey comboBoxGlyphBackgroundDisabledBackgroundKey; private static ThemeResourceKey comboBoxGlyphBackgroundFocusedBackgroundKey; private static ThemeResourceKey comboBoxGlyphBackgroundHoverBackgroundKey; private static ThemeResourceKey comboBoxGlyphBackgroundKey; private static ThemeResourceKey comboBoxGlyphBackgroundPressedBackgroundKey; private static ThemeResourceKey comboBoxGlyphDisabledBackgroundKey; private static ThemeResourceKey comboBoxGlyphFocusedBackgroundKey; private static ThemeResourceKey comboBoxGlyphHoverBackgroundKey; private static ThemeResourceKey comboBoxGlyphPressedBackgroundKey; private static ThemeResourceKey comboBoxListBackgroundBackgroundKey; private static ThemeResourceKey comboBoxListBackgroundShadowBackgroundKey; private static ThemeResourceKey comboBoxListBorderBackgroundKey; private static ThemeResourceKey comboBoxListItemBackgroundHoverBackgroundKey; private static ThemeResourceKey comboBoxListItemBorderHoverBackgroundKey; private static ThemeResourceKey comboBoxListItemTextBackgroundKey; private static ThemeResourceKey comboBoxListItemTextHoverBackgroundKey; private static ThemeResourceKey comboBoxSelectionBackgroundKey; private static ThemeResourceKey comboBoxSeparatorBackgroundKey; private static ThemeResourceKey comboBoxSeparatorDisabledBackgroundKey; private static ThemeResourceKey comboBoxSeparatorFocusedBackgroundKey; private static ThemeResourceKey comboBoxSeparatorHoverBackgroundKey; private static ThemeResourceKey comboBoxSeparatorPressedBackgroundKey; private static ThemeResourceKey comboBoxTextBackgroundKey; private static ThemeResourceKey comboBoxTextDisabledBackgroundKey; private static ThemeResourceKey comboBoxTextFocusedBackgroundKey; private static ThemeResourceKey comboBoxTextHoverBackgroundKey; private static ThemeResourceKey comboBoxTextInputSelectionBackgroundKey; private static ThemeResourceKey comboBoxTextPressedBackgroundKey; private static ThemeResourceKey focusVisualBackgroundKey; private static ThemeResourceKey focusVisualForegroundKey; private static ThemeResourceKey innerTabActiveBackgroundBackgroundKey; private static ThemeResourceKey innerTabActiveBorderBackgroundKey; private static ThemeResourceKey innerTabActiveTextBackgroundKey; private static ThemeResourceKey innerTabInactiveBackgroundBackgroundKey; private static ThemeResourceKey innerTabInactiveBorderBackgroundKey; private static ThemeResourceKey innerTabInactiveHoverBackgroundBackgroundKey; private static ThemeResourceKey innerTabInactiveHoverBorderBackgroundKey; private static ThemeResourceKey innerTabInactiveHoverTextBackgroundKey; private static ThemeResourceKey innerTabInactiveTextBackgroundKey; private static ThemeResourceKey textBoxBackgroundBackgroundKey; private static ThemeResourceKey textBoxBackgroundDisabledBackgroundKey; private static ThemeResourceKey textBoxBackgroundFocusedBackgroundKey; private static ThemeResourceKey textBoxBorderBackgroundKey; private static ThemeResourceKey textBoxBorderDisabledBackgroundKey; private static ThemeResourceKey textBoxBorderFocusedBackgroundKey; private static ThemeResourceKey textBoxTextBackgroundKey; private static ThemeResourceKey textBoxTextDisabledBackgroundKey; private static ThemeResourceKey textBoxTextFocusedBackgroundKey; public static ThemeResourceKey CheckBoxBackgroundDisabledBackgroundKey => checkBoxBackgroundDisabledBackgroundKey ?? (checkBoxBackgroundDisabledBackgroundKey = new ThemeResourceKey( Category, "CheckBoxBackgroundDisabled", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey TextBoxBackgroundDisabledBackgroundKey => textBoxBackgroundDisabledBackgroundKey ?? (textBoxBackgroundDisabledBackgroundKey = new ThemeResourceKey( Category, "TextBoxBackgroundDisabled", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey CheckBoxGlyphBackgroundKey => checkBoxGlyphBackgroundKey ?? (checkBoxGlyphBackgroundKey = new ThemeResourceKey( Category, "CheckBoxGlyph", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey CheckBoxGlyphPressedBackgroundKey => checkBoxGlyphPressedBackgroundKey ?? (checkBoxGlyphPressedBackgroundKey = new ThemeResourceKey( Category, "CheckBoxGlyphPressed", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxListItemTextBackgroundKey => comboBoxListItemTextBackgroundKey ?? (comboBoxListItemTextBackgroundKey = new ThemeResourceKey( Category, "ComboBoxListItemText", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ButtonBorderHoverBackgroundKey => buttonBorderHoverBackgroundKey ?? (buttonBorderHoverBackgroundKey = new ThemeResourceKey( Category, "ButtonBorderHover", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxBorderHoverBackgroundKey => comboBoxBorderHoverBackgroundKey ?? (comboBoxBorderHoverBackgroundKey = new ThemeResourceKey( Category, "ComboBoxBorderHover", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ButtonPressedBackgroundKey => buttonPressedBackgroundKey ?? (buttonPressedBackgroundKey = new ThemeResourceKey( Category, "ButtonPressed", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ButtonPressedTextKey => buttonPressedForegroundKey ?? (buttonPressedForegroundKey = new ThemeResourceKey( Category, "ButtonPressed", ThemeResourceKeyType.ForegroundBrush)); public static ThemeResourceKey CheckBoxBorderHoverBackgroundKey => checkBoxBorderHoverBackgroundKey ?? (checkBoxBorderHoverBackgroundKey = new ThemeResourceKey( Category, "CheckBoxBorderHover", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey TextBoxBorderDisabledBackgroundKey => textBoxBorderDisabledBackgroundKey ?? (textBoxBorderDisabledBackgroundKey = new ThemeResourceKey( Category, "TextBoxBorderDisabled", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxTextHoverBackgroundKey => comboBoxTextHoverBackgroundKey ?? (comboBoxTextHoverBackgroundKey = new ThemeResourceKey( Category, "ComboBoxTextHover", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxGlyphHoverBackgroundKey => comboBoxGlyphHoverBackgroundKey ?? (comboBoxGlyphHoverBackgroundKey = new ThemeResourceKey( Category, "ComboBoxGlyphHover", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxTextInputSelectionBackgroundKey => comboBoxTextInputSelectionBackgroundKey ?? (comboBoxTextInputSelectionBackgroundKey = new ThemeResourceKey( Category, "ComboBoxTextInputSelection", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxSeparatorHoverBackgroundKey => comboBoxSeparatorHoverBackgroundKey ?? (comboBoxSeparatorHoverBackgroundKey = new ThemeResourceKey( Category, "ComboBoxSeparatorHover", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ButtonBorderFocusedBackgroundKey => buttonBorderFocusedBackgroundKey ?? (buttonBorderFocusedBackgroundKey = new ThemeResourceKey( Category, "ButtonBorderFocused", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey InnerTabInactiveHoverTextBackgroundKey => innerTabInactiveHoverTextBackgroundKey ?? (innerTabInactiveHoverTextBackgroundKey = new ThemeResourceKey( Category, "InnerTabInactiveHoverText", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxSeparatorFocusedBackgroundKey => comboBoxSeparatorFocusedBackgroundKey ?? (comboBoxSeparatorFocusedBackgroundKey = new ThemeResourceKey( Category, "ComboBoxSeparatorFocused", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxBorderPressedBackgroundKey => comboBoxBorderPressedBackgroundKey ?? (comboBoxBorderPressedBackgroundKey = new ThemeResourceKey( Category, "ComboBoxBorderPressed", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxSeparatorBackgroundKey => comboBoxSeparatorBackgroundKey ?? (comboBoxSeparatorBackgroundKey = new ThemeResourceKey( Category, "ComboBoxSeparator", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxSelectionBackgroundKey => comboBoxSelectionBackgroundKey ?? (comboBoxSelectionBackgroundKey = new ThemeResourceKey( Category, "ComboBoxSelection", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxBorderDisabledBackgroundKey => comboBoxBorderDisabledBackgroundKey ?? (comboBoxBorderDisabledBackgroundKey = new ThemeResourceKey( Category, "ComboBoxBorderDisabled", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey InnerTabInactiveTextBackgroundKey => innerTabInactiveTextBackgroundKey ?? (innerTabInactiveTextBackgroundKey = new ThemeResourceKey( Category, "InnerTabInactiveText", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ButtonBorderPressedBackgroundKey => buttonBorderPressedBackgroundKey ?? (buttonBorderPressedBackgroundKey = new ThemeResourceKey( Category, "ButtonBorderPressed", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxBackgroundFocusedBackgroundKey => comboBoxBackgroundFocusedBackgroundKey ?? (comboBoxBackgroundFocusedBackgroundKey = new ThemeResourceKey( Category, "ComboBoxBackgroundFocused", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ButtonTextKey => buttonForegroundKey ?? (buttonForegroundKey = new ThemeResourceKey( Category, "Button", ThemeResourceKeyType.ForegroundBrush)); public static ThemeResourceKey ButtonBackgroundKey => buttonBackgroundKey ?? (buttonBackgroundKey = new ThemeResourceKey( Category, "Button", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey TextBoxBorderFocusedBackgroundKey => textBoxBorderFocusedBackgroundKey ?? (textBoxBorderFocusedBackgroundKey = new ThemeResourceKey( Category, "TextBoxBorderFocused", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxListItemBorderHoverBackgroundKey => comboBoxListItemBorderHoverBackgroundKey ?? (comboBoxListItemBorderHoverBackgroundKey = new ThemeResourceKey( Category, "ComboBoxListItemBorderHover", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey TextBoxBackgroundBackgroundKey => textBoxBackgroundBackgroundKey ?? (textBoxBackgroundBackgroundKey = new ThemeResourceKey( Category, "TextBoxBackground", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxGlyphBackgroundFocusedBackgroundKey => comboBoxGlyphBackgroundFocusedBackgroundKey ?? (comboBoxGlyphBackgroundFocusedBackgroundKey = new ThemeResourceKey( Category, "ComboBoxGlyphBackgroundFocused", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey CheckBoxBorderBackgroundKey => checkBoxBorderBackgroundKey ?? (checkBoxBorderBackgroundKey = new ThemeResourceKey( Category, "CheckBoxBorder", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey CheckBoxBackgroundHoverBackgroundKey => checkBoxBackgroundHoverBackgroundKey ?? (checkBoxBackgroundHoverBackgroundKey = new ThemeResourceKey( Category, "CheckBoxBackgroundHover", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxBackgroundDisabledBackgroundKey => comboBoxBackgroundDisabledBackgroundKey ?? (comboBoxBackgroundDisabledBackgroundKey = new ThemeResourceKey( Category, "ComboBoxBackgroundDisabled", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxGlyphBackgroundHoverBackgroundKey => comboBoxGlyphBackgroundHoverBackgroundKey ?? (comboBoxGlyphBackgroundHoverBackgroundKey = new ThemeResourceKey( Category, "ComboBoxGlyphBackgroundHover", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxTextPressedBackgroundKey => comboBoxTextPressedBackgroundKey ?? (comboBoxTextPressedBackgroundKey = new ThemeResourceKey( Category, "ComboBoxTextPressed", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey CheckBoxBackgroundBackgroundKey => checkBoxBackgroundBackgroundKey ?? (checkBoxBackgroundBackgroundKey = new ThemeResourceKey( Category, "CheckBoxBackground", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey InnerTabActiveTextBackgroundKey => innerTabActiveTextBackgroundKey ?? (innerTabActiveTextBackgroundKey = new ThemeResourceKey( Category, "InnerTabActiveText", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey CheckBoxBorderDisabledBackgroundKey => checkBoxBorderDisabledBackgroundKey ?? (checkBoxBorderDisabledBackgroundKey = new ThemeResourceKey( Category, "CheckBoxBorderDisabled", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ButtonDisabledBackgroundKey => buttonDisabledBackgroundKey ?? (buttonDisabledBackgroundKey = new ThemeResourceKey( Category, "ButtonDisabled", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ButtonDisabledTextKey => buttonDisabledForegroundKey ?? (buttonDisabledForegroundKey = new ThemeResourceKey( Category, "ButtonDisabled", ThemeResourceKeyType.ForegroundBrush)); public static ThemeResourceKey InnerTabActiveBorderBackgroundKey => innerTabActiveBorderBackgroundKey ?? (innerTabActiveBorderBackgroundKey = new ThemeResourceKey( Category, "InnerTabActiveBorder", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey FocusVisualForegroundKey => focusVisualForegroundKey ?? (focusVisualForegroundKey = new ThemeResourceKey( Category, "FocusVisual", ThemeResourceKeyType.ForegroundBrush)); public static ThemeResourceKey ComboBoxBorderBackgroundKey => comboBoxBorderBackgroundKey ?? (comboBoxBorderBackgroundKey = new ThemeResourceKey( Category, "ComboBoxBorder", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxTextBackgroundKey => comboBoxTextBackgroundKey ?? (comboBoxTextBackgroundKey = new ThemeResourceKey( Category, "ComboBoxText", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey InnerTabInactiveBackgroundBackgroundKey => innerTabInactiveBackgroundBackgroundKey ?? (innerTabInactiveBackgroundBackgroundKey = new ThemeResourceKey( Category, "InnerTabInactiveBackground", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxTextFocusedBackgroundKey => comboBoxTextFocusedBackgroundKey ?? (comboBoxTextFocusedBackgroundKey = new ThemeResourceKey( Category, "ComboBoxTextFocused", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey TextBoxTextBackgroundKey => textBoxTextBackgroundKey ?? (textBoxTextBackgroundKey = new ThemeResourceKey( Category, "TextBoxText", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey CheckBoxGlyphFocusedBackgroundKey => checkBoxGlyphFocusedBackgroundKey ?? (checkBoxGlyphFocusedBackgroundKey = new ThemeResourceKey( Category, "CheckBoxGlyphFocused", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxTextDisabledBackgroundKey => comboBoxTextDisabledBackgroundKey ?? (comboBoxTextDisabledBackgroundKey = new ThemeResourceKey( Category, "ComboBoxTextDisabled", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxListItemTextHoverBackgroundKey => comboBoxListItemTextHoverBackgroundKey ?? (comboBoxListItemTextHoverBackgroundKey = new ThemeResourceKey( Category, "ComboBoxListItemTextHover", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ButtonHoverTextKey => buttonHoverForegroundKey ?? (buttonHoverForegroundKey = new ThemeResourceKey( Category, "ButtonHover", ThemeResourceKeyType.ForegroundBrush)); public static ThemeResourceKey ButtonHoverBackgroundKey => buttonHoverBackgroundKey ?? (buttonHoverBackgroundKey = new ThemeResourceKey( Category, "ButtonHover", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxGlyphPressedBackgroundKey => comboBoxGlyphPressedBackgroundKey ?? (comboBoxGlyphPressedBackgroundKey = new ThemeResourceKey( Category, "ComboBoxGlyphPressed", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxListBackgroundShadowBackgroundKey => comboBoxListBackgroundShadowBackgroundKey ?? (comboBoxListBackgroundShadowBackgroundKey = new ThemeResourceKey( Category, "ComboBoxListBackgroundShadow", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxSeparatorPressedBackgroundKey => comboBoxSeparatorPressedBackgroundKey ?? (comboBoxSeparatorPressedBackgroundKey = new ThemeResourceKey( Category, "ComboBoxSeparatorPressed", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxBackgroundPressedBackgroundKey => comboBoxBackgroundPressedBackgroundKey ?? (comboBoxBackgroundPressedBackgroundKey = new ThemeResourceKey( Category, "ComboBoxBackgroundPressed", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey CheckBoxTextPressedBackgroundKey => checkBoxTextPressedBackgroundKey ?? (checkBoxTextPressedBackgroundKey = new ThemeResourceKey( Category, "CheckBoxTextPressed", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey TextBoxBackgroundFocusedBackgroundKey => textBoxBackgroundFocusedBackgroundKey ?? (textBoxBackgroundFocusedBackgroundKey = new ThemeResourceKey( Category, "TextBoxBackgroundFocused", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey CheckBoxBorderPressedBackgroundKey => checkBoxBorderPressedBackgroundKey ?? (checkBoxBorderPressedBackgroundKey = new ThemeResourceKey( Category, "CheckBoxBorderPressed", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey TextBoxTextFocusedBackgroundKey => textBoxTextFocusedBackgroundKey ?? (textBoxTextFocusedBackgroundKey = new ThemeResourceKey( Category, "TextBoxTextFocused", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey InnerTabInactiveHoverBorderBackgroundKey => innerTabInactiveHoverBorderBackgroundKey ?? (innerTabInactiveHoverBorderBackgroundKey = new ThemeResourceKey( Category, "InnerTabInactiveHoverBorder", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey CheckBoxGlyphHoverBackgroundKey => checkBoxGlyphHoverBackgroundKey ?? (checkBoxGlyphHoverBackgroundKey = new ThemeResourceKey( Category, "CheckBoxGlyphHover", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey CheckBoxBackgroundFocusedBackgroundKey => checkBoxBackgroundFocusedBackgroundKey ?? (checkBoxBackgroundFocusedBackgroundKey = new ThemeResourceKey( Category, "CheckBoxBackgroundFocused", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxGlyphFocusedBackgroundKey => comboBoxGlyphFocusedBackgroundKey ?? (comboBoxGlyphFocusedBackgroundKey = new ThemeResourceKey( Category, "ComboBoxGlyphFocused", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ButtonDefaultTextKey => buttonDefaultForegroundKey ?? (buttonDefaultForegroundKey = new ThemeResourceKey( Category, "ButtonDefault", ThemeResourceKeyType.ForegroundBrush)); public static ThemeResourceKey ButtonDefaultBackgroundKey => buttonDefaultBackgroundKey ?? (buttonDefaultBackgroundKey = new ThemeResourceKey( Category, "ButtonDefault", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey TextBoxBorderBackgroundKey => textBoxBorderBackgroundKey ?? (textBoxBorderBackgroundKey = new ThemeResourceKey( Category, "TextBoxBorder", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxBackgroundBackgroundKey => comboBoxBackgroundBackgroundKey ?? (comboBoxBackgroundBackgroundKey = new ThemeResourceKey( Category, "ComboBoxBackground", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey CheckBoxBackgroundPressedBackgroundKey => checkBoxBackgroundPressedBackgroundKey ?? (checkBoxBackgroundPressedBackgroundKey = new ThemeResourceKey( Category, "CheckBoxBackgroundPressed", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxGlyphBackgroundKey => comboBoxGlyphBackgroundKey ?? (comboBoxGlyphBackgroundKey = new ThemeResourceKey( Category, "ComboBoxGlyph", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey CheckBoxTextBackgroundKey => checkBoxTextBackgroundKey ?? (checkBoxTextBackgroundKey = new ThemeResourceKey( Category, "CheckBoxText", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxListBackgroundBackgroundKey => comboBoxListBackgroundBackgroundKey ?? (comboBoxListBackgroundBackgroundKey = new ThemeResourceKey( Category, "ComboBoxListBackground", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxListBorderBackgroundKey => comboBoxListBorderBackgroundKey ?? (comboBoxListBorderBackgroundKey = new ThemeResourceKey( Category, "ComboBoxListBorder", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey CheckBoxBorderFocusedBackgroundKey => checkBoxBorderFocusedBackgroundKey ?? (checkBoxBorderFocusedBackgroundKey = new ThemeResourceKey( Category, "CheckBoxBorderFocused", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ButtonFocusedBackgroundKey => buttonFocusedBackgroundKey ?? (buttonFocusedBackgroundKey = new ThemeResourceKey( Category, "ButtonFocused", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ButtonFocusedTextKey => buttonFocusedForegroundKey ?? (buttonFocusedForegroundKey = new ThemeResourceKey( Category, "ButtonFocused", ThemeResourceKeyType.ForegroundBrush)); public static ThemeResourceKey FocusVisualBackgroundKey => focusVisualBackgroundKey ?? (focusVisualBackgroundKey = new ThemeResourceKey( Category, "FocusVisual", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey InnerTabInactiveBorderBackgroundKey => innerTabInactiveBorderBackgroundKey ?? (innerTabInactiveBorderBackgroundKey = new ThemeResourceKey( Category, "InnerTabInactiveBorder", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey CheckBoxTextDisabledBackgroundKey => checkBoxTextDisabledBackgroundKey ?? (checkBoxTextDisabledBackgroundKey = new ThemeResourceKey( Category, "CheckBoxTextDisabled", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey CheckBoxTextHoverBackgroundKey => checkBoxTextHoverBackgroundKey ?? (checkBoxTextHoverBackgroundKey = new ThemeResourceKey( Category, "CheckBoxTextHover", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey InnerTabInactiveHoverBackgroundBackgroundKey => innerTabInactiveHoverBackgroundBackgroundKey ?? (innerTabInactiveHoverBackgroundBackgroundKey = new ThemeResourceKey( Category, "InnerTabInactiveHoverBackground", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey TextBoxTextDisabledBackgroundKey => textBoxTextDisabledBackgroundKey ?? (textBoxTextDisabledBackgroundKey = new ThemeResourceKey( Category, "TextBoxTextDisabled", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ButtonBorderDisabledBackgroundKey => buttonBorderDisabledBackgroundKey ?? (buttonBorderDisabledBackgroundKey = new ThemeResourceKey( Category, "ButtonBorderDisabled", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxBackgroundHoverBackgroundKey => comboBoxBackgroundHoverBackgroundKey ?? (comboBoxBackgroundHoverBackgroundKey = new ThemeResourceKey( Category, "ComboBoxBackgroundHover", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxGlyphBackgroundPressedBackgroundKey => comboBoxGlyphBackgroundPressedBackgroundKey ?? (comboBoxGlyphBackgroundPressedBackgroundKey = new ThemeResourceKey( Category, "ComboBoxGlyphBackgroundPressed", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ButtonBorderBackgroundKey => buttonBorderBackgroundKey ?? (buttonBorderBackgroundKey = new ThemeResourceKey( Category, "ButtonBorder", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey CheckBoxGlyphDisabledBackgroundKey => checkBoxGlyphDisabledBackgroundKey ?? (checkBoxGlyphDisabledBackgroundKey = new ThemeResourceKey( Category, "CheckBoxGlyphDisabled", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxGlyphBackgroundDisabledBackgroundKey => comboBoxGlyphBackgroundDisabledBackgroundKey ?? (comboBoxGlyphBackgroundDisabledBackgroundKey = new ThemeResourceKey( Category, "ComboBoxGlyphBackgroundDisabled", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxGlyphBackgroundBackgroundKey => comboBoxGlyphBackgroundBackgroundKey ?? (comboBoxGlyphBackgroundBackgroundKey = new ThemeResourceKey( Category, "ComboBoxGlyphBackground", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxBorderFocusedBackgroundKey => comboBoxBorderFocusedBackgroundKey ?? (comboBoxBorderFocusedBackgroundKey = new ThemeResourceKey( Category, "ComboBoxBorderFocused", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxListItemBackgroundHoverBackgroundKey => comboBoxListItemBackgroundHoverBackgroundKey ?? (comboBoxListItemBackgroundHoverBackgroundKey = new ThemeResourceKey( Category, "ComboBoxListItemBackgroundHover", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ButtonBorderDefaultBackgroundKey => buttonBorderDefaultBackgroundKey ?? (buttonBorderDefaultBackgroundKey = new ThemeResourceKey( Category, "ButtonBorderDefault", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey InnerTabActiveBackgroundBackgroundKey => innerTabActiveBackgroundBackgroundKey ?? (innerTabActiveBackgroundBackgroundKey = new ThemeResourceKey( Category, "InnerTabActiveBackground", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxGlyphDisabledBackgroundKey => comboBoxGlyphDisabledBackgroundKey ?? (comboBoxGlyphDisabledBackgroundKey = new ThemeResourceKey( Category, "ComboBoxGlyphDisabled", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey CheckBoxTextFocusedBackgroundKey => checkBoxTextFocusedBackgroundKey ?? (checkBoxTextFocusedBackgroundKey = new ThemeResourceKey( Category, "CheckBoxTextFocused", ThemeResourceKeyType.BackgroundBrush)); public static ThemeResourceKey ComboBoxSeparatorDisabledBackgroundKey => comboBoxSeparatorDisabledBackgroundKey ?? (comboBoxSeparatorDisabledBackgroundKey = new ThemeResourceKey( Category, "ComboBoxSeparatorDisabled", ThemeResourceKeyType.BackgroundBrush)); } }
58.978188
100
0.746778
[ "MIT" ]
gix/event-trace-kit
src/EventTraceKit.VsExtension/CommonControlBrushes.cs
35,153
C#
using System; using System.Xml.Serialization; using System.Collections.Generic; namespace Aop.Api.Domain { /// <summary> /// Car Data Structure. /// </summary> [Serializable] public class Car : AopObject { /// <summary> /// 发动机号 /// </summary> [XmlElement("car_engine_no")] public string CarEngineNo { get; set; } /// <summary> /// 车架号 /// </summary> [XmlElement("car_frame_no")] public string CarFrameNo { get; set; } /// <summary> /// 品牌型号 /// </summary> [XmlElement("car_model_code")] public string CarModelCode { get; set; } /// <summary> /// 车牌号 /// </summary> [XmlElement("car_no")] public string CarNo { get; set; } /// <summary> /// 该车辆数据来源,1 来自 ISV,2来自保险师内部数据 /// </summary> [XmlElement("data_source")] public string DataSource { get; set; } /// <summary> /// 初次登记日期 /// </summary> [XmlElement("first_register_date")] public string FirstRegisterDate { get; set; } /// <summary> /// 是否新车 /// </summary> [XmlElement("is_new")] public string IsNew { get; set; } /// <summary> /// 天津地区行驶证地址 /// </summary> [XmlElement("license_address")] public string LicenseAddress { get; set; } /// <summary> /// 贷款车标识 /// </summary> [XmlElement("loan_flag")] public string LoanFlag { get; set; } /// <summary> /// 座位数 /// </summary> [XmlElement("seat_number")] public string SeatNumber { get; set; } /// <summary> /// 是否过户车 /// </summary> [XmlElement("transfer_car")] public string TransferCar { get; set; } /// <summary> /// 过户日期 /// </summary> [XmlElement("transfer_date")] public string TransferDate { get; set; } /// <summary> /// 精友代码和精友主体编码 /// </summary> [XmlElement("vehicle_info")] public VehicleInfo VehicleInfo { get; set; } /// <summary> /// 所有需要报价机构对应的精友码 /// </summary> [XmlArray("vehicle_info_list")] [XmlArrayItem("vehicle_info")] public List<VehicleInfo> VehicleInfoList { get; set; } /// <summary> /// 天津地区行驶证车辆类型 /// </summary> [XmlElement("vehicle_type")] public string VehicleType { get; set; } } }
25.4
63
0.47694
[ "Apache-2.0" ]
554393109/alipay-sdk-net-all
AlipaySDKNet.Standard/Domain/Car.cs
2,879
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using Xunit; namespace Enyim.Diagnostics { public class MessageFormatterTests { [Theory] [MemberData(nameof(DataForFormatMessageTemplate))] public void FormatMessageTemplate(string input, string expected) { Assert.Equal(expected, Enyim.Diagnostics.ConsoleLoggerFactory.FormatMessageTemplate(input)); } private static object[] Same(object arg) => new[] { arg, arg }; private static object[] R(string input, string expected) => new[] { input, expected }; public static IEnumerable<object[]> DataForFormatMessageTemplate { get { yield return Same("Hello World"); yield return Same("1234"); yield return Same("1234 1234"); yield return Same("{0}"); yield return Same("Hello {2} World"); yield return Same("Hello {2,1234} World"); yield return Same("Hello {2:yy-mm} World"); yield return Same("{0:yy-mm} Hello {2:yy-mm} World {3:abcd,1234} world"); yield return R("{Hello} {World}!", "<<{0}>> <<{1}>>!"); yield return R("{Hello:1234} {World,abcd}!", "<<{0:1234}>> <<{1,abcd}>>!"); yield return R("{Hello:1234} {1234} {World,abcd}!", "<<{0:1234}>> {1234} <<{1,abcd}>>!"); } } } } #region [ License information ] /* Copyright (c) Attila Kiskó, enyim.com 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. */ #endregion
29.59375
95
0.694826
[ "Apache-2.0" ]
EugeneKrapivin/Memcached2
tests/MemcachedTests/MessageFormatterTests.cs
1,897
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Commands.Storage.Common { using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Blob; using Microsoft.WindowsAzure.Storage.File; using System; using System.Globalization; using System.Net; using System.Threading.Tasks; internal static class Util { /// <summary> /// Size formats /// </summary> private static string[] sizeFormats = { Resources.HumanReadableSizeFormat_Bytes, Resources.HumanReadableSizeFormat_KiloBytes, Resources.HumanReadableSizeFormat_MegaBytes, Resources.HumanReadableSizeFormat_GigaBytes, Resources.HumanReadableSizeFormat_TeraBytes, Resources.HumanReadableSizeFormat_PetaBytes, Resources.HumanReadableSizeFormat_ExaBytes }; /// <summary> /// Translate a size in bytes to human readable form. /// </summary> /// <param name="size">Size in bytes.</param> /// <returns>Human readable form string.</returns> public static string BytesToHumanReadableSize(double size) { int order = 0; while (size >= 1024 && order + 1 < sizeFormats.Length) { ++order; size /= 1024; } return string.Format(sizeFormats[order], size); } public static CloudBlob GetBlobReferenceFromServer( CloudBlobContainer container, string blobName, AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null, DateTimeOffset? snapshotTime = null) { CloudBlob blob = container.GetBlobReference(blobName, snapshotTime); return GetBlobReferenceFromServer(blob, accessCondition, options, operationContext); } public static CloudBlob GetBlobReferenceFromServer(CloudBlobClient client, Uri blobUri) { CloudBlob blob = new CloudBlob(blobUri, client.Credentials); return GetBlobReferenceFromServer(blob); } private static CloudBlob GetBlobReferenceFromServer( CloudBlob blob, AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null, DateTimeOffset? snapshotTime = null) { try { Task.Run(() => blob.FetchAttributesAsync(accessCondition, options, operationContext)).Wait(); } catch (AggregateException e) when (e.InnerException is StorageException) { if (((StorageException)e.InnerException).RequestInformation == null || (((StorageException)e.InnerException).RequestInformation.HttpStatusCode != (int)HttpStatusCode.NotFound)) { throw e.InnerException; } return null; } catch (StorageException se) { if (se.RequestInformation == null || (se.RequestInformation.HttpStatusCode != (int)HttpStatusCode.NotFound)) { throw; } return null; } return GetCorrespondingTypeBlobReference(blob); } public static CloudBlob GetCorrespondingTypeBlobReference(CloudBlob blob) { CloudBlob targetBlob; switch (blob.Properties.BlobType) { case BlobType.BlockBlob: targetBlob = new CloudBlockBlob(blob.SnapshotQualifiedUri, blob.ServiceClient.Credentials); break; case BlobType.PageBlob: targetBlob = new CloudPageBlob(blob.SnapshotQualifiedUri, blob.ServiceClient.Credentials); break; case BlobType.AppendBlob: targetBlob = new CloudAppendBlob(blob.SnapshotQualifiedUri, blob.ServiceClient.Credentials); break; default: throw new InvalidOperationException(string.Format( CultureInfo.CurrentCulture, Resources.InvalidBlobType, blob.Properties.BlobType, blob.Name)); } try { Task.Run(() => targetBlob.FetchAttributesAsync()).Wait(); } catch (AggregateException e) when (e.InnerException is StorageException) { throw e.InnerException; } return targetBlob; } public static CloudBlob GetBlobReference(CloudBlobContainer container, string blobName, BlobType blobType) { switch (blobType) { case BlobType.BlockBlob: return container.GetBlockBlobReference(blobName); case BlobType.PageBlob: return container.GetPageBlobReference(blobName); case BlobType.AppendBlob: return container.GetAppendBlobReference(blobName); default: throw new ArgumentException(String.Format( CultureInfo.CurrentCulture, Resources.InvalidBlobType, blobType, blobName)); } } public static CloudBlob GetBlobReference(Uri blobUri, StorageCredentials storageCredentials, BlobType blobType) { switch (blobType) { case BlobType.BlockBlob: return new CloudBlockBlob(blobUri, storageCredentials); case BlobType.PageBlob: return new CloudPageBlob(blobUri, storageCredentials); case BlobType.AppendBlob: return new CloudAppendBlob(blobUri, storageCredentials); case BlobType.Unspecified: return new CloudBlob(blobUri, storageCredentials); default: throw new ArgumentException(String.Format( CultureInfo.CurrentCulture, Resources.InvalidBlobType, blobType, blobUri)); } } public static IPAddressOrRange SetupIPAddressOrRangeForSAS(string inputIPACL) { if (string.IsNullOrEmpty(inputIPACL)) return null; int separator = inputIPACL.IndexOf('-'); if (-1 == separator) { return new IPAddressOrRange(inputIPACL); } else { return new IPAddressOrRange(inputIPACL.Substring(0, separator), inputIPACL.Substring(separator + 1)); } } /// <summary> /// Used in DMlib ShouldOverwriteCallback, to convert object to blob/file/localpath, and return path /// </summary> /// <param name="instance">object instace</param> /// <returns>path of the object</returns> public static string ConvertToString(this object instance) { CloudBlob blob = instance as CloudBlob; if (null != blob) { return blob.SnapshotQualifiedUri.AbsoluteUri; } CloudFile file = instance as CloudFile; if (null != file) { return file.SnapshotQualifiedUri.AbsoluteUri; } return instance.ToString(); } } }
38.578947
126
0.546498
[ "MIT" ]
Acidburn0zzz/azure-powershell
src/ResourceManager/Storage/Commands.Storage/Common/Util.cs
8,571
C#
namespace LiveCharts.Drawing.Shapes { /// <summary> /// Defines a SVG-based path in the user interface. /// </summary> public interface ISvgPath : IShape { /// <summary> /// The SVG vector. /// </summary> string Svg { get; set; } } }
20.785714
55
0.52921
[ "MIT" ]
adospace/Live-Charts
src/LiveCharts.Core/Drawing/Shapes/ISvgPath.cs
293
C#
using System.ServiceProcess; namespace GodSharp.Mina { /// <summary> /// The account option of service. /// </summary> public class MinaAccountOption { /// <summary> /// Gets or sets the service account. /// </summary> /// <value> /// The service account. /// </value> public ServiceAccount ServiceAccount { get; set; } = ServiceAccount.LocalSystem; /// <summary> /// Gets or sets the password. /// </summary> /// <value> /// The password. /// </value> public string Password { get; set; } /// <summary> /// Gets or sets the username. /// </summary> /// <value> /// The username. /// </value> public string Username { get; set; } } }
23.714286
88
0.493976
[ "MIT" ]
godsharp/Mina
src/Mina/Options/MinaAccountOption.cs
832
C#
using System; using System.CodeDom; using System.CodeDom.Compiler; using System.ComponentModel; using System.IO; using System.Reflection; using System.Security.Permissions; namespace Microsoft.VJSharp { [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust"), PermissionSet(SecurityAction.InheritanceDemand, Name = "FullTrust")] public class VJSharpCodeProvider : CodeDomProvider { // Fields private VJSharpCodeGenerator generator = new VJSharpCodeGenerator(); // Methods [Obsolete("Callers should not use the ICodeCompiler interface and should instead use the methods directly on the CodeDomProvider class.")] public override ICodeCompiler CreateCompiler() { return this.generator; } [Obsolete("Callers should not use the ICodeGenerator interface and should instead use the methods directly on the CodeDomProvider class.")] public override ICodeGenerator CreateGenerator() { return this.generator; } public override void GenerateCodeFromMember(CodeTypeMember member, TextWriter writer, CodeGeneratorOptions options) { this.generator.GenerateCodeFromMember(member, writer, options); } public override TypeConverter GetConverter(Type type) { if (type == typeof(MemberAttributes)) { return VJSharpMemberAttributeConverter.Default; } if (type == typeof(TypeAttributes)) { return VJSharpTypeAttributeConverter.Default; } return base.GetConverter(type); } // Properties public override string FileExtension { get { return ".jsl"; } } } }
31.084746
147
0.637405
[ "Apache-2.0" ]
WesleyKhoiVo/asp_contestjudge
CHOJ2.0/VJSharpCodeProvider/VJSharpCodeProvider.cs
1,834
C#
// 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 Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { [Flags] internal enum ExpansionFlags { None = 0x0, IncludeBaseMembers = 0x1, IncludeResultsView = 0x2, All = IncludeBaseMembers | IncludeResultsView, } /// <summary> /// The immediate children of a DkmEvaluationResult (e.g. the /// elements within an array). Ideally, the children are generated /// on demand, and not cached in the Expansion. /// </summary> internal abstract class Expansion { /// <summary> /// Get the rows within the given range. 'index' is advanced /// to the end of the range, or if 'visitAll' is true, 'index' is /// advanced to the end of the expansion. /// </summary> internal abstract void GetRows( ResultProvider resultProvider, ArrayBuilder<EvalResultDataItem> rows, DkmInspectionContext inspectionContext, EvalResultDataItem parent, DkmClrValue value, int startIndex, int count, bool visitAll, ref int index); internal static bool InRange(int startIndex, int count, int index) { return (index >= startIndex) && (index < startIndex + count); } internal static void GetIntersection(int startIndex1, int count1, int startIndex2, int count2, out int startIndex3, out int count3) { startIndex3 = Math.Max(startIndex1, startIndex2); int endIndex3 = Math.Min(startIndex1 + count1, startIndex2 + count2); count3 = Math.Max(endIndex3 - startIndex3, 0); } } }
36.296296
160
0.638776
[ "Apache-2.0" ]
0x53A/roslyn
src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/Expansion.cs
1,960
C#
using System; namespace Jokk.Microservice.Log.Exceptions { public class EnvironmentException : Exception { public EnvironmentException() : base() {} public EnvironmentException(string message) : base(message) {} public EnvironmentException(string message, Exception inner) : base(message, inner) {} } }
26.846154
94
0.681948
[ "Apache-2.0" ]
jokk-itu/microservice_packages
Jokk.Microservice.Log/Exceptions/EnvironmentException.cs
349
C#
 namespace Simple.OData.Client { internal static class RestVerbs { // ReSharper disable InconsistentNaming public const string Get = "GET"; public const string Post = "POST"; public const string Put = "PUT"; public const string Patch = "PATCH"; public const string Delete = "DELETE"; // ReSharper restore InconsistentNaming } }
26.466667
47
0.627204
[ "MIT" ]
GGZORR/OdataSample
Simple.OData.Client.Core/Http/RestVerbs.cs
399
C#
using BenchmarkDotNet.Attributes; namespace FuncSharp.Benchmarks { [MemoryDiagnoser] public class OptionBenchmarks { private object Object { get; } = new object(); private IOption<string> NonEmptyOption { get; } = "non-empty".ToOption(); private IOption<string> EmptyOption { get; } = Option.Empty<string>(); [Benchmark] public void Creation() { Option.Create(42); Option.Create(42 as int?); Option.Create(null as int?); Option.Create(Object); Option.Create(null as object); } [Benchmark] public void Retrieval() { var a = NonEmptyOption.NonEmpty; var b = EmptyOption.NonEmpty; var c = NonEmptyOption.IsEmpty; var d = EmptyOption.IsEmpty; NonEmptyOption.Get(); NonEmptyOption.GetOrElse("else"); EmptyOption.GetOrElse("else"); NonEmptyOption.OrElse(_ => NonEmptyOption); EmptyOption.OrElse(_ => NonEmptyOption); } [Benchmark] public void Mapping() { NonEmptyOption.Map(o => "non-empty-mapped"); EmptyOption.Map(o => "empty-mapped"); NonEmptyOption.FlatMap(o => EmptyOption); NonEmptyOption.FlatMap(o => NonEmptyOption); EmptyOption.FlatMap(o => EmptyOption); EmptyOption.FlatMap(o => NonEmptyOption); } [Benchmark] public void Matching() { NonEmptyOption.Match(_ => true, _ => false); EmptyOption.Match(_ => true, _ => false); } [Benchmark] public void ToEnumerable() { NonEmptyOption.ToEnumerable(); EmptyOption.ToEnumerable(); } } }
27.757576
81
0.544214
[ "MIT" ]
KaliCZ/FuncSharp
src/FuncSharp.Benchmarks/Option/OptionBenchmarks.cs
1,832
C#
/* * Classifications API * * The Classifications API gives access to various Industry Classifications for a given list of securities. Beginning first with GICS Direct, the service will then expand to offering NAICS, SIC, RBICS, and more. * * The version of the OpenAPI document: 1.0.1 * Contact: api@factset.com * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; namespace FactSet.SDK.Classifications.Client { /// <summary> /// A delegate to ExceptionFactory method /// </summary> /// <param name="methodName">Method name</param> /// <param name="response">Response</param> /// <returns>Exceptions</returns> public delegate Exception ExceptionFactory(string methodName, IApiResponse response); }
32.208333
213
0.723157
[ "Apache-2.0" ]
factset/enterprise-sdk
code/dotnet/Classifications/v1/src/FactSet.SDK.Classifications/Client/ExceptionFactory.cs
773
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebApplication1.Models { public class Login1 { string username; string password; public string USERNAME { get { return username; } set { username = value; } } public string PASSWORD { get { return password; } set { password = value; } } } }
14.318182
33
0.396825
[ "MIT" ]
umairakhtar/mailbox
WebApplication1/Models/Login1.cs
632
C#
using FirstApplication; using NUnit.Framework; namespace UnitTestsExample { public class Tests { private ExampleClass example; [SetUp] public void Setup() { example = new ExampleClass(2, 3.14f); } [Test] public void Test1() { Assert.AreEqual(6.28f, example.Calculate(), 0.0000001d); } [Test] public void Test2() { Assert.AreEqual(2, example.firstField); } } }
18.392857
68
0.518447
[ "Apache-2.0" ]
ShaderInvader/TPUM-2021
ExampleSolution/UnitTestsExample/UnitTest1.cs
515
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright company="Microsoft"> // Copyright (c) 2013 Microsoft Corporation // </copyright> // -------------------------------------------------------------------------------------------------------------------- using Microsoft.Research.DataOnboarding.FileService.Interface; using Microsoft.Research.DataOnboarding.FileService.Models; using Microsoft.Research.DataOnboarding.Utilities; using Microsoft.Research.DataOnboarding.Utilities.Extensions; using Microsoft.WindowsAzure; using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using Microsoft.WindowsAzure.Storage.Blob; using Microsoft.WindowsAzure.Storage; using System.Configuration; namespace Microsoft.Research.DataOnboarding { /// <summary> /// Class representing the Blob Data Repository having methods for adding/retrieving files from /// Azure blob storage. /// </summary> public class BlobDataRepository : IBlobDataRepository { /// <summary> /// lazy client variable. /// </summary> private static Lazy<CloudBlobClient> lazyClient; /// <summary> /// Storage account variable. /// </summary> private CloudStorageAccount storageAccount; /// <summary> /// Initializes a new instance of the <see cref="BlobDataRepository"/> class. /// </summary> [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Code does not grant its callers access to operations or resources that can be used in a destructive manner.")] public BlobDataRepository() { if (!CloudStorageAccount.TryParse(ConfigReader<string>.GetSetting(Constants.StorageSettingName, string.Empty), out storageAccount)) { throw new ArgumentException("Storage account details are either invalid or cannot be found. Check the configuration files.", Constants.StorageSettingName); } lazyClient = new Lazy<CloudBlobClient>(() => (this.storageAccount.CreateCloudBlobClient())); } /// <summary> /// Gets the container URL. /// </summary> public static Uri ContainerUrl { get { return new Uri(string.Join(Constants.PathSeparator, new string[] { BlobClient.BaseUri.AbsolutePath, Constants.ContainerName })); } } /// <summary> /// Gets the CloudBlobClient instance from lazy client. /// </summary> private static CloudBlobClient BlobClient { get { CloudBlobClient blobclient = lazyClient.Value; blobclient.RetryPolicy = Constants.DefaultRetryPolicy; return blobclient; } } /// <summary> /// Method to get the url for the specified blob. /// </summary> /// <param name="blobId">Blob id.</param> /// <returns>URL of the specific blob.</returns> [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0")] public string GetBlobURL(string blobId) { Check.IsNotEmptyOrWhiteSpace(blobId, "blobId"); CloudBlobContainer container = GetContainer(Constants.ContainerName); string blobUrl = container.Uri.ToString(); return string.Format(CultureInfo.InvariantCulture, "{0}/{1}", blobUrl, blobId.ToUpperInvariant()); } /// <summary> /// Gets the blob content from azure as a stream. /// </summary> /// <param name="blobName"> /// Name of the blob. /// </param> /// <returns> /// The blob details. /// </returns> public DataDetail GetBlobContent(string blobName) { if (string.IsNullOrWhiteSpace(blobName)) { throw new ArgumentNullException("blobName"); } return GetBlob(blobName, Constants.ContainerName); } /// <summary> /// Uploads a file to azure as a blob. /// </summary> /// <param name="details"> /// Details of the file which has to be uploaded to azure. /// </param> /// <returns> /// True if the file is uploaded successfully; otherwise false. /// </returns> public bool UploadFile(DataDetail details) { details.CheckNotNull(); return UploadBlobContent(details, Constants.ContainerName); } /// <summary> /// Deletes a file from azure. /// </summary> /// <param name="blobId">Azure file id.</param> /// <returns>True if the file is deleted successfully; otherwise false.</returns> public bool DeleteFile(string blobId) { return DeleteBlob(blobId, Constants.ContainerName); } /// <summary> /// Checks a file in azure. /// </summary> /// <param name="details"> /// Details of the file which has to be checked. /// </param> /// <returns> /// True if the file is found successfully; otherwise false. /// </returns> public bool CheckIfExists(DataDetail details) { details.CheckNotNull(); return ExistsBlobContent(details, Constants.ContainerName); } /// <summary> /// Gets the content from azure as a stream. /// </summary> /// <param name="blobName"> /// Name of the blob. /// </param> /// <param name="outputStream"> /// The content is exposed as output stream. /// </param> /// <param name="container"> /// Container where we could find the blob. /// </param> /// <returns> /// The blob properties. /// </returns> private static BlobProperties GetContent(string blobName, Stream outputStream, CloudBlobContainer container) { new { blobName, outputStream, container }.CheckNotNull(); var blob = container.GetBlobReferenceFromServer(blobName.ToUpperInvariant()); blob.DownloadToStream(outputStream, null, new BlobRequestOptions() { ServerTimeout = TimeSpan.FromMinutes(30) }); return blob.Properties; } /// <summary> /// Used to retrieve the container reference identified by the container name. /// </summary> /// <param name="containerName"> /// Name of the container. /// </param> /// <returns> /// Container instance. /// </returns> private static CloudBlobContainer GetContainer(string containerName) { var blobContainer = BlobClient.GetContainerReference(containerName); return blobContainer; } /// <summary> /// Gets the content of the blob from specified container. /// </summary> /// <param name="blobName"> /// Name of the blob. /// </param> /// <param name="containerName"> /// name of the container. /// </param> /// <returns> /// The blob details. /// </returns> private static DataDetail GetBlob(string blobName, string containerName) { new { blobName, containerName }.CheckNotNull(); using (Stream outputStream = new MemoryStream()) { CloudBlobContainer container = GetContainer(containerName); GetContent(blobName, outputStream, container); DataDetail dataDetail = new DataDetail() { DataStream = outputStream.GetBytes() }; return dataDetail; } } /// <summary> /// Checks if the blob content is present in azure or not. /// </summary> /// <param name="details"> /// Details of the blob. /// </param> /// <param name="containerName"> /// Name of the container. /// </param> /// <returns> /// True, if the blob is successfully found to azure;otherwise false. /// </returns> private static bool ExistsBlobContent(DataDetail details, string containerName) { var returnStatus = false; new { details, containerName }.CheckNotNull(); CloudBlobContainer container = GetContainer(containerName); // TODO: Check if the input file type and then use either block blob or page blob. // For plate file we need to upload the file as page blob. var blob = container.GetBlobReferenceFromServer(details.FileDetail.BlobId.ToUpperInvariant()); blob.FetchAttributes(); returnStatus = true; return returnStatus; } /// <summary> /// Deletes the specified file pointed by the blob. /// </summary> /// <param name="details"> /// Details of the blob. /// </param> /// <param name="containerName"> /// Name of the container. /// </param> private static bool DeleteBlob(string blobId, string containerName) { var deleteStatus = false; Check.IsNotEmptyOrWhiteSpace(blobId, "blobId"); Check.IsNotEmptyOrWhiteSpace(containerName, "containerName"); try { CloudBlobContainer container = GetContainer(containerName); container.GetBlobReferenceFromServer(blobId.ToUpperInvariant()).Delete(); deleteStatus = true; } catch (InvalidOperationException) { deleteStatus = false; throw; } catch (StorageException ex) { if (ex.RequestInformation.ExtendedErrorInformation.ErrorCode == "BlobNotFound") { deleteStatus = true; } else { deleteStatus = false; throw; } } return deleteStatus; } /// <summary> /// Upload the blob content to azure. /// </summary> /// <param name="details"> /// Details of the blob. /// </param> /// <param name="containerName"> /// Name of the container. /// </param> /// <returns> /// True, if the blob is successfully uploaded to azure;otherwise false. /// </returns> private static bool UploadBlobContent(DataDetail details, string containerName) { var uploadStatus = false; try { new { details, containerName }.CheckNotNull(); CloudBlobContainer container = GetContainer(containerName); using (Stream filestream = new MemoryStream(details.DataStream)) { // Seek to start. filestream.Position = 0; // TODO: Check if the input file type and then use either block blob or page blob. // For plate file we need to upload the file as page blob. var blob = container.GetBlockBlobReference(details.FileDetail.BlobId.ToUpperInvariant()); blob.Properties.ContentType = details.FileDetail.MimeType; blob.UploadFromStream(filestream, null, new BlobRequestOptions() { ServerTimeout = TimeSpan.FromMinutes(30) }); } uploadStatus = true; } catch (InvalidOperationException) { uploadStatus = false; throw; } return uploadStatus; } /// <summary> /// /// </summary> /// <param name="blobId"></param> /// <returns></returns> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] public Stream GetBlob(string blobId) { new { blobId }.CheckNotNull(); Stream outputStream = null; outputStream = new MemoryStream(); CloudBlobContainer container = GetContainer(Constants.ContainerName); GetContent(blobId, outputStream, container); return outputStream; } } }
36.943182
229
0.538296
[ "MIT" ]
CDLUC3/dataup2
Services/FileService/BlobDataRepository.cs
13,006
C#
using System.Collections.Generic; using Vulkan; using static Vulkan.VulkanNative; using static Veldrid.Vk.VulkanUtil; namespace Veldrid.Vk { internal unsafe class VkResourceSet : ResourceSet { private readonly VkGraphicsDevice _gd; private readonly DescriptorResourceCounts _descriptorCounts; private readonly DescriptorAllocationToken _descriptorAllocationToken; private readonly List<ResourceRefCount> _refCounts = new List<ResourceRefCount>(); private bool _destroyed; private string _name; public VkDescriptorSet DescriptorSet => _descriptorAllocationToken.Set; private readonly List<VkTexture> _sampledTextures = new List<VkTexture>(); public IReadOnlyList<VkTexture> SampledTextures => _sampledTextures; private readonly List<VkTexture> _storageImages = new List<VkTexture>(); public IReadOnlyList<VkTexture> StorageTextures => _storageImages; public ResourceRefCount RefCount { get; } public IReadOnlyList<ResourceRefCount> RefCounts => _refCounts; public VkResourceSet(VkGraphicsDevice gd, ref ResourceSetDescription description) : base(ref description) { _gd = gd; RefCount = new ResourceRefCount(DisposeCore); VkResourceLayout vkLayout = Util.AssertSubtype<ResourceLayout, VkResourceLayout>(description.Layout); VkDescriptorSetLayout dsl = vkLayout.DescriptorSetLayout; _descriptorCounts = vkLayout.DescriptorResourceCounts; _descriptorAllocationToken = _gd.DescriptorPoolManager.Allocate(_descriptorCounts, dsl); BindableResource[] boundResources = description.BoundResources; uint descriptorWriteCount = (uint)boundResources.Length; VkWriteDescriptorSet* descriptorWrites = stackalloc VkWriteDescriptorSet[(int)descriptorWriteCount]; VkDescriptorBufferInfo* bufferInfos = stackalloc VkDescriptorBufferInfo[(int)descriptorWriteCount]; VkDescriptorImageInfo* imageInfos = stackalloc VkDescriptorImageInfo[(int)descriptorWriteCount]; for (int i = 0; i < descriptorWriteCount; i++) { VkDescriptorType type = vkLayout.DescriptorTypes[i]; descriptorWrites[i].sType = VkStructureType.WriteDescriptorSet; descriptorWrites[i].descriptorCount = 1; descriptorWrites[i].descriptorType = type; descriptorWrites[i].dstBinding = (uint)i; descriptorWrites[i].dstSet = _descriptorAllocationToken.Set; if (type == VkDescriptorType.UniformBuffer || type == VkDescriptorType.UniformBufferDynamic || type == VkDescriptorType.StorageBuffer || type == VkDescriptorType.StorageBufferDynamic) { DeviceBufferRange range = Util.GetBufferRange(boundResources[i], 0); VkBuffer rangedVkBuffer = Util.AssertSubtype<DeviceBuffer, VkBuffer>(range.Buffer); bufferInfos[i].buffer = rangedVkBuffer.DeviceBuffer; bufferInfos[i].offset = range.Offset; bufferInfos[i].range = range.SizeInBytes; descriptorWrites[i].pBufferInfo = &bufferInfos[i]; _refCounts.Add(rangedVkBuffer.RefCount); } else if (type == VkDescriptorType.SampledImage) { TextureView texView = Util.GetTextureView(_gd, boundResources[i]); VkTextureView vkTexView = Util.AssertSubtype<TextureView, VkTextureView>(texView); imageInfos[i].imageView = vkTexView.ImageView; imageInfos[i].imageLayout = VkImageLayout.ShaderReadOnlyOptimal; descriptorWrites[i].pImageInfo = &imageInfos[i]; _sampledTextures.Add(Util.AssertSubtype<Texture, VkTexture>(texView.Target)); _refCounts.Add(vkTexView.RefCount); } else if (type == VkDescriptorType.StorageImage) { TextureView texView = Util.GetTextureView(_gd, boundResources[i]); VkTextureView vkTexView = Util.AssertSubtype<TextureView, VkTextureView>(texView); imageInfos[i].imageView = vkTexView.ImageView; imageInfos[i].imageLayout = VkImageLayout.General; descriptorWrites[i].pImageInfo = &imageInfos[i]; _storageImages.Add(Util.AssertSubtype<Texture, VkTexture>(texView.Target)); _refCounts.Add(vkTexView.RefCount); } else if (type == VkDescriptorType.Sampler) { VkSampler sampler = Util.AssertSubtype<BindableResource, VkSampler>(boundResources[i]); imageInfos[i].sampler = sampler.DeviceSampler; descriptorWrites[i].pImageInfo = &imageInfos[i]; _refCounts.Add(sampler.RefCount); } } vkUpdateDescriptorSets(_gd.Device, descriptorWriteCount, descriptorWrites, 0, null); } public override string Name { get => _name; set { _name = value; _gd.SetResourceName(this, value); } } public override void Dispose() { RefCount.Decrement(); } private void DisposeCore() { if (!_destroyed) { _destroyed = true; _gd.DescriptorPoolManager.Free(_descriptorAllocationToken, _descriptorCounts); } } } }
47.172131
113
0.622937
[ "MIT" ]
Ronmenator/veldrid
src/Veldrid/Vk/VkResourceSet.cs
5,757
C#
// <auto-generated> // ReSharper disable All using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Tester.Integration.EfCore3 { // Boo public class Stafford_Boo { public int Id { get; set; } // id (Primary key) public string Name { get; set; } // name (length: 10) // Reverse navigation /// <summary> /// Parent (One-to-One) Stafford_Boo pointed by [Foo].[id] (FK_Foo_Boo) /// </summary> public virtual Stafford_Foo Stafford_Foo { get; set; } // Foo.FK_Foo_Boo } } // </auto-generated>
23
80
0.626409
[ "Apache-2.0" ]
janissimsons/EntityFramework-Reverse-POCO-Code-First-Generator
Tester.Integration.EfCore3/EfrpgTestData/Entities/Stafford_Boo.cs
621
C#
using System; namespace PartyPlaylists.Models { public class Item { public string Id { get; set; } public string Text { get; set; } public string Description { get; set; } } }
19.363636
47
0.591549
[ "MIT" ]
toastmalone/PartyPlaylists-1
PartyPlaylists/PartyPlaylists/Models/Item.cs
215
C#
using UnityEngine; using System.Collections; using LuaInterface; using System; using System.IO; //展示searchpath 使用,require 与 dofile 区别 public class ScriptsFromFile : MonoBehaviour { LuaState lua = null; private string strLog = ""; void Start () { #if UNITY_5_4_OR_NEWER Application.logMessageReceived += Log; #else Application.RegisterLogCallback(Log); #endif lua = new LuaState(); lua.Start(); //如果移动了ToLua目录,自己手动修复吧,只是例子就不做配置了 string fullPath = Application.dataPath + "\\ToLua/Examples/02_ScriptsFromFile"; lua.AddSearchPath(fullPath); } void Log(string msg, string stackTrace, LogType type) { strLog += msg; strLog += "\r\n"; } void OnGUI() { GUI.Label(new Rect(100, Screen.height / 2 - 100, 600, 400), strLog); if (GUI.Button(new Rect(50, 50, 120, 45), "DoFile")) { strLog = ""; lua.DoFile("ScriptsFromFile.lua"); } else if (GUI.Button(new Rect(50, 150, 120, 45), "Require")) { strLog = ""; lua.Require("ScriptsFromFile"); } lua.Collect(); lua.CheckTop(); } void OnApplicationQuit() { lua.Dispose(); lua = null; #if UNITY_5_4_OR_NEWER Application.logMessageReceived -= Log; #else Application.RegisterLogCallback(null); #endif } }
24.047619
87
0.547195
[ "MIT" ]
FlyApple/LuaFramework-Unity
Assets/ToLua/Examples/02_ScriptsFromFile/ScriptsFromFile.cs
1,585
C#
using RestoreMonarchy.PaymentGateway.Client.Constants; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Website.Shared.Constants { public class OrderConstants { public class Status { public const string Completed = "Completed"; public const string Pending = "Pending"; } public class Methods { public static string PayPal => PaymentProviders.PayPal; public static string Nano => PaymentProviders.Nano; } } }
22.444444
67
0.641914
[ "MIT" ]
Nonanti/UnturnedStore
src/Website/Shared/Constants/OrderConstants.cs
608
C#
using System.Linq; namespace DotNetHelper_Contracts.Helpers { public static class RandomHelper { public static string GetRandomString(int size, bool allowAlphaCharacters = true, bool allowNumericCharacters = true) { var random = new System.Random(); var input = ""; if (allowAlphaCharacters) input += "abcdefghijklmnopqrstuvwxyz" + "abcdefghijklmnopqrstuvwxyz".ToUpper(); if (allowNumericCharacters) input += "01234567890123456789"; if (!allowNumericCharacters && !allowAlphaCharacters) { return "@$$"; } // var chars = Enumerable.Range(0, size).Select(x => input[random.Next(0, input.Length)]); var chars = Enumerable.Range(0, size).Select(x => input[random.Next(input.Length)]); return new string(chars.ToArray()); } } }
37.2
124
0.588172
[ "MIT" ]
TheMofaDe/DotNetHelper-Contracts
src/DotNetHelper-Contracts/Helpers/RandomHelper.cs
932
C#
using Newtonsoft.Json; namespace WWB.Wx.Sdk.Apis.Message { public class SendVideoInput : SendInputBase { public SendVideoInput() { MessageType = MessageTypes.video; } [JsonProperty("video")] public VideoInfo Video { get; set; } public class VideoInfo { [JsonProperty("media_id")] public string MediaId { get; set; } } } }
20.809524
47
0.551487
[ "MIT" ]
my6521/WWB.Wx.Sdk
src/WWB.Wx.Sdk/Apis/Message/Dtos/SendVideoInput.cs
439
C#
using System.IO; using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class gamedataInteractionMountBase_Record : gamedataInteractionBase_Record { public gamedataInteractionMountBase_Record(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
24.466667
122
0.765668
[ "MIT" ]
Eingin/CP77Tools
CP77.CR2W/Types/cp77/gamedataInteractionMountBase_Record.cs
353
C#
using System; using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; using Xunit; namespace ActiveLogin.Authentication.GrandId.AspNetCore.Test { public class GrandId_Authentication_Tests { [Fact] public async Task Challenge_Redirects_To_SignIn() { // Arrange using var client = CreateServer(o => { o.UseSimulatedEnvironment() .AddBankIdSameDevice(options => { }); }, async context => { await context.ChallengeAsync(GrandIdDefaults.BankIdSameDeviceAuthenticationScheme); }).CreateClient(); // Act var transaction = await client.GetAsync("/"); // Assert Assert.Equal(HttpStatusCode.Redirect, transaction.StatusCode); Assert.Equal("/signin-grandid-bankid-samedevice", transaction.Headers.Location.LocalPath); } private TestServer CreateServer(Action<IGrandIdBuilder> builder, Func<HttpContext, Task> testpath, Action<IServiceCollection> configureServices = null) { var webHostBuilder = new WebHostBuilder() .Configure(app => { app.UseAuthentication(); app.Use(async (context, next) => { await testpath(context); await next(); }); app.Run(context => context.Response.WriteAsync("")); }) .ConfigureServices(services => { services.AddAuthentication().AddGrandId(builder); configureServices?.Invoke(services); }); return new TestServer(webHostBuilder); } } }
34.163934
159
0.564299
[ "MIT" ]
ActiveLogin/ActiveLogin.Authentication
test/ActiveLogin.Authentication.GrandId.AspNetCore.Test/GrandId_Authentication_Tests.cs
2,084
C#
using ActiveTimeline.Enumerate; using ActiveTimeline.Value.Primitive; using JetBrains.Annotations; using UniRx; using UniRx.Triggers; using UnityEngine; namespace ActiveTimeline.Value.Process { [PublicAPI] [AddComponentMenu("ActiveTimeline/Value/Process/Timer", (int)ValueType.Timer)] public class Timer : FloatValue { [SerializeField] private bool playOnAwake; private bool IsPlaying { get; set; } private void Awake() { IsPlaying = playOnAwake; } private void Start() { this .UpdateAsObservable() .Where(_ => IsPlaying) .Subscribe(_ => Value += Time.deltaTime) .AddTo(this); } public void StartTimer() { ResetTimer(); IsPlaying = true; } public void StopTimer() { ResetTimer(); IsPlaying = false; } public void PauseTimer() { IsPlaying = false; } public void ResumeTimer() { IsPlaying = true; } public void ResetTimer() { Value = 0.0f; } } }
20.813559
82
0.516287
[ "MIT" ]
umm/active_timeline
Assets/Scripts/Value/Process/Timer.cs
1,228
C#
namespace NebScope { partial class ScopeForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ScopeForm)); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.btnSettings = new System.Windows.Forms.Button(); this.chkCapture = new System.Windows.Forms.CheckBox(); this.btnHelp = new System.Windows.Forms.Button(); this.txtMsgs = new System.Windows.Forms.RichTextBox(); this.potCh2Position = new NBagOfTricks.UI.Pot(); this.potCh1Position = new NBagOfTricks.UI.Pot(); this.potXPosition = new NBagOfTricks.UI.Pot(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.label2 = new System.Windows.Forms.Label(); this.selTimebase = new System.Windows.Forms.ComboBox(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.label1 = new System.Windows.Forms.Label(); this.selCh1VoltsPerDiv = new System.Windows.Forms.ComboBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.label3 = new System.Windows.Forms.Label(); this.selCh2VoltsPerDiv = new System.Windows.Forms.ComboBox(); this.skControl = new SkiaSharp.Views.Desktop.SKControl(); this.timerHousekeeping = new System.Windows.Forms.Timer(this.components); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.groupBox1.SuspendLayout(); this.groupBox3.SuspendLayout(); this.groupBox2.SuspendLayout(); this.SuspendLayout(); // // splitContainer1 // this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel1; this.splitContainer1.Location = new System.Drawing.Point(0, 0); this.splitContainer1.Margin = new System.Windows.Forms.Padding(4); this.splitContainer1.Name = "splitContainer1"; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this.btnSettings); this.splitContainer1.Panel1.Controls.Add(this.chkCapture); this.splitContainer1.Panel1.Controls.Add(this.btnHelp); this.splitContainer1.Panel1.Controls.Add(this.txtMsgs); this.splitContainer1.Panel1.Controls.Add(this.potCh2Position); this.splitContainer1.Panel1.Controls.Add(this.potCh1Position); this.splitContainer1.Panel1.Controls.Add(this.potXPosition); this.splitContainer1.Panel1.Controls.Add(this.groupBox1); this.splitContainer1.Panel1.Controls.Add(this.groupBox3); this.splitContainer1.Panel1.Controls.Add(this.groupBox2); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add(this.skControl); this.splitContainer1.Size = new System.Drawing.Size(1109, 594); this.splitContainer1.SplitterDistance = 257; this.splitContainer1.SplitterWidth = 5; this.splitContainer1.TabIndex = 1; // // btnSettings // this.btnSettings.Image = global::NebScope.Properties.Resources.glyphicons_137_cogwheel; this.btnSettings.Location = new System.Drawing.Point(148, 15); this.btnSettings.Margin = new System.Windows.Forms.Padding(4); this.btnSettings.Name = "btnSettings"; this.btnSettings.Size = new System.Drawing.Size(43, 39); this.btnSettings.TabIndex = 18; this.btnSettings.UseVisualStyleBackColor = true; this.btnSettings.Click += new System.EventHandler(this.UserSettings_Click); // // chkCapture // this.chkCapture.Appearance = System.Windows.Forms.Appearance.Button; this.chkCapture.AutoSize = true; this.chkCapture.Image = global::NebScope.Properties.Resources.glyphicons_82_refresh; this.chkCapture.Location = new System.Drawing.Point(17, 15); this.chkCapture.Margin = new System.Windows.Forms.Padding(4); this.chkCapture.Name = "chkCapture"; this.chkCapture.Size = new System.Drawing.Size(31, 32); this.chkCapture.TabIndex = 17; this.chkCapture.UseVisualStyleBackColor = true; this.chkCapture.CheckedChanged += new System.EventHandler(this.ChkCapture_CheckedChanged); // // btnHelp // this.btnHelp.Image = global::NebScope.Properties.Resources.glyphicons_195_question_sign; this.btnHelp.Location = new System.Drawing.Point(199, 15); this.btnHelp.Margin = new System.Windows.Forms.Padding(4); this.btnHelp.Name = "btnHelp"; this.btnHelp.Size = new System.Drawing.Size(43, 39); this.btnHelp.TabIndex = 15; this.btnHelp.UseVisualStyleBackColor = true; this.btnHelp.Click += new System.EventHandler(this.BtnHelp_Click); // // txtMsgs // this.txtMsgs.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.txtMsgs.BackColor = System.Drawing.SystemColors.Control; this.txtMsgs.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtMsgs.Location = new System.Drawing.Point(17, 396); this.txtMsgs.Margin = new System.Windows.Forms.Padding(4); this.txtMsgs.Name = "txtMsgs"; this.txtMsgs.Size = new System.Drawing.Size(223, 186); this.txtMsgs.TabIndex = 13; this.txtMsgs.Text = ""; this.txtMsgs.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.txtMsgs_MouseDoubleClick); // // potCh2Position // this.potCh2Position.DecPlaces = 2; this.potCh2Position.DrawColor = System.Drawing.Color.Black; this.potCh2Position.Label = "Pos"; this.potCh2Position.Location = new System.Drawing.Point(155, 311); this.potCh2Position.Margin = new System.Windows.Forms.Padding(5); this.potCh2Position.Maximum = 1D; this.potCh2Position.Minimum = -1D; this.potCh2Position.Name = "potCh2Position"; this.potCh2Position.Size = new System.Drawing.Size(67, 62); this.potCh2Position.TabIndex = 6; this.potCh2Position.Taper = NBagOfTricks.UI.Taper.Linear; this.potCh2Position.Value = 0D; this.potCh2Position.ValueChanged += new System.EventHandler(this.Pot_ValueChanged); this.potCh2Position.DoubleClick += new System.EventHandler(this.Pot_DoubleClick); // // potCh1Position // this.potCh1Position.DecPlaces = 2; this.potCh1Position.DrawColor = System.Drawing.Color.Black; this.potCh1Position.Label = "Pos"; this.potCh1Position.Location = new System.Drawing.Point(155, 208); this.potCh1Position.Margin = new System.Windows.Forms.Padding(5); this.potCh1Position.Maximum = 1D; this.potCh1Position.Minimum = -1D; this.potCh1Position.Name = "potCh1Position"; this.potCh1Position.Size = new System.Drawing.Size(67, 62); this.potCh1Position.TabIndex = 5; this.potCh1Position.Taper = NBagOfTricks.UI.Taper.Linear; this.potCh1Position.Value = 0D; this.potCh1Position.ValueChanged += new System.EventHandler(this.Pot_ValueChanged); this.potCh1Position.DoubleClick += new System.EventHandler(this.Pot_DoubleClick); // // potXPosition // this.potXPosition.DecPlaces = 2; this.potXPosition.DrawColor = System.Drawing.Color.Black; this.potXPosition.Label = "Pos"; this.potXPosition.Location = new System.Drawing.Point(155, 105); this.potXPosition.Margin = new System.Windows.Forms.Padding(5); this.potXPosition.Maximum = 1D; this.potXPosition.Minimum = -1D; this.potXPosition.Name = "potXPosition"; this.potXPosition.Size = new System.Drawing.Size(67, 62); this.potXPosition.TabIndex = 1; this.potXPosition.Taper = NBagOfTricks.UI.Taper.Linear; this.potXPosition.Value = 0D; this.potXPosition.ValueChanged += new System.EventHandler(this.Pot_ValueChanged); this.potXPosition.DoubleClick += new System.EventHandler(this.Pot_DoubleClick); // // groupBox1 // this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.selTimebase); this.groupBox1.Location = new System.Drawing.Point(16, 90); this.groupBox1.Margin = new System.Windows.Forms.Padding(4); this.groupBox1.Name = "groupBox1"; this.groupBox1.Padding = new System.Windows.Forms.Padding(4); this.groupBox1.Size = new System.Drawing.Size(225, 94); this.groupBox1.TabIndex = 11; this.groupBox1.TabStop = false; this.groupBox1.Text = "X"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(32, 58); this.label2.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(54, 17); this.label2.TabIndex = 15; this.label2.Text = "Sec/div"; // // selTimebase // this.selTimebase.FormattingEnabled = true; this.selTimebase.Location = new System.Drawing.Point(29, 28); this.selTimebase.Margin = new System.Windows.Forms.Padding(4); this.selTimebase.Name = "selTimebase"; this.selTimebase.Size = new System.Drawing.Size(79, 24); this.selTimebase.TabIndex = 13; this.selTimebase.SelectedValueChanged += new System.EventHandler(this.Sel_SelectedValueChanged); // // groupBox3 // this.groupBox3.Controls.Add(this.label1); this.groupBox3.Controls.Add(this.selCh1VoltsPerDiv); this.groupBox3.Location = new System.Drawing.Point(16, 191); this.groupBox3.Margin = new System.Windows.Forms.Padding(4); this.groupBox3.Name = "groupBox3"; this.groupBox3.Padding = new System.Windows.Forms.Padding(4); this.groupBox3.Size = new System.Drawing.Size(225, 94); this.groupBox3.TabIndex = 12; this.groupBox3.TabStop = false; this.groupBox3.Text = "Ch 1"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(32, 59); this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(61, 17); this.label1.TabIndex = 16; this.label1.Text = "Volts/div"; // // selCh1VoltsPerDiv // this.selCh1VoltsPerDiv.FormattingEnabled = true; this.selCh1VoltsPerDiv.Location = new System.Drawing.Point(29, 26); this.selCh1VoltsPerDiv.Margin = new System.Windows.Forms.Padding(4); this.selCh1VoltsPerDiv.Name = "selCh1VoltsPerDiv"; this.selCh1VoltsPerDiv.Size = new System.Drawing.Size(79, 24); this.selCh1VoltsPerDiv.TabIndex = 14; this.selCh1VoltsPerDiv.SelectedValueChanged += new System.EventHandler(this.Sel_SelectedValueChanged); // // groupBox2 // this.groupBox2.Controls.Add(this.label3); this.groupBox2.Controls.Add(this.selCh2VoltsPerDiv); this.groupBox2.Location = new System.Drawing.Point(16, 294); this.groupBox2.Margin = new System.Windows.Forms.Padding(4); this.groupBox2.Name = "groupBox2"; this.groupBox2.Padding = new System.Windows.Forms.Padding(4); this.groupBox2.Size = new System.Drawing.Size(225, 94); this.groupBox2.TabIndex = 12; this.groupBox2.TabStop = false; this.groupBox2.Text = "Ch 2"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(32, 47); this.label3.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(61, 17); this.label3.TabIndex = 17; this.label3.Text = "Volts/div"; // // selCh2VoltsPerDiv // this.selCh2VoltsPerDiv.FormattingEnabled = true; this.selCh2VoltsPerDiv.Location = new System.Drawing.Point(29, 17); this.selCh2VoltsPerDiv.Margin = new System.Windows.Forms.Padding(4); this.selCh2VoltsPerDiv.Name = "selCh2VoltsPerDiv"; this.selCh2VoltsPerDiv.Size = new System.Drawing.Size(79, 24); this.selCh2VoltsPerDiv.TabIndex = 15; this.selCh2VoltsPerDiv.SelectedValueChanged += new System.EventHandler(this.Sel_SelectedValueChanged); // // skControl // this.skControl.BackColor = System.Drawing.Color.Moccasin; this.skControl.Dock = System.Windows.Forms.DockStyle.Fill; this.skControl.Location = new System.Drawing.Point(0, 0); this.skControl.Margin = new System.Windows.Forms.Padding(4); this.skControl.Name = "skControl"; this.skControl.Size = new System.Drawing.Size(847, 594); this.skControl.TabIndex = 0; this.skControl.Text = "skControl"; this.skControl.PaintSurface += new System.EventHandler<SkiaSharp.Views.Desktop.SKPaintSurfaceEventArgs>(this.SkControl_PaintSurface); this.skControl.Resize += new System.EventHandler(this.SkControl_Resize); // // timerHousekeeping // this.timerHousekeeping.Tick += new System.EventHandler(this.TimerHousekeeping_Tick); // // ScopeForm // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1109, 594); this.Controls.Add(this.splitContainer1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Margin = new System.Windows.Forms.Padding(4); this.Name = "ScopeForm"; this.Text = "NebScope"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.ScopeForm_FormClosing); this.Load += new System.EventHandler(this.ScopeForm_Load); this.Paint += new System.Windows.Forms.PaintEventHandler(this.ScopeForm_Paint); this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel1.PerformLayout(); this.splitContainer1.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit(); this.splitContainer1.ResumeLayout(false); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.SplitContainer splitContainer1; private SkiaSharp.Views.Desktop.SKControl skControl; private NBagOfTricks.UI.Pot potXPosition; private NBagOfTricks.UI.Pot potCh2Position; private NBagOfTricks.UI.Pot potCh1Position; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox selTimebase; private System.Windows.Forms.Label label1; private System.Windows.Forms.ComboBox selCh1VoltsPerDiv; private System.Windows.Forms.Label label3; private System.Windows.Forms.ComboBox selCh2VoltsPerDiv; private System.Windows.Forms.RichTextBox txtMsgs; private System.Windows.Forms.Timer timerHousekeeping; private System.Windows.Forms.Button btnHelp; private System.Windows.Forms.CheckBox chkCapture; private System.Windows.Forms.Button btnSettings; } }
52.578488
155
0.621275
[ "MIT" ]
cepthomas/NebScope
ScopeForm.Designer.cs
18,089
C#
using IdentityServer4.Services; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace SAEON.Identity.Service.UI { //[SecurityHeaders] public class HomeController : Controller { private readonly IIdentityServerInteractionService _interaction; public HomeController(IIdentityServerInteractionService interaction) { _interaction = interaction; } public IActionResult Index() { return View(); } [Route("About")] public IActionResult About() { return View(); } [Route("Contact")] public IActionResult Contact() { return View(); } /// <summary> /// Shows the error page /// </summary> public async Task<IActionResult> Error(string errorId) { var vm = new ErrorViewModel(); // retrieve error details from identityserver var message = await _interaction.GetErrorContextAsync(errorId); if (message != null) { vm.Error = message; } return View("Error", vm); } } }
23.326923
76
0.551525
[ "MIT" ]
SAEONData/Identity-Service
SAEON.Identity.Service/Home/HomeController.cs
1,215
C#
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // #region Usings using System; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Xml.XPath; using DotNetNuke.Common; using DotNetNuke.Common.Utilities; using DotNetNuke.Instrumentation; using Microsoft.Extensions.FileSystemGlobbing; #endregion namespace DotNetNuke.Services.Installer.Installers { /// ----------------------------------------------------------------------------- /// <summary> /// The CleanupInstaller cleans up (removes) files from previous versions /// </summary> /// <remarks> /// </remarks> /// ----------------------------------------------------------------------------- public class CleanupInstaller : FileInstaller { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (CleanupInstaller)); #region "Private Members" private string _fileName; private string _glob; #endregion #region "Public Properties" /// ----------------------------------------------------------------------------- /// <summary> /// Gets a list of allowable file extensions (in addition to the Host's List) /// </summary> /// <value>A String</value> /// ----------------------------------------------------------------------------- public override string AllowableFiles => "*"; #endregion #region "Private Methods" private bool ProcessCleanupFile() { Log.AddInfo(string.Format(Util.CLEANUP_Processing, Version.ToString(3))); try { var strListFile = Path.Combine(Package.InstallerInfo.TempInstallFolder, _fileName); if (File.Exists(strListFile)) { FileSystemUtils.DeleteFiles(File.ReadAllLines(strListFile)); } } catch (Exception ex) { Log.AddWarning(string.Format(Util.CLEANUP_ProcessError, ex.Message)); //DNN-9202: MUST NOT fail installation when cleanup files deletion fails //return false; } Log.AddInfo(string.Format(Util.CLEANUP_ProcessComplete, Version.ToString(3))); return true; } private bool ProcessGlob() { Log.AddInfo(string.Format(Util.CLEANUP_Processing, Version.ToString(3))); try { if (_glob.Contains("..")) { Log.AddWarning(Util.EXCEPTION + " - " + Util.EXCEPTION_GlobDotDotNotSupportedInCleanup); } else { var globs = new Matcher(StringComparison.InvariantCultureIgnoreCase); globs.AddIncludePatterns(_glob.Split(';')); var files = globs.GetResultsInFullPath(Globals.ApplicationMapPath).ToArray(); FileSystemUtils.DeleteFiles(files); } } catch (Exception ex) { Log.AddWarning(string.Format(Util.CLEANUP_ProcessError, ex.Message)); } Log.AddInfo(string.Format(Util.CLEANUP_ProcessComplete, Version.ToString(3))); return true; } #endregion #region "Protected Methods" /// ----------------------------------------------------------------------------- /// <summary> /// The CleanupFile method cleansup a single file. /// </summary> /// <param name="insFile">The InstallFile to clean up</param> /// ----------------------------------------------------------------------------- protected bool CleanupFile(InstallFile insFile) { try { //Backup File if (File.Exists(PhysicalBasePath + insFile.FullName)) { Util.BackupFile(insFile, PhysicalBasePath, Log); } //Delete file Util.DeleteFile(insFile, PhysicalBasePath, Log); return true; } catch (Exception exc) { Logger.Error(exc); return false; } } /// ----------------------------------------------------------------------------- /// <summary> /// The ProcessFile method determines what to do with parsed "file" node /// </summary> /// <param name="file">The file represented by the node</param> /// <param name="nav">The XPathNavigator representing the node</param> /// ----------------------------------------------------------------------------- protected override void ProcessFile(InstallFile file, XPathNavigator nav) { if (file != null) { Files.Add(file); } } protected override InstallFile ReadManifestItem(XPathNavigator nav, bool checkFileExists) { return base.ReadManifestItem(nav, false); } /// ----------------------------------------------------------------------------- /// <summary> /// The RollbackFile method rolls back the cleanup of a single file. /// </summary> /// <param name="installFile">The InstallFile to commit</param> /// ----------------------------------------------------------------------------- protected override void RollbackFile(InstallFile installFile) { if (File.Exists(installFile.BackupFileName)) { Util.RestoreFile(installFile, PhysicalBasePath, Log); } } #endregion #region "Public Methods" /// ----------------------------------------------------------------------------- /// <summary> /// The Commit method finalises the Install and commits any pending changes. /// </summary> /// <remarks>In the case of Clenup this is not neccessary</remarks> /// ----------------------------------------------------------------------------- public override void Commit() { //Do nothing base.Commit(); } /// ----------------------------------------------------------------------------- /// <summary> /// The Install method cleansup the files /// </summary> /// ----------------------------------------------------------------------------- public override void Install() { try { bool bSuccess = true; if (string.IsNullOrEmpty(_fileName) && string.IsNullOrEmpty(_glob)) // No attribute: use the xml files definition. { foreach (InstallFile file in Files) { bSuccess = CleanupFile(file); if (!bSuccess) { break; } } } else if (!string.IsNullOrEmpty(_fileName)) // Cleanup file provided: clean each file in the cleanup text file line one by one. { bSuccess = ProcessCleanupFile(); } else if (!string.IsNullOrEmpty(_glob)) // A globbing pattern was provided, use it to find the files and delete what matches. { bSuccess = ProcessGlob(); } Completed = bSuccess; } catch (Exception ex) { Log.AddFailure(Util.EXCEPTION + " - " + ex.Message); } } public override void ReadManifest(XPathNavigator manifestNav) { _fileName = Util.ReadAttribute(manifestNav, "fileName"); _glob = Util.ReadAttribute(manifestNav, "glob"); base.ReadManifest(manifestNav); } /// ----------------------------------------------------------------------------- /// <summary> /// The UnInstall method uninstalls the file component /// </summary> /// <remarks>There is no uninstall for this component</remarks> /// ----------------------------------------------------------------------------- public override void UnInstall() { } #endregion } }
35.915966
142
0.452387
[ "MIT" ]
CMarius94/Dnn.Platform
DNN Platform/Library/Services/Installer/Installers/CleanupInstaller.cs
8,550
C#
namespace BitcoinVanityAddressFinder { // ReSharper disable once UnusedMember.Global public class Logging { // Intentionally no logging in this app as it could be a security risk if private keys are languishing on disk. } }
34.857143
119
0.733607
[ "MIT" ]
iainholder/BitcoinVanityAddressFinder
BitcoinVanityAddressFinder/Logging.cs
246
C#
//////////////////////////////////////////////////////////////////////////////// //EF Core Provider for LCPI OLE DB. // IBProvider and Contributors. 20.09.2018. using System; using System.Diagnostics; using System.Collections.Generic; using System.Linq.Expressions; using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.Query.SqlExpressions; using Microsoft.EntityFrameworkCore.Storage; namespace Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Dbms.Firebird.Common.Query.Sql.Expressions.Nodes{ //////////////////////////////////////////////////////////////////////////////// //class FB_Common__Sql_ENode_Function__SQL__TRIM sealed class FB_Common__Sql_ENode_Function__SQL__TRIM :FB_Common__Sql_ENode_Function { private const ErrSourceID c_ErrSrcID =ErrSourceID.FB_Common__Sql_ENode_Function__SQL__TRIM; //----------------------------------------------------------------------- private const int c_ArgCount=1; private const int c_ArgIdx__value=0; //----------------------------------------------------------------------- private FB_Common__Sql_ENode_Function__SQL__TRIM (System.String functionName, IEnumerable<SqlExpression> arguments, System.Type resultType, RelationalTypeMapping resultTypeMapping) :base(functionName, arguments, Core.SQL.Core_SQL__TestNullable.TestNullable_ANY(arguments), sm_argumentsPropagateNullability, resultType, resultTypeMapping) { #if TRACE Core.Core_Trace.Method ("FB_Common__Sql_ENode_Function__SQL__TRIM::FB_Common__Sql_ENode_Function__SQL__TRIM(...) - clone"); #endif //---------------------------------------- #if DEBUG this.DEBUG__CheckState(); #endif }//FB_Common__Sql_ENode_Function__SQL__TRIM //----------------------------------------------------------------------- public FB_Common__Sql_ENode_Function__SQL__TRIM (SqlExpression valueExpression) :this("TRIM", new[]{valueExpression}, Structure.Structure_TypeCache.TypeOf__System_String, FB_Common__TypeMappingCache.TypeMapping__TEXT) { #if TRACE Core.Core_Trace.Method ("FB_Common__Sql_ENode_Function__SQL__TRIM::FB_Common__Sql_ENode_Function__SQL__TRIM\n" +" (valueExpression: {0})", valueExpression); #endif //---------------------------------------- Debug.Assert(!Object.ReferenceEquals(valueExpression,null)); #if DEBUG this.DEBUG__CheckState(); #endif Debug.Assert(Object.ReferenceEquals(this.Arguments[c_ArgIdx__value],valueExpression)); }//FB_Common__Sql_ENode_Function__SQL__TRIM //Expression interface -------------------------------------------------- public override bool CanReduce { get { #if TRACE Core.Core_Trace.Method ("FB_Common__Sql_ENode_Function__SQL__TRIM::get_CanReduce - false"); #endif //---------------------------------------- #if DEBUG this.DEBUG__CheckState(); #endif //---------------------------------------- return false; }//get }//CanReduce //----------------------------------------------------------------------- protected override Expression Accept(ExpressionVisitor visitor) { Debug.Assert(!Object.ReferenceEquals(visitor,null)); #if TRACE Core.Core_Trace.Method_Enter ("FB_Common__Sql_ENode_Function__SQL__TRIM::Accept" +" (visitorType: {0})", visitor.GetType()); #endif Expression r; if(visitor is Sql.FB_Common__QuerySqlGenerator x) { r=this.Helper__Accept__GenerateSql(x); } else { r=base.Accept(visitor); }//else #if TRACE Core.Core_Trace.Method_Exit ("FB_Common__Sql_ENode_Function__SQL__TRIM::Accept" +" (visitorType: {0}) - {1}", visitor.GetType(), r?.GetType()); #endif return r; }//Accept //----------------------------------------------------------------------- protected override Expression VisitChildren(ExpressionVisitor visitor) { Debug.Assert(!Object.ReferenceEquals(visitor,null)); //---------------------------------------- const string c_bugcheck_src ="FB_Common__Sql_ENode_Function__SQL__TRIM::VisitChildren"; //---------------------------------------- #if TRACE Core.Core_Trace.Method ("FB_Common__Sql_ENode_Function__SQL__TRIM::VisitChildren\n" +" ({0})", visitor); #endif //---------------------------------------- #if DEBUG this.DEBUG__CheckState(); #endif //---------------------------------------- Expression newValueExpression_e = visitor.Visit(this.Arguments[c_ArgIdx__value]); //---------------------------------------- var newValueExpression =Check.BugCheck_Value_NotNullAndInstanceOf<SqlExpression,Expression> (c_ErrSrcID, c_bugcheck_src, "#001", "newValueExpression_e", newValueExpression_e); Debug.Assert(!Object.ReferenceEquals(newValueExpression,null)); //---------------------------------------- for(;;) { if(newValueExpression!=this.Arguments[c_ArgIdx__value]) break; Debug.Assert(this.Arguments.Count==1); return this; }//for[ever] //create new instance return new FB_Common__Sql_ENode_Function__SQL__TRIM (this.Name, new[]{newValueExpression}, this.Type, this.TypeMapping); }//VisitChildren //----------------------------------------------------------------------- public override SqlFunctionExpression ApplyTypeMapping(RelationalTypeMapping typeMapping) { //[2020-12-03] Call of this method not expected Debug.Assert(false); #if DEBUG this.DEBUG__CheckState(); #endif ThrowSysError.method_not_impl (c_ErrSrcID, nameof(ApplyTypeMapping)); return null; }//ApplyTypeMapping //----------------------------------------------------------------------- public override SqlFunctionExpression Update(SqlExpression instance, IReadOnlyList<SqlExpression> arguments) { Check.Arg_IsNull (c_ErrSrcID, nameof(Update), nameof(instance), instance); Check.Arg_NotNull (c_ErrSrcID, nameof(Update), nameof(arguments), arguments); Check.Arg_ListSize (c_ErrSrcID, nameof(Update), nameof(arguments), arguments.Count, c_ArgCount); Debug.Assert(c_ArgIdx__value==0); Check.Arg_NotNull (c_ErrSrcID, nameof(Update), nameof(arguments)+"[0]", arguments[c_ArgIdx__value]); //------------------------------------------------------------ #if DEBUG this.DEBUG__CheckState(); #endif //------------------------------------------------------------ for(;;) { if(!Object.ReferenceEquals(this.Arguments[c_ArgIdx__value],arguments[c_ArgIdx__value])) break; return this; }//for[ever] return new FB_Common__Sql_ENode_Function__SQL__TRIM (this.Name, arguments, this.Type, this.TypeMapping); }//Update //----------------------------------------------------------------------- protected override void Print(ExpressionPrinter expressionPrinter) { #if TRACE Core.Core_Trace.Method ("FB_Common__Sql_ENode_Function__SQL__TRIM::Print(...)"); #endif //------------------------------------------------------------ Check.Arg_NotNull (c_ErrSrcID, nameof(Print), nameof(expressionPrinter), expressionPrinter); //------------------------------------------------------------ #if DEBUG this.DEBUG__CheckState(); #endif //------------------------------------------------------------ expressionPrinter.Append("TRIM("); expressionPrinter.Visit(this.Arguments[c_ArgIdx__value]); expressionPrinter.Append(")"); }//Print //Helper methods -------------------------------------------------------- private Expression Helper__Accept__GenerateSql(Sql.FB_Common__QuerySqlGenerator querySqlGenerator) { #if TRACE Core.Core_Trace.Method ("FB_Common__Sql_ENode_Function__SQL__TRIM::Helper__Accept__GenerateSql(...)"); #endif //------------------------------------------------------------ Debug.Assert(!Object.ReferenceEquals(querySqlGenerator,null)); #if DEBUG this.DEBUG__CheckState(); #endif //------------------------------------------------------------ querySqlGenerator.Sql.Append("TRIM("); querySqlGenerator.Visit(this.Arguments[c_ArgIdx__value]); querySqlGenerator.Sql.Append(")"); return this; }//Helper__Accept__GenerateSql //Debug methods --------------------------------------------------------- #if DEBUG private void DEBUG__CheckState() { Debug.Assert(Object.ReferenceEquals(this.Instance,null)); Debug.Assert(!Object.ReferenceEquals(this.Arguments,null)); Debug.Assert(this.Arguments.Count==c_ArgCount); Debug.Assert(!Object.ReferenceEquals(this.Arguments[c_ArgIdx__value],null)); }//DEBUG__CheckState #endif //private data ---------------------------------------------------------- private static readonly bool[] sm_argumentsPropagateNullability =new bool[c_ArgCount]{true}; };//class FB_Common__Sql_ENode_Function__SQL__TRIM //////////////////////////////////////////////////////////////////////////////// }//namespace Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Dbms.Firebird.Common.Query.Sql.Expressions.Nodes
28.191489
121
0.573477
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Code/Provider/Source/Basement/EF/Dbms/Firebird/Common/Query/Sql/Expressions/Nodes/FB_Common__Sql_ENode_Function__SQL__TRIM.cs
9,275
C#
/* * Test for ValueConvertExtensions * * Copyright (c) 2019 Takahisa YAMASHIGE * * This software is released under the MIT License. * https://opensource.org/licenses/mit-license.php */ using System; using System.Collections.Generic; using MinimalTools.Extensions.Convert; using Xunit; namespace MinimalTools.Test.Extensions.Convert { #region [ DateTime format ] /// <summary> /// Test for DateTime extensions of ValueConvertExtensions. /// </summary> public class ValueConvertExtensions_ToXXX { DateTime Now = DateTime.Now; string Ymd; string DelimitedYmd; string YmdHms; string DelimitedYmdHms; string Timestp; string DelimitedTimestp; /// <summary> /// Set up. /// </summary> public ValueConvertExtensions_ToXXX() { this.Ymd = $"{Now.Year:D4}{Now.Month:D2}{Now.Day:D2}"; this.YmdHms = $"{Now.Year:D4}{Now.Month:D2}{Now.Day:D2}{Now.Hour:D2}{Now.Minute:D2}{Now.Second:D2}"; this.Timestp = $"{Now.Year:D4}{Now.Month:D2}{Now.Day:D2}{Now.Hour:D2}{Now.Minute:D2}{Now.Second:D2}{Now.Millisecond:D3}"; this.DelimitedYmd = $"{Now.Year:D4}/{Now.Month:D2}/{Now.Day:D2}"; this.DelimitedYmdHms = $"{Now.Year:D4}/{Now.Month:D2}/{Now.Day:D2} {Now.Hour:D2}:{Now.Minute:D2}:{Now.Second:D2}"; this.DelimitedTimestp = $"{Now.Year:D4}/{Now.Month:D2}/{Now.Day:D2} {Now.Hour:D2}:{Now.Minute:D2}:{Now.Second:D2}.{Now.Millisecond:D3}"; } #region [ YMD ] [Fact(DisplayName = "DateTime should be formatted to [yyyyMMdd].")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToYmd))] public void DateTimeToYmd() => this.Now.ToYmd().Is(this.Ymd); [Fact(DisplayName = "DateTime? should be formatted to [yyyyMMdd].")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToYmd))] public void NullableDateTimeToYmd() => (new DateTime?(this.Now)).ToYmd().Is(this.Ymd); [Fact(DisplayName = "DateTime? without value should be string.Empty.")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToYmd))] public void NullToYmd() => (null as DateTime?).ToYmd().Is(string.Empty); [Fact(DisplayName = "DateTime should be formatted to [yyyy/MM/dd].")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToDelimitedYmd))] public void DateTimeToYmdWithSlash() => this.Now.ToDelimitedYmd().Is(this.DelimitedYmd); [Fact(DisplayName = "DateTime? should be formatted to [yyyy/MM/dd].")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToDelimitedYmd))] public void NullableDateTimeToYmdWithSlash() => (new DateTime?(this.Now)).ToDelimitedYmd().Is(this.DelimitedYmd); [Fact(DisplayName = "DateTime? without value should be string.Empty.")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToDelimitedYmd))] public void NullToYmdWithSlash() => (null as DateTime?).ToDelimitedYmd().Is(string.Empty); #endregion #region [ YMDHMS ] [Fact(DisplayName = "DateTime should be formatted to [yyyyMMddHHmmss].")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToYmdHms))] public void DateTimeToYmdHms() => this.Now.ToYmdHms().Is(this.YmdHms); [Fact(DisplayName = "DateTime? should be formatted to [yyyyMMddHHmmss].")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToYmdHms))] public void NullableDateTimeToYmdHms() => (new DateTime?(this.Now)).ToYmdHms().Is(this.YmdHms); [Fact(DisplayName = "DateTime? without value should be string.Empty.")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToYmdHms))] public void NullToYmdHms() => (null as DateTime?).ToYmdHms().Is(string.Empty); [Fact(DisplayName = "DateTime should be formatted to [yyyy/MM/dd HH:mm:ss].")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToDelimitedYmdHms))] public void DateTimeToYmdHmsWithSlash() => this.Now.ToDelimitedYmdHms().Is(this.DelimitedYmdHms); [Fact(DisplayName = "DateTime? should be formatted to [yyyy/MM/dd HH:mm:ss].")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToDelimitedYmdHms))] public void NullableDateTimeToYmdHmsWithSlash() => (new DateTime?(this.Now)).ToDelimitedYmdHms().Is(this.DelimitedYmdHms); [Fact(DisplayName = "DateTime? without value should be string.Empty.")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToDelimitedYmdHms))] public void NullToYmdHmsWithSlash() => (null as DateTime?).ToDelimitedYmdHms().Is(string.Empty); #endregion #region [ TIMESTAMP ] [Fact(DisplayName = "DateTime should be formatted to [yyyyMMddHHmmssfff].")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToTimestamp))] public void DateTimeToTmstmp() => this.Now.ToTimestamp().Is(this.Timestp); [Fact(DisplayName = "DateTime? should be formatted to [yyyyMMddHHmmssfff].")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToTimestamp))] public void NullableDateTimeToTmstamp() => (new DateTime?(this.Now)).ToTimestamp().Is(this.Timestp); [Fact(DisplayName = "DateTime? without value should be string.Empty.")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToTimestamp))] public void NullToTmstamp() => (null as DateTime?).ToYmdHms().Is(string.Empty); [Fact(DisplayName = "DateTime should be formatted to [yyyy/MM/dd HH:mm:ss.fff].")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToDelimitedTimestamp))] public void DateTimeToTmstampWithSlash() => this.Now.ToDelimitedTimestamp().Is(this.DelimitedTimestp); [Fact(DisplayName = "DateTime? should be formatted to [yyyy/MM/dd HH:mm:ss.fff].")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToDelimitedTimestamp))] public void NullableDateTimeToTmstampWithSlash() => (new DateTime?(this.Now)).ToDelimitedTimestamp().Is(this.DelimitedTimestp); [Fact(DisplayName = "DateTime? without value should be string.Empty.")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToDelimitedTimestamp))] public void NullToTmstampsWithSlash() => (null as DateTime?).ToDelimitedTimestamp().Is(string.Empty); #endregion } #endregion #region [ ToHexadecimalString ] /// <summary> /// Test for ValueConvertExtensions.ToHexadecimalString. /// </summary> public class ValueConvertExtensions_ToHexadecimalString { [Fact(DisplayName = "A sbyte value should be a hexadecimal-string.")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToHexadecimalString))] public void Sbyte() { sbyte x = 10; var replace = "XXX"; var expect = x.ToString("X2"); x.ToHexadecimalString().Is(expect); sbyte? nx = x; nx.ToHexadecimalString().Is(expect); nx.ToHexadecimalString(replace).Is(expect); nx = null; nx.ToHexadecimalString().Is(string.Empty); nx.ToHexadecimalString(replace).Is(replace); } [Fact(DisplayName = "A byte value should be a hexadecimal-string.")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToHexadecimalString))] public void Byte() { byte x = 128; var replace = "XXX"; var expect = x.ToString("X2"); x.ToHexadecimalString().Is(expect); byte? nx = x; nx.ToHexadecimalString().Is(expect); nx.ToHexadecimalString(replace).Is(expect); nx = null; nx.ToHexadecimalString().Is(string.Empty); nx.ToHexadecimalString(replace).Is(replace); } [Fact(DisplayName = "A short value should be a hexadecimal-string.")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToHexadecimalString))] public void Short() { short x = -128; var replace = "XXX"; var expect = x.ToString("X4"); x.ToHexadecimalString().Is(expect); short? nx = x; nx.ToHexadecimalString().Is(expect); nx.ToHexadecimalString(replace).Is(expect); nx = null; nx.ToHexadecimalString().Is(string.Empty); nx.ToHexadecimalString(replace).Is(replace); } [Fact(DisplayName = "An ushort value should be a hexadecimal-string.")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToHexadecimalString))] public void Ushort() { ushort x = 511; var replace = "XXX"; var expect = x.ToString("X4"); x.ToHexadecimalString().Is(expect); ushort? nx = x; nx.ToHexadecimalString().Is(expect); nx.ToHexadecimalString(replace).Is(expect); nx = null; nx.ToHexadecimalString().Is(string.Empty); nx.ToHexadecimalString(replace).Is(replace); } [Fact(DisplayName = "An int value should be a hexadecimal-string.")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToHexadecimalString))] public void Int() { int x = -768; var replace = "XXX"; var expect = x.ToString("X8"); x.ToHexadecimalString().Is(expect); int? nx = x; nx.ToHexadecimalString().Is(expect); nx.ToHexadecimalString(replace).Is(expect); nx = null; nx.ToHexadecimalString().Is(string.Empty); nx.ToHexadecimalString(replace).Is(replace); } [Fact(DisplayName = "An uint value should be a hexadecimal-string.")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToHexadecimalString))] public void Uint() { uint x = 768; var replace = "XXX"; var expect = x.ToString("X8"); x.ToHexadecimalString().Is(expect); uint? nx = x; nx.ToHexadecimalString().Is(expect); nx.ToHexadecimalString(replace).Is(expect); nx = null; nx.ToHexadecimalString().Is(string.Empty); nx.ToHexadecimalString(replace).Is(replace); } [Fact(DisplayName = "A long value should be a hexadecimal-string.")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToHexadecimalString))] public void Long() { long x = -70000; var replace = "XXX"; var expect = x.ToString("X16"); x.ToHexadecimalString().Is(expect); long? nx = x; nx.ToHexadecimalString().Is(expect); nx.ToHexadecimalString(replace).Is(expect); nx = null; nx.ToHexadecimalString().Is(string.Empty); nx.ToHexadecimalString(replace).Is(replace); } [Fact(DisplayName = "An ulong value should be a hexadecimal-string.")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToHexadecimalString))] public void Ulong() { ulong x = 0xFFFF0000FFFF0000; var replace = "XXX"; var expect = x.ToString("X16"); x.ToHexadecimalString().Is(expect); ulong? nx = x; nx.ToHexadecimalString().Is(expect); nx.ToHexadecimalString(replace).Is(expect); nx = null; nx.ToHexadecimalString().Is(string.Empty); nx.ToHexadecimalString(replace).Is(replace); } } #endregion #region [ ToBigEndianBytes ] /// <summary> /// Test for ValueConvertExtensions.ToBigEndianBytes /// </summary> public class ValueConvertExtensions_ToBigEndianBytes { [Fact(DisplayName = "An ushort value should be big-endian byte array.")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToBigEndianBytes))] public void UShort() { ushort x = 0xFFFA; var expect = new byte[] { 0xFF, 0xFA, }; x.ToBigEndianBytes().Is(expect); ushort? nx = x; nx.ToBigEndianBytes().Is(expect); nx = null; nx.ToBigEndianBytes().Is(new byte[] { }); } [Fact(DisplayName = "A short value should be big-endian byte array.")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToBigEndianBytes))] public void Short() { short x = -32768; var expect = new byte[] { 0x80, 0x00, }; x.ToBigEndianBytes().Is(expect); short? nx = x; nx.ToBigEndianBytes().Is(expect); nx = null; nx.ToBigEndianBytes().Is(new byte[] { }); } [Fact(DisplayName = "An int value should be big-endian byte array.")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToBigEndianBytes))] public void Int() { int x = -1; var expect = new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, }; x.ToBigEndianBytes().Is(expect); int? nx = x; nx.ToBigEndianBytes().Is(expect); nx = null; nx.ToBigEndianBytes().Is(new byte[] { }); } [Fact(DisplayName = "An uint value should be big-endian byte array.")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToBigEndianBytes))] public void UInt() { uint x = 0xFFFF0000; var expect = new byte[] { 0xFF, 0xFF, 0x00, 0x00, }; x.ToBigEndianBytes().Is(expect); uint? nx = x; nx.ToBigEndianBytes().Is(expect); nx = null; nx.ToBigEndianBytes().Is(new byte[] { }); } [Fact(DisplayName = "A long value should be big-endian byte array.")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToBigEndianBytes))] public void Long() { long x = -2; var expect = new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, }; x.ToBigEndianBytes().Is(expect); long? nx = x; nx.ToBigEndianBytes().Is(expect); nx = null; nx.ToBigEndianBytes().Is(new byte[] { }); } [Fact(DisplayName = "An ulong value should be big-endian byte array.")] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToBigEndianBytes))] public void ULong() { ulong x = 0x1122334455667788; var expect = new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, }; x.ToBigEndianBytes().Is(expect); ulong? nx = x; nx.ToBigEndianBytes().Is(expect); nx = null; nx.ToBigEndianBytes().Is(new byte[] { }); } } #endregion #region [ ToHexadecimalStringAsBigEndianBytes ] /// <summary> /// Test for ValueConvertExtensions.ToHexadecimalStringAsBigEndianBytes. /// </summary> public class ValueConvertExtensions_ToHexadecimalStringAsBigEndianBytes { #region [ sbyte ] /// <summary>Test data supplier for sbyte.</summary> class TestData001 : DataGenerator { /// <summary>constructor</summary> public TestData001() { sbyte[] array = new sbyte[] { 1, 127, -1, -128, 0 }; this.Add(array, false, null, "017FFF8000"); this.Add(array, true, null, "017FFF8000"); this.Add(array, true, string.Empty, "017FFF8000"); this.Add(array, true, "/", "01/7F/FF/80/00"); this.Add(array, true, " ", "01 7F FF 80 00"); array = new sbyte[] { 127, }; this.Add(array, false, null, "7F"); this.Add(array, true, null, "7F"); this.Add(array, true, string.Empty, "7F"); this.Add(array, true, "/", "7F"); this.Add(array, true, " ", "7F"); array = new sbyte[] { }; this.Add(array, false, null, string.Empty); this.Add(array, true, null, string.Empty); this.Add(array, true, string.Empty, string.Empty); this.Add(array, true, "/", string.Empty); this.Add(array, true, " ", string.Empty); this.Add(null, false, null, string.Empty); this.Add(null, true, null, string.Empty); this.Add(null, true, string.Empty, string.Empty); this.Add(null, true, "/", string.Empty); this.Add(null, true, " ", string.Empty); } } [Theory(DisplayName = "The sbyte array should be converted to hexadecimal-string array that ordered by big-endian.")] [ClassData(typeof(TestData001))] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToHexadecimalStringAsBigEndianBytes))] public void SbyteArray(IEnumerable<sbyte> array, bool useSepalator, string sepalator, string expect) { if (useSepalator) { array.ToHexadecimalStringAsBigEndianBytes(sepalator).Is(expect); } else { array.ToHexadecimalStringAsBigEndianBytes().Is(expect); } } #endregion #region [ byte ] /// <summary> /// Test Data for byte. /// </summary> class TestData002 : DataGenerator { /// <summary> /// constructor ///</summary> public TestData002() { byte[] array = new byte[] { 1, 127, 0xFF, 0x80, 0 }; this.Add(array, false, null, "017FFF8000"); this.Add(array, true, null, "017FFF8000"); this.Add(array, true, string.Empty, "017FFF8000"); this.Add(array, true, "/", "01/7F/FF/80/00"); this.Add(array, true, " ", "01 7F FF 80 00"); array = new byte[] { 127, }; this.Add(array, false, null, "7F"); this.Add(array, true, null, "7F"); this.Add(array, true, string.Empty, "7F"); this.Add(array, true, "/", "7F"); this.Add(array, true, " ", "7F"); array = new byte[] { }; this.Add(array, false, null, string.Empty); this.Add(array, true, null, string.Empty); this.Add(array, true, string.Empty, string.Empty); this.Add(array, true, "/", string.Empty); this.Add(array, true, " ", string.Empty); this.Add(null, false, null, string.Empty); this.Add(null, true, null, string.Empty); this.Add(null, true, string.Empty, string.Empty); this.Add(null, true, "/", string.Empty); this.Add(null, true, " ", string.Empty); } } [Theory(DisplayName = "The byte array should be converted to hexadecimal-string array that ordered by big-endian.")] [ClassData(typeof(TestData002))] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToHexadecimalStringAsBigEndianBytes))] public void ByteArray(IEnumerable<byte> array, bool useSepalator, string sepalator, string expect) { if (useSepalator) { array.ToHexadecimalStringAsBigEndianBytes(sepalator).Is(expect); } else { array.ToHexadecimalStringAsBigEndianBytes().Is(expect); } } #endregion #region [ short ] /// <summary> /// Test Data for short. /// </summary> class TestData003 : DataGenerator { /// <summary> /// constructor /// </summary> public TestData003() { short[] array = new short[] { 0, 1, 32767, -32768, -1, }; this.Add(array, false, null, "000000017FFF8000FFFF"); this.Add(array, true, null, "000000017FFF8000FFFF"); this.Add(array, true, string.Empty, "000000017FFF8000FFFF"); this.Add(array, true, "/", "00/00/00/01/7F/FF/80/00/FF/FF"); this.Add(array, true, " ", "00 00 00 01 7F FF 80 00 FF FF"); array = new short[] { 127, }; this.Add(array, false, null, "007F"); this.Add(array, true, null, "007F"); this.Add(array, true, string.Empty, "007F"); this.Add(array, true, "/", "00/7F"); this.Add(array, true, " ", "00 7F"); array = new short[] { }; this.Add(array, false, null, string.Empty); this.Add(array, true, null, string.Empty); this.Add(array, true, string.Empty, string.Empty); this.Add(array, true, "/", string.Empty); this.Add(array, true, " ", string.Empty); this.Add(null, false, null, string.Empty); this.Add(null, true, null, string.Empty); this.Add(null, true, string.Empty, string.Empty); this.Add(null, true, "/", string.Empty); this.Add(null, true, " ", string.Empty); } } [Theory(DisplayName = "The short array should be converted to hexadecimal-string array that ordered by big-endian.")] [ClassData(typeof(TestData003))] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToHexadecimalStringAsBigEndianBytes))] public void ShortArray(IEnumerable<short> array, bool useSepalator, string sepalator, string expect) { if (useSepalator) { array.ToHexadecimalStringAsBigEndianBytes(sepalator).Is(expect); } else { array.ToHexadecimalStringAsBigEndianBytes().Is(expect); } } #endregion #region [ ushort ] /// <summary> /// Test Data for ushort. /// </summary> class TestData004 : DataGenerator { /// <summary> /// constructor /// </summary> public TestData004() { ushort[] array = new ushort[] { 0, 1, 32767, 0x8000, 0xFFFF, }; this.Add(array, false, null, "000000017FFF8000FFFF"); this.Add(array, true, null, "000000017FFF8000FFFF"); this.Add(array, true, string.Empty, "000000017FFF8000FFFF"); this.Add(array, true, "/", "00/00/00/01/7F/FF/80/00/FF/FF"); this.Add(array, true, " ", "00 00 00 01 7F FF 80 00 FF FF"); array = new ushort[] { 127, }; this.Add(array, false, null, "007F"); this.Add(array, true, null, "007F"); this.Add(array, true, string.Empty, "007F"); this.Add(array, true, "/", "00/7F"); this.Add(array, true, " ", "00 7F"); array = new ushort[] { }; this.Add(array, false, null, string.Empty); this.Add(array, true, null, string.Empty); this.Add(array, true, string.Empty, string.Empty); this.Add(array, true, "/", string.Empty); this.Add(array, true, " ", string.Empty); this.Add(null, false, null, string.Empty); this.Add(null, true, null, string.Empty); this.Add(null, true, string.Empty, string.Empty); this.Add(null, true, "/", string.Empty); this.Add(null, true, " ", string.Empty); } } [Theory(DisplayName = "The ushort array should be converted to hexadecimal-string array that ordered by big-endian.")] [ClassData(typeof(TestData004))] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToHexadecimalStringAsBigEndianBytes))] public void UShortArray(IEnumerable<ushort> array, bool useSepalator, string sepalator, string expect) { if (useSepalator) { array.ToHexadecimalStringAsBigEndianBytes(sepalator).Is(expect); } else { array.ToHexadecimalStringAsBigEndianBytes().Is(expect); } } #endregion #region [ int ] /// <summary> /// Test Data for int. /// </summary> class TestData005 : DataGenerator { /// <summary> /// constructor /// </summary> public TestData005() { int[] array = new int[] { 0, 1, 0x7FFFFFFF, -0x80000000, -1 }; this.Add(array, false, null, "00000000000000017FFFFFFF80000000FFFFFFFF"); this.Add(array, true, null, "00000000000000017FFFFFFF80000000FFFFFFFF"); this.Add(array, true, string.Empty, "00000000000000017FFFFFFF80000000FFFFFFFF"); this.Add(array, true, "/", "00/00/00/00/00/00/00/01/7F/FF/FF/FF/80/00/00/00/FF/FF/FF/FF"); this.Add(array, true, " ", "00 00 00 00 00 00 00 01 7F FF FF FF 80 00 00 00 FF FF FF FF"); array = new int[] { 127, }; this.Add(array, false, null, "0000007F"); this.Add(array, true, null, "0000007F"); this.Add(array, true, string.Empty, "0000007F"); this.Add(array, true, "/", "00/00/00/7F"); this.Add(array, true, " ", "00 00 00 7F"); array = new int[] { }; this.Add(array, false, null, string.Empty); this.Add(array, true, null, string.Empty); this.Add(array, true, string.Empty, string.Empty); this.Add(array, true, "/", string.Empty); this.Add(array, true, " ", string.Empty); this.Add(null, false, null, string.Empty); this.Add(null, true, null, string.Empty); this.Add(null, true, string.Empty, string.Empty); this.Add(null, true, "/", string.Empty); this.Add(null, true, " ", string.Empty); } } [Theory(DisplayName = "The int array should be converted to hexadecimal-string array that ordered by big-endian.")] [ClassData(typeof(TestData005))] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToHexadecimalStringAsBigEndianBytes))] public void IntArray(IEnumerable<int> array, bool useSepalator, string sepalator, string expect) { if (useSepalator) { array.ToHexadecimalStringAsBigEndianBytes(sepalator).Is(expect); } else { array.ToHexadecimalStringAsBigEndianBytes().Is(expect); } } #endregion #region [ uint ] /// <summary> /// Test Data for uint. /// </summary> class TestData006 : DataGenerator { /// <summary> /// constructor /// </summary> public TestData006() { uint[] array = new uint[] { 0, 1, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF }; this.Add(array, false, null, "00000000000000017FFFFFFF80000000FFFFFFFF"); this.Add(array, true, null, "00000000000000017FFFFFFF80000000FFFFFFFF"); this.Add(array, true, string.Empty, "00000000000000017FFFFFFF80000000FFFFFFFF"); this.Add(array, true, "/", "00/00/00/00/00/00/00/01/7F/FF/FF/FF/80/00/00/00/FF/FF/FF/FF"); this.Add(array, true, " ", "00 00 00 00 00 00 00 01 7F FF FF FF 80 00 00 00 FF FF FF FF"); array = new uint[] { 127, }; this.Add(array, false, null, "0000007F"); this.Add(array, true, null, "0000007F"); this.Add(array, true, string.Empty, "0000007F"); this.Add(array, true, "/", "00/00/00/7F"); this.Add(array, true, " ", "00 00 00 7F"); array = new uint[] { }; this.Add(array, false, null, string.Empty); this.Add(array, true, null, string.Empty); this.Add(array, true, string.Empty, string.Empty); this.Add(array, true, "/", string.Empty); this.Add(array, true, " ", string.Empty); this.Add(null, false, null, string.Empty); this.Add(null, true, null, string.Empty); this.Add(null, true, string.Empty, string.Empty); this.Add(null, true, "/", string.Empty); this.Add(null, true, " ", string.Empty); } } [Theory(DisplayName = "The uint array should be converted to hexadecimal-string array that ordered by big-endian.")] [ClassData(typeof(TestData006))] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToHexadecimalStringAsBigEndianBytes))] public void UIntArray(IEnumerable<uint> array, bool useSepalator, string sepalator, string expect) { if (useSepalator) { array.ToHexadecimalStringAsBigEndianBytes(sepalator).Is(expect); } else { array.ToHexadecimalStringAsBigEndianBytes().Is(expect); } } #endregion #region [ long ] /// <summary>Test Data for long.</summary> class TestData007 : DataGenerator { /// <summary> /// constructor /// </summary> public TestData007() { long[] array = new long[] { 0, 1, -1 }; this.Add(array, false, null, "00000000000000000000000000000001FFFFFFFFFFFFFFFF"); this.Add(array, true, null, "00000000000000000000000000000001FFFFFFFFFFFFFFFF"); this.Add(array, true, string.Empty, "00000000000000000000000000000001FFFFFFFFFFFFFFFF"); this.Add(array, true, "/", "00/00/00/00/00/00/00/00/00/00/00/00/00/00/00/01/FF/FF/FF/FF/FF/FF/FF/FF"); this.Add(array, true, "__", "00__00__00__00__00__00__00__00__00__00__00__00__00__00__00__01__FF__FF__FF__FF__FF__FF__FF__FF"); array = new long[] { 127, }; this.Add(array, false, null, "000000000000007F"); this.Add(array, true, null, "000000000000007F"); this.Add(array, true, string.Empty, "000000000000007F"); this.Add(array, true, "/", "00/00/00/00/00/00/00/7F"); this.Add(array, true, " ", "00 00 00 00 00 00 00 7F"); array = new long[] { }; this.Add(array, false, null, string.Empty); this.Add(array, true, null, string.Empty); this.Add(array, true, string.Empty, string.Empty); this.Add(array, true, "/", string.Empty); this.Add(array, true, " ", string.Empty); this.Add(null, false, null, string.Empty); this.Add(null, true, null, string.Empty); this.Add(null, true, string.Empty, string.Empty); this.Add(null, true, "/", string.Empty); this.Add(null, true, " ", string.Empty); } } [Theory(DisplayName = "The long array should be converted to hexadecimal-string array that ordered by big-endian.")] [ClassData(typeof(TestData007))] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToHexadecimalStringAsBigEndianBytes))] public void LongArray(IEnumerable<long> array, bool useSepalator, string sepalator, string expect) { if (useSepalator) { array.ToHexadecimalStringAsBigEndianBytes(sepalator).Is(expect); } else { array.ToHexadecimalStringAsBigEndianBytes().Is(expect); } } #endregion #region [ ulong ] /// <summary> /// Test Data for ulong. /// </summary> class TestData008 : DataGenerator { /// <summary> /// constructor /// </summary> public TestData008() { ulong[] array = new ulong[] { 0, 1, 0xFFFFFFFFFFFFFFFF }; this.Add(array, false, null, "00000000000000000000000000000001FFFFFFFFFFFFFFFF"); this.Add(array, true, null, "00000000000000000000000000000001FFFFFFFFFFFFFFFF"); this.Add(array, true, string.Empty, "00000000000000000000000000000001FFFFFFFFFFFFFFFF"); this.Add(array, true, "/", "00/00/00/00/00/00/00/00/00/00/00/00/00/00/00/01/FF/FF/FF/FF/FF/FF/FF/FF"); this.Add(array, true, "__", "00__00__00__00__00__00__00__00__00__00__00__00__00__00__00__01__FF__FF__FF__FF__FF__FF__FF__FF"); array = new ulong[] { 127, }; this.Add(array, false, null, "000000000000007F"); this.Add(array, true, null, "000000000000007F"); this.Add(array, true, string.Empty, "000000000000007F"); this.Add(array, true, "/", "00/00/00/00/00/00/00/7F"); this.Add(array, true, " ", "00 00 00 00 00 00 00 7F"); array = new ulong[] { }; this.Add(array, false, null, string.Empty); this.Add(array, true, null, string.Empty); this.Add(array, true, string.Empty, string.Empty); this.Add(array, true, "/", string.Empty); this.Add(array, true, " ", string.Empty); this.Add(null, false, null, string.Empty); this.Add(null, true, null, string.Empty); this.Add(null, true, string.Empty, string.Empty); this.Add(null, true, "/", string.Empty); this.Add(null, true, " ", string.Empty); } } [Theory(DisplayName = "The ulong array should be converted to hexadecimal-string array that ordered by big-endian.")] [ClassData(typeof(TestData008))] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToHexadecimalStringAsBigEndianBytes))] public void ULongArray(IEnumerable<long> array, bool useSepalator, string sepalator, string expect) { if (useSepalator) { array.ToHexadecimalStringAsBigEndianBytes(sepalator).Is(expect); } else { array.ToHexadecimalStringAsBigEndianBytes().Is(expect); } } #endregion } #endregion #region [ ToHexadecimalStringAsBigEndianBytes[nullable array] ] /// <summary> /// Test for ValueConvertExtensions.ToHexadecimalStringAsBigEndianBytes /// </summary> public class ValueConvertExtensions_ToHexadecimalStringAsBigEndianBytesForNullables { /// <summary>single asterisk</summary> const string SA = "*"; /// <summary>double asterisk</summary> const string DA = "**"; /// <summary>slash</summary> const string SL = "/"; /// <summary>double space</summary> const string DS = " "; /// <summary>string empty</summary> const string EP = ""; /// <summary>null</summary> const string NL = null; #region [ sbyte? ] /// <summary>Test data supplier for sbyte?.</summary> class TestData001 : DataGenerator { /// <summary>constructor</summary> public TestData001() { sbyte?[] array = new sbyte?[] { 1, 127, null, -1, -128, 0 }; this.Add(array, false, NL, false, NL, "017FFF8000"); this.Add(array, false, NL, true, NL, "017FFF8000"); this.Add(array, false, NL, true, EP, "017FFF8000"); this.Add(array, false, NL, true, SA, "017F*FF8000"); this.Add(array, false, NL, true, DA, "017F**FF8000"); this.Add(array, true, NL, false, NL, "017FFF8000"); this.Add(array, true, EP, false, NL, "017FFF8000"); this.Add(array, true, SL, false, NL, "01/7F//FF/80/00"); this.Add(array, true, DS, false, NL, "01 7F FF 80 00"); this.Add(array, true, NL, true, NL, "017FFF8000"); this.Add(array, true, NL, true, EP, "017FFF8000"); this.Add(array, true, NL, true, SA, "017F*FF8000"); this.Add(array, true, NL, true, DA, "017F**FF8000"); this.Add(array, true, EP, true, NL, "017FFF8000"); this.Add(array, true, EP, true, EP, "017FFF8000"); this.Add(array, true, EP, true, SA, "017F*FF8000"); this.Add(array, true, EP, true, DA, "017F**FF8000"); this.Add(array, true, SL, true, NL, "01/7F//FF/80/00"); this.Add(array, true, SL, true, EP, "01/7F//FF/80/00"); this.Add(array, true, SL, true, SA, "01/7F/*/FF/80/00"); this.Add(array, true, SL, true, DA, "01/7F/**/FF/80/00"); this.Add(array, true, DS, true, NL, "01 7F FF 80 00"); this.Add(array, true, DS, true, EP, "01 7F FF 80 00"); this.Add(array, true, DS, true, SA, "01 7F * FF 80 00"); this.Add(array, true, DS, true, DA, "01 7F ** FF 80 00"); array = new sbyte?[] { 127, }; this.Add(array, false, NL, false, NL, "7F"); this.Add(array, false, NL, true, NL, "7F"); this.Add(array, false, NL, true, EP, "7F"); this.Add(array, false, NL, true, SA, "7F"); this.Add(array, false, NL, true, DA, "7F"); this.Add(array, true, NL, false, NL, "7F"); this.Add(array, true, EP, false, NL, "7F"); this.Add(array, true, SL, false, NL, "7F"); this.Add(array, true, DA, false, NL, "7F"); this.Add(array, true, NL, true, NL, "7F"); this.Add(array, true, NL, true, EP, "7F"); this.Add(array, true, NL, true, SA, "7F"); this.Add(array, true, NL, true, DA, "7F"); this.Add(array, true, EP, true, NL, "7F"); this.Add(array, true, EP, true, EP, "7F"); this.Add(array, true, EP, true, SA, "7F"); this.Add(array, true, EP, true, DA, "7F"); this.Add(array, true, SL, true, NL, "7F"); this.Add(array, true, SL, true, EP, "7F"); this.Add(array, true, SL, true, SA, "7F"); this.Add(array, true, SL, true, DA, "7F"); this.Add(array, true, DS, true, NL, "7F"); this.Add(array, true, DS, true, EP, "7F"); this.Add(array, true, DS, true, SA, "7F"); this.Add(array, true, DS, true, DA, "7F"); array = new sbyte?[] { null, }; this.Add(array, false, NL, false, NL, EP); this.Add(array, false, NL, true, NL, EP); this.Add(array, false, NL, true, EP, EP); this.Add(array, false, NL, true, SA, SA); this.Add(array, false, NL, true, DA, DA); this.Add(array, true, NL, false, NL, EP); this.Add(array, true, EP, false, NL, EP); this.Add(array, true, SL, false, NL, EP); this.Add(array, true, DA, false, NL, EP); this.Add(array, true, NL, true, NL, EP); this.Add(array, true, NL, true, EP, EP); this.Add(array, true, NL, true, SA, SA); this.Add(array, true, NL, true, DA, DA); this.Add(array, true, EP, true, NL, EP); this.Add(array, true, EP, true, EP, EP); this.Add(array, true, EP, true, SA, SA); this.Add(array, true, EP, true, DA, DA); this.Add(array, true, SL, true, NL, EP); this.Add(array, true, SL, true, EP, EP); this.Add(array, true, SL, true, SA, SA); this.Add(array, true, SL, true, DA, DA); this.Add(array, true, DS, true, NL, EP); this.Add(array, true, DS, true, EP, EP); this.Add(array, true, DS, true, SA, SA); this.Add(array, true, DS, true, DA, DA); array = new sbyte?[] { }; this.Add(array, false, NL, false, NL, EP); this.Add(array, false, NL, true, NL, EP); this.Add(array, false, NL, true, EP, EP); this.Add(array, false, NL, true, SA, EP); this.Add(array, false, NL, true, DA, EP); this.Add(array, true, NL, false, NL, EP); this.Add(array, true, EP, false, NL, EP); this.Add(array, true, SL, false, NL, EP); this.Add(array, true, DS, false, NL, EP); this.Add(array, true, NL, true, NL, EP); this.Add(array, true, NL, true, EP, EP); this.Add(array, true, NL, true, SA, EP); this.Add(array, true, NL, true, DA, EP); this.Add(array, true, EP, true, NL, EP); this.Add(array, true, EP, true, EP, EP); this.Add(array, true, EP, true, SA, EP); this.Add(array, true, EP, true, DA, EP); this.Add(array, true, SL, true, NL, EP); this.Add(array, true, SL, true, EP, EP); this.Add(array, true, SL, true, SA, EP); this.Add(array, true, SL, true, DA, EP); this.Add(array, true, DS, true, NL, EP); this.Add(array, true, DS, true, EP, EP); this.Add(array, true, DS, true, SA, EP); this.Add(array, true, DS, true, DA, EP); this.Add(null, false, NL, false, NL, EP); this.Add(null, false, NL, true, NL, EP); this.Add(null, false, NL, true, EP, EP); this.Add(null, false, NL, true, SA, EP); this.Add(null, false, NL, true, DA, EP); this.Add(null, true, NL, false, NL, EP); this.Add(null, true, EP, false, NL, EP); this.Add(null, true, SL, false, NL, EP); this.Add(null, true, DS, false, NL, EP); this.Add(null, true, NL, true, NL, EP); this.Add(null, true, NL, true, EP, EP); this.Add(null, true, NL, true, SA, EP); this.Add(null, true, NL, true, DA, EP); this.Add(null, true, EP, true, NL, EP); this.Add(null, true, EP, true, EP, EP); this.Add(null, true, EP, true, SA, EP); this.Add(null, true, EP, true, DA, EP); this.Add(null, true, SL, true, NL, EP); this.Add(null, true, SL, true, EP, EP); this.Add(null, true, SL, true, SA, EP); this.Add(null, true, SL, true, DA, EP); this.Add(null, true, DS, true, NL, EP); this.Add(null, true, DS, true, EP, EP); this.Add(null, true, DS, true, SA, EP); this.Add(null, true, DS, true, DA, EP); } } [Theory(DisplayName = "The sbyte? array should be converted to hexadecimal-string array that ordered by big-endian.")] [ClassData(typeof(TestData001))] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToHexadecimalStringAsBigEndianBytes))] public void SbyteArray( IEnumerable<sbyte?> array, bool useSepalator, string sepalator, bool useReplace, string replace, string expect) { if (useSepalator) { if (useReplace) { array.ToHexadecimalStringAsBigEndianBytes(sepalator, replace).Is(expect); } else { array.ToHexadecimalStringAsBigEndianBytes(sepalator).Is(expect); } } else { if (useReplace) { array.ToHexadecimalStringAsBigEndianBytes(nullByteReplacement: replace).Is(expect); } else { array.ToHexadecimalStringAsBigEndianBytes().Is(expect); } } } #endregion #region [ byte? ] /// <summary> /// Test Data for byte?. /// </summary> class TestData002 : DataGenerator { /// <summary> /// constructor /// </summary> public TestData002() { byte?[] array = new byte?[] { 1, 127, null, 0xFF, 0x80, 0 }; this.Add(array, false, NL, false, NL, "017FFF8000"); this.Add(array, false, NL, true, NL, "017FFF8000"); this.Add(array, false, NL, true, EP, "017FFF8000"); this.Add(array, false, NL, true, SA, "017F*FF8000"); this.Add(array, false, NL, true, DA, "017F**FF8000"); this.Add(array, true, NL, false, NL, "017FFF8000"); this.Add(array, true, EP, false, NL, "017FFF8000"); this.Add(array, true, SL, false, NL, "01/7F//FF/80/00"); this.Add(array, true, DS, false, NL, "01 7F FF 80 00"); this.Add(array, true, NL, true, NL, "017FFF8000"); this.Add(array, true, NL, true, EP, "017FFF8000"); this.Add(array, true, NL, true, SA, "017F*FF8000"); this.Add(array, true, NL, true, DA, "017F**FF8000"); this.Add(array, true, EP, true, NL, "017FFF8000"); this.Add(array, true, EP, true, EP, "017FFF8000"); this.Add(array, true, EP, true, SA, "017F*FF8000"); this.Add(array, true, EP, true, DA, "017F**FF8000"); this.Add(array, true, SL, true, NL, "01/7F//FF/80/00"); this.Add(array, true, SL, true, EP, "01/7F//FF/80/00"); this.Add(array, true, SL, true, SA, "01/7F/*/FF/80/00"); this.Add(array, true, SL, true, DA, "01/7F/**/FF/80/00"); this.Add(array, true, DS, true, NL, "01 7F FF 80 00"); this.Add(array, true, DS, true, EP, "01 7F FF 80 00"); this.Add(array, true, DS, true, SA, "01 7F * FF 80 00"); this.Add(array, true, DS, true, DA, "01 7F ** FF 80 00"); array = new byte?[] { 127, }; this.Add(array, false, NL, false, NL, "7F"); this.Add(array, false, NL, true, NL, "7F"); this.Add(array, false, NL, true, EP, "7F"); this.Add(array, false, NL, true, SA, "7F"); this.Add(array, false, NL, true, DA, "7F"); this.Add(array, true, NL, false, NL, "7F"); this.Add(array, true, EP, false, NL, "7F"); this.Add(array, true, SL, false, NL, "7F"); this.Add(array, true, DA, false, NL, "7F"); this.Add(array, true, NL, true, NL, "7F"); this.Add(array, true, NL, true, EP, "7F"); this.Add(array, true, NL, true, SA, "7F"); this.Add(array, true, NL, true, DA, "7F"); this.Add(array, true, EP, true, NL, "7F"); this.Add(array, true, EP, true, EP, "7F"); this.Add(array, true, EP, true, SA, "7F"); this.Add(array, true, EP, true, DA, "7F"); this.Add(array, true, SL, true, NL, "7F"); this.Add(array, true, SL, true, EP, "7F"); this.Add(array, true, SL, true, SA, "7F"); this.Add(array, true, SL, true, DA, "7F"); this.Add(array, true, DS, true, NL, "7F"); this.Add(array, true, DS, true, EP, "7F"); this.Add(array, true, DS, true, SA, "7F"); this.Add(array, true, DS, true, DA, "7F"); array = new byte?[] { null, }; this.Add(array, false, NL, false, NL, EP); this.Add(array, false, NL, true, NL, EP); this.Add(array, false, NL, true, EP, EP); this.Add(array, false, NL, true, SA, SA); this.Add(array, false, NL, true, DA, DA); this.Add(array, true, NL, false, NL, EP); this.Add(array, true, EP, false, NL, EP); this.Add(array, true, SL, false, NL, EP); this.Add(array, true, DA, false, NL, EP); this.Add(array, true, NL, true, NL, EP); this.Add(array, true, NL, true, EP, EP); this.Add(array, true, NL, true, SA, SA); this.Add(array, true, NL, true, DA, DA); this.Add(array, true, EP, true, NL, EP); this.Add(array, true, EP, true, EP, EP); this.Add(array, true, EP, true, SA, SA); this.Add(array, true, EP, true, DA, DA); this.Add(array, true, SL, true, NL, EP); this.Add(array, true, SL, true, EP, EP); this.Add(array, true, SL, true, SA, SA); this.Add(array, true, SL, true, DA, DA); this.Add(array, true, DS, true, NL, EP); this.Add(array, true, DS, true, EP, EP); this.Add(array, true, DS, true, SA, SA); this.Add(array, true, DS, true, DA, DA); array = new byte?[] { }; this.Add(array, false, NL, false, NL, EP); this.Add(array, false, NL, true, NL, EP); this.Add(array, false, NL, true, EP, EP); this.Add(array, false, NL, true, SA, EP); this.Add(array, false, NL, true, DA, EP); this.Add(array, true, NL, false, NL, EP); this.Add(array, true, EP, false, NL, EP); this.Add(array, true, SL, false, NL, EP); this.Add(array, true, DS, false, NL, EP); this.Add(array, true, NL, true, NL, EP); this.Add(array, true, NL, true, EP, EP); this.Add(array, true, NL, true, SA, EP); this.Add(array, true, NL, true, DA, EP); this.Add(array, true, EP, true, NL, EP); this.Add(array, true, EP, true, EP, EP); this.Add(array, true, EP, true, SA, EP); this.Add(array, true, EP, true, DA, EP); this.Add(array, true, SL, true, NL, EP); this.Add(array, true, SL, true, EP, EP); this.Add(array, true, SL, true, SA, EP); this.Add(array, true, SL, true, DA, EP); this.Add(array, true, DS, true, NL, EP); this.Add(array, true, DS, true, EP, EP); this.Add(array, true, DS, true, SA, EP); this.Add(array, true, DS, true, DA, EP); this.Add(null, false, NL, false, NL, EP); this.Add(null, false, NL, true, NL, EP); this.Add(null, false, NL, true, EP, EP); this.Add(null, false, NL, true, SA, EP); this.Add(null, false, NL, true, DA, EP); this.Add(null, true, NL, false, NL, EP); this.Add(null, true, EP, false, NL, EP); this.Add(null, true, SL, false, NL, EP); this.Add(null, true, DS, false, NL, EP); this.Add(null, true, NL, true, NL, EP); this.Add(null, true, NL, true, EP, EP); this.Add(null, true, NL, true, SA, EP); this.Add(null, true, NL, true, DA, EP); this.Add(null, true, EP, true, NL, EP); this.Add(null, true, EP, true, EP, EP); this.Add(null, true, EP, true, SA, EP); this.Add(null, true, EP, true, DA, EP); this.Add(null, true, SL, true, NL, EP); this.Add(null, true, SL, true, EP, EP); this.Add(null, true, SL, true, SA, EP); this.Add(null, true, SL, true, DA, EP); this.Add(null, true, DS, true, NL, EP); this.Add(null, true, DS, true, EP, EP); this.Add(null, true, DS, true, SA, EP); this.Add(null, true, DS, true, DA, EP); } } [Theory(DisplayName = "The byte? array should be converted to hexadecimal-string array that ordered by big-endian.")] [ClassData(typeof(TestData002))] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToHexadecimalStringAsBigEndianBytes))] public void ByteArray( IEnumerable<byte?> array, bool useSepalator, string sepalator, bool useReplace, string replace, string expect) { if (useSepalator) { if (useReplace) { array.ToHexadecimalStringAsBigEndianBytes(sepalator, replace).Is(expect); } else { array.ToHexadecimalStringAsBigEndianBytes(sepalator).Is(expect); } } else { if (useReplace) { array.ToHexadecimalStringAsBigEndianBytes(nullByteReplacement: replace).Is(expect); } else { array.ToHexadecimalStringAsBigEndianBytes().Is(expect); } } } #endregion #region [ short? ] /// <summary> /// Test Data for short?. /// </summary> class TestData003 : DataGenerator { /// <summary> /// constructor /// </summary> public TestData003() { short?[] array = new short?[] { 1, 127, null, -1, -32768, 0 }; this.Add(array, false, NL, false, NL, "0001007FFFFF80000000"); this.Add(array, false, NL, true, NL, "0001007FFFFF80000000"); this.Add(array, false, NL, true, EP, "0001007FFFFF80000000"); this.Add(array, false, NL, true, SA, "0001007F**FFFF80000000"); this.Add(array, false, NL, true, DA, "0001007F****FFFF80000000"); this.Add(array, true, NL, false, NL, "0001007FFFFF80000000"); this.Add(array, true, EP, false, NL, "0001007FFFFF80000000"); this.Add(array, true, SL, false, NL, "00/01/00/7F///FF/FF/80/00/00/00"); this.Add(array, true, DS, false, NL, "00 01 00 7F FF FF 80 00 00 00"); this.Add(array, true, NL, true, NL, "0001007FFFFF80000000"); this.Add(array, true, NL, true, EP, "0001007FFFFF80000000"); this.Add(array, true, NL, true, SA, "0001007F**FFFF80000000"); this.Add(array, true, NL, true, DA, "0001007F****FFFF80000000"); this.Add(array, true, EP, true, NL, "0001007FFFFF80000000"); this.Add(array, true, EP, true, EP, "0001007FFFFF80000000"); this.Add(array, true, EP, true, SA, "0001007F**FFFF80000000"); this.Add(array, true, EP, true, DA, "0001007F****FFFF80000000"); this.Add(array, true, SL, true, NL, "00/01/00/7F///FF/FF/80/00/00/00"); this.Add(array, true, SL, true, EP, "00/01/00/7F///FF/FF/80/00/00/00"); this.Add(array, true, SL, true, SA, "00/01/00/7F/*/*/FF/FF/80/00/00/00"); this.Add(array, true, SL, true, DA, "00/01/00/7F/**/**/FF/FF/80/00/00/00"); this.Add(array, true, DS, true, NL, "00 01 00 7F FF FF 80 00 00 00"); this.Add(array, true, DS, true, EP, "00 01 00 7F FF FF 80 00 00 00"); this.Add(array, true, DS, true, SA, "00 01 00 7F * * FF FF 80 00 00 00"); this.Add(array, true, DS, true, DA, "00 01 00 7F ** ** FF FF 80 00 00 00"); array = new short?[] { 127, }; this.Add(array, false, NL, false, NL, "007F"); this.Add(array, false, NL, true, NL, "007F"); this.Add(array, false, NL, true, EP, "007F"); this.Add(array, false, NL, true, SA, "007F"); this.Add(array, false, NL, true, DA, "007F"); this.Add(array, true, NL, false, NL, "007F"); this.Add(array, true, EP, false, NL, "007F"); this.Add(array, true, SL, false, NL, "00/7F"); this.Add(array, true, DS, false, NL, "00 7F"); this.Add(array, true, NL, true, NL, "007F"); this.Add(array, true, NL, true, EP, "007F"); this.Add(array, true, NL, true, SA, "007F"); this.Add(array, true, NL, true, DA, "007F"); this.Add(array, true, EP, true, NL, "007F"); this.Add(array, true, EP, true, EP, "007F"); this.Add(array, true, EP, true, SA, "007F"); this.Add(array, true, EP, true, DA, "007F"); this.Add(array, true, SL, true, NL, "00/7F"); this.Add(array, true, SL, true, EP, "00/7F"); this.Add(array, true, SL, true, SA, "00/7F"); this.Add(array, true, SL, true, DA, "00/7F"); this.Add(array, true, DS, true, NL, "00 7F"); this.Add(array, true, DS, true, EP, "00 7F"); this.Add(array, true, DS, true, SA, "00 7F"); this.Add(array, true, DS, true, DA, "00 7F"); array = new short?[] { null, }; this.Add(array, false, NL, false, NL, EP); this.Add(array, false, NL, true, NL, EP); this.Add(array, false, NL, true, EP, EP); this.Add(array, false, NL, true, SA, "**"); this.Add(array, false, NL, true, DA, "****"); this.Add(array, true, NL, false, NL, EP); this.Add(array, true, EP, false, NL, EP); this.Add(array, true, SL, false, NL, "/"); this.Add(array, true, DS, false, NL, " "); this.Add(array, true, NL, true, NL, EP); this.Add(array, true, NL, true, EP, EP); this.Add(array, true, NL, true, SA, "**"); this.Add(array, true, NL, true, DA, "****"); this.Add(array, true, EP, true, NL, EP); this.Add(array, true, EP, true, EP, EP); this.Add(array, true, EP, true, SA, "**"); this.Add(array, true, EP, true, DA, "****"); this.Add(array, true, SL, true, NL, "/"); this.Add(array, true, SL, true, EP, "/"); this.Add(array, true, SL, true, SA, "*/*"); this.Add(array, true, SL, true, DA, "**/**"); this.Add(array, true, DS, true, NL, " "); this.Add(array, true, DS, true, EP, " "); this.Add(array, true, DS, true, SA, "* *"); this.Add(array, true, DS, true, DA, "** **"); array = new short?[] { }; this.Add(array, false, NL, false, NL, EP); this.Add(array, false, NL, true, NL, EP); this.Add(array, false, NL, true, EP, EP); this.Add(array, false, NL, true, SA, EP); this.Add(array, false, NL, true, DA, EP); this.Add(array, true, NL, false, NL, EP); this.Add(array, true, EP, false, NL, EP); this.Add(array, true, SL, false, NL, EP); this.Add(array, true, DS, false, NL, EP); this.Add(array, true, NL, true, NL, EP); this.Add(array, true, NL, true, EP, EP); this.Add(array, true, NL, true, SA, EP); this.Add(array, true, NL, true, DA, EP); this.Add(array, true, EP, true, NL, EP); this.Add(array, true, EP, true, EP, EP); this.Add(array, true, EP, true, SA, EP); this.Add(array, true, EP, true, DA, EP); this.Add(array, true, SL, true, NL, EP); this.Add(array, true, SL, true, EP, EP); this.Add(array, true, SL, true, SA, EP); this.Add(array, true, SL, true, DA, EP); this.Add(array, true, DS, true, NL, EP); this.Add(array, true, DS, true, EP, EP); this.Add(array, true, DS, true, SA, EP); this.Add(array, true, DS, true, DA, EP); this.Add(null, false, NL, false, NL, EP); this.Add(null, false, NL, true, NL, EP); this.Add(null, false, NL, true, EP, EP); this.Add(null, false, NL, true, SA, EP); this.Add(null, false, NL, true, DA, EP); this.Add(null, true, NL, false, NL, EP); this.Add(null, true, EP, false, NL, EP); this.Add(null, true, SL, false, NL, EP); this.Add(null, true, DS, false, NL, EP); this.Add(null, true, NL, true, NL, EP); this.Add(null, true, NL, true, EP, EP); this.Add(null, true, NL, true, SA, EP); this.Add(null, true, NL, true, DA, EP); this.Add(null, true, EP, true, NL, EP); this.Add(null, true, EP, true, EP, EP); this.Add(null, true, EP, true, SA, EP); this.Add(null, true, EP, true, DA, EP); this.Add(null, true, SL, true, NL, EP); this.Add(null, true, SL, true, EP, EP); this.Add(null, true, SL, true, SA, EP); this.Add(null, true, SL, true, DA, EP); this.Add(null, true, DS, true, NL, EP); this.Add(null, true, DS, true, EP, EP); this.Add(null, true, DS, true, SA, EP); this.Add(null, true, DS, true, DA, EP); } } [Theory(DisplayName = "The short? array should be converted to hexadecimal-string array that ordered by big-endian.")] [ClassData(typeof(TestData003))] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToHexadecimalStringAsBigEndianBytes))] public void ShortArray( IEnumerable<short?> array, bool useSepalator, string sepalator, bool useReplace, string replace, string expect) { if (useSepalator) { if (useReplace) { array.ToHexadecimalStringAsBigEndianBytes(sepalator, replace).Is(expect); } else { array.ToHexadecimalStringAsBigEndianBytes(sepalator).Is(expect); } } else { if (useReplace) { array.ToHexadecimalStringAsBigEndianBytes(nullByteReplacement: replace).Is(expect); } else { array.ToHexadecimalStringAsBigEndianBytes().Is(expect); } } } #endregion #region [ ushort? ] /// <summary> /// Test Data for ushort?. /// </summary> class TestData004 : DataGenerator { /// <summary> /// constructor /// </summary> public TestData004() { ushort?[] array = new ushort?[] { 1, 127, null, 0xFFFF, 0x8000, 0 }; this.Add(array, false, NL, false, NL, "0001007FFFFF80000000"); this.Add(array, false, NL, true, NL, "0001007FFFFF80000000"); this.Add(array, false, NL, true, EP, "0001007FFFFF80000000"); this.Add(array, false, NL, true, SA, "0001007F**FFFF80000000"); this.Add(array, false, NL, true, DA, "0001007F****FFFF80000000"); this.Add(array, true, NL, false, NL, "0001007FFFFF80000000"); this.Add(array, true, EP, false, NL, "0001007FFFFF80000000"); this.Add(array, true, SL, false, NL, "00/01/00/7F///FF/FF/80/00/00/00"); this.Add(array, true, DS, false, NL, "00 01 00 7F FF FF 80 00 00 00"); this.Add(array, true, NL, true, NL, "0001007FFFFF80000000"); this.Add(array, true, NL, true, EP, "0001007FFFFF80000000"); this.Add(array, true, NL, true, SA, "0001007F**FFFF80000000"); this.Add(array, true, NL, true, DA, "0001007F****FFFF80000000"); this.Add(array, true, EP, true, NL, "0001007FFFFF80000000"); this.Add(array, true, EP, true, EP, "0001007FFFFF80000000"); this.Add(array, true, EP, true, SA, "0001007F**FFFF80000000"); this.Add(array, true, EP, true, DA, "0001007F****FFFF80000000"); this.Add(array, true, SL, true, NL, "00/01/00/7F///FF/FF/80/00/00/00"); this.Add(array, true, SL, true, EP, "00/01/00/7F///FF/FF/80/00/00/00"); this.Add(array, true, SL, true, SA, "00/01/00/7F/*/*/FF/FF/80/00/00/00"); this.Add(array, true, SL, true, DA, "00/01/00/7F/**/**/FF/FF/80/00/00/00"); this.Add(array, true, DS, true, NL, "00 01 00 7F FF FF 80 00 00 00"); this.Add(array, true, DS, true, EP, "00 01 00 7F FF FF 80 00 00 00"); this.Add(array, true, DS, true, SA, "00 01 00 7F * * FF FF 80 00 00 00"); this.Add(array, true, DS, true, DA, "00 01 00 7F ** ** FF FF 80 00 00 00"); array = new ushort?[] { 127, }; this.Add(array, false, NL, false, NL, "007F"); this.Add(array, false, NL, true, NL, "007F"); this.Add(array, false, NL, true, EP, "007F"); this.Add(array, false, NL, true, SA, "007F"); this.Add(array, false, NL, true, DA, "007F"); this.Add(array, true, NL, false, NL, "007F"); this.Add(array, true, EP, false, NL, "007F"); this.Add(array, true, SL, false, NL, "00/7F"); this.Add(array, true, DS, false, NL, "00 7F"); this.Add(array, true, NL, true, NL, "007F"); this.Add(array, true, NL, true, EP, "007F"); this.Add(array, true, NL, true, SA, "007F"); this.Add(array, true, NL, true, DA, "007F"); this.Add(array, true, EP, true, NL, "007F"); this.Add(array, true, EP, true, EP, "007F"); this.Add(array, true, EP, true, SA, "007F"); this.Add(array, true, EP, true, DA, "007F"); this.Add(array, true, SL, true, NL, "00/7F"); this.Add(array, true, SL, true, EP, "00/7F"); this.Add(array, true, SL, true, SA, "00/7F"); this.Add(array, true, SL, true, DA, "00/7F"); this.Add(array, true, DS, true, NL, "00 7F"); this.Add(array, true, DS, true, EP, "00 7F"); this.Add(array, true, DS, true, SA, "00 7F"); this.Add(array, true, DS, true, DA, "00 7F"); array = new ushort?[] { null, }; this.Add(array, false, NL, false, NL, EP); this.Add(array, false, NL, true, NL, EP); this.Add(array, false, NL, true, EP, EP); this.Add(array, false, NL, true, SA, "**"); this.Add(array, false, NL, true, DA, "****"); this.Add(array, true, NL, false, NL, EP); this.Add(array, true, EP, false, NL, EP); this.Add(array, true, SL, false, NL, "/"); this.Add(array, true, DS, false, NL, " "); this.Add(array, true, NL, true, NL, EP); this.Add(array, true, NL, true, EP, EP); this.Add(array, true, NL, true, SA, "**"); this.Add(array, true, NL, true, DA, "****"); this.Add(array, true, EP, true, NL, EP); this.Add(array, true, EP, true, EP, EP); this.Add(array, true, EP, true, SA, "**"); this.Add(array, true, EP, true, DA, "****"); this.Add(array, true, SL, true, NL, "/"); this.Add(array, true, SL, true, EP, "/"); this.Add(array, true, SL, true, SA, "*/*"); this.Add(array, true, SL, true, DA, "**/**"); this.Add(array, true, DS, true, NL, " "); this.Add(array, true, DS, true, EP, " "); this.Add(array, true, DS, true, SA, "* *"); this.Add(array, true, DS, true, DA, "** **"); array = new ushort?[] { }; this.Add(array, false, NL, false, NL, EP); this.Add(array, false, NL, true, NL, EP); this.Add(array, false, NL, true, EP, EP); this.Add(array, false, NL, true, SA, EP); this.Add(array, false, NL, true, DA, EP); this.Add(array, true, NL, false, NL, EP); this.Add(array, true, EP, false, NL, EP); this.Add(array, true, SL, false, NL, EP); this.Add(array, true, DS, false, NL, EP); this.Add(array, true, NL, true, NL, EP); this.Add(array, true, NL, true, EP, EP); this.Add(array, true, NL, true, SA, EP); this.Add(array, true, NL, true, DA, EP); this.Add(array, true, EP, true, NL, EP); this.Add(array, true, EP, true, EP, EP); this.Add(array, true, EP, true, SA, EP); this.Add(array, true, EP, true, DA, EP); this.Add(array, true, SL, true, NL, EP); this.Add(array, true, SL, true, EP, EP); this.Add(array, true, SL, true, SA, EP); this.Add(array, true, SL, true, DA, EP); this.Add(array, true, DS, true, NL, EP); this.Add(array, true, DS, true, EP, EP); this.Add(array, true, DS, true, SA, EP); this.Add(array, true, DS, true, DA, EP); this.Add(null, false, NL, false, NL, EP); this.Add(null, false, NL, true, NL, EP); this.Add(null, false, NL, true, EP, EP); this.Add(null, false, NL, true, SA, EP); this.Add(null, false, NL, true, DA, EP); this.Add(null, true, NL, false, NL, EP); this.Add(null, true, EP, false, NL, EP); this.Add(null, true, SL, false, NL, EP); this.Add(null, true, DS, false, NL, EP); this.Add(null, true, NL, true, NL, EP); this.Add(null, true, NL, true, EP, EP); this.Add(null, true, NL, true, SA, EP); this.Add(null, true, NL, true, DA, EP); this.Add(null, true, EP, true, NL, EP); this.Add(null, true, EP, true, EP, EP); this.Add(null, true, EP, true, SA, EP); this.Add(null, true, EP, true, DA, EP); this.Add(null, true, SL, true, NL, EP); this.Add(null, true, SL, true, EP, EP); this.Add(null, true, SL, true, SA, EP); this.Add(null, true, SL, true, DA, EP); this.Add(null, true, DS, true, NL, EP); this.Add(null, true, DS, true, EP, EP); this.Add(null, true, DS, true, SA, EP); this.Add(null, true, DS, true, DA, EP); } } [Theory(DisplayName = "The ushort? array should be converted to hexadecimal-string array that ordered by big-endian.")] [ClassData(typeof(TestData004))] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToHexadecimalStringAsBigEndianBytes))] public void UShortArray( IEnumerable<ushort?> array, bool useSepalator, string sepalator, bool useReplace, string replace, string expect) { if (useSepalator) { if (useReplace) { array.ToHexadecimalStringAsBigEndianBytes(sepalator, replace).Is(expect); } else { array.ToHexadecimalStringAsBigEndianBytes(sepalator).Is(expect); } } else { if (useReplace) { array.ToHexadecimalStringAsBigEndianBytes(nullByteReplacement: replace).Is(expect); } else { array.ToHexadecimalStringAsBigEndianBytes().Is(expect); } } } #endregion #region [ int? ] /// <summary> /// Test Data for int?. /// </summary> class TestData005 : DataGenerator { /// <summary> /// constructor /// </summary> public TestData005() { int?[] array = new int?[] { 1, 0x11223344, null, int.MaxValue, 0 }; this.Add(array, false, NL, false, NL, "00000001112233447FFFFFFF00000000"); this.Add(array, false, NL, true, NL, "00000001112233447FFFFFFF00000000"); this.Add(array, false, NL, true, EP, "00000001112233447FFFFFFF00000000"); this.Add(array, false, NL, true, SA, "0000000111223344****7FFFFFFF00000000"); this.Add(array, false, NL, true, DA, "0000000111223344********7FFFFFFF00000000"); this.Add(array, true, NL, false, NL, "00000001112233447FFFFFFF00000000"); this.Add(array, true, EP, false, NL, "00000001112233447FFFFFFF00000000"); this.Add(array, true, SL, false, NL, "00/00/00/01/11/22/33/44/////7F/FF/FF/FF/00/00/00/00"); this.Add(array, true, DS, false, NL, "00 00 00 01 11 22 33 44 7F FF FF FF 00 00 00 00"); this.Add(array, true, NL, true, NL, "00000001112233447FFFFFFF00000000"); this.Add(array, true, NL, true, EP, "00000001112233447FFFFFFF00000000"); this.Add(array, true, NL, true, SA, "0000000111223344****7FFFFFFF00000000"); this.Add(array, true, NL, true, DA, "0000000111223344********7FFFFFFF00000000"); this.Add(array, true, EP, true, NL, "00000001112233447FFFFFFF00000000"); this.Add(array, true, EP, true, EP, "00000001112233447FFFFFFF00000000"); this.Add(array, true, EP, true, SA, "0000000111223344****7FFFFFFF00000000"); this.Add(array, true, EP, true, DA, "0000000111223344********7FFFFFFF00000000"); this.Add(array, true, SL, true, NL, "00/00/00/01/11/22/33/44/////7F/FF/FF/FF/00/00/00/00"); this.Add(array, true, SL, true, EP, "00/00/00/01/11/22/33/44/////7F/FF/FF/FF/00/00/00/00"); this.Add(array, true, SL, true, SA, "00/00/00/01/11/22/33/44/*/*/*/*/7F/FF/FF/FF/00/00/00/00"); this.Add(array, true, SL, true, DA, "00/00/00/01/11/22/33/44/**/**/**/**/7F/FF/FF/FF/00/00/00/00"); this.Add(array, true, DS, true, NL, "00 00 00 01 11 22 33 44 7F FF FF FF 00 00 00 00"); this.Add(array, true, DS, true, EP, "00 00 00 01 11 22 33 44 7F FF FF FF 00 00 00 00"); this.Add(array, true, DS, true, SA, "00 00 00 01 11 22 33 44 * * * * 7F FF FF FF 00 00 00 00"); this.Add(array, true, DS, true, DA, "00 00 00 01 11 22 33 44 ** ** ** ** 7F FF FF FF 00 00 00 00"); array = new int?[] { 127, }; this.Add(array, false, NL, false, NL, "0000007F"); this.Add(array, false, NL, true, NL, "0000007F"); this.Add(array, false, NL, true, EP, "0000007F"); this.Add(array, false, NL, true, SA, "0000007F"); this.Add(array, false, NL, true, DA, "0000007F"); this.Add(array, true, NL, false, NL, "0000007F"); this.Add(array, true, EP, false, NL, "0000007F"); this.Add(array, true, SL, false, NL, "00/00/00/7F"); this.Add(array, true, DS, false, NL, "00 00 00 7F"); this.Add(array, true, NL, true, NL, "0000007F"); this.Add(array, true, NL, true, EP, "0000007F"); this.Add(array, true, NL, true, SA, "0000007F"); this.Add(array, true, NL, true, DA, "0000007F"); this.Add(array, true, EP, true, NL, "0000007F"); this.Add(array, true, EP, true, EP, "0000007F"); this.Add(array, true, EP, true, SA, "0000007F"); this.Add(array, true, EP, true, DA, "0000007F"); this.Add(array, true, SL, true, NL, "00/00/00/7F"); this.Add(array, true, SL, true, EP, "00/00/00/7F"); this.Add(array, true, SL, true, SA, "00/00/00/7F"); this.Add(array, true, SL, true, DA, "00/00/00/7F"); this.Add(array, true, DS, true, NL, "00 00 00 7F"); this.Add(array, true, DS, true, EP, "00 00 00 7F"); this.Add(array, true, DS, true, SA, "00 00 00 7F"); this.Add(array, true, DS, true, DA, "00 00 00 7F"); array = new int?[] { null, }; this.Add(array, false, NL, false, NL, EP); this.Add(array, false, NL, true, NL, EP); this.Add(array, false, NL, true, EP, EP); this.Add(array, false, NL, true, SA, "****"); this.Add(array, false, NL, true, DA, "********"); this.Add(array, true, NL, false, NL, EP); this.Add(array, true, EP, false, NL, EP); this.Add(array, true, SL, false, NL, "///"); this.Add(array, true, DS, false, NL, " "); this.Add(array, true, NL, true, NL, EP); this.Add(array, true, NL, true, EP, EP); this.Add(array, true, NL, true, SA, "****"); this.Add(array, true, NL, true, DA, "********"); this.Add(array, true, EP, true, NL, EP); this.Add(array, true, EP, true, EP, EP); this.Add(array, true, EP, true, SA, "****"); this.Add(array, true, EP, true, DA, "********"); this.Add(array, true, SL, true, NL, "///"); this.Add(array, true, SL, true, EP, "///"); this.Add(array, true, SL, true, SA, "*/*/*/*"); this.Add(array, true, SL, true, DA, "**/**/**/**"); this.Add(array, true, DS, true, NL, " "); this.Add(array, true, DS, true, EP, " "); this.Add(array, true, DS, true, SA, "* * * *"); this.Add(array, true, DS, true, DA, "** ** ** **"); array = new int?[] { }; this.Add(array, false, NL, false, NL, EP); this.Add(array, false, NL, true, NL, EP); this.Add(array, false, NL, true, EP, EP); this.Add(array, false, NL, true, SA, EP); this.Add(array, false, NL, true, DA, EP); this.Add(array, true, NL, false, NL, EP); this.Add(array, true, EP, false, NL, EP); this.Add(array, true, SL, false, NL, EP); this.Add(array, true, DS, false, NL, EP); this.Add(array, true, NL, true, NL, EP); this.Add(array, true, NL, true, EP, EP); this.Add(array, true, NL, true, SA, EP); this.Add(array, true, NL, true, DA, EP); this.Add(array, true, EP, true, NL, EP); this.Add(array, true, EP, true, EP, EP); this.Add(array, true, EP, true, SA, EP); this.Add(array, true, EP, true, DA, EP); this.Add(array, true, SL, true, NL, EP); this.Add(array, true, SL, true, EP, EP); this.Add(array, true, SL, true, SA, EP); this.Add(array, true, SL, true, DA, EP); this.Add(array, true, DS, true, NL, EP); this.Add(array, true, DS, true, EP, EP); this.Add(array, true, DS, true, SA, EP); this.Add(array, true, DS, true, DA, EP); this.Add(null, false, NL, false, NL, EP); this.Add(null, false, NL, true, NL, EP); this.Add(null, false, NL, true, EP, EP); this.Add(null, false, NL, true, SA, EP); this.Add(null, false, NL, true, DA, EP); this.Add(null, true, NL, false, NL, EP); this.Add(null, true, EP, false, NL, EP); this.Add(null, true, SL, false, NL, EP); this.Add(null, true, DS, false, NL, EP); this.Add(null, true, NL, true, NL, EP); this.Add(null, true, NL, true, EP, EP); this.Add(null, true, NL, true, SA, EP); this.Add(null, true, NL, true, DA, EP); this.Add(null, true, EP, true, NL, EP); this.Add(null, true, EP, true, EP, EP); this.Add(null, true, EP, true, SA, EP); this.Add(null, true, EP, true, DA, EP); this.Add(null, true, SL, true, NL, EP); this.Add(null, true, SL, true, EP, EP); this.Add(null, true, SL, true, SA, EP); this.Add(null, true, SL, true, DA, EP); this.Add(null, true, DS, true, NL, EP); this.Add(null, true, DS, true, EP, EP); this.Add(null, true, DS, true, SA, EP); this.Add(null, true, DS, true, DA, EP); } } [Theory(DisplayName = "The int? array should be converted to hexadecimal-string array that ordered by big-endian.")] [ClassData(typeof(TestData005))] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToHexadecimalStringAsBigEndianBytes))] public void IntArray( IEnumerable<int?> array, bool useSepalator, string sepalator, bool useReplace, string replace, string expect) { if (useSepalator) { if (useReplace) { array.ToHexadecimalStringAsBigEndianBytes(sepalator, replace).Is(expect); } else { array.ToHexadecimalStringAsBigEndianBytes(sepalator).Is(expect); } } else { if (useReplace) { array.ToHexadecimalStringAsBigEndianBytes(nullByteReplacement: replace).Is(expect); } else { array.ToHexadecimalStringAsBigEndianBytes().Is(expect); } } } #endregion #region [ uint? ] /// <summary> /// Test Data for uint?. /// </summary> class TestData006 : DataGenerator { /// <summary> /// constructor /// </summary> public TestData006() { uint?[] array = new uint?[] { 1, 0x11223344, null, int.MaxValue, 0 }; this.Add(array, false, NL, false, NL, "00000001112233447FFFFFFF00000000"); this.Add(array, false, NL, true, NL, "00000001112233447FFFFFFF00000000"); this.Add(array, false, NL, true, EP, "00000001112233447FFFFFFF00000000"); this.Add(array, false, NL, true, SA, "0000000111223344****7FFFFFFF00000000"); this.Add(array, false, NL, true, DA, "0000000111223344********7FFFFFFF00000000"); this.Add(array, true, NL, false, NL, "00000001112233447FFFFFFF00000000"); this.Add(array, true, EP, false, NL, "00000001112233447FFFFFFF00000000"); this.Add(array, true, SL, false, NL, "00/00/00/01/11/22/33/44/////7F/FF/FF/FF/00/00/00/00"); this.Add(array, true, DS, false, NL, "00 00 00 01 11 22 33 44 7F FF FF FF 00 00 00 00"); this.Add(array, true, NL, true, NL, "00000001112233447FFFFFFF00000000"); this.Add(array, true, NL, true, EP, "00000001112233447FFFFFFF00000000"); this.Add(array, true, NL, true, SA, "0000000111223344****7FFFFFFF00000000"); this.Add(array, true, NL, true, DA, "0000000111223344********7FFFFFFF00000000"); this.Add(array, true, EP, true, NL, "00000001112233447FFFFFFF00000000"); this.Add(array, true, EP, true, EP, "00000001112233447FFFFFFF00000000"); this.Add(array, true, EP, true, SA, "0000000111223344****7FFFFFFF00000000"); this.Add(array, true, EP, true, DA, "0000000111223344********7FFFFFFF00000000"); this.Add(array, true, SL, true, NL, "00/00/00/01/11/22/33/44/////7F/FF/FF/FF/00/00/00/00"); this.Add(array, true, SL, true, EP, "00/00/00/01/11/22/33/44/////7F/FF/FF/FF/00/00/00/00"); this.Add(array, true, SL, true, SA, "00/00/00/01/11/22/33/44/*/*/*/*/7F/FF/FF/FF/00/00/00/00"); this.Add(array, true, SL, true, DA, "00/00/00/01/11/22/33/44/**/**/**/**/7F/FF/FF/FF/00/00/00/00"); this.Add(array, true, DS, true, NL, "00 00 00 01 11 22 33 44 7F FF FF FF 00 00 00 00"); this.Add(array, true, DS, true, EP, "00 00 00 01 11 22 33 44 7F FF FF FF 00 00 00 00"); this.Add(array, true, DS, true, SA, "00 00 00 01 11 22 33 44 * * * * 7F FF FF FF 00 00 00 00"); this.Add(array, true, DS, true, DA, "00 00 00 01 11 22 33 44 ** ** ** ** 7F FF FF FF 00 00 00 00"); array = new uint?[] { 127, }; this.Add(array, false, NL, false, NL, "0000007F"); this.Add(array, false, NL, true, NL, "0000007F"); this.Add(array, false, NL, true, EP, "0000007F"); this.Add(array, false, NL, true, SA, "0000007F"); this.Add(array, false, NL, true, DA, "0000007F"); this.Add(array, true, NL, false, NL, "0000007F"); this.Add(array, true, EP, false, NL, "0000007F"); this.Add(array, true, SL, false, NL, "00/00/00/7F"); this.Add(array, true, DS, false, NL, "00 00 00 7F"); this.Add(array, true, NL, true, NL, "0000007F"); this.Add(array, true, NL, true, EP, "0000007F"); this.Add(array, true, NL, true, SA, "0000007F"); this.Add(array, true, NL, true, DA, "0000007F"); this.Add(array, true, EP, true, NL, "0000007F"); this.Add(array, true, EP, true, EP, "0000007F"); this.Add(array, true, EP, true, SA, "0000007F"); this.Add(array, true, EP, true, DA, "0000007F"); this.Add(array, true, SL, true, NL, "00/00/00/7F"); this.Add(array, true, SL, true, EP, "00/00/00/7F"); this.Add(array, true, SL, true, SA, "00/00/00/7F"); this.Add(array, true, SL, true, DA, "00/00/00/7F"); this.Add(array, true, DS, true, NL, "00 00 00 7F"); this.Add(array, true, DS, true, EP, "00 00 00 7F"); this.Add(array, true, DS, true, SA, "00 00 00 7F"); this.Add(array, true, DS, true, DA, "00 00 00 7F"); array = new uint?[] { null, }; this.Add(array, false, NL, false, NL, EP); this.Add(array, false, NL, true, NL, EP); this.Add(array, false, NL, true, EP, EP); this.Add(array, false, NL, true, SA, "****"); this.Add(array, false, NL, true, DA, "********"); this.Add(array, true, NL, false, NL, EP); this.Add(array, true, EP, false, NL, EP); this.Add(array, true, SL, false, NL, "///"); this.Add(array, true, DS, false, NL, " "); this.Add(array, true, NL, true, NL, EP); this.Add(array, true, NL, true, EP, EP); this.Add(array, true, NL, true, SA, "****"); this.Add(array, true, NL, true, DA, "********"); this.Add(array, true, EP, true, NL, EP); this.Add(array, true, EP, true, EP, EP); this.Add(array, true, EP, true, SA, "****"); this.Add(array, true, EP, true, DA, "********"); this.Add(array, true, SL, true, NL, "///"); this.Add(array, true, SL, true, EP, "///"); this.Add(array, true, SL, true, SA, "*/*/*/*"); this.Add(array, true, SL, true, DA, "**/**/**/**"); this.Add(array, true, DS, true, NL, " "); this.Add(array, true, DS, true, EP, " "); this.Add(array, true, DS, true, SA, "* * * *"); this.Add(array, true, DS, true, DA, "** ** ** **"); array = new uint?[] { }; this.Add(array, false, NL, false, NL, EP); this.Add(array, false, NL, true, NL, EP); this.Add(array, false, NL, true, EP, EP); this.Add(array, false, NL, true, SA, EP); this.Add(array, false, NL, true, DA, EP); this.Add(array, true, NL, false, NL, EP); this.Add(array, true, EP, false, NL, EP); this.Add(array, true, SL, false, NL, EP); this.Add(array, true, DS, false, NL, EP); this.Add(array, true, NL, true, NL, EP); this.Add(array, true, NL, true, EP, EP); this.Add(array, true, NL, true, SA, EP); this.Add(array, true, NL, true, DA, EP); this.Add(array, true, EP, true, NL, EP); this.Add(array, true, EP, true, EP, EP); this.Add(array, true, EP, true, SA, EP); this.Add(array, true, EP, true, DA, EP); this.Add(array, true, SL, true, NL, EP); this.Add(array, true, SL, true, EP, EP); this.Add(array, true, SL, true, SA, EP); this.Add(array, true, SL, true, DA, EP); this.Add(array, true, DS, true, NL, EP); this.Add(array, true, DS, true, EP, EP); this.Add(array, true, DS, true, SA, EP); this.Add(array, true, DS, true, DA, EP); this.Add(null, false, NL, false, NL, EP); this.Add(null, false, NL, true, NL, EP); this.Add(null, false, NL, true, EP, EP); this.Add(null, false, NL, true, SA, EP); this.Add(null, false, NL, true, DA, EP); this.Add(null, true, NL, false, NL, EP); this.Add(null, true, EP, false, NL, EP); this.Add(null, true, SL, false, NL, EP); this.Add(null, true, DS, false, NL, EP); this.Add(null, true, NL, true, NL, EP); this.Add(null, true, NL, true, EP, EP); this.Add(null, true, NL, true, SA, EP); this.Add(null, true, NL, true, DA, EP); this.Add(null, true, EP, true, NL, EP); this.Add(null, true, EP, true, EP, EP); this.Add(null, true, EP, true, SA, EP); this.Add(null, true, EP, true, DA, EP); this.Add(null, true, SL, true, NL, EP); this.Add(null, true, SL, true, EP, EP); this.Add(null, true, SL, true, SA, EP); this.Add(null, true, SL, true, DA, EP); this.Add(null, true, DS, true, NL, EP); this.Add(null, true, DS, true, EP, EP); this.Add(null, true, DS, true, SA, EP); this.Add(null, true, DS, true, DA, EP); } } [Theory(DisplayName = "The uint? array should be converted to hexadecimal-string array that ordered by big-endian.")] [ClassData(typeof(TestData006))] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToHexadecimalStringAsBigEndianBytes))] public void UIntArray( IEnumerable<uint?> array, bool useSepalator, string sepalator, bool useReplace, string replace, string expect) { if (useSepalator) { if (useReplace) { array.ToHexadecimalStringAsBigEndianBytes(sepalator, replace).Is(expect); } else { array.ToHexadecimalStringAsBigEndianBytes(sepalator).Is(expect); } } else { if (useReplace) { array.ToHexadecimalStringAsBigEndianBytes(nullByteReplacement: replace).Is(expect); } else { array.ToHexadecimalStringAsBigEndianBytes().Is(expect); } } } #endregion #region [ long? ] /// <summary> /// Test Data for long?. /// </summary> class TestData007 : DataGenerator { /// <summary> /// constructor /// </summary> public TestData007() { long?[] array = new long?[] { 1, 0x1122334455667788, null, long.MaxValue, long.MinValue }; this.Add(array, false, NL, false, NL, "000000000000000111223344556677887FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, false, NL, true, NL, "000000000000000111223344556677887FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, false, NL, true, EP, "000000000000000111223344556677887FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, false, NL, true, SA, "00000000000000011122334455667788********7FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, false, NL, true, DA, "00000000000000011122334455667788****************7FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, true, NL, false, NL, "000000000000000111223344556677887FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, true, EP, false, NL, "000000000000000111223344556677887FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, true, SL, false, NL, "00/00/00/00/00/00/00/01/11/22/33/44/55/66/77/88/////////7F/FF/FF/FF/FF/FF/FF/FF/80/00/00/00/00/00/00/00"); this.Add(array, true, DS, false, NL, "00 00 00 00 00 00 00 01 11 22 33 44 55 66 77 88 7F FF FF FF FF FF FF FF 80 00 00 00 00 00 00 00"); this.Add(array, true, NL, true, NL, "000000000000000111223344556677887FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, true, NL, true, EP, "000000000000000111223344556677887FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, true, NL, true, SA, "00000000000000011122334455667788********7FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, true, NL, true, DA, "00000000000000011122334455667788****************7FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, true, EP, true, NL, "000000000000000111223344556677887FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, true, EP, true, EP, "000000000000000111223344556677887FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, true, EP, true, SA, "00000000000000011122334455667788********7FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, true, EP, true, DA, "00000000000000011122334455667788****************7FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, true, SL, true, NL, "00/00/00/00/00/00/00/01/11/22/33/44/55/66/77/88/////////7F/FF/FF/FF/FF/FF/FF/FF/80/00/00/00/00/00/00/00"); this.Add(array, true, SL, true, EP, "00/00/00/00/00/00/00/01/11/22/33/44/55/66/77/88/////////7F/FF/FF/FF/FF/FF/FF/FF/80/00/00/00/00/00/00/00"); this.Add(array, true, SL, true, SA, "00/00/00/00/00/00/00/01/11/22/33/44/55/66/77/88/*/*/*/*/*/*/*/*/7F/FF/FF/FF/FF/FF/FF/FF/80/00/00/00/00/00/00/00"); this.Add(array, true, SL, true, DA, "00/00/00/00/00/00/00/01/11/22/33/44/55/66/77/88/**/**/**/**/**/**/**/**/7F/FF/FF/FF/FF/FF/FF/FF/80/00/00/00/00/00/00/00"); this.Add(array, true, DS, true, NL, "00 00 00 00 00 00 00 01 11 22 33 44 55 66 77 88 7F FF FF FF FF FF FF FF 80 00 00 00 00 00 00 00"); this.Add(array, true, DS, true, EP, "00 00 00 00 00 00 00 01 11 22 33 44 55 66 77 88 7F FF FF FF FF FF FF FF 80 00 00 00 00 00 00 00"); this.Add(array, true, DS, true, SA, "00 00 00 00 00 00 00 01 11 22 33 44 55 66 77 88 * * * * * * * * 7F FF FF FF FF FF FF FF 80 00 00 00 00 00 00 00"); this.Add(array, true, DS, true, DA, "00 00 00 00 00 00 00 01 11 22 33 44 55 66 77 88 ** ** ** ** ** ** ** ** 7F FF FF FF FF FF FF FF 80 00 00 00 00 00 00 00"); array = new long?[] { 127, }; this.Add(array, false, NL, false, NL, "000000000000007F"); this.Add(array, false, NL, true, NL, "000000000000007F"); this.Add(array, false, NL, true, EP, "000000000000007F"); this.Add(array, false, NL, true, SA, "000000000000007F"); this.Add(array, false, NL, true, DA, "000000000000007F"); this.Add(array, true, NL, false, NL, "000000000000007F"); this.Add(array, true, EP, false, NL, "000000000000007F"); this.Add(array, true, SL, false, NL, "00/00/00/00/00/00/00/7F"); this.Add(array, true, DS, false, NL, "00 00 00 00 00 00 00 7F"); this.Add(array, true, NL, true, NL, "000000000000007F"); this.Add(array, true, NL, true, EP, "000000000000007F"); this.Add(array, true, NL, true, SA, "000000000000007F"); this.Add(array, true, NL, true, DA, "000000000000007F"); this.Add(array, true, EP, true, NL, "000000000000007F"); this.Add(array, true, EP, true, EP, "000000000000007F"); this.Add(array, true, EP, true, SA, "000000000000007F"); this.Add(array, true, EP, true, DA, "000000000000007F"); this.Add(array, true, SL, true, NL, "00/00/00/00/00/00/00/7F"); this.Add(array, true, SL, true, EP, "00/00/00/00/00/00/00/7F"); this.Add(array, true, SL, true, SA, "00/00/00/00/00/00/00/7F"); this.Add(array, true, SL, true, DA, "00/00/00/00/00/00/00/7F"); this.Add(array, true, DS, true, NL, "00 00 00 00 00 00 00 7F"); this.Add(array, true, DS, true, EP, "00 00 00 00 00 00 00 7F"); this.Add(array, true, DS, true, SA, "00 00 00 00 00 00 00 7F"); this.Add(array, true, DS, true, DA, "00 00 00 00 00 00 00 7F"); array = new long?[] { null, }; this.Add(array, false, NL, false, NL, EP); this.Add(array, false, NL, true, NL, EP); this.Add(array, false, NL, true, EP, EP); this.Add(array, false, NL, true, SA, "********"); this.Add(array, false, NL, true, DA, "****************"); this.Add(array, true, NL, false, NL, EP); this.Add(array, true, EP, false, NL, EP); this.Add(array, true, SL, false, NL, "///////"); this.Add(array, true, DS, false, NL, " "); this.Add(array, true, NL, true, NL, EP); this.Add(array, true, NL, true, EP, EP); this.Add(array, true, NL, true, SA, "********"); this.Add(array, true, NL, true, DA, "****************"); this.Add(array, true, EP, true, NL, EP); this.Add(array, true, EP, true, EP, EP); this.Add(array, true, EP, true, SA, "********"); this.Add(array, true, EP, true, DA, "****************"); this.Add(array, true, SL, true, NL, "///////"); this.Add(array, true, SL, true, EP, "///////"); this.Add(array, true, SL, true, SA, "*/*/*/*/*/*/*/*"); this.Add(array, true, SL, true, DA, "**/**/**/**/**/**/**/**"); this.Add(array, true, DS, true, NL, " "); this.Add(array, true, DS, true, EP, " "); this.Add(array, true, DS, true, SA, "* * * * * * * *"); this.Add(array, true, DS, true, DA, "** ** ** ** ** ** ** **"); array = new long?[] { }; this.Add(array, false, NL, false, NL, EP); this.Add(array, false, NL, true, NL, EP); this.Add(array, false, NL, true, EP, EP); this.Add(array, false, NL, true, SA, EP); this.Add(array, false, NL, true, DA, EP); this.Add(array, true, NL, false, NL, EP); this.Add(array, true, EP, false, NL, EP); this.Add(array, true, SL, false, NL, EP); this.Add(array, true, DS, false, NL, EP); this.Add(array, true, NL, true, NL, EP); this.Add(array, true, NL, true, EP, EP); this.Add(array, true, NL, true, SA, EP); this.Add(array, true, NL, true, DA, EP); this.Add(array, true, EP, true, NL, EP); this.Add(array, true, EP, true, EP, EP); this.Add(array, true, EP, true, SA, EP); this.Add(array, true, EP, true, DA, EP); this.Add(array, true, SL, true, NL, EP); this.Add(array, true, SL, true, EP, EP); this.Add(array, true, SL, true, SA, EP); this.Add(array, true, SL, true, DA, EP); this.Add(array, true, DS, true, NL, EP); this.Add(array, true, DS, true, EP, EP); this.Add(array, true, DS, true, SA, EP); this.Add(array, true, DS, true, DA, EP); this.Add(null, false, NL, false, NL, EP); this.Add(null, false, NL, true, NL, EP); this.Add(null, false, NL, true, EP, EP); this.Add(null, false, NL, true, SA, EP); this.Add(null, false, NL, true, DA, EP); this.Add(null, true, NL, false, NL, EP); this.Add(null, true, EP, false, NL, EP); this.Add(null, true, SL, false, NL, EP); this.Add(null, true, DS, false, NL, EP); this.Add(null, true, NL, true, NL, EP); this.Add(null, true, NL, true, EP, EP); this.Add(null, true, NL, true, SA, EP); this.Add(null, true, NL, true, DA, EP); this.Add(null, true, EP, true, NL, EP); this.Add(null, true, EP, true, EP, EP); this.Add(null, true, EP, true, SA, EP); this.Add(null, true, EP, true, DA, EP); this.Add(null, true, SL, true, NL, EP); this.Add(null, true, SL, true, EP, EP); this.Add(null, true, SL, true, SA, EP); this.Add(null, true, SL, true, DA, EP); this.Add(null, true, DS, true, NL, EP); this.Add(null, true, DS, true, EP, EP); this.Add(null, true, DS, true, SA, EP); this.Add(null, true, DS, true, DA, EP); } } [Theory(DisplayName = "The long? array should be converted to hexadecimal-string array that ordered by big-endian.")] [ClassData(typeof(TestData007))] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToHexadecimalStringAsBigEndianBytes))] public void LongArray( IEnumerable<long?> array, bool useSepalator, string sepalator, bool useReplace, string replace, string expect) { if (useSepalator) { if (useReplace) { array.ToHexadecimalStringAsBigEndianBytes(sepalator, replace).Is(expect); } else { array.ToHexadecimalStringAsBigEndianBytes(sepalator).Is(expect); } } else { if (useReplace) { array.ToHexadecimalStringAsBigEndianBytes(nullByteReplacement: replace).Is(expect); } else { array.ToHexadecimalStringAsBigEndianBytes().Is(expect); } } } #endregion #region [ ulong? ] /// <summary> /// Test Data for ulong?. /// </summary> class TestData008 : DataGenerator { /// <summary> /// constructor /// </summary> public TestData008() { ulong?[] array = new ulong?[] { 1, 0x1122334455667788, null, long.MaxValue, (ulong)long.MaxValue + 1 }; this.Add(array, false, NL, false, NL, "000000000000000111223344556677887FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, false, NL, true, NL, "000000000000000111223344556677887FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, false, NL, true, EP, "000000000000000111223344556677887FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, false, NL, true, SA, "00000000000000011122334455667788********7FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, false, NL, true, DA, "00000000000000011122334455667788****************7FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, true, NL, false, NL, "000000000000000111223344556677887FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, true, EP, false, NL, "000000000000000111223344556677887FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, true, SL, false, NL, "00/00/00/00/00/00/00/01/11/22/33/44/55/66/77/88/////////7F/FF/FF/FF/FF/FF/FF/FF/80/00/00/00/00/00/00/00"); this.Add(array, true, DS, false, NL, "00 00 00 00 00 00 00 01 11 22 33 44 55 66 77 88 7F FF FF FF FF FF FF FF 80 00 00 00 00 00 00 00"); this.Add(array, true, NL, true, NL, "000000000000000111223344556677887FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, true, NL, true, EP, "000000000000000111223344556677887FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, true, NL, true, SA, "00000000000000011122334455667788********7FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, true, NL, true, DA, "00000000000000011122334455667788****************7FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, true, EP, true, NL, "000000000000000111223344556677887FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, true, EP, true, EP, "000000000000000111223344556677887FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, true, EP, true, SA, "00000000000000011122334455667788********7FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, true, EP, true, DA, "00000000000000011122334455667788****************7FFFFFFFFFFFFFFF8000000000000000"); this.Add(array, true, SL, true, NL, "00/00/00/00/00/00/00/01/11/22/33/44/55/66/77/88/////////7F/FF/FF/FF/FF/FF/FF/FF/80/00/00/00/00/00/00/00"); this.Add(array, true, SL, true, EP, "00/00/00/00/00/00/00/01/11/22/33/44/55/66/77/88/////////7F/FF/FF/FF/FF/FF/FF/FF/80/00/00/00/00/00/00/00"); this.Add(array, true, SL, true, SA, "00/00/00/00/00/00/00/01/11/22/33/44/55/66/77/88/*/*/*/*/*/*/*/*/7F/FF/FF/FF/FF/FF/FF/FF/80/00/00/00/00/00/00/00"); this.Add(array, true, SL, true, DA, "00/00/00/00/00/00/00/01/11/22/33/44/55/66/77/88/**/**/**/**/**/**/**/**/7F/FF/FF/FF/FF/FF/FF/FF/80/00/00/00/00/00/00/00"); this.Add(array, true, DS, true, NL, "00 00 00 00 00 00 00 01 11 22 33 44 55 66 77 88 7F FF FF FF FF FF FF FF 80 00 00 00 00 00 00 00"); this.Add(array, true, DS, true, EP, "00 00 00 00 00 00 00 01 11 22 33 44 55 66 77 88 7F FF FF FF FF FF FF FF 80 00 00 00 00 00 00 00"); this.Add(array, true, DS, true, SA, "00 00 00 00 00 00 00 01 11 22 33 44 55 66 77 88 * * * * * * * * 7F FF FF FF FF FF FF FF 80 00 00 00 00 00 00 00"); this.Add(array, true, DS, true, DA, "00 00 00 00 00 00 00 01 11 22 33 44 55 66 77 88 ** ** ** ** ** ** ** ** 7F FF FF FF FF FF FF FF 80 00 00 00 00 00 00 00"); array = new ulong?[] { 127, }; this.Add(array, false, NL, false, NL, "000000000000007F"); this.Add(array, false, NL, true, NL, "000000000000007F"); this.Add(array, false, NL, true, EP, "000000000000007F"); this.Add(array, false, NL, true, SA, "000000000000007F"); this.Add(array, false, NL, true, DA, "000000000000007F"); this.Add(array, true, NL, false, NL, "000000000000007F"); this.Add(array, true, EP, false, NL, "000000000000007F"); this.Add(array, true, SL, false, NL, "00/00/00/00/00/00/00/7F"); this.Add(array, true, DS, false, NL, "00 00 00 00 00 00 00 7F"); this.Add(array, true, NL, true, NL, "000000000000007F"); this.Add(array, true, NL, true, EP, "000000000000007F"); this.Add(array, true, NL, true, SA, "000000000000007F"); this.Add(array, true, NL, true, DA, "000000000000007F"); this.Add(array, true, EP, true, NL, "000000000000007F"); this.Add(array, true, EP, true, EP, "000000000000007F"); this.Add(array, true, EP, true, SA, "000000000000007F"); this.Add(array, true, EP, true, DA, "000000000000007F"); this.Add(array, true, SL, true, NL, "00/00/00/00/00/00/00/7F"); this.Add(array, true, SL, true, EP, "00/00/00/00/00/00/00/7F"); this.Add(array, true, SL, true, SA, "00/00/00/00/00/00/00/7F"); this.Add(array, true, SL, true, DA, "00/00/00/00/00/00/00/7F"); this.Add(array, true, DS, true, NL, "00 00 00 00 00 00 00 7F"); this.Add(array, true, DS, true, EP, "00 00 00 00 00 00 00 7F"); this.Add(array, true, DS, true, SA, "00 00 00 00 00 00 00 7F"); this.Add(array, true, DS, true, DA, "00 00 00 00 00 00 00 7F"); array = new ulong?[] { null, }; this.Add(array, false, NL, false, NL, EP); this.Add(array, false, NL, true, NL, EP); this.Add(array, false, NL, true, EP, EP); this.Add(array, false, NL, true, SA, "********"); this.Add(array, false, NL, true, DA, "****************"); this.Add(array, true, NL, false, NL, EP); this.Add(array, true, EP, false, NL, EP); this.Add(array, true, SL, false, NL, "///////"); this.Add(array, true, DS, false, NL, " "); this.Add(array, true, NL, true, NL, EP); this.Add(array, true, NL, true, EP, EP); this.Add(array, true, NL, true, SA, "********"); this.Add(array, true, NL, true, DA, "****************"); this.Add(array, true, EP, true, NL, EP); this.Add(array, true, EP, true, EP, EP); this.Add(array, true, EP, true, SA, "********"); this.Add(array, true, EP, true, DA, "****************"); this.Add(array, true, SL, true, NL, "///////"); this.Add(array, true, SL, true, EP, "///////"); this.Add(array, true, SL, true, SA, "*/*/*/*/*/*/*/*"); this.Add(array, true, SL, true, DA, "**/**/**/**/**/**/**/**"); this.Add(array, true, DS, true, NL, " "); this.Add(array, true, DS, true, EP, " "); this.Add(array, true, DS, true, SA, "* * * * * * * *"); this.Add(array, true, DS, true, DA, "** ** ** ** ** ** ** **"); array = new ulong?[] { }; this.Add(array, false, NL, false, NL, EP); this.Add(array, false, NL, true, NL, EP); this.Add(array, false, NL, true, EP, EP); this.Add(array, false, NL, true, SA, EP); this.Add(array, false, NL, true, DA, EP); this.Add(array, true, NL, false, NL, EP); this.Add(array, true, EP, false, NL, EP); this.Add(array, true, SL, false, NL, EP); this.Add(array, true, DS, false, NL, EP); this.Add(array, true, NL, true, NL, EP); this.Add(array, true, NL, true, EP, EP); this.Add(array, true, NL, true, SA, EP); this.Add(array, true, NL, true, DA, EP); this.Add(array, true, EP, true, NL, EP); this.Add(array, true, EP, true, EP, EP); this.Add(array, true, EP, true, SA, EP); this.Add(array, true, EP, true, DA, EP); this.Add(array, true, SL, true, NL, EP); this.Add(array, true, SL, true, EP, EP); this.Add(array, true, SL, true, SA, EP); this.Add(array, true, SL, true, DA, EP); this.Add(array, true, DS, true, NL, EP); this.Add(array, true, DS, true, EP, EP); this.Add(array, true, DS, true, SA, EP); this.Add(array, true, DS, true, DA, EP); this.Add(null, false, NL, false, NL, EP); this.Add(null, false, NL, true, NL, EP); this.Add(null, false, NL, true, EP, EP); this.Add(null, false, NL, true, SA, EP); this.Add(null, false, NL, true, DA, EP); this.Add(null, true, NL, false, NL, EP); this.Add(null, true, EP, false, NL, EP); this.Add(null, true, SL, false, NL, EP); this.Add(null, true, DS, false, NL, EP); this.Add(null, true, NL, true, NL, EP); this.Add(null, true, NL, true, EP, EP); this.Add(null, true, NL, true, SA, EP); this.Add(null, true, NL, true, DA, EP); this.Add(null, true, EP, true, NL, EP); this.Add(null, true, EP, true, EP, EP); this.Add(null, true, EP, true, SA, EP); this.Add(null, true, EP, true, DA, EP); this.Add(null, true, SL, true, NL, EP); this.Add(null, true, SL, true, EP, EP); this.Add(null, true, SL, true, SA, EP); this.Add(null, true, SL, true, DA, EP); this.Add(null, true, DS, true, NL, EP); this.Add(null, true, DS, true, EP, EP); this.Add(null, true, DS, true, SA, EP); this.Add(null, true, DS, true, DA, EP); } } [Theory(DisplayName = "The ulong? array should be converted to hexadecimal-string array that ordered by big-endian.")] [ClassData(typeof(TestData008))] [Trait(nameof(ValueConvertExtensions), nameof(ValueConvertExtensions.ToHexadecimalStringAsBigEndianBytes))] public void ULongArray( IEnumerable<ulong?> array, bool useSepalator, string sepalator, bool useReplace, string replace, string expect) { if (useSepalator) { if (useReplace) { array.ToHexadecimalStringAsBigEndianBytes(sepalator, replace).Is(expect); } else { array.ToHexadecimalStringAsBigEndianBytes(sepalator).Is(expect); } } else { if (useReplace) { array.ToHexadecimalStringAsBigEndianBytes(nullByteReplacement: replace).Is(expect); } else { array.ToHexadecimalStringAsBigEndianBytes().Is(expect); } } } #endregion } #endregion }
45.627794
215
0.492034
[ "MIT" ]
yamasimoncini/MinimalTools.Essentials
MinimalTools.Essentials.Test/Extensions/Convert/ValueConvertExtensions.cs
122,465
C#
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. //---------------------------------------------------------------- namespace Microsoft.Azure.NotificationHubs { using System; using System.Collections.Generic; using Newtonsoft.Json; /// <summary> /// Represents a template notification. /// </summary> public sealed class TemplateNotification : Notification { IDictionary<string, string> templateProperties; /// <summary> /// Initializes a new instance of the <see cref="T:Microsoft.Azure.NotificationHubs.TemplateNotification" /> class. /// </summary> /// <param name="templateProperties">The template properties.</param> /// <exception cref="System.ArgumentNullException">properties</exception> public TemplateNotification(IDictionary<string, string> templateProperties) : base(null, null) { if (templateProperties == null) { throw new ArgumentNullException("properties"); } this.templateProperties = templateProperties; } /// <summary> /// Initializes a new instance of the <see cref="T:Microsoft.Azure.NotificationHubs.TemplateNotification" /> class. /// </summary> /// <param name="templateProperties">The template properties.</param> /// <param name="tag">The notification tag.</param> /// <exception cref="System.ArgumentNullException">properties</exception> [Obsolete("This method is obsolete.")] public TemplateNotification(IDictionary<string, string> templateProperties, string tag) : base(null, tag) { if (templateProperties == null) { throw new ArgumentNullException("properties"); } this.templateProperties = templateProperties; } /// <summary> /// Gets the type of the platform. /// </summary> /// <value> /// The type of the platform. /// </value> protected override string PlatformType { get { return RegistrationDescription.TemplateRegistrationType; } } /// <summary> /// Validate and populates the headers. /// </summary> protected override void OnValidateAndPopulateHeaders() { this.Body = JsonConvert.SerializeObject(this.templateProperties); } } }
36.164384
123
0.580682
[ "MIT" ]
4or5trees/azure-notificationhubs-dotnet
src/Microsoft.Azure.NotificationHubs/TemplateNotification.cs
2,642
C#
// 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 Moq; using Xunit; namespace Microsoft.VisualStudio.ProjectSystem.VS.PropertyPages { public class BuildMacroInfoTests { [Theory] [InlineData("MyBuildMacro", "MyBuildMacroValue", VSConstants.S_OK)] [InlineData("NonExistantMacro", "", VSConstants.E_FAIL)] public void GetBuildMacroValue(string macroName, string expectedValue, int expectedRetVal) { var projectProperties = IProjectPropertiesFactory.CreateWithPropertyAndValue("MyBuildMacro", "MyBuildMacroValue"); var propertiesProvider = IProjectPropertiesProviderFactory.Create(commonProps: projectProperties); var configuredProjectServices = Mock.Of<ConfiguredProjectServices>(o => o.ProjectPropertiesProvider == propertiesProvider); var configuredProject = ConfiguredProjectFactory.Create(services: configuredProjectServices); var buildMacroInfo = CreateInstance(configuredProject); int retVal = buildMacroInfo.GetBuildMacroValue(macroName, out string? macroValue); Assert.Equal(expectedRetVal, retVal); Assert.Equal(expectedValue, macroValue); } [Fact] public void GetBuildMacroValue_WhenDisposed_ReturnsUnexpected() { var buildMacroInfo = CreateInstance(); buildMacroInfo.Dispose(); var result = buildMacroInfo.GetBuildMacroValue("Macro", out _); Assert.Equal(VSConstants.E_UNEXPECTED, result); } private static BuildMacroInfo CreateInstance(ConfiguredProject? configuredProject = null) { configuredProject ??= ConfiguredProjectFactory.Create(); var threadingService = IProjectThreadingServiceFactory.Create(); return new BuildMacroInfo(ActiveConfiguredProjectFactory.ImplementValue(() => configuredProject), threadingService); } } }
44.229167
162
0.685822
[ "Apache-2.0" ]
MSLukeWest/project-system
tests/Microsoft.VisualStudio.ProjectSystem.Managed.VS.UnitTests/ProjectSystem/VS/PropertyPages/BuildMacroInfoTests.cs
2,078
C#
namespace Microsoft.CodeAnalysis { /// <summary> /// Resolves references to metadata specified in the source (#r directives). /// </summary> public abstract class MetadataReferenceResolver { public abstract override bool Equals(object other); public abstract override int GetHashCode(); public abstract string ResolveReference(string reference, string baseFilePath); } }
32.307692
87
0.702381
[ "Apache-2.0" ]
semihokur/pattern-matching-csharp
Src/Compilers/Core/Portable/MetadataReference/MetadataReferenceResolver.cs
422
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PicDemo { public class GoogleCoordinate { //经度到像素X值 public static double lngToPixel(double lng, int zoom) { return (lng + 180) * (256L << zoom) / 360; } //像素X到经度 public static double pixelToLng(double pixelX, int zoom) { return pixelX * 360 / (256L << zoom) - 180; } //纬度到像素Y public static double latToPixel(double lat, int zoom) { double siny = Math.Sin(lat * Math.PI / 180); double y = Math.Log((1 + siny) / (1 - siny)); return (128 << zoom) * (1 - y / (2 * Math.PI)); } //像素Y到纬度 public static double pixelToLat(double pixelY, int zoom) { double y = 2 * Math.PI * (1 - pixelY / (128 << zoom)); double z = Math.Pow(Math.E, y); double siny = (z - 1) / (z + 1); return Math.Asin(siny) * 180 / Math.PI; } } }
26.833333
67
0.472937
[ "MIT" ]
gong-1997/GITD-IEA
PicDemo/PicDemo/GoogleCoordinate.cs
1,171
C#
using System; using Remora.Discord.Core; namespace Accord.Bot.Helpers { public static class DiscordFormatter { // https://discord.com/developers/docs/reference#message-formatting public static string UserIdToMention(ulong discordUserId) => $"<@{discordUserId}>"; public static string ChannelIdToMention(ulong discordChannelId) => $"<#{discordChannelId}>"; public static string RoleIdToMention(ulong discordRoleId) => $"<@&{discordRoleId}>"; public static string TimeToMarkdown(DateTimeOffset dateTimeOffset, TimeToMentionType type = TimeToMentionType.ShortDateTime) => $"<t:{dateTimeOffset.ToUnixTimeSeconds()}:{(char)type}>"; public static string TimeToMarkdown(DateTime dateTime, TimeToMentionType type = TimeToMentionType.ShortDateTime) => TimeToMarkdown(dateTimeOffset: dateTime, type); public static string ToUserMention(this Snowflake snowflake) => UserIdToMention(snowflake.Value); public static string ToRoleMention(this Snowflake snowflake) => RoleIdToMention(snowflake.Value); public static string ToChannelMention(this Snowflake snowflake) => ChannelIdToMention(snowflake.Value); public static string ToTimeMarkdown(this DateTime dateTime, TimeToMentionType type = TimeToMentionType.ShortDateTime) => TimeToMarkdown(dateTime, type); public static string ToTimeMarkdown(this DateTimeOffset dateTimeOffset, TimeToMentionType type = TimeToMentionType.ShortDateTime) => TimeToMarkdown(dateTimeOffset, type); public static string GetJumpUrl(ulong guildId, ulong channelId, ulong messageId) => $"https://discord.com/channels/{guildId}/{channelId}/{messageId}"; public static string ToFormattedUrl(string text, string url) => $"[{text}]({url})"; } }
62.068966
178
0.743889
[ "MIT" ]
ChaseDRedmon/Accord
src/Accord.Bot/Helpers/DiscordFormatter.cs
1,802
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Vod.V20180717.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class PornConfigureInfoForUpdate : AbstractModel { /// <summary> /// 画面鉴别涉及令人反感的信息的控制参数。 /// </summary> [JsonProperty("ImgReviewInfo")] public PornImgReviewTemplateInfoForUpdate ImgReviewInfo{ get; set; } /// <summary> /// 语音鉴别涉及令人反感的信息的控制参数。 /// </summary> [JsonProperty("AsrReviewInfo")] public PornAsrReviewTemplateInfoForUpdate AsrReviewInfo{ get; set; } /// <summary> /// 文本鉴别涉及令人反感的信息的控制参数。 /// </summary> [JsonProperty("OcrReviewInfo")] public PornOcrReviewTemplateInfoForUpdate OcrReviewInfo{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamObj(map, prefix + "ImgReviewInfo.", this.ImgReviewInfo); this.SetParamObj(map, prefix + "AsrReviewInfo.", this.AsrReviewInfo); this.SetParamObj(map, prefix + "OcrReviewInfo.", this.OcrReviewInfo); } } }
32.87931
81
0.654955
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Vod/V20180717/Models/PornConfigureInfoForUpdate.cs
2,021
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ObjExporter.cs" company="Helix 3D Toolkit"> // http://helixtoolkit.codeplex.com, license: MIT // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace HelixToolkit.Wpf.SharpDX { using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Windows.Media; using System.Windows.Media.Media3D; /// <summary> /// Export the 3D visual tree to a Wavefront OBJ file /// </summary> /// <remarks> /// http://en.wikipedia.org/wiki/Obj /// http://www.martinreddy.net/gfx/3d/OBJ.spec /// http://www.eg-models.de/formats/Format_Obj.html /// </remarks> public class ObjExporter : Exporter { /// <summary> /// Gets or sets a value indicating whether to export normals. /// </summary> public bool ExportNormals { get; set; } /// <summary> /// Gets or sets a value indicating whether to use "d" for transparency (default is "Tr"). /// </summary> public bool UseDissolveForTransparency { get; set; } /// <summary> /// The directory. /// </summary> private readonly string directory; /// <summary> /// The exported materials. /// </summary> private readonly Dictionary<Material, string> exportedMaterials = new Dictionary<Material, string>(); /// <summary> /// The mwriter. /// </summary> private readonly StreamWriter mwriter; /// <summary> /// The writer. /// </summary> private readonly StreamWriter writer; /// <summary> /// Normal index counter. /// </summary> private int normalIndex = 1; /// <summary> /// Texture index counter. /// </summary> private int textureIndex = 1; /// <summary> /// Vertex index counter. /// </summary> private int vertexIndex = 1; /// <summary> /// Initializes a new instance of the <see cref="ObjExporter"/> class. /// </summary> /// <param name="outputFileName"> /// Name of the output file. /// </param> public ObjExporter(string outputFileName) : this(outputFileName, null) { } /// <summary> /// Initializes a new instance of the <see cref="ObjExporter"/> class. /// </summary> /// <param name="outputFileName"> /// Name of the output file. /// </param> /// <param name="comment"> /// The comment. /// </param> public ObjExporter(string outputFileName, string comment) { this.SwitchYZ = true; this.ExportNormals = false; var fullPath = Path.GetFullPath(outputFileName); var mtlPath = Path.ChangeExtension(outputFileName, ".mtl"); string mtlFilename = Path.GetFileName(mtlPath); this.directory = Path.GetDirectoryName(fullPath); this.writer = new StreamWriter(outputFileName); this.mwriter = new StreamWriter(mtlPath); if (!string.IsNullOrEmpty(comment)) { this.writer.WriteLine(string.Format("# {0}", comment)); } this.writer.WriteLine("mtllib ./" + mtlFilename); } /// <summary> /// Gets or sets a value indicating whether to switch Y and Z coordinates. /// </summary> public bool SwitchYZ { get; set; } /// <summary> /// Closes this exporter. /// </summary> public override void Close() { this.writer.Close(); this.mwriter.Close(); base.Close(); } /// <summary> /// The export mesh. /// </summary> /// <param name="m"> /// The m. /// </param> /// <param name="t"> /// The t. /// </param> public void ExportMesh(MeshGeometry3D m, Transform3D t) { if (m == null) { throw new ArgumentNullException("m"); } if (t == null) { throw new ArgumentNullException("t"); } // mapping from local indices (0-based) to the obj file indices (1-based) var vertexIndexMap = new Dictionary<int, int>(); var textureIndexMap = new Dictionary<int, int>(); var normalIndexMap = new Dictionary<int, int>(); int index = 0; if (m.Positions != null) { foreach (var v in m.Positions) { vertexIndexMap.Add(index++, this.vertexIndex++); var p = t.Transform(v.ToPoint3D()); this.writer.WriteLine( string.Format( CultureInfo.InvariantCulture, "v {0} {1} {2}", p.X, this.SwitchYZ ? p.Z : p.Y, this.SwitchYZ ? -p.Y : p.Z)); } this.writer.WriteLine(string.Format("# {0} vertices", index)); } if (m.TextureCoordinates != null) { index = 0; foreach (var vt in m.TextureCoordinates) { textureIndexMap.Add(index++, this.textureIndex++); this.writer.WriteLine(string.Format(CultureInfo.InvariantCulture, "vt {0} {1}", vt.X, 1 - vt.Y)); } this.writer.WriteLine(string.Format("# {0} texture coordinates", index)); } if (m.Normals != null && ExportNormals) { index = 0; foreach (var vn in m.Normals) { normalIndexMap.Add(index++, this.normalIndex++); this.writer.WriteLine( string.Format(CultureInfo.InvariantCulture, "vn {0} {1} {2}", vn.X, vn.Y, vn.Z)); } this.writer.WriteLine(string.Format("# {0} normals", index)); } Func<int, string> formatIndices = i0 => { bool hasTextureIndex = textureIndexMap.ContainsKey(i0); bool hasNormalIndex = normalIndexMap.ContainsKey(i0); if (hasTextureIndex && hasNormalIndex) { return string.Format("{0}/{1}/{2}", vertexIndexMap[i0], textureIndexMap[i0], normalIndexMap[i0]); } if (hasTextureIndex) { return string.Format("{0}/{1}", vertexIndexMap[i0], textureIndexMap[i0]); } if (hasNormalIndex) { return string.Format("{0}//{1}", vertexIndexMap[i0], normalIndexMap[i0]); } return vertexIndexMap[i0].ToString(); }; if (m.Indices != null) { for (int i = 0; i < m.Indices.Count; i += 3) { int i0 = m.Indices[i]; int i1 = m.Indices[i + 1]; int i2 = m.Indices[i + 2]; this.writer.WriteLine("f {0} {1} {2}", formatIndices(i0), formatIndices(i1), formatIndices(i2)); } this.writer.WriteLine(string.Format("# {0} faces", m.Indices.Count / 3)); } this.writer.WriteLine(); } /// <summary> /// The export model. /// </summary> /// <param name="model"> /// The model. /// </param> /// <param name="transform"> /// The transform. /// </param> protected override void ExportModel(GeometryModel3D model, Transform3D transform) { #if TODO_MATERIAL this.writer.WriteLine(string.Format("o object{0}", this.objectNo++)); this.writer.WriteLine(string.Format("g group{0}", this.groupNo++)); if (this.exportedMaterials.ContainsKey(model.Material)) { string matName = this.exportedMaterials[model.Material]; this.writer.WriteLine(string.Format("usemtl {0}", matName)); } else { string matName = string.Format("mat{0}", this.matNo++); this.writer.WriteLine(string.Format("usemtl {0}", matName)); this.ExportMaterial(matName, model.Material, model.BackMaterial); this.exportedMaterials.Add(model.Material, matName); } var mesh = model.Geometry as MeshGeometry3D; this.ExportMesh(mesh, Transform3DHelper.CombineTransform(transform, model.Transform)); #endif } /// <summary> /// The export material. /// </summary> /// <param name="matName"> /// The mat name. /// </param> /// <param name="material"> /// The material. /// </param> /// <param name="backMaterial"> /// The back material. /// </param> private void ExportMaterial(string matName, Material material, Material backMaterial) { #if TODO_MATERIAL this.mwriter.WriteLine(string.Format("newmtl {0}", matName)); var dm = material as DiffuseMaterial; var sm = material as SpecularMaterial; var mg = material as MaterialGroup; if (mg != null) { foreach (var m in mg.Children) { if (m is DiffuseMaterial) { dm = m as DiffuseMaterial; } if (m is SpecularMaterial) { sm = m as SpecularMaterial; } } } if (dm != null) { var adjustedAmbientColor = dm.AmbientColor.ChangeIntensity(0.2); // this.mwriter.WriteLine(string.Format("Ka {0}", this.ToColorString(adjustedAmbientColor))); var scb = dm.Brush as SolidColorBrush; if (scb != null) { this.mwriter.WriteLine(string.Format("Kd {0}", this.ToColorString(scb.Color))); if (this.UseDissolveForTransparency) { // Dissolve factor this.mwriter.WriteLine( string.Format(CultureInfo.InvariantCulture, "d {0:F4}", scb.Color.A / 255.0)); } else { // Transparency this.mwriter.WriteLine( string.Format(CultureInfo.InvariantCulture, "Tr {0:F4}", scb.Color.A / 255.0)); } } else { var textureFilename = matName + ".png"; var texturePath = Path.Combine(this.directory, textureFilename); // create .png bitmap file for the brush RenderBrush(texturePath, dm.Brush, 1024, 1024); this.mwriter.WriteLine(string.Format("map_Ka {0}", textureFilename)); } } // Illumination model 1 // This is a diffuse illumination model using Lambertian shading. The // color includes an ambient constant term and a diffuse shading term for // each light source. The formula is // color = KaIa + Kd { SUM j=1..ls, (N * Lj)Ij } int illum = 1; // Lambertian if (sm != null) { var scb = sm.Brush as SolidColorBrush; this.mwriter.WriteLine( string.Format( "Ks {0}", this.ToColorString(scb != null ? scb.Color : Color.FromScRgb(1.0f, 0.2f, 0.2f, 0.2f)))); // Illumination model 2 // This is a diffuse and specular illumination model using Lambertian // shading and Blinn's interpretation of Phong's specular illumination // model (BLIN77). The color includes an ambient constant term, and a // diffuse and specular shading term for each light source. The formula // is: color = KaIa + Kd { SUM j=1..ls, (N*Lj)Ij } + Ks { SUM j=1..ls, ((H*Hj)^Ns)Ij } illum = 2; // Specifies the specular exponent for the current material. This defines the focus of the specular highlight. // "exponent" is the value for the specular exponent. A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000. this.mwriter.WriteLine(string.Format(CultureInfo.InvariantCulture, "Ns {0:F4}", sm.SpecularPower)); } // roughness this.mwriter.WriteLine(string.Format("Ns {0}", 2)); // Optical density (index of refraction) this.mwriter.WriteLine(string.Format("Ni {0}", 1)); // Transmission filter this.mwriter.WriteLine(string.Format("Tf {0} {1} {2}", 1, 1, 1)); // Illumination model // Illumination Properties that are turned on in the // model Property Editor // 0 Color on and Ambient off // 1 Color on and Ambient on // 2 Highlight on // 3 Reflection on and Ray trace on // 4 Transparency: Glass on // Reflection: Ray trace on // 5 Reflection: Fresnel on and Ray trace on // 6 Transparency: Refraction on // Reflection: Fresnel off and Ray trace on // 7 Transparency: Refraction on // Reflection: Fresnel on and Ray trace on // 8 Reflection on and Ray trace off // 9 Transparency: Glass on // Reflection: Ray trace off // 10 Casts shadows onto invisible surfaces this.mwriter.WriteLine(string.Format("illum {0}", illum)); #endif } /// <summary> /// Converts a color to a string. /// </summary> /// <param name="color"> /// The color. /// </param> /// <returns> /// The string. /// </returns> private string ToColorString(Color color) { return string.Format( CultureInfo.InvariantCulture, "{0:F4} {1:F4} {2:F4}", color.R / 255.0, color.G / 255.0, color.B / 255.0); } } }
37.433414
173
0.473221
[ "MIT" ]
smallholexu/helix-toolkit
Source/HelixToolkit.Wpf.SharpDX/Utilities/ObjExporter.cs
15,462
C#
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using System.Collections.Immutable; using System.Linq; namespace CodeCracker.CSharp.Usage { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class DisposableFieldNotDisposedAnalyzer : DiagnosticAnalyzer { internal const string Title = "Use object initializer"; internal const string MessageFormat = "Field {0} should be disposed."; internal const string Category = SupportedCategories.Usage; const string Description = "This class has a disposable field and is not disposing it."; internal static DiagnosticDescriptor RuleForReturned = new DiagnosticDescriptor( DiagnosticId.DisposableFieldNotDisposed_Returned.ToDiagnosticId(), Title, MessageFormat, Category, DiagnosticSeverity.Info, isEnabledByDefault: true, description: Description, helpLinkUri: HelpLink.ForDiagnostic(DiagnosticId.DisposableFieldNotDisposed_Returned)); internal static DiagnosticDescriptor RuleForCreated = new DiagnosticDescriptor( DiagnosticId.DisposableFieldNotDisposed_Created.ToDiagnosticId(), Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description, helpLinkUri: HelpLink.ForDiagnostic(DiagnosticId.DisposableFieldNotDisposed_Created)); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(RuleForCreated, RuleForReturned); public override void Initialize(AnalysisContext context) => context.RegisterSymbolAction(AnalyzeField, SymbolKind.Field); private void AnalyzeField(SymbolAnalysisContext context) { var fieldSymbol = (IFieldSymbol)context.Symbol; if (!fieldSymbol.Type.AllInterfaces.Any(i => i.ToString() == "System.IDisposable") && fieldSymbol.Type.ToString() != "System.IDisposable") return; var fieldSyntaxRef = fieldSymbol.DeclaringSyntaxReferences.FirstOrDefault(); var variableDeclarator = fieldSyntaxRef.GetSyntax() as VariableDeclaratorSyntax; if (variableDeclarator == null) return; if (ContainingTypeImplementsIDisposableAndCallsItOnTheField(context, fieldSymbol, fieldSymbol.ContainingType)) return; if (variableDeclarator.Initializer?.Value is InvocationExpressionSyntax) context.ReportDiagnostic(Diagnostic.Create(RuleForReturned, variableDeclarator.GetLocation(), fieldSymbol.Name)); else if (variableDeclarator.Initializer?.Value is ObjectCreationExpressionSyntax) context.ReportDiagnostic(Diagnostic.Create(RuleForCreated, variableDeclarator.GetLocation(), fieldSymbol.Name)); } private bool ContainingTypeImplementsIDisposableAndCallsItOnTheField(SymbolAnalysisContext context, IFieldSymbol fieldSymbol, INamedTypeSymbol typeSymbol) { if (typeSymbol == null) return false; var iDisposableInterface = typeSymbol.AllInterfaces.FirstOrDefault(i => i.ToString() == "System.IDisposable"); if (iDisposableInterface != null) { var disposableMethod = iDisposableInterface.GetMembers("Dispose").OfType<IMethodSymbol>().First(d => d.Arity == 0); var disposeMethodSymbol = typeSymbol.FindImplementationForInterfaceMember(disposableMethod) as IMethodSymbol; if (disposeMethodSymbol != null) { var disposeMethod = (MethodDeclarationSyntax)disposeMethodSymbol.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax(); if (disposeMethod == null) return false; if (disposeMethod.Modifiers.Any(SyntaxKind.AbstractKeyword)) return true; var typeDeclaration = (TypeDeclarationSyntax)typeSymbol.DeclaringSyntaxReferences.FirstOrDefault().GetSyntax(); var semanticModel = context.Compilation.GetSemanticModel(typeDeclaration.SyntaxTree); if (CallsDisposeOnField(fieldSymbol, disposeMethod, semanticModel)) return true; } } return false; } private static bool CallsDisposeOnField(IFieldSymbol fieldSymbol, MethodDeclarationSyntax disposeMethod, SemanticModel semanticModel) { var hasDisposeCall = disposeMethod.Body.Statements.OfType<ExpressionStatementSyntax>() .Any(exp => { var invocation = exp.Expression as InvocationExpressionSyntax; if (!invocation?.Expression?.IsKind(SyntaxKind.SimpleMemberAccessExpression) ?? true) return false; var memberAccess = (MemberAccessExpressionSyntax)invocation.Expression; if (memberAccess.Name.Identifier.ToString() != "Dispose" || memberAccess.Name.Arity != 0) return false; var memberAccessIdentificer = memberAccess.Expression as IdentifierNameSyntax; if (memberAccessIdentificer == null) return false; return fieldSymbol.Equals(semanticModel.GetSymbolInfo(memberAccessIdentificer).Symbol); }); return hasDisposeCall; } } }
59.380435
162
0.692843
[ "Apache-2.0" ]
f14n/code-cracker
src/CSharp/CodeCracker/Usage/DisposableFieldNotDisposedAnalyzer.cs
5,463
C#
using System; using System.Collections.Concurrent; using System.Threading; using System.Threading.Channels; using System.Threading.Tasks; namespace RabbitMQ.Client.Impl { internal class ConsumerWorkService { private readonly ConcurrentDictionary<IModel, WorkPool> _workPools = new ConcurrentDictionary<IModel, WorkPool>(); private readonly Func<IModel, WorkPool> _startNewWorkPoolFunc; protected readonly int _concurrency; public ConsumerWorkService(int concurrency) { _concurrency = concurrency; _startNewWorkPoolFunc = model => StartNewWorkPool(model); } public void AddWork(IModel model, Action fn) { /* * rabbitmq/rabbitmq-dotnet-client#841 * https://docs.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentdictionary-2.getoradd * Note that the value delegate is not atomic but the AddWork method will not be called concurrently. */ WorkPool workPool = _workPools.GetOrAdd(model, _startNewWorkPoolFunc); workPool.Enqueue(fn); } private WorkPool StartNewWorkPool(IModel model) { var newWorkPool = new WorkPool(_concurrency); newWorkPool.Start(); return newWorkPool; } public void StopWork() { foreach (IModel model in _workPools.Keys) { StopWork(model); } } public void StopWork(IModel model) { StopWorkAsync(model).GetAwaiter().GetResult(); } internal Task StopWorkAsync(IModel model) { if (_workPools.TryRemove(model, out WorkPool workPool)) { return workPool.Stop(); } return Task.CompletedTask; } class WorkPool { private readonly Channel<Action> _channel; private readonly int _concurrency; private Task _worker; CancellationTokenSource _tokenSource; private SemaphoreSlim _limiter; public WorkPool(int concurrency) { _concurrency = concurrency; _channel = Channel.CreateUnbounded<Action>(new UnboundedChannelOptions { SingleReader = true, SingleWriter = false, AllowSynchronousContinuations = false }); } public void Start() { if (_concurrency == 1) { _worker = Task.Run(Loop, CancellationToken.None); } else { _limiter = new SemaphoreSlim(_concurrency); _tokenSource = new CancellationTokenSource(); _worker = Task.Run(() => LoopWithConcurrency(_tokenSource.Token), CancellationToken.None); } } public void Enqueue(Action action) { _channel.Writer.TryWrite(action); } async Task Loop() { while (await _channel.Reader.WaitToReadAsync().ConfigureAwait(false)) { while (_channel.Reader.TryRead(out Action work)) { try { work(); } catch { // ignored } } } } async Task LoopWithConcurrency(CancellationToken cancellationToken) { try { while (await _channel.Reader.WaitToReadAsync(cancellationToken).ConfigureAwait(false)) { while (_channel.Reader.TryRead(out Action action)) { // Do a quick synchronous check before we resort to async/await with the state-machine overhead. if (!_limiter.Wait(0)) { await _limiter.WaitAsync(cancellationToken).ConfigureAwait(false); } _ = OffloadToWorkerThreadPool(action, _limiter); } } } catch (OperationCanceledException) { // ignored } } static async Task OffloadToWorkerThreadPool(Action action, SemaphoreSlim limiter) { try { // like Task.Run but doesn't closure allocate await Task.Factory.StartNew(state => { ((Action)state)(); }, action, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default).ConfigureAwait(false); } catch { // ignored } finally { limiter.Release(); } } public Task Stop() { _channel.Writer.Complete(); _tokenSource?.Cancel(); _limiter?.Dispose(); return _worker; } } } }
32.744048
173
0.484276
[ "MIT" ]
houseofcat/RabbitMQ.Core
v6.1.0/RabbitMQ.Client/client/impl/ConsumerWorkService.cs
5,503
C#
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public class NullableKeywordRecommenderTests : KeywordRecommenderTests { [Fact] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact] public async Task TestAfterHash() { await VerifyKeywordAsync( @"#$$"); } [Fact] public async Task TestAfterHashAndSpace() { await VerifyKeywordAsync( @"# $$"); } [Fact] public async Task TestNotAfterHashAndNullable() { await VerifyAbsenceAsync( @"#nullable $$"); } [Fact] public async Task TestNotAfterPragma() { await VerifyAbsenceAsync(@"#pragma $$"); } [Fact] public async Task TestNotAfterPragmaWarning() { await VerifyAbsenceAsync(@"#pragma warning $$"); } [Fact] public async Task TestAfterPragmaWarningDisable() { await VerifyKeywordAsync(@"#pragma warning disable $$"); } [Fact] public async Task TestAfterPragmaWarningEnable() { await VerifyKeywordAsync(@"#pragma warning enable $$"); } [Fact] public async Task TestAfterPragmaWarningRestore() { await VerifyKeywordAsync(@"#pragma warning restore $$"); } [Fact] public async Task TestAfterPragmaWarningSafeOnly() { await VerifyKeywordAsync(@"#pragma warning safeonly $$"); } [Fact] public async Task TestNotAfterPragmaWarningSafeOnlyNullable() { await VerifyAbsenceAsync(@"#pragma warning safeonly nullable $$"); } [Fact] public async Task TestNotAfterPragmaWarningRestoreNullable() { await VerifyAbsenceAsync(@"#pragma warning restore nullable, $$"); } [Fact] public async Task TestNotAfterPragmaWarningDisableId() { await VerifyAbsenceAsync(@"#pragma warning disable 114, $$"); } } }
25.458647
161
0.58417
[ "Apache-2.0" ]
DustinCampbell/roslyn
src/EditorFeatures/CSharpTest2/Recommendations/NullableKeywordRecommenderTests.cs
3,388
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using FluentData.Business.Service; using FluentData.Business.ViewModels; using FluentData.Web2.Filters; namespace FluentData.Web2.Controllers { [AuthFilters] public class HomeController : Controller { #region Index public ActionResult Index() { PageVM<ArticleVM> data = new ArticleService().GetArticlePageList(new ArticleQuery()); return View(data); } #endregion #region GetArticlePageList public ActionResult GetArticlePageList(ArticleQuery query) { if (query == null) query = new ArticleQuery(); if (!query.PageIndex.HasValue) query.PageIndex = 1; if (!query.PageSize.HasValue) query.PageSize = 8; PageVM<ArticleVM> list = new ArticleService().GetArticlePageList(query); if (list == null || list.Data == null || list.Data.Count == 0) { return Json(new { Code = -200, Msg = "暂无数据" }); } return Json(new { Code = 200, Msg = "获取成功", Data = list }); } #endregion } }
25.327273
97
0.524767
[ "MIT" ]
shuaiagain/orm-fluentdata
FluentData/sourceCode/sourceCode/Source/v4/FluentData.Web2/Controllers/HomeController.cs
1,411
C#
namespace CSharpUtilsNETFramework.GUI.CustomControls { partial class MultiControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.TLPMain = new System.Windows.Forms.TableLayoutPanel(); this.textBox = new System.Windows.Forms.TextBox(); this.label = new System.Windows.Forms.Label(); this.comboBox = new System.Windows.Forms.ComboBox(); this.button = new System.Windows.Forms.Button(); this.TLPMain.SuspendLayout(); this.SuspendLayout(); // // TLPMain // this.TLPMain.ColumnCount = 1; this.TLPMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.TLPMain.Controls.Add(this.textBox, 0, 2); this.TLPMain.Controls.Add(this.label, 0, 1); this.TLPMain.Controls.Add(this.comboBox, 0, 3); this.TLPMain.Controls.Add(this.button, 0, 4); this.TLPMain.Dock = System.Windows.Forms.DockStyle.Fill; this.TLPMain.Location = new System.Drawing.Point(0, 0); this.TLPMain.Margin = new System.Windows.Forms.Padding(0); this.TLPMain.Name = "TLPMain"; this.TLPMain.RowCount = 6; this.TLPMain.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.TLPMain.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.TLPMain.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.TLPMain.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.TLPMain.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.TLPMain.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.TLPMain.Size = new System.Drawing.Size(150, 80); this.TLPMain.TabIndex = 0; // // textBox // this.textBox.Dock = System.Windows.Forms.DockStyle.Fill; this.textBox.Location = new System.Drawing.Point(0, 14); this.textBox.Margin = new System.Windows.Forms.Padding(0); this.textBox.Name = "textBox"; this.textBox.Size = new System.Drawing.Size(150, 20); this.textBox.TabIndex = 0; this.textBox.Visible = false; // // label // this.label.AutoSize = true; this.label.Dock = System.Windows.Forms.DockStyle.Fill; this.label.Location = new System.Drawing.Point(0, 1); this.label.Margin = new System.Windows.Forms.Padding(0); this.label.Name = "label"; this.label.Size = new System.Drawing.Size(150, 13); this.label.TabIndex = 1; this.label.Text = "label"; this.label.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.label.Visible = false; // // comboBox // this.comboBox.Dock = System.Windows.Forms.DockStyle.Fill; this.comboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox.FormattingEnabled = true; this.comboBox.Location = new System.Drawing.Point(0, 34); this.comboBox.Margin = new System.Windows.Forms.Padding(0); this.comboBox.Name = "comboBox"; this.comboBox.Size = new System.Drawing.Size(150, 21); this.comboBox.TabIndex = 2; this.comboBox.Visible = false; // // button // this.button.Dock = System.Windows.Forms.DockStyle.Fill; this.button.Location = new System.Drawing.Point(0, 55); this.button.Margin = new System.Windows.Forms.Padding(0); this.button.Name = "button"; this.button.Size = new System.Drawing.Size(150, 23); this.button.TabIndex = 3; this.button.Text = "button"; this.button.UseVisualStyleBackColor = true; this.button.Visible = false; // // MultiControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.TLPMain); this.Name = "MultiControl"; this.Size = new System.Drawing.Size(150, 80); this.TLPMain.ResumeLayout(false); this.TLPMain.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TableLayoutPanel TLPMain; private System.Windows.Forms.TextBox textBox; private System.Windows.Forms.Label label; private System.Windows.Forms.ComboBox comboBox; private System.Windows.Forms.Button button; } }
44.146154
125
0.586513
[ "MIT" ]
FairPlayer4/CSharpUtils
CSharpUtilsNETFramework/GUI/CustomControls/MultiControl.Designer.cs
5,741
C#
using Xunit; using System.Collections.Generic; namespace AnagramList.Objects { public class AnagramTest { [Fact] public void Test1_SimpleInput_True() { Anagram myAnagram = new Anagram("a","a"); Assert.Equal(true,myAnagram.isAnagram()); } [Fact] public void Test2_SimpleInput_False() { Anagram myAnagram = new Anagram("b","c"); Assert.Equal(false,myAnagram.isAnagram()); } [Fact] public void Test3_ComplexInput_True() { Anagram myAnagram = new Anagram("bread","beard"); Assert.Equal(true,myAnagram.isAnagram()); } [Fact] public void Test4_ComplexInput_False() { Anagram myAnagram = new Anagram("bread","orange"); Assert.Equal(false,myAnagram.isAnagram()); } [Fact] public void test5_PartialMatch_True() { Anagram myAnagram =new Anagram("Pat","Path"); Assert.Equal(true,myAnagram.isAnagram()); } [Fact] public void Test6_SingleNumber_False() { Anagram myAnagram = new Anagram("0","0"); Assert.Equal(false,myAnagram.isAnagram()); } [Fact] public void Test7_IfWordIncludeNumber_False() { Anagram myAnagram = new Anagram("p0g","p0g"); Assert.Equal(false,myAnagram.isAnagram()); } [Fact] public void Test8_CaseInSentive_True() { Anagram myAnagram = new Anagram("PIG","GIP"); Assert.Equal(true,myAnagram.isAnagram()); } } }
24.770492
57
0.606221
[ "MIT" ]
russvetsper/Anagram
Tests/AnagramTest.cs
1,511
C#
#nullable disable using VocaDb.Model.Domain.Tags; using VocaDb.Model.Domain.Users; namespace VocaDb.Model.Domain.Songs { public class SongTagVote : GenericTagVote<SongTagUsage> { public SongTagVote() { } public SongTagVote(SongTagUsage usage, User user) : base(usage, user) { } } }
21.714286
76
0.720395
[ "MIT" ]
AgFlore/vocadb
VocaDbModel/Domain/Songs/SongTagVote.cs
304
C#
using Devices.Application.Devices.DTOs.Validators; using Enmeshed.BuildingBlocks.Application.FluentValidation; using FluentValidation; namespace Devices.Application.Devices.Commands.RegisterDevice; public class RegisterDeviceCommandValidator : AbstractValidator<RegisterDeviceCommand> { public RegisterDeviceCommandValidator() { RuleFor(c => c.DevicePassword).DetailedNotEmpty(); RuleFor(c => c.SignedChallenge).DetailedNotEmpty().SetValidator(new SignedChallengeDTOValidator()); } }
34.333333
107
0.798058
[ "MIT" ]
nmshd/bkb-devices
Devices.Application/Devices/Commands/RegisterDevice/RegisterDeviceCommandValidator.cs
517
C#
using System; namespace ExpenseReportApp.AuditLogService.Areas.HelpPage { /// <summary> /// This represents an invalid sample on the help page. There's a display template named InvalidSample associated with this class. /// </summary> public class InvalidSample { public InvalidSample(string errorMessage) { if (errorMessage == null) { throw new ArgumentNullException("errorMessage"); } ErrorMessage = errorMessage; } public string ErrorMessage { get; private set; } public override bool Equals(object obj) { InvalidSample other = obj as InvalidSample; return other != null && ErrorMessage == other.ErrorMessage; } public override int GetHashCode() { return ErrorMessage.GetHashCode(); } public override string ToString() { return ErrorMessage; } } }
26.864865
134
0.583501
[ "MIT" ]
Magenic/GCELiftAndShift
ExpenseReportApp.AuditLogService/Areas/HelpPage/SampleGeneration/InvalidSample.cs
994
C#
using System; using CSF.Screenplay.Actors; using CSF.Screenplay.Performables; namespace Agiil.BDD.Tasks.Tickets { public class OpenTicketForEditingByTitle : Performable { readonly string title; protected override string GetReport(INamed actor) => $"{actor.Name} opens a ticket with the title '{title}' for editing"; protected override void PerformAs(IPerformer actor) { actor.Perform(OpenTheTicket.Titled(title)); actor.Perform<BeginEditingTheTicket>(); } public OpenTicketForEditingByTitle(string title) { if(title == null) throw new ArgumentNullException(nameof(title)); this.title = title; } } }
23.482759
77
0.698972
[ "MIT" ]
csf-dev/agiil
Tests/Agiil.BDD/Tasks/Tickets/OpenTicketForEditingByTitle.cs
683
C#
using Markdig.Syntax.Inlines; namespace Markdig.Renderers.LaTeX.Inlines { public class DelimiterInlineRenderer : LatexObjectRenderer<DelimiterInline> { protected override void Write(LatexRenderer renderer, DelimiterInline obj) { renderer.WriteEscape(obj.ToLiteral()); renderer.WriteChildren(obj); } } }
27.923077
82
0.688705
[ "MIT" ]
namofun/blogging
src/Markdig/LatexRenderers/Inlines/DelimiterInlineRenderer.cs
363
C#
using System; using System.Collections.Generic; using System.Linq; using EventStore.Core.Data; using EventStore.Core.Messages; using EventStore.Core.Services.AwakeReaderService; using EventStore.Core.Services.TimerService; using EventStore.Core.TransactionLog.LogRecords; using EventStore.Projections.Core.Messages; using EventStore.Projections.Core.Services.Processing; using EventStore.Projections.Core.Tests.Services.core_projection; using NUnit.Framework; using ResolvedEvent = EventStore.Core.Data.ResolvedEvent; namespace EventStore.Projections.Core.Tests.Services.event_reader.multi_stream_reader { [TestFixture] public class when_handling_streams_with_deleted_events_and_reader_starting_after_event_zero : TestFixtureWithExistingEvents { private MultiStreamEventReader _edp; private int _fromSequenceNumber; private string[] _streamNames; private Dictionary<string,long> _streamPositions; private Guid _distibutionPointCorrelationId; protected override void Given() { TicksAreHandledImmediately(); _fromSequenceNumber = 10; _streamNames = new[] {"stream1","stream2"}; _streamPositions = new Dictionary<string, long> {{"stream1", _fromSequenceNumber}, {"stream2", 100}}; } [SetUp] public new void When() { _distibutionPointCorrelationId = Guid.NewGuid(); _edp = new MultiStreamEventReader( _ioDispatcher, _bus, _distibutionPointCorrelationId, null, 0, _streamNames, _streamPositions, false, new RealTimeProvider()); _edp.Resume(); } private void HandleEvents(string stream, long[] eventNumbers){ string eventType = "event_type"; List<ResolvedEvent> events = new List<ResolvedEvent>(); foreach(long eventNumber in eventNumbers){ events.Add( ResolvedEvent.ForUnresolvedEvent( new EventRecord( eventNumber, 50*(eventNumber+1), Guid.NewGuid(), Guid.NewGuid(), 50*(eventNumber+1), 0, stream, ExpectedVersion.Any, DateTime.UtcNow, PrepareFlags.SingleWrite | PrepareFlags.TransactionBegin | PrepareFlags.TransactionEnd, eventType, new byte[] {0}, new byte[] {0} ) ) ); } long start, end; if(eventNumbers.Length > 0){ start = eventNumbers[0]; end = eventNumbers[eventNumbers.Length-1]; } else{ start = _fromSequenceNumber; end = _fromSequenceNumber; } var correlationId = _consumer.HandledMessages.OfType<ClientMessage.ReadStreamEventsForward>().Last(x => x.EventStreamId == stream).CorrelationId; _edp.Handle( new ClientMessage.ReadStreamEventsForwardCompleted( correlationId, stream, start, 100, ReadStreamResult.Success,events.ToArray(), null, false, "", start+1, end, true, 200) ); } private void HandleEvents(string stream,long start,long end){ List<long> eventNumbers = new List<long>(); for(long i=start;i<=end;i++) eventNumbers.Add(i); HandleEvents(stream,eventNumbers.ToArray()); } [Test] public void allows_first_event_to_be_equal_to_sequence_number() { long eventSequenceNumber = _fromSequenceNumber; Assert.DoesNotThrow(() => { HandleEvents(_streamNames[0],eventSequenceNumber,eventSequenceNumber); //to trigger event delivery: HandleEvents(_streamNames[1],100,101); }); } [Test] public void should_not_allow_first_event_to_be_greater_than_sequence_number() { long eventSequenceNumber = _fromSequenceNumber+5; HandleEvents(_streamNames[0],eventSequenceNumber,eventSequenceNumber); //to trigger event delivery: HandleEvents(_streamNames[1],100,101); Assert.AreEqual(1, HandledMessages.OfType<ReaderSubscriptionMessage.Faulted>().Count()); } [Test] public void should_not_allow_first_event_to_be_less_than_sequence_number() { long eventSequenceNumber = _fromSequenceNumber-1; HandleEvents(_streamNames[0],eventSequenceNumber,eventSequenceNumber); //to trigger event delivery: HandleEvents(_streamNames[1],100,101); Assert.AreEqual(1, HandledMessages.OfType<ReaderSubscriptionMessage.Faulted>().Count()); } [Test] public void events_after_first_event_should_not_be_in_sequence() { //_fromSequenceNumber+2 has been omitted HandleEvents(_streamNames[0],new long[]{_fromSequenceNumber,_fromSequenceNumber+1,_fromSequenceNumber+3,_fromSequenceNumber+4}); //to trigger event delivery: HandleEvents(_streamNames[1],100,101); Assert.AreEqual(2, HandledMessages.OfType<ReaderSubscriptionMessage.Faulted>().Count()); } } }
41.045113
169
0.615314
[ "Apache-2.0", "CC0-1.0" ]
cuteant/EventStore-DotNetty-Fork
src/EventStore.Projections.Core.Tests/Services/event_reader/multi_stream_reader/when_handling_streams_with_deleted_events_and_reader_starting_after_event_zero.cs
5,461
C#
// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using System.IO; using Tea; namespace AlibabaCloud.SDK.Cms20190101.Models { public class DescribeAlertingMetricRuleResourcesRequest : TeaModel { [NameInMap("RuleId")] [Validation(Required=false)] public string RuleId { get; set; } [NameInMap("GroupId")] [Validation(Required=false)] public string GroupId { get; set; } [NameInMap("Page")] [Validation(Required=false)] public int? Page { get; set; } [NameInMap("PageSize")] [Validation(Required=false)] public int? PageSize { get; set; } } }
22.774194
72
0.631728
[ "Apache-2.0" ]
atptro/alibabacloud-sdk
cms-20190101/csharp/core/Models/DescribeAlertingMetricRuleResourcesRequest.cs
706
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Text; namespace Web_Sample_HTTP_ { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnSend_Click(object sender, EventArgs e) { SMSHttp smsHttp = new SMSHttp(); if (smsHttp.sendSMS(this.accountInputText.Value, this.passwordInputText.Value, this.subjectInputText.Value, this.contentInputText.Value, this.phonesInputText.Value, "")) { this.Page.Controls.Add(new LiteralControl(new StringBuilder("<script>alert('發送成功!點數剩餘").Append(smsHttp.Credit.ToString()).Append("點。');</script>").ToString())); } else { this.Page.Controls.Add(new LiteralControl("<script>alert('發送失敗!');</script>")); } } } }
34.12
174
0.73857
[ "MIT" ]
Thomas-Chiu/smsTest
api/every8d/SAMPLE_CODE/CSharp.NET/API21_Sample/Web_Sample(HTTP)/Default.aspx.cs
887
C#
using UnityEngine; public class Bullet : MonoBehaviour { private Transform target; private Enemy targetEnemy; public GameObject effect; private float speed; private float range; private float damage; public void SetInfo(Enemy _target, float _damage, float _range, float _speed) { targetEnemy = _target; target = _target.gameObject.transform; damage = _damage; range = _range; speed = _speed; } void Update() { if (target == null) { Destroy(gameObject); //Destroy game object if it has no target return; } Vector3 dir = target.position - transform.position; //Get direction to target float moveDistance = speed * Time.deltaTime; //Get distance bullet can move if (dir.sqrMagnitude <= moveDistance * moveDistance) //If the distance the bullet can move is more than the distance of target { HitTarget(); return; } transform.Translate(dir.normalized * moveDistance, Space.World); //Move towards target transform.LookAt(target); //Look towards target } void HitTarget() { Destroy(Instantiate(effect, transform.position, transform.rotation), 7f); //Create particle effect and destroy after 7 seconds if (range > 0f) //If bullet's blast radius is more than 0 { Explode(); //Explode, potentially hurting other enemies around it } else { Damage(targetEnemy); //Only hurt the target enemy } Destroy(gameObject); //Destroy itself } void Damage(Transform enemy) { try { enemy.GetComponent<Enemy>().takeDamage(damage); //Try getting enemy script and damage it } catch (System.Exception) {} } void Damage(Enemy enemy) { try { enemy.takeDamage(damage); //Try getting enemy and damage it } catch (System.Exception) {} } void Explode() { Collider[] colliders = Physics.OverlapSphere(transform.position, range); //Get overlapping colliders in the bullets range for (int i = 0; i < colliders.Length; i++) { Collider collider = colliders[i]; try { if (collider.transform.parent.CompareTag("Enemy")) //If collider is an enemy { Damage(collider.transform.parent); //Hurt the enemy } } catch (System.Exception) { } } } void OnDrawGizmosSelected() { Gizmos.color = Color.green; Gizmos.DrawWireSphere(transform.position, range); //Draw a green sphere to show range of bullet } }
31.806818
134
0.580922
[ "Apache-2.0" ]
RaphGamingz/Unity
Assets/Scripts/Bullet.cs
2,799
C#
using System; using System.Collections.Generic; using NUnit.Framework; using UnityEngine.ResourceManagement.AsyncOperations; using UnityEngine.ResourceManagement.ResourceLocations; using UnityEngine.ResourceManagement.ResourceProviders; using UnityEngine.ResourceManagement.Util; namespace UnityEngine.ResourceManagement.Tests { public class OperationsCacheTests { ResourceManager m_ResourceManager; [SetUp] public void Setup() { m_ResourceManager = new ResourceManager(); m_ResourceManager.CallbackHooksEnabled = false; // default for tests. disabled callback hooks. we will call update manually } [TearDown] public void TearDown() { Assert.Zero(m_ResourceManager.OperationCacheCount); m_ResourceManager.Dispose(); } [Test] public void OperationCache_CollisionsAreProperlyHandled() { Assert.Zero(m_ResourceManager.OperationCacheCount); var provType = typeof(InstanceProvider); var loc1 = new TestResourceLocation("asset1", "asset1", provType.FullName, typeof(GameObject)); var key1 = new LocationCacheKey(loc1, typeof(GameObject)); var opType = typeof(TestOperation); m_ResourceManager.CreateOperation<TestOperation>(opType, opType.GetHashCode(), key1, null); Assert.AreEqual(1, m_ResourceManager.CachedOperationCount()); Assert.IsTrue(m_ResourceManager.IsOperationCached(key1)); var loc2 = new TestResourceLocation("asset2", "asset2", provType.FullName, typeof(GameObject)); var key2 = new LocationCacheKey(loc2, typeof(GameObject)); Assert.IsFalse(m_ResourceManager.IsOperationCached(key2)); Assert.IsTrue(m_ResourceManager.RemoveOperationFromCache(key1)); } class TestOperation : AsyncOperationBase<GameObject>, ICachable { protected override void Execute() { } public IOperationCacheKey Key { get; set; } } class TestResourceLocation : IResourceLocation { public TestResourceLocation(string name, string id, string providerId, Type t, params IResourceLocation[] dependencies) { PrimaryKey = name; InternalId = id; ProviderId = providerId; Dependencies = new List<IResourceLocation>(dependencies); ResourceType = t == null ? typeof(object) : t; } public string InternalId { get; } public string ProviderId { get; } public IList<IResourceLocation> Dependencies { get; } public int Hash(Type type) { // Returning a constant hashcode to force collisions. return 1337; } public int DependencyHashCode => 0; public bool HasDependencies => Dependencies.Count > 0; public object Data { get; } public string PrimaryKey { get; } public Type ResourceType { get; } } [Test] public void Locations_WithDiffNames_LocationEquals_Returns_True() { var l1 = new ResourceLocationBase("a", "b", "c", typeof(Mesh)); var l2 = new ResourceLocationBase("x", "b", "c", typeof(Mesh)); Assert.IsTrue(LocationUtils.LocationEquals(l1, l2)); } [Test] public void Locations_WithDiffIds_LocationEquals_Returns_False() { var l1 = new ResourceLocationBase("a", "b", "c", typeof(Mesh)); var l2 = new ResourceLocationBase("a", "x", "c", typeof(Mesh)); Assert.IsFalse(LocationUtils.LocationEquals(l1, l2)); } [Test] public void Locations_WithDiffProvider_LocationEquals_Returns_False() { var l1 = new ResourceLocationBase("a", "b", "c", typeof(Mesh)); var l2 = new ResourceLocationBase("a", "b", "x", typeof(Mesh)); Assert.IsFalse(LocationUtils.LocationEquals(l1, l2)); } [Test] public void Locations_WithDiffResourceTypes_LocationEquals_Returns_True() { var l1 = new ResourceLocationBase("a", "b", "c", typeof(Mesh)); var l2 = new ResourceLocationBase("a", "b", "c", typeof(Material)); Assert.IsFalse(LocationUtils.LocationEquals(l1, l2)); } class ResourceLocatonTestSub : ResourceLocationBase { public ResourceLocatonTestSub(string n, string id, string pr, Type t) : base(n, id, pr, t) { } } [Test] public void Locations_WithDiffTypes_LocationEquals_Returns_True() { var l1 = new ResourceLocationBase("a", "b", "c", typeof(Mesh)); var l2 = new ResourceLocatonTestSub("a", "b", "c", typeof(Mesh)); Assert.IsTrue(LocationUtils.LocationEquals(l1, l2)); } } }
39.0625
135
0.6138
[ "Apache-2.0" ]
BrinisSpark/Space-Invaders-Clone
Library/PackageCache/com.unity.addressables@1.18.16/Tests/Runtime/ResourceManager/OperationsCacheTests.cs
5,000
C#
using System; using System.ComponentModel; using System.Drawing; using System.IO; using System.Windows.Forms; namespace FrontEnd { public partial class ExtractArchiveWindow : Form { private readonly Time time = new Time(); private bool extractionCompleted; private bool extractionStarted; private string path; private bool selected; public ExtractArchiveWindow() { InitializeComponent(); } private void cancel_Click(object sender, EventArgs e) { Close(); } private void select_Click(object sender, EventArgs e) { if (ChoosePathDialog.ShowDialog() == DialogResult.OK) { path = ChoosePathDialog.SelectedPath; var shortPath = Path.GetFileName(path); if (shortPath.Length > 20) shortPath = shortPath.Substring(0, 20) + "..."; file.Text = shortPath; extract.ForeColor = Color.FromArgb(64, 64, 64); toolTip1.SetToolTip(extract, ""); toolTip1.SetToolTip(file, path); selected = true; } } private void taskFour_Click(object sender, EventArgs e) { } private void extract_Click(object sender, EventArgs e) { if (selected) { selectionPanel.Visible = false; selectionPanel.Enabled = false; progressPanel.Visible = true; timer1.Enabled = true; backgroundExtractor.RunWorkerAsync(); } } private void UpdateState(string next) { BeginInvoke((Action) delegate { var shortName = next; if (shortName.Length > 25) shortName = shortName.Substring(0, 25) + "..."; currentFileName.Text = shortName; toolTip1.SetToolTip(currentFileName, next); }); } private void UpdateFile(string next) { BeginInvoke((Action) delegate { currentFileIndex.Text = next; }); } private void backgroundExtractor_DoWork(object sender, DoWorkEventArgs e) { extractionStarted = true; Controller.controller.SubscribeToStateUpdates(UpdateState); Controller.controller.SubscribeToFileUpdates(UpdateFile); Controller.controller.SubscribeToPercentageUpdates(backgroundExtractor.ReportProgress); Controller.controller.ExtractArchiveTo(path); } private void backgroundExtractor_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { extractionCompleted = true; Controller.controller.UnsubscribeFromStateUpdates(UpdateState); Controller.controller.UnsubscribeFromFileUpdates(UpdateFile); Controller.controller.UnsubscribeToPercentageUpdates(backgroundExtractor.ReportProgress); if (e.Error == null) { progressPanel.Visible = false; progressPanel.Enabled = false; ShowResultPanel(); } else { progressPanel.Visible = false; progressPanel.Enabled = false; error.Text = e.Error.Message; errorPanel.Visible = true; } } private void backgroundExtractor_ProgressChanged(object sender, ProgressChangedEventArgs e) { percentage.Text = "(progress: " + e.ProgressPercentage + "%)"; } private void timer1_Tick(object sender, EventArgs e) { if (extractionCompleted) timer1.Enabled = false; if (timer1.Enabled) { /* update timer in the corner */ var res = ""; if (time.min > 0) res += time.min + "m "; res += time.sec + "s"; timerText.Text = res; /* update progress message */ var reminder = time.sec % 3; progressMessage.Text = "The archive is being extracted"; for (var i = 0; i <= reminder; i++) progressMessage.Text += "."; /* update time */ time.Inc(); } } private void ShowResultPanel() { totalTime.Text = "in "; if (time.min > 0) { totalTime.Text += time.min + " "; if (time.min == 1) totalTime.Text += "minute "; else totalTime.Text += "minutes "; } if (time.sec > 0) { totalTime.Text += time.sec + " "; if (time.sec == 1) totalTime.Text += "second "; else totalTime.Text += "seconds "; } if (time.min == 0 && time.sec == 0) totalTime.Text += "less than a second"; resultPanel.Visible = true; } private void okErrorButton_Click(object sender, EventArgs e) { Close(); } private void ExtractArchiveWindow_Load(object sender, EventArgs e) { } private void okResultButton_Click(object sender, EventArgs e) { Close(); } private void progressPanel_Paint(object sender, PaintEventArgs e) { } private void ExtractArchiveWindow_FormClosing(object sender, FormClosingEventArgs e) { if (!extractionCompleted && extractionStarted) e.Cancel = true; } } }
31.048649
105
0.529422
[ "MIT" ]
eugene-popov/Huffman-Archiver
FrontEnd/ExtractArchiveWindow.cs
5,746
C#
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using Franson.Protocols.Obex.OBEXService; namespace ObexServiceSampleCF { /// <summary> /// Summary description for ServerExtended. /// </summary> public class ServiceExtended : Franson.Protocols.Obex.OBEXService.ObexService { //Add a couple of event handlers to communicate to the GUI with public delegate void ObexServiceEventHandler(ObexSession obexSessions); public delegate void ObexServiceFileTransferEventHandler(ObexSession obexSessions, ObexFile obexFile); public delegate void ObexServiceFolderOperationEventHandler(ObexSession obexSessions, ObexFolder obexFolder); public delegate void ObexServiceFolderItemEventHandler(ObexSession obexSessions, ObexFolderItem folderItem); public delegate void ObexServiceExceptionEventHandler(ObexSession obexSession, Exception exception); public event ObexServiceEventHandler OnConnect; public event ObexServiceEventHandler OnDisconnect; public event ObexServiceFolderItemEventHandler OnDelete; public event ObexServiceEventHandler OnGetPath; public event ObexServiceFileTransferEventHandler OnGet; public event ObexServiceFileTransferEventHandler OnPut; public event ObexServiceFolderOperationEventHandler OnCreateFolder; public event ObexServiceFolderOperationEventHandler OnSetPath; public event ObexServiceEventHandler OnAbort; public event ObexServiceExceptionEventHandler OnObexException; public ServiceExtended(ObexServiceType obexServiceType, string name, string description, ObexFolder rootFolder) : base (obexServiceType, name, description, rootFolder) { } public override Response OnConnectRequest(ObexSession obexSession) { OnConnect(obexSession); return base.OnConnectRequest (obexSession); } public override Response OnDisconnectRequest(ObexSession obexSession) { OnDisconnect(obexSession); return base.OnDisconnectRequest (obexSession); } public override Response OnDeleteRequest(ObexSession obexSession, ObexFolderItem folderItem) { OnDelete(obexSession, folderItem); return base.OnDeleteRequest (obexSession, folderItem); } public override Response OnFolderCreateRequest(ObexSession obexSession, ObexFolder folder) { OnCreateFolder(obexSession, folder); return base.OnFolderCreateRequest (obexSession, folder); } public override Response OnGetPathRequest(ObexSession obexSession, ObexFolderContent folderContent) { OnGetPath(obexSession); return base.OnGetPathRequest (obexSession, folderContent); } public override Response OnGetRequest(ObexSession obexSession, ObexFile file, ObexStream outStream) { OnGet(obexSession, file); return base.OnGetRequest (obexSession, file, outStream); } public override Response OnPutRequest(ObexSession obexSession, ObexFile file, ObexStream inStream) { OnPut(obexSession, file); return base.OnPutRequest (obexSession, file, inStream); } public override Response OnSetPathRequest(ObexSession obexSession, ObexFolder folderToChangeTo) { OnSetPath(obexSession, folderToChangeTo); return base.OnSetPathRequest (obexSession, folderToChangeTo); } public override Response OnAbortRequest(ObexSession obexSession) { OnAbort(obexSession); return base.OnAbortRequest (obexSession); } public override void OnOBEXServerException(ObexSession obexSession, object sender, Exception exception) { base.OnOBEXServerException (obexSession, sender, exception); OnObexException(obexSession, exception); } } }
36.732673
170
0.784097
[ "MIT" ]
johanlantz/headsetpresenter
HeadsetPresenter_Bluetools/HeadsetPresenter/Bluetools/BlueTools SDK v1.2/dotNet200/C#/ObexServiceGUI/ServiceExtended.cs
3,710
C#
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; namespace WebsitePanel.FixDefaultPublicFolderMailbox { class Program { static void Main(string[] args) { Log.Initialize(ConfigurationManager.AppSettings["LogFile"]); bool showHelp = false; string param = null; if (args.Length==0) { showHelp = true; } else { param = args[0]; if ((param == "/?") || (param.ToLower() == "/h")) showHelp = true; } if (showHelp) { string name = typeof(Log).Assembly.GetName().Name; string version = typeof(Log).Assembly.GetName().Version.ToString(3); Console.WriteLine("WebsitePanel Fix default public folder mailbox. " + version); Console.WriteLine("Usage :"); Console.WriteLine(name + " [/All]"); Console.WriteLine("or"); Console.WriteLine(name + " [OrganizationId]"); return; } Log.WriteApplicationStart(); if (param.ToLower() == "/all") param = null; Fix.Start(param); Log.WriteApplicationEnd(); } } }
38.109756
97
0.61088
[ "BSD-3-Clause" ]
9192939495969798/Websitepanel
WebsitePanel/Sources/Tools/WebsitePanel.FixDefaultPublicFolderMailbox/Program.cs
3,125
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Immutable; using System.IO; using System.Reflection; namespace Microsoft.CodeAnalysis.Sarif.Driver.Sdk { public abstract class ExportConfigurationCommandBase : PlugInDriverCommand<ExportConfigurationOptions> { public override int Run(ExportConfigurationOptions exportOptions) { int result = FAILURE; try { PropertyBag allOptions = new PropertyBag(); // The export command could be updated in the future to accept an arbitrary set // of analyzers for which to build an options XML file suitable for configuring them. // Currently, we perform discovery against the built-in CodeFormatter rules // and analyzers only. ImmutableArray<IOptionsProvider> providers = DriverUtilities.GetExports<IOptionsProvider>(DefaultPlugInAssemblies); foreach (IOptionsProvider provider in providers) { foreach (IOption option in provider.GetOptions()) { allOptions.SetProperty(option, option.DefaultValue, cacheDescription: true); } } string exe = Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location); allOptions.SaveTo(exportOptions.OutputFilePath, id: exe + "-config"); Console.WriteLine("Configuration file saved to: " + Path.GetFullPath(exportOptions.OutputFilePath)); result = SUCCESS; } catch (Exception ex) { Console.Error.WriteLine(ex.ToString()); } return result; } } }
36.884615
131
0.616788
[ "MIT" ]
Bhaskers-Blu-Org2/driver-utilities
src/Sarif.Driver/Sdk/ExportConfigurationCommandBase.cs
1,920
C#
namespace MountainSocialNetwork.Data.Seeding { using System; using System.Linq; using System.Threading.Tasks; using MountainSocialNetwork.Data.Models; internal class SettingsSeeder : ISeeder { public async Task SeedAsync(ApplicationDbContext dbContext, IServiceProvider serviceProvider) { if (dbContext.Settings.Any()) { return; } await dbContext.Settings.AddAsync(new Setting { Name = "Setting1", Value = "value1" }); } } }
24.772727
101
0.618349
[ "MIT" ]
Ventsislav-Ignatov/MountainSocialNetwork
src/Data/MountainSocialNetwork.Data/Seeding/SettingsSeeder.cs
547
C#
using Uno.UI.Samples.Controls; using Uno.UI.Samples.Presentation.SamplePages; using Windows.UI.Xaml.Controls; namespace Uno.UI.Samples.Content.UITests.ButtonTestsControl { [SampleControlInfo("Buttons", "Simple_Button", typeof(ButtonTestsViewModel), ignoreInSnapshotTests: true)] public sealed partial class Simple_Button : UserControl { public Simple_Button() { this.InitializeComponent(); } } }
24.176471
107
0.783455
[ "Apache-2.0" ]
iury-kc/uno
src/SamplesApp/UITests.Shared/Windows_UI_Xaml_Controls/Button/Simple_Button.xaml.cs
411
C#
namespace Stripe { using Newtonsoft.Json; using Stripe.Infrastructure; public class ChargePaymentMethodDetailsInteracPresent : StripeEntity<ChargePaymentMethodDetailsInteracPresent> { /// <summary> /// Card brand. Can be <c>interac</c>, <c>mastercard</c> or <c>visa</c>. /// </summary> [JsonProperty("brand")] public string Brand { get; set; } /// <summary> /// The cardholder name as read from the card, in /// [ISO 7813](https://en.wikipedia.org/wiki/ISO/IEC_7813) format. /// May include alphanumeric characters, special characters /// and first/last name separator (`/`). /// </summary> [JsonProperty("cardholder_name")] public string CardholderName { get; set; } /// <summary> /// Two-letter ISO code representing the country of the card. You could use /// this attribute to get a sense of the international breakdown of cards /// you've collected. /// </summary> [JsonProperty("country")] public string Country { get; set; } /// <summary> /// Authorization response cryptogram. /// </summary> [JsonProperty("emv_auth_data")] public string EmvAuthData { get; set; } /// <summary> /// Two-digit number representing the card's expiration month. /// </summary> [JsonProperty("exp_month")] public long ExpMonth { get; set; } /// <summary> /// Four-digit number representing the card's expiration year. /// </summary> [JsonProperty("exp_year")] public long ExpYear { get; set; } /// <summary> /// Uniquely identifies this particular card number. /// You can use this attribute to check whether two customers /// who've signed up with you are using the same card number, /// for example. For payment methods that tokenize card /// information (Apple Pay, Google Pay), the tokenized number /// might be provided instead of the underlying card number. /// </summary> [JsonProperty("fingerprint")] public string Fingerprint { get; set; } /// <summary> /// Card funding type. Can be <c>credit</c>, <c>debit</c>, /// <c>prepaid</c>, or <c>unknown</c>. /// </summary> [JsonProperty("funding")] public string Funding { get; set; } /// <summary> /// ID of a card PaymentMethod generated from the card_present /// PaymentMethod that may be attached to a Customer for future /// transactions. Only present if it was possible to generate a /// card PaymentMethod. /// </summary> [JsonProperty("generated_card")] public string GeneratedCard { get; set; } /// <summary> /// The last four digits of the card. /// </summary> [JsonProperty("last4")] public string Last4 { get; set; } /// <summary> /// Identifies which network this charge was processed on. /// Can be <c>amex</c>, <c>diners</c>, <c>discover</c>, /// <c>interac</c>, <c>jcb</c>, <c>mastercard</c>, /// <c>unionpay</c>, <c>visa</c>, or <c>unknown</c>. /// </summary> [JsonProperty("network")] public string Network { get; set; } /// <summary> How were card details read in this transaction. Can be /// <c>contact_emv</c>, <c>contactless_emv</c>, /// <c>magnetic_stripe_fallback</c>, <c>magnetic_stripe_track2</c>, or /// <c>contactless_magstripe_mode</c>. /// </summary> [JsonProperty("read_method")] public string ReadMethod { get; set; } /// <summary> /// A collection of fields required to be displayed on receipts. /// Only required for EMV transactions. /// </summary> [JsonProperty("receipt")] public ChargePaymentMethodDetailsInteracPresentReceipt Receipt { get; set; } } }
37.785047
114
0.579025
[ "Apache-2.0" ]
Loyalar/stripe-dotnet
src/Stripe.net/Entities/Charges/ChargePaymentMethodDetailsInteracPresent.cs
4,043
C#