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
using System; namespace MetaFoo.Core.Delegates { public static class FuncValueTuplePackingExtensions { public static Func<ValueTuple<T1, T2>, TResult> Pack<T1, T2, TResult>(this Func<T1, T2, TResult> func) { return tuple => func(tuple.Item1, tuple.Item2); } public static Func<ValueTuple<T1, T2, T3>, TResult> Pack<T1, T2, T3, TResult>(this Func<T1, T2, T3, TResult> func) { return tuple => func(tuple.Item1, tuple.Item2, tuple.Item3); } public static Func<ValueTuple<T1, T2, T3, T4>, TResult> Pack<T1, T2, T3, T4, TResult>(this Func<T1, T2, T3, T4, TResult> func) { return tuple => func(tuple.Item1, tuple.Item2, tuple.Item3, tuple.Item4); } public static Func<ValueTuple<T1, T2, T3, T4, T5>, TResult> Pack<T1, T2, T3, T4, T5, TResult>(this Func<T1, T2, T3, T4, T5, TResult> func) { return tuple => func(tuple.Item1, tuple.Item2, tuple.Item3, tuple.Item4, tuple.Item5); } public static Func<ValueTuple<T1, T2, T3, T4, T5, T6>, TResult> Pack<T1, T2, T3, T4, T5, T6, TResult>(this Func<T1, T2, T3, T4, T5, T6, TResult> func) { return tuple => func(tuple.Item1, tuple.Item2, tuple.Item3, tuple.Item4, tuple.Item5, tuple.Item6); } public static Func<ValueTuple<T1, T2, T3, T4, T5, T6, T7>, TResult> Pack<T1, T2, T3, T4, T5, T6, T7, TResult>(this Func<T1, T2, T3, T4, T5, T6, T7, TResult> func) { return tuple => func(tuple.Item1, tuple.Item2, tuple.Item3, tuple.Item4, tuple.Item5, tuple.Item6, tuple.Item7); } } }
51.28125
170
0.602072
[ "MIT" ]
philiplaureano/MetaFoo
MetaFoo/MetaFoo.Core/Delegates/FuncValueTuplePackingExtensions.cs
1,643
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager; using Azure.ResourceManager.Resources; namespace Azure.ResourceManager.Dashboard { /// <summary> /// A class representing a collection of <see cref="GrafanaResource" /> and their operations. /// Each <see cref="GrafanaResource" /> in the collection will belong to the same instance of <see cref="ResourceGroupResource" />. /// To get a <see cref="GrafanaResourceCollection" /> instance call the GetGrafanaResources method from an instance of <see cref="ResourceGroupResource" />. /// </summary> public partial class GrafanaResourceCollection : ArmCollection, IEnumerable<GrafanaResource>, IAsyncEnumerable<GrafanaResource> { private readonly ClientDiagnostics _grafanaResourceGrafanaClientDiagnostics; private readonly GrafanaRestOperations _grafanaResourceGrafanaRestClient; /// <summary> Initializes a new instance of the <see cref="GrafanaResourceCollection"/> class for mocking. </summary> protected GrafanaResourceCollection() { } /// <summary> Initializes a new instance of the <see cref="GrafanaResourceCollection"/> class. </summary> /// <param name="client"> The client parameters to use in these operations. </param> /// <param name="id"> The identifier of the parent resource that is the target of operations. </param> internal GrafanaResourceCollection(ArmClient client, ResourceIdentifier id) : base(client, id) { _grafanaResourceGrafanaClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Dashboard", GrafanaResource.ResourceType.Namespace, Diagnostics); TryGetApiVersion(GrafanaResource.ResourceType, out string grafanaResourceGrafanaApiVersion); _grafanaResourceGrafanaRestClient = new GrafanaRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, grafanaResourceGrafanaApiVersion); #if DEBUG ValidateResourceId(Id); #endif } internal static void ValidateResourceId(ResourceIdentifier id) { if (id.ResourceType != ResourceGroupResource.ResourceType) throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceGroupResource.ResourceType), nameof(id)); } /// <summary> /// Create or update a workspace for Grafana resource. This API is idempotent, so user can either create a new grafana or update an existing grafana. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName} /// Operation Id: Grafana_Create /// </summary> /// <param name="waitUntil"> "F:Azure.WaitUntil.Completed" if the method should wait to return until the long-running operation has completed on the service; "F:Azure.WaitUntil.Started" if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param> /// <param name="workspaceName"> The name of Azure Managed Grafana. </param> /// <param name="data"> The GrafanaResource to use. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="workspaceName"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="workspaceName"/> is null. </exception> public virtual async Task<ArmOperation<GrafanaResource>> CreateOrUpdateAsync(WaitUntil waitUntil, string workspaceName, GrafanaResourceData data = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(workspaceName, nameof(workspaceName)); using var scope = _grafanaResourceGrafanaClientDiagnostics.CreateScope("GrafanaResourceCollection.CreateOrUpdate"); scope.Start(); try { var response = await _grafanaResourceGrafanaRestClient.CreateAsync(Id.SubscriptionId, Id.ResourceGroupName, workspaceName, data, cancellationToken).ConfigureAwait(false); var operation = new DashboardArmOperation<GrafanaResource>(new GrafanaResourceOperationSource(Client), _grafanaResourceGrafanaClientDiagnostics, Pipeline, _grafanaResourceGrafanaRestClient.CreateCreateRequest(Id.SubscriptionId, Id.ResourceGroupName, workspaceName, data).Request, response, OperationFinalStateVia.AzureAsyncOperation); if (waitUntil == WaitUntil.Completed) await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Create or update a workspace for Grafana resource. This API is idempotent, so user can either create a new grafana or update an existing grafana. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName} /// Operation Id: Grafana_Create /// </summary> /// <param name="waitUntil"> "F:Azure.WaitUntil.Completed" if the method should wait to return until the long-running operation has completed on the service; "F:Azure.WaitUntil.Started" if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param> /// <param name="workspaceName"> The name of Azure Managed Grafana. </param> /// <param name="data"> The GrafanaResource to use. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="workspaceName"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="workspaceName"/> is null. </exception> public virtual ArmOperation<GrafanaResource> CreateOrUpdate(WaitUntil waitUntil, string workspaceName, GrafanaResourceData data = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(workspaceName, nameof(workspaceName)); using var scope = _grafanaResourceGrafanaClientDiagnostics.CreateScope("GrafanaResourceCollection.CreateOrUpdate"); scope.Start(); try { var response = _grafanaResourceGrafanaRestClient.Create(Id.SubscriptionId, Id.ResourceGroupName, workspaceName, data, cancellationToken); var operation = new DashboardArmOperation<GrafanaResource>(new GrafanaResourceOperationSource(Client), _grafanaResourceGrafanaClientDiagnostics, Pipeline, _grafanaResourceGrafanaRestClient.CreateCreateRequest(Id.SubscriptionId, Id.ResourceGroupName, workspaceName, data).Request, response, OperationFinalStateVia.AzureAsyncOperation); if (waitUntil == WaitUntil.Completed) operation.WaitForCompletion(cancellationToken); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Get the properties of a specific workspace for Grafana resource. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName} /// Operation Id: Grafana_Get /// </summary> /// <param name="workspaceName"> The name of Azure Managed Grafana. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="workspaceName"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="workspaceName"/> is null. </exception> public virtual async Task<Response<GrafanaResource>> GetAsync(string workspaceName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(workspaceName, nameof(workspaceName)); using var scope = _grafanaResourceGrafanaClientDiagnostics.CreateScope("GrafanaResourceCollection.Get"); scope.Start(); try { var response = await _grafanaResourceGrafanaRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, workspaceName, cancellationToken).ConfigureAwait(false); if (response.Value == null) throw new RequestFailedException(response.GetRawResponse()); return Response.FromValue(new GrafanaResource(Client, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Get the properties of a specific workspace for Grafana resource. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName} /// Operation Id: Grafana_Get /// </summary> /// <param name="workspaceName"> The name of Azure Managed Grafana. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="workspaceName"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="workspaceName"/> is null. </exception> public virtual Response<GrafanaResource> Get(string workspaceName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(workspaceName, nameof(workspaceName)); using var scope = _grafanaResourceGrafanaClientDiagnostics.CreateScope("GrafanaResourceCollection.Get"); scope.Start(); try { var response = _grafanaResourceGrafanaRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, workspaceName, cancellationToken); if (response.Value == null) throw new RequestFailedException(response.GetRawResponse()); return Response.FromValue(new GrafanaResource(Client, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// List all resources of workspaces for Grafana under the specified resource group. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana /// Operation Id: Grafana_ListByResourceGroup /// </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <returns> An async collection of <see cref="GrafanaResource" /> that may take multiple service requests to iterate over. </returns> public virtual AsyncPageable<GrafanaResource> GetAllAsync(CancellationToken cancellationToken = default) { async Task<Page<GrafanaResource>> FirstPageFunc(int? pageSizeHint) { using var scope = _grafanaResourceGrafanaClientDiagnostics.CreateScope("GrafanaResourceCollection.GetAll"); scope.Start(); try { var response = await _grafanaResourceGrafanaRestClient.ListByResourceGroupAsync(Id.SubscriptionId, Id.ResourceGroupName, cancellationToken: cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value.Select(value => new GrafanaResource(Client, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } async Task<Page<GrafanaResource>> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _grafanaResourceGrafanaClientDiagnostics.CreateScope("GrafanaResourceCollection.GetAll"); scope.Start(); try { var response = await _grafanaResourceGrafanaRestClient.ListByResourceGroupNextPageAsync(nextLink, Id.SubscriptionId, Id.ResourceGroupName, cancellationToken: cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value.Select(value => new GrafanaResource(Client, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc); } /// <summary> /// List all resources of workspaces for Grafana under the specified resource group. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana /// Operation Id: Grafana_ListByResourceGroup /// </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <returns> A collection of <see cref="GrafanaResource" /> that may take multiple service requests to iterate over. </returns> public virtual Pageable<GrafanaResource> GetAll(CancellationToken cancellationToken = default) { Page<GrafanaResource> FirstPageFunc(int? pageSizeHint) { using var scope = _grafanaResourceGrafanaClientDiagnostics.CreateScope("GrafanaResourceCollection.GetAll"); scope.Start(); try { var response = _grafanaResourceGrafanaRestClient.ListByResourceGroup(Id.SubscriptionId, Id.ResourceGroupName, cancellationToken: cancellationToken); return Page.FromValues(response.Value.Value.Select(value => new GrafanaResource(Client, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } Page<GrafanaResource> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _grafanaResourceGrafanaClientDiagnostics.CreateScope("GrafanaResourceCollection.GetAll"); scope.Start(); try { var response = _grafanaResourceGrafanaRestClient.ListByResourceGroupNextPage(nextLink, Id.SubscriptionId, Id.ResourceGroupName, cancellationToken: cancellationToken); return Page.FromValues(response.Value.Value.Select(value => new GrafanaResource(Client, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc); } /// <summary> /// Checks to see if the resource exists in azure. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName} /// Operation Id: Grafana_Get /// </summary> /// <param name="workspaceName"> The name of Azure Managed Grafana. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="workspaceName"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="workspaceName"/> is null. </exception> public virtual async Task<Response<bool>> ExistsAsync(string workspaceName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(workspaceName, nameof(workspaceName)); using var scope = _grafanaResourceGrafanaClientDiagnostics.CreateScope("GrafanaResourceCollection.Exists"); scope.Start(); try { var response = await _grafanaResourceGrafanaRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, workspaceName, cancellationToken: cancellationToken).ConfigureAwait(false); return Response.FromValue(response.Value != null, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Checks to see if the resource exists in azure. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Dashboard/grafana/{workspaceName} /// Operation Id: Grafana_Get /// </summary> /// <param name="workspaceName"> The name of Azure Managed Grafana. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="workspaceName"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="workspaceName"/> is null. </exception> public virtual Response<bool> Exists(string workspaceName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(workspaceName, nameof(workspaceName)); using var scope = _grafanaResourceGrafanaClientDiagnostics.CreateScope("GrafanaResourceCollection.Exists"); scope.Start(); try { var response = _grafanaResourceGrafanaRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, workspaceName, cancellationToken: cancellationToken); return Response.FromValue(response.Value != null, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } IEnumerator<GrafanaResource> IEnumerable<GrafanaResource>.GetEnumerator() { return GetAll().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetAll().GetEnumerator(); } IAsyncEnumerator<GrafanaResource> IAsyncEnumerable<GrafanaResource>.GetAsyncEnumerator(CancellationToken cancellationToken) { return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); } } }
59.378378
480
0.667375
[ "MIT" ]
alexbuckgit/azure-sdk-for-net
sdk/dashboard/Azure.ResourceManager.Dashboard/src/Generated/GrafanaResourceCollection.cs
19,773
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: ComplexType.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// The type Bundle. /// </summary> [JsonObject(MemberSerialization = MemberSerialization.OptIn)] [JsonConverter(typeof(DerivedTypeConverter))] public partial class Bundle { /// <summary> /// Initializes a new instance of the <see cref="Bundle"/> class. /// </summary> public Bundle() { this.ODataType = "microsoft.graph.bundle"; } /// <summary> /// Gets or sets album. /// If the bundle is an [album][], then the album property is included /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "album", Required = Newtonsoft.Json.Required.Default)] public Album Album { get; set; } /// <summary> /// Gets or sets childCount. /// Number of children contained immediately within this container. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "childCount", Required = Newtonsoft.Json.Required.Default)] public Int32? ChildCount { get; set; } /// <summary> /// Gets or sets additional data. /// </summary> [JsonExtensionData(ReadData = true)] public IDictionary<string, object> AdditionalData { get; set; } /// <summary> /// Gets or sets @odata.type. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "@odata.type", Required = Newtonsoft.Json.Required.Default)] public string ODataType { get; set; } } }
36.967213
153
0.584035
[ "MIT" ]
GeertVL/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/model/Bundle.cs
2,255
C#
/* * 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 sagemaker-2017-07-24.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.SageMaker.Model { /// <summary> /// The inputs for a processing job. The processing input must specify exactly one of /// either <code>S3Input</code> or <code>DatasetDefinition</code> types. /// </summary> public partial class ProcessingInput { private bool? _appManaged; private DatasetDefinition _datasetDefinition; private string _inputName; private ProcessingS3Input _s3Input; /// <summary> /// Gets and sets the property AppManaged. /// <para> /// When <code>True</code>, input operations such as data download are managed natively /// by the processing job application. When <code>False</code> (default), input operations /// are managed by Amazon SageMaker. /// </para> /// </summary> public bool AppManaged { get { return this._appManaged.GetValueOrDefault(); } set { this._appManaged = value; } } // Check to see if AppManaged property is set internal bool IsSetAppManaged() { return this._appManaged.HasValue; } /// <summary> /// Gets and sets the property DatasetDefinition. /// <para> /// Configuration for a Dataset Definition input. /// </para> /// </summary> public DatasetDefinition DatasetDefinition { get { return this._datasetDefinition; } set { this._datasetDefinition = value; } } // Check to see if DatasetDefinition property is set internal bool IsSetDatasetDefinition() { return this._datasetDefinition != null; } /// <summary> /// Gets and sets the property InputName. /// <para> /// The name of the inputs for the processing job. /// </para> /// </summary> [AWSProperty(Required=true)] public string InputName { get { return this._inputName; } set { this._inputName = value; } } // Check to see if InputName property is set internal bool IsSetInputName() { return this._inputName != null; } /// <summary> /// Gets and sets the property S3Input. /// <para> /// Configuration for processing job inputs in Amazon S3. /// </para> /// </summary> public ProcessingS3Input S3Input { get { return this._s3Input; } set { this._s3Input = value; } } // Check to see if S3Input property is set internal bool IsSetS3Input() { return this._s3Input != null; } } }
30.788136
107
0.60033
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/SageMaker/Generated/Model/ProcessingInput.cs
3,633
C#
/* Copyright (c) 2016, Kevin Pope, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 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 OWNER 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. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using System.Collections.Generic; using System.Diagnostics; using System.Linq; using MatterControl.Printing; using MatterHackers.Agg.Platform; using MatterHackers.MatterControl; using MatterHackers.MatterControl.Library.Export; using MatterHackers.MatterControl.PrinterCommunication.Io; using MatterHackers.MatterControl.SlicerConfiguration; using MatterHackers.MatterControl.Tests.Automation; using MatterHackers.VectorMath; using Newtonsoft.Json; using NUnit.Framework; namespace MatterControl.Tests.MatterControl { [TestFixture, RunInApplicationDomain, Category("GCodeStream")] public class GCodeStreamTests { [SetUp] public void TestSetup() { StaticData.RootPath = TestContext.CurrentContext.ResolveProjectPath(4, "StaticData"); MatterControlUtilities.OverrideAppDataLocation(TestContext.CurrentContext.ResolveProjectPath(4)); } [Test] public void MaxLengthStreamTests() { string[] lines = new string[] { "G1 X0 Y0 Z0 E0 F500", "M105", "G1 X18 Y0 Z0 F2500", "G28", "G1 X0 Y0 Z0 E0 F500", }; // We should go back to the above code when possible. It requires making pause part and move while paused part of the stream. // All communication should go through stream to minimize the difference between printing and controlling while not printing (all printing in essence). string[] expected = new string[] { "G1 X0 Y0 Z0 E0 F500", "M105", "G1 X6 F2500", "G1 X12", "G1 X18", "G28", "G1 X0 Y0 Z0 E0 F500", }; PrinterConfig printer = null; MaxLengthStream maxLengthStream = new MaxLengthStream(printer, new TestGCodeStream(printer, lines), 6); ValidateStreamResponse(expected, maxLengthStream); } [Test] public void ExportStreamG30Tests() { string[] inputLines = new string[] { "M117 Starting Print", "M104 S0", "; comment line", "G28 ; home all axes", "G0 Z10 F1800", "G0 Z11 F1800", "G0 X1Y0Z9 F1800", "G0 Z10 F1801", "G30 Z0", "M114", "G0 Z10 F1800", "M114", "M109 S[temperature]", }; // We should go back to the above code when possible. It requires making pause part and move while paused part of the stream. // All communication should go through stream to minimize the difference between printing and controlling while not printing (all printing in essence). string[] expected = new string[] { "M117 Starting Print", "M104 S0", "; comment line", "G28 ; home all axes", "G1 Z10 F1800", "G1 Z11", "G1 X1 Y0 Z9", "G1 Z10 F1801", "G30 Z0", "M114", "G1 Z10 F1800", "M114", "M109 S[temperature]", }; var printer = new PrinterConfig(new PrinterSettings()); var testStream = GCodeExport.GetExportStream(printer, new TestGCodeStream(printer, inputLines), true); ValidateStreamResponse(expected, testStream); } [Test] public void SmoothieRewriteTest() { string[] inputLines = new string[] { "G28", "M119", }; // We should go back to the above code when possible. It requires making pause part and move while paused part of the stream. // All communication should go through stream to minimize the difference between printing and controlling while not printing (all printing in essence). string[] expected = new string[] { "G28", "M280 P0 S10.6", "G4 P400", "M280 P0 S7", "G4 P400", "M117 Ready ", "M119", "switch filament; WRITE_RAW", }; var printer = new PrinterConfig(new PrinterSettings()); var write_filter = "\"^(G28)\", \"G28,M280 P0 S10.6,G4 P400,M280 P0 S7,G4 P400,M117 Ready \""; write_filter += "\\n\"^(M119)\", \"M119,switch filament; WRITE_RAW\""; printer.Settings.SetValue(SettingsKey.write_regex, write_filter); var testStream = GCodeExport.GetExportStream(printer, new TestGCodeStream(printer, inputLines), true); ValidateStreamResponse(expected, testStream); } [Test] public void LineCuttingOffWhenNoLevelingTest() { string[] inputLines = new string[] { "G1 X0Y0Z0E0 F1000", "G1 X10 Y0 Z0 F1000", }; // We should go back to the above code when possible. It requires making pause part and move while paused part of the stream. // All communication should go through stream to minimize the difference between printing and controlling while not printing (all printing in essence). string[] expected = new string[] { "G1 X0 Y0 Z0 E0 F1000", "G1 X10", }; var printer = new PrinterConfig(new PrinterSettings()); printer.Settings.SetValue(SettingsKey.has_hardware_leveling, "1"); var testStream = GCodeExport.GetExportStream(printer, new TestGCodeStream(printer, inputLines), true); ValidateStreamResponse(expected, testStream); } [Test] public void LineCuttingOnWhenLevelingOnWithProbeTest() { string[] inputLines = new string[] { "G1 X0Y0Z0E0F1000", "G1 X0Y0Z0E1F1000", "G1 X10 Y0 Z0 F1000", }; string[] expected = new string[] { PrintLevelingStream.SoftwareLevelingAppliedMessage, "G1 X0 Y0 Z-0.1 E0 F1000", "G1 E1", "G1 X1", "G1 X2", "G1 X3", "G1 X4", "G1 X5", "G1 X6", "G1 X7", "G1 X8", "G1 X9", "G1 X10", }; var printer = new PrinterConfig(new PrinterSettings()); var levelingData = new PrintLevelingData() { SampledPositions = new List<Vector3>() { new Vector3(0, 0, 0), new Vector3(10, 0, 0), new Vector3(5, 10, 0) } }; printer.Settings.SetValue(SettingsKey.print_leveling_data, JsonConvert.SerializeObject(levelingData)); printer.Settings.SetValue(SettingsKey.has_z_probe, "1"); printer.Settings.SetValue(SettingsKey.use_z_probe, "1"); printer.Settings.SetValue(SettingsKey.probe_offset, "0,0,-.1"); printer.Settings.SetValue(SettingsKey.print_leveling_enabled, "1"); var testStream = GCodeExport.GetExportStream(printer, new TestGCodeStream(printer, inputLines), true); ValidateStreamResponse(expected, testStream); } [Test] public void LineCuttingOnWhenLevelingOnNoProbeTest() { string[] inputLines = new string[] { "G1 X0Y0Z0E0F1000", "G1 X0Y0Z0E1F1000", "G1 X10 Y0 Z0 F1000", }; string[] expected = new string[] { PrintLevelingStream.SoftwareLevelingAppliedMessage, "G1 X0 Y0 Z-0.1 E0 F1000", "G1 E1", "G1 X1", "G1 X2", "G1 X3", "G1 X4", "G1 X5", "G1 X6", "G1 X7", "G1 X8", "G1 X9", "G1 X10", }; var printer = new PrinterConfig(new PrinterSettings()); var levelingData = new PrintLevelingData() { SampledPositions = new List<Vector3>() { new Vector3(0, 0, -.1), new Vector3(10, 0, -.1), new Vector3(5, 10, -.1) } }; printer.Settings.SetValue(SettingsKey.print_leveling_data, JsonConvert.SerializeObject(levelingData)); printer.Settings.SetValue(SettingsKey.probe_offset, "0,0,-.1"); printer.Settings.SetValue(SettingsKey.print_leveling_enabled, "1"); var testStream = GCodeExport.GetExportStream(printer, new TestGCodeStream(printer, inputLines), true); ValidateStreamResponse(expected, testStream); } public static GCodeStream CreateTestGCodeStream(PrinterConfig printer, string[] inputLines, out List<GCodeStream> streamList) { streamList = new List<GCodeStream>(); streamList.Add(new TestGCodeStream(printer, inputLines)); streamList.Add(new PauseHandlingStream(printer, streamList[streamList.Count - 1])); streamList.Add(new QueuedCommandsStream(printer, streamList[streamList.Count - 1])); streamList.Add(new RelativeToAbsoluteStream(printer, streamList[streamList.Count - 1])); streamList.Add(new WaitForTempStream(printer, streamList[streamList.Count - 1])); streamList.Add(new BabyStepsStream(printer, streamList[streamList.Count - 1])); streamList.Add(new MaxLengthStream(printer, streamList[streamList.Count - 1], 1)); streamList.Add(new ExtrusionMultiplierStream(printer, streamList[streamList.Count - 1])); streamList.Add(new FeedRateMultiplierStream(printer, streamList[streamList.Count - 1])); GCodeStream totalGCodeStream = streamList[streamList.Count - 1]; return totalGCodeStream; } [Test] public void RegexReplacementStreamIsLast() { var printer = new PrinterConfig(new PrinterSettings()); var context = GCodeExport.GetExportStream(printer, new TestGCodeStream(printer, new[] { "" }), true); var streamProcessors = new List<GCodeStream>(); while (context is GCodeStream gCodeStream) { streamProcessors.Add(context); context = gCodeStream.InternalStream; } Assert.IsTrue(streamProcessors.First() is ProcessWriteRegexStream, "ProcessWriteRegexStream should be the last stream in the stack"); } [Test] public void CorrectEOutputPositionsG91() { string[] inputLines = new string[] { "G1 E11 F300", // E = 11 // Before: "G92 E0", // E = 0 "G91", "G1 E - 5 F302", // E = -5 "G90", // After: "G91", "G1 E8 F150", // E = 3 "G90", "G4 P0", "G92 E0", // E = 0 "G4 P0", "G91", "G1 E-2 F301", // E = -2 "G90", }; // We should go back to the above code when possible. It requires making pause part and move while paused part of the stream. // All communication should go through stream to minimize the difference between printing and controlling while not printing (all printing in essence). string[] expected = new string[] { "G1 E11 F300", "G92 E0", "", "G1 E-1 F302", "G1 E-2", "G1 E-3", "G1 E-4", "G1 E-5", "G90", "", // 10 "G1 E-4 F150", "G1 E-3", "G1 E-2", "G1 E-1", "G1 E0", "G1 E1", "G1 E2", "G1 E3", "", "G4 P0", "G92 E0", "G4 P0", "", "G1 E-1 F301", "G1 E-2", "", }; var printer = new PrinterConfig(new PrinterSettings()); GCodeStream testStream = CreateTestGCodeStream(printer, inputLines, out List<GCodeStream> streamList); ValidateStreamResponse(expected, testStream); } [Test] public void CorrectEOutputPositionsM83() { string[] inputLines = new string[] { "G1 E11 F300", // Before: "G92 E0", "M83", // relative extruder "G1 E - 5 F302", "M82", // After: "M83", "G1 E8 F150", "M82", "G4 P0", "G92 E0", "G4 P0", "M83", "G1 E-2 F301", "M82", "G1 E2 F301", }; string[] expected = new string[] { "G1 E11 F300", "G92 E0", "", "G1 E-1 F302", "G1 E-2", "G1 E-3", "G1 E-4", "G1 E-5", "M82", "", // 10 "G1 E-4 F150", "G1 E-3", "G1 E-2", "G1 E-1", "G1 E0", "G1 E1", "G1 E2", "G1 E3", "", "G4 P0", // 20 "G92 E0", "G4 P0", "", "G1 E-1 F301", "G1 E-2", "", "G1 E-1", "G1 E0", "G1 E1", "G1 E2", // 30 }; var printer = new PrinterConfig(new PrinterSettings()); GCodeStream testStream = CreateTestGCodeStream(printer, inputLines, out List<GCodeStream> streamList); ValidateStreamResponse(expected, testStream); } [Test] public void CorrectEOutputForMiniStartupWithM83() { string[] inputLines = new string[] { "G21 ; set units to millimeters", "M107 ; fan off", "T0 ; set the active extruder to 0", "; settings from start_gcode", "M83", "M104 S170 ; set hotend temperature for bed leveling", "M140 S60 ; set bed temperature", "M109 R170", "G28", "G29", "M104 S215 ; set hotend temperature", "G92 E0.0", "G1 X0 Y0 F2400", "G1 Z3 F720", "G92 E0.0", "G1 X5 F1000", "G1 Z0 F720", "G1 X10 E5 F900", "G1 X15 E5", "G92 E0.0", "; automatic settings after start_gcode", "T0 ; set the active extruder to 0", "G90 ; use absolute coordinates", "G92 E0 ; reset the expected extruder position", "M82 ; use absolute distance for extrusion", "G1 E5 F440", "G1 E10", }; string[] expected = new string[] { "G21 ; set units to millimeters", "M107 ; fan off", "T0 ; set the active extruder to 0", "; settings from start_gcode", "", // set to relative e "M104 S170 ; set hotend temperature for bed leveling", "M140 S60 ; set bed temperature", "M109 R170", "G28", "G29", // 10 "M104 S215 ; set hotend temperature", "G92 E0.0", "G1 F2400", "G1 Z1 F720", "G1 Z2", "G1 Z3", "G92 E0.0", "G1 X1 F1000", "G1 X2", "G1 X3", // 20 "G1 X4", "G1 X5", "G1 F720", "G1 X6 E1 F900", "G1 X7 E2", "G1 X8 E3", "G1 X9 E4", "G1 X10 E5", "G1 X11 E6", "G1 X12 E7", // 30 "G1 X13 E8", "G1 X14 E9", "G1 X15 E10", "G92 E0.0", "; automatic settings after start_gcode", "T0 ; set the active extruder to 0", "G90 ; use absolute coordinates", "G92 E0 ; reset the expected extruder position", "M82 ; use absolute distance for extrusion", "G1 E1 F440", // 40 "G1 E2", "G1 E3", "G1 E4", "G1 E5", "G1 E6", "G1 E7", "G1 E8", "G1 E9", "G1 E10", }; var printer = new PrinterConfig(new PrinterSettings()); GCodeStream testStream = CreateTestGCodeStream(printer, inputLines, out List<GCodeStream> streamList); ValidateStreamResponse(expected, testStream); } [Test] public void CorrectZOutputPositions() { string[] inputLines = new string[] { "G1 Z-2 F300", "G92 Z0", "G1 Z5 F300", "G28", }; // We should go back to the above code when possible. It requires making pause part and move while paused part of the stream. // All communication should go through stream to minimize the difference between printing and controlling while not printing (all printing in essence). string[] expected = new string[] { "G1 Z-2 F300", "G92 Z0", "G1 Z1 F300", "G1 Z2", "G1 Z3", "G1 Z4", "G1 Z5", "G28", }; var printer = new PrinterConfig(new PrinterSettings()); GCodeStream testStream = CreateTestGCodeStream(printer, inputLines, out List<GCodeStream> streamList); ValidateStreamResponse(expected, testStream); } [Test] public void PauseHandlingStreamTests() { int readX = 50; // Validate that the number parsing code is working as expected, specifically ignoring data that appears in comments // This is a regression that we saw in the Lulzbot Mini profile after adding macro processing. GCodeFile.GetFirstNumberAfter("X", "G1 Z10 E - 10 F12000 ; suck up XXmm of filament", ref readX); // did not change Assert.AreEqual(50, readX, "Don't change the x if it is after a comment"); // a comments that looks more like a valid line GCodeFile.GetFirstNumberAfter("X", "G1 Z10 E - 10 F12000 ; X33", ref readX); // did not change Assert.AreEqual(50, readX, "Don't change the x if it is after a comment"); // a line that should parse GCodeFile.GetFirstNumberAfter("X", "G1 Z10 E - 10 F12000 X33", ref readX); // did change Assert.AreEqual(33, readX, "not in a comment, do a change"); string[] inputLines = new string[] { "; the printer is moving normally", "G1 X10 Y10 Z10 E0", "G1 X10 Y10 Z10 E10", "G1 X10 Y10 Z10 E30", "; the printer pauses", "G91", "G1 Z10 E - 10 F12000 ; suck up XXmm of filament", "G90", "; the user moves the printer", "; the printer un-pauses", "G91", "G1 Z-10 E10.8 F12000", "G90", }; // We should go back to the above code when possible. It requires making pause part and move while paused part of the stream. // All communication should go through stream to minimize the difference between printing and controlling while not printing (all printing in essence). string[] expected = new string[] { "; the printer is moving normally", "G1 X10 Y10 Z10 E0", "G1 E10", "G1 E30", "; the printer pauses", "", // G91 is removed "G1 Z20 E20 F12000", // altered to be absolute "G90", "; the user moves the printer", "; the printer un-pauses", "", // G91 is removed "G1 Z10 E30.8", "", // G90 is removed }; var printer = new PrinterConfig(new PrinterSettings()); GCodeStream pauseHandlingStream = CreateTestGCodeStream(printer, inputLines, out List<GCodeStream> streamList); ValidateStreamResponse(expected, pauseHandlingStream); } [Test, Ignore("WIP")] public void SoftwareEndstopstreamTests() { string[] inputLines = new string[] { // test x min // move without extrusion "G1 X100Y100Z0E0", // start at the bed center "G1 X-100", // move left off the bed "G1 Y110", // move while outside bounds "G1 X100", // move back on // move with extrusion "G1 X100Y100Z0E0", // start at the bed center "G1 X-100E10", // move left off the bed "G1 Y110E20", // move while outside bounds "G1 X100E30", // move back on // test x max // test y min // test y max // test z min // test z max }; // We should go back to the above code when possible. It requires making pause part and move while paused part of the stream. // All communication should go through stream to minimize the difference between printing and controlling while not printing (all printing in essence). string[] expected = new string[] { // move without extrusion "G1 X100 Y100 Z0 E0", // start position "G1 X0", // clamped x "", // move while outside "G1 Y110", // first position back in bounds "G1 X100", // move to requested x // move with extrusion "G1 X100Y100Z0E0", // start at the bed center "G1 X-100E10", // move left off the bed "G1 Y110E20", // move while outside bounds "G1 X100E30", // move back on }; var printer = new PrinterConfig(new PrinterSettings()); var pauseHandlingStream = new SoftwareEndstopsStream(printer, new TestGCodeStream(printer, inputLines)); ValidateStreamResponse(expected, pauseHandlingStream); } [Test] public void MorePauseHandlingStreamTests() { string[] inputLines = new string[] { "; the printer is moving normally", "G1 X10 Y10 Z10 E0", "G1 X11 Y10 Z10 E10", "G1 X12 Y10 Z10 E30", "; the printer pauses", "@pause", "; do_resume", // just a marker for us to issue a resume // move some more "G1 X13 Y10 Z10 E40", }; // We should go back to the above code when possible. It requires making pause part and move while paused part of the stream. // All communication should go through stream to minimize the difference between printing and controlling while not printing (all printing in essence). string[] expected = new string[] { "; the printer is moving normally", "G1 X10 Y10 Z10 E0", "G1 X11 E10", "G1 X12 E30", "; the printer pauses", "", "", "G1 Z20 E20 F12000", "G90", "M114", "", "; do_resume", "G92 E-10", "G1 Z16.67 F3001", "G1 X12.01 Y10.01 Z13.34", "G1 Z10.01", "G1 X12 Y10 Z10 F3000", "", "G1 Z0 E30.8 F12000", "", // G90 removed "M114", "", "G1 X12.1 F1800", "G1 X12.2", "", // G90 removed "G1 X12.33 Z1.667 E32.333", "G1 X12.47 Z3.333 E33.867", "G1 X12.6 Z5 E35.4", "G1 X12.73 Z6.667 E36.933", "G1 X12.87 Z8.333 E38.467", "G1 X13 Z10 E40", }; // this is the pause and resume from the Eris var printer = new PrinterConfig(new PrinterSettings()); printer.Settings.SetValue(SettingsKey.pause_gcode, "G91\nG1 Z10 E - 10 F12000\n G90"); printer.Settings.SetValue(SettingsKey.resume_gcode, "G91\nG1 Z-10 E10.8 F12000\nG90"); GCodeStream pauseHandlingStream = CreateTestGCodeStream(printer, inputLines, out List<GCodeStream> streamList); ValidateStreamResponse(expected, pauseHandlingStream, streamList); } public static void ValidateStreamResponse(string[] expected, GCodeStream testStream, List<GCodeStream> streamList = null) { int lineIndex = 0; // Advance string actualLine = testStream.ReadLine(); string expectedLine = expected[lineIndex++]; while (actualLine != null) { if (actualLine.StartsWith("G92 E0")) { testStream.SetPrinterPosition(new PrinterMove(default(Vector3), 0, 300)); } if (actualLine.StartsWith("G92 Z0")) { testStream.SetPrinterPosition(new PrinterMove(new Vector3(), 0, 0)); } if (actualLine == "; do_resume") { PauseHandlingStream pauseStream = null; foreach (var stream in streamList) { if (stream as PauseHandlingStream != null) { pauseStream = (PauseHandlingStream)stream; pauseStream.Resume(); } } } if (expectedLine != actualLine) { int a = 0; } Debug.WriteLine(actualLine); Assert.AreEqual(expectedLine, actualLine, "Unexpected response from testStream"); // Advance actualLine = testStream.ReadLine(); if (lineIndex < expected.Length) { expectedLine = expected[lineIndex++]; } } } [Test] public void KnownLayerLinesTest() { Assert.AreEqual(8, GCodeFile.GetLayerNumber("; layer 8, Z = 0.800"), "Simplify3D ~ 2019"); Assert.AreEqual(1, GCodeFile.GetLayerNumber("; LAYER:1"), "Cura/MatterSlice"); Assert.AreEqual(7, GCodeFile.GetLayerNumber(";LAYER:7"), "Slic3r Prusa Edition 1.38.7-prusa3d on 2018-04-25"); } [Test] public void WriteReplaceStreamTests() { string[] inputLines = new string[] { "; the printer is moving normally", "G1 X10 Y10 Z10 E0", "M114", "G29", "G28", "G28 X0", "M107", "M107 ; extra stuff", }; string[] expected = new string[] { "; the printer is moving normally", "G1 X10 Y10 Z10 E0", "M114", "G29", "G28", "M115", "G28 X0", "M115", "; none", "; none ; extra stuff", }; var printer = new PrinterConfig(new PrinterSettings()); printer.Settings.SetValue(SettingsKey.write_regex, "\"^(G28)\",\"G28,M115\"\\n\"^(M107)\",\"; none\""); var inputLinesStream = new TestGCodeStream(printer, inputLines); var queueStream = new QueuedCommandsStream(printer, inputLinesStream); var writeStream = new ProcessWriteRegexStream(printer, queueStream, queueStream); ValidateStreamResponse(expected, writeStream); } [Test] public void FeedRateRatioChangesFeedRate() { string line; PrinterConfig printer = new PrinterConfig(new PrinterSettings()); var gcodeStream = new FeedRateMultiplierStream(printer, new TestGCodeStream(printer, new string[] { "G1 X10 F1000", "G1 Y5 F1000" })); Assert.AreEqual(1, (int)gcodeStream.FeedRateRatio, "FeedRateRatio should default to 1"); line = gcodeStream.ReadLine(); Assert.AreEqual("G1 X10 F1000", line, "FeedRate should remain unchanged when FeedRateRatio is 1.0"); gcodeStream.FeedRateRatio = 2; line = gcodeStream.ReadLine(); Assert.AreEqual("G1 Y5 F2000", line, "FeedRate should scale from F1000 to F2000 when FeedRateRatio is 2x"); } [Test] public void ExtrusionRatioChangesExtrusionAmount() { string line; PrinterConfig printer = new PrinterConfig(new PrinterSettings()); var gcodeStream = new ExtrusionMultiplierStream(printer, new TestGCodeStream(printer, new string[] { "G1 E10", "G1 E0 ; Move back to 0", "G1 E12" })); Assert.AreEqual(1, (int)gcodeStream.ExtrusionRatio, "ExtrusionRatio should default to 1"); line = gcodeStream.ReadLine(); // Move back to E0 gcodeStream.ReadLine(); Assert.AreEqual("G1 E10", line, "ExtrusionMultiplier should remain unchanged when FeedRateRatio is 1.0"); gcodeStream.ExtrusionRatio = 2; line = gcodeStream.ReadLine(); Assert.AreEqual("G1 E24", line, "ExtrusionMultiplier should scale from E12 to E24 when ExtrusionRatio is 2x"); } } public class TestGCodeStream : GCodeStream { private int index = 0; private string[] lines; public TestGCodeStream(PrinterConfig printer, string[] lines) : base(printer) { this.lines = lines; } public override void Dispose() { } public override string ReadLine() { return index < lines.Length ? lines[index++] : null; } public override void SetPrinterPosition(PrinterMove position) { } public override GCodeStream InternalStream => null; public override string DebugInfo => ""; } }
28.339912
154
0.655459
[ "BSD-2-Clause" ]
fortsnek9348/MatterControl
Tests/MatterControl.Tests/MatterControl/GCodeStreamTests.cs
25,848
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemySpawner : MonoBehaviour { public bool isGameOver; public int gameLevel; public GameObject squareEnemy; private void Awake() { isGameOver = false; } // Use this for initialization void Start () { gameLevel = 1; StartCoroutine(SquareEnemyInstantiator()); } // Update is called once per frame void Update () { } private void FixedUpdate() { } IEnumerator SquareEnemyInstantiator() { while (isGameOver == false) { float randomEnemyX = Random.Range(squareEnemy.GetComponent<SquareEnemyController>().spawnPoints[0], squareEnemy.GetComponent<SquareEnemyController>().spawnPoints[2]); float randomEnemyY = Random.Range(squareEnemy.GetComponent<SquareEnemyController>().spawnPoints[1], squareEnemy.GetComponent<SquareEnemyController>().spawnPoints[3]); if (gameLevel == 1) { Instantiate(squareEnemy, new Vector3(randomEnemyX, randomEnemyY, 0), Quaternion.identity); yield return new WaitForSeconds(squareEnemy.GetComponent<SquareEnemyController>().spawnTime); } } yield return null; } }
28.723404
179
0.632593
[ "MIT" ]
umutefiloglu/Space-Shooter-2D
EnemySpawner.cs
1,352
C#
using System; using System.Collections.Generic; using Aop.Api.Response; namespace Aop.Api.Request { /// <summary> /// AOP API: alipay.micropay.order.get /// </summary> public class AlipayMicropayOrderGetRequest : IAopRequest<AlipayMicropayOrderGetResponse> { /// <summary> /// 支付宝订单号,冻结流水号(创建冻结订单返回) /// </summary> public string AlipayOrderNo { get; set; } #region IAopRequest Members private bool needEncrypt=false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private AopObject bizModel; public void SetNeedEncrypt(bool needEncrypt){ this.needEncrypt=needEncrypt; } public bool GetNeedEncrypt(){ return this.needEncrypt; } public void SetNotifyUrl(string notifyUrl){ this.notifyUrl = notifyUrl; } public string GetNotifyUrl(){ return this.notifyUrl; } public void SetTerminalType(String terminalType){ this.terminalType=terminalType; } public string GetTerminalType(){ return this.terminalType; } public void SetTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public string GetTerminalInfo(){ return this.terminalInfo; } public void SetProdCode(String prodCode){ this.prodCode=prodCode; } public string GetProdCode(){ return this.prodCode; } public string GetApiName() { return "alipay.micropay.order.get"; } public void SetApiVersion(string apiVersion){ this.apiVersion=apiVersion; } public string GetApiVersion(){ return this.apiVersion; } public IDictionary<string, string> GetParameters() { AopDictionary parameters = new AopDictionary(); parameters.Add("alipay_order_no", this.AlipayOrderNo); return parameters; } public AopObject GetBizModel() { return this.bizModel; } public void SetBizModel(AopObject bizModel) { this.bizModel = bizModel; } #endregion } }
23.42
92
0.606319
[ "MIT" ]
erikzhouxin/CSharpSolution
OSS/Alipay/F2FPayDll/Projects/alipay-sdk-NET20161213174056/Request/AlipayMicropayOrderGetRequest.cs
2,382
C#
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; using System.Reflection; using WolvenKit.RED4.CR2W; using WolvenKit.Common.Model.Cr2w; using WolvenKit.RED4.CR2W.Reflection; using CP77Types = WolvenKit.RED4.CR2W.Types; namespace GraphEditor.CP77.Quest { using AddSocketFn = Action<string /* name */, CP77Types.Enums.questSocketType /* socketType */>; static partial class NodeFactory { public static IReadOnlyList<Editor.IGraphNodeCreateParams> NodesCreateParamsList => _nodesCreateParamsList; static List<Editor.IGraphNodeCreateParams> _nodesCreateParamsList; static NodeFactory() { _nodesCreateParamsList = new List<Editor.IGraphNodeCreateParams>(); var allQuestNodes = AssemblyDictionary.GetSubClassesOf(typeof(CP77Types.questNodeDefinition)); foreach (var questNodeType in allQuestNodes) { if (questNodeType == typeof(CP77Types.questDisableableNodeDefinition) || questNodeType == typeof(CP77Types.questStartEndNodeDefinition) || questNodeType == typeof(CP77Types.questIONodeDefinition) || questNodeType == typeof(CP77Types.questSignalStoppingNodeDefinition) || questNodeType == typeof(CP77Types.questTypedSignalStoppingNodeDefinition) || questNodeType == typeof(CP77Types.questEmbeddedGraphNodeDefinition) || questNodeType == typeof(CP77Types.questAICommandNodeBase) || questNodeType == typeof(CP77Types.questLogicalBaseNodeDefinition) || questNodeType == typeof(CP77Types.questConfigurableAICommandNode) || questNodeType == typeof(CP77Types.questBaseObjectNodeDefinition)) { continue; } _nodesCreateParamsList.Add(new CP77NodeCreateParams(questNodeType, CreateGraphNode)); } } public static CP77Types.CHandle<CP77Types.graphGraphNodeDefinition> CreateQuestNode(long id, string typeName, CR2WFile cr2wFile, CP77Types.CVariable parent = null, string uniqueName = null) { if (id > ushort.MaxValue) { MainWindow.ShowPopup("Can't create more than 65535 nodes"); return null; } var nodeChunk = cr2wFile.CreateChunkEx(typeName); var nodeHandle = new CP77Types.CHandle<CP77Types.graphGraphNodeDefinition>(cr2wFile, parent, uniqueName ?? string.Empty); nodeHandle.SetReference(nodeChunk); var questNode = (CP77Types.questNodeDefinition)nodeHandle.GetInstance(); questNode.Id.IsSerialized = true; questNode.Id.Value = (ushort)id; return nodeHandle; } public static CP77Types.CHandle<CP77Types.graphGraphSocketDefinition> CreateQuestSocket(string name, CP77Types.Enums.questSocketType socketType, CR2WFile cr2wFile, CP77Types.CVariable parent = null, string uniqueName = null) { var socketChunk = cr2wFile.CreateChunkEx("questSocketDefinition"); var socketHandle = new CP77Types.CHandle<CP77Types.graphGraphSocketDefinition>(cr2wFile, parent, uniqueName ?? string.Empty); socketHandle.SetReference(socketChunk); var questSocket = socketHandle.GetInstance<CP77Types.questSocketDefinition>(); questSocket.Name.IsSerialized = true; questSocket.Name.Value = name; questSocket.Type.IsSerialized = true; questSocket.Type.Value = socketType; return socketHandle; } public static void AddNodeSockets(IEditableVariable obj, AddSocketFn addInputSocket, AddSocketFn addOutputSocket) { var bindingFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod; //for (Type currentType = obj.GetType(); currentType != null && currentType != typeof(CP77Types.questNodeDefinition); currentType = currentType.BaseType) { Type currentType = obj.GetType(); var method = typeof(NodeFactory).GetMethod($"AddNodeSockets_{currentType.Name}", bindingFlags); if (method != null) { method.Invoke(null, new object[] { Convert.ChangeType(obj, currentType), addInputSocket, addOutputSocket }); return; } } } public static GraphNode CreateGraphNodeByReflection(CP77Types.CHandle<CP77Types.graphGraphNodeDefinition> nodeHandle) { var nodeDef = nodeHandle.GetInstance<CP77Types.questNodeDefinition>(); var id = (long)nodeDef.Id.Value; var name = nodeDef.REDType; GraphNode node = null; var currentAssembly = Assembly.GetExecutingAssembly(); for (var nodeDefType = nodeDef.GetType(); nodeDefType != typeof(CP77Types.graphIGraphObjectDefinition); nodeDefType = nodeDefType.BaseType) { var nodeType = currentAssembly.GetType($"{typeof(Graph).Namespace}.CustomNodes.{nodeDefType.Name}"); if (nodeType == null) continue; var @params = new object[3] { nodeHandle, id, name }; var bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; node = (GraphNode)Activator.CreateInstance(nodeType, bindingFlags, null, @params, null); } if (node == null) { node = new GraphNode(nodeHandle, id, name); } return node; } public static GraphSocket CreateGraphSocket(long id, string name, CP77Types.Enums.questSocketType socketType, CP77Types.graphGraphNodeDefinition parentNode) { var socketHandle = CreateQuestSocket(name, socketType, (CR2WFile)parentNode.Cr2wFile, parentNode.Sockets); return CreateGraphSocket(id, name, socketHandle); } public static GraphSocket CreateGraphSocket(long id, string name, CP77Types.CHandle<CP77Types.graphGraphSocketDefinition> socketHandle) { return new GraphSocket(socketHandle, id, name); } public static GraphNode CreateGraphNode(string typeName, Vector2 position) { var graph = (Graph)Editor.GraphContext.CurrentContext.Graph; var nodeHandle = CreateQuestNode(graph.GetNextNodeID(), typeName, graph.CR2WFile, graph.GraphDef.Nodes); if (nodeHandle == null) return null; var node = CreateGraphNodeByReflection(nodeHandle); AddNodeSockets(nodeHandle.Reference.data, (name, socketType) => node.AddInputSocket(CreateGraphSocket(node.GetNextInputSocketID(), name, socketType, node.NodeDef)), (name, socketType) => node.AddOutputSocket(CreateGraphSocket(node.GetNextOutputSocketID(), name, socketType, node.NodeDef))); node.Position = position; return node; } static void CreateGraphNode(Vector2 position, CP77NodeCreateParams @params) { var graph = (Graph)Editor.GraphContext.CurrentContext.Graph; var node = CreateGraphNode(@params.NodeType.Name, position); graph.AddNode(node); } } }
48.044872
232
0.6503
[ "MIT" ]
0xSombra/GraphEditor
GraphEditor/CP77/Quest/NodeFactory.cs
7,497
C#
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Chinook.DataEF; using Chinook.Domain.Repositories; using Chinook.Domain.Entities; using Microsoft.EntityFrameworkCore; namespace Chinook.DataEFCore.Repositories { public class CustomerRepository : ICustomerRepository { private readonly ChinookContext _context; public CustomerRepository(ChinookContext context) { _context = context; } private async Task<bool> CustomerExists(int id) => await _context.Customers.AnyAsync(c => c.Id == id); public void Dispose() => _context.Dispose(); public async Task<List<Customer>> GetAll() => await _context.Customers.ToListAsync(); public async Task<Customer> GetById(int id) => await _context.Customers.FindAsync(id); public async Task<Customer> Add(Customer newCustomer) { await _context.Customers.AddAsync(newCustomer); await _context.SaveChangesAsync(); return newCustomer; } public async Task<bool> Update(Customer customer) { if (!await CustomerExists(customer.Id)) return false; _context.Customers.Update(customer); await _context.SaveChangesAsync(); return true; } public async Task<bool> Delete(int id) { if (!await CustomerExists(id)) return false; var toRemove = await _context.Customers.FindAsync(id); _context.Customers.Remove(toRemove); await _context.SaveChangesAsync(); return true; } public async Task<List<Customer>> GetBySupportRepId(int id) => await _context.Customers.Where(a => a.SupportRepId == id).ToListAsync(); } }
31.15
84
0.623863
[ "MIT" ]
ANgajasinghe/ChinookASPNETWebAPI
ChinookASPNETWebAPI/Chinook.DataEF/Repositories/CustomerRepository.cs
1,871
C#
using System.Collections.Generic; namespace JsonInterfaceSerialize.DataModels.DataInterfaces { public interface IJisCountry { long Area { get; set; } string Capital { get; set; } string Name { get; set; } string OfficialName { get; set; } long Population { get; set; } IList<IJisState> States { get; set; } } }
24.866667
58
0.613941
[ "Apache-2.0" ]
sajidak/JsonInterfaceSerialize
JsonInterfaceSerialize/DataModels/DataInterfaces/IJisCountry.cs
375
C#
#pragma warning disable IDE1006, S101 // Naming Styles namespace SJP.Schematic.Sqlite.Pragma.Query { /// <summary> /// Stores information on key columns within an index. /// </summary> public sealed record pragma_index_info { /// <summary> /// The rank of the column within the index. /// </summary> public long seqno { get; init; } /// <summary> /// The rank of the column within the table. /// </summary> public int cid { get; init; } /// <summary> /// The name of the column being indexed. This column is <c>null</c> if the column is the rowid or an expression. /// </summary> public string? name { get; init; } } } #pragma warning restore IDE1006, S101 // Naming Styles
32.8
122
0.570732
[ "MIT" ]
sjp/Schematic
src/SJP.Schematic.Sqlite/Pragma/Query/pragma_index_info.cs
822
C#
using Microsoft.EntityFrameworkCore; using OpenBudgeteer.Core.Common.Database; using OpenBudgeteer.Core.Models; namespace OpenBudgeteer.Core.ViewModels.ItemViewModels; public class MappingRuleViewModelItem : ViewModelBase { private MappingRule _mappingRule; /// <summary> /// Reference to model object in the database /// </summary> public MappingRule MappingRule { get => _mappingRule; set => Set(ref _mappingRule, value); } private string _ruleOutput; /// <summary> /// Helper property to generate a readable output for <see cref="MappingRule"/> /// </summary> public string RuleOutput { get => _ruleOutput; set => Set(ref _ruleOutput, value); } private readonly DbContextOptions<DatabaseContext> _dbOptions; /// <summary> /// Basic constructor /// </summary> /// <param name="dbOptions">Options to connect to a database</param> public MappingRuleViewModelItem(DbContextOptions<DatabaseContext> dbOptions) { _dbOptions = dbOptions; } /// <summary> /// Initialize ViewModel with an existing <see cref="MappingRule"/> object /// </summary> /// <param name="dbOptions">Options to connect to a database</param> /// <param name="mappingRule">MappingRule instance</param> public MappingRuleViewModelItem(DbContextOptions<DatabaseContext> dbOptions, MappingRule mappingRule) : this(dbOptions) { MappingRule = mappingRule; GenerateRuleOutput(); } /// <summary> /// Translates <see cref="MappingRule"/> object into a readable format /// </summary> public void GenerateRuleOutput() { RuleOutput = MappingRule == null ? string.Empty : $"{MappingRule.ComparisonFieldOutput} " + $"{MappingRule.ComparisionTypeOutput} " + $"{MappingRule.ComparisionValue}"; } }
30.725806
123
0.660892
[ "Apache-2.0", "MIT" ]
Hazy87/OpenBudgeteer
OpenBudgeteer.Core/ViewModels/ItemViewModels/MappingRuleViewModelItem.cs
1,907
C#
/********************************************************************* * * Copyright (C) 2002 Andrew Khan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ***************************************************************************/ // Port to C# // Chris Laforet // Wachovia, a Wells-Fargo Company // Feb 2010 using CSharpJExcel.Jxl.Biff; using CSharpJExcel.Jxl.Biff.Formula; using CSharpJExcel.Jxl.Common; namespace CSharpJExcel.Jxl.Read.Biff { /** * A string formula's last calculated value */ class StringFormulaRecord : CellValue,LabelCell,FormulaData,StringFormulaCell { /** * The logger */ //private static Logger logger = Logger.getLogger(StringFormulaRecord.class); /** * The last calculated value of the formula */ private string value; /** * A handle to the class needed to access external sheets */ private ExternalSheet externalSheet; /** * A handle to the name table */ private WorkbookMethods nameTable; /** * The formula as an excel string */ private string formulaString; /** * The raw data */ private byte[] data; /** * Constructs this object from the raw data. We need to use the excelFile * to retrieve the string record which follows this formula record * * @param t the raw data * @param excelFile the excel file * @param fr the formatting records * @param es the external sheet records * @param nt the workbook * @param si the sheet impl * @param ws the workbook settings */ public StringFormulaRecord(Record t,File excelFile, FormattingRecords fr, ExternalSheet es, WorkbookMethods nt, SheetImpl si, WorkbookSettings ws) : base(t,fr,si) { externalSheet = es; nameTable = nt; data = getRecord().getData(); int pos = excelFile.getPos(); // Look for the string record in one of the records after the // formula. Put a cap on it to prevent looping Record nextRecord = excelFile.next(); int count = 0; while (nextRecord.getType() != Type.STRING && count < 4) { nextRecord = excelFile.next(); count++; } Assert.verify(count < 4," @ " + pos); byte[] stringData = nextRecord.getData(); // Read in any continuation records nextRecord = excelFile.peek(); while (nextRecord.getType() == Type.CONTINUE) { nextRecord = excelFile.next(); // move the pointer within the data byte[] d = new byte[stringData.Length + nextRecord.getLength() - 1]; System.Array.Copy(stringData,0,d,0,stringData.Length); System.Array.Copy(nextRecord.getData(),1,d, stringData.Length,nextRecord.getLength() - 1); stringData = d; nextRecord = excelFile.peek(); } readString(stringData,ws); } /** * Constructs this object from the raw data. Used when reading in formula * strings which evaluate to null (in the case of some IF statements) * * @param t the raw data * @param fr the formatting records * @param es the external sheet records * @param nt the workbook * @param si the sheet impl * @param ws the workbook settings */ public StringFormulaRecord(Record t, FormattingRecords fr, ExternalSheet es, WorkbookMethods nt, SheetImpl si) : base(t,fr,si) { externalSheet = es; nameTable = nt; data = getRecord().getData(); value = string.Empty; } /** * Reads in the string * * @param d the data * @param ws the workbook settings */ private void readString(byte[] d,WorkbookSettings ws) { int pos = 0; int chars = IntegerHelper.getInt(d[0],d[1]); if (chars == 0) { value = string.Empty; return; } pos += 2; int optionFlags = d[pos]; pos++; if ((optionFlags & 0xf) != optionFlags) { // Uh oh - looks like a plain old string, not unicode // Recalculate all the positions pos = 0; chars = IntegerHelper.getInt(d[0],(byte)0); optionFlags = d[1]; pos = 2; } // See if it is an extended string bool extendedString = ((optionFlags & 0x04) != 0); // See if string contains formatting information bool richString = ((optionFlags & 0x08) != 0); if (richString) { pos += 2; } if (extendedString) { pos += 4; } // See if string is ASCII (compressed) or unicode bool asciiEncoding = ((optionFlags & 0x01) == 0); if (asciiEncoding) { value = StringHelper.getString(d,chars,pos,ws); } else { value = StringHelper.getUnicodeString(d,chars,pos); } } /** * Interface method which returns the value * * @return the last calculated value of the formula */ public override string getContents() { return value; } /** * Interface method which returns the value * * @return the last calculated value of the formula */ public string getString() { return value; } /** * Returns the cell type * * @return The cell type */ public override CellType getType() { return CellType.STRING_FORMULA; } /** * Gets the raw bytes for the formula. This will include the * parsed tokens array * * @return the raw record data */ public byte[] getFormulaData() { if (!getSheet().getWorkbook().getWorkbookBof().isBiff8()) { throw new FormulaException(FormulaException.BIFF8_SUPPORTED); } // Lop off the standard information byte[] d = new byte[data.Length - 6]; System.Array.Copy(data,6,d,0,data.Length - 6); return d; } /** * Gets the formula as an excel string * * @return the formula as an excel string * @exception FormulaException */ public string getFormula() { if (formulaString == null) { byte[] tokens = new byte[data.Length - 22]; System.Array.Copy(data,22,tokens,0,tokens.Length); FormulaParser fp = new FormulaParser (tokens,this,externalSheet,nameTable, getSheet().getWorkbook().getSettings()); fp.parse(); formulaString = fp.getFormula(); } return formulaString; } } }
24.163701
79
0.629897
[ "Apache-2.0" ]
Tatetaylor/kbplumbapp
CSharpJExcel/CSharpJExcel/CSharpJExcel/Jxl/Read/Biff/StringFormulaRecord.cs
6,790
C#
using System; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using PicoService.Builder; using PicoService.Bus; using PicoService.Configuration; namespace PicoService.Extensions.Bus { public static class BusPicoServiceExtensions { public static IPicoServiceBuilder UseServiceBus(this IBusPicoServiceBuilder builder, ServiceBusConfiguration configuration, Action<ISubscribeBus> registrations) { Action<IServiceCollection> configureServicesAction = services => { services.AddSingleton(typeof(ServiceBusConfiguration), configuration); services.AddTransient<IPublishBus, ServiceBus>(); services.AddTransient<ISubscribeBus, ServiceBus>(); }; Action<IApplicationBuilder> configureAction = app => { var subscribeBus = app.ApplicationServices.GetService<ISubscribeBus>(); registrations(subscribeBus); }; var busStep = new PicoServiceConfigurationStep(configureServicesAction, configureAction); builder.Configurator.AddStep(busStep); return builder; } } }
37.875
168
0.683993
[ "MIT" ]
PicoService/PicoService
PicoService/Extensions/Bus/BusPicoServiceExtensions.cs
1,212
C#
using System; using HotChocolate.Language; using static HotChocolate.Execution.ThrowHelper; namespace HotChocolate.Execution.Processing; public sealed class SelectionIncludeCondition { public SelectionIncludeCondition( IValueNode? skip = null, IValueNode? include = null, SelectionIncludeCondition? parent = null) { if (skip is null && include is null) { throw new ArgumentException("Either skip or include have to be set."); } if (skip != null && skip.Kind != SyntaxKind.Variable && skip.Kind != SyntaxKind.BooleanValue) { throw new ArgumentException("skip must be a variable or a boolean value"); } if (include != null && include.Kind != SyntaxKind.Variable && include.Kind != SyntaxKind.BooleanValue) { throw new ArgumentException("skip must be a variable or a boolean value"); } Skip = skip; Include = include; Parent = parent; } public IValueNode? Skip { get; } public IValueNode? Include { get; } public SelectionIncludeCondition? Parent { get; } public bool IsTrue(IVariableValueCollection variables) { if (Parent != null && !Parent.IsTrue(variables)) { return false; } if (Skip != null && IsTrue(variables, Skip)) { return false; } return Include is null || IsTrue(variables, Include); } private static bool IsTrue( IVariableValueCollection variables, IValueNode value) { if (value is BooleanValueNode b) { return b.Value; } if (value is VariableNode v) { return variables.GetVariable<bool>(v.Name.Value); } throw FieldVisibility_ValueNotSupported(value); } public bool Equals(IValueNode? skip, IValueNode? include) { return EqualsInternal(skip, Skip) && EqualsInternal(include, Include); } public bool Equals(SelectionIncludeCondition visibility) { if (Equals(visibility.Skip, visibility.Include)) { if (Parent is null) { return visibility.Parent is null; } else { return visibility.Parent is { } && Parent.Equals(visibility.Parent); } } return false; } private static bool EqualsInternal(IValueNode? a, IValueNode? b) { if (ReferenceEquals(a, b)) { return true; } if (a is BooleanValueNode ab && b is BooleanValueNode bb && ab.Value == bb.Value) { return true; } if (a is VariableNode av && b is VariableNode bv && string.Equals(av.Value, bv.Value, StringComparison.Ordinal)) { return true; } return false; } }
24.900826
86
0.555592
[ "MIT" ]
AccountTechnologies/hotchocolate
src/HotChocolate/Core/src/Execution/Processing/SelectionIncludeCondition.cs
3,013
C#
using System; using System.Linq; using System.Threading.Tasks; namespace custom_popup_form.Data { public class WeatherForecastService { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; public Task<WeatherForecast[]> GetForecastAsync(DateTime startDate) { var rng = new Random(); return Task.FromResult(Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = startDate.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }).ToArray()); } } }
29.807692
110
0.574194
[ "MIT" ]
SeppPenner/blazor-ui
grid/custom-popup-form/Data/WeatherForecastService.cs
775
C#
using System; class BankAccauntData { static void Main() { string Name; string MiddleName; string LastName; int Balance; object BankName; long IBAN; ulong CredintCard1; ulong CreditCard2; ulong CreditCard3; Name = "Dancho"; MiddleName = "Iotov"; LastName = "Ganchev"; Balance = 50000; BankName = "InvestBank"; IBAN = 600555432361; CredintCard1 = 4454758923; CreditCard2 = 238472163231364; CreditCard3 = 15371274912323; Console.WriteLine("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}",Name,MiddleName,LastName,Balance,BankName,IBAN,CredintCard1,CreditCard2,CreditCard3); } }
24.322581
157
0.574271
[ "MIT" ]
MartinQnkovDobrev/ZadachiCSharp
BankAccauntData/BankAccauntData.cs
756
C#
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; using System.Collections; /// Manages when the visual elements of GvrControllerPointer should be active. /// When the controller is disconnected, the visual elements will be turned off. public class GvrControllerVisualManager : MonoBehaviour { #if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) private bool wasControllerConnected = false; void Start() { wasControllerConnected = IsControllerConnected(); SetChildrenActive(wasControllerConnected); } void Update() { bool isControllerConnected = IsControllerConnected(); if (isControllerConnected != wasControllerConnected) { SetChildrenActive(isControllerConnected); } wasControllerConnected = isControllerConnected; } private bool IsControllerConnected() { return GvrController.State == GvrConnectionState.Connected; } /// Activate/Deactivate the children of the transform. /// It is expected that the children will be the visual elements /// of GvrControllerPointer (I.e. the Laser and the 3D Controller Model). private void SetChildrenActive(bool active) { for (int i = 0; i < transform.childCount; i++) { transform.GetChild(i).gameObject.SetActive(active); } } #endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) }
38.156863
81
0.727133
[ "MIT" ]
E-restrepo14/Noisy-googlevr
Assets/Zdownloads/GoogleVR/Scripts/Controller/GvrControllerVisualManager.cs
1,948
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace ConnectFour { public class GameResultsView : MonoBehaviour { public Text RedTeamWinCount, BlackTeamWinCount, RedTeamWintypeDisplay, BlackTeamWinTypeDisplay; public Text RedTeamPlayedByText, BlackTeamPlayedByText; void Update() { BuildView(); } void BuildView() { TeamStats redTeamStats = ScoreKeeper.GetRedTeamStats(); TeamStats blackTeamStats = ScoreKeeper.GetBlackTeamStats(); RedTeamWinCount.text = BuildWinCountDisplay(redTeamStats); BlackTeamWinCount.text = BuildWinCountDisplay(blackTeamStats); RedTeamWintypeDisplay.text = BuildWinTypeDisplay(redTeamStats); BlackTeamWinTypeDisplay.text = BuildWinTypeDisplay(blackTeamStats); RedTeamPlayedByText.text = BuildPlayedByText(redTeamStats); BlackTeamPlayedByText.text = BuildPlayedByText(blackTeamStats); } string BuildWinCountDisplay(TeamStats stats) { string winCountMessage = $"Wins -- {stats.WinCount}"; return winCountMessage; } string BuildWinTypeDisplay(TeamStats stats) { string wintypeDisplay = $" Horizontal Wins -- {stats.HorizontalWins} \n Vertical Wins -- {stats.VerticalWins} \n Diagonal Wins -- {stats.DiagonalWins} \n Forfeitures {stats.Forfeits}"; return wintypeDisplay; } string BuildPlayedByText(TeamStats stats) { string playedByText = ""; if (stats.Player != null) { playedByText = $"Played by: {stats.Player.GetName()}"; } else { playedByText = "Played by:"; } return playedByText; } } }
37.431373
196
0.622315
[ "MIT" ]
eamonn-keogh/CoderDojo2019-ConnectFour
Connect-Four-master/Connect-Four-master/Assets/Scripts/UI/GameResultsView.cs
1,911
C#
namespace Nacos.AspNetCore { using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Http.Features; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; public class StatusReportBgTask : IHostedService, IDisposable { private readonly ILogger _logger; private readonly INacosNamingClient _client; private readonly IFeatureCollection _features; private NacosAspNetCoreOptions _options; private Timer _timer; private bool _reporting; private IEnumerable<Uri> uris = null; private List<SendHeartbeatRequest> beatRequests = new List<SendHeartbeatRequest>(); public StatusReportBgTask( ILoggerFactory loggerFactory, INacosNamingClient client, IServer server, IOptionsMonitor<NacosAspNetCoreOptions> optionsAccs) { _logger = loggerFactory.CreateLogger<StatusReportBgTask>(); _client = client; _options = optionsAccs.CurrentValue; _features = server.Features; } public Task StartAsync(CancellationToken cancellationToken) { uris = UriTool.GetUri(_features, _options); foreach (var uri in uris) { _logger.LogInformation("Report instance ({0}:{1}) status....", uri.Host, uri.Port); var metadata = new Dictionary<string, string>() { { PreservedMetadataKeys.REGISTER_SOURCE, "ASPNET_CORE" } }; foreach (var item in _options.Metadata) { if (!metadata.ContainsKey(item.Key)) { metadata.TryAdd(item.Key, item.Value); } } var beatRequest = new SendHeartbeatRequest { Ephemeral = true, ServiceName = _options.ServiceName, GroupName = _options.GroupName, BeatInfo = new BeatInfo { ip = uri.Host, port = uri.Port, serviceName = _options.ServiceName, scheduled = true, weight = _options.Weight, cluster = _options.ClusterName, metadata = metadata, }, NameSpaceId = _options.Namespace }; beatRequests.Add(beatRequest); } _timer = new Timer( async x => { if (_reporting) { _logger.LogInformation($"Latest manipulation is still working ..."); return; } _reporting = true; await ReportAsync(); _reporting = false; }, null, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(10)); return Task.CompletedTask; } private async Task ReportAsync() { foreach (var beatRequest in beatRequests) { bool flag = false; try { // send heart beat will register instance flag = await _client.SendHeartbeatAsync(beatRequest); } catch (Exception ex) { _logger.LogWarning(ex, $"{beatRequest.BeatInfo.ip}:{beatRequest.BeatInfo.port} Send heart beat to Nacos error"); } _logger.LogDebug("host = {0} report at {1}, status = {2}", $"{beatRequest.BeatInfo.ip}:{beatRequest.BeatInfo.port}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), flag); } } public async Task StopAsync(CancellationToken cancellationToken) { _logger.LogWarning("Unregistering from Nacos, serviceName={0}", _options.ServiceName); foreach (var uri in uris) { var removeRequest = new RemoveInstanceRequest { ServiceName = _options.ServiceName, Ip = uri.Host, Port = uri.Port, GroupName = _options.GroupName, NamespaceId = _options.Namespace, ClusterName = _options.ClusterName, Ephemeral = true }; for (int i = 0; i < 3; i++) { try { _logger.LogWarning("begin to remove instance, {0}", JsonConvert.SerializeObject(removeRequest)); var flag = await _client.RemoveInstanceAsync(removeRequest); _logger.LogWarning("remove instance, status = {0}", flag); break; } catch (Exception ex) { _logger.LogError(ex, "Unregistering error, count = {0}", i + 1); } } } _timer?.Change(Timeout.Infinite, 0); } public void Dispose() { _timer?.Dispose(); } } }
34.949686
189
0.495411
[ "Apache-2.0" ]
lengyjc/nacos-sdk-csharp
src/Nacos.AspNetCore/StatusReportBgTask.cs
5,559
C#
using System.Text.Json.Serialization; namespace KaiHeiLa.API; internal class VideoModule : ModuleBase { [JsonPropertyName("src")] public string Source { get; set; } [JsonPropertyName("title")] public string Title { get; set; } }
26.444444
65
0.726891
[ "MIT" ]
gehongyan/KaiHeiLa.Net
src/KaiHeiLa.Net.Rest/API/Common/Cards/Modules/VideoModule.cs
238
C#
#region Copyright (c) 2020 Filip Fodemski // // Copyright (c) 2020 Filip Fodemski // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files // (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR // ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH // THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE // #endregion using SmartGraph.Dag.Interfaces; using System; using System.Collections.Generic; using System.IO; namespace SmartGraph.TestApp { internal class Helpers { public static string DataDir( string f ) { return Environment.CurrentDirectory + @"\..\..\..\data\" + f; } public static string LoadExpectedStringFile(string expectedName) { StreamReader s = File.OpenText( Helpers.DataDir( expectedName + ".txt" ) ); return s.ReadToEnd(); } public static string DumpVertexList(IList<IVertex> vo) { int i = 0; string res = string.Empty; foreach ( IVertex v in vo ) { res += v.Name; if ( i++ != ( vo.Count - 1 ) ) res += ", "; } return res; } public static string DumpListOfVertexLists(IList<IList<IVertex>> lvl) { int i = 0; string res = string.Empty; foreach (IList<IVertex> vl in lvl) { res += string.Format( "{0}", DumpVertexList( vl ) ); if ( i++ != ( lvl.Count - 1 ) ) res += "\r\n"; } return res; } } }
33.446154
138
0.694112
[ "MIT" ]
filipek/SmartGraph
SmartGraph.TestApp/Helpers.cs
2,174
C#
using Com.Game.Data; using Com.Game.Module; using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using UnityEngine; public class HeadItem : MonoBehaviour { private UITexture Icon1; private Transform State1; private UILabel deathTimeLbl; private UISlider hp; private UISlider mp; public int player_unique_id; public string npc_id; private VTrigger PlayerDeath; private VTrigger PlayerReBrith; private VTrigger PlayerTimer; private Units m_units; private List<string> mSkillIds; private Transform SkillIcons; private UILabel level; private void Awake() { this.State1 = base.transform.FindChild("State1"); this.Icon1 = this.State1.FindChild("Icon").GetComponent<UITexture>(); this.hp = this.State1.FindChild("hp").GetComponent<UISlider>(); this.deathTimeLbl = this.State1.FindChild("deathTime").GetComponent<UILabel>(); this.mp = this.State1.FindChild("mp").GetComponent<UISlider>(); this.SkillIcons = this.State1.FindChild("Skills"); this.level = this.State1.Find("Anchor/level").GetComponent<UILabel>(); UIEventListener.Get(this.Icon1.gameObject).onClick = new UIEventListener.VoidDelegate(this.ChangePlayer); this.NormalHeroHead(); } public void UpdateItem(string hero_icon, bool ismaster, string heroName = null) { IList<Units> mapUnits = MapManager.Instance.GetMapUnits(TeamType.None, TargetTag.Hero); for (int i = 0; i < mapUnits.Count; i++) { if (mapUnits[i].npc_id == heroName) { this.player_unique_id = mapUnits[i].unique_id; this.npc_id = mapUnits[i].npc_id; base.name = this.player_unique_id.ToString(); this.m_units = mapUnits[i]; break; } } this.RegisterTrigger(); this.Icon1.mainTexture = ResourceManager.Load<Texture>(hero_icon, true, true, null, 0, false); if (ismaster) { } } private void UpdateSkills() { for (int i = 0; i < this.mSkillIds.Count; i++) { SysSkillMainVo skillData = SkillUtility.GetSkillData(this.mSkillIds[i], -1, -1); UITexture component = this.SkillIcons.GetChild(i).GetComponent<UITexture>(); component.name = this.mSkillIds[i]; string skill_icon = skillData.skill_icon; Texture mainTexture = ResourceManager.Load<Texture>(skill_icon, true, true, null, 0, false); component.mainTexture = mainTexture; } } public void UpdateItemById(int uid, string hero_icon, string nid) { this.player_unique_id = uid; base.name = this.player_unique_id.ToString(); this.npc_id = nid; this.RegisterTrigger(); this.Icon1.mainTexture = ResourceManager.Load<Texture>(hero_icon, true, true, null, 0, false); this.m_units = MapManager.Instance.GetUnit(uid); } private void RegisterTrigger() { if (this.PlayerDeath != null) { TriggerManager.DestroyTrigger(this.PlayerDeath); } if (this.PlayerReBrith != null) { TriggerManager.DestroyTrigger(this.PlayerReBrith); } if (this.PlayerTimer != null) { TriggerManager.DestroyTrigger(this.PlayerTimer); } this.PlayerDeath = TriggerManager.CreateUnitEventTrigger(UnitEvent.UnitDeath, null, new TriggerAction(this.GrayHeroHead), this.player_unique_id); this.PlayerReBrith = TriggerManager.CreateUnitEventTrigger(UnitEvent.UnitRebirthAgain, null, new TriggerAction(this.NormalHeroHead), this.player_unique_id); this.PlayerTimer = TriggerManager.CreateUnitEventTrigger(UnitEvent.HeroDeathTimer, null, new TriggerAction(this.DeathTimer), this.player_unique_id); } public void UpdateValue(float hp_value, float mp_value) { if (this.hp != null) { this.hp.value = hp_value; } if (this.mp != null) { this.mp.value = mp_value; } } private void ChangePlayer(GameObject obj) { } private void FixedUpdate() { if (this.mSkillIds == null && this.mSkillIds == null && MapManager.Instance != null && MapManager.Instance.GetUnit(this.player_unique_id) != null && MapManager.Instance.GetUnit(this.player_unique_id).skills.Length > 0) { this.m_units = MapManager.Instance.GetUnit(this.player_unique_id); this.mSkillIds = this.m_units.skills.ToList<string>(); this.UpdateSkills(); this.level.text = this.m_units.level.ToString(); } } private void GrayHeroHead() { this.Icon1.material = CharacterDataMgr.instance.ReturnMaterialType(9); this.hp.value = 0f; this.mp.value = 0f; } private void DeathTimer() { float playerDeathTime = BattleAttrManager.Instance.GetPlayerDeathTime(this.player_unique_id); if (base.gameObject.activeInHierarchy) { base.StartCoroutine(this.UpdateTimer(playerDeathTime)); } } [DebuggerHidden] private IEnumerator UpdateTimer(float length) { HeadItem.<UpdateTimer>c__IteratorDF <UpdateTimer>c__IteratorDF = new HeadItem.<UpdateTimer>c__IteratorDF(); <UpdateTimer>c__IteratorDF.length = length; <UpdateTimer>c__IteratorDF.<$>length = length; <UpdateTimer>c__IteratorDF.<>f__this = this; return <UpdateTimer>c__IteratorDF; } private void SetDeathTime(float time) { if (time <= 0f) { this.deathTimeLbl.text = string.Empty; } else { this.deathTimeLbl.text = time.ToString("F0"); } } public void NormalHeroHead() { this.Icon1.material = CharacterDataMgr.instance.ReturnMaterialType(1); this.SetDeathTime(0f); } }
28.951872
221
0.711304
[ "MIT" ]
corefan/mobahero_src
HeadItem.cs
5,414
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace Monolith { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
25.555556
70
0.643478
[ "MIT" ]
CodeMazeBlog/api-gateway-pattern-dotnet
Monolith/Program.cs
690
C#
using Beer.DaAPI.Core.Helper; using System; using System.Collections.Generic; namespace Beer.DaAPI.Core.Common { public class LinkLayerAddressDUID : DUID { public enum DUIDLinkLayerTypes : ushort { Ethernet = 1, } #region Properties public DUIDLinkLayerTypes AddressType { get; private set; } public Byte[] LinkLayerAddress { get; private set; } #endregion #region Constructor private LinkLayerAddressDUID() : base() { } public LinkLayerAddressDUID(DUIDLinkLayerTypes addressType, Byte[] linkLayerAddress) : base( DUIDTypes.LinkLayer, ByteHelper.GetBytes((UInt16)addressType), linkLayerAddress) { if (addressType == DUIDLinkLayerTypes.Ethernet) { if (linkLayerAddress.Length != 6) { throw new ArgumentException("invalid mac address", nameof(linkLayerAddress)); } } AddressType = addressType; LinkLayerAddress = ByteHelper.CopyData(linkLayerAddress); } public static LinkLayerAddressDUID FromByteArray(Byte[] data, Int32 offset) { UInt16 code = ByteHelper.ConvertToUInt16FromByte(data, offset); if (code != (UInt16)DUIDTypes.LinkLayer) { throw new ArgumentException($"invalid duid type. expected {(UInt16)DUIDTypes.LinkLayer} actual {code}"); } DUIDLinkLayerTypes linkLayerType = (DUIDLinkLayerTypes)ByteHelper.ConvertToUInt16FromByte(data, offset+2); Byte[] hwAddress = ByteHelper.CopyData(data, offset + 4); return new LinkLayerAddressDUID(linkLayerType, hwAddress); } #endregion } }
30.84127
120
0.567164
[ "MIT" ]
just-the-benno/Beer
src/DaAPI/Service/Beer.DaAPI.Service.Core/Common/DUID/LinkLayerAddressDUID.cs
1,945
C#
using CleanArchitecture.Application.TodoLists.Queries.ExportTodos; namespace CleanArchitecture.Application.Common.Interfaces; public interface ICsvFileBuilder { byte[] BuildTodoItemsFile(IEnumerable<TodoItemRecord> records); }
29.125
67
0.845494
[ "MIT" ]
wahidrezgui/RealEstate
src/Application/Common/Interfaces/ICsvFileBuilder.cs
235
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ImputationH31per.Modele.Entite; namespace ImputationH31per.Vue.RapportMensuel.Modele.Entite { public class GroupeItem : InformationBaseItem<IInformationTacheTfs> { public GroupeItem(EnumTypeItem typeItem) : base(typeItem) { } public GroupeItem(IInformationTacheTfs information) : base(information) { } protected override string ObtenirLibelleEntite() { return Entite.NomGroupement; } protected override bool EntiteEgale(IInformationTacheTfs entite) { return String.Equals(Entite.NomGroupement, entite.NomGroupement); } public override EnumTypeInformation TypeInformation { get { return EnumTypeInformation.Groupe; } } public static readonly GroupeItem Tous = new GroupeItem(EnumTypeItem.Tous); } }
27.184211
84
0.633107
[ "Unlicense" ]
blueneosky/Bag
ImputationH31per/ImputationH31per/Vue/RapportMensuel/Modele/Entite/GroupeItem.cs
1,035
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Logic.V20190501 { public static class ListWorkflowRunActionExpressionTraces { public static Task<ListWorkflowRunActionExpressionTracesResult> InvokeAsync(ListWorkflowRunActionExpressionTracesArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<ListWorkflowRunActionExpressionTracesResult>("azure-nextgen:logic/v20190501:listWorkflowRunActionExpressionTraces", args ?? new ListWorkflowRunActionExpressionTracesArgs(), options.WithVersion()); } public sealed class ListWorkflowRunActionExpressionTracesArgs : Pulumi.InvokeArgs { /// <summary> /// The workflow action name. /// </summary> [Input("actionName", required: true)] public string ActionName { get; set; } = null!; /// <summary> /// The resource group name. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; /// <summary> /// The workflow run name. /// </summary> [Input("runName", required: true)] public string RunName { get; set; } = null!; /// <summary> /// The workflow name. /// </summary> [Input("workflowName", required: true)] public string WorkflowName { get; set; } = null!; public ListWorkflowRunActionExpressionTracesArgs() { } } [OutputType] public sealed class ListWorkflowRunActionExpressionTracesResult { public readonly ImmutableArray<Outputs.ExpressionRootResponseResult> Inputs; [OutputConstructor] private ListWorkflowRunActionExpressionTracesResult(ImmutableArray<Outputs.ExpressionRootResponseResult> inputs) { Inputs = inputs; } } }
34.031746
250
0.670709
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/Logic/V20190501/ListWorkflowRunActionExpressionTraces.cs
2,144
C#
using UnityEngine; namespace Hoard.MVC.Unity { /// <summary> /// Helper object that helps to do a math related to the vertical carousel /// </summary> public class SlidingObjectControl { public float ContentElementWidth { get; set; } public float spacing = 0; public float ContentWidth { get; set; } public float ContentOriginPoint; public float ContentOffset; public float LocalZeroPoint => ContentOriginPoint + ContentOffset; public SlidingObjectControl(float startPoint, float elementWidth, float contentHolderWidth, float spacing) { if (elementWidth == 0) throw new System.ArgumentOutOfRangeException(nameof(elementWidth), "Can't be 0"); if (contentHolderWidth == 0) throw new System.ArgumentOutOfRangeException(nameof(contentHolderWidth), "Can't be 0"); ContentWidth = contentHolderWidth; this.spacing = spacing; ContentElementWidth = elementWidth + spacing; ContentOriginPoint = startPoint; ContentOffset = ((contentHolderWidth / 2f) - (ContentElementWidth / 2f)); } public float GetContentPositionOnIndex(int index) { var width = ContentElementWidth * index; return LocalZeroPoint + -1f * width; } public int GetContentElementIndexAt(float elemX, float contentX) { var beginning = contentX - (ContentWidth * .5f); var distance = elemX - beginning; return Mathf.RoundToInt(distance / ContentElementWidth); } public int GetIndexAtContentPosition(float position) { if (position > LocalZeroPoint) return -1; var distance = Mathf.Abs(position - LocalZeroPoint); if (distance > ContentWidth) return (int)(ContentWidth / ContentElementWidth); return Mathf.RoundToInt(distance / (ContentElementWidth)); } public void ExpandShrinkByElementsCount(int count) { var additionalWidth = ContentElementWidth * count; ContentWidth += additionalWidth; ContentOffset += (additionalWidth / 2); } public float GetClosestSnapPosition(float position) { var distance = position - LocalZeroPoint; var count = Mathf.RoundToInt(distance / (ContentElementWidth)); return LocalZeroPoint + (count * ContentElementWidth); } } }
34.189189
103
0.624506
[ "MIT" ]
hoardexchange/hoard-overlay-unity
MVCUnity/UIComponents/SlidingObjectControl.cs
2,530
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SteamBotExample.SteamApi.IEconItems_730.GetPlayerItems { public class getPlayerItems_Items { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("original_id")] public string OriginalId { get; set; } [JsonProperty("defindex")] public string DefIndex { get; set; } [JsonProperty("level")] public string Level { get; set; } [JsonProperty("quality")] public string Quality { get; set; } [JsonProperty("inventory")] public string Inventory { get; set; } [JsonProperty("quantity")] public string Quantity { get; set; } [JsonProperty("rarity")] public string Rarity { get; set; } [JsonProperty("flag_cannot_trade")] public string FlagCannotTrade { get; set; } [JsonProperty("flag_cannot_craft")] public string FlagCannotCraft { get; set; } [JsonProperty("attributes")] public getPlayerItems_Attribute[] Attributes { get; set; } } }
22.891304
64
0.710351
[ "MIT" ]
BattleRush/SteamTradeExample-Console
SteamBotExample/SteamApi/IEconItems_730/GetPlayerItems/getPlayerItems_Items.cs
1,055
C#
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CDR.Register.IdentityServer.Configurations; using CDR.Register.IdentityServer.Interfaces; using IdentityServer4.Models; using Microsoft.IdentityModel.Tokens; namespace CDR.Register.IdentityServer.Extensions { public static class ClientExtensions { public static async Task<List<SecurityKey>> GetJsonWebKeysAsync(this IEnumerable<Secret> secrets, IJwkService jwkService) { var secretList = secrets.ToList().AsReadOnly(); var keys = new List<SecurityKey>(); foreach (var secret in secretList.Where(s => s.Type == Constants.SecretTypes.JwksUrl)) { var jwks = await jwkService.GetJwksAsync(secret.Value); keys.AddRange(jwks); } return keys; } } }
31.285714
129
0.674658
[ "MIT" ]
AmilaSamith/mock-register
Source/CDR.Register.IdentityServer/Extensions/ClientExtensions.cs
878
C#
//--------------------------------------------------------------------- // <copyright file="CatalogUrlManager.cs" company="Sitecore Corporation"> // Copyright (c) Sitecore Corporation 1999-2015 // </copyright> // <summary>The CatalogUrlManager class</summary> //--------------------------------------------------------------------- // Copyright 2015 Sitecore Corporation A/S // 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 Sitecore.Commerce.Storefront { using Sitecore.Commerce.Connect.CommerceServer; using Sitecore.Commerce.Connect.CommerceServer.Search; using Sitecore.Commerce.Storefront.Managers; using Sitecore.Commerce.Storefront.SitecorePipelines; using Sitecore.Data.Items; using Sitecore.Diagnostics; using System; using System.Text; /// <summary> /// Helper class used to build product and category links /// </summary> public static class CatalogUrlManager { private const string UrlTokenDelimiter = "-"; private const string EncodedDelimiter = "[[_]]"; private static string[] InvalidPathCharacters = new string[] { "<", ">", "*", "%", "&", ":", "\\", "?", ".", "\"", " " }; private static Lazy<ICommerceSearchManager> SearchManagerLoader = new Lazy<ICommerceSearchManager>(() => CommerceTypeLoader.CreateInstance<ICommerceSearchManager>()); private static bool IncludeLanguage { get { if (Sitecore.Context.Language != null) { if (Sitecore.Context.Site == null || !string.Equals(Sitecore.Context.Language.Name, Sitecore.Context.Site.Language, StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } } /// <summary> /// Builds a product link /// </summary> /// <param name="item">The product item to build a link for</param> /// <param name="includeCatalog">Whether or not to include catalog id in the url</param> /// <param name="includeFriendlyName">Specifies whether or not to include the friendly / display name in the url.</param> /// <returns>The built link</returns> public static string BuildProductLink(Item item, bool includeCatalog, bool includeFriendlyName) { var url = BuildUrl(item, includeCatalog, includeFriendlyName, ProductItemResolver.ProductUrlRoute); return url; } /// <summary> /// Builds a category link /// </summary> /// <param name="item">The category item to build a link for</param> /// <param name="includeCatalog">Whether or not to include catalog id in the url</param> /// <param name="includeFriendlyName">Specifies whether or not to include the friendly / display name in the url.</param> /// <returns>The built link</returns> public static string BuildCategoryLink(Item item, bool includeCatalog, bool includeFriendlyName) { var url = BuildUrl(item, includeCatalog, includeFriendlyName, ProductItemResolver.CategoryUrlRoute); return url; } /// <summary> /// Builds a catalog item link /// </summary> /// <param name="item">The category item to build a link for</param> /// <param name="includeCatalog">Whether or not to include catalog id in the url</param> /// <param name="includeFriendlyName">Specifies whether or not to include the friendly / display name in the url.</param> /// <param name="root">The root part of the url e.g. product or category</param> /// <returns>The built link</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings", Justification = "By design, we ned a string to be returned.")] public static string BuildUrl(Item item, bool includeCatalog, bool includeFriendlyName, string root) { Assert.ArgumentNotNull(item, "item"); var itemFriendlyName = string.Empty; var itemName = item.Name.ToLowerInvariant(); var catalogName = ExtractCatalogName(item, includeCatalog); ExtractCatalogItemInfo(item, includeFriendlyName, out itemName, out itemFriendlyName); var url = BuildUrl(itemName, itemFriendlyName, catalogName, root); return url; } /// <summary> /// Builds a catalog item link. /// </summary> /// <param name="itemName">The catalog item name.</param> /// <param name="itemFriendlyName">The catalog item friendy / display name.</param> /// <param name="catalogName">The name of the catalog that includes the catalog item.</param> /// <param name="root">The root catalog item path.</param> /// <returns>The catalog item link.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings", Justification = "By design, we ned a string to be returned.")] public static string BuildUrl(string itemName, string itemFriendlyName, string catalogName, string root) { Assert.ArgumentNotNullOrEmpty(itemName, "itemName"); var route = new StringBuilder("/"); if (IncludeLanguage) { route.Append(Sitecore.Context.Language.Name); route.Append("/"); } var isGiftCard = (itemName == StorefrontManager.CurrentStorefront.GiftCardProductId); if (isGiftCard) { route.Append(ProductItemResolver.LandingUrlRoute); route.Append("/"); route.Append(ProductItemResolver.BuyGiftCardUrlRoute); } else { if (!string.IsNullOrEmpty(catalogName)) { route.Append(EncodeUrlToken(catalogName, true)); route.Append("/"); } route.Append(root); route.Append("/"); if (!string.IsNullOrEmpty(itemFriendlyName)) { route.Append(EncodeUrlToken(itemFriendlyName, true)); route.Append(UrlTokenDelimiter); } route.Append(EncodeUrlToken(itemName, false)); } var url = StorefrontManager.StorefrontUri(route.ToString()); return url; } /// <summary> /// Builds a product variant shop link /// </summary> /// <param name="item">The product variant item to build a link for</param> /// <param name="includeCatalog">Whether or not to include catalog id in the url</param> /// <param name="includeFriendlyName">Specifies whether or not to include the friendly / display name in the url.</param> /// <param name="includeCurrentCategory">Specifies whether or not to include the current category information in the URL, or to instead use the primary parent category.</param> /// <returns>The built link</returns> public static string BuildVariantShopLink(Item item, bool includeCatalog, bool includeFriendlyName, bool includeCurrentCategory) { Assert.ArgumentNotNull(item, "item"); var variantName = string.Empty; var variantId = string.Empty; var productName = string.Empty; var productId = string.Empty; var categoryName = string.Empty; var categoryId = string.Empty; var catalogName = ExtractCatalogName(item, includeCatalog); ExtractCatalogItemInfo(item, includeFriendlyName, out variantId, out variantName); var parentItem = item.Parent; ExtractCatalogItemInfo(parentItem, includeFriendlyName, out productId, out productName); if (includeCurrentCategory) { ExtractCategoryInfoFromCurrentShopUrl(out categoryId, out categoryName); } if (string.IsNullOrEmpty(categoryId)) { var grandParentItem = parentItem.Parent; ExtractCatalogItemInfo(grandParentItem, includeFriendlyName, out categoryId, out categoryName); } var url = BuildShopUrl(categoryId, categoryName, productId, productName, variantId, variantName, catalogName); return url; } /// <summary> /// Builds a product shop link /// </summary> /// <param name="item">The product item to build a link for</param> /// <param name="includeCatalog">Whether or not to include catalog id in the url</param> /// <param name="includeFriendlyName">Specifies whether or not to include the friendly / display name in the url.</param> /// <param name="includeCurrentCategory">Specifies whether or not to include the current category information in the URL, or to instead use the primary parent category.</param> /// <returns>The built link</returns> public static string BuildProductShopLink(Item item, bool includeCatalog, bool includeFriendlyName, bool includeCurrentCategory) { Assert.ArgumentNotNull(item, "item"); var productName = string.Empty; var productId = string.Empty; var categoryName = string.Empty; var categoryId = string.Empty; var catalogName = ExtractCatalogName(item, includeCatalog); ExtractCatalogItemInfo(item, includeFriendlyName, out productId, out productName); if (includeCurrentCategory) { ExtractCategoryInfoFromCurrentShopUrl(out categoryId, out categoryName); } if (string.IsNullOrEmpty(categoryId)) { var parentItem = item.Parent; ExtractCatalogItemInfo(parentItem, includeFriendlyName, out categoryId, out categoryName); } var url = BuildShopUrl(categoryId, categoryName, productId, productName, string.Empty, string.Empty, catalogName); return url; } /// <summary> /// Builds a category shop link /// </summary> /// <param name="item">The category item to build a link for</param> /// <param name="includeCatalog">Whether or not to include catalog id in the url</param> /// <param name="includeFriendlyName">Specifies whether or not to include the friendly / display name in the url.</param> /// <returns>The built link</returns> public static string BuildCategoryShopLink(Item item, bool includeCatalog, bool includeFriendlyName) { Assert.ArgumentNotNull(item, "item"); var categoryName = string.Empty; var categoryId = string.Empty; var catalogName = ExtractCatalogName(item, includeCatalog); ExtractCatalogItemInfo(item, includeFriendlyName, out categoryId, out categoryName); var url = BuildShopUrl(categoryId, categoryName, string.Empty, string.Empty, string.Empty, string.Empty, catalogName); return url; } /// <summary> /// Gets the canonical shop URI for a catalog item. /// </summary> /// <param name="categoryId">The category ID.</param> /// <param name="categoryName">The category friendly name / display name.</param> /// <param name="productId">The product ID.</param> /// <param name="productName">The product friendly name / display name.</param> /// <param name="variantId">The product variant ID.</param> /// <param name="variantName">The product variant fiendly name / display name.</param> /// <param name="catalogName">The name of the catalog that includes the catalog item.</param> /// <returns>The canonical shop URI for the catalog item.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings", Justification = "By design, we ned a string to be returned.")] public static string BuildShopUrl(string categoryId, string categoryName, string productId, string productName, string variantId, string variantName, string catalogName) { Assert.ArgumentNotNullOrEmpty(categoryId, "categoryId"); var route = new StringBuilder("/"); if (IncludeLanguage) { route.Append(Sitecore.Context.Language.Name); route.Append("/"); } var isGiftCard = (productId == StorefrontManager.CurrentStorefront.GiftCardProductId); if (isGiftCard) { route.Append(ProductItemResolver.LandingUrlRoute); route.Append("/"); route.Append(ProductItemResolver.BuyGiftCardUrlRoute); } else { if (!string.IsNullOrEmpty(catalogName)) { route.Append(EncodeUrlToken(catalogName, true)); route.Append("/"); } route.Append(ProductItemResolver.ShopUrlRoute); route.Append("/"); if (!string.IsNullOrEmpty(categoryName)) { route.Append(EncodeUrlToken(categoryName, true)); route.Append(UrlTokenDelimiter); } route.Append(EncodeUrlToken(categoryId, false)); if (!string.IsNullOrEmpty(productId)) { route.Append("/"); if (!string.IsNullOrEmpty(productName)) { route.Append(EncodeUrlToken(productName, true)); route.Append(UrlTokenDelimiter); } route.Append(EncodeUrlToken(productId, false)); if (!string.IsNullOrEmpty(variantId)) { route.Append("/"); if (!string.IsNullOrEmpty(variantName)) { route.Append(EncodeUrlToken(variantName, true)); route.Append(UrlTokenDelimiter); } route.Append(EncodeUrlToken(variantId, false)); } } } var url = StorefrontManager.StorefrontUri(route.ToString()); return url; } /// <summary> /// Extracts the target catalog item ID from the current request URL. /// </summary> /// <returns>The target catalog item ID.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings", Justification = "By design, we ned a string to be returned.")] public static string ExtractItemIdFromCurrentUrl() { return ExtractItemId(Sitecore.Web.WebUtil.GetUrlName(0)); } /// <summary> /// Extracts the target category name from the current request URL. /// </summary> /// <returns>The target category name.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings", Justification = "By design, we ned a string to be returned.")] public static string ExtractCategoryNameFromCurrentUrl() { var categoryFolder = Sitecore.Web.WebUtil.GetUrlName(1); if (string.IsNullOrEmpty(categoryFolder)) { return ExtractItemIdFromCurrentUrl(); } return ExtractItemId(categoryFolder); } /// <summary> /// Extracts the target catalog name from the current request URL. /// </summary> /// <returns>The target catalog name.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings", Justification = "By design, we ned a string to be returned.")] public static string ExtractCatalogNameFromCurrentUrl() { var linkProvider = Sitecore.Links.LinkManager.Provider as CatalogLinkProvider; if (linkProvider != null && linkProvider.IncludeCatalog) { var catalogName = Sitecore.Web.WebUtil.GetUrlName(2); if (!string.IsNullOrEmpty(catalogName)) { return catalogName; } catalogName = Sitecore.Web.WebUtil.GetUrlName(1); if (!string.IsNullOrEmpty(catalogName)) { return catalogName; } } return StorefrontManager.CurrentStorefront.DefaultCatalog.Name; } /// <summary> /// Extracts a catalog item ID from a URL folder name. /// </summary> /// <param name="folder">The URL folder name.</param> /// <returns>The catalog item ID.</returns> public static string ExtractItemId(string folder) { var itemName = folder; if (folder != null && folder.Contains(UrlTokenDelimiter)) { var tokens = folder.Split(new[] { UrlTokenDelimiter }, StringSplitOptions.None); itemName = tokens[tokens.Length - 1]; } return DecodeUrlToken(itemName); } /// <summary> /// Extracts a catalog item friendly name from a URL folder name. /// </summary> /// <param name="folder">The URL folder name.</param> /// <returns>The catalog item friendly name.</returns> public static string ExtractItemName(string folder) { var itemName = string.Empty; if (folder != null && folder.Contains(UrlTokenDelimiter)) { var tokens = folder.Split(new[] { UrlTokenDelimiter }, StringSplitOptions.None); itemName = tokens[tokens.Length - 2]; } return DecodeUrlToken(itemName); } private static void ExtractCatalogItemInfo(string folder, out string itemId, out string ItemName) { itemId = ExtractItemId(folder); ItemName = ExtractItemName(folder); } private static void ExtractCategoryInfoFromCurrentShopUrl(out string categoryId, out string categoryName) { categoryId = string.Empty; categoryName = string.Empty; if (Sitecore.Web.WebUtil.GetUrlName(1).ToLowerInvariant() == ProductItemResolver.ShopUrlRoute) { // store/<category> ExtractCatalogItemInfo(Sitecore.Web.WebUtil.GetUrlName(0), out categoryId, out categoryName); } if (Sitecore.Web.WebUtil.GetUrlName(2).ToLowerInvariant() == ProductItemResolver.ShopUrlRoute) { // store/<category>/<product> ExtractCatalogItemInfo(Sitecore.Web.WebUtil.GetUrlName(1), out categoryId, out categoryName); } if (Sitecore.Web.WebUtil.GetUrlName(3).ToLowerInvariant() == ProductItemResolver.ShopUrlRoute) { // store/<category>/<product>/<variant> ExtractCatalogItemInfo(Sitecore.Web.WebUtil.GetUrlName(2), out categoryId, out categoryName); } } private static string ExtractCatalogName(Item item, bool includeCatalog) { Assert.ArgumentNotNull(item, "item"); if (includeCatalog) { return item[CommerceConstants.KnownFieldIds.CatalogName].ToLowerInvariant(); } return string.Empty; } private static void ExtractCatalogItemInfo(Item item, bool includeFriendlyName, out string itemName, out string itemFriendlyName) { Assert.ArgumentNotNull(item, "item"); if (SearchManagerLoader.Value.IsItemCatalog(item) || SearchManagerLoader.Value.IsItemVirtualCatalog(item)) { itemName = ProductItemResolver.ProductUrlRoute; itemFriendlyName = string.Empty; } else { itemName = item.Name.ToLowerInvariant(); itemFriendlyName = string.Empty; if (includeFriendlyName) { itemFriendlyName = item.DisplayName; } } } private static string EncodeUrlToken(string urlToken, bool removeInvalidPathCharacters) { if (!string.IsNullOrEmpty(urlToken)) { if (removeInvalidPathCharacters) { foreach (var character in InvalidPathCharacters) { urlToken = urlToken.Replace(character, ""); } } urlToken = Uri.EscapeDataString(urlToken).Replace(UrlTokenDelimiter, EncodedDelimiter); } return urlToken; } private static string DecodeUrlToken(string urlToken) { if (!string.IsNullOrEmpty(urlToken)) { urlToken = Uri.UnescapeDataString(urlToken).Replace(EncodedDelimiter, UrlTokenDelimiter); } return urlToken; } } }
43.587426
184
0.59222
[ "Apache-2.0" ]
Sitecore/Reference-Storefront-SCpbMD
Storefront/CSF/Util/CatalogUrlManager.cs
22,188
C#
using System; using System.Collections.Generic; using System.Text; namespace LoanManager.Core.Domain { public class LoanRate { public int LoanRateId { get; set; } public int LowerCreditScore { get; set; } public int UpperCreditScore { get; set; } public double InterestRate { get; set; } public int LoanTypeId { get; set; } public LoanType LoanType { get; set; } } }
17.48
49
0.627002
[ "MIT" ]
alex-wolf-ps/visual-studio-code-analysis
LoanManager.Core/Domain/LoanRate.cs
439
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.MachineLearningServices.V20181119 { public static class GetMachineLearningCompute { public static Task<GetMachineLearningComputeResult> InvokeAsync(GetMachineLearningComputeArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetMachineLearningComputeResult>("azure-nextgen:machinelearningservices/v20181119:getMachineLearningCompute", args ?? new GetMachineLearningComputeArgs(), options.WithVersion()); } public sealed class GetMachineLearningComputeArgs : Pulumi.InvokeArgs { /// <summary> /// Name of the Azure Machine Learning compute. /// </summary> [Input("computeName", required: true)] public string ComputeName { get; set; } = null!; /// <summary> /// Name of the resource group in which workspace is located. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; /// <summary> /// Name of Azure Machine Learning workspace. /// </summary> [Input("workspaceName", required: true)] public string WorkspaceName { get; set; } = null!; public GetMachineLearningComputeArgs() { } } [OutputType] public sealed class GetMachineLearningComputeResult { /// <summary> /// The identity of the resource. /// </summary> public readonly Outputs.IdentityResponse? Identity; /// <summary> /// Specifies the location of the resource. /// </summary> public readonly string? Location; /// <summary> /// Specifies the name of the resource. /// </summary> public readonly string Name; /// <summary> /// Compute properties /// </summary> public readonly Union<Outputs.AKSResponse, Union<Outputs.AmlComputeResponse, Union<Outputs.DataFactoryResponse, Union<Outputs.DataLakeAnalyticsResponse, Union<Outputs.DatabricksResponse, Union<Outputs.HDInsightResponse, Outputs.VirtualMachineResponse>>>>>> Properties; /// <summary> /// Contains resource tags defined as key/value pairs. /// </summary> public readonly ImmutableDictionary<string, string>? Tags; /// <summary> /// Specifies the type of the resource. /// </summary> public readonly string Type; [OutputConstructor] private GetMachineLearningComputeResult( Outputs.IdentityResponse? identity, string? location, string name, Union<Outputs.AKSResponse, Union<Outputs.AmlComputeResponse, Union<Outputs.DataFactoryResponse, Union<Outputs.DataLakeAnalyticsResponse, Union<Outputs.DatabricksResponse, Union<Outputs.HDInsightResponse, Outputs.VirtualMachineResponse>>>>>> properties, ImmutableDictionary<string, string>? tags, string type) { Identity = identity; Location = location; Name = name; Properties = properties; Tags = tags; Type = type; } } }
36.375
276
0.645762
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/MachineLearningServices/V20181119/GetMachineLearningCompute.cs
3,492
C#
/******************************************************************************** Copyright (C) Binod Nepal, Mix Open Foundation (http://mixof.org). This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. ***********************************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.Common; using System.Web.UI.WebControls; namespace MixERP.Net.BusinessLayer.Helpers { public static class FormHelper { public static DataTable GetView(string tableSchema, string tableName, string orderBy, int limit, int offset) { return MixERP.Net.DatabaseLayer.Helpers.FormHelper.GetView(tableSchema, tableName, orderBy, limit, offset); } public static DataTable GetTable(string tableSchema, string tableName) { return MixERP.Net.DatabaseLayer.Helpers.FormHelper.GetTable(tableSchema, tableName); } public static DataTable GetTable(string tableSchema, string tableName, string columnNames, string columnValues) { return MixERP.Net.DatabaseLayer.Helpers.FormHelper.GetTable(tableSchema, tableName, columnNames, columnValues); } public static DataTable GetTable(string tableSchema, string tableName, string columnNames, string columnValuesLike, int limit) { return MixERP.Net.DatabaseLayer.Helpers.FormHelper.GetTable(tableSchema, tableName, columnNames, columnValuesLike, limit); } public static int GetTotalRecords(string tableSchema, string tableName) { return MixERP.Net.DatabaseLayer.Helpers.FormHelper.GetTotalRecords(tableSchema, tableName); } public static bool InsertRecord(string tableSchema, string tableName, System.Collections.ObjectModel.Collection<KeyValuePair<string, string>> data, string imageColumn) { return MixERP.Net.DatabaseLayer.Helpers.FormHelper.InsertRecord(MixERP.Net.BusinessLayer.Helpers.SessionHelper.UserId(), tableSchema, tableName, data, imageColumn); } public static bool UpdateRecord(string tableSchema, string tableName, System.Collections.ObjectModel.Collection<KeyValuePair<string, string>> data, string keyColumn, string keyColumnValue, string imageColumn) { return MixERP.Net.DatabaseLayer.Helpers.FormHelper.UpdateRecord(MixERP.Net.BusinessLayer.Helpers.SessionHelper.UserId(), tableSchema, tableName, data, keyColumn, keyColumnValue, imageColumn); } public static bool DeleteRecord(string tableSchema, string tableName, string keyColumn, string keyColumnValue) { return MixERP.Net.DatabaseLayer.Helpers.FormHelper.DeleteRecord(tableSchema, tableName, keyColumn, keyColumnValue); } public static void MakeDirty(WebControl control) { if(control != null) { control.CssClass = "dirty"; control.Focus(); } } public static void RemoveDirty(WebControl control) { if(control != null) { control.CssClass = ""; } } } }
41.317073
216
0.658501
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
gj86/mixerp2
MixERP.Net.BusinessLayer/Helpers/FormHelper.cs
3,390
C#
using System; using System.Collections.Generic; using System.Text; namespace IteratorsAndComparators { public class Book { public string Title { get; } public int Year { get; } public IReadOnlyList<string> Authors { get; } public Book(string title, int year, params string[] authors) { Title = title; Year = year; Authors = authors; } } }
20.857143
68
0.575342
[ "MIT" ]
d1ma1/CSharp-OOP
Iterators and Comparators - Lab/01. Library/Book.cs
440
C#
using NBitcoin.Tests.Generators; using Xunit; using FsCheck; using FsCheck.Xunit; using System; using NBitcoin.Crypto; namespace NBitcoin.Tests.PropertyTest { // Test for non-segwit tx. public class LegacyTransactionTest { public LegacyTransactionTest() { Arb.Register<LegacyTransactionGenerators>(); } [Property(MaxTest = 100)] [Trait("UnitTest", "UnitTest")] public bool CanConvertToRaw(Tuple<Transaction, Network> param) { var tx = param.Item1; string hex = tx.ToHex(); var tx2 = Transaction.Parse(hex, param.Item2); return tx.GetHash() == tx2.GetHash(); } [Property(MaxTest = 100)] [Trait("UnitTest", "UnitTest")] public bool TxIdMustMatchHexSha256(Transaction tx) { return tx.GetHash() == Hashes.DoubleSHA256(tx.ToBytes()); } } }
20.736842
64
0.704315
[ "MIT" ]
3DA4C300/NBitcoin
NBitcoin.Tests/PropertyTest/LegacyTransactionTest.cs
788
C#
using Deribit.S4KTNET.Core.Mapping; using FluentValidation; namespace Deribit.S4KTNET.Core.Trading { // https://docs.deribit.com/v2/#private-get_open_orders_by_currency public class GetOpenOrdersByCurrencyRequest : RequestBase { public CurrencyCode currency { get; set; } public InstrumentKind? kind { get; set; } public string type { get; set; } internal class Profile : AutoMapper.Profile { public Profile() { this.CreateMap<GetOpenOrdersByCurrencyRequest, GetOpenOrdersByCurrencyRequestDto>() .ForMember(d => d.currency, o => o.MapFrom(s => s.currency.ToDeribitString())) .ForMember(d => d.kind, o => { o.PreCondition(s => s.kind.HasValue); o.MapFrom(s => s.kind.Value.ToDeribitString()); }) .AfterMap((s, d, r) => { if (d.kind == "any") d.kind = null; }); } } internal class Validator : FluentValidation.AbstractValidator<GetOpenOrdersByCurrencyRequest> { public Validator() { this.RuleFor(x => x.currency).NotEmpty().NotEqual(CurrencyCode.any); this.RuleFor(x => x.type).Must(x => x == null || x == "all" || x == "limit" || x == "stop_all" || x == "stop_limit" || x == "stop_market") .WithMessage(x => @"type == [ ""all"" | ""limit"" | ""stop_all"" | ""stop_limit"" | ""stop_market"" ]"); ; } } } public class GetOpenOrdersByCurrencyRequestDto { public string currency { get; set; } public string kind { get; set; } public string type { get; set; } internal class Validator : FluentValidation.AbstractValidator<GetOpenOrdersByCurrencyRequestDto> { public Validator() { this.RuleFor(x => x.currency).NotEmpty().Must(x => x == "BTC" || x == "ETH"); this.RuleFor(x => x.kind).Must(x => x == null || x == "future" || x == "option"); this.RuleFor(x => x.type).Must(x => x == null || x == "all" || x == "limit" || x == "stop_all" || x == "stop_limit" || x == "stop_market"); } } } }
36.191176
124
0.489638
[ "MIT" ]
HA07Z7XE/Deribit.S4KTNET
Deribit.S4KTNET.Core/src/deribit/trading/requests/GetOpenOrdersByCurrencyRequest.cs
2,461
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace exerc_14 { class Program { static void Main(string[] args) { int candidato = 0; int cvr = 0, jam = 0, cfl = 0, lcp = 0, atv = 0,nulo=0; Console.WriteLine("======== Eleições da Turma B208 =========="); Console.WriteLine("1 - Cristiano Vladimir Rodrigues"); Console.WriteLine("2 - Jorge António Muxito"); Console.WriteLine("3 - Cristiano Francisco Lourenço"); Console.WriteLine("4 - Lucrécia Da Conceição Palanga"); Console.WriteLine("5 - Ana Tavares Viegas"); for(int i = 0; i < 10; i++) { Console.Write("O seu voto vai para o candidato Nº: "); candidato = int.Parse(Console.ReadLine()); switch (candidato) { case 1: cvr += 1; Console.WriteLine("1 - Cristiano Vladimir Rodrigues"); Console.WriteLine(" "); break; case 2: jam += 1; Console.WriteLine("2 - Jorge António Muxito"); Console.WriteLine(" "); break; case 3: cfl += 1; Console.WriteLine("3 - Cristiano Francisco Lourenço"); Console.WriteLine(" "); break; case 4: lcp += 1; Console.WriteLine("4 - Lucrécia Da Conceição Palanga"); Console.WriteLine(" "); break; case 5: atv += 1; Console.WriteLine("5 - Ana Tavares Viegas"); Console.WriteLine(" "); break; default: nulo += 1; Console.WriteLine("Voto Nulo"); Console.WriteLine(" "); break; } } Console.WriteLine("======== Resultado das Eleições da Turma B208 =========="); Console.WriteLine("1 - Cristiano Vladimir Rodrigues --- {0} votos",cvr); Console.WriteLine("2 - Jorge António Muxito ----------- {0} votos",jam); Console.WriteLine("3 - Cristiano Francisco Lourenço --- {0} votos",cfl); Console.WriteLine("4 - Lucrécia Da Conceição Palanga -- {0} votos",lcp); Console.WriteLine("5 - Ana Tavares Viegas ------------- {0} votos",atv); Console.WriteLine("6 - Votos Nulos -------------------- {0} votos",nulo); Console.ReadKey(); } } }
39.459459
90
0.432534
[ "MIT" ]
Paulo-Faustino/Tarefas
Exercicios/Algoritmo C#/exerc_14/exerc_14/Program.cs
2,942
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Alexw.ProxyableClient.ConsoleApplication")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Alexw.ProxyableClient.ConsoleApplication")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("918fe51b-6d12-4438-bff0-2f018b90551e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.27027
84
0.752237
[ "Apache-2.0" ]
3686/Alexw.ProxyableClient
source/Alexw.ProxyableClient.ConsoleApplication/Properties/AssemblyInfo.cs
1,456
C#
/** * Copyright 2013 Canada Health Infoway, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: $LastChangedBy: gng $ * Last modified: $LastChangedDate: 2015-11-19 18:20:12 -0500 (Fri, 30 Jan 2015) $ * Revision: $LastChangedRevision: 9755 $ */ /* This class was auto-generated by the message builder generator tools. */ using Ca.Infoway.Messagebuilder; namespace Ca.Infoway.Messagebuilder.Model.Ab_r02_04_03_shr.Domainvalue { public interface RespiratoryTherapistHIPAA : Code { } }
36.586207
83
0.711593
[ "ECL-2.0", "Apache-2.0" ]
CanadaHealthInfoway/message-builder-dotnet
message-builder-release-ab_r02_04_03_shr/Main/Ca/Infoway/Messagebuilder/Model/Ab_r02_04_03_shr/Domainvalue/RespiratoryTherapistHIPAA.cs
1,061
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnusedParametersAndValues { public partial class RemoveUnusedValueExpressionStatementTests : RemoveUnusedValuesTestsBase { protected override IDictionary<OptionKey, object> PreferNone => Option(CSharpCodeStyleOptions.UnusedValueExpressionStatement, new CodeStyleOption<UnusedValuePreference>(UnusedValuePreference.DiscardVariable, NotificationOption.None)); protected override IDictionary<OptionKey, object> PreferDiscard => Option(CSharpCodeStyleOptions.UnusedValueExpressionStatement, new CodeStyleOption<UnusedValuePreference>(UnusedValuePreference.DiscardVariable, NotificationOption.Silent)); protected override IDictionary<OptionKey, object> PreferUnusedLocal => Option(CSharpCodeStyleOptions.UnusedValueExpressionStatement, new CodeStyleOption<UnusedValuePreference>(UnusedValuePreference.UnusedLocalVariable, NotificationOption.Silent)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] public async Task ExpressionStatement_Suppressed() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|M2()|]; } int M2() => 0; }", options: PreferNone); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] public async Task ExpressionStatement_PreferDiscard_CSharp6() { // Discard not supported in C# 6.0, so we fallback to unused local variable. await TestInRegularAndScriptAsync( @"class C { void M() { [|M2()|]; } int M2() => 0; }", @"class C { void M() { var unused = M2(); } int M2() => 0; }", options: PreferDiscard, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6)); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] public async Task ExpressionStatement_VariableInitialization(string optionName) { await TestMissingInRegularAndScriptAsync( @"class C { void M() { int x = [|M2()|]; } int M2() => 0; }", optionName); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] [InlineData(nameof(PreferDiscard), "_")] [InlineData(nameof(PreferUnusedLocal), "var unused")] public async Task ExpressionStatement_NonConstantPrimitiveTypeValue(string optionName, string fix) { await TestInRegularAndScriptAsync( @"class C { void M() { [|M2()|]; } int M2() => 0; }", $@"class C {{ void M() {{ {fix} = M2(); }} int M2() => 0; }}", optionName); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] [InlineData(nameof(PreferDiscard), "_")] [InlineData(nameof(PreferUnusedLocal), "var unused")] public async Task ExpressionStatement_UserDefinedType(string optionName, string fix) { await TestInRegularAndScriptAsync( @"class C { void M() { [|M2()|]; } C M2() => new C(); }", $@"class C {{ void M() {{ {fix} = M2(); }} C M2() => new C(); }}", optionName); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] public async Task ExpressionStatement_ConstantValue(string optionName) { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|1|]; } }", optionName); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] public async Task ExpressionStatement_SyntaxError(string optionName) { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|M2(,)|]; } int M2() => 0; }", optionName); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] public async Task ExpressionStatement_SemanticError(string optionName) { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|M2()|]; } }", optionName); } [WorkItem(33073, "https://github.com/dotnet/roslyn/issues/33073")] [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] public async Task ExpressionStatement_SemanticError_02(string optionName) { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|M2()|]; } UndefinedType M2() => null; }", optionName); } [WorkItem(33073, "https://github.com/dotnet/roslyn/issues/33073")] [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] public async Task ExpressionStatement_SemanticError_03(string optionName) { await TestMissingInRegularAndScriptAsync( @"using System.Threading.Tasks; class C { private async Task M() { // error CS0103: The name 'CancellationToken' does not exist in the current context [|await Task.Delay(0, CancellationToken.None).ConfigureAwait(false)|]; } }", optionName); } [WorkItem(33073, "https://github.com/dotnet/roslyn/issues/33073")] [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] public async Task ExpressionStatement_SemanticError_04(string optionName) { await TestMissingInRegularAndScriptAsync( @"class C { private async Task M() { // error CS0103: The name 'Task' does not exist in the current context // error CS0103: The name 'CancellationToken' does not exist in the current context // error CS1983: The return type of an async method must be void, Task or Task<T> [|await Task.Delay(0, CancellationToken.None).ConfigureAwait(false)|]; } }", optionName); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] public async Task ExpressionStatement_VoidReturningMethodCall(string optionName) { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|M2()|]; } void M2() { } }", optionName); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] [InlineData("=")] [InlineData("+=")] public async Task ExpressionStatement_AssignmentExpression(string op) { await TestMissingInRegularAndScriptWithAllOptionsAsync( $@"class C {{ void M(int x) {{ x {op} [|M2()|]; }} int M2() => 0; }}"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] [InlineData("x++")] [InlineData("x--")] [InlineData("++x")] [InlineData("--x")] public async Task ExpressionStatement_IncrementOrDecrement(string incrementOrDecrement) { await TestMissingInRegularAndScriptWithAllOptionsAsync( $@"class C {{ int M(int x) {{ [|{incrementOrDecrement}|]; return x; }} }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] public async Task ExpressionStatement_UnusedLocal_NameAlreadyUsed() { await TestInRegularAndScriptAsync( @"class C { void M() { var unused = M2(); [|M2()|]; } int M2() => 0; }", @"class C { void M() { var unused = M2(); var unused1 = M2(); } int M2() => 0; }", options: PreferUnusedLocal); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] public async Task ExpressionStatement_UnusedLocal_NameAlreadyUsed_02() { await TestInRegularAndScriptAsync( @"class C { void M() { [|M2()|]; var unused = M2(); } int M2() => 0; }", @"class C { void M() { var unused1 = M2(); var unused = M2(); } int M2() => 0; }", options: PreferUnusedLocal); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] public async Task ExpressionStatement_UnusedLocal_NameAlreadyUsed_03() { await TestInRegularAndScriptAsync( @"class C { void M(int p) { [|M2()|]; if (p > 0) { var unused = M2(); } } int M2() => 0; }", @"class C { void M(int p) { var unused1 = M2(); if (p > 0) { var unused = M2(); } } int M2() => 0; }", options: PreferUnusedLocal); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] public async Task ExpressionStatement_UnusedLocal_NameAlreadyUsed_04() { await TestInRegularAndScriptAsync( @"class C { void M(int p) { if (p > 0) { [|M2()|]; } else { var unused = M2(); } } int M2() => 0; }", @"class C { void M(int p) { if (p > 0) { var unused1 = M2(); } else { var unused = M2(); } } int M2() => 0; }", options: PreferUnusedLocal); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] [InlineData(nameof(PreferDiscard), "_", "_", "_")] [InlineData(nameof(PreferUnusedLocal), "var unused", "var unused", "var unused3")] public async Task ExpressionStatement_FixAll(string optionName, string fix1, string fix2, string fix3) { await TestInRegularAndScriptAsync( @"class C { public C() { M2(); // Separate code block } void M(int unused1, int unused2) { {|FixAllInDocument:M2()|}; M2(); // Another instance in same code block _ = M2(); // Already fixed var x = M2(); // Different unused value diagnostic } int M2() => 0; }", $@"class C {{ public C() {{ {fix1} = M2(); // Separate code block }} void M(int unused1, int unused2) {{ {fix2} = M2(); {fix3} = M2(); // Another instance in same code block _ = M2(); // Already fixed var x = M2(); // Different unused value diagnostic }} int M2() => 0; }}", optionName); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] public async Task ExpressionStatement_Trivia_PreferDiscard_01() { await TestInRegularAndScriptAsync( @"class C { void M() { // C1 [|M2()|]; // C2 // C3 } int M2() => 0; }", @"class C { void M() { // C1 _ = M2(); // C2 // C3 } int M2() => 0; }", options: PreferDiscard); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] public async Task ExpressionStatement_Trivia_PreferDiscard_02() { await TestInRegularAndScriptAsync( @"class C { void M() {/*C0*/ /*C1*/[|M2()|]/*C2*/;/*C3*/ /*C4*/ } int M2() => 0; }", @"class C { void M() {/*C0*/ /*C1*/ _ = M2()/*C2*/;/*C3*/ /*C4*/ } int M2() => 0; }", options: PreferDiscard); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] public async Task ExpressionStatement_Trivia_PreferUnusedLocal_01() { await TestInRegularAndScriptAsync( @"class C { void M() { // C1 [|M2()|]; // C2 // C3 } int M2() => 0; }", @"class C { void M() { // C1 var unused = M2(); // C2 // C3 } int M2() => 0; }", options: PreferUnusedLocal); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] public async Task ExpressionStatement_Trivia_PreferUnusedLocal_02() { await TestInRegularAndScriptAsync( @"class C { void M() {/*C0*/ /*C1*/[|M2()|]/*C2*/;/*C3*/ /*C4*/ } int M2() => 0; }", @"class C { void M() {/*C0*/ /*C1*/ var unused = M2()/*C2*/;/*C3*/ /*C4*/ } int M2() => 0; }", options: PreferUnusedLocal); } [WorkItem(32942, "https://github.com/dotnet/roslyn/issues/32942")] [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] public async Task ExpressionBodiedMember_01(string optionName) { await TestMissingInRegularAndScriptAsync( @"class C { void M() => [|M2()|]; int M2() => 0; }", optionName); } [WorkItem(32942, "https://github.com/dotnet/roslyn/issues/32942")] [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] public async Task ExpressionBodiedMember_02(string optionName) { await TestMissingInRegularAndScriptAsync( @"class C { void M() { System.Action a = () => [|M2()|]; } int M2() => 0; }", optionName); } [WorkItem(32942, "https://github.com/dotnet/roslyn/issues/32942")] [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedValues)] [InlineData(nameof(PreferDiscard))] [InlineData(nameof(PreferUnusedLocal))] public async Task ExpressionBodiedMember_03(string optionName) { await TestMissingInRegularAndScriptAsync( @"class C { void M() { LocalFunction(); return; void LocalFunction() => [|M2()|]; } int M2() => 0; }", optionName); } } }
24.798077
133
0.590604
[ "Apache-2.0" ]
KGRWhite/roslyn
src/EditorFeatures/CSharpTest/RemoveUnusedParametersAndValues/RemoveUnusedValueExpressionStatementTests.cs
15,476
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Dds.Model.V20151201; namespace Aliyun.Acs.Dds.Transform.V20151201 { public class DescribeSlowLogRecordsResponseUnmarshaller { public static DescribeSlowLogRecordsResponse Unmarshall(UnmarshallerContext _ctx) { DescribeSlowLogRecordsResponse describeSlowLogRecordsResponse = new DescribeSlowLogRecordsResponse(); describeSlowLogRecordsResponse.HttpResponse = _ctx.HttpResponse; describeSlowLogRecordsResponse.RequestId = _ctx.StringValue("DescribeSlowLogRecords.RequestId"); describeSlowLogRecordsResponse.Engine = _ctx.StringValue("DescribeSlowLogRecords.Engine"); describeSlowLogRecordsResponse.TotalRecordCount = _ctx.IntegerValue("DescribeSlowLogRecords.TotalRecordCount"); describeSlowLogRecordsResponse.PageNumber = _ctx.IntegerValue("DescribeSlowLogRecords.PageNumber"); describeSlowLogRecordsResponse.PageRecordCount = _ctx.IntegerValue("DescribeSlowLogRecords.PageRecordCount"); List<DescribeSlowLogRecordsResponse.DescribeSlowLogRecords_LogRecords> describeSlowLogRecordsResponse_items = new List<DescribeSlowLogRecordsResponse.DescribeSlowLogRecords_LogRecords>(); for (int i = 0; i < _ctx.Length("DescribeSlowLogRecords.Items.Length"); i++) { DescribeSlowLogRecordsResponse.DescribeSlowLogRecords_LogRecords logRecords = new DescribeSlowLogRecordsResponse.DescribeSlowLogRecords_LogRecords(); logRecords.HostAddress = _ctx.StringValue("DescribeSlowLogRecords.Items["+ i +"].HostAddress"); logRecords.DBName = _ctx.StringValue("DescribeSlowLogRecords.Items["+ i +"].DBName"); logRecords.SQLText = _ctx.StringValue("DescribeSlowLogRecords.Items["+ i +"].SQLText"); logRecords.QueryTimes = _ctx.StringValue("DescribeSlowLogRecords.Items["+ i +"].QueryTimes"); logRecords.DocsExamined = _ctx.LongValue("DescribeSlowLogRecords.Items["+ i +"].DocsExamined"); logRecords.KeysExamined = _ctx.LongValue("DescribeSlowLogRecords.Items["+ i +"].KeysExamined"); logRecords.ReturnRowCounts = _ctx.LongValue("DescribeSlowLogRecords.Items["+ i +"].ReturnRowCounts"); logRecords.ExecutionStartTime = _ctx.StringValue("DescribeSlowLogRecords.Items["+ i +"].ExecutionStartTime"); logRecords.AccountName = _ctx.StringValue("DescribeSlowLogRecords.Items["+ i +"].AccountName"); logRecords.TableName = _ctx.StringValue("DescribeSlowLogRecords.Items["+ i +"].TableName"); describeSlowLogRecordsResponse_items.Add(logRecords); } describeSlowLogRecordsResponse.Items = describeSlowLogRecordsResponse_items; return describeSlowLogRecordsResponse; } } }
56.548387
191
0.781517
[ "Apache-2.0" ]
awei1688/aliyun-openapi-net-sdk
aliyun-net-sdk-dds/Dds/Transform/V20151201/DescribeSlowLogRecordsResponseUnmarshaller.cs
3,506
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.IO; using System.Linq.Expressions; using System.Security; using System.Security.Authentication; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using Microsoft.Win32; using Xunit; namespace System { public static partial class PlatformDetection { // // Do not use the " { get; } = <expression> " pattern here. Having all the initialization happen in the type initializer // means that one exception anywhere means all tests using PlatformDetection fail. If you feel a value is worth latching, // do it in a way that failures don't cascade. // public static bool IsNetCore => Environment.Version.Major >= 5 || RuntimeInformation.FrameworkDescription.StartsWith(".NET Core", StringComparison.OrdinalIgnoreCase); public static bool IsMonoRuntime => Type.GetType("Mono.RuntimeStructs") != null; public static bool IsNotMonoRuntime => !IsMonoRuntime; public static bool IsMonoInterpreter => GetIsRunningOnMonoInterpreter(); public static bool IsMonoAOT => Environment.GetEnvironmentVariable("MONO_AOT_MODE") == "aot"; public static bool IsNotMonoAOT => Environment.GetEnvironmentVariable("MONO_AOT_MODE") != "aot"; public static bool IsNativeAot => IsNotMonoRuntime && !IsReflectionEmitSupported; public static bool IsFreeBSD => RuntimeInformation.IsOSPlatform(OSPlatform.Create("FREEBSD")); public static bool IsNetBSD => RuntimeInformation.IsOSPlatform(OSPlatform.Create("NETBSD")); public static bool IsAndroid => RuntimeInformation.IsOSPlatform(OSPlatform.Create("ANDROID")); public static bool IsiOS => RuntimeInformation.IsOSPlatform(OSPlatform.Create("IOS")); public static bool IstvOS => RuntimeInformation.IsOSPlatform(OSPlatform.Create("TVOS")); public static bool IsMacCatalyst => RuntimeInformation.IsOSPlatform(OSPlatform.Create("MACCATALYST")); public static bool Isillumos => RuntimeInformation.IsOSPlatform(OSPlatform.Create("ILLUMOS")); public static bool IsSolaris => RuntimeInformation.IsOSPlatform(OSPlatform.Create("SOLARIS")); public static bool IsBrowser => RuntimeInformation.IsOSPlatform(OSPlatform.Create("BROWSER")); public static bool IsNotBrowser => !IsBrowser; public static bool IsMobile => IsBrowser || IsAppleMobile || IsAndroid; public static bool IsNotMobile => !IsMobile; public static bool IsAppleMobile => IsMacCatalyst || IsiOS || IstvOS; public static bool IsNotAppleMobile => !IsAppleMobile; public static bool IsNotNetFramework => !IsNetFramework; public static bool IsArmProcess => RuntimeInformation.ProcessArchitecture == Architecture.Arm; public static bool IsNotArmProcess => !IsArmProcess; public static bool IsArm64Process => RuntimeInformation.ProcessArchitecture == Architecture.Arm64; public static bool IsNotArm64Process => !IsArm64Process; public static bool IsArmOrArm64Process => IsArmProcess || IsArm64Process; public static bool IsNotArmNorArm64Process => !IsArmOrArm64Process; public static bool IsArmv6Process => (int)RuntimeInformation.ProcessArchitecture == 7; // Architecture.Armv6 public static bool IsX86Process => RuntimeInformation.ProcessArchitecture == Architecture.X86; public static bool IsNotX86Process => !IsX86Process; public static bool IsArgIteratorSupported => IsMonoRuntime || (IsWindows && IsNotArmProcess && !IsNativeAot); public static bool IsArgIteratorNotSupported => !IsArgIteratorSupported; public static bool Is32BitProcess => IntPtr.Size == 4; public static bool Is64BitProcess => IntPtr.Size == 8; public static bool IsNotWindows => !IsWindows; private static Lazy<bool> s_isCheckedRuntime => new Lazy<bool>(() => AssemblyConfigurationEquals("Checked")); private static Lazy<bool> s_isReleaseRuntime => new Lazy<bool>(() => AssemblyConfigurationEquals("Release")); private static Lazy<bool> s_isDebugRuntime => new Lazy<bool>(() => AssemblyConfigurationEquals("Debug")); public static bool IsCheckedRuntime => s_isCheckedRuntime.Value; public static bool IsReleaseRuntime => s_isReleaseRuntime.Value; public static bool IsDebugRuntime => s_isDebugRuntime.Value; // For use as needed on tests that time out when run on a Debug runtime. // Not relevant for timeouts on external activities, such as network timeouts. public static int SlowRuntimeTimeoutModifier = (PlatformDetection.IsDebugRuntime ? 5 : 1); public static bool IsCaseInsensitiveOS => IsWindows || IsOSX || IsMacCatalyst; #if NETCOREAPP public static bool IsCaseSensitiveOS => !IsCaseInsensitiveOS && !RuntimeInformation.RuntimeIdentifier.StartsWith("iossimulator") && !RuntimeInformation.RuntimeIdentifier.StartsWith("tvossimulator"); #else public static bool IsCaseSensitiveOS => !IsCaseInsensitiveOS; #endif public static bool IsThreadingSupported => !IsBrowser; public static bool IsBinaryFormatterSupported => IsNotMobile && !IsNativeAot; public static bool IsSymLinkSupported => !IsiOS && !IstvOS; public static bool IsSpeedOptimized => !IsSizeOptimized; public static bool IsSizeOptimized => IsBrowser || IsAndroid || IsAppleMobile; public static bool IsBrowserDomSupported => IsEnvironmentVariableTrue("IsBrowserDomSupported"); public static bool IsBrowserDomSupportedOrNotBrowser => IsNotBrowser || IsBrowserDomSupported; public static bool IsNotBrowserDomSupported => !IsBrowserDomSupported; public static bool IsWebSocketSupported => IsEnvironmentVariableTrue("IsWebSocketSupported"); public static bool IsNodeJS => IsEnvironmentVariableTrue("IsNodeJS"); public static bool IsNotNodeJS => !IsNodeJS; public static bool LocalEchoServerIsNotAvailable => !LocalEchoServerIsAvailable; public static bool LocalEchoServerIsAvailable => IsBrowser; public static bool IsUsingLimitedCultures => !IsNotMobile; public static bool IsNotUsingLimitedCultures => IsNotMobile; public static bool IsLinqExpressionsBuiltWithIsInterpretingOnly => s_linqExpressionsBuiltWithIsInterpretingOnly.Value; public static bool IsNotLinqExpressionsBuiltWithIsInterpretingOnly => !IsLinqExpressionsBuiltWithIsInterpretingOnly; private static readonly Lazy<bool> s_linqExpressionsBuiltWithIsInterpretingOnly = new Lazy<bool>(GetLinqExpressionsBuiltWithIsInterpretingOnly); private static bool GetLinqExpressionsBuiltWithIsInterpretingOnly() { return !(bool)typeof(LambdaExpression).GetMethod("get_CanCompileToIL").Invoke(null, Array.Empty<object>()); } // Drawing is not supported on non windows platforms in .NET 7.0+. public static bool IsDrawingSupported => IsWindows && IsNotWindowsNanoServer && IsNotWindowsServerCore; public static bool IsAsyncFileIOSupported => !IsBrowser && !(IsWindows && IsMonoRuntime); // https://github.com/dotnet/runtime/issues/34582 public static bool IsLineNumbersSupported => !IsNativeAot; public static bool IsInContainer => GetIsInContainer(); public static bool SupportsComInterop => IsWindows && IsNotMonoRuntime && !IsNativeAot; // matches definitions in clr.featuredefines.props public static bool SupportsSsl3 => GetSsl3Support(); public static bool SupportsSsl2 => IsWindows && !PlatformDetection.IsWindows10Version1607OrGreater; #if NETCOREAPP public static bool IsReflectionEmitSupported => RuntimeFeature.IsDynamicCodeSupported; public static bool IsNotReflectionEmitSupported => !IsReflectionEmitSupported; #else public static bool IsReflectionEmitSupported => true; #endif public static bool IsInvokingStaticConstructorsSupported => !IsNativeAot; public static bool IsMetadataUpdateSupported => !IsNativeAot; // System.Security.Cryptography.Xml.XmlDsigXsltTransform.GetOutput() relies on XslCompiledTransform which relies // heavily on Reflection.Emit public static bool IsXmlDsigXsltTransformSupported => !PlatformDetection.IsInAppContainer && IsReflectionEmitSupported; public static bool IsPreciseGcSupported => !IsMonoRuntime; public static bool IsNotIntMaxValueArrayIndexSupported => s_largeArrayIsNotSupported.Value; public static bool IsAssemblyLoadingSupported => !IsNativeAot; public static bool IsMethodBodySupported => !IsNativeAot; public static bool IsDebuggerTypeProxyAttributeSupported => !IsNativeAot; private static volatile Tuple<bool> s_lazyNonZeroLowerBoundArraySupported; public static bool IsNonZeroLowerBoundArraySupported { get { if (s_lazyNonZeroLowerBoundArraySupported == null) { bool nonZeroLowerBoundArraysSupported = false; try { Array.CreateInstance(typeof(int), new int[] { 5 }, new int[] { 5 }); nonZeroLowerBoundArraysSupported = true; } catch (PlatformNotSupportedException) { } s_lazyNonZeroLowerBoundArraySupported = Tuple.Create<bool>(nonZeroLowerBoundArraysSupported); } return s_lazyNonZeroLowerBoundArraySupported.Item1; } } private static volatile Tuple<bool> s_lazyMetadataTokensSupported; public static bool IsMetadataTokenSupported { get { if (s_lazyMetadataTokensSupported == null) { bool metadataTokensSupported = false; try { _ = typeof(PlatformDetection).MetadataToken; metadataTokensSupported = true; } catch (InvalidOperationException) { } s_lazyMetadataTokensSupported = Tuple.Create<bool>(metadataTokensSupported); } return s_lazyMetadataTokensSupported.Item1; } } public static bool IsDomainJoinedMachine => !Environment.MachineName.Equals(Environment.UserDomainName, StringComparison.OrdinalIgnoreCase); public static bool IsNotDomainJoinedMachine => !IsDomainJoinedMachine; public static bool IsOpenSslSupported => IsLinux || IsFreeBSD || Isillumos || IsSolaris; public static bool UsesAppleCrypto => IsOSX || IsMacCatalyst || IsiOS || IstvOS; public static bool UsesMobileAppleCrypto => IsMacCatalyst || IsiOS || IstvOS; // Changed to `true` when linking public static bool IsBuiltWithAggressiveTrimming => false; public static bool IsNotBuiltWithAggressiveTrimming => !IsBuiltWithAggressiveTrimming; // Windows - Schannel supports alpn from win8.1/2012 R2 and higher. // Linux - OpenSsl supports alpn from openssl 1.0.2 and higher. // OSX - SecureTransport doesn't expose alpn APIs. TODO https://github.com/dotnet/runtime/issues/27727 // Android - Platform supports alpn from API level 29 and higher private static Lazy<bool> s_supportsAlpn = new Lazy<bool>(GetAlpnSupport); private static bool GetAlpnSupport() { if (IsWindows && !IsWindows7 && !IsNetFramework) { return true; } if (IsOpenSslSupported) { if (OpenSslVersion.Major >= 3) { return true; } return OpenSslVersion.Major == 1 && (OpenSslVersion.Minor >= 1 || OpenSslVersion.Build >= 2); } if (IsAndroid) { return Interop.AndroidCrypto.SSLSupportsApplicationProtocolsConfiguration(); } return false; } public static bool SupportsAlpn => s_supportsAlpn.Value; public static bool SupportsClientAlpn => SupportsAlpn || IsOSX || IsMacCatalyst || IsiOS || IstvOS; private static Lazy<bool> s_supportsTls10 = new Lazy<bool>(GetTls10Support); private static Lazy<bool> s_supportsTls11 = new Lazy<bool>(GetTls11Support); private static Lazy<bool> s_supportsTls12 = new Lazy<bool>(GetTls12Support); private static Lazy<bool> s_supportsTls13 = new Lazy<bool>(GetTls13Support); public static bool SupportsTls10 => s_supportsTls10.Value; public static bool SupportsTls11 => s_supportsTls11.Value; public static bool SupportsTls12 => s_supportsTls12.Value; public static bool SupportsTls13 => s_supportsTls13.Value; private static Lazy<bool> s_largeArrayIsNotSupported = new Lazy<bool>(IsLargeArrayNotSupported); [MethodImpl(MethodImplOptions.NoOptimization)] private static bool IsLargeArrayNotSupported() { try { var tmp = new byte[int.MaxValue]; return tmp == null; } catch (OutOfMemoryException) { return true; } } public static string GetDistroVersionString() { if (IsWindows) { return "WindowsProductType=" + GetWindowsProductType() + " WindowsInstallationType=" + GetWindowsInstallationType(); } else if (IsOSX) { return "OSX Version=" + Environment.OSVersion.Version.ToString(); } else { DistroInfo v = GetDistroInfo(); return $"Distro={v.Id} VersionId={v.VersionId}"; } } private static readonly Lazy<bool> m_isInvariant = new Lazy<bool>(() => GetStaticNonPublicBooleanPropertyValue("System.Globalization.GlobalizationMode", "Invariant")); private static bool GetStaticNonPublicBooleanPropertyValue(string typeName, string propertyName) { if (Type.GetType(typeName)?.GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Static)?.GetMethod is MethodInfo mi) { return (bool)mi.Invoke(null, null); } return false; } private static readonly Lazy<Version> m_icuVersion = new Lazy<Version>(GetICUVersion); public static Version ICUVersion => m_icuVersion.Value; public static bool IsInvariantGlobalization => m_isInvariant.Value; public static bool IsNotInvariantGlobalization => !IsInvariantGlobalization; public static bool IsIcuGlobalization => ICUVersion > new Version(0,0,0,0); public static bool IsNlsGlobalization => IsNotInvariantGlobalization && !IsIcuGlobalization; public static bool IsSubstAvailable { get { try { if (IsWindows) { string systemRoot = Environment.GetEnvironmentVariable("SystemRoot"); if (string.IsNullOrWhiteSpace(systemRoot)) { return false; } string system32 = Path.Combine(systemRoot, "System32"); return File.Exists(Path.Combine(system32, "subst.exe")); } } catch { } return false; } } private static Version GetICUVersion() { int version = 0; try { Type interopGlobalization = Type.GetType("Interop+Globalization, System.Private.CoreLib"); if (interopGlobalization != null) { MethodInfo methodInfo = interopGlobalization.GetMethod("GetICUVersion", BindingFlags.NonPublic | BindingFlags.Static); if (methodInfo != null) { version = (int)methodInfo.Invoke(null, null); } } } catch { } return new Version(version >> 24, (version >> 16) & 0xFF, (version >> 8) & 0xFF, version & 0xFF); } private static readonly Lazy<bool> s_fileLockingDisabled = new Lazy<bool>(() => GetStaticNonPublicBooleanPropertyValue("Microsoft.Win32.SafeHandles.SafeFileHandle", "DisableFileLocking")); public static bool IsFileLockingEnabled => IsWindows || !s_fileLockingDisabled.Value; private static bool GetIsInContainer() { if (IsWindows) { string key = @"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control"; return Registry.GetValue(key, "ContainerType", defaultValue: null) != null; } return (IsLinux && File.Exists("/.dockerenv")); } private static bool GetProtocolSupportFromWindowsRegistry(SslProtocols protocol, bool defaultProtocolSupport) { string registryProtocolName = protocol switch { #pragma warning disable CS0618 // Ssl2 and Ssl3 are obsolete SslProtocols.Ssl3 => "SSL 3.0", #pragma warning restore CS0618 SslProtocols.Tls => "TLS 1.0", SslProtocols.Tls11 => "TLS 1.1", SslProtocols.Tls12 => "TLS 1.2", #if !NETFRAMEWORK SslProtocols.Tls13 => "TLS 1.3", #endif _ => throw new Exception($"Registry key not defined for {protocol}.") }; string clientKey = @$"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\{registryProtocolName}\Client"; string serverKey = @$"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\{registryProtocolName}\Server"; object client, server; try { client = Registry.GetValue(clientKey, "Enabled", defaultProtocolSupport ? 1 : 0); server = Registry.GetValue(serverKey, "Enabled", defaultProtocolSupport ? 1 : 0); if (client is int c && server is int s) { return c == 1 && s == 1; } } catch (SecurityException) { // Insufficient permission, assume that we don't have protocol support (since we aren't exactly sure) return false; } catch { } return defaultProtocolSupport; } private static bool GetSsl3Support() { if (IsWindows) { // Missing key. If we're pre-20H1 then assume SSL3 is enabled. // Otherwise, disabled. (See comments on https://github.com/dotnet/runtime/issues/1166) // Alternatively the returned values must have been some other types. bool ssl3DefaultSupport = !IsWindows10Version2004OrGreater; #pragma warning disable CS0618 // Ssl2 and Ssl3 are obsolete return GetProtocolSupportFromWindowsRegistry(SslProtocols.Ssl3, ssl3DefaultSupport); #pragma warning restore CS0618 } return (IsOSX || (IsLinux && OpenSslVersion < new Version(1, 0, 2) && !IsDebian)); } private static bool OpenSslGetTlsSupport(SslProtocols protocol) { Debug.Assert(IsOpenSslSupported); int ret = Interop.OpenSsl.OpenSslGetProtocolSupport((int)protocol); return ret == 1; } private static readonly Lazy<SslProtocols> s_androidSupportedSslProtocols = new Lazy<SslProtocols>(Interop.AndroidCrypto.SSLGetSupportedProtocols); private static bool AndroidGetSslProtocolSupport(SslProtocols protocol) { Debug.Assert(IsAndroid); return (protocol & s_androidSupportedSslProtocols.Value) == protocol; } private static bool GetTls10Support() { // on Windows, macOS, and Android TLS1.0/1.1 are supported. if (IsOSXLike || IsAndroid) { return true; } if (IsWindows) { return GetProtocolSupportFromWindowsRegistry(SslProtocols.Tls, true); } return OpenSslGetTlsSupport(SslProtocols.Tls); } private static bool GetTls11Support() { // on Windows, macOS, and Android TLS1.0/1.1 are supported. if (IsWindows) { // TLS 1.1 and 1.2 can work on Windows7 but it is not enabled by default. bool defaultProtocolSupport = !IsWindows7; return GetProtocolSupportFromWindowsRegistry(SslProtocols.Tls11, defaultProtocolSupport); } else if (IsOSXLike || IsAndroid) { return true; } return OpenSslGetTlsSupport(SslProtocols.Tls11); } private static bool GetTls12Support() { // TLS 1.1 and 1.2 can work on Windows7 but it is not enabled by default. bool defaultProtocolSupport = !IsWindows7; return GetProtocolSupportFromWindowsRegistry(SslProtocols.Tls12, defaultProtocolSupport); } private static bool GetTls13Support() { if (IsWindows) { if (!IsWindows10Version2004OrGreater) { return false; } // assume no if positive entry is missing on older Windows // Latest insider builds have TLS 1.3 enabled by default. // The build number is approximation. bool defaultProtocolSupport = IsWindows10Version20348OrGreater; #if NETFRAMEWORK return false; #else return GetProtocolSupportFromWindowsRegistry(SslProtocols.Tls13, defaultProtocolSupport); #endif } else if (IsOSX || IsMacCatalyst || IsiOS || IstvOS) { // [ActiveIssue("https://github.com/dotnet/runtime/issues/1979")] return false; } else if (IsAndroid) { #if NETFRAMEWORK return false; #else return AndroidGetSslProtocolSupport(SslProtocols.Tls13); #endif } else if (IsOpenSslSupported) { // Covers Linux, FreeBSD, illumos and Solaris return OpenSslVersion >= new Version(1,1,1); } return false; } private static bool GetIsRunningOnMonoInterpreter() { #if NETCOREAPP return IsMonoRuntime && RuntimeFeature.IsDynamicCodeSupported && !RuntimeFeature.IsDynamicCodeCompiled; #else return false; #endif } private static bool IsEnvironmentVariableTrue(string variableName) { if (!IsBrowser) return false; var val = Environment.GetEnvironmentVariable(variableName); return (val != null && val == "true"); } private static bool AssemblyConfigurationEquals(string configuration) { AssemblyConfigurationAttribute assemblyConfigurationAttribute = typeof(string).Assembly.GetCustomAttribute<AssemblyConfigurationAttribute>(); return assemblyConfigurationAttribute != null && string.Equals(assemblyConfigurationAttribute.Configuration, configuration, StringComparison.InvariantCulture); } } }
44.966667
196
0.633226
[ "MIT" ]
BodyBuildingKang/runtime
src/libraries/Common/tests/TestUtilities/System/PlatformDetection.cs
24,282
C#
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. // // Microsoft Bot Framework: http://botframework.com // // Bot Builder SDK Github: // https://github.com/Microsoft/BotBuilder // // 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. // using Autofac; using Microsoft.Bot.Builder.Internals.Fibers; using Microsoft.Bot.Connector; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.Bot.Builder.Internals.Scorables { /// <summary> /// Allow the resolution of values based on type and optionally tag. /// </summary> public interface IResolver { bool TryResolve(Type type, object tag, out object value); } public delegate bool TryResolve(Type type, object tag, out object value); public static partial class Extensions { public static bool TryResolve<T>(this IResolver resolver, object tag, out T value) { object inner; if (resolver.TryResolve(typeof(T), tag, out inner)) { value = (T)inner; return true; } else { value = default(T); return false; } } } public sealed class NullResolver : IResolver { bool IResolver.TryResolve(Type type, object tag, out object value) { value = null; return false; } } public abstract class DelegatingResolver : IResolver { protected readonly IResolver inner; protected DelegatingResolver(IResolver inner) { SetField.NotNull(out this.inner, nameof(inner), inner); } public virtual bool TryResolve(Type type, object tag, out object value) { return inner.TryResolve(type, tag, out value); } } public sealed class DictionaryResolver : DelegatingResolver { private readonly IReadOnlyDictionary<Type, object> serviceByType; public DictionaryResolver(IReadOnlyDictionary<Type, object> serviceByType, IResolver inner) : base(inner) { SetField.NotNull(out this.serviceByType, nameof(serviceByType), serviceByType); } public override bool TryResolve(Type type, object tag, out object value) { if (this.serviceByType.TryGetValue(type, out value)) { return true; } return base.TryResolve(type, tag, out value); } } /// <summary> /// A resolver to recover C# type information from Activity schema types. /// </summary> public sealed class ActivityResolver : DelegatingResolver { public ActivityResolver(IResolver inner) : base(inner) { } public static readonly IReadOnlyDictionary<string, Type> TypeByName = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase) { { ActivityTypes.ContactRelationUpdate, typeof(IContactRelationUpdateActivity) }, { ActivityTypes.ConversationUpdate, typeof(IConversationUpdateActivity) }, { ActivityTypes.DeleteUserData, typeof(IActivity) }, { ActivityTypes.Message, typeof(IMessageActivity) }, { ActivityTypes.Ping, typeof(IActivity) }, { ActivityTypes.Typing, typeof(ITypingActivity) }, }; public override bool TryResolve(Type type, object tag, out object value) { // if type is Activity, we're not delegating to the inner IResolver. if (typeof(IActivity).IsAssignableFrom(type)) { // if we have a registered IActivity IActivity activity; if (this.inner.TryResolve<IActivity>(tag, out activity)) { // then make sure the IActivity.Type allows the desired type Type allowedType; if (TypeByName.TryGetValue(activity.Type, out allowedType)) { if (type.IsAssignableFrom(allowedType)) { // and make sure the actual CLR type also allows the desired type // (this is true most of the time since Activity implements all of the interfaces) Type clrType = activity.GetType(); if (allowedType.IsAssignableFrom(clrType)) { value = activity; return true; } } } } // otherwise we were asking for IActivity and it wasn't assignable from the IActivity.Type value = null; return false; } // delegate to the inner for all remaining type resolutions return base.TryResolve(type, tag, out value); } } public sealed class AutofacResolver : DelegatingResolver { private readonly ILifetimeScope scope; public AutofacResolver(ILifetimeScope scope, IResolver inner) : base(inner) { SetField.NotNull(out this.scope, nameof(scope), scope); } public override bool TryResolve(Type type, object tag, out object value) { if (tag != null && this.scope.TryResolveKeyed(tag, type, out value)) { return true; } else if (this.scope.TryResolve(type, out value)) { return true; } return base.TryResolve(type, tag, out value); } } }
35.326531
140
0.598498
[ "MIT" ]
luciany/BotBuilder
CSharp/Library/Scorables/Resolver.cs
6,926
C#
using System; namespace Gizmo { public static class StringExtensions { public static bool IsNotQuit(this string s) { if(s == null) return true; s = s.Trim().ToLower(); return !(s == ":q" || s == ":quit"); } public static bool IsNullOrEmpty(this string val) { return string.IsNullOrEmpty(val); } public static string Truncate(this string text, int length, string ellipsis = null, bool breakOnWord = false) { if (text.IsNullOrEmpty()) return string.Empty; if (text.Length < length) return text; if(ellipsis.IsNullOrEmpty()) { text = text.Substring(0, length); } else { text = text.Substring(0, length - ellipsis.Length); } if (breakOnWord) { text = text.Substring(0, text.LastIndexOf(' ')); } return text + ellipsis; } } }
25.02381
117
0.486204
[ "MIT" ]
jasonchester/gizmo.sh
src/Gizmo/StringExtensions.cs
1,051
C#
/* * Streamr API * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: 1.0.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using RestSharp; using NUnit.Framework; using IO.Swagger.Client; using IO.Swagger.Api; using IO.Swagger.Model; namespace IO.Swagger.Test { /// <summary> /// Class for testing CanvasesApi /// </summary> /// <remarks> /// This file is automatically generated by Swagger Codegen. /// Please update the test case below to test the API endpoint. /// </remarks> [TestFixture] public class CanvasesApiTests { private CanvasesApi instance; /// <summary> /// Setup before each unit test /// </summary> [SetUp] public void Init() { instance = new CanvasesApi(); } /// <summary> /// Clean up after each unit test /// </summary> [TearDown] public void Cleanup() { } /// <summary> /// Test an instance of CanvasesApi /// </summary> [Test] public void InstanceTest() { // TODO uncomment below to test 'IsInstanceOfType' CanvasesApi //Assert.IsInstanceOfType(typeof(CanvasesApi), instance, "instance is a CanvasesApi"); } /// <summary> /// Test CanvasesDownloadCsvGet /// </summary> [Test] public void CanvasesDownloadCsvGetTest() { // TODO uncomment below to test the method and replace null with proper value //string filename = null; //var response = instance.CanvasesDownloadCsvGet(filename); //Assert.IsInstanceOf<System.IO.Stream> (response, "response is System.IO.Stream"); } /// <summary> /// Test CanvasesGet /// </summary> [Test] public void CanvasesGetTest() { // TODO uncomment below to test the method and replace null with proper value //string name = null; //string state = null; //bool? adhoc = null; //string search = null; //string sortBy = null; //string order = null; //int? max = null; //int? offset = null; //bool? grantedAccess = null; //bool? publicAccess = null; //string operation = null; //var response = instance.CanvasesGet(name, state, adhoc, search, sortBy, order, max, offset, grantedAccess, publicAccess, operation); //Assert.IsInstanceOf<List<Canvas>> (response, "response is List<Canvas>"); } /// <summary> /// Test CanvasesIdDelete /// </summary> [Test] public void CanvasesIdDeleteTest() { // TODO uncomment below to test the method and replace null with proper value //string id = null; //instance.CanvasesIdDelete(id); } /// <summary> /// Test CanvasesIdGet /// </summary> [Test] public void CanvasesIdGetTest() { // TODO uncomment below to test the method and replace null with proper value //string id = null; //var response = instance.CanvasesIdGet(id); //Assert.IsInstanceOf<Canvas> (response, "response is Canvas"); } /// <summary> /// Test CanvasesIdPermissionsGet /// </summary> [Test] public void CanvasesIdPermissionsGetTest() { // TODO uncomment below to test the method and replace null with proper value //string id = null; //var response = instance.CanvasesIdPermissionsGet(id); //Assert.IsInstanceOf<List<Permission>> (response, "response is List<Permission>"); } /// <summary> /// Test CanvasesIdPermissionsPidDelete /// </summary> [Test] public void CanvasesIdPermissionsPidDeleteTest() { // TODO uncomment below to test the method and replace null with proper value //string id = null; //int? pid = null; //instance.CanvasesIdPermissionsPidDelete(id, pid); } /// <summary> /// Test CanvasesIdPermissionsPidGet /// </summary> [Test] public void CanvasesIdPermissionsPidGetTest() { // TODO uncomment below to test the method and replace null with proper value //string id = null; //int? pid = null; //var response = instance.CanvasesIdPermissionsPidGet(id, pid); //Assert.IsInstanceOf<Permission> (response, "response is Permission"); } /// <summary> /// Test CanvasesIdPermissionsPost /// </summary> [Test] public void CanvasesIdPermissionsPostTest() { // TODO uncomment below to test the method and replace null with proper value //string id = null; //Permission body = null; //var response = instance.CanvasesIdPermissionsPost(id, body); //Assert.IsInstanceOf<Permission> (response, "response is Permission"); } /// <summary> /// Test CanvasesIdPut /// </summary> [Test] public void CanvasesIdPutTest() { // TODO uncomment below to test the method and replace null with proper value //string id = null; //CanvasCreateRequest body = null; //instance.CanvasesIdPut(id, body); } /// <summary> /// Test CanvasesIdStartPost /// </summary> [Test] public void CanvasesIdStartPostTest() { // TODO uncomment below to test the method and replace null with proper value //string id = null; //StartRequest body = null; //var response = instance.CanvasesIdStartPost(id, body); //Assert.IsInstanceOf<Canvas> (response, "response is Canvas"); } /// <summary> /// Test CanvasesIdStopPost /// </summary> [Test] public void CanvasesIdStopPostTest() { // TODO uncomment below to test the method and replace null with proper value //string id = null; //var response = instance.CanvasesIdStopPost(id); //Assert.IsInstanceOf<Canvas> (response, "response is Canvas"); } /// <summary> /// Test CanvasesPost /// </summary> [Test] public void CanvasesPostTest() { // TODO uncomment below to test the method and replace null with proper value //CanvasCreateRequest body = null; //var response = instance.CanvasesPost(body); //Assert.IsInstanceOf<Canvas> (response, "response is Canvas"); } } }
31.908297
146
0.550568
[ "Apache-2.0" ]
Rjrunner44/streamr-api-dotnet-tutorial
csharp-client/src/IO.Swagger.Test/Api/CanvasesApiTests.cs
7,307
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization.Formatters.Binary; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using System.Xml; namespace MobiFlightInstaller { static public class MobiFlightHelperMethods { public static readonly string ProcessName = "MFConnector"; public static readonly string OptionBetaEnableSearch = "/configuration/userSettings/MobiFlight.Properties.Settings/setting[@name='BetaUpdates']"; static Char[] s_Base32Char = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5'}; static public bool GetMfBetaOptionValue() { if (!File.Exists(Directory.GetCurrentDirectory() + "\\" + ProcessName + ".exe")) { Log.Instance.log("MFConnector.exe not found, BETA disable", LogSeverity.Debug); return false; } string PatchConfigFile = MobiFlightHelperMethods.GetExeLocalAppDataUserConfigPath(Directory.GetCurrentDirectory() + "\\" + ProcessName + ".exe"); Log.Instance.log("Check BETA option in " + PatchConfigFile, LogSeverity.Debug); if (!File.Exists(PatchConfigFile)) { Log.Instance.log("Impossible to read the file does not exist -> BETA disable", LogSeverity.Debug); return false; } bool result = ExtractConfigBetaValueFromXML(PatchConfigFile); if (result) Log.Instance.log("BETA enable", LogSeverity.Debug); else Log.Instance.log("BETA disable", LogSeverity.Debug); return result; } static public bool ExtractConfigBetaValueFromXML(string PatchConfigFile) { string xmlFile = File.ReadAllText(@PatchConfigFile); XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(xmlFile); XmlNodeList nodeList = xmldoc.SelectNodes(OptionBetaEnableSearch); string Result = string.Empty; foreach (XmlNode node in nodeList) { Result = node.InnerText; } if (Result == "True") return true; else return false; } static public string GetExeLocalAppDataUserConfigPath(string fullExePath) { var localAppDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); var versionInfo = FileVersionInfo.GetVersionInfo(fullExePath); var companyName = versionInfo.CompanyName; var exeName = versionInfo.OriginalFilename; var assemblyName = AssemblyName.GetAssemblyName(fullExePath); var version = assemblyName.Version.ToString(); var uri = "file:///" + fullExePath; uri = uri.ToUpperInvariant(); var ms = new MemoryStream(); var bSer = new BinaryFormatter(); bSer.Serialize(ms, uri); ms.Position = 0; var sha1 = new SHA1CryptoServiceProvider(); var hash = sha1.ComputeHash(ms); var hashstring = ToBase32StringSuitableForDirName(hash); var userConfigLocalAppDataPath = Path.Combine(localAppDataPath, companyName, exeName + "_Url_" + hashstring, version, "user.config"); return userConfigLocalAppDataPath; } private static string ToBase32StringSuitableForDirName(byte[] buff) { StringBuilder sb = new StringBuilder(); byte b0, b1, b2, b3, b4; int l, i; l = buff.Length; i = 0; // Create l chars using the last 5 bits of each byte. // Consume 3 MSB bits 5 bytes at a time. do { b0 = (i < l) ? buff[i++] : (byte)0; b1 = (i < l) ? buff[i++] : (byte)0; b2 = (i < l) ? buff[i++] : (byte)0; b3 = (i < l) ? buff[i++] : (byte)0; b4 = (i < l) ? buff[i++] : (byte)0; // Consume the 5 Least significant bits of each byte sb.Append(s_Base32Char[b0 & 0x1F]); sb.Append(s_Base32Char[b1 & 0x1F]); sb.Append(s_Base32Char[b2 & 0x1F]); sb.Append(s_Base32Char[b3 & 0x1F]); sb.Append(s_Base32Char[b4 & 0x1F]); // Consume 3 MSB of b0, b1, MSB bits 6, 7 of b3, b4 sb.Append(s_Base32Char[( ((b0 & 0xE0) >> 5) | ((b3 & 0x60) >> 2))]); sb.Append(s_Base32Char[( ((b1 & 0xE0) >> 5) | ((b4 & 0x60) >> 2))]); // Consume 3 MSB bits of b2, 1 MSB bit of b3, b4 b2 >>= 5; if ((b3 & 0x80) != 0) b2 |= 0x08; if ((b4 & 0x80) != 0) b2 |= 0x10; sb.Append(s_Base32Char[b2]); } while (i < l); return sb.ToString(); } } }
36.108844
157
0.537679
[ "Unlicense" ]
CaptainBobSim/Connector-Open-Source-Control-Loading-system
MobiFlight-Installer/MobiFlight-Installer/model/MobiFlightHelperMethods.cs
5,310
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using UnityEngine.UI; namespace UI.Xml.Tags { public partial class ToggleTagHandler : InputBaseTagHandler, IHasXmlFormValue { } }
17.714286
81
0.770161
[ "Apache-2.0" ]
exporl/lars-common
Plugins/UI/XmlLayout/ViewModel/Tags/Toggle.MVVM.cs
248
C#
using System; using System.Threading.Tasks; using System.Windows; using System.Windows.Media; using Microsoft.Phone.Shell; using MVVMSidekick.ViewModels; namespace WikiaWP.ViewModels { public static class ViewModelExtensions { public static readonly TimeSpan DefaultShowToastMessageTime = TimeSpan.FromSeconds(2); public static async Task ShowToastMessageAsync<TViewModel>(this ViewModelBase<TViewModel> vm, string message, TimeSpan time = default(TimeSpan)) where TViewModel : ViewModelBase<TViewModel> { if (message == null) { throw new ArgumentNullException("message"); } if (time < TimeSpan.Zero) { throw new ArgumentOutOfRangeException("time"); } if (time == TimeSpan.Zero) { time = DefaultShowToastMessageTime; } await vm.Dispatcher.InvokeAsync( async () => { var currentIndicator = SystemTray.ProgressIndicator; var currentColor = SystemTray.BackgroundColor; var newIndicator = new ProgressIndicator { Text = message, IsIndeterminate = false, IsVisible = true }; SystemTray.BackgroundColor = (Color)Application.Current.Resources["PhoneAccentColor"]; SystemTray.ProgressIndicator = newIndicator; await Task.Delay(time); SystemTray.BackgroundColor = currentColor; SystemTray.ProgressIndicator = currentIndicator; }); } } }
34.37037
153
0.531789
[ "MIT" ]
lianzhao/WikiaWP
src/WikiaWP/ViewModels/ViewModelExtensions.cs
1,858
C#
using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; using Commitments.Core.Extensions; namespace Commitments.Api.Features.Users { [Authorize] [ApiController] [Route("api/users")] public class UsersController { private readonly IHttpContextAccessor _httpContextAccessor; private readonly IMediator _mediator; public UsersController(IHttpContextAccessor httpContextAccessor, IMediator mediator) { _httpContextAccessor = httpContextAccessor; _mediator = mediator; } [AllowAnonymous] [HttpPost("token")] public async Task<ActionResult<AuthenticateCommand.Response>> SignIn(AuthenticateCommand.Request request) => await _mediator.Send(request); [HttpPost("changePassword")] public async Task<ActionResult<ChangePasswordCommand.Response>> ChangePassword(ChangePasswordCommand.Request request) { request.ProfileId = _httpContextAccessor.GetProfileIdFromClaims(); return await _mediator.Send(request); } } }
33.6
127
0.712585
[ "MIT" ]
QuinntyneBrown/Commitments
src/Commitments.API/Features/Users/UsersController.cs
1,176
C#
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; namespace SixLabors.Fonts.Unicode { /// <summary> /// Implementation of Unicode Bidirection Algorithm (UAX #9) /// https://unicode.org/reports/tr9/ /// </summary> /// <remarks> /// <para> /// The Bidi algorithm uses a number of memory arrays for resolved /// types, level information, bracket types, x9 removal maps and /// more... /// </para> /// <para> /// This implementation of the Bidi algorithm has been designed /// to reduce memory pressure on the GC by re-using the same /// work buffers, so instances of this class should be re-used /// as much as possible. /// </para> /// </remarks> internal sealed class BidiAlgorithm { /// <summary> /// The original BidiCharacterType types as provided by the caller /// </summary> private ReadOnlyArraySlice<BidiCharacterType> originalTypes; /// <summary> /// Paired bracket types as provided by caller /// </summary> private ReadOnlyArraySlice<BidiPairedBracketType> pairedBracketTypes; /// <summary> /// Paired bracket values as provided by caller /// </summary> private ReadOnlyArraySlice<int> pairedBracketValues; /// <summary> /// Try if the incoming data is known to contain brackets /// </summary> private bool hasBrackets; /// <summary> /// True if the incoming data is known to contain embedding runs /// </summary> private bool hasEmbeddings; /// <summary> /// True if the incoming data is known to contain isolating runs /// </summary> private bool hasIsolates; /// <summary> /// Two directional mapping of isolate start/end pairs /// </summary> /// <remarks> /// The forward mapping maps the start index to the end index. /// The reverse mapping maps the end index to the start index. /// </remarks> private readonly BidiDictionary<int, int> isolatePairs = new(); /// <summary> /// The working BidiCharacterType types /// </summary> private ArraySlice<BidiCharacterType> workingTypes; /// <summary> /// The buffer underlying _workingTypes /// </summary> private ArrayBuilder<BidiCharacterType> workingTypesBuffer; /// <summary> /// A slice of the resolved levels. /// </summary> private ArraySlice<sbyte> resolvedLevels; /// <summary> /// The buffer underlying resolvedLevels /// </summary> private ArrayBuilder<sbyte> resolvedLevelsBuffer; /// <summary> /// The resolve paragraph embedding level /// </summary> private sbyte paragraphEmbeddingLevel; /// <summary> /// The status stack used during resolution of explicit /// embedding and isolating runs /// </summary> private readonly Stack<Status> statusStack = new(); /// <summary> /// Mapping used to virtually remove characters for rule X9 /// </summary> private ArrayBuilder<int> x9Map; /// <summary> /// Re-usable list of level runs /// </summary> private readonly List<LevelRun> levelRuns = new(); /// <summary> /// Mapping for the current isolating sequence, built /// by joining level runs from the x9 map. /// </summary> private ArrayBuilder<int> isolatedRunMapping; /// <summary> /// A stack of pending isolate openings used by FindIsolatePairs() /// </summary> private readonly Stack<int> pendingIsolateOpenings = new(); /// <summary> /// The level of the isolating run currently being processed /// </summary> private int runLevel; /// <summary> /// The direction of the isolating run currently being processed /// </summary> private BidiCharacterType runDirection; /// <summary> /// The length of the isolating run currently being processed /// </summary> private int runLength; /// <summary> /// A mapped slice of the resolved types for the isolating run currently /// being processed /// </summary> private MappedArraySlice<BidiCharacterType> runResolvedTypes; /// <summary> /// A mapped slice of the original types for the isolating run currently /// being processed /// </summary> private MappedArraySlice<BidiCharacterType> runOriginalTypes; /// <summary> /// A mapped slice of the run levels for the isolating run currently /// being processed /// </summary> private MappedArraySlice<sbyte> runLevels; /// <summary> /// A mapped slice of the paired bracket types of the isolating /// run currently being processed /// </summary> private MappedArraySlice<BidiPairedBracketType> runBidiPairedBracketTypes; /// <summary> /// A mapped slice of the paired bracket values of the isolating /// run currently being processed /// </summary> private MappedArraySlice<int> runPairedBracketValues; /// <summary> /// Maximum pairing depth for paired brackets /// </summary> private const int MaxPairedBracketDepth = 63; /// <summary> /// Reusable list of pending opening brackets used by the /// LocatePairedBrackets method /// </summary> private readonly List<int> pendingOpeningBrackets = new(); /// <summary> /// Resolved list of paired brackets /// </summary> private readonly List<BracketPair> pairedBrackets = new(); /// <summary> /// Initializes a new instance of the <see cref="BidiAlgorithm"/> class. /// </summary> public BidiAlgorithm() { } /// <summary> /// Gets a per-thread instance that can be re-used as often /// as necessary. /// </summary> public static ThreadLocal<BidiAlgorithm> Instance { get; } = new ThreadLocal<BidiAlgorithm>(() => new BidiAlgorithm()); /// <summary> /// Gets the resolved levels. /// </summary> public ArraySlice<sbyte> ResolvedLevels => this.resolvedLevels; /// <summary> /// Gets the resolved paragraph embedding level /// </summary> public int ResolvedParagraphEmbeddingLevel => this.paragraphEmbeddingLevel; /// <summary> /// Process data from a BidiData instance /// </summary> /// <param name="data">The Bidi Unicode data.</param> public void Process(BidiData data) => this.Process( data.Types, data.PairedBracketTypes, data.PairedBracketValues, data.ParagraphEmbeddingLevel, data.HasBrackets, data.HasEmbeddings, data.HasIsolates, null); /// <summary> /// Processes Bidi Data /// </summary> public void Process( ReadOnlyArraySlice<BidiCharacterType> types, ReadOnlyArraySlice<BidiPairedBracketType> pairedBracketTypes, ReadOnlyArraySlice<int> pairedBracketValues, sbyte paragraphEmbeddingLevel, bool? hasBrackets, bool? hasEmbeddings, bool? hasIsolates, ArraySlice<sbyte>? outLevels) { // Reset state this.isolatePairs.Clear(); this.workingTypesBuffer.Clear(); this.levelRuns.Clear(); this.resolvedLevelsBuffer.Clear(); // Setup original types and working types this.originalTypes = types; this.workingTypes = this.workingTypesBuffer.Add(types); // Capture paired bracket values and types this.pairedBracketTypes = pairedBracketTypes; this.pairedBracketValues = pairedBracketValues; // Store things we know this.hasBrackets = hasBrackets ?? this.pairedBracketTypes.Length == this.originalTypes.Length; this.hasEmbeddings = hasEmbeddings ?? true; this.hasIsolates = hasIsolates ?? true; // Find all isolate pairs this.FindIsolatePairs(); // Resolve the paragraph embedding level if (paragraphEmbeddingLevel == 2) { this.paragraphEmbeddingLevel = this.ResolveEmbeddingLevel(this.originalTypes); } else { this.paragraphEmbeddingLevel = paragraphEmbeddingLevel; } // Create resolved levels buffer if (outLevels.HasValue) { if (outLevels.Value.Length != this.originalTypes.Length) { throw new ArgumentException("Out levels must be the same length as the input data"); } this.resolvedLevels = outLevels.Value; } else { this.resolvedLevels = this.resolvedLevelsBuffer.Add(this.originalTypes.Length); this.resolvedLevels.Fill(this.paragraphEmbeddingLevel); } // Resolve explicit embedding levels (Rules X1-X8) this.ResolveExplicitEmbeddingLevels(); // Build the rule X9 map this.BuildX9RemovalMap(); // Process all isolated run sequences this.ProcessIsolatedRunSequences(); // Reset whitespace levels this.ResetWhitespaceLevels(); // Clean up this.AssignLevelsToCodePointsRemovedByX9(); } /// <summary> /// Resolve the paragraph embedding level if not explicitly passed /// by the caller. Also used by rule X5c for FSI isolating sequences. /// </summary> /// <param name="data">The data to be evaluated</param> /// <returns>The resolved embedding level</returns> public sbyte ResolveEmbeddingLevel(ReadOnlyArraySlice<BidiCharacterType> data) { // P2 for (int i = 0; i < data.Length; ++i) { switch (data[i]) { case BidiCharacterType.LeftToRight: // P3 return 0; case BidiCharacterType.ArabicLetter: case BidiCharacterType.RightToLeft: // P3 return 1; case BidiCharacterType.FirstStrongIsolate: case BidiCharacterType.LeftToRightIsolate: case BidiCharacterType.RightToLeftIsolate: // Skip isolate pairs // (Because we're working with a slice, we need to adjust the indices // we're using for the isolatePairs map) if (this.isolatePairs.TryGetValue(data.Start + i, out i)) { i -= data.Start; } else { i = data.Length; } break; } } // P3 return 0; } /// <summary> /// Build a list of matching isolates for a directionality slice /// Implements BD9 /// </summary> private void FindIsolatePairs() { // Redundant? if (!this.hasIsolates) { return; } // Lets double check this as we go and clear the flag // if there actually aren't any isolate pairs as this might // mean we can skip some later steps this.hasIsolates = false; // BD9... this.pendingIsolateOpenings.Clear(); for (int i = 0; i < this.originalTypes.Length; i++) { BidiCharacterType t = this.originalTypes[i]; if (t is BidiCharacterType.LeftToRightIsolate or BidiCharacterType.RightToLeftIsolate or BidiCharacterType.FirstStrongIsolate) { this.pendingIsolateOpenings.Push(i); this.hasIsolates = true; } else if (t == BidiCharacterType.PopDirectionalIsolate) { if (this.pendingIsolateOpenings.Count > 0) { this.isolatePairs.Add(this.pendingIsolateOpenings.Pop(), i); } this.hasIsolates = true; } } } /// <summary> /// Resolve the explicit embedding levels from the original /// data. Implements rules X1 to X8. /// </summary> private void ResolveExplicitEmbeddingLevels() { // Redundant? if (!this.hasIsolates && !this.hasEmbeddings) { return; } // Work variables this.statusStack.Clear(); int overflowIsolateCount = 0; int overflowEmbeddingCount = 0; int validIsolateCount = 0; // Constants const int maxStackDepth = 125; // Rule X1 - setup initial state this.statusStack.Clear(); // Neutral this.statusStack.Push(new Status(this.paragraphEmbeddingLevel, BidiCharacterType.OtherNeutral, false)); // Process all characters for (int i = 0; i < this.originalTypes.Length; i++) { switch (this.originalTypes[i]) { case BidiCharacterType.RightToLeftEmbedding: { // Rule X2 sbyte newLevel = (sbyte)((this.statusStack.Peek().EmbeddingLevel + 1) | 1); if (newLevel <= maxStackDepth && overflowIsolateCount == 0 && overflowEmbeddingCount == 0) { this.statusStack.Push(new Status(newLevel, BidiCharacterType.OtherNeutral, false)); this.resolvedLevels[i] = newLevel; } else if (overflowIsolateCount == 0) { overflowEmbeddingCount++; } break; } case BidiCharacterType.LeftToRightEmbedding: { // Rule X3 sbyte newLevel = (sbyte)((this.statusStack.Peek().EmbeddingLevel + 2) & ~1); if (newLevel < maxStackDepth && overflowIsolateCount == 0 && overflowEmbeddingCount == 0) { this.statusStack.Push(new Status(newLevel, BidiCharacterType.OtherNeutral, false)); this.resolvedLevels[i] = newLevel; } else if (overflowIsolateCount == 0) { overflowEmbeddingCount++; } break; } case BidiCharacterType.RightToLeftOverride: { // Rule X4 sbyte newLevel = (sbyte)((this.statusStack.Peek().EmbeddingLevel + 1) | 1); if (newLevel <= maxStackDepth && overflowIsolateCount == 0 && overflowEmbeddingCount == 0) { this.statusStack.Push(new Status(newLevel, BidiCharacterType.RightToLeft, false)); this.resolvedLevels[i] = newLevel; } else if (overflowIsolateCount == 0) { overflowEmbeddingCount++; } break; } case BidiCharacterType.LeftToRightOverride: { // Rule X5 sbyte newLevel = (sbyte)((this.statusStack.Peek().EmbeddingLevel + 2) & ~1); if (newLevel <= maxStackDepth && overflowIsolateCount == 0 && overflowEmbeddingCount == 0) { this.statusStack.Push(new Status(newLevel, BidiCharacterType.LeftToRight, false)); this.resolvedLevels[i] = newLevel; } else if (overflowIsolateCount == 0) { overflowEmbeddingCount++; } break; } case BidiCharacterType.RightToLeftIsolate: case BidiCharacterType.LeftToRightIsolate: case BidiCharacterType.FirstStrongIsolate: { // Rule X5a, X5b and X5c BidiCharacterType resolvedIsolate = this.originalTypes[i]; if (resolvedIsolate == BidiCharacterType.FirstStrongIsolate) { if (!this.isolatePairs.TryGetValue(i, out int endOfIsolate)) { endOfIsolate = this.originalTypes.Length; } // Rule X5c if (this.ResolveEmbeddingLevel(this.originalTypes.Slice(i + 1, endOfIsolate - (i + 1))) == 1) { resolvedIsolate = BidiCharacterType.RightToLeftIsolate; } else { resolvedIsolate = BidiCharacterType.LeftToRightIsolate; } } // Replace RLI's level with current embedding level Status tos = this.statusStack.Peek(); this.resolvedLevels[i] = tos.EmbeddingLevel; // Apply override if (tos.OverrideStatus != BidiCharacterType.OtherNeutral) { this.workingTypes[i] = tos.OverrideStatus; } // Work out new level sbyte newLevel; if (resolvedIsolate == BidiCharacterType.RightToLeftIsolate) { newLevel = (sbyte)((tos.EmbeddingLevel + 1) | 1); } else { newLevel = (sbyte)((tos.EmbeddingLevel + 2) & ~1); } // Valid? if (newLevel <= maxStackDepth && overflowIsolateCount == 0 && overflowEmbeddingCount == 0) { validIsolateCount++; this.statusStack.Push(new Status(newLevel, BidiCharacterType.OtherNeutral, true)); } else { overflowIsolateCount++; } break; } case BidiCharacterType.BoundaryNeutral: { // Mentioned in rule X6 - "for all types besides ..., BN, ..." // no-op break; } default: { // Rule X6 Status tos = this.statusStack.Peek(); this.resolvedLevels[i] = tos.EmbeddingLevel; if (tos.OverrideStatus != BidiCharacterType.OtherNeutral) { this.workingTypes[i] = tos.OverrideStatus; } break; } case BidiCharacterType.PopDirectionalIsolate: { // Rule X6a if (overflowIsolateCount > 0) { overflowIsolateCount--; } else if (validIsolateCount != 0) { overflowEmbeddingCount = 0; while (!this.statusStack.Peek().IsolateStatus) { this.statusStack.Pop(); } this.statusStack.Pop(); validIsolateCount--; } Status tos = this.statusStack.Peek(); this.resolvedLevels[i] = tos.EmbeddingLevel; if (tos.OverrideStatus != BidiCharacterType.OtherNeutral) { this.workingTypes[i] = tos.OverrideStatus; } break; } case BidiCharacterType.PopDirectionalFormat: { // Rule X7 if (overflowIsolateCount == 0) { if (overflowEmbeddingCount > 0) { overflowEmbeddingCount--; } else if (!this.statusStack.Peek().IsolateStatus && this.statusStack.Count >= 2) { this.statusStack.Pop(); } } break; } case BidiCharacterType.ParagraphSeparator: { // Rule X8 this.resolvedLevels[i] = this.paragraphEmbeddingLevel; break; } } } } /// <summary> /// Build a map to the original data positions that excludes all /// the types defined by rule X9 /// </summary> private void BuildX9RemovalMap() { // Reserve room for the x9 map this.x9Map.Length = this.originalTypes.Length; if (this.hasEmbeddings || this.hasIsolates) { // Build a map the removes all x9 characters int j = 0; for (int i = 0; i < this.originalTypes.Length; i++) { if (!IsRemovedByX9(this.originalTypes[i])) { this.x9Map[j++] = i; } } // Set the final length this.x9Map.Length = j; } else { for (int i = 0, count = this.originalTypes.Length; i < count; i++) { this.x9Map[i] = i; } } } /// <summary> /// Find the original character index for an entry in the X9 map /// </summary> /// <param name="index">Index in the x9 removal map</param> /// <returns>Index to the original data</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] private int MapX9(int index) => this.x9Map[index]; /// <summary> /// Add a new level run /// </summary> /// <remarks> /// This method resolves the sos and eos values for the run /// and adds the run to the list /// /// </remarks> /// <param name="start">The index of the start of the run (in x9 removed units)</param> /// <param name="length">The length of the run (in x9 removed units)</param> /// <param name="level">The level of the run</param> private void AddLevelRun(int start, int length, int level) { // Get original indices to first and last character in this run int firstCharIndex = this.MapX9(start); int lastCharIndex = this.MapX9(start + length - 1); // Work out sos int i = firstCharIndex - 1; while (i >= 0 && IsRemovedByX9(this.originalTypes[i])) { i--; } sbyte prevLevel = i < 0 ? this.paragraphEmbeddingLevel : this.resolvedLevels[i]; BidiCharacterType sos = DirectionFromLevel(Math.Max(prevLevel, level)); // Work out eos BidiCharacterType lastType = this.workingTypes[lastCharIndex]; int nextLevel; if (lastType is BidiCharacterType.LeftToRightIsolate or BidiCharacterType.RightToLeftIsolate or BidiCharacterType.FirstStrongIsolate) { nextLevel = this.paragraphEmbeddingLevel; } else { i = lastCharIndex + 1; while (i < this.originalTypes.Length && IsRemovedByX9(this.originalTypes[i])) { i++; } nextLevel = i >= this.originalTypes.Length ? this.paragraphEmbeddingLevel : this.resolvedLevels[i]; } BidiCharacterType eos = DirectionFromLevel(Math.Max(nextLevel, level)); // Add the run this.levelRuns.Add(new LevelRun(start, length, level, sos, eos)); } /// <summary> /// Find all runs of the same level, populating the _levelRuns /// collection /// </summary> private void FindLevelRuns() { int currentLevel = -1; int runStart = 0; for (int i = 0; i < this.x9Map.Length; ++i) { int level = this.resolvedLevels[this.MapX9(i)]; if (level != currentLevel) { if (currentLevel != -1) { this.AddLevelRun(runStart, i - runStart, currentLevel); } currentLevel = level; runStart = i; } } // Don't forget the final level run if (currentLevel != -1) { this.AddLevelRun(runStart, this.x9Map.Length - runStart, currentLevel); } } /// <summary> /// Given a character index, find the level run that starts at that position /// </summary> /// <param name="index">The index into the original (unmapped) data</param> /// <returns>The index of the run that starts at that index</returns> private int FindRunForIndex(int index) { for (int i = 0; i < this.levelRuns.Count; i++) { // Passed index is for the original non-x9 filtered data, however // the level run ranges are for the x9 filtered data. Convert before // comparing if (this.MapX9(this.levelRuns[i].Start) == index) { return i; } } throw new InvalidOperationException("Internal error"); } /// <summary> /// Determine and the process all isolated run sequences /// </summary> private void ProcessIsolatedRunSequences() { // Find all runs with the same level this.FindLevelRuns(); // Process them one at a time by first building // a mapping using slices from the x9 map for each // run section that needs to be joined together to // form an complete run. That full run mapping // will be placed in _isolatedRunMapping and then // processed by ProcessIsolatedRunSequence(). while (this.levelRuns.Count > 0) { // Clear the mapping this.isolatedRunMapping.Clear(); // Combine mappings from this run and all runs that continue on from it int runIndex = 0; BidiCharacterType eos; BidiCharacterType sos = this.levelRuns[0].Sos; int level = this.levelRuns[0].Level; while (true) { // Get the run LevelRun r = this.levelRuns[runIndex]; // The eos of the isolating run is the eos of the // last level run that comprises it. eos = r.Eos; // Remove this run as we've now processed it this.levelRuns.RemoveAt(runIndex); // Add the x9 map indices for the run range to the mapping // for this isolated run this.isolatedRunMapping.Add(this.x9Map.AsSlice(r.Start, r.Length)); // Get the last character and see if it's an isolating run with a matching // PDI and concatenate that run to this one int lastCharacterIndex = this.isolatedRunMapping[this.isolatedRunMapping.Length - 1]; BidiCharacterType lastType = this.originalTypes[lastCharacterIndex]; if ((lastType == BidiCharacterType.LeftToRightIsolate || lastType == BidiCharacterType.RightToLeftIsolate || lastType == BidiCharacterType.FirstStrongIsolate) && this.isolatePairs.TryGetValue(lastCharacterIndex, out int nextRunIndex)) { // Find the continuing run index runIndex = this.FindRunForIndex(nextRunIndex); } else { break; } } // Process this isolated run this.ProcessIsolatedRunSequence(sos, eos, level); } } /// <summary> /// Process a single isolated run sequence, where the character sequence /// mapping is currently held in _isolatedRunMapping. /// </summary> private void ProcessIsolatedRunSequence(BidiCharacterType sos, BidiCharacterType eos, int runLevel) { // Create mappings onto the underlying data this.runResolvedTypes = new MappedArraySlice<BidiCharacterType>(this.workingTypes, this.isolatedRunMapping.AsSlice()); this.runOriginalTypes = new MappedArraySlice<BidiCharacterType>(this.originalTypes, this.isolatedRunMapping.AsSlice()); this.runLevels = new MappedArraySlice<sbyte>(this.resolvedLevels, this.isolatedRunMapping.AsSlice()); if (this.hasBrackets) { this.runBidiPairedBracketTypes = new MappedArraySlice<BidiPairedBracketType>(this.pairedBracketTypes, this.isolatedRunMapping.AsSlice()); this.runPairedBracketValues = new MappedArraySlice<int>(this.pairedBracketValues, this.isolatedRunMapping.AsSlice()); } this.runLevel = runLevel; this.runDirection = DirectionFromLevel(runLevel); this.runLength = this.runResolvedTypes.Length; // By tracking the types of characters known to be in the current run, we can // skip some of the rules that we know won't apply. The flags will be // initialized while we're processing rule W1 below. bool hasEN = false; bool hasAL = false; bool hasES = false; bool hasCS = false; bool hasAN = false; bool hasET = false; // Rule W1 // Also, set hasXX flags int i; BidiCharacterType prevType = sos; for (i = 0; i < this.runLength; i++) { BidiCharacterType t = this.runResolvedTypes[i]; switch (t) { case BidiCharacterType.NonspacingMark: this.runResolvedTypes[i] = prevType; break; case BidiCharacterType.LeftToRightIsolate: case BidiCharacterType.RightToLeftIsolate: case BidiCharacterType.FirstStrongIsolate: case BidiCharacterType.PopDirectionalIsolate: prevType = BidiCharacterType.OtherNeutral; break; case BidiCharacterType.EuropeanNumber: hasEN = true; prevType = t; break; case BidiCharacterType.ArabicLetter: hasAL = true; prevType = t; break; case BidiCharacterType.EuropeanSeparator: hasES = true; prevType = t; break; case BidiCharacterType.CommonSeparator: hasCS = true; prevType = t; break; case BidiCharacterType.ArabicNumber: hasAN = true; prevType = t; break; case BidiCharacterType.EuropeanTerminator: hasET = true; prevType = t; break; default: prevType = t; break; } } // Rule W2 if (hasEN) { for (i = 0; i < this.runLength; i++) { if (this.runResolvedTypes[i] == BidiCharacterType.EuropeanNumber) { for (int j = i - 1; j >= 0; j--) { BidiCharacterType t = this.runResolvedTypes[j]; if (t is BidiCharacterType.LeftToRight or BidiCharacterType.RightToLeft or BidiCharacterType.ArabicLetter) { if (t == BidiCharacterType.ArabicLetter) { this.runResolvedTypes[i] = BidiCharacterType.ArabicNumber; hasAN = true; } break; } } } } } // Rule W3 if (hasAL) { for (i = 0; i < this.runLength; i++) { if (this.runResolvedTypes[i] == BidiCharacterType.ArabicLetter) { this.runResolvedTypes[i] = BidiCharacterType.RightToLeft; } } } // Rule W4 if ((hasES || hasCS) && (hasEN || hasAN)) { for (i = 1; i < this.runLength - 1; ++i) { ref BidiCharacterType rt = ref this.runResolvedTypes[i]; if (rt == BidiCharacterType.EuropeanSeparator) { BidiCharacterType prevSepType = this.runResolvedTypes[i - 1]; BidiCharacterType succSepType = this.runResolvedTypes[i + 1]; if (prevSepType == BidiCharacterType.EuropeanNumber && succSepType == BidiCharacterType.EuropeanNumber) { // ES between EN and EN rt = BidiCharacterType.EuropeanNumber; } } else if (rt == BidiCharacterType.CommonSeparator) { BidiCharacterType prevSepType = this.runResolvedTypes[i - 1]; BidiCharacterType succSepType = this.runResolvedTypes[i + 1]; if ((prevSepType == BidiCharacterType.ArabicNumber && succSepType == BidiCharacterType.ArabicNumber) || (prevSepType == BidiCharacterType.EuropeanNumber && succSepType == BidiCharacterType.EuropeanNumber)) { // CS between (AN and AN) or (EN and EN) rt = prevSepType; } } } } // Rule W5 if (hasET && hasEN) { for (i = 0; i < this.runLength; ++i) { if (this.runResolvedTypes[i] == BidiCharacterType.EuropeanTerminator) { // Locate end of sequence int seqStart = i; int seqEnd = i; while (seqEnd < this.runLength && this.runResolvedTypes[seqEnd] == BidiCharacterType.EuropeanTerminator) { seqEnd++; } // Preceded by, or followed by EN? if ((seqStart == 0 ? sos : this.runResolvedTypes[seqStart - 1]) == BidiCharacterType.EuropeanNumber || (seqEnd == this.runLength ? eos : this.runResolvedTypes[seqEnd]) == BidiCharacterType.EuropeanNumber) { // Change the entire range for (int j = seqStart; i < seqEnd; ++i) { this.runResolvedTypes[i] = BidiCharacterType.EuropeanNumber; } } // continue at end of sequence i = seqEnd; } } } // Rule W6 if (hasES || hasET || hasCS) { for (i = 0; i < this.runLength; ++i) { ref BidiCharacterType t = ref this.runResolvedTypes[i]; if (t is BidiCharacterType.EuropeanSeparator or BidiCharacterType.EuropeanTerminator or BidiCharacterType.CommonSeparator) { t = BidiCharacterType.OtherNeutral; } } } // Rule W7. if (hasEN) { BidiCharacterType prevStrongType = sos; for (i = 0; i < this.runLength; ++i) { ref BidiCharacterType rt = ref this.runResolvedTypes[i]; if (rt == BidiCharacterType.EuropeanNumber) { // If prev strong type was an L change this to L too if (prevStrongType == BidiCharacterType.LeftToRight) { this.runResolvedTypes[i] = BidiCharacterType.LeftToRight; } } // Remember previous strong type (NB: AL should already be changed to R) if (rt is BidiCharacterType.LeftToRight or BidiCharacterType.RightToLeft) { prevStrongType = rt; } } } // Rule N0 - process bracket pairs if (this.hasBrackets) { int count; List<BracketPair>? pairedBrackets = this.LocatePairedBrackets(); for (i = 0, count = pairedBrackets.Count; i < count; i++) { BracketPair pb = pairedBrackets[i]; BidiCharacterType dir = this.InspectPairedBracket(pb); // Case "d" - no strong types in the brackets, ignore if (dir == BidiCharacterType.OtherNeutral) { continue; } // Case "b" - strong type found that matches the embedding direction if ((dir == BidiCharacterType.LeftToRight || dir == BidiCharacterType.RightToLeft) && dir == this.runDirection) { this.SetPairedBracketDirection(pb, dir); continue; } // Case "c" - found opposite strong type found, look before to establish context dir = this.InspectBeforePairedBracket(pb, sos); if (dir == this.runDirection || dir == BidiCharacterType.OtherNeutral) { dir = this.runDirection; } this.SetPairedBracketDirection(pb, dir); } } // Rules N1 and N2 - resolve neutral types for (i = 0; i < this.runLength; ++i) { BidiCharacterType t = this.runResolvedTypes[i]; if (this.IsNeutralType(t)) { // Locate end of sequence int seqStart = i; int seqEnd = i; while (seqEnd < this.runLength && this.IsNeutralType(this.runResolvedTypes[seqEnd])) { seqEnd++; } // Work out the preceding type BidiCharacterType typeBefore; if (seqStart == 0) { typeBefore = sos; } else { typeBefore = this.runResolvedTypes[seqStart - 1]; if (typeBefore is BidiCharacterType.ArabicNumber or BidiCharacterType.EuropeanNumber) { typeBefore = BidiCharacterType.RightToLeft; } } // Work out the following type BidiCharacterType typeAfter; if (seqEnd == this.runLength) { typeAfter = eos; } else { typeAfter = this.runResolvedTypes[seqEnd]; if (typeAfter is BidiCharacterType.ArabicNumber or BidiCharacterType.EuropeanNumber) { typeAfter = BidiCharacterType.RightToLeft; } } // Work out the final resolved type BidiCharacterType resolvedType; if (typeBefore == typeAfter) { // Rule N1 resolvedType = typeBefore; } else { // Rule N2 resolvedType = this.runDirection; } // Apply changes for (int j = seqStart; j < seqEnd; j++) { this.runResolvedTypes[j] = resolvedType; } // continue after this run i = seqEnd; } } // Rules I1 and I2 - resolve implicit types if ((this.runLevel & 0x01) == 0) { // Rule I1 - even for (i = 0; i < this.runLength; i++) { BidiCharacterType t = this.runResolvedTypes[i]; ref sbyte l = ref this.runLevels[i]; if (t == BidiCharacterType.RightToLeft) { l++; } else if (t is BidiCharacterType.ArabicNumber or BidiCharacterType.EuropeanNumber) { l += 2; } } } else { // Rule I2 - odd for (i = 0; i < this.runLength; i++) { BidiCharacterType t = this.runResolvedTypes[i]; ref sbyte l = ref this.runLevels[i]; if (t != BidiCharacterType.RightToLeft) { l++; } } } } /// <summary> /// Locate all pair brackets in the current isolating run /// </summary> /// <returns>A sorted list of BracketPairs</returns> private List<BracketPair> LocatePairedBrackets() { // Clear work collections this.pendingOpeningBrackets.Clear(); this.pairedBrackets.Clear(); // Since List.Sort is expensive on memory if called often (it internally // allocates an ArraySorted object) and since we will rarely have many // items in this list (most paragraphs will only have a handful of bracket // pairs - if that), we use a simple linear lookup and insert most of the // time. If there are more that `sortLimit` paired brackets we abort th // linear searching/inserting and using List.Sort at the end. const int sortLimit = 8; // Process all characters in the run, looking for paired brackets for (int ich = 0, length = this.runLength; ich < length; ich++) { // Ignore non-neutral characters if (this.runResolvedTypes[ich] != BidiCharacterType.OtherNeutral) { continue; } switch (this.runBidiPairedBracketTypes[ich]) { case BidiPairedBracketType.Open: if (this.pendingOpeningBrackets.Count == MaxPairedBracketDepth) { goto exit; } this.pendingOpeningBrackets.Insert(0, ich); break; case BidiPairedBracketType.Close: // see if there is a match for (int i = 0; i < this.pendingOpeningBrackets.Count; i++) { if (this.runPairedBracketValues[ich] == this.runPairedBracketValues[this.pendingOpeningBrackets[i]]) { // Add this paired bracket set int opener = this.pendingOpeningBrackets[i]; if (this.pairedBrackets.Count < sortLimit) { int ppi = 0; while (ppi < this.pairedBrackets.Count && this.pairedBrackets[ppi].OpeningIndex < opener) { ppi++; } this.pairedBrackets.Insert(ppi, new BracketPair(opener, ich)); } else { this.pairedBrackets.Add(new BracketPair(opener, ich)); } // remove up to and including matched opener this.pendingOpeningBrackets.RemoveRange(0, i + 1); break; } } break; } } exit: // Is a sort pending? if (this.pairedBrackets.Count > sortLimit) { this.pairedBrackets.Sort(); } return this.pairedBrackets; } /// <summary> /// Inspect a paired bracket set and determine its strong direction /// </summary> /// <param name="pb">The paired bracket to be inspected</param> /// <returns>The direction of the bracket set content</returns> private BidiCharacterType InspectPairedBracket(in BracketPair pb) { BidiCharacterType dirEmbed = DirectionFromLevel(this.runLevel); BidiCharacterType dirOpposite = BidiCharacterType.OtherNeutral; for (int ich = pb.OpeningIndex + 1; ich < pb.ClosingIndex; ich++) { BidiCharacterType dir = this.GetStrongTypeN0(this.runResolvedTypes[ich]); if (dir == BidiCharacterType.OtherNeutral) { continue; } if (dir == dirEmbed) { return dir; } dirOpposite = dir; } return dirOpposite; } /// <summary> /// Look for a strong type before a paired bracket /// </summary> /// <param name="pb">The paired bracket set to be inspected</param> /// <param name="sos">The sos in case nothing found before the bracket</param> /// <returns>The strong direction before the brackets</returns> private BidiCharacterType InspectBeforePairedBracket(in BracketPair pb, BidiCharacterType sos) { for (int ich = pb.OpeningIndex - 1; ich >= 0; --ich) { BidiCharacterType dir = this.GetStrongTypeN0(this.runResolvedTypes[ich]); if (dir != BidiCharacterType.OtherNeutral) { return dir; } } return sos; } /// <summary> /// Sets the direction of a bracket pair, including setting the direction of /// NSM's inside the brackets and following. /// </summary> /// <param name="pb">The paired brackets</param> /// <param name="dir">The resolved direction for the bracket pair</param> private void SetPairedBracketDirection(in BracketPair pb, BidiCharacterType dir) { // Set the direction of the brackets this.runResolvedTypes[pb.OpeningIndex] = dir; this.runResolvedTypes[pb.ClosingIndex] = dir; // Set the directionality of NSM's inside the brackets for (int i = pb.OpeningIndex + 1; i < pb.ClosingIndex; i++) { if (this.runOriginalTypes[i] == BidiCharacterType.NonspacingMark) { this.runOriginalTypes[i] = dir; } else { break; } } // Set the directionality of NSM's following the brackets for (int i = pb.ClosingIndex + 1; i < this.runLength; i++) { if (this.runOriginalTypes[i] == BidiCharacterType.NonspacingMark) { this.runResolvedTypes[i] = dir; } else { break; } } } /// <summary> /// Resets whitespace levels. Implements rule L1 /// </summary> private void ResetWhitespaceLevels() { for (int i = 0; i < this.resolvedLevels.Length; i++) { BidiCharacterType t = this.originalTypes[i]; if (t is BidiCharacterType.ParagraphSeparator or BidiCharacterType.SegmentSeparator) { // Rule L1, clauses one and two. this.resolvedLevels[i] = this.paragraphEmbeddingLevel; // Rule L1, clause three. for (int j = i - 1; j >= 0; --j) { if (IsWhitespace(this.originalTypes[j])) { // including format codes this.resolvedLevels[j] = this.paragraphEmbeddingLevel; } else { break; } } } } // Rule L1, clause four. for (int j = this.resolvedLevels.Length - 1; j >= 0; j--) { if (IsWhitespace(this.originalTypes[j])) { // including format codes this.resolvedLevels[j] = this.paragraphEmbeddingLevel; } else { break; } } } /// <summary> /// Assign levels to any characters that would be have been /// removed by rule X9. The idea is to keep level runs together /// that would otherwise be broken by an interfering isolate/embedding /// control character. /// </summary> private void AssignLevelsToCodePointsRemovedByX9() { // Redundant? if (!this.hasIsolates && !this.hasEmbeddings) { return; } // No-op? if (this.workingTypes.Length == 0) { return; } // Fix up first character if (this.resolvedLevels[0] < 0) { this.resolvedLevels[0] = this.paragraphEmbeddingLevel; } if (IsRemovedByX9(this.originalTypes[0])) { this.workingTypes[0] = this.originalTypes[0]; } for (int i = 1, length = this.workingTypes.Length; i < length; i++) { BidiCharacterType t = this.originalTypes[i]; if (IsRemovedByX9(t)) { this.workingTypes[i] = t; this.resolvedLevels[i] = this.resolvedLevels[i - 1]; } } } /// <summary> /// Check if a directionality type represents whitespace /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsWhitespace(BidiCharacterType biditype) => biditype switch { BidiCharacterType.LeftToRightEmbedding or BidiCharacterType.RightToLeftEmbedding or BidiCharacterType.LeftToRightOverride or BidiCharacterType.RightToLeftOverride or BidiCharacterType.PopDirectionalFormat or BidiCharacterType.LeftToRightIsolate or BidiCharacterType.RightToLeftIsolate or BidiCharacterType.FirstStrongIsolate or BidiCharacterType.PopDirectionalIsolate or BidiCharacterType.BoundaryNeutral or BidiCharacterType.Whitespace => true, _ => false, }; /// <summary> /// Convert a level to a direction where odd is RTL and /// even is LTR /// </summary> /// <param name="level">The level to convert</param> /// <returns>A directionality</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static BidiCharacterType DirectionFromLevel(int level) => ((level & 0x1) == 0) ? BidiCharacterType.LeftToRight : BidiCharacterType.RightToLeft; /// <summary> /// Helper to check if a directionality is removed by rule X9 /// </summary> /// <param name="biditype">The bidi type to check</param> /// <returns>True if rule X9 would remove this character; otherwise false</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsRemovedByX9(BidiCharacterType biditype) => biditype switch { BidiCharacterType.LeftToRightEmbedding or BidiCharacterType.RightToLeftEmbedding or BidiCharacterType.LeftToRightOverride or BidiCharacterType.RightToLeftOverride or BidiCharacterType.PopDirectionalFormat or BidiCharacterType.BoundaryNeutral => true, _ => false, }; /// <summary> /// Check if a a directionality is neutral for rules N1 and N2 /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool IsNeutralType(BidiCharacterType dir) => dir switch { BidiCharacterType.ParagraphSeparator or BidiCharacterType.SegmentSeparator or BidiCharacterType.Whitespace or BidiCharacterType.OtherNeutral or BidiCharacterType.RightToLeftIsolate or BidiCharacterType.LeftToRightIsolate or BidiCharacterType.FirstStrongIsolate or BidiCharacterType.PopDirectionalIsolate => true, _ => false, }; /// <summary> /// Maps a direction to a strong type for rule N0 /// </summary> /// <param name="dir">The direction to map</param> /// <returns>A strong direction - R, L or ON</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] private BidiCharacterType GetStrongTypeN0(BidiCharacterType dir) => dir switch { BidiCharacterType.EuropeanNumber or BidiCharacterType.ArabicNumber or BidiCharacterType.ArabicLetter or BidiCharacterType.RightToLeft => BidiCharacterType.RightToLeft, BidiCharacterType.LeftToRight => BidiCharacterType.LeftToRight, _ => BidiCharacterType.OtherNeutral, }; /// <summary> /// Hold the start and end index of a pair of brackets /// </summary> private readonly struct BracketPair : IComparable<BracketPair> { /// <summary> /// Initializes a new instance of the <see cref="BracketPair"/> struct. /// </summary> /// <param name="openingIndex">Index of the opening bracket</param> /// <param name="closingIndex">Index of the closing bracket</param> public BracketPair(int openingIndex, int closingIndex) { this.OpeningIndex = openingIndex; this.ClosingIndex = closingIndex; } /// <summary> /// Gets the index of the opening bracket /// </summary> public int OpeningIndex { get; } /// <summary> /// Gets the index of the closing bracket /// </summary> public int ClosingIndex { get; } public int CompareTo(BracketPair other) => this.OpeningIndex.CompareTo(other.OpeningIndex); } /// <summary> /// Status stack entry used while resolving explicit /// embedding levels /// </summary> private readonly struct Status { public Status(sbyte embeddingLevel, BidiCharacterType overrideStatus, bool isolateStatus) { this.EmbeddingLevel = embeddingLevel; this.OverrideStatus = overrideStatus; this.IsolateStatus = isolateStatus; } public sbyte EmbeddingLevel { get; } public BidiCharacterType OverrideStatus { get; } public bool IsolateStatus { get; } } /// <summary> /// Provides information about a level run - a continuous /// sequence of equal levels. /// </summary> private readonly struct LevelRun { public LevelRun(int start, int length, int level, BidiCharacterType sos, BidiCharacterType eos) { this.Start = start; this.Length = length; this.Level = level; this.Sos = sos; this.Eos = eos; } public int Start { get; } public int Length { get; } public int Level { get; } public BidiCharacterType Sos { get; } public BidiCharacterType Eos { get; } } } }
38.28821
181
0.477467
[ "Apache-2.0" ]
Turnerj/Fonts
src/SixLabors.Fonts/Unicode/BidiAlgorithm.cs
61,376
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Net.Quic; using System.Text; using System.Threading.Tasks; using System.Linq; using System.Net.Http.Functional.Tests; namespace System.Net.Test.Common { internal sealed class Http3LoopbackConnection : GenericLoopbackConnection { public const long H3_NO_ERROR = 0x100; public const long H3_GENERAL_PROTOCOL_ERROR = 0x101; public const long H3_INTERNAL_ERROR = 0x102; public const long H3_STREAM_CREATION_ERROR = 0x103; public const long H3_CLOSED_CRITICAL_STREAM = 0x104; public const long H3_FRAME_UNEXPECTED = 0x105; public const long H3_FRAME_ERROR = 0x106; public const long H3_EXCESSIVE_LOAD = 0x107; public const long H3_ID_ERROR = 0x108; public const long H3_SETTINGS_ERROR = 0x109; public const long H3_MISSING_SETTINGS = 0x10a; public const long H3_REQUEST_REJECTED = 0x10b; public const long H3_REQUEST_CANCELLED = 0x10c; public const long H3_REQUEST_INCOMPLETE = 0x10d; public const long H3_CONNECT_ERROR = 0x10f; public const long H3_VERSION_FALLBACK = 0x110; private readonly QuicConnection _connection; private readonly Dictionary<int, Http3LoopbackStream> _openStreams = new Dictionary<int, Http3LoopbackStream>(); private Http3LoopbackStream _controlStream; // Our outbound control stream private Http3LoopbackStream _currentStream; private bool _closed; public Http3LoopbackConnection(QuicConnection connection) { _connection = connection; } public override void Dispose() { foreach (Http3LoopbackStream stream in _openStreams.Values) { stream.Dispose(); } if (!_closed) { // CloseAsync(H3_INTERNAL_ERROR).GetAwaiter().GetResult(); } //_connection.Dispose(); } public async Task CloseAsync(long errorCode) { await _connection.CloseAsync(errorCode).ConfigureAwait(false); _closed = true; } public Http3LoopbackStream OpenUnidirectionalStream() { return new Http3LoopbackStream(_connection.OpenUnidirectionalStream()); } public Http3LoopbackStream OpenBidirectionalStream() { return new Http3LoopbackStream(_connection.OpenBidirectionalStream()); } public static int GetRequestId(QuicStream stream) { Debug.Assert(stream.CanRead && stream.CanWrite, "Stream must be a request stream."); // TODO: QUIC streams can have IDs larger than int.MaxValue; update all our tests to use long rather than int. return checked((int)stream.StreamId + 1); } public Http3LoopbackStream GetOpenRequest(int requestId = 0) { return requestId == 0 ? _currentStream : _openStreams[requestId - 1]; } public override Task InitializeConnectionAsync() { throw new NotImplementedException(); } public async Task<Http3LoopbackStream> AcceptStreamAsync() { QuicStream quicStream = await _connection.AcceptStreamAsync().ConfigureAwait(false); var stream = new Http3LoopbackStream(quicStream); _openStreams.Add(checked((int)quicStream.StreamId), stream); _currentStream = stream; return stream; } public async Task<Http3LoopbackStream> AcceptRequestStreamAsync() { Http3LoopbackStream stream; do { stream = await AcceptStreamAsync().ConfigureAwait(false); } while (!stream.CanWrite); // skip control stream. return stream; } public async Task<(Http3LoopbackStream clientControlStream, Http3LoopbackStream requestStream)> AcceptControlAndRequestStreamAsync() { Http3LoopbackStream streamA = null, streamB = null; try { streamA = await AcceptStreamAsync(); streamB = await AcceptStreamAsync(); return (streamA.CanWrite, streamB.CanWrite) switch { (false, true) => (streamA, streamB), (true, false) => (streamB, streamA), _ => throw new Exception("Expected one unidirectional and one bidirectional stream; received something else.") }; } catch { streamA?.Dispose(); streamB?.Dispose(); throw; } } public async Task EstablishControlStreamAsync() { _controlStream = OpenUnidirectionalStream(); await _controlStream.SendUnidirectionalStreamTypeAsync(Http3LoopbackStream.ControlStream); await _controlStream.SendSettingsFrameAsync(); } public override async Task<byte[]> ReadRequestBodyAsync() { return await _currentStream.ReadRequestBodyAsync().ConfigureAwait(false); } public override async Task<HttpRequestData> ReadRequestDataAsync(bool readBody = true) { Http3LoopbackStream stream = await AcceptRequestStreamAsync().ConfigureAwait(false); return await stream.ReadRequestDataAsync(readBody).ConfigureAwait(false); } public override Task SendResponseAsync(HttpStatusCode statusCode = HttpStatusCode.OK, IList<HttpHeaderData> headers = null, string content = "", bool isFinal = true, int requestId = 0) { return GetOpenRequest(requestId).SendResponseAsync(statusCode, headers, content, isFinal); } public override Task SendResponseBodyAsync(byte[] content, bool isFinal = true, int requestId = 0) { return GetOpenRequest(requestId).SendResponseBodyAsync(content, isFinal); } public override Task SendResponseHeadersAsync(HttpStatusCode statusCode = HttpStatusCode.OK, IList<HttpHeaderData> headers = null, int requestId = 0) { return GetOpenRequest(requestId).SendResponseHeadersAsync(statusCode, headers); } public override Task SendPartialResponseHeadersAsync(HttpStatusCode statusCode = HttpStatusCode.OK, IList<HttpHeaderData> headers = null, int requestId = 0) { return GetOpenRequest(requestId).SendPartialResponseHeadersAsync(statusCode, headers); } public override async Task<HttpRequestData> HandleRequestAsync(HttpStatusCode statusCode = HttpStatusCode.OK, IList<HttpHeaderData> headers = null, string content = "") { Http3LoopbackStream stream = await AcceptRequestStreamAsync().ConfigureAwait(false); HttpRequestData request = await stream.ReadRequestDataAsync().ConfigureAwait(false); // We are about to close the connection, after we send the response. // So, send a GOAWAY frame now so the client won't inadvertantly try to reuse the connection. await _controlStream.SendGoAwayFrameAsync(stream.StreamId + 4); await stream.SendResponseAsync(statusCode, headers, content).ConfigureAwait(false); await WaitForClientDisconnectAsync(); return request; } // Wait for the client to close the connection, e.g. after we send a GOAWAY, or after the HttpClient is disposed. public async Task WaitForClientDisconnectAsync(bool refuseNewRequests = true) { while (true) { Http3LoopbackStream stream; try { stream = await AcceptRequestStreamAsync().ConfigureAwait(false); if (!refuseNewRequests) { throw new Exception("Unexpected request stream received while waiting for client disconnect"); } } catch (QuicConnectionAbortedException abortException) when (abortException.ErrorCode == H3_NO_ERROR) { break; } using (stream) { await stream.AbortAndWaitForShutdownAsync(H3_REQUEST_REJECTED); } } await CloseAsync(H3_NO_ERROR); } public override async Task WaitForCancellationAsync(bool ignoreIncomingData = true, int requestId = 0) { await GetOpenRequest(requestId).WaitForCancellationAsync(ignoreIncomingData).ConfigureAwait(false); } } }
38.15812
192
0.63333
[ "MIT" ]
AerisG222/runtime
src/libraries/Common/tests/System/Net/Http/Http3LoopbackConnection.cs
8,929
C#
namespace DotNext.Generic; /// <summary> /// Represents <see cref="int"/> constant as type. /// </summary> public abstract class Int32Const : Constant<int> { /// <summary> /// Associated <see cref="int"/> value with this type. /// </summary> /// <param name="value">A value to be associated with this type.</param> protected Int32Const(int value) : base(value) { } /// <summary> /// Represents zero value as type. /// </summary> public sealed class Zero : Int32Const { /// <summary> /// Represents constant value. /// </summary> public new const int Value = 0; /// <summary> /// Initializes a new constant value. /// </summary> public Zero() : base(Value) { } } /// <summary> /// Represents max integer value as type. /// </summary> public sealed class Max : Int32Const { /// <summary> /// Represents constant value. /// </summary> public new const int Value = int.MaxValue; /// <summary> /// Initializes a new constant value. /// </summary> public Max() : base(Value) { } } /// <summary> /// Represents min integer value as type. /// </summary> public sealed class Min : Int32Const { /// <summary> /// Represents constant value. /// </summary> public new const int Value = int.MinValue; /// <summary> /// Initializes a new constant value. /// </summary> public Min() : base(Value) { } } }
23.013699
76
0.505952
[ "MIT" ]
copenhagenatomics/dotNext
src/DotNext/Generic/Int32Const.cs
1,680
C#
using System; using YARC.Messages.Bus; namespace YARC.Messages.ExtApi { [Serializable] public class ExtApiDataRequest : IMessage, ICanValidate { public string RequestId { get; set; } public string ProviderName { get; set; } public string ObjectName { get; set; } public string Action { get; set; } public string Id { get; set; } public string Params { get; set; } public string RequestOrigin { get; set; } public string AuthToken { get; set; } public bool Validate() { return RequestId.NotNullOrEmpty() && ProviderName.NotNullOrEmpty() && ObjectName.NotNullOrEmpty() && Action.NotNullOrEmpty(); } } }
27.464286
59
0.579974
[ "MIT" ]
steelden/yet-another-rabbitmq-client
src/YARC.Messages/ExtApi/ExtApiDataRequest.cs
771
C#
#region License // Jdenticon-net // https://github.com/dmester/jdenticon-net // Copyright © Daniel Mester Pirttijärvi 2016 // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #endregion using Jdenticon.Gdi.Extensions; using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Text; using System.Threading; namespace Jdenticon.Rendering { /// <summary> /// Renders icons to a GDI+ <see cref="Graphics"/> drawing context. /// </summary> public class GdiRenderer : Renderer { private GraphicsPath path; private Graphics graphics; /// <summary> /// Creates an instance of the class <see cref="GdiRenderer"/>. /// </summary> /// <param name="graphics">GDI+ drawing context to which the icon will be rendered.</param> public GdiRenderer(Graphics graphics) { this.graphics = graphics; } /// <inheritdoc /> protected override void AddCircleNoTransform(PointF location, float diameter, bool counterClockwise) { var rect = new RectangleF(location.ToGdi(), new SizeF(diameter, diameter)); var angle = counterClockwise ? -360f : 360f; path.AddArc(rect, 0, angle); path.CloseFigure(); } /// <inheritdoc /> protected override void AddPolygonNoTransform(PointF[] points) { path.AddPolygon(points.ToGdi()); } /// <inheritdoc /> public override void SetBackground(Color color) { graphics.Clear(color.ToGdi()); } /// <inheritdoc /> public override IDisposable BeginShape(Color color) { var localPath = new GraphicsPath(FillMode.Alternate); this.path = localPath; return new ActionDisposable(() => { Interlocked.CompareExchange(ref this.path, null, localPath); var state = graphics.Save(); try { graphics.SmoothingMode = SmoothingMode.AntiAlias; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; using (var brush = new SolidBrush(color.ToGdi())) { graphics.FillPath(brush, localPath); } } finally { graphics.Restore(state); localPath.Dispose(); } }); } } }
34.590476
108
0.615088
[ "MIT" ]
topikon-de/jdenticon-net
Extensions/Jdenticon.Gdi/Rendering/GdiRenderer.cs
3,636
C#
using CQELight; using CQELight.Dispatcher; using CQELight.IoC; using CQELight.EventStore.EFCore.Common; using Geneao.Commands; using Geneao.Data; using Geneao.Queries; using Microsoft.EntityFrameworkCore; using System; using System.IO; using System.Threading.Tasks; using CQELight.Abstractions.DDD; using Geneao.Domain; using System.Linq; using Geneao.Identity; using System.Globalization; namespace Geneao { class Program { static async Task Main(string[] args) { Console.WriteLine("Bienvenue dans la gestion de votre arbre généalogique"); if (!File.Exists("./familles.json")) { File.WriteAllText("./familles.json", "[]"); } new Bootstrapper() .UseInMemoryEventBus() .UseInMemoryCommandBus() .UseAutofacAsIoC(c => { }) .UseEFCoreAsEventStore( new CQELight.EventStore.EFCore.EFEventStoreOptions( c => c.UseSqlite("FileName=events.db", opts => opts.MigrationsAssembly(typeof(Program).Assembly.GetName().Name)), archiveBehavior: CQELight.EventStore.SnapshotEventsArchiveBehavior.Delete)) .Bootstrapp(); await DisplayMainMenuAsync(); } private static async Task DisplayMainMenuAsync() { while (true) { try { Console.WriteLine("Choisissez votre commande"); Console.WriteLine("1. Lister les familles du logiciel"); Console.WriteLine("2. Créer une nouvelle famille"); Console.WriteLine("3. Ajouter une personne à une famille"); Console.WriteLine("Ou tapez q pour quitter"); Console.WriteLine(); var result = Console.ReadLine().Trim(); Console.WriteLine(); switch (result) { case "1": await ListerFamillesAsync(); break; case "2": await CreerFamilleAsync(); break; case "3": await AjouterPersonneAsync(); break; case "q": Environment.Exit(0); break; default: Console.WriteLine("Choix incorrect, merci de faire un choix dans la liste"); break; } } catch (Exception e) { var color = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine("Aie, pas bien, ça a planté ... :("); Console.WriteLine(e.ToString()); Console.ForegroundColor = color; } } } private static async Task AjouterPersonneAsync() { Console.WriteLine("Veuillez saisir la famille concernée"); var familleConcernee = Console.ReadLine(); using (var scope = DIManager.BeginScope()) { var query = scope.Resolve<IRecupererListeFamille>(); var famille = (await query.ExecuteQueryAsync()).FirstOrDefault(f => f.Nom == familleConcernee); if(famille != null) { await CreerPersonneAsync(familleConcernee); } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"La famille {familleConcernee} n'existe pas dans le système. Voulez-vous la créer ? (y/n)"); Console.ResetColor(); var response = Console.ReadLine(); if(response.Trim().Equals("y", StringComparison.OrdinalIgnoreCase)) { await CreerFamilleCommandAsync(familleConcernee); } } } } private static async Task CreerPersonneAsync(NomFamille nomFamille) { Console.WriteLine("Veuillez entrer le nom de la personne à créer"); var prenom = Console.ReadLine(); Console.WriteLine("Veuillez entrer le lieu de naissance de la personne à créer"); var lieu = Console.ReadLine(); Console.WriteLine("Veuillez entrer la date de naissance (dd/MM/yyyy)"); DateTime date = DateTime.MinValue; DateTime.TryParseExact(Console.ReadLine(), "dd/MM/yyyy", CultureInfo.GetCultureInfo("fr-FR"), DateTimeStyles.None, out date); if(!string.IsNullOrWhiteSpace(prenom) && !string.IsNullOrWhiteSpace(lieu) && date != DateTime.MinValue) { var result = await CoreDispatcher.DispatchCommandAsync( new AjouterPersonneCommand(nomFamille, prenom, lieu, date)); if(!result) { Console.ForegroundColor = ConsoleColor.Red; var message = $"La personne n'a pas pu être ajoutée à la famille {nomFamille.Value}"; if(result is Result<PersonneNonAjouteeCar> resultRaison) { switch(resultRaison.Value) { case PersonneNonAjouteeCar.InformationsDeNaissanceInvalides: message += " car les informations de naissance sont invalides"; break; case PersonneNonAjouteeCar.PersonneExistante: message += " car cette personne existe déjà dans cette famille"; break; case PersonneNonAjouteeCar.PrenomInvalide: message += " car son prénom n'est pas reconnu valide"; break; } } Console.WriteLine(message); } } } private static async Task ListerFamillesAsync() { using (var scope = DIManager.BeginScope()) { var query = scope.Resolve<IRecupererListeFamille>(); var familles = await query.ExecuteQueryAsync(); Console.WriteLine("---- Liste des familles du système ----"); foreach (var item in familles) { Console.WriteLine(item.Nom); } Console.WriteLine(); } } private static async Task CreerFamilleAsync() { string familleName = string.Empty; do { Console.WriteLine("Choisissez un nom de famille pour la créer"); familleName = Console.ReadLine(); } while (string.IsNullOrWhiteSpace(familleName)); await CreerFamilleCommandAsync(familleName); } private static async Task CreerFamilleCommandAsync(string familleName) { var result = await CoreDispatcher.DispatchCommandAsync(new CreerFamilleCommand(familleName)); if (!result) { var color = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.DarkRed; string raisonText = string.Empty; if (result is Result<FamilleNonCreeeCar> resultErreurFamille) { raisonText = resultErreurFamille.Value == FamilleNonCreeeCar.FamilleDejaExistante ? "cette famille existe déjà." : "le nom de la famille est incorrect."; } if (!string.IsNullOrWhiteSpace(raisonText)) { Console.WriteLine($"La famille {familleName} n'a pas pu être créée car {raisonText}"); } Console.ForegroundColor = color; } } } }
40.394231
137
0.50238
[ "MIT" ]
Thanouz/CQELight
samples/documentation/2.Geneao/Geneao/Program.cs
8,430
C#
using LanguageExtensions.AspNetCore.Middlewares.CorrelationId; using LanguageExtensions.Correlation; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using System; namespace Microsoft.AspNetCore.Builder { public static class CorrelationIdServiceExtensions { public static IServiceCollection AddCorrelationContext(this IServiceCollection serviceCollection) { serviceCollection.TryAddSingleton<ICorrelationContextAccessor, CorrelationContextAccessor>(); serviceCollection.AddTransient(s => s.GetService<ICorrelationContextAccessor>().CorrelationContext); return serviceCollection; } public static IApplicationBuilder UseCorrelationId(this IApplicationBuilder app) { if (app.ApplicationServices.GetService(typeof(ICorrelationContextAccessor)) == null) { throw new InvalidOperationException("Unable to find the required services. You must call the AddCorrelationId method in ConfigureServices in the application startup code."); } return app.UseMiddleware<CorrelationIdMiddleware>(); } } }
41.655172
189
0.744205
[ "MIT" ]
LanguageExtensions/LanguageExtensions
src/AspNetCore/LanguageExtensions.AspNetCore/Middlewares/CorrelationId/CorrelationIdServiceExtensions.cs
1,210
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Interpidians.Catalyst.Core.Entity; namespace Interpidians.Catalyst.Core.DomainService { public interface IStateMasterRepository { IEnumerable<StateMaster> GetAll(); StateMaster GetById(IdentifiableData id); void Add(StateMaster StateMaster); void Update(StateMaster StateMaster); void Delete(IdentifiableData id); } }
25.666667
50
0.738095
[ "MIT" ]
prashantkakde31/Catalyst
app/SRC/Interpidians.Catalyst/Interpidians.Catalyst.Core/DomainService/IStateMasterRepository.cs
464
C#
// CS0432: Alias `Sa' not found // Line: 6 using S = System; [assembly: Sa::CLSCompliantAttribute (false)]
15.571429
45
0.678899
[ "Apache-2.0" ]
121468615/mono
mcs/errors/cs0432-3.cs
109
C#
namespace MassTransit.Transports { using System; using System.Threading; using System.Threading.Tasks; using Context; using Initializers; /// <summary> /// Generalized proxy for ISendEndpoint to intercept pipe/context /// </summary> public abstract class SendEndpointProxy : ISendEndpoint { readonly ISendEndpoint _endpoint; protected SendEndpointProxy(ISendEndpoint endpoint) { _endpoint = endpoint; } public ISendEndpoint Endpoint => _endpoint; public ConnectHandle ConnectSendObserver(ISendObserver observer) { return _endpoint.ConnectSendObserver(observer); } public virtual Task Send<T>(T message, CancellationToken cancellationToken) where T : class { if (message == null) throw new ArgumentNullException(nameof(message)); return _endpoint.Send(message, GetPipeProxy<T>(), cancellationToken); } public virtual Task Send<T>(T message, IPipe<SendContext<T>> pipe, CancellationToken cancellationToken) where T : class { if (message == null) throw new ArgumentNullException(nameof(message)); if (pipe == null) throw new ArgumentNullException(nameof(pipe)); return _endpoint.Send(message, GetPipeProxy(pipe), cancellationToken); } public virtual Task Send<T>(T message, IPipe<SendContext> pipe, CancellationToken cancellationToken) where T : class { if (message == null) throw new ArgumentNullException(nameof(message)); if (pipe == null) throw new ArgumentNullException(nameof(pipe)); return _endpoint.Send(message, GetPipeProxy<T>(pipe), cancellationToken); } public Task Send(object message, CancellationToken cancellationToken) { if (message == null) throw new ArgumentNullException(nameof(message)); var messageType = message.GetType(); return SendEndpointConverterCache.Send(this, message, messageType, cancellationToken); } public Task Send(object message, Type messageType, CancellationToken cancellationToken) { if (message == null) throw new ArgumentNullException(nameof(message)); if (messageType == null) throw new ArgumentNullException(nameof(messageType)); return SendEndpointConverterCache.Send(this, message, messageType, cancellationToken); } public Task Send(object message, IPipe<SendContext> pipe, CancellationToken cancellationToken) { if (message == null) throw new ArgumentNullException(nameof(message)); if (pipe == null) throw new ArgumentNullException(nameof(pipe)); var messageType = message.GetType(); return SendEndpointConverterCache.Send(this, message, messageType, pipe, cancellationToken); } public Task Send(object message, Type messageType, IPipe<SendContext> pipe, CancellationToken cancellationToken) { if (message == null) throw new ArgumentNullException(nameof(message)); if (messageType == null) throw new ArgumentNullException(nameof(messageType)); if (pipe == null) throw new ArgumentNullException(nameof(pipe)); return SendEndpointConverterCache.Send(this, message, messageType, pipe, cancellationToken); } public async Task Send<T>(object values, CancellationToken cancellationToken) where T : class { if (values == null) throw new ArgumentNullException(nameof(values)); (var message, IPipe<SendContext<T>> sendPipe) = await MessageInitializerCache<T>.InitializeMessage(values, GetPipeProxy<T>(), cancellationToken).ConfigureAwait(false); await _endpoint.Send(message, sendPipe, cancellationToken).ConfigureAwait(false); } public async Task Send<T>(object values, IPipe<SendContext<T>> pipe, CancellationToken cancellationToken) where T : class { if (values == null) throw new ArgumentNullException(nameof(values)); if (pipe == null) throw new ArgumentNullException(nameof(pipe)); (var message, IPipe<SendContext<T>> sendPipe) = await MessageInitializerCache<T>.InitializeMessage(values, GetPipeProxy<T>(pipe), cancellationToken).ConfigureAwait(false); await _endpoint.Send(message, sendPipe, cancellationToken).ConfigureAwait(false); } public async Task Send<T>(object values, IPipe<SendContext> pipe, CancellationToken cancellationToken) where T : class { if (values == null) throw new ArgumentNullException(nameof(values)); if (pipe == null) throw new ArgumentNullException(nameof(pipe)); (var message, IPipe<SendContext<T>> sendPipe) = await MessageInitializerCache<T>.InitializeMessage(values, GetPipeProxy<T>(pipe), cancellationToken).ConfigureAwait(false); await _endpoint.Send(message, sendPipe, cancellationToken).ConfigureAwait(false); } protected abstract IPipe<SendContext<T>> GetPipeProxy<T>(IPipe<SendContext<T>> pipe = default) where T : class; } }
37.390728
139
0.62469
[ "ECL-2.0", "Apache-2.0" ]
AlexanderMeier/MassTransit
src/MassTransit/Transports/SendEndpointProxy.cs
5,646
C#
using System; namespace RangHo.DialogueScript { public class InvalidCharacterException : Exception { public InvalidCharacterException() { } public InvalidCharacterException(string message) : base(message) { } public InvalidCharacterException(string message, Exception innerException) : base(message, innerException) { } } public class UnexpectedTokenException : Exception { public UnexpectedTokenException() { } public UnexpectedTokenException(string message) : base(message) { } public UnexpectedTokenException(string message, Exception innerException) : base(message, innerException) { } } public class UnexpectedStatementException : Exception { public UnexpectedStatementException() { } public UnexpectedStatementException(string message) : base(message) { } public UnexpectedStatementException(string message, Exception innerException) : base(message, innerException) { } } public class InvalidStatementPassedException : Exception { public InvalidStatementPassedException() { } public InvalidStatementPassedException(string message) : base(message) { } public InvalidStatementPassedException(string message, Exception innerException) : base(message, innerException) { } } public class PropertyNotExistException : Exception { public PropertyNotExistException() { } public PropertyNotExistException(string message) : base(message) { } public PropertyNotExistException(string message, Exception innerException) : base(message, innerException) { } } public class LabelNotFoundException : Exception { public LabelNotFoundException() { } public LabelNotFoundException(string message) : base(message) { } public LabelNotFoundException(string message, Exception innerException) : base(message, innerException) { } } }
33.948276
121
0.710005
[ "MIT" ]
RangHo/DialogueScript
DialogueScriptLibrary/Exception.cs
1,969
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace TetrisApiServer { public class Program { public static void Main(string[] args) { APIServer.Init(args); BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseKestrel() .UseIISIntegration() .UseStartup<Startup>() .UseUrls("http://*:19000/") .Build(); } }
23.382353
62
0.581132
[ "MIT" ]
jacking75/examples_unity_network
Server/PvPTetris_APIServer/Program.cs
797
C#
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework.Graphics; using P3D.Legacy.MapEditor.Data.Models; using P3D.Legacy.MapEditor.Utils; using P3D.Legacy.MapEditor.World; namespace P3D.Legacy.MapEditor.Renders { public class LevelRenderer : IDisposable { protected BaseModelListRenderer StaticRenderer; protected BaseModelListRenderer DynamicRenderer; public void HandleModels(List<BaseModel> models) { bool isStatic(BaseModel model) { if (model is BillModel) return false; return true; } bool isDynamic(BaseModel model) { return !isStatic(model); } StaticRenderer = new StaticModelListRenderer(); StaticRenderer.AddModels(models.Where(isStatic).ToList()); DynamicRenderer = new DynamicModelListRenderer(); DynamicRenderer.AddModels(models.Where(isDynamic).ToList()); } public void Setup(GraphicsDevice graphicsDevice) { StaticRenderer.Setup(graphicsDevice); DynamicRenderer.Setup(graphicsDevice); } public void Draw(Level level, BasicEffect basicEffect, AlphaTestEffect alphaTestEffect) { StaticRenderer.Draw(level, basicEffect, alphaTestEffect); DynamicRenderer.Draw(level, basicEffect, alphaTestEffect); } public void Dispose() { TextureHandler.Dispose(); } } }
28.410714
95
0.622879
[ "MIT" ]
P3D-Legacy/P3D-Legacy-MapEditor
P3D-Legacy-MapEditor/Renders/LevelRenderer.cs
1,593
C#
using CommonLib.Models; using System; using System.ComponentModel.DataAnnotations.Schema; namespace NNMR.Models.DBModels { [Table("UserProgress")] public class UserProgressDB : IBaseDBModel { public int Id { get; set; } public int UserId { get; set; } public int ChapterId { get; set; } public DateTime Created { get; set; } public DateTime Updated { get; set; } } }
23.666667
51
0.643192
[ "MIT" ]
MoreManga/RESTAPI
NNMR.Model/DBModels/UserProgressDB.cs
428
C#
using System; using System.Linq; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using NetModular.Lib.Module.Abstractions; using NetModular.Lib.Utils.Core; namespace NetModular.Lib.Module.AspNetCore { public static class ServiceCollectionExtensions { /// <summary> /// 添加模块 /// </summary> /// <param name="services"></param> /// <returns></returns> public static IModuleCollection AddModules(this IServiceCollection services) { var modules = new ModuleCollection(); modules.Load(); services.AddSingleton<IModuleCollection>(modules); foreach (var module in modules) { if (module == null) continue; services.AddApplicationServices(module); services.AddSingleton(module); } return modules; } /// <summary> /// 添加模块的自定义服务 /// </summary> /// <param name="services"></param> /// <param name="modules"></param> /// <param name="env"></param> /// <returns></returns> public static IServiceCollection AddModuleServices(this IServiceCollection services, IModuleCollection modules, IHostEnvironment env) { foreach (var module in modules) { //加载模块初始化器 ((ModuleDescriptor)module).ServicesConfigurator?.Configure(services, modules, env); } return services; } /// <summary> /// 添加模块初始化服务 /// </summary> /// <param name="services"></param> /// <param name="modules"></param> /// <param name="env"></param> /// <returns></returns> public static IServiceCollection AddModuleInitializerServices(this IServiceCollection services, IModuleCollection modules, IHostEnvironment env) { foreach (var module in modules) { //加载模块初始化器 ((ModuleDescriptor)module).Initializer?.ConfigureServices(services, modules, env); } return services; } /// <summary> /// 添加应用服务 /// </summary> private static void AddApplicationServices(this IServiceCollection services, IModuleDescriptor module) { if (module.AssemblyDescriptor == null) return; var types = module.AssemblyDescriptor.Application.GetTypes(); var interfaces = types.Where(t => t.FullName != null && t.IsInterface && t.FullName.EndsWith("Service", StringComparison.OrdinalIgnoreCase)); foreach (var serviceType in interfaces) { var implementationType = types.FirstOrDefault(m => m != serviceType && serviceType.IsAssignableFrom(m)); if (implementationType != null) { services.Add(new ServiceDescriptor(serviceType, implementationType, ServiceLifetime.Singleton)); } } } /// <summary> /// 自动注入单例服务 /// </summary> /// <param name="services"></param> /// <param name="module"></param> private static void AddSingleton(this IServiceCollection services, IModuleDescriptor module) { if (module.AssemblyDescriptor != null && module.AssemblyDescriptor is ModuleAssemblyDescriptor descriptor) { services.AddSingletonFromAssembly(descriptor.Domain); services.AddSingletonFromAssembly(descriptor.Infrastructure); services.AddSingletonFromAssembly(descriptor.Application); services.AddSingletonFromAssembly(descriptor.Web); services.AddSingletonFromAssembly(descriptor.Api); } } } }
34.732143
153
0.58072
[ "MIT" ]
sunlibo111111/NetModular
src/Framework/Module/Module.AspNetCore/ServiceCollectionExtensions.cs
3,998
C#
using JT809.Protocol.Extensions; using JT809.Protocol.Enums; using JT809.Protocol.SubMessageBody; using System; using System.Buffers; using System.Collections.Generic; using System.Text; namespace JT809.Protocol.Formatters.SubMessageBodyFormatters { public class JT809_0x9500_0x9504_Formatter : IJT809Formatter<JT809_0x9500_0x9504> { public JT809_0x9500_0x9504 Deserialize(ReadOnlySpan<byte> bytes, out int readSize) { int offset = 0; JT809_0x9500_0x9504 jT809_0X9500_0X9504 = new JT809_0x9500_0x9504(); jT809_0X9500_0X9504.Command = (JT809CommandType) JT809BinaryExtensions.ReadByteLittle(bytes, ref offset); switch (jT809_0X9500_0X9504.Command) { case JT809CommandType.记录仪标准版本: case JT809CommandType.当前驾驶人信息: case JT809CommandType.记录仪时间: case JT809CommandType.记录仪累计行驶里程: case JT809CommandType.记录仪脉冲系数: case JT809CommandType.车辆信息: case JT809CommandType.记录仪状态信号配置信息: case JT809CommandType.记录仪唯一性编号: break; case JT809CommandType.采集记录仪行驶记录: case JT809CommandType.采集记录仪位置信息记录: case JT809CommandType.采集记录仪事故疑点记录: case JT809CommandType.采集记录仪超时驾驶记录: case JT809CommandType.采集记录仪驾驶人身份记录: case JT809CommandType.采集记录仪外部供电记录: case JT809CommandType.采集记录仪参数修改记录: case JT809CommandType.采集记录仪速度状态日志: jT809_0X9500_0X9504.StartTime = JT809BinaryExtensions.ReadDateTime6Little(bytes, ref offset); jT809_0X9500_0X9504.EndTime = JT809BinaryExtensions.ReadDateTime6Little(bytes, ref offset); jT809_0X9500_0X9504.Max = JT809BinaryExtensions.ReadUInt16Little(bytes, ref offset); break; } readSize = offset; return jT809_0X9500_0X9504; } public int Serialize(ref byte[] bytes, int offset, JT809_0x9500_0x9504 value) { offset += JT809BinaryExtensions.WriteByteLittle(bytes, offset, (byte)value.Command); switch (value.Command) { case JT809CommandType.记录仪标准版本: case JT809CommandType.当前驾驶人信息: case JT809CommandType.记录仪时间: case JT809CommandType.记录仪累计行驶里程: case JT809CommandType.记录仪脉冲系数: case JT809CommandType.车辆信息: case JT809CommandType.记录仪状态信号配置信息: case JT809CommandType.记录仪唯一性编号: break; case JT809CommandType.采集记录仪行驶记录: case JT809CommandType.采集记录仪位置信息记录: case JT809CommandType.采集记录仪事故疑点记录: case JT809CommandType.采集记录仪超时驾驶记录: case JT809CommandType.采集记录仪驾驶人身份记录: case JT809CommandType.采集记录仪外部供电记录: case JT809CommandType.采集记录仪参数修改记录: case JT809CommandType.采集记录仪速度状态日志: offset += JT809BinaryExtensions.WriteDateTime6Little(bytes, offset, value.StartTime); offset += JT809BinaryExtensions.WriteDateTime6Little(bytes, offset, value.EndTime); offset += JT809BinaryExtensions.WriteUInt16Little(bytes, offset, value.Max); break; } return offset; } } }
44.831169
117
0.62022
[ "MIT" ]
maodaxiong/JT809
src/JT809.Protocol/Formatters/SubMessageBodyFormatters/JT809_0x9500_0x9504_Formatter.cs
4,034
C#
using LifeCycleDevEnvironmentConsole.Settings; using LifeCycleDevEnvironmentConsole.Settings.OperationSettings; using LifeCycleDevEnvironmentConsole.Utilities; using Microsoft.Office.Interop.Excel; using ProcessManagement; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace LifeCycleDevEnvironmentConsole.BannerOperations { public sealed class O5Operations : BannerOperationBase { private BannerSettings _o5Settings; private BaseOperationSettings _o5WorksheetSettings; private Microsoft.Office.Interop.Excel.Application excelApp; private Workbook wipWb; private Workbook finalWb; //Wip worksheets private Worksheet reportWsWip; private Worksheet inactiveWsWip; private Worksheet detailsProductWsWip; private Worksheet detailsProductDataWsWip; private Worksheet inventoryValueWsWip; //Final worksheets private Worksheet reportWsFinal; private Worksheet inactiveWsFinal; private Worksheet detailsProductWsFinal; public O5Operations(BannerSettings settings) : base(settings) { _o5Settings = settings; _o5WorksheetSettings = (BaseOperationSettings)settings.WorksheetSettings; } public void RunOperation() { System.Data.DataTable inputDataTable = new System.Data.DataTable(); System.Data.DataTable templateDataTable = new System.Data.DataTable(); excelApp = new Application(); ExcelProcessControl excelProcess = new ExcelProcessControl(excelApp); WipWbInitialization(); FinalWbInitialization(); excelApp.Calculation = XlCalculation.xlCalculationManual; excelApp.Visible = false; try { //SummaryChart string dateAddress = _o5WorksheetSettings.SummarySettings.ReportSettings.DateAddress; reportWsWip.Range[dateAddress].Value = _o5Settings.OutputDate.ToOADate(); WipBitReportOp(); WipInactiveUpcOp(); WipWorkflowOp(); O5SpeicalRule1(detailsProductWsWip, _o5WorksheetSettings.WorkflowSettings.WipSettings.HeaderRow); excelApp.Calculate(); WipWbFormatAsValuesOnly(true); wipWb.Save(); CopyToFinalWb(); } catch (Exception ex) { //TODO handle exception Console.WriteLine(ex.ToString()); } finally { excelApp.DisplayAlerts = false; excelApp.Calculation = XlCalculation.xlCalculationAutomatic; wipWb.Save(); finalWb.Save(); wipWb.Close(); finalWb.Close(); excelApp.Quit(); Marshal.ReleaseComObject(wipWb); Marshal.ReleaseComObject(finalWb); Marshal.ReleaseComObject(excelApp); excelProcess.Dispose(); } } //TODO O5 change reading size private void O5SpeicalRule1(Worksheet ws, int headerRow) { Range furAttributeRange = ws.FindColumnInHeaderRow<string>("Active_PIM", headerRow); System.Data.DataTable dt = new System.Data.DataTable(); if (furAttributeRange.Cells.Count > 1) { string writeToAddress = furAttributeRange.Cells[2, 1].Address; //cell under rework column name dt = ExcelUtilities.ReadWorksheetRangeAsTable(ws, furAttributeRange.Resize[ColumnSize: 43].Address); var rowToUpdate = dt.AsEnumerable() .Where(r => r.Field<string>("Active_PIM") == "Yes" && r.Field<string>("ReadyforProd_PIM") == "Yes" && r.Field<string>("Current_Workflow_Status") == "Not in PIM Workflow" || r.Field<string>("Current_Workflow_Status") == "Workflow Complete" ); foreach (System.Data.DataRow row in rowToUpdate) { row.SetField<string>(dt.Columns["Current_Workflow_Status"], "Not Flagged for eCOM"); row.SetField<string>(dt.Columns["Current Team"], "Merchants"); } dt.WriteToExcelSheets(ws, writeToAddress, false); } } private void WipWbInitialization() { try { wipWb = excelApp.Workbooks.Open(_o5Settings.OutputFileFullnameWip); } catch (Exception ex) { //TODO Error Workbook failed to open. Console.WriteLine("Workbook open failed."); } try { reportWsWip = wipWb.Worksheets[_o5WorksheetSettings.SummarySettings.ReportSettings.WorksheetName]; inactiveWsWip = wipWb.Worksheets[_o5WorksheetSettings.InactiveUpcSettings.WipSettings.WorksheetName]; detailsProductWsWip = wipWb.Worksheets[_o5WorksheetSettings.WorkflowSettings.WipSettings.WorksheetName]; detailsProductDataWsWip = wipWb.Worksheets[_o5WorksheetSettings.WorkflowSettings.DataSourceSettings.WorksheetName]; inventoryValueWsWip = wipWb.Worksheets[_o5WorksheetSettings.BitreportSettings.WipSettings.WorksheetName]; } catch (Exception ex) { //TODO Error worksheet name not found Console.WriteLine("Worksheet within workbook not found."); } } private void FinalWbInitialization() { try { finalWb = excelApp.Workbooks.Open(_o5Settings.OutputFileFullnameFinal); } catch (Exception ex) { //TODO Error Workbook failed to open. Console.WriteLine("Workbook open failed."); } try { reportWsFinal = finalWb.Worksheets[_o5WorksheetSettings.SummarySettings.FinalSettings.WorksheetName]; inactiveWsFinal = finalWb.Worksheets[_o5WorksheetSettings.InactiveUpcSettings.FinalSettings.WorksheetName]; detailsProductWsFinal = finalWb.Worksheets[_o5WorksheetSettings.WorkflowSettings.FinalSettings.WorksheetName]; } catch (Exception ex) { //TODO Error worksheet name not found Console.WriteLine("Worksheet within workbook not found."); } } /// <summary> /// Make the wip workbook values only at the end. If this is not turned on, final workbook will have external links to the wip workbook. /// </summary> private void WipWbFormatAsValuesOnly(bool valuesOnlyOn) { if (valuesOnlyOn) { inactiveWsWip.ConvertAllDataUnderRowToValues(_o5WorksheetSettings.InactiveUpcSettings.WipSettings.HeaderRow); detailsProductWsWip.ConvertAllDataUnderRowToValues(_o5WorksheetSettings.WorkflowSettings.WipSettings.HeaderRow); //Turn summary chart into values string readingAddress = _o5WorksheetSettings.SummarySettings.ReportSettings.ReadingAddress; reportWsWip.Range[readingAddress].Value2 = reportWsWip.Range[readingAddress].Value2; } } //===================================================WIP OPERATIONS====================================================== #region O5Wip private void WipBitReportOp() { System.Data.DataTable inputDataTable = new System.Data.DataTable(); System.Data.DataTable templateDataTable = new System.Data.DataTable(); //Bit report BitReportHandler bitReport = new BitReportHandler(_o5Settings.InputFilenameBitReport); templateDataTable = ExcelUtilities.ReadExcelDataFileAsTable(_o5Settings.OutputFileFullnameWip, inventoryValueWsWip.Name); inputDataTable = bitReport.JoinWithDataTable(templateDataTable); string writingAddress = string.Format("A{0}", _o5WorksheetSettings.BitreportSettings.WipSettings.WritingRow); inputDataTable.WriteToExcelSheets(inventoryValueWsWip, writingAddress); CommonOperations.FormatColumnsAsAccounting(inventoryValueWsWip, "OH $ @R"); } private void WipInactiveUpcOp() { System.Data.DataTable inputDataTable = new System.Data.DataTable(); //Inactive UPC inputDataTable = ExcelUtilities.ReadExcelDataFileAsTable(_o5Settings.InputFilenameInactiveUpc, 1); string writingAddress = string.Format("A{0}", _o5WorksheetSettings.InactiveUpcSettings.WipSettings.WritingRow); inputDataTable.WriteToExcelSheets(inactiveWsWip, writingAddress, false); inactiveWsWip.ProcessFormulaRow( refTable: inputDataTable, formulaRow: _o5WorksheetSettings.InactiveUpcSettings.WipSettings.FormulaRow, headerRow: _o5WorksheetSettings.InactiveUpcSettings.WipSettings.ReferenceRow, outputRow: _o5WorksheetSettings.InactiveUpcSettings.WipSettings.WritingRow); } private void WipWorkflowOp() { System.Data.DataTable inputDataTable = new System.Data.DataTable(); //Workflow DM inputDataTable = ExcelUtilities.ReadExcelDataFileAsTable(_o5Settings.InputFilenameWorkflow, 1); string writingAddress = string.Format("A{0}", _o5WorksheetSettings.WorkflowSettings.DataSourceSettings.WritingRow); inputDataTable.WriteToExcelSheets(detailsProductDataWsWip, writingAddress, true); detailsProductWsWip.ProcessFormulaRow( refTable: inputDataTable, formulaRow: _o5WorksheetSettings.WorkflowSettings.WipSettings.FormulaRow, headerRow: _o5WorksheetSettings.WorkflowSettings.WipSettings.ReferenceRow, outputRow: _o5WorksheetSettings.WorkflowSettings.WipSettings.WritingRow); detailsProductWsWip.Calculate(); CommonOperations.ReworkFurRule(detailsProductWsWip, _o5WorksheetSettings.WorkflowSettings.WipSettings.HeaderRow); } #endregion //===================================================Final OPERATIONS==================================================== #region O5Final private void CopyToFinalWb() { //Temp variables string writingAddress; //excel writing address for datatables and final workbook string readingAddress; //excel reading address to aquire data areas int colCount; //temporary count for resizing purposes int rowCount; finalWb.Activate(); //Summary Chart readingAddress = _o5WorksheetSettings.SummarySettings.ReportSettings.ReadingAddress; writingAddress = _o5WorksheetSettings.SummarySettings.FinalSettings.WritingAddress; rowCount = reportWsWip.Range[readingAddress].Rows.Count; colCount = reportWsWip.Range[readingAddress].Columns.Count; reportWsWip.Range[readingAddress].Copy(reportWsFinal.Range[writingAddress].Resize[rowCount, colCount]); //Details Product readingAddress = detailsProductWsWip.ConvertColumnAddressToPreciseAddress( _o5WorksheetSettings.WorkflowSettings.WipSettings.ReadingAddress, _o5WorksheetSettings.WorkflowSettings.WipSettings.WritingRow); writingAddress = _o5WorksheetSettings.WorkflowSettings.FinalSettings.WritingAddress; rowCount = detailsProductWsWip.Range[readingAddress].Rows.Count; colCount = detailsProductWsWip.Range[readingAddress].Columns.Count; detailsProductWsFinal.Range[writingAddress].Resize[rowCount, colCount].Value = detailsProductWsWip.Range[readingAddress].Value; //Inactive Upc readingAddress = inactiveWsWip.ConvertColumnAddressToPreciseAddress( _o5WorksheetSettings.InactiveUpcSettings.WipSettings.ReadingAddress, _o5WorksheetSettings.InactiveUpcSettings.WipSettings.WritingRow); writingAddress = _o5WorksheetSettings.InactiveUpcSettings.FinalSettings.WritingAddress; rowCount = inactiveWsWip.Range[readingAddress].Rows.Count; colCount = inactiveWsWip.Range[readingAddress].Columns.Count; inactiveWsFinal.Range[writingAddress].Resize[rowCount, colCount].Value = inactiveWsWip.Range[readingAddress].Value; } #endregion } }
44.49827
167
0.641213
[ "MIT", "Unlicense" ]
alwaysmiddle/LifeCycleWorkflowTool
LifeCycleDevEnvironmentConsole/BannerOperations/O5Operations.cs
12,862
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using ClearHl7.Extensions; using ClearHl7.Helpers; namespace ClearHl7.V290.Segments { /// <summary> /// HL7 Version 2 Segment BTS - Batch Trailer. /// </summary> public class BtsSegment : ISegment { /// <summary> /// Gets the ID for the Segment. This property is read-only. /// </summary> public string Id { get; } = "BTS"; /// <summary> /// Gets or sets the rank, or ordinal, which describes the place that this Segment resides in an ordered list of Segments. /// </summary> public int Ordinal { get; set; } /// <summary> /// BTS.1 - Batch Message Count. /// </summary> public string BatchMessageCount { get; set; } /// <summary> /// BTS.2 - Batch Comment. /// </summary> public string BatchComment { get; set; } /// <summary> /// BTS.3 - Batch Totals. /// </summary> public IEnumerable<decimal> BatchTotals { get; set; } /// <summary> /// Initializes properties of this instance with values parsed from the given delimited string. Separators defined in the Configuration class are used to split the string. /// </summary> /// <param name="delimitedString">A string representation that will be deserialized into the object instance.</param> /// <exception cref="ArgumentException">delimitedString does not begin with the proper segment Id.</exception> public void FromDelimitedString(string delimitedString) { FromDelimitedString(delimitedString, null); } /// <summary> /// Initializes properties of this instance with values parsed from the given delimited string. The provided separators are used to split the string. /// </summary> /// <param name="delimitedString">A string representation that will be deserialized into the object instance.</param> /// <param name="separators">The separators to use for splitting the string.</param> /// <exception cref="ArgumentException">delimitedString does not begin with the proper segment Id.</exception> public void FromDelimitedString(string delimitedString, Separators separators) { Separators seps = separators ?? new Separators().UsingConfigurationValues(); string[] segments = delimitedString == null ? Array.Empty<string>() : delimitedString.Split(seps.FieldSeparator, StringSplitOptions.None); if (segments.Length > 0) { if (string.Compare(Id, segments[0], true, CultureInfo.CurrentCulture) != 0) { throw new ArgumentException($"{ nameof(delimitedString) } does not begin with the proper segment Id: '{ Id }{ seps.FieldSeparator }'.", nameof(delimitedString)); } } BatchMessageCount = segments.Length > 1 && segments[1].Length > 0 ? segments[1] : null; BatchComment = segments.Length > 2 && segments[2].Length > 0 ? segments[2] : null; BatchTotals = segments.Length > 3 && segments[3].Length > 0 ? segments[3].Split(seps.FieldRepeatSeparator, StringSplitOptions.None).Select(x => x.ToDecimal()) : null; } /// <summary> /// Returns a delimited string representation of this instance. /// </summary> /// <returns>A string.</returns> public string ToDelimitedString() { CultureInfo culture = CultureInfo.CurrentCulture; return string.Format( culture, StringHelper.StringFormatSequence(0, 4, Configuration.FieldSeparator), Id, BatchMessageCount, BatchComment, BatchTotals != null ? string.Join(Configuration.FieldRepeatSeparator, BatchTotals.Select(x => x.ToString(Consts.NumericFormat, culture))) : null ).TrimEnd(Configuration.FieldSeparator.ToCharArray()); } } }
45.5
181
0.595978
[ "MIT" ]
davebronson/clear-hl7-net
src/ClearHl7/V290/Segments/BtsSegment.cs
4,279
C#
/* Copyright 2009-2012 Arno Wacker, University of Kassel Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using CrypTool.PluginBase; using System.ComponentModel; namespace CrypTool.Caesar { public class CaesarSettings : ISettings { #region Public Caesar specific interface /// <summary> /// We use this delegate to send log messages from the settings class to the Caesar plugin /// </summary> public delegate void CaesarLogMessage(string msg, NotificationLevel loglevel); public enum CaesarMode { Encrypt = 0, Decrypt = 1 }; /// <summary> /// An enumaration for the different modes of dealing with unknown characters /// </summary> public enum UnknownSymbolHandlingMode { Ignore = 0, Remove = 1, Replace = 2 }; /// <summary> /// Feuern, wenn ein neuer Text im Statusbar angezeigt werden soll. /// </summary> public event CaesarLogMessage LogMessage; #endregion #region Private variables and public constructor private CaesarMode selectedAction = CaesarMode.Encrypt; private readonly string upperAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private readonly string lowerAlphabet = "abcdefghijklmnopqrstuvwxyz"; private string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private int shiftValue = 3; private string shiftString; private UnknownSymbolHandlingMode unknownSymbolHandling = UnknownSymbolHandlingMode.Ignore; private bool caseSensitiveSensitive = false; private bool memorizeCase = false; public CaesarSettings() { SetKeyByValue(shiftValue); } #endregion #region Private methods private void OnLogMessage(string msg, NotificationLevel level) { if (LogMessage != null) { LogMessage(msg, level); } } private string removeEqualChars(string value) { int length = value.Length; for (int i = 0; i < length; i++) { for (int j = i + 1; j < length; j++) { if ((value[i] == value[j]) || (!CaseSensitive & (char.ToUpper(value[i]) == char.ToUpper(value[j])))) { OnLogMessage("Removing duplicate letter: \'" + value[j] + "\' from alphabet!", NotificationLevel.Warning); value = value.Remove(j, 1); j--; length--; } } } return value; } /// <summary> /// Set the new shiftValue and the new shiftString to offset % alphabet.Length /// </summary> public void SetKeyByValue(int offset, bool firePropertyChanges = true) { // making sure the shift value lies within the alphabet range shiftValue = ((offset % alphabet.Length) + alphabet.Length) % alphabet.Length; shiftString = "A -> " + alphabet[shiftValue]; // Anounnce this to the settings pane if (firePropertyChanges) { OnPropertyChanged("ShiftValue"); OnPropertyChanged("ShiftString"); } // print some info in the log. OnLogMessage("Accepted new shift value: " + offset, NotificationLevel.Debug); } #endregion #region Algorithm settings properties (visible in the Settings pane) [PropertySaveOrder(4)] [TaskPane("ActionTPCaption", "ActionTPTooltip", null, 1, false, ControlType.ComboBox, new string[] { "ActionList1", "ActionList2" })] public CaesarMode Action { get => selectedAction; set { if (value != selectedAction) { selectedAction = value; OnPropertyChanged("Action"); } } } [PropertySaveOrder(5)] [TaskPane("ShiftValueCaption", "ShiftValueTooltip", null, 2, false, ControlType.NumericUpDown, ValidationType.RangeInteger, -1, 100)] public int ShiftKey { get => shiftValue; set => SetKeyByValue(value); } [PropertySaveOrder(6)] [TaskPane("ShiftStringCaption", "ShiftStringTooltip", null, 3, false, ControlType.TextBoxReadOnly)] public string ShiftString => shiftString; //[SettingsFormat(0, "Normal", "Normal", "Black", "White", Orientation.Vertical)] [PropertySaveOrder(7)] [TaskPane("AlphabetSymbolsCaption", "AlphabetSymbolsTooltip", "AlphabetGroup", 4, false, ControlType.TextBox, "")] public string AlphabetSymbols { get => alphabet; set { string a = removeEqualChars(value); if (a.Length == 0) // cannot accept empty alphabets { OnLogMessage("Ignoring empty alphabet from user! Using previous alphabet: \"" + alphabet + "\" (" + alphabet.Length.ToString() + " Symbols)", NotificationLevel.Info); } else if (!alphabet.Equals(a)) { alphabet = a; SetKeyByValue(shiftValue); //re-evaluate if the shiftvalue is still within the range OnLogMessage("Accepted new alphabet from user: \"" + alphabet + "\" (" + alphabet.Length.ToString() + " Symbols)", NotificationLevel.Info); OnPropertyChanged("AlphabetSymbols"); } } } [PropertySaveOrder(8)] [TaskPane("UnknownSymbolHandlingCaption", "UnknownSymbolHandlingTooltip", "AlphabetGroup", 5, false, ControlType.ComboBox, new string[] { "UnknownSymbolHandlingList1", "UnknownSymbolHandlingList2", "UnknownSymbolHandlingList3" })] public UnknownSymbolHandlingMode UnknownSymbolHandling { get => unknownSymbolHandling; set { if (value != unknownSymbolHandling) { unknownSymbolHandling = value; OnPropertyChanged("UnknownSymbolHandling"); } } } /// <summary> /// Visible setting how to deal with alphabet case. false = case insensitive, true = case sensitive /// </summary [PropertySaveOrder(9)] [TaskPane("AlphabetCaseCaption", "AlphabetCaseTooltip", "AlphabetGroup", 6, false, ControlType.CheckBox)] public bool CaseSensitive { get => caseSensitiveSensitive; set { if (value == caseSensitiveSensitive) { return; } if (value == true) { memorizeCase = false; OnPropertyChanged("MemorizeCase"); } caseSensitiveSensitive = value; if (value) { if (alphabet == upperAlphabet) { alphabet = upperAlphabet + lowerAlphabet; OnLogMessage( "Changing alphabet to: \"" + alphabet + "\" (" + alphabet.Length + " Symbols)", NotificationLevel.Debug); OnPropertyChanged("AlphabetSymbols"); } } else { if (alphabet == (upperAlphabet + lowerAlphabet)) { alphabet = upperAlphabet; OnLogMessage( "Changing alphabet to: \"" + alphabet + "\" (" + alphabet.Length + " Symbols)", NotificationLevel.Debug); OnPropertyChanged("AlphabetSymbols"); // re-set also the key (shiftvalue/shiftString to be in the range of the new alphabet SetKeyByValue(shiftValue); } } // remove equal characters from the current alphabet string a = alphabet; alphabet = removeEqualChars(alphabet); if (a != alphabet) { OnPropertyChanged("AlphabetSymbols"); OnLogMessage("Changing alphabet to: \"" + alphabet + "\" (" + alphabet.Length.ToString() + " Symbols)", NotificationLevel.Info); } OnPropertyChanged("CaseSensitive"); } } [PropertySaveOrder(10)] [TaskPane("MemorizeCaseCaption", "MemorizeCaseTooltip", "AlphabetGroup", 7, false, ControlType.CheckBox)] public bool MemorizeCase { get => memorizeCase; set { bool newMemorizeCase = CaseSensitive ? false : value; if (newMemorizeCase != memorizeCase) { memorizeCase = newMemorizeCase; OnPropertyChanged("MemorizeCase"); } } } #endregion #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; public void Initialize() { } private void OnPropertyChanged(string name) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion } }
36.347518
238
0.538439
[ "Apache-2.0" ]
CrypToolProject/CrypTool-2
CrypPlugins/Caesar/CaesarSettings.cs
10,252
C#
namespace ArmyOfCreatures.Extended.Creatures { using ArmyOfCreatures.Logic.Creatures; using ArmyOfCreatures.Logic.Specialties; public class AncientBehemoth : Creature { private const int AttackPoints = 19; private const int DefensePoints = 19; private const int HealtPoints = 300; private const decimal DamagePoints = 40; private const int ReducePercentage = 80; private const int DoubleDefenceRounds = 5; public AncientBehemoth() : base(AttackPoints, DefensePoints, HealtPoints, DamagePoints) { this.AddSpecialty(new ReduceEnemyDefenseByPercentage(ReducePercentage)); this.AddSpecialty(new DoubleDefenseWhenDefending(DoubleDefenceRounds)); } } }
35.5
84
0.6863
[ "MIT" ]
EmilMitev/Telerik-Academy
CSarp - OOP/Exam/ArmyOfCreatures/ArmyOfCreatures/Extended/Creatures/AncientBehemoth.cs
783
C#
namespace Umbraco.Core.Persistence.Migrations.Syntax.Delete.Index { public interface IDeleteIndexForTableSyntax : IFluentSyntax { IDeleteIndexOnColumnSyntax OnTable(string tableName); } }
29.714286
66
0.769231
[ "MIT" ]
filipesousa20/Umbraco-CMS-V7
src/Umbraco.Core/Persistence/Migrations/Syntax/Delete/Index/IDeleteIndexForTableSyntax.cs
210
C#
//------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // // Änderungen an dieser Datei können fehlerhaftes Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ namespace Compori.MagentoApi.SoapClient.RemoteServices.Core.ResourceModel.StoreGroupRepositoryV1 { /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil", "1.0.4")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://connector.monnier.cidev04.test/soap/default?services=storeGroupRepositoryV" + "1")] public partial class GenericFault { private string traceField; private GenericFaultParameter[] parametersField; private WrappedError[] wrappedErrorsField; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=0)] public string Trace { get { return this.traceField; } set { this.traceField = value; } } /// <remarks/> [System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=1)] [System.Xml.Serialization.XmlArrayItemAttribute("item", Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)] public GenericFaultParameter[] Parameters { get { return this.parametersField; } set { this.parametersField = value; } } /// <remarks/> [System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=2)] [System.Xml.Serialization.XmlArrayItemAttribute("item", Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)] public WrappedError[] WrappedErrors { get { return this.wrappedErrorsField; } set { this.wrappedErrorsField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil", "1.0.4")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://connector.monnier.cidev04.test/soap/default?services=storeGroupRepositoryV" + "1")] public partial class GenericFaultParameter { private string keyField; private string valueField; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=0)] public string key { get { return this.keyField; } set { this.keyField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=1)] public string value { get { return this.valueField; } set { this.valueField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil", "1.0.4")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://connector.monnier.cidev04.test/soap/default?services=storeGroupRepositoryV" + "1")] public partial class WrappedError { private string messageField; private GenericFaultParameter[] parametersField; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=0)] public string message { get { return this.messageField; } set { this.messageField = value; } } /// <remarks/> [System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=1)] [System.Xml.Serialization.XmlArrayItemAttribute("item", Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)] public GenericFaultParameter[] parameters { get { return this.parametersField; } set { this.parametersField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil", "1.0.4")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://connector.monnier.cidev04.test/soap/default?services=storeGroupRepositoryV" + "1")] public partial class StoreDataGroupExtensionInterface { } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil", "1.0.4")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://connector.monnier.cidev04.test/soap/default?services=storeGroupRepositoryV" + "1")] public partial class StoreDataGroupInterface { private int idField; private int websiteIdField; private int rootCategoryIdField; private int defaultStoreIdField; private string nameField; private string codeField; private StoreDataGroupExtensionInterface extensionAttributesField; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=0)] public int id { get { return this.idField; } set { this.idField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=1)] public int websiteId { get { return this.websiteIdField; } set { this.websiteIdField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=2)] public int rootCategoryId { get { return this.rootCategoryIdField; } set { this.rootCategoryIdField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=3)] public int defaultStoreId { get { return this.defaultStoreIdField; } set { this.defaultStoreIdField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=4)] public string name { get { return this.nameField; } set { this.nameField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=5)] public string code { get { return this.codeField; } set { this.codeField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=6)] public StoreDataGroupExtensionInterface extensionAttributes { get { return this.extensionAttributesField; } set { this.extensionAttributesField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil", "1.0.4")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://connector.monnier.cidev04.test/soap/default?services=storeGroupRepositoryV" + "1")] public partial class StoreGroupRepositoryV1GetListResponse { private StoreDataGroupInterface[] resultField; /// <remarks/> [System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=0)] [System.Xml.Serialization.XmlArrayItemAttribute("item", Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)] public StoreDataGroupInterface[] result { get { return this.resultField; } set { this.resultField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil", "1.0.4")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://connector.monnier.cidev04.test/soap/default?services=storeGroupRepositoryV" + "1")] public partial class StoreGroupRepositoryV1GetListRequest { } [System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil", "1.0.4")] [System.ServiceModel.ServiceContractAttribute(Namespace="http://connector.monnier.cidev04.test/soap/default?services=storeGroupRepositoryV" + "1", ConfigurationName="Compori.MagentoApi.SoapClient.RemoteServices.Core.ResourceModel.StoreGroupReposit" + "oryV1.storeGroupRepositoryV1PortType")] public interface storeGroupRepositoryV1PortType { [System.ServiceModel.OperationContractAttribute(Action="storeGroupRepositoryV1GetList", ReplyAction="*")] [System.ServiceModel.FaultContractAttribute(typeof(Compori.MagentoApi.SoapClient.RemoteServices.Core.ResourceModel.StoreGroupRepositoryV1.GenericFault), Action="storeGroupRepositoryV1GetList", Name="GenericFault")] [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)] System.Threading.Tasks.Task<Compori.MagentoApi.SoapClient.RemoteServices.Core.ResourceModel.StoreGroupRepositoryV1.storeGroupRepositoryV1GetListResponse1> storeGroupRepositoryV1GetListAsync(Compori.MagentoApi.SoapClient.RemoteServices.Core.ResourceModel.StoreGroupRepositoryV1.storeGroupRepositoryV1GetListRequest1 request); } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil", "1.0.4")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.ServiceModel.MessageContractAttribute(IsWrapped=false)] public partial class storeGroupRepositoryV1GetListRequest1 { [System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://connector.monnier.cidev04.test/soap/default?services=storeGroupRepositoryV" + "1", Order=0)] [System.Xml.Serialization.XmlElementAttribute(IsNullable=true)] public Compori.MagentoApi.SoapClient.RemoteServices.Core.ResourceModel.StoreGroupRepositoryV1.StoreGroupRepositoryV1GetListRequest storeGroupRepositoryV1GetListRequest; public storeGroupRepositoryV1GetListRequest1() { } public storeGroupRepositoryV1GetListRequest1(Compori.MagentoApi.SoapClient.RemoteServices.Core.ResourceModel.StoreGroupRepositoryV1.StoreGroupRepositoryV1GetListRequest storeGroupRepositoryV1GetListRequest) { this.storeGroupRepositoryV1GetListRequest = storeGroupRepositoryV1GetListRequest; } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil", "1.0.4")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] [System.ServiceModel.MessageContractAttribute(IsWrapped=false)] public partial class storeGroupRepositoryV1GetListResponse1 { [System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://connector.monnier.cidev04.test/soap/default?services=storeGroupRepositoryV" + "1", Order=0)] public Compori.MagentoApi.SoapClient.RemoteServices.Core.ResourceModel.StoreGroupRepositoryV1.StoreGroupRepositoryV1GetListResponse storeGroupRepositoryV1GetListResponse; public storeGroupRepositoryV1GetListResponse1() { } public storeGroupRepositoryV1GetListResponse1(Compori.MagentoApi.SoapClient.RemoteServices.Core.ResourceModel.StoreGroupRepositoryV1.StoreGroupRepositoryV1GetListResponse storeGroupRepositoryV1GetListResponse) { this.storeGroupRepositoryV1GetListResponse = storeGroupRepositoryV1GetListResponse; } } [System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil", "1.0.4")] public interface storeGroupRepositoryV1PortTypeChannel : Compori.MagentoApi.SoapClient.RemoteServices.Core.ResourceModel.StoreGroupRepositoryV1.storeGroupRepositoryV1PortType, System.ServiceModel.IClientChannel { } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil", "1.0.4")] public partial class storeGroupRepositoryV1PortTypeClient : System.ServiceModel.ClientBase<Compori.MagentoApi.SoapClient.RemoteServices.Core.ResourceModel.StoreGroupRepositoryV1.storeGroupRepositoryV1PortType>, Compori.MagentoApi.SoapClient.RemoteServices.Core.ResourceModel.StoreGroupRepositoryV1.storeGroupRepositoryV1PortType { /// <summary> /// Implementieren Sie diese partielle Methode, um den Dienstendpunkt zu konfigurieren. /// </summary> /// <param name="serviceEndpoint">Der zu konfigurierende Endpunkt</param> /// <param name="clientCredentials">Die Clientanmeldeinformationen</param> static partial void ConfigureEndpoint(System.ServiceModel.Description.ServiceEndpoint serviceEndpoint, System.ServiceModel.Description.ClientCredentials clientCredentials); public storeGroupRepositoryV1PortTypeClient() : base(storeGroupRepositoryV1PortTypeClient.GetDefaultBinding(), storeGroupRepositoryV1PortTypeClient.GetDefaultEndpointAddress()) { this.Endpoint.Name = EndpointConfiguration.storeGroupRepositoryV1Port.ToString(); ConfigureEndpoint(this.Endpoint, this.ClientCredentials); } public storeGroupRepositoryV1PortTypeClient(EndpointConfiguration endpointConfiguration) : base(storeGroupRepositoryV1PortTypeClient.GetBindingForEndpoint(endpointConfiguration), storeGroupRepositoryV1PortTypeClient.GetEndpointAddress(endpointConfiguration)) { this.Endpoint.Name = endpointConfiguration.ToString(); ConfigureEndpoint(this.Endpoint, this.ClientCredentials); } public storeGroupRepositoryV1PortTypeClient(EndpointConfiguration endpointConfiguration, string remoteAddress) : base(storeGroupRepositoryV1PortTypeClient.GetBindingForEndpoint(endpointConfiguration), new System.ServiceModel.EndpointAddress(remoteAddress)) { this.Endpoint.Name = endpointConfiguration.ToString(); ConfigureEndpoint(this.Endpoint, this.ClientCredentials); } public storeGroupRepositoryV1PortTypeClient(EndpointConfiguration endpointConfiguration, System.ServiceModel.EndpointAddress remoteAddress) : base(storeGroupRepositoryV1PortTypeClient.GetBindingForEndpoint(endpointConfiguration), remoteAddress) { this.Endpoint.Name = endpointConfiguration.ToString(); ConfigureEndpoint(this.Endpoint, this.ClientCredentials); } public storeGroupRepositoryV1PortTypeClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : base(binding, remoteAddress) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] System.Threading.Tasks.Task<Compori.MagentoApi.SoapClient.RemoteServices.Core.ResourceModel.StoreGroupRepositoryV1.storeGroupRepositoryV1GetListResponse1> Compori.MagentoApi.SoapClient.RemoteServices.Core.ResourceModel.StoreGroupRepositoryV1.storeGroupRepositoryV1PortType.storeGroupRepositoryV1GetListAsync(Compori.MagentoApi.SoapClient.RemoteServices.Core.ResourceModel.StoreGroupRepositoryV1.storeGroupRepositoryV1GetListRequest1 request) { return base.Channel.storeGroupRepositoryV1GetListAsync(request); } public System.Threading.Tasks.Task<Compori.MagentoApi.SoapClient.RemoteServices.Core.ResourceModel.StoreGroupRepositoryV1.storeGroupRepositoryV1GetListResponse1> storeGroupRepositoryV1GetListAsync(Compori.MagentoApi.SoapClient.RemoteServices.Core.ResourceModel.StoreGroupRepositoryV1.StoreGroupRepositoryV1GetListRequest storeGroupRepositoryV1GetListRequest) { Compori.MagentoApi.SoapClient.RemoteServices.Core.ResourceModel.StoreGroupRepositoryV1.storeGroupRepositoryV1GetListRequest1 inValue = new Compori.MagentoApi.SoapClient.RemoteServices.Core.ResourceModel.StoreGroupRepositoryV1.storeGroupRepositoryV1GetListRequest1(); inValue.storeGroupRepositoryV1GetListRequest = storeGroupRepositoryV1GetListRequest; return ((Compori.MagentoApi.SoapClient.RemoteServices.Core.ResourceModel.StoreGroupRepositoryV1.storeGroupRepositoryV1PortType)(this)).storeGroupRepositoryV1GetListAsync(inValue); } public virtual System.Threading.Tasks.Task OpenAsync() { return System.Threading.Tasks.Task.Factory.FromAsync(((System.ServiceModel.ICommunicationObject)(this)).BeginOpen(null, null), new System.Action<System.IAsyncResult>(((System.ServiceModel.ICommunicationObject)(this)).EndOpen)); } public virtual System.Threading.Tasks.Task CloseAsync() { return System.Threading.Tasks.Task.Factory.FromAsync(((System.ServiceModel.ICommunicationObject)(this)).BeginClose(null, null), new System.Action<System.IAsyncResult>(((System.ServiceModel.ICommunicationObject)(this)).EndClose)); } private static System.ServiceModel.Channels.Binding GetBindingForEndpoint(EndpointConfiguration endpointConfiguration) { if ((endpointConfiguration == EndpointConfiguration.storeGroupRepositoryV1Port)) { System.ServiceModel.Channels.CustomBinding result = new System.ServiceModel.Channels.CustomBinding(); System.ServiceModel.Channels.TextMessageEncodingBindingElement textBindingElement = new System.ServiceModel.Channels.TextMessageEncodingBindingElement(); textBindingElement.MessageVersion = System.ServiceModel.Channels.MessageVersion.CreateVersion(System.ServiceModel.EnvelopeVersion.Soap12, System.ServiceModel.Channels.AddressingVersion.None); result.Elements.Add(textBindingElement); System.ServiceModel.Channels.HttpTransportBindingElement httpBindingElement = new System.ServiceModel.Channels.HttpTransportBindingElement(); httpBindingElement.AllowCookies = true; httpBindingElement.MaxBufferSize = int.MaxValue; httpBindingElement.MaxReceivedMessageSize = int.MaxValue; result.Elements.Add(httpBindingElement); return result; } throw new System.InvalidOperationException(string.Format("Es wurde kein Endpunkt mit dem Namen \"{0}\" gefunden.", endpointConfiguration)); } private static System.ServiceModel.EndpointAddress GetEndpointAddress(EndpointConfiguration endpointConfiguration) { if ((endpointConfiguration == EndpointConfiguration.storeGroupRepositoryV1Port)) { return new System.ServiceModel.EndpointAddress("http://connector.monnier.cidev04.test/soap/default?services=storeGroupRepositoryV" + "1"); } throw new System.InvalidOperationException(string.Format("Es wurde kein Endpunkt mit dem Namen \"{0}\" gefunden.", endpointConfiguration)); } private static System.ServiceModel.Channels.Binding GetDefaultBinding() { return storeGroupRepositoryV1PortTypeClient.GetBindingForEndpoint(EndpointConfiguration.storeGroupRepositoryV1Port); } private static System.ServiceModel.EndpointAddress GetDefaultEndpointAddress() { return storeGroupRepositoryV1PortTypeClient.GetEndpointAddress(EndpointConfiguration.storeGroupRepositoryV1Port); } public enum EndpointConfiguration { storeGroupRepositoryV1Port, } } }
44.389899
449
0.666181
[ "BSD-3-Clause" ]
compori/magentoapi
src/MagentoApi.SoapClient.RemoteServices.Core243/ResourceModel/StoreGroupRepositoryV1.cs
21,977
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Media.Models { /// <summary> /// Defines values for ContentKeyPolicyPlayReadyUnknownOutputPassingOption. /// </summary> public static class ContentKeyPolicyPlayReadyUnknownOutputPassingOption { /// <summary> /// Represents a ContentKeyPolicyPlayReadyUnknownOutputPassingOption /// that is unavailable in current API version. /// </summary> public const string Unknown = "Unknown"; /// <summary> /// Passing the video portion of protected content to an Unknown Output /// is not allowed. /// </summary> public const string NotAllowed = "NotAllowed"; /// <summary> /// Passing the video portion of protected content to an Unknown Output /// is allowed. /// </summary> public const string Allowed = "Allowed"; /// <summary> /// Passing the video portion of protected content to an Unknown Output /// is allowed but with constrained resolution. /// </summary> public const string AllowedWithVideoConstriction = "AllowedWithVideoConstriction"; } }
37.02439
90
0.665349
[ "MIT" ]
dsgouda/aznetsdk
src/SDKs/Media/Management.Media/Generated/Models/ContentKeyPolicyPlayReadyUnknownOutputPassingOption.cs
1,518
C#
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using D = Duracellko.PlanningPoker.Domain; namespace Duracellko.PlanningPoker.Service.Test { [TestClass] public class PlanningPokerServiceTest { private const string TeamName = "test team"; private const string ScrumMasterName = "master"; private const string MemberName = "member"; private const string ObserverName = "observer"; private const string LongTeamName = "ttttttttttttttttttttttttttttttttttttttttttttttttttt"; private const string LongMemberName = "mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm"; [TestMethod] public void Constructor_PlanningPoker_PlanningPokerPropertyIsSet() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); // Act var result = new PlanningPokerService(planningPoker.Object); // Verify Assert.AreEqual<D.IPlanningPoker>(planningPoker.Object, result.PlanningPoker); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void Constructor_Null_ArgumentNullException() { // Act var result = new PlanningPokerService(null); } [TestMethod] public void CreateTeam_TeamNameAndScrumMasterName_ReturnsCreatedTeam() { // Arrange var team = CreateBasicTeam(); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.CreateScrumTeam(TeamName, ScrumMasterName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act var result = target.CreateTeam(TeamName, ScrumMasterName).Value; // Verify planningPoker.Verify(); teamLock.Verify(); teamLock.Verify(l => l.Team); Assert.IsNotNull(result); Assert.AreEqual<string>(TeamName, result.Name); Assert.IsNotNull(result.ScrumMaster); Assert.AreEqual<string>(ScrumMasterName, result.ScrumMaster.Name); Assert.AreEqual<string>(typeof(D.ScrumMaster).Name, result.ScrumMaster.Type); } [TestMethod] public void CreateTeam_TeamNameAndScrumMasterName_ReturnsTeamWithAvilableEstimations() { // Arrange var team = CreateBasicTeam(); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.CreateScrumTeam(TeamName, ScrumMasterName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act var result = target.CreateTeam(TeamName, ScrumMasterName).Value; // Verify Assert.IsNotNull(result.AvailableEstimations); var expectedCollection = new double?[] { 0.0, 0.5, 1.0, 2.0, 3.0, 5.0, 8.0, 13.0, 20.0, 40.0, 100.0, Estimation.PositiveInfinity, null }; CollectionAssert.AreEquivalent(expectedCollection, result.AvailableEstimations.Select(e => e.Value).ToList()); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void CreateTeam_TeamNameIsEmpty_ArgumentNullException() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); var target = new PlanningPokerService(planningPoker.Object); // Act target.CreateTeam(null, ScrumMasterName); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void CreateTeam_ScrumMasterNameIsEmpty_ArgumentNullException() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); var target = new PlanningPokerService(planningPoker.Object); // Act target.CreateTeam(TeamName, null); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void CreateTeam_TeamNameTooLong_ArgumentException() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); var target = new PlanningPokerService(planningPoker.Object); // Act target.CreateTeam(LongTeamName, ScrumMasterName); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void CreateTeam_ScrumMasterNameTooLong_ArgumentException() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); var target = new PlanningPokerService(planningPoker.Object); // Act target.CreateTeam(TeamName, LongMemberName); } [TestMethod] public void JoinTeam_TeamNameAndMemberNameAsMember_ReturnsTeamJoined() { // Arrange var team = CreateBasicTeam(); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act var result = target.JoinTeam(TeamName, MemberName, false).Value; // Verify planningPoker.Verify(); teamLock.Verify(); teamLock.Verify(l => l.Team); Assert.IsNotNull(result); Assert.AreEqual<string>(TeamName, result.Name); Assert.IsNotNull(result.ScrumMaster); Assert.AreEqual<string>(ScrumMasterName, result.ScrumMaster.Name); Assert.IsNotNull(result.Members); var expectedMembers = new string[] { ScrumMasterName, MemberName }; CollectionAssert.AreEquivalent(expectedMembers, result.Members.Select(m => m.Name).ToList()); var expectedMemberTypes = new string[] { typeof(D.ScrumMaster).Name, typeof(D.Member).Name }; CollectionAssert.AreEquivalent(expectedMemberTypes, result.Members.Select(m => m.Type).ToList()); } [TestMethod] public void JoinTeam_TeamNameAndMemberNameAsMember_MemberIsAddedToTheTeam() { // Arrange var team = CreateBasicTeam(); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act target.JoinTeam(TeamName, MemberName, false); // Verify var expectedMembers = new string[] { ScrumMasterName, MemberName }; CollectionAssert.AreEquivalent(expectedMembers, team.Members.Select(m => m.Name).ToList()); } [TestMethod] public void JoinTeam_TeamNameAndMemberNameAsMemberAndEstimationStarted_ScrumMasterIsEstimationParticipant() { // Arrange var team = CreateBasicTeam(); team.ScrumMaster.StartEstimation(); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act target.JoinTeam(TeamName, MemberName, false); // Verify var expectedParticipants = new string[] { ScrumMasterName }; CollectionAssert.AreEquivalent(expectedParticipants, team.EstimationParticipants.Select(m => m.MemberName).ToList()); } [TestMethod] public void JoinTeam_TeamNameAndObserverNameAsObserver_ReturnsTeamJoined() { // Arrange var team = CreateBasicTeam(); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act var result = target.JoinTeam(TeamName, ObserverName, true).Value; // Verify planningPoker.Verify(); teamLock.Verify(); teamLock.Verify(l => l.Team); Assert.IsNotNull(result); Assert.AreEqual<string>(TeamName, result.Name); Assert.IsNotNull(result.ScrumMaster); Assert.AreEqual<string>(ScrumMasterName, result.ScrumMaster.Name); Assert.IsNotNull(result.Observers); var expectedObservers = new string[] { ObserverName }; CollectionAssert.AreEquivalent(expectedObservers, result.Observers.Select(m => m.Name).ToList()); var expectedMemberTypes = new string[] { typeof(D.Observer).Name }; CollectionAssert.AreEquivalent(expectedMemberTypes, result.Observers.Select(m => m.Type).ToList()); } [TestMethod] public void JoinTeam_TeamNameAndObserverNameAsObserver_ObserverIsAddedToTheTeam() { // Arrange var team = CreateBasicTeam(); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act target.JoinTeam(TeamName, ObserverName, true); // Verify var expectedObservers = new string[] { ObserverName }; CollectionAssert.AreEquivalent(expectedObservers, team.Observers.Select(m => m.Name).ToList()); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void JoinTeam_TeamNameIsEmpty_ArgumentNullException() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); var target = new PlanningPokerService(planningPoker.Object); // Act target.JoinTeam(null, MemberName, false); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void JoinTeam_MemberNameIsEmpty_ArgumentNullException() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); var target = new PlanningPokerService(planningPoker.Object); // Act target.JoinTeam(TeamName, null, false); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void JoinTeam_TeamNameTooLong_ArgumentException() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); var target = new PlanningPokerService(planningPoker.Object); // Act target.JoinTeam(LongTeamName, MemberName, false); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void JoinTeam_MemberNameTooLong_ArgumentException() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); var target = new PlanningPokerService(planningPoker.Object); // Act target.JoinTeam(TeamName, LongMemberName, false); } [TestMethod] public void ReconnectTeam_TeamNameAndScrumMasterName_ReturnsReconnectedTeam() { // Arrange var team = CreateBasicTeam(); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act var result = target.ReconnectTeam(TeamName, ScrumMasterName).Value; // Verify planningPoker.Verify(); teamLock.Verify(); teamLock.Verify(l => l.Team); Assert.IsNotNull(result); Assert.IsNotNull(result.ScrumTeam); Assert.AreEqual<long>(0, result.LastMessageId); Assert.AreEqual<string>(TeamName, result.ScrumTeam.Name); Assert.IsNotNull(result.ScrumTeam.ScrumMaster); Assert.AreEqual<string>(ScrumMasterName, result.ScrumTeam.ScrumMaster.Name); Assert.IsNotNull(result.ScrumTeam.Members); var expectedMembers = new string[] { ScrumMasterName }; CollectionAssert.AreEquivalent(expectedMembers, result.ScrumTeam.Members.Select(m => m.Name).ToList()); var expectedMemberTypes = new string[] { typeof(D.ScrumMaster).Name }; CollectionAssert.AreEquivalent(expectedMemberTypes, result.ScrumTeam.Members.Select(m => m.Type).ToList()); } [TestMethod] public void ReconnectTeam_TeamNameAndMemberName_ReturnsReconnectedTeam() { // Arrange var team = CreateBasicTeam(); var member = team.Join(MemberName, false); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act var result = target.ReconnectTeam(TeamName, MemberName).Value; // Verify planningPoker.Verify(); teamLock.Verify(); teamLock.Verify(l => l.Team); Assert.IsNotNull(result); Assert.IsNotNull(result.ScrumTeam); Assert.AreEqual<long>(0, result.LastMessageId); Assert.AreEqual<string>(TeamName, result.ScrumTeam.Name); Assert.IsNotNull(result.ScrumTeam.ScrumMaster); Assert.AreEqual<string>(ScrumMasterName, result.ScrumTeam.ScrumMaster.Name); Assert.IsNotNull(result.ScrumTeam.Members); var expectedMembers = new string[] { ScrumMasterName, MemberName }; CollectionAssert.AreEquivalent(expectedMembers, result.ScrumTeam.Members.Select(m => m.Name).ToList()); var expectedMemberTypes = new string[] { typeof(D.ScrumMaster).Name, typeof(D.Member).Name }; CollectionAssert.AreEquivalent(expectedMemberTypes, result.ScrumTeam.Members.Select(m => m.Type).ToList()); } [TestMethod] public void ReconnectTeam_TeamNameAndObserverName_ReturnsReconnectedTeam() { // Arrange var team = CreateBasicTeam(); var observer = team.Join(ObserverName, true); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act var result = target.ReconnectTeam(TeamName, ObserverName).Value; // Verify planningPoker.Verify(); teamLock.Verify(); teamLock.Verify(l => l.Team); Assert.IsNotNull(result); Assert.IsNotNull(result.ScrumTeam); Assert.AreEqual<long>(0, result.LastMessageId); Assert.AreEqual<string>(TeamName, result.ScrumTeam.Name); Assert.IsNotNull(result.ScrumTeam.ScrumMaster); Assert.AreEqual<string>(ScrumMasterName, result.ScrumTeam.ScrumMaster.Name); Assert.IsNotNull(result.ScrumTeam.Members); var expectedMembers = new string[] { ScrumMasterName }; CollectionAssert.AreEquivalent(expectedMembers, result.ScrumTeam.Members.Select(m => m.Name).ToList()); var expectedMemberTypes = new string[] { typeof(D.ScrumMaster).Name }; CollectionAssert.AreEquivalent(expectedMemberTypes, result.ScrumTeam.Members.Select(m => m.Type).ToList()); Assert.IsNotNull(result.ScrumTeam.Observers); var expectedObservers = new string[] { ObserverName }; CollectionAssert.AreEquivalent(expectedObservers, result.ScrumTeam.Observers.Select(m => m.Name).ToList()); } [TestMethod] public void ReconnectTeam_TeamNameAndNonExistingMemberName_ArgumentException() { // Arrange var team = CreateBasicTeam(); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act var result = target.ReconnectTeam(TeamName, MemberName); // Verify Assert.IsInstanceOfType(result.Result, typeof(BadRequestObjectResult)); } [TestMethod] public void ReconnectTeam_TeamNameAndMemberNameWithMessages_ReturnsLastMessageId() { // Arrange var team = CreateBasicTeam(); var member = team.Join(MemberName, false); team.ScrumMaster.StartEstimation(); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act var result = target.ReconnectTeam(TeamName, MemberName).Value; // Verify planningPoker.Verify(); teamLock.Verify(); teamLock.Verify(l => l.Team); Assert.IsNotNull(result); Assert.IsNotNull(result.ScrumTeam); Assert.AreEqual<long>(1, result.LastMessageId); Assert.IsFalse(member.HasMessage); } [TestMethod] public void ReconnectTeam_TeamNameAndMemberNameAndEstimationInProgress_NoEstimationResult() { // Arrange var team = CreateBasicTeam(); var member = (D.Member)team.Join(MemberName, false); team.ScrumMaster.StartEstimation(); member.Estimation = new D.Estimation(1); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act var result = target.ReconnectTeam(TeamName, MemberName).Value; // Verify planningPoker.Verify(); teamLock.Verify(); teamLock.Verify(l => l.Team); Assert.IsNotNull(result); Assert.IsNotNull(result.ScrumTeam); Assert.IsNull(result.ScrumTeam.EstimationResult); } [TestMethod] public void ReconnectTeam_TeamNameAndMemberNameAndEstimationFinished_EstimationResultIsSet() { // Arrange var team = CreateBasicTeam(); var member = (D.Member)team.Join(MemberName, false); team.ScrumMaster.StartEstimation(); member.Estimation = new D.Estimation(1); team.ScrumMaster.Estimation = new D.Estimation(2); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act var result = target.ReconnectTeam(TeamName, MemberName).Value; // Verify planningPoker.Verify(); teamLock.Verify(); teamLock.Verify(l => l.Team); Assert.IsNotNull(result); Assert.IsNotNull(result.ScrumTeam); Assert.IsNotNull(result.ScrumTeam.EstimationResult); var expectedEstimations = new double?[] { 2, 1 }; CollectionAssert.AreEquivalent(expectedEstimations, result.ScrumTeam.EstimationResult.Select(e => e.Estimation.Value).ToList()); } [TestMethod] public void ReconnectTeam_TeamNameAndMemberNameAndMemberEstimated_ReturnsSelectedEstimation() { // Arrange var team = CreateBasicTeam(); var member = (D.Member)team.Join(MemberName, false); team.ScrumMaster.StartEstimation(); member.Estimation = new D.Estimation(1); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act var result = target.ReconnectTeam(TeamName, MemberName).Value; // Verify planningPoker.Verify(); teamLock.Verify(); teamLock.Verify(l => l.Team); Assert.IsNotNull(result); Assert.IsNotNull(result.SelectedEstimation); Assert.AreEqual<double?>(1, result.SelectedEstimation.Value); } [TestMethod] public void ReconnectTeam_TeamNameAndMemberNameAndMemberNotEstimated_NoSelectedEstimation() { // Arrange var team = CreateBasicTeam(); var member = (D.Member)team.Join(MemberName, false); team.ScrumMaster.StartEstimation(); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act var result = target.ReconnectTeam(TeamName, MemberName).Value; // Verify planningPoker.Verify(); teamLock.Verify(); teamLock.Verify(l => l.Team); Assert.IsNotNull(result); Assert.IsNull(result.SelectedEstimation); } [TestMethod] public void ReconnectTeam_TeamNameAndMemberNameAndEstimationNotStarted_NoSelectedEstimation() { // Arrange var team = CreateBasicTeam(); var member = (D.Member)team.Join(MemberName, false); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act var result = target.ReconnectTeam(TeamName, MemberName).Value; // Verify planningPoker.Verify(); teamLock.Verify(); teamLock.Verify(l => l.Team); Assert.IsNotNull(result); Assert.IsNull(result.SelectedEstimation); } [TestMethod] public void ReconnectTeam_TeamNameAndMemberNameAndEstimationStarted_AllMembersAreEstimationParticipants() { // Arrange var team = CreateBasicTeam(); var member = (D.Member)team.Join(MemberName, false); team.ScrumMaster.StartEstimation(); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act var result = target.ReconnectTeam(TeamName, MemberName).Value; // Verify planningPoker.Verify(); teamLock.Verify(); teamLock.Verify(l => l.Team); Assert.IsNotNull(result); Assert.IsNotNull(result.ScrumTeam); Assert.IsNotNull(result.ScrumTeam.EstimationParticipants); var expectedParticipants = new string[] { ScrumMasterName, MemberName }; CollectionAssert.AreEqual(expectedParticipants, result.ScrumTeam.EstimationParticipants.Select(p => p.MemberName).ToList()); } [TestMethod] public void ReconnectTeam_TeamNameAndMemberNameAndEstimationNotStarted_NoEstimationParticipants() { // Arrange var team = CreateBasicTeam(); var member = (D.Member)team.Join(MemberName, false); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act var result = target.ReconnectTeam(TeamName, MemberName).Value; // Verify planningPoker.Verify(); teamLock.Verify(); teamLock.Verify(l => l.Team); Assert.IsNotNull(result); Assert.IsNotNull(result.ScrumTeam); Assert.IsNull(result.ScrumTeam.EstimationParticipants); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void ReconnectTeam_TeamNameIsEmpty_ArgumentNullException() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); var target = new PlanningPokerService(planningPoker.Object); // Act target.ReconnectTeam(null, MemberName); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void ReconnectTeam_MemberNameIsEmpty_ArgumentNullException() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); var target = new PlanningPokerService(planningPoker.Object); // Act target.ReconnectTeam(TeamName, null); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void ReconnectTeam_TeamNameTooLong_ArgumentException() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); var target = new PlanningPokerService(planningPoker.Object); // Act target.ReconnectTeam(LongTeamName, MemberName); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void ReconnectTeam_MemberNameTooLong_ArgumentException() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); var target = new PlanningPokerService(planningPoker.Object); // Act target.ReconnectTeam(TeamName, LongMemberName); } [TestMethod] public void DisconnectTeam_TeamNameAndScrumMasterName_ScrumMasterIsRemovedFromTheTeam() { // Arrange var team = CreateBasicTeam(); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act target.DisconnectTeam(TeamName, ScrumMasterName); // Verify planningPoker.Verify(); teamLock.Verify(); teamLock.Verify(l => l.Team); Assert.IsNull(team.ScrumMaster); Assert.IsFalse(team.Members.Any()); } [TestMethod] public void DisconnectTeam_TeamNameAndMemberName_MemberIsRemovedFromTheTeam() { // Arrange var team = CreateBasicTeam(); team.Join(MemberName, false); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act target.DisconnectTeam(TeamName, MemberName); // Verify planningPoker.Verify(); teamLock.Verify(); teamLock.Verify(l => l.Team); var expectedMembers = new string[] { ScrumMasterName }; CollectionAssert.AreEquivalent(expectedMembers, team.Members.Select(m => m.Name).ToList()); } [TestMethod] public void DisconnectTeam_TeamNameAndObserverName_ObserverIsRemovedFromTheTeam() { // Arrange var team = CreateBasicTeam(); team.Join(ObserverName, true); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act target.DisconnectTeam(TeamName, ObserverName); // Verify planningPoker.Verify(); teamLock.Verify(); teamLock.Verify(l => l.Team); Assert.IsFalse(team.Observers.Any()); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void DisconnectTeam_TeamNameIsEmpty_ArgumentNullException() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); var target = new PlanningPokerService(planningPoker.Object); // Act target.DisconnectTeam(null, MemberName); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void DisconnectTeam_MemberNameIsEmpty_ArgumentNullException() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); var target = new PlanningPokerService(planningPoker.Object); // Act target.DisconnectTeam(TeamName, null); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void DisconnectTeam_TeamNameTooLong_ArgumentException() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); var target = new PlanningPokerService(planningPoker.Object); // Act target.DisconnectTeam(LongTeamName, MemberName); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void DisconnectTeam_MemberNameTooLong_ArgumentException() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); var target = new PlanningPokerService(planningPoker.Object); // Act target.DisconnectTeam(TeamName, LongMemberName); } [TestMethod] public void StartEstimation_TeamName_ScrumTeamEstimationIsInProgress() { // Arrange var team = CreateBasicTeam(); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act target.StartEstimation(TeamName); // Verify planningPoker.Verify(); teamLock.Verify(); teamLock.Verify(l => l.Team); Assert.AreEqual<D.TeamState>(D.TeamState.EstimationInProgress, team.State); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void StartEstimation_TeamNameIsEmpty_ArgumentNullException() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); var target = new PlanningPokerService(planningPoker.Object); // Act target.StartEstimation(null); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void StartEstimation_TeamNameTooLong_ArgumentException() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); var target = new PlanningPokerService(planningPoker.Object); // Act target.StartEstimation(LongTeamName); } [TestMethod] public void CancelEstimation_TeamName_ScrumTeamEstimationIsCanceled() { // Arrange var team = CreateBasicTeam(); team.ScrumMaster.StartEstimation(); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act target.CancelEstimation(TeamName); // Verify planningPoker.Verify(); teamLock.Verify(); teamLock.Verify(l => l.Team); Assert.AreEqual<D.TeamState>(D.TeamState.EstimationCanceled, team.State); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void CancelEstimation_TeamNameIsEmpty_ArgumentNullException() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); var target = new PlanningPokerService(planningPoker.Object); // Act target.CancelEstimation(null); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void CancelEstimation_TeamNameTooLong_ArgumentException() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); var target = new PlanningPokerService(planningPoker.Object); // Act target.CancelEstimation(LongTeamName); } [TestMethod] public void SubmitEstimation_TeamNameAndScrumMasterName_EstimationIsSetForScrumMaster() { // Arrange var team = CreateBasicTeam(); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act target.SubmitEstimation(TeamName, ScrumMasterName, 2.0); // Verify planningPoker.Verify(); teamLock.Verify(); teamLock.Verify(l => l.Team); Assert.IsNotNull(team.ScrumMaster.Estimation); Assert.AreEqual<double?>(2.0, team.ScrumMaster.Estimation.Value); } [TestMethod] public void SubmitEstimation_TeamNameAndScrumMasterNameAndMinus1111111_EstimationIsSetToNull() { // Arrange var team = CreateBasicTeam(); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act target.SubmitEstimation(TeamName, ScrumMasterName, -1111111.0); // Verify planningPoker.Verify(); teamLock.Verify(); teamLock.Verify(l => l.Team); Assert.IsNotNull(team.ScrumMaster.Estimation); Assert.IsNull(team.ScrumMaster.Estimation.Value); } [TestMethod] public void SubmitEstimation_TeamNameAndMemberNameAndMinus1111100_EstimationOfMemberIsSetToInfinity() { // Arrange var team = CreateBasicTeam(); var member = (D.Member)team.Join(MemberName, false); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act target.SubmitEstimation(TeamName, MemberName, -1111100.0); // Verify planningPoker.Verify(); teamLock.Verify(); teamLock.Verify(l => l.Team); Assert.IsNotNull(member.Estimation); Assert.IsTrue(double.IsPositiveInfinity(member.Estimation.Value.Value)); } [TestMethod] public void SubmitEstimation_TeamNameAndMemberName_EstimationOfMemberIsSet() { // Arrange var team = CreateBasicTeam(); var member = (D.Member)team.Join(MemberName, false); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act target.SubmitEstimation(TeamName, MemberName, 8.0); // Verify planningPoker.Verify(); teamLock.Verify(); teamLock.Verify(l => l.Team); Assert.IsNotNull(member.Estimation); Assert.AreEqual<double?>(8.0, member.Estimation.Value); } [TestMethod] public void SubmitEstimation_TeamNameAndMemberNameAndMinus1111100_EstimationOfMemberIsSetInifinty() { // Arrange var team = CreateBasicTeam(); var member = (D.Member)team.Join(MemberName, false); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act target.SubmitEstimation(TeamName, MemberName, -1111100.0); // Verify planningPoker.Verify(); teamLock.Verify(); teamLock.Verify(l => l.Team); Assert.IsNotNull(member.Estimation); Assert.IsTrue(double.IsPositiveInfinity(member.Estimation.Value.Value)); } [TestMethod] public void SubmitEstimation_TeamNameAndMemberNameAndMinus1111111_EstimationIsSetToNull() { // Arrange var team = CreateBasicTeam(); var member = (D.Member)team.Join(MemberName, false); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act target.SubmitEstimation(TeamName, MemberName, -1111111.0); // Verify planningPoker.Verify(); teamLock.Verify(); teamLock.Verify(l => l.Team); Assert.IsNotNull(member.Estimation); Assert.IsNull(member.Estimation.Value); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void SubmitEstimation_TeamNameIsEmpty_ArgumentNullException() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); var target = new PlanningPokerService(planningPoker.Object); // Act target.SubmitEstimation(null, MemberName, 0.0); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void SubmitEstimation_MemberNameIsEmpty_ArgumentNullException() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); var target = new PlanningPokerService(planningPoker.Object); // Act target.SubmitEstimation(TeamName, null, 0.0); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void SubmitEstimation_TeamNameTooLong_ArgumentException() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); var target = new PlanningPokerService(planningPoker.Object); // Act target.SubmitEstimation(LongTeamName, MemberName, 1.0); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void SubmitEstimation_MemberNameTooLong_ArgumentException() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); var target = new PlanningPokerService(planningPoker.Object); // Act target.SubmitEstimation(TeamName, LongMemberName, 1.0); } [TestMethod] public async Task GetMessages_MemberJoinedTeam_ScrumMasterGetsMessage() { // Arrange var team = CreateBasicTeam(); var member = team.Join(MemberName, false); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); planningPoker.Setup(p => p.GetMessagesAsync(team.ScrumMaster, It.IsAny<Action<bool, D.Observer>>())) .Callback<D.Observer, Action<bool, D.Observer>>((o, c) => c(true, o)).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act var result = await target.GetMessages(TeamName, ScrumMasterName, 0); // Verify planningPoker.Verify(); teamLock.Verify(); Assert.IsNotNull(result); Assert.AreEqual<int>(1, result.Count); Assert.AreEqual<long>(1, result[0].Id); Assert.AreEqual<MessageType>(MessageType.MemberJoined, result[0].Type); Assert.IsInstanceOfType(result[0], typeof(MemberMessage)); var memberMessage = (MemberMessage)result[0]; Assert.IsNotNull(memberMessage.Member); Assert.AreEqual<string>(MemberName, memberMessage.Member.Name); } [TestMethod] public async Task GetMessages_EstimationEnded_ScrumMasterGetsMessages() { // Arrange var team = CreateBasicTeam(); var member = (D.Member)team.Join(MemberName, false); var master = team.ScrumMaster; master.StartEstimation(); master.Estimation = new D.Estimation(1.0); member.Estimation = new D.Estimation(2.0); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); planningPoker.Setup(p => p.GetMessagesAsync(master, It.IsAny<Action<bool, D.Observer>>())) .Callback<D.Observer, Action<bool, D.Observer>>((o, c) => c(true, o)).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act var result = await target.GetMessages(TeamName, ScrumMasterName, 1); // Verify planningPoker.Verify(); teamLock.Verify(); Assert.IsNotNull(result); Assert.AreEqual<int>(4, result.Count); Assert.AreEqual<long>(2, result[0].Id); Assert.AreEqual<MessageType>(MessageType.EstimationStarted, result[0].Type); Assert.AreEqual<long>(3, result[1].Id); Assert.AreEqual<MessageType>(MessageType.MemberEstimated, result[1].Type); Assert.AreEqual<long>(4, result[2].Id); Assert.AreEqual<MessageType>(MessageType.MemberEstimated, result[2].Type); Assert.AreEqual<long>(5, result[3].Id); Assert.AreEqual<MessageType>(MessageType.EstimationEnded, result[3].Type); Assert.IsInstanceOfType(result[3], typeof(EstimationResultMessage)); var estimationResultMessage = (EstimationResultMessage)result[3]; Assert.IsNotNull(estimationResultMessage.EstimationResult); var expectedResult = new Tuple<string, double>[] { new Tuple<string, double>(ScrumMasterName, 1.0), new Tuple<string, double>(MemberName, 2.0) }; CollectionAssert.AreEquivalent(expectedResult, estimationResultMessage.EstimationResult.Select(i => new Tuple<string, double>(i.Member.Name, i.Estimation.Value.Value)).ToList()); } [TestMethod] public async Task GetMessages_NoMessagesOnTime_ReturnsEmptyCollection() { // Arrange var team = CreateBasicTeam(); var teamLock = CreateTeamLock(team); var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); planningPoker.Setup(p => p.GetScrumTeam(TeamName)).Returns(teamLock.Object).Verifiable(); planningPoker.Setup(p => p.GetMessagesAsync(team.ScrumMaster, It.IsAny<Action<bool, D.Observer>>())) .Callback<D.Observer, Action<bool, D.Observer>>((o, c) => c(false, null)).Verifiable(); var target = new PlanningPokerService(planningPoker.Object); // Act var result = await target.GetMessages(TeamName, ScrumMasterName, 0); // Verify planningPoker.Verify(); Assert.IsNotNull(result); Assert.AreEqual<int>(0, result.Count); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public async Task GetMessages_TeamNameIsEmpty_ArgumentNullException() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); var target = new PlanningPokerService(planningPoker.Object); // Act await target.GetMessages(null, MemberName, 0); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public async Task GetMessages_MemberNameIsEmpty_ArgumentNullException() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); var target = new PlanningPokerService(planningPoker.Object); // Act await target.GetMessages(TeamName, null, 0); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public async Task GetMessages_TeamNameTooLong_ArgumentException() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); var target = new PlanningPokerService(planningPoker.Object); // Act await target.GetMessages(LongTeamName, MemberName, 0); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public async Task GetMessages_MemberNameTooLong_ArgumentException() { // Arrange var planningPoker = new Mock<D.IPlanningPoker>(MockBehavior.Strict); var target = new PlanningPokerService(planningPoker.Object); // Act await target.GetMessages(TeamName, LongMemberName, 0); } private static D.ScrumTeam CreateBasicTeam() { var result = new D.ScrumTeam(TeamName); result.SetScrumMaster(ScrumMasterName); return result; } private static Mock<D.IScrumTeamLock> CreateTeamLock(D.ScrumTeam scrumTeam) { var result = new Mock<D.IScrumTeamLock>(MockBehavior.Strict); result.Setup(l => l.Team).Returns(scrumTeam); result.Setup(l => l.Lock()).Verifiable(); result.Setup(l => l.Dispose()).Verifiable(); return result; } } }
40.305578
190
0.621264
[ "MIT" ]
msawczyn/planningpoker4azure
test/Duracellko.PlanningPoker.Test/Service/PlanningPokerServiceTest.cs
49,860
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Microsoft.Owin.Infrastructure; namespace Microsoft.Owin { /// <summary> /// A wrapper for the response Set-Cookie header /// </summary> public class ResponseCookieCollection { /// <summary> /// Create a new wrapper /// </summary> /// <param name="headers"></param> public ResponseCookieCollection(IHeaderDictionary headers) { if (headers == null) { throw new ArgumentNullException("headers"); } Headers = headers; } private IHeaderDictionary Headers { get; set; } /// <summary> /// Add a new cookie and value /// </summary> /// <param name="key"></param> /// <param name="value"></param> public void Append(string key, string value) { Headers.AppendValues(Constants.Headers.SetCookie, Uri.EscapeDataString(key) + "=" + Uri.EscapeDataString(value) + "; path=/"); } /// <summary> /// Add a new cookie /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="options"></param> public void Append(string key, string value, CookieOptions options) { if (options == null) { throw new ArgumentNullException("options"); } bool domainHasValue = !string.IsNullOrEmpty(options.Domain); bool pathHasValue = !string.IsNullOrEmpty(options.Path); bool expiresHasValue = options.Expires.HasValue; string setCookieValue = string.Concat( Uri.EscapeDataString(key), "=", Uri.EscapeDataString(value ?? string.Empty), !domainHasValue ? null : "; domain=", !domainHasValue ? null : options.Domain, !pathHasValue ? null : "; path=", !pathHasValue ? null : options.Path, !expiresHasValue ? null : "; expires=", !expiresHasValue ? null : options.Expires.Value.ToString("ddd, dd-MMM-yyyy HH:mm:ss ", CultureInfo.InvariantCulture) + "GMT", !options.Secure ? null : "; secure", !options.HttpOnly ? null : "; HttpOnly"); Headers.AppendValues("Set-Cookie", setCookieValue); } /// <summary> /// Sets an expired cookie /// </summary> /// <param name="key"></param> public void Delete(string key) { Func<string, bool> predicate = value => value.StartsWith(key + "=", StringComparison.OrdinalIgnoreCase); var deleteCookies = new[] { Uri.EscapeDataString(key) + "=; expires=Thu, 01-Jan-1970 00:00:00 GMT" }; IList<string> existingValues = Headers.GetValues(Constants.Headers.SetCookie); if (existingValues == null || existingValues.Count == 0) { Headers.SetValues(Constants.Headers.SetCookie, deleteCookies); } else { Headers.SetValues(Constants.Headers.SetCookie, existingValues.Where(value => !predicate(value)).Concat(deleteCookies).ToArray()); } } /// <summary> /// Sets an expired cookie /// </summary> /// <param name="key"></param> /// <param name="options"></param> public void Delete(string key, CookieOptions options) { if (options == null) { throw new ArgumentNullException("options"); } bool domainHasValue = !string.IsNullOrEmpty(options.Domain); bool pathHasValue = !string.IsNullOrEmpty(options.Path); Func<string, bool> rejectPredicate; if (domainHasValue) { rejectPredicate = value => value.StartsWith(key + "=", StringComparison.OrdinalIgnoreCase) && value.IndexOf("domain=" + options.Domain, StringComparison.OrdinalIgnoreCase) != -1; } else if (pathHasValue) { rejectPredicate = value => value.StartsWith(key + "=", StringComparison.OrdinalIgnoreCase) && value.IndexOf("path=" + options.Path, StringComparison.OrdinalIgnoreCase) != -1; } else { rejectPredicate = value => value.StartsWith(key + "=", StringComparison.OrdinalIgnoreCase); } IList<string> existingValues = Headers.GetValues(Constants.Headers.SetCookie); if (existingValues != null) { Headers.SetValues(Constants.Headers.SetCookie, existingValues.Where(value => !rejectPredicate(value)).ToArray()); } Append(key, string.Empty, new CookieOptions { Path = options.Path, Domain = options.Domain, Expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), }); } } }
37.535211
145
0.545779
[ "Apache-2.0" ]
15901213541/-OAuth2.0
src/Microsoft.Owin/ResponseCookieCollection.cs
5,332
C#
using Exadel.CrazyPrice.Common.Models; using Exadel.CrazyPrice.Common.Models.Option; using Exadel.CrazyPrice.WebApi.Extentions; using FluentValidation; namespace Exadel.CrazyPrice.WebApi.Validators { public class CompanyValidator : AbstractValidator<Company> { public CompanyValidator() { CascadeMode = CascadeMode.Stop; RuleSet("Company", () => { RuleFor(x => x.Name) .NotEmpty() .MinimumLength(3) .MaximumLength(200) .ValidCharacters(CharOptions.Letter | CharOptions.Number | CharOptions.Punctuation | CharOptions.Symbol, " ,.-"); RuleFor(x => x.Description) .NotEmpty() .MinimumLength(3) .MaximumLength(2000) .ValidCharacters(CharOptions.Letter | CharOptions.Number | CharOptions.Punctuation | CharOptions.Symbol, " ,.-"); RuleFor(x => x.Mail) .NotEmpty() .MinimumLength(6) .MaximumLength(50) .EmailAddress() .NotContainsSpace(); }); } } }
33.976744
65
0.443532
[ "BSD-3-Clause" ]
ssivazhalezau/exadel_discounts_be
src/Exadel.CrazyPrice/Exadel.CrazyPrice.WebApi/Validators/CompanyValidator.cs
1,463
C#
using Neo.Network.P2P.Payloads; using System; namespace Neo.Wallets { public class BalanceEventArgs : EventArgs { public Transaction Transaction; public UInt160[] RelatedAccounts; public uint? Height; public uint Time; } }
19.214286
45
0.66171
[ "MIT" ]
NewEconoLab/neo-cli-node
neo/Wallets/BalanceEventArgs.cs
271
C#
//********************************************************************************** //* Copyright (C) 2007,2016 Hitachi Solutions,Ltd. //********************************************************************************** #region Apache License // // 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 //********************************************************************************** //* クラス名 :EventLogWin32 //* クラス日本語名 :イベントログ関連Win32 API宣言クラス //* //* 作成者 :生技 西野 //* 更新履歴 : //* //* 日時 更新者 内容 //* ---------- ---------------- ------------------------------------------------- //* 2012/09/21 西野 大介 新規作成 //* 2013/02/18 西野 大介 SetLastError対応 //********************************************************************************** using System; using System.Runtime.InteropServices; namespace Touryo.Infrastructure.Public.Win32 { class EventLogWin32 { /// <summary>イベントログの登録済みハンドルを返します。</summary> /// <param name="lpUNCServerName"> /// 操作を実行するサーバの名前 /// (NULLを指定でローカルコンピュータ) /// </param> /// <param name="lpSourceName"> /// 登録済みハンドルを取得するイベントソースの名前 /// HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Application /// </param> /// <returns> /// イベントログの登録済みハンドル /// </returns> [DllImport("advapi32.dll", SetLastError = true)] public static extern IntPtr RegisterEventSource(string lpUNCServerName, string lpSourceName); /// <summary>指定したイベントログのハンドルを閉じます。</summary> /// <param name="hEventLog"> /// イベントログの登録済みハンドル /// (RegisterEventSource 関数が返すハンドル) /// </param> /// <returns> /// true:関数が成功 /// false:関数が失敗 /// </returns> [DllImport("advapi32.dll", SetLastError = true)] public static extern bool DeregisterEventSource(IntPtr hEventLog); /// <summary>指定したイベントログの最後にエントリを書き込みます。</summary> /// <param name="hEventLog">イベントログのハンドル</param> /// <param name="wType">ログに書き込むイベントの種類</param> /// <param name="wCategory">イベントの分類</param> /// <param name="dwEventID">イベント識別子</param> /// <param name="lpUserSid">ユーザーセキュリティ識別子</param> /// <param name="wNumStrings">メッセージにマージする文字列の数</param> /// <param name="dwDataSize">バイナリデータのサイズ(バイト数)</param> /// <param name="lpStrings">メッセージにマージする文字列の配列</param> /// <param name="lpRawData">バイナリデータのアドレス</param> /// <returns> /// true:関数が成功 /// false:関数が失敗 /// </returns> [DllImport("advapi32.dll", EntryPoint = "ReportEventW", CharSet = CharSet.Unicode, SetLastError=true)] public static extern bool ReportEvent( IntPtr hEventLog, ushort wType, ushort wCategory, int dwEventID, IntPtr lpUserSid, ushort wNumStrings, int dwDataSize, string[] lpStrings, IntPtr lpRawData); } }
37.210526
110
0.538331
[ "Apache-2.0" ]
OpenTouryoProject/OpenTouryo
root/programs/CS/Frameworks/Infrastructure/Public/Win32/EventLogWin32.cs
4,255
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("CodeFactory.VisualStudio.Configuration")] [assembly: AssemblyDescription("Internal library used by CodeFactory automation.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("CodeFactory LLC")] [assembly: AssemblyProduct("CodeFactory.VisualStudio.Configuration")] [assembly: AssemblyCopyright("Copyright © 2020 CodeFactory LLC")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a6eb6ee0-b2f9-4412-8f43-92595fa1fa57")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.20230.1")]
41.27027
84
0.761624
[ "MIT" ]
CodeFactoryLLC/CodeFactoryDocs
src/CodeFactoryVisualStudio/CodeFactory.VisualStudio.Configuration/Properties/AssemblyInfo.cs
1,530
C#
namespace Rebus.NewRelicApi { using Config; using Pipeline; using Pipeline.Receive; public static class NewRelicTraceIncomingStepExtensions { public static void AddNewRelicIncomingStep(this OptionsConfigurer optionsConfiguration) { optionsConfiguration.Decorate<IPipeline>(context => { var onWorkflowItemCompletedStep = new NewRelicTraceIncomingStep(); var pipeline = context.Get<IPipeline>(); return new PipelineStepInjector(pipeline) .OnReceive(onWorkflowItemCompletedStep, PipelineRelativePosition.Before, typeof(DispatchIncomingMessageStep)); }); } } }
33.409091
95
0.638095
[ "MIT" ]
P47Phoenix/Rebus.AwsSnsAndSqs
Rebus.NewRelic/NewRelicTraceIncomingStepExtensions.cs
737
C#
using System.Threading.Tasks; using Shouldly; using Xunit; namespace Homely.Storage.Blobs.Tests { public class DeleteAsyncTests : CommonTestSetup { [Fact] public async Task GivenAnExistingBlob_DeleteAsync_DeletesTheBlob() { // Arrange. var azureBlob = await GetAzureBlobAsync(); // Act. await azureBlob.DeleteAsync(TestClassInstanceName); // Assert. var user = await azureBlob.GetAsync<SomeFakeUser>(TestClassInstanceName, default); user.ShouldBeNull(); } [Fact] public async Task GivenAnMissingBlob_DeleteAsync_DoesNotThrowAnError() { // Arrange. var azureBlob = await GetAzureBlobAsync(); const string blobName = "aaa"; // Act. await azureBlob.DeleteAsync(blobName); // Assert. var user = await azureBlob.GetAsync<SomeFakeUser>(blobName, default); user.ShouldBeNull(); } } }
27.615385
95
0.570102
[ "MIT" ]
PureKrome/Homely.Storage.Blobs
tests/Homely.Storage.Blobs.Tests/DeleteAsyncTests.cs
1,077
C#
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using Mono.Cecil; using System; using System.Collections.Generic; using System.Linq; using Unity.CecilTools; using Unity.CecilTools.Extensions; namespace Unity.SerializationLogic { internal class GenericInstanceHolder { public int Count; public IGenericInstance GenericInstance; } public class TypeResolver { private readonly IGenericInstance _typeDefinitionContext; private readonly IGenericInstance _methodDefinitionContext; private readonly Dictionary<string, GenericInstanceHolder> _context = new Dictionary<string, GenericInstanceHolder>(); public TypeResolver() { } public TypeResolver(IGenericInstance typeDefinitionContext) { _typeDefinitionContext = typeDefinitionContext; } public TypeResolver(GenericInstanceMethod methodDefinitionContext) { _methodDefinitionContext = methodDefinitionContext; } public TypeResolver(IGenericInstance typeDefinitionContext, IGenericInstance methodDefinitionContext) { _typeDefinitionContext = typeDefinitionContext; _methodDefinitionContext = methodDefinitionContext; } public void Add(GenericInstanceType genericInstanceType) { Add(ElementTypeFor(genericInstanceType).FullName, genericInstanceType); } public void Remove(GenericInstanceType genericInstanceType) { Remove(genericInstanceType.ElementType.FullName, genericInstanceType); } public void Add(GenericInstanceMethod genericInstanceMethod) { Add(ElementTypeFor(genericInstanceMethod).FullName, genericInstanceMethod); } private static MemberReference ElementTypeFor(TypeSpecification genericInstanceType) { return genericInstanceType.ElementType; } private static MemberReference ElementTypeFor(MethodSpecification genericInstanceMethod) { return genericInstanceMethod.ElementMethod; } public void Remove(GenericInstanceMethod genericInstanceMethod) { Remove(genericInstanceMethod.ElementMethod.FullName, genericInstanceMethod); } public TypeReference Resolve(TypeReference typeReference) { var genericParameter = typeReference as GenericParameter; if (genericParameter != null) { var resolved = ResolveGenericParameter(genericParameter); if (genericParameter == resolved) // Resolving failed, return what we have. return resolved; return Resolve(resolved); } var arrayType = typeReference as ArrayType; if (arrayType != null) return new ArrayType(Resolve(arrayType.ElementType), arrayType.Rank); var pointerType = typeReference as PointerType; if (pointerType != null) return new PointerType(Resolve(pointerType.ElementType)); var byReferenceType = typeReference as ByReferenceType; if (byReferenceType != null) return new ByReferenceType(Resolve(byReferenceType.ElementType)); var genericInstanceType = typeReference as GenericInstanceType; if (genericInstanceType != null) { var newGenericInstanceType = new GenericInstanceType(Resolve(genericInstanceType.ElementType)); foreach (var genericArgument in genericInstanceType.GenericArguments) newGenericInstanceType.GenericArguments.Add(Resolve(genericArgument)); return newGenericInstanceType; } var pinnedType = typeReference as PinnedType; if (pinnedType != null) return new PinnedType(Resolve(pinnedType.ElementType)); var reqModifierType = typeReference as RequiredModifierType; if (reqModifierType != null) return Resolve(reqModifierType.ElementType); var optModifierType = typeReference as OptionalModifierType; if (optModifierType != null) return new OptionalModifierType(Resolve(optModifierType.ModifierType), Resolve(optModifierType.ElementType)); var sentinelType = typeReference as SentinelType; if (sentinelType != null) return new SentinelType(Resolve(sentinelType.ElementType)); var funcPtrType = typeReference as FunctionPointerType; if (funcPtrType != null) throw new NotSupportedException("Function pointer types are not supported by the SerializationWeaver"); if (typeReference is TypeSpecification) throw new NotSupportedException(); return typeReference; } private TypeReference ResolveGenericParameter(GenericParameter genericParameter) { if (genericParameter.Owner == null) throw new NotSupportedException(); var memberReference = genericParameter.Owner as MemberReference; if (memberReference == null) throw new NotSupportedException(); var key = memberReference.FullName; if (!_context.ContainsKey(key)) { if (genericParameter.Type == GenericParameterType.Type) { if (_typeDefinitionContext != null) return _typeDefinitionContext.GenericArguments[genericParameter.Position]; return genericParameter; } if (_methodDefinitionContext != null) return _methodDefinitionContext.GenericArguments[genericParameter.Position]; return genericParameter; } return GenericArgumentAt(key, genericParameter.Position); } private TypeReference GenericArgumentAt(string key, int position) { return _context[key].GenericInstance.GenericArguments[position]; } private void Add(string key, IGenericInstance value) { GenericInstanceHolder oldValue; if (_context.TryGetValue(key, out oldValue)) { var memberReference = value as MemberReference; if (memberReference == null) throw new NotSupportedException(); var storedValue = (MemberReference)oldValue.GenericInstance; if (storedValue.FullName != memberReference.FullName) throw new ArgumentException("Duplicate key!", "key"); oldValue.Count++; return; } _context.Add(key, new GenericInstanceHolder { Count = 1, GenericInstance = value }); } private void Remove(string key, IGenericInstance value) { GenericInstanceHolder oldValue; if (_context.TryGetValue(key, out oldValue)) { var memberReference = value as MemberReference; if (memberReference == null) throw new NotSupportedException(); var storedValue = (MemberReference)oldValue.GenericInstance; if (storedValue.FullName != memberReference.FullName) throw new ArgumentException("Invalid value!", "value"); oldValue.Count--; if (oldValue.Count == 0) _context.Remove(key); return; } throw new ArgumentException("Invalid key!", "key"); } } public static class UnitySerializationLogic { public static bool WillUnitySerialize(FieldDefinition fieldDefinition) { return WillUnitySerialize(fieldDefinition, new TypeResolver(null)); } public static bool WillUnitySerialize(FieldDefinition fieldDefinition, TypeResolver typeResolver) { if (fieldDefinition == null) return false; //skip static, const and NotSerialized fields before even checking the type if (fieldDefinition.IsStatic || IsConst(fieldDefinition) || fieldDefinition.IsNotSerialized || fieldDefinition.IsInitOnly) return false; // The field must have correct visibility/decoration to be serialized. if (!fieldDefinition.IsPublic && !ShouldHaveHadAllFieldsPublic(fieldDefinition) && !HasSerializeFieldAttribute(fieldDefinition) && !HasSerializeReferenceAttribute(fieldDefinition)) return false; // Don't try to resolve types that come from Windows assembly, // as serialization weaver will fail to resolve that (due to it being in platform specific SDKs) if (ShouldNotTryToResolve(fieldDefinition.FieldType)) return false; if (IsFixedBuffer(fieldDefinition)) return true; // Resolving types is more complex and slower than checking their names or attributes, // thus keep those checks below var typeReference = typeResolver.Resolve(fieldDefinition.FieldType); //the type of the field must be serializable in the first place. if (typeReference.MetadataType == MetadataType.String) return true; if (typeReference.IsValueType) return IsValueTypeSerializable(typeReference); if (typeReference is ArrayType || CecilUtils.IsGenericList(typeReference)) { if (!HasSerializeReferenceAttribute(fieldDefinition)) return IsSupportedCollection(typeReference); } if (!IsReferenceTypeSerializable(typeReference) && !HasSerializeReferenceAttribute(fieldDefinition)) return false; if (IsDelegate(typeReference)) return false; return true; } private static bool IsDelegate(TypeReference typeReference) { return typeReference.IsAssignableTo("System.Delegate"); } public static bool ShouldFieldBePPtrRemapped(FieldDefinition fieldDefinition) { return ShouldFieldBePPtrRemapped(fieldDefinition, new TypeResolver(null)); } public static bool ShouldFieldBePPtrRemapped(FieldDefinition fieldDefinition, TypeResolver typeResolver) { if (!WillUnitySerialize(fieldDefinition, typeResolver)) return false; return CanTypeContainUnityEngineObjectReference(typeResolver.Resolve(fieldDefinition.FieldType)); } private static bool CanTypeContainUnityEngineObjectReference(TypeReference typeReference) { if (IsUnityEngineObject(typeReference)) return true; if (typeReference.IsEnum()) return false; if (IsSerializablePrimitive(typeReference)) return false; if (IsSupportedCollection(typeReference)) return CanTypeContainUnityEngineObjectReference(CecilUtils.ElementTypeOfCollection(typeReference)); var definition = typeReference.Resolve(); if (definition == null) return false; return HasFieldsThatCanContainUnityEngineObjectReferences(definition, new TypeResolver(typeReference as GenericInstanceType)); } private static bool HasFieldsThatCanContainUnityEngineObjectReferences(TypeDefinition definition, TypeResolver typeResolver) { return AllFieldsFor(definition, typeResolver).Where(kv => kv.Value.Resolve(kv.Key.FieldType).Resolve() != definition).Any(kv => CanFieldContainUnityEngineObjectReference(definition, kv.Key, kv.Value)); } private static IEnumerable<KeyValuePair<FieldDefinition, TypeResolver>> AllFieldsFor(TypeDefinition definition, TypeResolver typeResolver) { var baseType = definition.BaseType; if (baseType != null) { var genericBaseInstanceType = baseType as GenericInstanceType; if (genericBaseInstanceType != null) typeResolver.Add(genericBaseInstanceType); foreach (var kv in AllFieldsFor(baseType.Resolve(), typeResolver)) yield return kv; if (genericBaseInstanceType != null) typeResolver.Remove(genericBaseInstanceType); } foreach (var fieldDefinition in definition.Fields) yield return new KeyValuePair<FieldDefinition, TypeResolver>(fieldDefinition, typeResolver); } private static bool CanFieldContainUnityEngineObjectReference(TypeReference typeReference, FieldDefinition t, TypeResolver typeResolver) { if (typeResolver.Resolve(t.FieldType) == typeReference) return false; if (!WillUnitySerialize(t, typeResolver)) return false; if (UnityEngineTypePredicates.IsUnityEngineValueType(typeReference)) return false; return true; } private static bool IsConst(FieldDefinition fieldDefinition) { return fieldDefinition.IsLiteral && !fieldDefinition.IsInitOnly; } public static bool HasSerializeFieldAttribute(FieldDefinition field) { //return FieldAttributes(field).Any(UnityEngineTypePredicates.IsSerializeFieldAttribute); foreach (var attribute in FieldAttributes(field)) if (UnityEngineTypePredicates.IsSerializeFieldAttribute(attribute)) return true; return false; } public static bool HasSerializeReferenceAttribute(FieldDefinition field) { foreach (var attribute in FieldAttributes(field)) if (UnityEngineTypePredicates.IsSerializeReferenceAttribute(attribute)) return true; return false; } private static IEnumerable<TypeReference> FieldAttributes(FieldDefinition field) { return field.CustomAttributes.Select(_ => _.AttributeType); } public static bool ShouldNotTryToResolve(TypeReference typeReference) { var typeReferenceScopeName = typeReference.Scope.Name; if (typeReferenceScopeName == "Windows") { return true; } if (typeReferenceScopeName == "mscorlib") { var resolved = typeReference.Resolve(); return resolved == null; } try { // This will throw an exception if typereference thinks it's referencing a .dll, // but actually there's .winmd file in the current directory. RRW will fix this // at a later step, so we will not try to resolve this type. This is OK, as any // type defined in a winmd cannot be serialized. typeReference.Resolve(); } catch { return true; } return false; } private static bool IsFieldTypeSerializable(TypeReference typeReference, FieldDefinition fieldDefinition) { return IsTypeSerializable(typeReference) || IsSupportedCollection(typeReference) || IsFixedBuffer(fieldDefinition); } private static bool IsValueTypeSerializable(TypeReference typeReference) { if (typeReference.IsPrimitive) return IsSerializablePrimitive(typeReference); return UnityEngineTypePredicates.IsSerializableUnityStruct(typeReference) || typeReference.IsEnum() || ShouldImplementIDeserializable(typeReference); } private static bool IsReferenceTypeSerializable(TypeReference typeReference) { if (typeReference.MetadataType == MetadataType.String) return IsSerializablePrimitive(typeReference); if (IsGenericDictionary(typeReference)) return false; if (IsUnityEngineObject(typeReference) || ShouldImplementIDeserializable(typeReference) || UnityEngineTypePredicates.IsSerializableUnityClass(typeReference)) return true; return false; } private static bool IsTypeSerializable(TypeReference typeReference) { if (typeReference.MetadataType == MetadataType.String) return true; if (typeReference.IsValueType) return IsValueTypeSerializable(typeReference); return IsReferenceTypeSerializable(typeReference); } private static bool IsGenericDictionary(TypeReference typeReference) { var current = typeReference; if (current != null) { if (CecilUtils.IsGenericDictionary(current)) return true; } return false; } public static bool IsFixedBuffer(FieldDefinition fieldDefinition) { return GetFixedBufferAttribute(fieldDefinition) != null; } public static CustomAttribute GetFixedBufferAttribute(FieldDefinition fieldDefinition) { if (!fieldDefinition.HasCustomAttributes) return null; return fieldDefinition.CustomAttributes.SingleOrDefault(a => a.AttributeType.FullName == "System.Runtime.CompilerServices.FixedBufferAttribute"); } public static int GetFixedBufferLength(FieldDefinition fieldDefinition) { var fixedBufferAttribute = GetFixedBufferAttribute(fieldDefinition); if (fixedBufferAttribute == null) throw new ArgumentException(string.Format("Field '{0}' is not a fixed buffer field.", fieldDefinition.FullName)); var size = (Int32)fixedBufferAttribute.ConstructorArguments[1].Value; return size; } public static int PrimitiveTypeSize(TypeReference type) { switch (type.MetadataType) { case MetadataType.Boolean: case MetadataType.Byte: case MetadataType.SByte: return 1; case MetadataType.Char: case MetadataType.Int16: case MetadataType.UInt16: return 2; case MetadataType.Int32: case MetadataType.UInt32: case MetadataType.Single: return 4; case MetadataType.Int64: case MetadataType.UInt64: case MetadataType.Double: return 8; default: throw new ArgumentException(string.Format("Unsupported {0}", type.MetadataType)); } } private static bool IsSerializablePrimitive(TypeReference typeReference) { switch (typeReference.MetadataType) { case MetadataType.SByte: case MetadataType.Byte: case MetadataType.Char: case MetadataType.Int16: case MetadataType.UInt16: case MetadataType.Int64: case MetadataType.UInt64: case MetadataType.Int32: case MetadataType.UInt32: case MetadataType.Single: case MetadataType.Double: case MetadataType.Boolean: case MetadataType.String: return true; } return false; } public static bool IsSupportedCollection(TypeReference typeReference) { if (!(typeReference is ArrayType || CecilUtils.IsGenericList(typeReference))) return false; // We don't support arrays like byte[,] etc if (typeReference.IsArray && ((ArrayType)typeReference).Rank > 1) return false; return IsTypeSerializable(CecilUtils.ElementTypeOfCollection(typeReference)); } private static bool ShouldHaveHadAllFieldsPublic(FieldDefinition field) { return UnityEngineTypePredicates.IsUnityEngineValueType(field.DeclaringType); } private static bool IsUnityEngineObject(TypeReference typeReference) { return UnityEngineTypePredicates.IsUnityEngineObject(typeReference); } public static bool IsNonSerialized(TypeReference typeDeclaration) { if (typeDeclaration == null) return true; if (typeDeclaration.HasGenericParameters) return true; if (typeDeclaration.MetadataType == MetadataType.Object) return true; var fullName = typeDeclaration.FullName; if (fullName.StartsWith("System.")) //can this be done better? return true; if (typeDeclaration.IsArray) return true; if (typeDeclaration.FullName == UnityEngineTypePredicates.MonoBehaviour) return true; if (typeDeclaration.FullName == UnityEngineTypePredicates.ScriptableObject) return true; if (typeDeclaration.IsEnum()) return true; return false; } public static bool ShouldImplementIDeserializable(TypeReference typeDeclaration) { if (typeDeclaration.FullName == "UnityEngine.ExposedReference`1") return true; if (IsNonSerialized(typeDeclaration)) return false; try { if (UnityEngineTypePredicates.ShouldHaveHadSerializableAttribute(typeDeclaration)) return true; var resolvedTypeDeclaration = typeDeclaration.CheckedResolve(); if (resolvedTypeDeclaration.IsValueType) { return resolvedTypeDeclaration.IsSerializable && !resolvedTypeDeclaration.CustomAttributes.Any(a => a.AttributeType.FullName.Contains("System.Runtime.CompilerServices.CompilerGenerated")); } else { return (resolvedTypeDeclaration.IsSerializable && !resolvedTypeDeclaration.CustomAttributes.Any(a => a.AttributeType.FullName.Contains("System.Runtime.CompilerServices.CompilerGenerated"))) || resolvedTypeDeclaration.IsSubclassOf(UnityEngineTypePredicates.MonoBehaviour, UnityEngineTypePredicates.ScriptableObject); } } catch (Exception) { return false; } } } }
37.998366
213
0.61776
[ "MIT" ]
K0lb3/TypeTreeGenerator
TypeTreeGenerator/Unity.SerializationLogic/UnitySerializationLogic.cs
23,255
C#
using System; using Newtonsoft.Json.Linq; namespace CryptoExchange.Net.Sockets { /// <summary> /// Socket subscription /// </summary> public class SocketSubscription { /// <summary> /// Exception event /// </summary> public event Action<Exception>? Exception; /// <summary> /// Message handlers for this subscription. Should return true if the message is handled and should not be distributed to the other handlers /// </summary> public Action<SocketConnection, JToken> MessageHandler { get; set; } /// <summary> /// Request object /// </summary> public object? Request { get; set; } /// <summary> /// Subscription identifier /// </summary> public string? Identifier { get; set; } /// <summary> /// Is user subscription or generic /// </summary> public bool UserSubscription { get; set; } /// <summary> /// If the subscription has been confirmed /// </summary> public bool Confirmed { get; set; } private SocketSubscription(object? request, string? identifier, bool userSubscription, Action<SocketConnection, JToken> dataHandler) { UserSubscription = userSubscription; MessageHandler = dataHandler; Request = request; Identifier = identifier; } /// <summary> /// Create SocketSubscription for a request /// </summary> /// <param name="request"></param> /// <param name="userSubscription"></param> /// <param name="dataHandler"></param> /// <returns></returns> public static SocketSubscription CreateForRequest(object request, bool userSubscription, Action<SocketConnection, JToken> dataHandler) { return new SocketSubscription(request, null, userSubscription, dataHandler); } /// <summary> /// Create SocketSubscription for an identifier /// </summary> /// <param name="identifier"></param> /// <param name="userSubscription"></param> /// <param name="dataHandler"></param> /// <returns></returns> public static SocketSubscription CreateForIdentifier(string identifier, bool userSubscription, Action<SocketConnection, JToken> dataHandler) { return new SocketSubscription(null, identifier, userSubscription, dataHandler); } /// <summary> /// Invoke the exception event /// </summary> /// <param name="e"></param> public void InvokeExceptionHandler(Exception e) { Exception?.Invoke(e); } } }
33.385542
148
0.580296
[ "MIT" ]
1Konto/CryptoExchange.Net
CryptoExchange.Net/Sockets/SocketSubscription.cs
2,773
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ngDemo.Migrator")] [assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("880b3591-e057-46fe-b525-10bd83828b93")]
41.368421
84
0.777354
[ "MIT" ]
TruthLiAng/ng_NetCore
src/ngDemo.Migrator/Properties/AssemblyInfo.cs
788
C#
using System; using System.Globalization; using System.Windows; using System.Windows.Controls.Primitives; namespace Swiddler.Behaviors { public static class TextBox { public static bool GetSelectAllText(System.Windows.Controls.TextBox textBox) => (bool)textBox.GetValue(SelectAllTextProperty); public static void SetSelectAllText(System.Windows.Controls.TextBox textBox, bool value) => textBox.SetValue(SelectAllTextProperty, value); public static readonly DependencyProperty SelectAllTextProperty = DependencyProperty.RegisterAttached("SelectAllText", typeof(bool), typeof(TextBox), new UIPropertyMetadata(false, OnSelectAllTextChanged)); private static void OnSelectAllTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { // https://stackoverflow.com/questions/660554/how-to-automatically-select-all-text-on-focus-in-wpf-textbox if (d is TextBoxBase textBox) { if (e.NewValue is bool == true) { textBox.GotFocus += SelectAll; textBox.PreviewMouseDown += IgnoreMouseButton; } else { textBox.GotFocus -= SelectAll; textBox.PreviewMouseDown -= IgnoreMouseButton; } } } private static void SelectAll(object sender, RoutedEventArgs e) { (e.OriginalSource as TextBoxBase)?.SelectAll(); } private static void IgnoreMouseButton(object sender, System.Windows.Input.MouseButtonEventArgs e) { if (sender is TextBoxBase textBox) { if (!textBox.IsReadOnly && textBox.IsKeyboardFocusWithin) return; e.Handled = true; textBox.Focus(); } } public static string GetNumericRange(System.Windows.Controls.TextBox textBox) => (string)textBox.GetValue(NumericRangeProperty); public static void SetNumericRange(System.Windows.Controls.TextBox textBox, string value) => textBox.SetValue(NumericRangeProperty, value); public static readonly DependencyProperty NumericRangeProperty = DependencyProperty.RegisterAttached("NumericRange", typeof(string), typeof(TextBox), new UIPropertyMetadata(OnNumericRangeChanged)); private static void OnNumericRangeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is TextBoxBase textBox) { if (e.NewValue is string value) { var vals = value.Split(' '); if (vals.Length == 2) { if (int.TryParse(vals[0], out var n1) && int.TryParse(vals[1], out var n2)) { new NumericRangeHandler(textBox) { MinValue = n1, MaxValue = n2 }; } } } } } class NumericRangeHandler { public int MinValue { get; set; } public int MaxValue { get; set; } System.Windows.Controls.TextBox textBox; string oldText; int oldCaret, oldSelectionStart, oldSelectionLen; public NumericRangeHandler(TextBoxBase textBox) { this.textBox = (System.Windows.Controls.TextBox)textBox; textBox.PreviewTextInput += OnPreviewTextInput; textBox.TextChanged += OnTextChanged; DataObject.AddPastingHandler(textBox, PastingHandler); oldText = this.textBox.Text; } private void OnTextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e) { if (!string.IsNullOrEmpty(textBox.Text)) // allow empty { if (int.TryParse(textBox.Text, out var num) == false || num < MinValue || num > MaxValue) { //textBox.Text = Math.Max(Math.Min(num, MaxValue), MinValue).ToString(CultureInfo.InvariantCulture); textBox.Text = oldText; textBox.CaretIndex = oldCaret; textBox.SelectionStart = oldSelectionStart; textBox.SelectionLength= oldSelectionLen; } } oldText = textBox.Text; } void PastingHandler(object sender, DataObjectPastingEventArgs e) { StoreOldState(); } void OnPreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e) { StoreOldState(); if (int.TryParse(e.Text, out var _) == false) e.Handled = true; } void StoreOldState() { oldCaret = textBox.CaretIndex; oldSelectionStart = textBox.SelectionStart; oldSelectionLen = textBox.SelectionLength; } } } }
36.706294
147
0.560678
[ "Apache-2.0" ]
ihonliu/Swiddler
Source/Swiddler/Behaviors/TextBox.cs
5,251
C#
using CoreDocker.Api.GraphQl; using CoreDocker.Dal.Models.Auth; using CoreDocker.Shared.Models.Projects; using HotChocolate.Types; namespace CoreDocker.Api.Components.Projects { public class ProjectsMutationType : ObjectType<ProjectsMutation> { protected override void Configure(IObjectTypeDescriptor<ProjectsMutation> descriptor) { Name = "ProjectsMutation"; descriptor.Field(t => t.Create(default(ProjectCreateUpdateModel))) .Description("Add a project.") .RequirePermission(Activity.UpdateProject); descriptor.Field(t => t.Update(default(string), default(ProjectCreateUpdateModel))) .Description("Update a project.") .RequirePermission(Activity.UpdateProject); descriptor.Field(t => t.Remove(default(string))) .Description("Permanently remove a project.") .RequirePermission(Activity.DeleteProject); } } } /* scaffolding [ { "FileName": "DefaultMutation.cs", "Indexline": "using CoreDocker.Api.Components.Projects;", "InsertAbove": false, "InsertInline": false, "Lines": [ "using CoreDocker.Api.Components.Projects;" ] }, { "FileName": "DefaultMutation.cs", "Indexline": "ProjectsMutationType", "InsertAbove": false, "InsertInline": false, "Lines": [ "Field<ProjectsMutationType>(\"projects\", resolve: context => Task.BuildFromHttpContext(new object()));" ] } ] scaffolding */
32.791667
113
0.632783
[ "Apache-2.0" ]
rolfwessels/CoreDocker
src/CoreDocker.Api/Components/Projects/ProjectsMutationType.cs
1,576
C#
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.IO; namespace AccessBridgeExplorer.Utils.Settings { /// <summary> /// Abstraction over a central dictionary of settings, with eventing model /// for load/save/changes. /// </summary> public interface IUserSettings { event EventHandler<ErrorEventArgs> Error; event EventHandler Loaded; event EventHandler Saving; event EventHandler<SettingValueChangedEventArgs> ValueChanged; string GetValue(string key, string defaultValue); void SetValue(string key, string defaultValue, string value); void Load(); void Save(); void Clear(); } }
34.888889
77
0.713376
[ "Apache-2.0" ]
Nfactor26/access-bridge-explorer
src/AccessBridgeExplorer/Utils/Settings/IUserSettings.cs
1,256
C#
//----------------------------------------------------------------------------- // Copyright 2000-2022 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com) // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: Apache-2.0 //----------------------------------------------------------------------------- /*---------------------------------------------------------------------------*/ /* CSharpServiceGenerator.cc (C) 2000-2007 */ /* */ /* Classe générant le code de la classe de base d'un service. */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ using System; using System.IO; using System.Collections; using Integer = System.Int32; namespace Arcane.Axl { /** * Classe générant le code de la classe de base d'un service. */ public class CSharpServiceGenerator : CSharpCodeGenerator { /** Objet stockant les informations de l'élément XML "service". */ private ServiceInfo m_info; /** Générateur des fichiers "CaseOptions.h" et "CaseOptions.cc". */ private CSharpCaseOptionsGenerator m_co_generator; /** Nom du fichier xml contenant la description des options. */ private string m_case_options_xml_file_name; public CSharpServiceGenerator(string path, string output_path, ServiceInfo info) : base(path, output_path) { m_info = info; m_class_name = "Arcane" + m_info.Name + "Object"; m_co_generator = new CSharpCaseOptionsGenerator(path, m_output_path, m_info.Name, m_info.NamespaceMacroName, m_info.NamespaceName, m_info.Version, m_info.Options, m_info.AlternativeNames, m_info.NotCaseOption); m_case_options_xml_file_name = m_info.Name; m_case_options_xml_file_name += "_"; m_case_options_xml_file_name += path; } public override void writeFile() { if (HasTests) Console.WriteLine("WARNING: Balise <tests> non prise en compte avec le langage C#."); //double version = m_info.m_version; _writeClassFile(m_info.Name + "_axl.cs", null, false); // generation du fichier CaseOptions if (m_co_generator!=null) m_co_generator.writeFile(); TextWriter file_stream = new StringWriter(); WriteInfo(file_stream); WriteComments(file_stream); bool has_namespace = !string.IsNullOrEmpty(m_info.NamespaceName); if (has_namespace) { file_stream.Write("namespace " + m_info.NamespaceName + "{\n"); } // Ajoute un attribut pour indiquer au compilateur Arcane de ne pas generer de version // C++ de cette classe puisqu'il existe un axl.h correspondant file_stream.Write("public abstract class " + m_class_name + "\n"); file_stream.Write(": " + ConvertNamespace(m_info.ParentName) + "\n"); //for (Integer i = 0, iss = m_info.m_interfaces.Count; i < iss; ++i) { foreach(ServiceInfo.Interface itf in m_info.Interfaces){ if (itf.IsInherited) file_stream.Write(", " + ConvertNamespace(itf.Name) + "\n"); } file_stream.Write("{\n"); file_stream.Write(" public static Arcane.ServiceInfo serviceInfoCreateFunction(string name)\n"); file_stream.Write(" {\n"); file_stream.Write(" Arcane.ServiceInfo si = Arcane.ServiceInfo.Create(name,(int)(Arcane.ServiceType.{0}));\n",m_info.ServiceType); file_stream.Write(" si.SetCaseOptionsFileName(\"" + m_case_options_xml_file_name + "\");\n"); //for (Integer i = 0, iss = m_info.m_interfaces.Count; i < iss; ++i) { foreach(ServiceInfo.Interface itf in m_info.Interfaces){ file_stream.Write(" si.AddImplementedInterface(\"" + itf.Name + "\");\n"); } file_stream.Write(" si.SetAxlVersion(" + m_info.Version + ");\n"); { string service_lower_case_name = Utils.ToLowerWithDash(m_info.Name); file_stream.Write(" si.SetDefaultTagName(\"" + service_lower_case_name + "\");\n"); foreach (DictionaryEntry de in m_info.AlternativeNames.m_names) { string key = (string)de.Key; string value = (string)de.Value; file_stream.Write(" si.SetTagName(\"" + key + "\",\"" + value + "\");\n"); } } file_stream.Write(" return si;\n"); file_stream.Write(" }\n"); { // Génère une fabrique au nouveau format pour créér les instances de ce service. file_stream.Write(" public static Arcane.IServiceFactory2 CreateFactory(Arcane.GenericServiceFactory gsf)\n"); file_stream.Write(" { return new Arcane.AxlGeneratedServiceFactory(gsf); }\n"); } // Constructeur { file_stream.Write(" public " + m_class_name + "(Arcane.ServiceBuildInfo sbi)\n"); file_stream.Write(": base(sbi)\n"); file_stream.Write("{\n"); if (m_co_generator!=null) { file_stream.Write(" m_options = null;\n"); } _WriteVariablesConstructor(m_info.VariableInfoList,"sbi.Mesh()",file_stream); if (m_co_generator!=null) { string co_file_name = m_path; co_file_name += "_"; co_file_name += m_info.Name; if (m_info.NotCaseOption) { file_stream.Write(" m_options = new " + m_co_generator.getClassName() + "(sbi.SubDomain().CaseMng());\n"); } else { file_stream.Write(" Arcane.ICaseOptions co = sbi.CaseOptions();\n"); file_stream.Write(" if (co!=null){\n"); file_stream.Write(" m_options = new " + m_co_generator.getClassName() + "(sbi.SubDomain().CaseMng(),co);\n"); file_stream.Write(" }\n"); } } file_stream.Write("}\n"); } if (m_co_generator!=null) { file_stream.Write(" //! Options du jeu de données du module\n"); file_stream.Write(" public " + m_co_generator.getClassName() + " Options { get { return m_options; } }\n"); file_stream.Write("\n"); file_stream.Write(" //! Options du jeu de données du module\n"); file_stream.Write(" private " + m_co_generator.getClassName() + " m_options;\n\n"); } _WriteVariablesDeclaration(m_info.VariableInfoList,file_stream); file_stream.Write("};\n"); file_stream.Write("\n"); WriteComments(file_stream); if (has_namespace) { file_stream.Write("}\n"); } WriteComments(file_stream); // write file _writeClassFile(m_info.Name + "_axl.cs", file_stream.ToString(), true); } private bool HasTests { get { return m_info.m_tests_info != null && m_info.m_tests_info.m_test_info_list.Count > 0; } } } }
42.80814
139
0.546109
[ "Apache-2.0" ]
AlexlHer/framework
axlstar/Arcane.Axl/Arcane.Axl.Generator.CSharp/CSharpServiceGenerator.cs
7,377
C#
using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; namespace IFSMobileApp.iOS { public class Application { // This is the main entry point of the application. static void Main(string[] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. UIApplication.Main(args, null, "AppDelegate"); } } }
23.047619
91
0.634298
[ "MIT" ]
miroshkin/ifs-mobile-app
IFSMobileApp/IFSMobileApp/IFSMobileApp.iOS/Main.cs
486
C#
using System.Threading.Tasks; namespace FoodOnline.Application.Common.Interfaces { public interface IIdentityService { Task<string> GetUsernameAsync(string userId); } }
21.111111
53
0.736842
[ "MIT" ]
panoukos41/FoodOnline
src/Application/Common/Interfaces/IIdentityService.cs
192
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using Newtonsoft.Json; using PetHouse.MVC.Models; namespace PetHouse.MVC.Controllers { [CustomAuthorize] public class AdoptanteController : BasePadronController { // GET: Adoptante public async Task<ActionResult> Index() { var result = await GetAsync("api/Adoptante"); if (result.IsSuccessStatusCode) { var resultdata = result.Content.ReadAsStringAsync().Result; List<Adoptante> adoptantes = JsonConvert.DeserializeObject<List<Adoptante>>(resultdata); adoptantes = adoptantes.FindAll(adoptante => adoptante.Mascotas.Count() > 0); return View(adoptantes); } ViewData["Error"] = await ErrorAsync("Adoptante", "Index", "Error al consultar api", 500); return HttpNotFound(); } // GET: Adoptante/Details/5 public async Task<ActionResult> Details(int? id) { if (id == null) { ViewData["Error"] = await ErrorAsync("Adoptante", "Details", "No se ingreso el Id", 400); return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var result = await GetAsync("api/Adoptante/" + id.Value); Adoptante adoptante = null; if (result.IsSuccessStatusCode) { var resultdata = result.Content.ReadAsStringAsync().Result; adoptante = JsonConvert.DeserializeObject<Adoptante>(resultdata); } if (adoptante == null) { ViewData["Error"] = await ErrorAsync("Adoptante", "Details", "Error al consultar api", 404); return HttpNotFound(); } return View(adoptante); } // GET: Adoptante/Edit/5 public async Task<ActionResult> Edit(int? id) { if (id == null) { ViewData["Error"] = await ErrorAsync("Adoptante", "Edit", "No se ingreso el Id", 400); return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var result = await GetAsync("api/Adoptante/" + id.Value); Adoptante adoptante = null; if (result.IsSuccessStatusCode) { var resultdata = result.Content.ReadAsStringAsync().Result; adoptante = JsonConvert.DeserializeObject<Adoptante>(resultdata); } if (adoptante == null) { ViewData["Error"] = await ErrorAsync("Adoptante", "Edit", "Error al consultar api", 404); return HttpNotFound(); } await SetDomicilio(adoptante.Domicilio.ProvinciaId, adoptante.Domicilio.CantonId); return View(adoptante); } // POST: Adoptante/Edit/5 // Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que desea enlazarse. Para obtener // más información vea https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Edit([Bind(Include = "Id,Identificacion,Nombre,Primer_Apellido,Segundo_Apellido,Fecha_Nacimiento,Telefono,Correo,DomicilioId,Domicilio")] Adoptante adoptante) { if (ModelState.IsValid) { var resultDomicilio = await PutAsync("api/Domicilio/" + adoptante.DomicilioId, adoptante.Domicilio); if (resultDomicilio.IsSuccessStatusCode) { var result = await PutAsync("api/Adoptante/" + adoptante.Id, adoptante); if (result.IsSuccessStatusCode) return RedirectToAction("Index"); } } await SetDomicilio(adoptante.Domicilio.ProvinciaId, adoptante.Domicilio.CantonId); ViewData["Error"] = await ErrorAsync("Adoptante", "Edit", "Error actualizar adoptante compruebe los campos", 400); return View(adoptante); } } }
41.153846
198
0.592056
[ "MIT" ]
dabakura/PetHouse
PetHouse/PetHouse.MVC/Controllers/AdoptanteController.cs
4,286
C#
using UnityEngine; namespace ShineEngine { /** 推送基类 */ [Hotfix(needChildren = false)] public class BaseRequest:BaseData { /** 是否写过type */ private bool _maked=false; /** 是否写过type */ private bool _writed=false; /** 是否需要构造复制(默认复制,不必复制的地方自己设置) */ private bool _needMakeCopy=true; /** 是否需要回收 */ private bool _needRelease=false; /** 是否在断开连时不缓存 */ private bool _needCacheOnDisConnect=true; /** 是否需要完整写入 */ private bool _needFullWrite=false; /** 是否为长消息 */ private bool _needMessageLong=false; /** 写入缓存流 */ private BytesWriteStream _stream; /** 此次的号 */ public int sendMsgIndex=0; /** 是否已发送 */ public volatile bool sended=false; /** 发送时间 */ public long sendTime; public BaseRequest() { } /** 设置不在构造时拷贝 */ protected void setDontCopy() { _needMakeCopy=false; } protected void setDontCache() { _needCacheOnDisConnect=false; } protected void setNeedRelease() { _needRelease=true; } public bool needRelease() { return _needRelease; } /** 是否需要在断开连接时缓存 */ public bool needCacheOnDisConnect() { return _needCacheOnDisConnect; } /** 设置是否需要在构造时拷贝 */ protected void setNeedMakeCopy(bool value) { _needMakeCopy=value; } /** 设置是否需要完整写入 */ public void setNeedFullWrite(bool value) { _needFullWrite=value; } /** 设置为长消息 */ protected void setLongMessage() { _needMessageLong=true; } /** 构造(制造数据副本) */ protected void make() { if(_maked) return; _maked=true; if(_needMakeCopy) { copyData(); } } /** 把数据拷贝下 */ protected virtual void copyData() { } /** 执行写入到流 */ protected virtual void doWriteToStream(BytesWriteStream stream) { //写协议体 doWriteBytesSimple(stream); } /** 执行写入 */ protected virtual void doWriteBytesSimple(BytesWriteStream stream) { beforeWrite(); if(_needFullWrite) writeBytesFull(stream); else writeBytesSimple(stream); } /// <summary> /// 写出字节流(直接写的话不必再构造) /// </summary> public void write() { if(_writed) return; //视为构造完成 _maked=true; _writed=true; _stream=BytesWriteStreamPool.create(); _stream.setWriteLenLimit(getMessageLimit()); doWriteToStream(_stream); } public BytesWriteStream getWriteStream() { return _stream; } /// <summary> /// 直接写出byte[](sendAbs用) /// </summary> /// <returns></returns> public byte[] writeToBytes() { write(); return _stream.getByteArray(); } /// <summary> /// 写到流里 /// </summary> public void writeToStream(BytesWriteStream stream) { if(_writed) { stream.writeBytesStream(_stream,0,_stream.length()); } else { doWriteToStream(stream); } } //send public int getMessageLimit() { return ShineSetting.getMsgBufSize(_needMessageLong); } /** 预备推送(系统用) */ public void preSend() { //构造一下 make(); } public void dispose() { _maked=false; _writed=false; _stream=null; sended=false; sendMsgIndex=-1; } public bool released=false; /** 执行释放(主线程) */ public void doRelease() { if(!ShineSetting.messageUsePool) return; //还没发送,就跳过回收 if(!sended) { Ctrl.warnLog("出现一次Request释放时还没发送的情况",getDataID()); return; } if(released) { Ctrl.errorLog("析构了两次"); } released=true; BytesControl.releaseRequest(this); } } }
14.854626
68
0.632266
[ "Apache-2.0" ]
hw233/home3
core/client/game/src/shine/net/base/BaseRequest.cs
3,848
C#
#if CSHARP_7_OR_LATER || (UNITY_2018_3_OR_NEWER && (NET_STANDARD_2_0 || NET_4_6)) #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member using System.Collections.Generic; using System.Threading; using UnityEngine; using UnityEngine.EventSystems; namespace UniRx.Async.Triggers { [DisallowMultipleComponent] public class AsyncScrollTrigger : AsyncTriggerBase { AsyncTriggerPromise<PointerEventData> onScroll; AsyncTriggerPromiseDictionary<PointerEventData> onScrolls; protected override IEnumerable<ICancelablePromise> GetPromises() { return Concat(onScroll, onScrolls); } void OnScroll(PointerEventData eventData) { TrySetResult(onScroll, onScrolls, eventData); } public UniTask OnScrollAsync(CancellationToken cancellationToken = default(CancellationToken)) { return GetOrAddPromise(ref onScroll, ref onScrolls, cancellationToken); } } } #endif
25.595238
103
0.682791
[ "MIT" ]
317392507/QFramework
Assets/QFramework/Framework/0.Core/Plugins/UniRx/Async/Triggers/AsyncScrollTrigger.cs
1,075
C#
/****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using System.Linq; using System.Collections.Generic; namespace Leap.Unity.GraphicalRenderer { [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class LeapGraphicTagAttribute : Attribute { private static Dictionary<Type, LeapGraphicTagAttribute> _tagCache = new Dictionary<Type, LeapGraphicTagAttribute>(); private static Dictionary<string, Type> _stringTypeCache = new Dictionary<string, Type>(); public readonly string name; public readonly int order; public LeapGraphicTagAttribute(string name, int order = 0) { this.name = name; this.order = order; } public static string GetTagName(Type type) { var tag = GetTag(type); return tag == null ? type.Name : tag.name; } public static string GetTagName(string typeName) { var tag = GetTag(typeName); return tag == null ? typeName : tag.name; } public static LeapGraphicTagAttribute GetTag(Type type) { LeapGraphicTagAttribute tag; if (!_tagCache.TryGetValue(type, out tag)) { object[] attributes = type.GetCustomAttributes(typeof(LeapGraphicTagAttribute), inherit: true); if (attributes.Length == 1) { tag = attributes[0] as LeapGraphicTagAttribute; } _tagCache[type] = tag; } return tag; } public static LeapGraphicTagAttribute GetTag(string typeName) { Type type; if (!_stringTypeCache.TryGetValue(typeName, out type)) { type = typeof(LeapGraphicTagAttribute).Assembly.GetTypes().FirstOrDefault(t => t.Name == typeName); _stringTypeCache[typeName] = type; } if (type == null) { return null; } else { return GetTag(type); } } } }
35.776119
121
0.585732
[ "MIT" ]
LHuss/capstone
Virtual Modeller/Assets/ThirdParty/LeapMotion/Modules/GraphicRenderer/Scripts/Utility/LeapGraphicTagAttribute.cs
2,397
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Online.Chat; using osu.Game.Users; using osuTK; using System; using System.Linq; using osu.Framework.Graphics.Containers; using osu.Game.Graphics.Containers; using osu.Game.Overlays.Chat; namespace osu.Game.Tests.Visual.Online { public class TestSceneStandAloneChatDisplay : OsuTestScene { private readonly Channel testChannel = new Channel(); private readonly User admin = new User { Username = "HappyStick", Id = 2, Colour = "f2ca34" }; private readonly User redUser = new User { Username = "BanchoBot", Id = 3, }; private readonly User blueUser = new User { Username = "Zallius", Id = 4, }; private readonly User longUsernameUser = new User { Username = "Very Long Long Username", Id = 5, }; [Cached] private ChannelManager channelManager = new ChannelManager(); private readonly TestStandAloneChatDisplay chatDisplay; private readonly TestStandAloneChatDisplay chatDisplay2; public TestSceneStandAloneChatDisplay() { Add(channelManager); Add(chatDisplay = new TestStandAloneChatDisplay { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Margin = new MarginPadding(20), Size = new Vector2(400, 80) }); Add(chatDisplay2 = new TestStandAloneChatDisplay(true) { Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, Margin = new MarginPadding(20), Size = new Vector2(400, 150) }); } protected override void LoadComplete() { base.LoadComplete(); channelManager.CurrentChannel.Value = testChannel; chatDisplay.Channel.Value = testChannel; chatDisplay2.Channel.Value = testChannel; int sequence = 0; AddStep("message from admin", () => testChannel.AddNewMessages(new Message(sequence++) { Sender = admin, Content = "I am a wang!" })); AddStep("message from team red", () => testChannel.AddNewMessages(new Message(sequence++) { Sender = redUser, Content = "I am team red." })); AddStep("message from team red", () => testChannel.AddNewMessages(new Message(sequence++) { Sender = redUser, Content = "I plan to win!" })); AddStep("message from team blue", () => testChannel.AddNewMessages(new Message(sequence++) { Sender = blueUser, Content = "Not on my watch. Prepare to eat saaaaaaaaaand. Lots and lots of saaaaaaand." })); AddStep("message from admin", () => testChannel.AddNewMessages(new Message(sequence++) { Sender = admin, Content = "Okay okay, calm down guys. Let's do this!" })); AddStep("message from long username", () => testChannel.AddNewMessages(new Message(sequence++) { Sender = longUsernameUser, Content = "Hi guys, my new username is lit!" })); AddStep("message with new date", () => testChannel.AddNewMessages(new Message(sequence++) { Sender = longUsernameUser, Content = "Message from the future!", Timestamp = DateTimeOffset.Now })); AddUntilStep("ensure still scrolled to bottom", () => chatDisplay.ScrolledToBottom); const int messages_per_call = 10; AddRepeatStep("add many messages", () => { for (int i = 0; i < messages_per_call; i++) { testChannel.AddNewMessages(new Message(sequence++) { Sender = longUsernameUser, Content = "Many messages! " + Guid.NewGuid(), Timestamp = DateTimeOffset.Now }); } }, Channel.MAX_HISTORY / messages_per_call + 5); AddAssert("Ensure no adjacent day separators", () => { var indices = chatDisplay.FillFlow.OfType<DrawableChannel.DaySeparator>().Select(ds => chatDisplay.FillFlow.IndexOf(ds)); foreach (var i in indices) { if (i < chatDisplay.FillFlow.Count && chatDisplay.FillFlow[i + 1] is DrawableChannel.DaySeparator) return false; } return true; }); AddUntilStep("ensure still scrolled to bottom", () => chatDisplay.ScrolledToBottom); } private class TestStandAloneChatDisplay : StandAloneChatDisplay { public TestStandAloneChatDisplay(bool textbox = false) : base(textbox) { } protected DrawableChannel DrawableChannel => InternalChildren.OfType<DrawableChannel>().First(); protected OsuScrollContainer ScrollContainer => (OsuScrollContainer)((Container)DrawableChannel.Child).Child; public FillFlowContainer FillFlow => (FillFlowContainer)ScrollContainer.Child; public bool ScrolledToBottom => ScrollContainer.IsScrolledToEnd(1); } } }
34.357955
138
0.531503
[ "MIT" ]
AaqibAhamed/osu
osu.Game.Tests/Visual/Online/TestSceneStandAloneChatDisplay.cs
5,872
C#
namespace Boilerplate.Common.Keycloak { public class KeycloakSettings { public string ClientId { get; set; } public string ClientSecret { get; set; } public string RealmName { get; set; } public string KeycloakBaseUrl { get; set; } public string TokenUrl { get; set; } public string UserByUsernameUrl { get; set; } public string UserServiceUrl { get; set; } public string UserServiceAppName { get; set; } public string UserServiceAppKey { get; set; } } }
31.823529
54
0.630314
[ "MIT" ]
bssgroupgenova/Extensions
common/Boilerplate.Common/Keycloak/KeycloakSettings.cs
543
C#
/* * 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 securityhub-2018-10-26.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.SecurityHub.Model { /// <summary> /// This is the response object from the DeleteInsight operation. /// </summary> public partial class DeleteInsightResponse : AmazonWebServiceResponse { private string _insightArn; /// <summary> /// Gets and sets the property InsightArn. /// <para> /// The ARN of the insight that was deleted. /// </para> /// </summary> [AWSProperty(Required=true)] public string InsightArn { get { return this._insightArn; } set { this._insightArn = value; } } // Check to see if InsightArn property is set internal bool IsSetInsightArn() { return this._insightArn != null; } } }
29.034483
109
0.658551
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/SecurityHub/Generated/Model/DeleteInsightResponse.cs
1,684
C#
global using System; global using System.Collections; global using System.Collections.Concurrent; global using System.Collections.Generic; global using System.Linq; global using System.Reflection; global using System.Text; global using System.Threading; global using System.Threading.Tasks; global using Venflow;
28.545455
43
0.834395
[ "Apache-2.0" ]
T0shik/Venflow
src/Venflow/Properties/GlobalUsings.cs
316
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("02. Circle Area (Precision 12)")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("02. Circle Area (Precision 12)")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e633c218-ecd4-476e-a16e-a61962150711")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.72973
84
0.7418
[ "MIT" ]
AneliaDoychinova/Programming-Fundamentals
04. Data Types and Variables/Lab Data Types and Variables/02. Circle Area (Precision 12)/Properties/AssemblyInfo.cs
1,436
C#