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
// %BANNERBEGIN% // --------------------------------------------------------------------- // %COPYRIGHTBEGIN% // <copyright file="MLLocation.cs" company="Magic Leap"> // // Copyright (c) 2018-present, Magic Leap, Inc. All Rights Reserved. // // </copyright> // // %COPYRIGHTEND% // --------------------------------------------------------------------- // %BANNEREND% namespace UnityEngine.XR.MagicLeap { using System; using System.Runtime.InteropServices; #if PLATFORM_LUMIN using UnityEngine.XR.MagicLeap.Native; #endif /// <summary> /// Public represenation of MLIdentityProfile. /// MLIdentityProfile represents a set of attribute of a user's profile. /// </summary> [Obsolete("Use MLIdentity.Profile instead.", true)] public class MLIdentityProfile : MonoBehaviour { #if PLATFORM_LUMIN public delegate void CallbackDelegate(MLResult result); #endif private class Request { public enum State { CREATED, REQUESTING_ATTRIB_NAMES, ATTRIB_NAMES_READY, REQUESTING_ATTRIB_VALUES, ATTRIB_VALUES_READY, DONE } #if PLATFORM_LUMIN //pending future parameter which if set would mean our request to retrieve attribute names //or values is pending and further requests are prevented public MLInvokeFuture PendingFuture; public State RequestState = State.CREATED; public CallbackDelegate Callback; public MLResult.Code Result; #endif } #if PLATFORM_LUMIN /// <summary> /// Public property to check if internal pointer and hence this profile is valid. /// </summary> public bool IsValid { get { return _profilePtr != IntPtr.Zero; } } /// <summary> /// Array of MLIdentityAttributes containing user profile. /// </summary> public MLIdentityAttribute[] Attributes { get; set; } /// <summary> /// Optionally specific attributes to request for this profile. /// </summary> public MLIdentityAttributeKey[] RequestAttributes; /// <summary> /// Internal pointer used to associate the the managed version of this structure /// with the unmanaged pointer that is used by the Identity API to communicate with us. /// </summary> private IntPtr _profilePtr; /// <summary> /// Internal convenience structure which represents the marshaled unmanaged structure /// to communicate with the Identity API. /// </summary> private InternalMLIdentityProfile _profile; /// <summary> /// Request class used to keep track of pending requests for identity data. /// </summary> private Request _request; /// <summary> /// Fetch the specified attributes and callback when result is known. /// </summary> /// <param name="callback"> /// MLResult.Result in callback will be MLResult.Code.Ok if successful. /// MLResult.Result will be MLResult.Code.InvalidParam if failed due to invalid null internal parameter. /// MLResult.Result will be MLResult.Code.UnspecifiedFailure if failed due to internal error. /// MLResult.Result will be MLResult.Code.AllocFailed if failed to allocate memory. /// MLResult.Result will be MLResult.Code.PrivilegeDenied if caller does not have the IdentityRead privilege. /// MLResult.Result will be MLResult.Code.Identity* if an identity specific failure occurred during the operation. /// </param> /// <returns> /// MLResult.Result will be MLResult.Code.Pending if successful (request will be pending). /// MLResult.Result will be MLResult.Code.InvalidParam if failed due to invalid null internal parameter. /// MLResult.Result will be MLResult.Code.UnspecifiedFailure if failed due to internal error. /// MLResult.Result will be MLResult.Code.AllocFailed if failed to allocate memory. /// MLResult.Result will be MLResult.Code.PrivilegeDenied if caller does not have the IdentityRead privilege. /// MLResult.Result will be MLResult.Code.Identity* if an identity specific failure occurred during the operation. /// </returns> public MLResult Fetch(CallbackDelegate callback) { MLResult result; if (_request != null) { result = MLResult.Create(MLResult.Code.UnspecifiedFailure, "Already fetching attributes"); MLPluginLog.ErrorFormat("MLIdentityProfile.Fetch failed. Reason: {0}", result); return result; } // Create a request _request = new Request(); _request.Callback = callback; _request.Result = MLResult.Code.Pending; _request.RequestState = Request.State.REQUESTING_ATTRIB_NAMES; RequestAttributeNamesAsync(_request); // TODO: Map pending resultCode to OK for return value. result = MLResult.Create(_request.Result); return result; } private void Update() { if (_request != null) { ProcessRequest(); } } private void ProcessRequest() { switch (_request.RequestState) { case Request.State.REQUESTING_ATTRIB_NAMES: ProcessPendingAttribNamesRequest(); break; case Request.State.ATTRIB_NAMES_READY: RequestAttributeValuesAsync(_request); _request.RequestState = Request.State.REQUESTING_ATTRIB_VALUES; break; case Request.State.REQUESTING_ATTRIB_VALUES: ProcessPendingAttribValuesRequest(); break; case Request.State.DONE: ProcessDoneRequest(); break; default: //TODO: add error log that this state is unhandled break; } } private void ProcessPendingAttribNamesRequest() { _request.Result = RequestAttributeNamesWait(_request); if (_request.Result != MLResult.Code.Pending && _request.Result != MLResult.Code.Ok) { MLPluginLog.ErrorFormat("MLIdentityProfile.ProcessPendingAttribNamesRequest failed request to retrieve attribute names. Reason: {0}", _request.Result); _request.RequestState = Request.State.DONE; } else if (_request.Result == MLResult.Code.Ok) { if (_profilePtr == IntPtr.Zero || _profile.AttributePtrs == IntPtr.Zero) { _request.RequestState = Request.State.DONE; _request.Result = MLResult.Code.IdentityInvalidInformationFromCloud; MLPluginLog.ErrorFormat("MLIdentityProfile.ProcessPendingAttribNamesRequest failed request to retrieve attribute names. Reason: {0}", _request.Result); } else { _request.RequestState = Request.State.ATTRIB_NAMES_READY; } } } private void ProcessPendingAttribValuesRequest() { _request.Result = RequestAttributeValuesWait(_request); if (_request.Result != MLResult.Code.Pending && _request.Result != MLResult.Code.Ok) { MLPluginLog.ErrorFormat("MLIdentityProfile.ProcessPendingAttribValuesRequest failed request to retrieve attribute values. Reason: {0}", _request.Result); _request.RequestState = Request.State.DONE; } else if (_request.Result == MLResult.Code.Ok) { if (_profilePtr == IntPtr.Zero || _profile.AttributePtrs == IntPtr.Zero) { _request.RequestState = Request.State.DONE; _request.Result = MLResult.Code.IdentityInvalidInformationFromCloud; MLPluginLog.ErrorFormat("MLIdentityProfile.ProcessPendingAttribValuesRequest failed request to retrieve attribute values. Reason: {0}", _request.Result); } else { _request.RequestState = Request.State.DONE; } } } private void ProcessDoneRequest() { Request temp = _request; _request = null; if (temp.Callback != null) { temp.Callback(MLResult.Create(temp.Result)); } temp = null; } [Obsolete("Use GetResultString(MLResult.Code) instead.", true)] private static string GetResultString(MLResultCode result) { return "This function is deprecated. Use MLIdentity.GetResultString(MLResult.Code) instead."; } private static string GetResultString(MLResult.Code result) { return Marshal.PtrToStringAnsi(MLIdentityNativeBindings.MLIdentityGetResultString(result)); } private void RequestAttributeNamesAsync(Request request) { // Make sure we cleanup any previous profile data. Cleanup(); if (RequestAttributes != null && RequestAttributes.Length > 0) { //_request.Result = MLIdentityNativeBindings.MLIdentityGetKnownAttributeNames(RequestAttributes, (uint)RequestAttributes.Length, ref _profilePtr); if (_request.Result == MLResult.Code.Ok) { _profile = (InternalMLIdentityProfile)Marshal.PtrToStructure(_profilePtr, typeof(InternalMLIdentityProfile)); Attributes = new MLIdentityAttribute[_profile.AttributeCount]; for (int i = 0; i < _profile.AttributeCount; i++) { IntPtr offsetPtr = Marshal.ReadIntPtr(new IntPtr(_profile.AttributePtrs.ToInt64() + (Marshal.SizeOf(typeof(IntPtr)) * i))); Attributes[i] = (MLIdentityAttribute)Marshal.PtrToStructure(offsetPtr, typeof(MLIdentityAttribute)); // Set this to true so that we can request the value. Attributes[i].IsRequested = true; } _request.Result = MLResult.Code.Pending; _request.RequestState = Request.State.ATTRIB_NAMES_READY; } else { MLPluginLog.ErrorFormat("MLIdentityProfile.RequestAttributeNamesAsync failed to get known attributes names. Reason: {0}", _request.Result); _request.RequestState = Request.State.DONE; } } else { request.PendingFuture = new MLInvokeFuture(); MLResult.Code getAttributeNamesAsyncResult = MLIdentityNativeBindings.MLIdentityGetAttributeNamesAsync(ref request.PendingFuture._invokeFuturePtr); if (getAttributeNamesAsyncResult == MLResult.Code.PrivilegeDenied) { MLPluginLog.Warning("MLIdentityProfile.RequestAttributeNamesAsync failed request for attribute names. Reason: Caller does not have IdentityRead Privilege."); } else if (getAttributeNamesAsyncResult != MLResult.Code.Ok) { MLPluginLog.ErrorFormat("MLIdentityProfile.RequestAttributeNamesAsync failed request for attribute names. Reason: {0}", getAttributeNamesAsyncResult); } } } private MLResult.Code RequestAttributeNamesWait(Request request) { MLInvokeFuture future = request.PendingFuture; // Attempt to get data if available, 0 is passed as a timeout to immediately return and never wait for results. MLResult.Code result = MLIdentityNativeBindings.MLIdentityGetAttributeNamesWait(future._invokeFuturePtr, 0, ref _profilePtr); // If it succeeded, copy any modifications made to the profile in unmanaged memory by the Identity API to managed memory. if (result == MLResult.Code.Ok) { _profile = (InternalMLIdentityProfile)Marshal.PtrToStructure(_profilePtr, typeof(InternalMLIdentityProfile)); Attributes = new MLIdentityAttribute[_profile.AttributeCount]; for (int i = 0; i < _profile.AttributeCount; i++) { IntPtr offsetPtr = Marshal.ReadIntPtr(new IntPtr(_profile.AttributePtrs.ToInt64() + (Marshal.SizeOf(typeof(IntPtr)) * i))); // Write the unmanaged copy back onto the managed memory we were passed in. Attributes[i] = (MLIdentityAttribute)Marshal.PtrToStructure(offsetPtr, typeof(MLIdentityAttribute)); // Set this to true so that we can request the value. Attributes[i].IsRequested = true; } } return result; } private void RequestAttributeValuesAsync(Request request) { request.PendingFuture = new MLInvokeFuture(); // Copy any modifications made to the profile in managed memory to the unmanaged memory used by the Identity API. for (int i = 0; i < Attributes.Length; i++) { IntPtr offsetPtr = Marshal.ReadIntPtr(new IntPtr(_profile.AttributePtrs.ToInt64() + (Marshal.SizeOf(typeof(IntPtr)) * i))); // Write the managed copy back onto the unmanaged memory we were originally given for it. Marshal.StructureToPtr(Attributes[i], offsetPtr, false); } MLResult.Code requestAttributeValuesAsyncResult = MLIdentityNativeBindings.MLIdentityRequestAttributeValuesAsync(_profilePtr, ref request.PendingFuture._invokeFuturePtr); if (requestAttributeValuesAsyncResult != MLResult.Code.Ok) { MLPluginLog.WarningFormat("MLIdentityProfile.RequestAttributeValuesAsync failed request for attribute values async. Reason: {0}", requestAttributeValuesAsyncResult); } } private MLResult.Code RequestAttributeValuesWait(Request request) { MLInvokeFuture future = request.PendingFuture; // Attempt to get data if available, 0 is passed as a timeout to immediately return and never wait for results. MLResult.Code result = MLIdentityNativeBindings.MLIdentityRequestAttributeValuesWait(future._invokeFuturePtr, 0); // If it succeeded, copy any modifications made to the profile in unmanaged memory by the Identity API to managed memory. if (result == MLResult.Code.Ok) { for (int i = 0; i < _profile.AttributeCount; i++) { IntPtr offsetPtr = Marshal.ReadIntPtr(new IntPtr(_profile.AttributePtrs.ToInt64() + (Marshal.SizeOf(typeof(IntPtr)) * i))); // Write the unmanaged copy back onto the managed memory we were passed in. Attributes[i] = (MLIdentityAttribute)Marshal.PtrToStructure(offsetPtr, typeof(MLIdentityAttribute)); } } return result; } private void OnDestroy() { Cleanup(); } /// ReleaseUserProfile releases all resources associated with the private void Cleanup() { if (IsValid) { // Make the native call with correct internal parameter. MLResult.Code releaseUserProfileResult = MLIdentityNativeBindings.MLIdentityReleaseUserProfile(_profilePtr); if (releaseUserProfileResult != MLResult.Code.Ok) { MLPluginLog.ErrorFormat("MLIdentityProfile.Cleanup failed request to release user profile. Reason: {0}", releaseUserProfileResult); } } // Null the local representation of these pointers as they should have been freed by the call above. _profilePtr = IntPtr.Zero; _profile.AttributePtrs = IntPtr.Zero; _profile.AttributeCount = 0; Attributes = null; } #endif } }
42.531807
182
0.597009
[ "Apache-2.0" ]
kedarshashi/UnityTemplate
Assets/MagicLeap/Lumin/Deprecated/MLIdentityProfile.cs
16,715
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 mediaconvert-2017-08-29.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.MediaConvert.Model { /// <summary> /// Settings specific to Teletext caption sources, including Page number. /// </summary> public partial class TeletextSourceSettings { private string _pageNumber; /// <summary> /// Gets and sets the property PageNumber. Use Page Number (PageNumber) to specify the /// three-digit hexadecimal page number that will be used for Teletext captions. Do not /// use this setting if you are passing through teletext from the input source to output. /// </summary> [AWSProperty(Min=3, Max=3)] public string PageNumber { get { return this._pageNumber; } set { this._pageNumber = value; } } // Check to see if PageNumber property is set internal bool IsSetPageNumber() { return this._pageNumber != null; } } }
32.77193
111
0.655782
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/MediaConvert/Generated/Model/TeletextSourceSettings.cs
1,868
C#
using System.Collections.Generic; using Newtonsoft.Json; using Infobip.Api.Config; using Infobip.Api.Model.Omni.Send; using System; namespace Infobip.Api.Model.Omni.Send { /// <summary> /// This is a generated class and is not intended for modification! /// </summary> public class PushData { [JsonProperty("customPayload")] public IDictionary<string, Object> CustomPayload { get; set; } [JsonProperty("notificationOptions")] public NotificationOptions NotificationOptions { get; set; } [JsonProperty("text")] public string Text { get; set; } [JsonProperty("validityPeriod")] public long? ValidityPeriod { get; set; } [JsonProperty("validityPeriodTimeUnit")] public TimeUnit ValidityPeriodTimeUnit { get; set; } } }
26.645161
71
0.664649
[ "Apache-2.0" ]
MirzaAbazovic/infobip-api-csharp-client
InfobipClient/InfobipClientLib/Infobip/Api/Model/Omni/Send/PushData.cs
826
C#
namespace RealArtists.ShipHub.Common.GitHub.Models.WebhookPayloads { public class PullRequestReviewPayload { public string Action { get; set; } public Review Review { get; set; } public PullRequest PullRequest { get; set; } public Repository Repository { get; set; } public Account Organization { get; set; } public Account Sender { get; set; } } }
34.363636
69
0.701058
[ "MIT" ]
opsroller/shiphub-server
RealArtists.ShipHub.Common/GitHub/Models/WebhookPayloads/PullRequestReviewPayload.cs
380
C#
using System.Data.Common; using System.Data.Entity; using System.Data.Entity.Infrastructure; namespace Coldairarrow.DataRepository { class BaseDbContext : DbContext { public BaseDbContext(DbConnection existingConnection, DbCompiledModel model) : base(existingConnection, model, true) { } } }
21.4375
84
0.696793
[ "MIT" ]
shmilyin/Colder.Fx.Net.AdminLTE
src/Coldairarrow.DataRepository/DbContext/BaseDbContext.cs
345
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Azure.Core; using Azure.Core.Pipeline; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Azure.Security.KeyVault.Keys { /// <summary> /// The KeyClient provides synchronous and asynchronous methods to manage <see cref="KeyVaultKey"/> in the Azure Key Vault. The client /// supports creating, retrieving, updating, deleting, purging, backing up, restoring and listing the <see cref="KeyVaultKey"/>. /// The client also supports listing <see cref="DeletedKey"/> for a soft-delete enabled Azure Key Vault. /// </summary> public class KeyClient { internal const string KeysPath = "/keys/"; internal const string DeletedKeysPath = "/deletedkeys/"; private readonly KeyVaultPipeline _pipeline; private readonly ClientDiagnostics _clientDiagnostics; /// <summary> /// Initializes a new instance of the <see cref="KeyClient"/> class for mocking. /// </summary> protected KeyClient() { } /// <summary> /// Initializes a new instance of the <see cref="KeyClient"/> class for the specified vault. /// </summary> /// <param name="vaultUri">A <see cref="Uri"/> to the vault on which the client operates. Appears as "DNS Name" in the Azure portal.</param> /// <param name="credential">A <see cref="TokenCredential"/> used to authenticate requests to the vault, such as DefaultAzureCredential.</param> /// <exception cref="ArgumentNullException"><paramref name="vaultUri"/> or <paramref name="credential"/> is null.</exception> public KeyClient(Uri vaultUri, TokenCredential credential) : this(vaultUri, credential, null) { } /// <summary> /// Initializes a new instance of the <see cref="KeyClient"/> class for the specified vault. /// </summary> /// <param name="vaultUri">A <see cref="Uri"/> to the vault on which the client operates. Appears as "DNS Name" in the Azure portal.</param> /// <param name="credential">A <see cref="TokenCredential"/> used to authenticate requests to the vault, such as DefaultAzureCredential.</param> /// <param name="options"><see cref="KeyClientOptions"/> that allow to configure the management of the request sent to Key Vault.</param> /// <exception cref="ArgumentNullException"><paramref name="vaultUri"/> or <paramref name="credential"/> is null.</exception> public KeyClient(Uri vaultUri, TokenCredential credential, KeyClientOptions options) { Argument.AssertNotNull(vaultUri, nameof(vaultUri)); Argument.AssertNotNull(credential, nameof(credential)); options ??= new KeyClientOptions(); string apiVersion = options.GetVersionString(); HttpPipeline pipeline = HttpPipelineBuilder.Build(options, new ChallengeBasedAuthenticationPolicy(credential)); _clientDiagnostics = new ClientDiagnostics(options); _pipeline = new KeyVaultPipeline(vaultUri, apiVersion, pipeline, _clientDiagnostics); } /// <summary> /// Gets the <see cref="Uri"/> of the vault used to create this instance of the <see cref="KeyClient"/>. /// </summary> public virtual Uri VaultUri => _pipeline.VaultUri; /// <summary> /// Creates and stores a new key in Key Vault. The create key operation can be used to create any key type in Azure Key Vault. /// If the named key already exists, Azure Key Vault creates a new version of the key. It requires the keys/create permission. /// </summary> /// <param name="name">The name of the key.</param> /// <param name="keyType">The type of key to create. See <see cref="KeyType"/> for valid values.</param> /// <param name="keyOptions">Specific attributes with information about the key.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="ArgumentException"><paramref name="name"/> is an empty string, or <paramref name="keyType"/> contains no value.</exception> /// <exception cref="ArgumentNullException"><paramref name="name"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual Response<KeyVaultKey> CreateKey(string name, KeyType keyType, CreateKeyOptions keyOptions = default, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(name, nameof(name)); Argument.AssertNotDefault(ref keyType, nameof(keyType)); var parameters = new KeyRequestParameters(keyType, keyOptions); using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Keys.KeyClient.CreateKey"); scope.AddAttribute("key", name); scope.Start(); try { return _pipeline.SendRequest(RequestMethod.Post, parameters, () => new KeyVaultKey(name), cancellationToken, KeysPath, name, "/create"); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Creates and stores a new key in Key Vault. The create key operation can be used to create any key type in Azure Key Vault. /// If the named key already exists, Azure Key Vault creates a new version of the key. It requires the keys/create permission. /// </summary> /// <param name="name">The name of the key.</param> /// <param name="keyType">The type of key to create. See <see cref="KeyType"/> for valid values.</param> /// <param name="keyOptions">Specific attributes with information about the key.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="ArgumentException"><paramref name="name"/> is an empty string, or <paramref name="keyType"/> contains no value.</exception> /// <exception cref="ArgumentNullException"><paramref name="name"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual async Task<Response<KeyVaultKey>> CreateKeyAsync(string name, KeyType keyType, CreateKeyOptions keyOptions = default, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(name, nameof(name)); Argument.AssertNotDefault(ref keyType, nameof(keyType)); var parameters = new KeyRequestParameters(keyType, keyOptions); using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Keys.KeyClient.CreateKey"); scope.AddAttribute("key", name); scope.Start(); try { return await _pipeline.SendRequestAsync(RequestMethod.Post, parameters, () => new KeyVaultKey(name), cancellationToken, KeysPath, name, "/create").ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Creates and stores a new Elliptic Curve key in Key Vault. If the named key already exists, /// Azure Key Vault creates a new version of the key. It requires the keys/create permission. /// </summary> /// <param name="ecKeyOptions">The key options object containing information about the Elliptic Curve key being created.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="ArgumentNullException"><paramref name="ecKeyOptions"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual Response<KeyVaultKey> CreateEcKey(CreateEcKeyOptions ecKeyOptions, CancellationToken cancellationToken = default) { Argument.AssertNotNull(ecKeyOptions, nameof(ecKeyOptions)); var parameters = new KeyRequestParameters(ecKeyOptions); using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Keys.KeyClient.CreateEcKey"); scope.AddAttribute("key", ecKeyOptions.Name); scope.Start(); try { return _pipeline.SendRequest(RequestMethod.Post, parameters, () => new KeyVaultKey(ecKeyOptions.Name), cancellationToken, KeysPath, ecKeyOptions.Name, "/create"); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Creates and stores a new Elliptic Curve key in Key Vault. If the named key already exists, /// Azure Key Vault creates a new version of the key. It requires the keys/create permission. /// </summary> /// <param name="ecKeyOptions">The key options object containing information about the Elliptic Curve key being created.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="ArgumentNullException"><paramref name="ecKeyOptions"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual async Task<Response<KeyVaultKey>> CreateEcKeyAsync(CreateEcKeyOptions ecKeyOptions, CancellationToken cancellationToken = default) { Argument.AssertNotNull(ecKeyOptions, nameof(ecKeyOptions)); var parameters = new KeyRequestParameters(ecKeyOptions); using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Keys.KeyClient.CreateEcKey"); scope.AddAttribute("key", ecKeyOptions.Name); scope.Start(); try { return await _pipeline.SendRequestAsync(RequestMethod.Post, parameters, () => new KeyVaultKey(ecKeyOptions.Name), cancellationToken, KeysPath, ecKeyOptions.Name, "/create").ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Creates and stores a new RSA key in Key Vault. If the named key already exists, Azure Key Vault creates a new /// version of the key. It requires the keys/create permission. /// </summary> /// <param name="rsaKeyOptions">The key options object containing information about the RSA key being created.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="ArgumentNullException"><paramref name="rsaKeyOptions"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual Response<KeyVaultKey> CreateRsaKey(CreateRsaKeyOptions rsaKeyOptions, CancellationToken cancellationToken = default) { Argument.AssertNotNull(rsaKeyOptions, nameof(rsaKeyOptions)); var parameters = new KeyRequestParameters(rsaKeyOptions); using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Keys.KeyClient.CreateRsaKey"); scope.AddAttribute("key", rsaKeyOptions.Name); scope.Start(); try { return _pipeline.SendRequest(RequestMethod.Post, parameters, () => new KeyVaultKey(rsaKeyOptions.Name), cancellationToken, KeysPath, rsaKeyOptions.Name, "/create"); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Creates and stores a new RSA key in Key Vault. If the named key already exists, Azure Key Vault creates a new /// version of the key. It requires the keys/create permission. /// </summary> /// <param name="rsaKeyOptions">The key options object containing information about the RSA key being created.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="ArgumentNullException"><paramref name="rsaKeyOptions"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual async Task<Response<KeyVaultKey>> CreateRsaKeyAsync(CreateRsaKeyOptions rsaKeyOptions, CancellationToken cancellationToken = default) { Argument.AssertNotNull(rsaKeyOptions, nameof(rsaKeyOptions)); var parameters = new KeyRequestParameters(rsaKeyOptions); using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Keys.KeyClient.CreateRsaKey"); scope.AddAttribute("key", rsaKeyOptions.Name); scope.Start(); try { return await _pipeline.SendRequestAsync(RequestMethod.Post, parameters, () => new KeyVaultKey(rsaKeyOptions.Name), cancellationToken, KeysPath, rsaKeyOptions.Name, "/create").ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// The update key operation changes specified attributes of a stored key and /// can be applied to any key type and key version stored in Azure Key Vault. /// </summary> /// <remarks> /// In order to perform this operation, the key must already exist in the Key /// Vault. Note: The cryptographic material of a key itself cannot be changed. /// This operation requires the keys/update permission. /// </remarks> /// <param name="properties">The <see cref="KeyProperties"/> object with updated properties.</param> /// <param name="keyOperations">Optional list of supported <see cref="KeyOperation"/>. If null, no changes will be made to existing key operations.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="ArgumentNullException"><paramref name="properties"/> is null, or <see cref="KeyProperties.Version"/> of <paramref name="properties"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual Response<KeyVaultKey> UpdateKeyProperties(KeyProperties properties, IEnumerable<KeyOperation> keyOperations = null, CancellationToken cancellationToken = default) { Argument.AssertNotNull(properties, nameof(properties)); Argument.AssertNotNull(properties.Version, $"{nameof(properties)}.{nameof(properties.Version)}"); var parameters = new KeyRequestParameters(properties, keyOperations); using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Keys.KeyClient.UpdateKeyProperties"); scope.AddAttribute("key", properties.Name); scope.Start(); try { return _pipeline.SendRequest(RequestMethod.Patch, parameters, () => new KeyVaultKey(properties.Name), cancellationToken, KeysPath, properties.Name, "/", properties.Version); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// The update key operation changes specified attributes of a stored key and /// can be applied to any key type and key version stored in Azure Key Vault. /// </summary> /// <remarks> /// In order to perform this operation, the key must already exist in the Key /// Vault. Note: The cryptographic material of a key itself cannot be changed. /// This operation requires the keys/update permission. /// </remarks> /// <param name="properties">The <see cref="KeyProperties"/> object with updated properties.</param> /// <param name="keyOperations">Optional list of supported <see cref="KeyOperation"/>. If null, no changes will be made to existing key operations.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="ArgumentNullException"><paramref name="properties"/> or <paramref name="keyOperations"/> is null, or <see cref="KeyProperties.Version"/> of <paramref name="properties"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual async Task<Response<KeyVaultKey>> UpdateKeyPropertiesAsync(KeyProperties properties, IEnumerable<KeyOperation> keyOperations = null, CancellationToken cancellationToken = default) { Argument.AssertNotNull(properties, nameof(properties)); Argument.AssertNotNull(properties.Version, $"{nameof(properties)}.{nameof(properties.Version)}"); var parameters = new KeyRequestParameters(properties, keyOperations); using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Keys.KeyClient.UpdateKeyProperties"); scope.AddAttribute("key", properties.Name); scope.Start(); try { return await _pipeline.SendRequestAsync(RequestMethod.Patch, parameters, () => new KeyVaultKey(properties.Name), cancellationToken, KeysPath, properties.Name, "/", properties.Version).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Gets the public part of a stored key. /// </summary> /// <remarks> /// The get key operation is applicable to all key types. If the requested key /// is symmetric, then no key is released in the response. This /// operation requires the keys/get permission. /// </remarks> /// <param name="name">The name of the key.</param> /// <param name="version">The version of the key.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="ArgumentException"><paramref name="name"/> is an empty string.</exception> /// <exception cref="ArgumentNullException"><paramref name="name"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual Response<KeyVaultKey> GetKey(string name, string version = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(name, nameof(name)); using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Keys.KeyClient.GetKey"); scope.AddAttribute("key", name); scope.Start(); try { return _pipeline.SendRequest(RequestMethod.Get, () => new KeyVaultKey(name), cancellationToken, KeysPath, name, "/", version); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Gets the public part of a stored key. /// </summary> /// <remarks> /// The get key operation is applicable to all key types. If the requested key /// is symmetric, then no key is released in the response. This /// operation requires the keys/get permission. /// </remarks> /// <param name="name">The name of the key.</param> /// <param name="version">The version of the key.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="ArgumentException"><paramref name="name"/> is an empty string.</exception> /// <exception cref="ArgumentNullException"><paramref name="name"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual async Task<Response<KeyVaultKey>> GetKeyAsync(string name, string version = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(name, nameof(name)); using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Keys.KeyClient.GetKey"); scope.AddAttribute("key", name); scope.Start(); try { return await _pipeline.SendRequestAsync(RequestMethod.Get, () => new KeyVaultKey(name), cancellationToken, KeysPath, name, "/", version).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// List keys in the specified vault. /// </summary> /// <remarks> /// Retrieves a list of the keys in the Key Vault that contains the public part of a stored key. /// The list operation is applicable to all key types, however only the base key identifier, /// attributes, and tags are provided in the response. Individual versions of a /// key are not listed in the response. This operation requires the keys/list /// permission. /// </remarks> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual Pageable<KeyProperties> GetPropertiesOfKeys(CancellationToken cancellationToken = default) { Uri firstPageUri = _pipeline.CreateFirstPageUri(KeysPath); return PageResponseEnumerator.CreateEnumerable(nextLink => _pipeline.GetPage(firstPageUri, nextLink, () => new KeyProperties(), "Azure.Security.KeyVault.Keys.KeyClient.GetPropertiesOfKeys", cancellationToken)); } /// <summary> /// List keys in the specified vault. /// </summary> /// <remarks> /// Retrieves a list of the keys in the Key Vault that contains the public part of a stored key. /// The list operation is applicable to all key types, however only the base key identifier, /// attributes, and tags are provided in the response. Individual versions of a /// key are not listed in the response. This operation requires the keys/list /// permission. /// </remarks> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> public virtual AsyncPageable<KeyProperties> GetPropertiesOfKeysAsync(CancellationToken cancellationToken = default) { Uri firstPageUri = _pipeline.CreateFirstPageUri(KeysPath); return PageResponseEnumerator.CreateAsyncEnumerable(nextLink => _pipeline.GetPageAsync(firstPageUri, nextLink, () => new KeyProperties(), "Azure.Security.KeyVault.Keys.KeyClient.GetPropertiesOfKeys", cancellationToken)); } /// <summary> /// Retrieves a list of individual key versions with the same key name. /// </summary> /// <remarks> /// The full key identifier, attributes, and tags are provided in the response. /// This operation requires the keys/list permission. /// </remarks> /// <param name="name">The name of the key.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="ArgumentException"><paramref name="name"/> is an empty string.</exception> /// <exception cref="ArgumentNullException"><paramref name="name"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual Pageable<KeyProperties> GetPropertiesOfKeyVersions(string name, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(name, nameof(name)); Uri firstPageUri = _pipeline.CreateFirstPageUri($"{KeysPath}{name}/versions"); return PageResponseEnumerator.CreateEnumerable(nextLink => _pipeline.GetPage(firstPageUri, nextLink, () => new KeyProperties(), "Azure.Security.KeyVault.Keys.KeyClient.GetPropertiesOfKeyVersions", cancellationToken)); } /// <summary> /// Retrieves a list of individual key versions with the same key name. /// </summary> /// <remarks> /// The full key identifier, attributes, and tags are provided in the response. /// This operation requires the keys/list permission. /// </remarks> /// <param name="name">The name of the key.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="ArgumentException"><paramref name="name"/> is an empty string.</exception> /// <exception cref="ArgumentNullException"><paramref name="name"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual AsyncPageable<KeyProperties> GetPropertiesOfKeyVersionsAsync(string name, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(name, nameof(name)); Uri firstPageUri = _pipeline.CreateFirstPageUri($"{KeysPath}{name}/versions"); return PageResponseEnumerator.CreateAsyncEnumerable(nextLink => _pipeline.GetPageAsync(firstPageUri, nextLink, () => new KeyProperties(), "Azure.Security.KeyVault.Keys.KeyClient.GetPropertiesOfKeyVersions", cancellationToken)); } /// <summary> /// Gets the public part of a deleted key. /// </summary> /// <remarks> /// The Get Deleted Key operation is applicable for soft-delete enabled vaults. /// While the operation can be invoked on any vault, it will return an error if /// invoked on a non soft-delete enabled vault. This operation requires the /// keys/get permission. /// </remarks> /// <param name="name">The name of the key.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="ArgumentException"><paramref name="name"/> is an empty string.</exception> /// <exception cref="ArgumentNullException"><paramref name="name"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual Response<DeletedKey> GetDeletedKey(string name, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(name, nameof(name)); using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Keys.KeyClient.GetDeletedKey"); scope.AddAttribute("key", name); scope.Start(); try { return _pipeline.SendRequest(RequestMethod.Get, () => new DeletedKey(name), cancellationToken, DeletedKeysPath, name); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Gets the public part of a deleted key. /// </summary> /// <remarks> /// The Get Deleted Key operation is applicable for soft-delete enabled vaults. /// While the operation can be invoked on any vault, it will return an error if /// invoked on a non soft-delete enabled vault. This operation requires the /// keys/get permission. /// </remarks> /// <param name="name">The name of the key.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="ArgumentException"><paramref name="name"/> is an empty string.</exception> /// <exception cref="ArgumentNullException"><paramref name="name"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual async Task<Response<DeletedKey>> GetDeletedKeyAsync(string name, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(name, nameof(name)); using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Keys.KeyClient.GetDeletedKey"); scope.AddAttribute("key", name); scope.Start(); try { return await _pipeline.SendRequestAsync(RequestMethod.Get, () => new DeletedKey(name), cancellationToken, DeletedKeysPath, name).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Deletes a key of any type from storage in Azure Key Vault. /// </summary> /// <remarks> /// The delete key operation cannot be used to remove individual versions of a /// key. This operation removes the cryptographic material associated with the /// key, which means the key is not usable for Sign/Verify, Wrap/Unwrap or /// Encrypt/Decrypt operations. This operation requires the keys/delete /// permission. /// </remarks> /// <param name="name">The name of the key.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns>A <see cref="DeleteKeyOperation"/> to wait on this long-running operation.</returns> /// <exception cref="ArgumentException"><paramref name="name"/> is an empty string.</exception> /// <exception cref="ArgumentNullException"><paramref name="name"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual DeleteKeyOperation StartDeleteKey(string name, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(name, nameof(name)); using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Keys.KeyClient.StartDeleteKey"); scope.AddAttribute("key", name); scope.Start(); try { Response<DeletedKey> response = _pipeline.SendRequest(RequestMethod.Delete, () => new DeletedKey(name), cancellationToken, KeysPath, name); return new DeleteKeyOperation(_pipeline, response); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Deletes a key of any type from storage in Azure Key Vault. /// </summary> /// <remarks> /// The delete key operation cannot be used to remove individual versions of a /// key. This operation removes the cryptographic material associated with the /// key, which means the key is not usable for Sign/Verify, Wrap/Unwrap or /// Encrypt/Decrypt operations. This operation requires the keys/delete /// permission. /// </remarks> /// <param name="name">The name of the key.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns>A <see cref="DeleteKeyOperation"/> to wait on this long-running operation.</returns> /// <exception cref="ArgumentException"><paramref name="name"/> is an empty string.</exception> /// <exception cref="ArgumentNullException"><paramref name="name"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual async Task<DeleteKeyOperation> StartDeleteKeyAsync(string name, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(name, nameof(name)); using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Keys.KeyClient.StartDeleteKey"); scope.AddAttribute("key", name); scope.Start(); try { Response<DeletedKey> response = await _pipeline.SendRequestAsync(RequestMethod.Delete, () => new DeletedKey(name), cancellationToken, KeysPath, name).ConfigureAwait(false); return new DeleteKeyOperation(_pipeline, response); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Lists the deleted keys in the specified vault. /// </summary> /// <remarks> /// Retrieves a list of the keys in the Key Vault that contains the public part of a deleted key. /// This operation includes deletion-specific information. /// The Get Deleted Keys operation is applicable /// for vaults enabled for soft-delete. While the operation can be invoked on /// any vault, it will return an error if invoked on a non soft-delete enabled /// vault. This operation requires the keys/list permission. /// </remarks> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual Pageable<DeletedKey> GetDeletedKeys(CancellationToken cancellationToken = default) { Uri firstPageUri = _pipeline.CreateFirstPageUri(DeletedKeysPath); return PageResponseEnumerator.CreateEnumerable(nextLink => _pipeline.GetPage(firstPageUri, nextLink, () => new DeletedKey(), "Azure.Security.KeyVault.Keys.KeyClient.GetDeletedKeys", cancellationToken)); } /// <summary> /// Lists the deleted keys in the specified vault. /// </summary> /// <remarks> /// Retrieves a list of the keys in the Key Vault that contains the public part of a deleted key. /// This operation includes deletion-specific information. /// The Get Deleted Keys operation is applicable /// for vaults enabled for soft-delete. While the operation can be invoked on /// any vault, it will return an error if invoked on a non soft-delete enabled /// vault. This operation requires the keys/list permission. /// </remarks> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual AsyncPageable<DeletedKey> GetDeletedKeysAsync(CancellationToken cancellationToken = default) { Uri firstPageUri = _pipeline.CreateFirstPageUri(DeletedKeysPath); return PageResponseEnumerator.CreateAsyncEnumerable(nextLink => _pipeline.GetPageAsync(firstPageUri, nextLink, () => new DeletedKey(), "Azure.Security.KeyVault.Keys.KeyClient.GetDeletedKeys", cancellationToken)); } /// <summary> /// Permanently deletes the specified key. /// </summary> /// <remarks> /// The Purge Deleted Key operation is applicable for soft-delete enabled /// vaults. While the operation can be invoked on any vault, it will return an /// error if invoked on a non soft-delete enabled vault. This operation /// requires the keys/purge permission. /// </remarks> /// <param name="name">The name of the key.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="ArgumentException"><paramref name="name"/> is an empty string.</exception> /// <exception cref="ArgumentNullException"><paramref name="name"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual Response PurgeDeletedKey(string name, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(name, nameof(name)); using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Keys.KeyClient.PurgeDeletedKey"); scope.AddAttribute("key", name); scope.Start(); try { return _pipeline.SendRequest(RequestMethod.Delete, cancellationToken, DeletedKeysPath, name); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Permanently deletes the specified key. /// </summary> /// <remarks> /// The Purge Deleted Key operation is applicable for soft-delete enabled /// vaults. While the operation can be invoked on any vault, it will return an /// error if invoked on a non soft-delete enabled vault. This operation /// requires the keys/purge permission. /// </remarks> /// <param name="name">The name of the key.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="ArgumentException"><paramref name="name"/> is an empty string.</exception> /// <exception cref="ArgumentNullException"><paramref name="name"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual async Task<Response> PurgeDeletedKeyAsync(string name, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(name, nameof(name)); using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Keys.KeyClient.PurgeDeletedKey"); scope.AddAttribute("key", name); scope.Start(); try { return await _pipeline.SendRequestAsync(RequestMethod.Delete, cancellationToken, DeletedKeysPath, name).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Recovers the deleted key to its latest version. /// </summary> /// <remarks> /// The Recover Deleted Key operation is applicable for deleted keys in /// soft-delete enabled vaults. It recovers the deleted key back to its latest /// version under /keys. An attempt to recover an non-deleted key will return /// an error. Consider this the inverse of the delete operation on soft-delete /// enabled vaults. This operation requires the keys/recover permission. /// </remarks> /// <param name="name">The name of the key.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns>A <see cref="RecoverDeletedKeyOperation"/> to wait on this long-running operation.</returns> /// <exception cref="ArgumentException"><paramref name="name"/> is an empty string.</exception> /// <exception cref="ArgumentNullException"><paramref name="name"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual RecoverDeletedKeyOperation StartRecoverDeletedKey(string name, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(name, nameof(name)); using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Keys.KeyClient.StartRecoverDeletedKey"); scope.AddAttribute("key", name); scope.Start(); try { Response<KeyVaultKey> response = _pipeline.SendRequest(RequestMethod.Post, () => new KeyVaultKey(name), cancellationToken, DeletedKeysPath, name, "/recover"); return new RecoverDeletedKeyOperation(_pipeline, response); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Recovers the deleted key to its latest version. /// </summary> /// <remarks> /// The Recover Deleted Key operation is applicable for deleted keys in /// soft-delete enabled vaults. It recovers the deleted key back to its latest /// version under /keys. An attempt to recover an non-deleted key will return /// an error. Consider this the inverse of the delete operation on soft-delete /// enabled vaults. This operation requires the keys/recover permission. /// </remarks> /// <param name="name">The name of the key.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns>A <see cref="RecoverDeletedKeyOperation"/> to wait on this long-running operation.</returns> /// <exception cref="ArgumentException"><paramref name="name"/> is an empty string.</exception> /// <exception cref="ArgumentNullException"><paramref name="name"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual async Task<RecoverDeletedKeyOperation> StartRecoverDeletedKeyAsync(string name, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(name, nameof(name)); using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Keys.KeyClient.StartRecoverDeletedKey"); scope.AddAttribute("key", name); scope.Start(); try { Response<KeyVaultKey> response = await _pipeline.SendRequestAsync(RequestMethod.Post, () => new KeyVaultKey(name), cancellationToken, DeletedKeysPath, name, "/recover").ConfigureAwait(false); return new RecoverDeletedKeyOperation(_pipeline, response); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Requests that a backup of the specified key be downloaded to the client. /// </summary> /// <remarks> /// The Key Backup operation exports a key from Azure Key Vault in a protected /// form. Note that this operation does NOT return the actual key in a form that /// can be used outside the Azure Key Vault system, the returned key /// is either protected to a Azure Key Vault HSM or to Azure Key Vault itself. /// The intent of this operation is to allow a client to GENERATE a key in one /// Azure Key Vault instance, BACKUP the key, and then RESTORE it into another /// Azure Key Vault instance. The BACKUP operation may be used to export, in /// protected form, any key type from Azure Key Vault. Individual versions of a /// key cannot be backed up. BACKUP / RESTORE can be performed within /// geographical boundaries only; meaning that a BACKUP from one geographical /// area cannot be restored to another geographical area. For example, a backup /// from the US geographical area cannot be restored in an EU geographical /// area. This operation requires the key/backup permission. /// </remarks> /// <param name="name">The name of the key.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="ArgumentException"><paramref name="name"/> is an empty string.</exception> /// <exception cref="ArgumentNullException"><paramref name="name"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual Response<byte[]> BackupKey(string name, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(name, nameof(name)); using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Keys.KeyClient.BackupKey"); scope.AddAttribute("key", name); scope.Start(); try { Response<KeyBackup> backup = _pipeline.SendRequest(RequestMethod.Post, () => new KeyBackup(), cancellationToken, KeysPath, name, "/backup"); return Response.FromValue(backup.Value.Value, backup.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Requests that a backup of the specified key be downloaded to the client. /// </summary> /// <remarks> /// The Key Backup operation exports a key from Azure Key Vault in a protected /// form. Note that this operation does NOT return the actual key in a form that /// can be used outside the Azure Key Vault system, the returned key /// is either protected to a Azure Key Vault HSM or to Azure Key Vault itself. /// The intent of this operation is to allow a client to GENERATE a key in one /// Azure Key Vault instance, BACKUP the key, and then RESTORE it into another /// Azure Key Vault instance. The BACKUP operation may be used to export, in /// protected form, any key type from Azure Key Vault. Individual versions of a /// key cannot be backed up. BACKUP / RESTORE can be performed within /// geographical boundaries only; meaning that a BACKUP from one geographical /// area cannot be restored to another geographical area. For example, a backup /// from the US geographical area cannot be restored in an EU geographical /// area. This operation requires the key/backup permission. /// </remarks> /// <param name="name">The name of the key.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="ArgumentException"><paramref name="name"/> is an empty string.</exception> /// <exception cref="ArgumentNullException"><paramref name="name"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual async Task<Response<byte[]>> BackupKeyAsync(string name, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(name, nameof(name)); using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Keys.KeyClient.BackupKey"); scope.AddAttribute("key", name); scope.Start(); try { Response<KeyBackup> backup = await _pipeline.SendRequestAsync(RequestMethod.Post, () => new KeyBackup(), cancellationToken, KeysPath, name, "/backup").ConfigureAwait(false); return Response.FromValue(backup.Value.Value, backup.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Restores a backed up key to a vault. /// </summary> /// <remarks> /// Imports a previously backed up key into Azure Key Vault, restoring the key, /// its key identifier, attributes and access control policies. The RESTORE /// operation may be used to import a previously backed up key. Individual /// versions of a key cannot be restored. The key is restored in its entirety /// with the same key name as it had when it was backed up. If the key name is /// not available in the target Key Vault, the RESTORE operation will be /// rejected. While the key name is retained during restore, the final key /// identifier will change if the key is restored to a different vault. Restore /// will restore all versions and preserve version identifiers. The RESTORE /// operation is subject to security constraints: The target Key Vault must be /// owned by the same Microsoft Azure Subscription as the source Key Vault The /// user must have RESTORE permission in the target Key Vault. This operation /// requires the keys/restore permission. /// </remarks> /// <param name="backup">The backup blob associated with a key.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="ArgumentException"><paramref name="backup"/> is an empty string.</exception> /// <exception cref="ArgumentNullException"><paramref name="backup"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual Response<KeyVaultKey> RestoreKeyBackup(byte[] backup, CancellationToken cancellationToken = default) { Argument.AssertNotNull(backup, nameof(backup)); using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Keys.KeyClient.RestoreKeyBackup"); scope.Start(); try { return _pipeline.SendRequest(RequestMethod.Post, new KeyBackup { Value = backup }, () => new KeyVaultKey(), cancellationToken, KeysPath, "/restore"); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Restores a backed up key to a vault. /// </summary> /// <remarks> /// Imports a previously backed up key into Azure Key Vault, restoring the key, /// its key identifier, attributes and access control policies. The RESTORE /// operation may be used to import a previously backed up key. Individual /// versions of a key cannot be restored. The key is restored in its entirety /// with the same key name as it had when it was backed up. If the key name is /// not available in the target Key Vault, the RESTORE operation will be /// rejected. While the key name is retained during restore, the final key /// identifier will change if the key is restored to a different vault. Restore /// will restore all versions and preserve version identifiers. The RESTORE /// operation is subject to security constraints: The target Key Vault must be /// owned by the same Microsoft Azure Subscription as the source Key Vault The /// user must have RESTORE permission in the target Key Vault. This operation /// requires the keys/restore permission. /// </remarks> /// <param name="backup">The backup blob associated with a key.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="ArgumentException"><paramref name="backup"/> is an empty string.</exception> /// <exception cref="ArgumentNullException"><paramref name="backup"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual async Task<Response<KeyVaultKey>> RestoreKeyBackupAsync(byte[] backup, CancellationToken cancellationToken = default) { Argument.AssertNotNull(backup, nameof(backup)); using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Keys.KeyClient.RestoreKeyBackup"); scope.Start(); try { return await _pipeline.SendRequestAsync(RequestMethod.Post, new KeyBackup { Value = backup }, () => new KeyVaultKey(), cancellationToken, KeysPath, "/restore").ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Imports an externally created key, stores it, and returns key parameters /// and attributes to the client. /// </summary> /// <remarks> /// The import key operation may be used to import any key type into an Azure /// Key Vault. If the named key already exists, Azure Key Vault creates a new /// version of the key. This operation requires the keys/import permission. /// </remarks> /// <param name="name">The name of the key.</param> /// <param name="keyMaterial">The <see cref="JsonWebKey"/> being imported.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="ArgumentException"><paramref name="name"/> is an empty string.</exception> /// <exception cref="ArgumentNullException"><paramref name="name"/> or <paramref name="keyMaterial"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual Response<KeyVaultKey> ImportKey(string name, JsonWebKey keyMaterial, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(name, nameof(name)); Argument.AssertNotNull(keyMaterial, nameof(keyMaterial)); var importKeyOptions = new ImportKeyOptions(name, keyMaterial); using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Keys.KeyClient.ImportKey"); scope.AddAttribute("key", name); scope.Start(); try { return _pipeline.SendRequest(RequestMethod.Put, importKeyOptions, () => new KeyVaultKey(name), cancellationToken, KeysPath, name); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Imports an externally created key, stores it, and returns key parameters /// and attributes to the client. /// </summary> /// <remarks> /// The import key operation may be used to import any key type into an Azure /// Key Vault. If the named key already exists, Azure Key Vault creates a new /// version of the key. This operation requires the keys/import permission. /// </remarks> /// <param name="name">The name of the key.</param> /// <param name="keyMaterial">The <see cref="JsonWebKey"/> being imported.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="ArgumentException"><paramref name="name"/> is an empty string.</exception> /// <exception cref="ArgumentNullException"><paramref name="name"/> or <paramref name="keyMaterial"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual async Task<Response<KeyVaultKey>> ImportKeyAsync(string name, JsonWebKey keyMaterial, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(name, nameof(name)); Argument.AssertNotNull(keyMaterial, nameof(keyMaterial)); var importKeyOptions = new ImportKeyOptions(name, keyMaterial); using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Keys.KeyClient.ImportKey"); scope.AddAttribute("key", name); scope.Start(); try { return await _pipeline.SendRequestAsync(RequestMethod.Put, importKeyOptions, () => new KeyVaultKey(name), cancellationToken, KeysPath, name).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Imports an externally created key, stores it, and returns key parameters /// and attributes to the client. /// </summary> /// <remarks> /// The import key operation may be used to import any key type into an Azure /// Key Vault. If the named key already exists, Azure Key Vault creates a new /// version of the key. This operation requires the keys/import permission. /// </remarks> /// <param name="importKeyOptions">The key import configuration object containing information about the <see cref="JsonWebKey"/> being imported.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="ArgumentNullException"><paramref name="importKeyOptions"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual Response<KeyVaultKey> ImportKey(ImportKeyOptions importKeyOptions, CancellationToken cancellationToken = default) { Argument.AssertNotNull(importKeyOptions, nameof(importKeyOptions)); using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Keys.KeyClient.ImportKey"); scope.AddAttribute("key", importKeyOptions.Name); scope.Start(); try { return _pipeline.SendRequest(RequestMethod.Put, importKeyOptions, () => new KeyVaultKey(importKeyOptions.Name), cancellationToken, KeysPath, importKeyOptions.Name); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Imports an externally created key, stores it, and returns key parameters /// and attributes to the client. /// </summary> /// <remarks> /// The import key operation may be used to import any key type into an Azure /// Key Vault. If the named key already exists, Azure Key Vault creates a new /// version of the key. This operation requires the keys/import permission. /// </remarks> /// <param name="importKeyOptions">The key import configuration object containing information about the <see cref="JsonWebKey"/> being imported.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="ArgumentNullException"><paramref name="importKeyOptions"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual async Task<Response<KeyVaultKey>> ImportKeyAsync(ImportKeyOptions importKeyOptions, CancellationToken cancellationToken = default) { Argument.AssertNotNull(importKeyOptions, nameof(importKeyOptions)); using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Keys.KeyClient.ImportKey"); scope.AddAttribute("key", importKeyOptions.Name); scope.Start(); try { return await _pipeline.SendRequestAsync(RequestMethod.Put, importKeyOptions, () => new KeyVaultKey(importKeyOptions.Name), cancellationToken, KeysPath, importKeyOptions.Name).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } } }
57.474932
239
0.646408
[ "MIT" ]
Violet26/azure-sdk-for-net
sdk/keyvault/Azure.Security.KeyVault.Keys/src/KeyClient.cs
63,052
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace values_cs { class values_cs { //URL public static string apiURL_clientAuth = "https://api.ggs-network.de/client/online"; public static string apiURL_clientConfig = "https://assets.ggs-network.de/config.json"; public static string apiURL_clientLogin = "https://api.ggs-network.de/client/auth/login"; public static string apiURL_clientGetUser = "https://api.ggs-network.de/client/auth/get-user"; public static string apiURL_clientGetVPN = "https://api.ggs-network.de/client/vpn/get"; public static string apiURL_clientGenVPN = "https://api.ggs-network.de/client/vpn/gen"; } }
36.714286
102
0.714656
[ "Apache-2.0" ]
Good-Game-Services/vpn-client
Client/assets/values.cs
773
C#
using System; using Calitha.Common; namespace Calitha.GoldParser { public enum SymbolType { None, Eof, Whitespace, End, CommentStart, CommentEnd, CommentLine, Error } /// <summary> /// Symbol implementation. /// </summary> public class Symbol { public static Symbol EOF = new Symbol(0, SymbolType.Eof); public static Symbol ERROR = new Symbol(1, SymbolType.Error); public Symbol(int id, string name, bool isTerminal) { Id = id; Name = name; Type = SymbolType.None; IsTerminal = isTerminal; } public Symbol(int id, SymbolType type) { Id = id; Name = string.Concat("(", type, ")"); Type = type; IsTerminal = true; } public override bool Equals(Object obj) { var result = Util.EqualsNoState(this, obj); if (result.HasValue) return result.Value; var other = (Symbol)obj; return (Id == other.Id); } public override int GetHashCode() { return Id; } public override String ToString() { return Name; } public int Id { get; private set; } public string Name { get; private set; } /// <summary> /// True if a symbol is directly linked to a token. /// </summary> public bool IsTerminal { get; private set; } public SymbolType Type { get; private set; } } }
18.434783
63
0.643868
[ "MIT" ]
jbosh/calculator
Calculator 3/Calitha/GoldParser/Symbol.cs
1,272
C#
// Copyright (c) 2015 Alachisoft // // 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.Runtime.Serialization; using System.Security.Permissions; namespace Alachisoft.NCache.Runtime.Exceptions { /// <summary> /// Thrown when an exception occurs during configuration. Likely causes are badly specified /// configuration strings. /// </summary> /// <example>The following example demonstrates how to use this exception in your code. /// <code> /// /// try /// { /// ... /// } /// catch(ConfigurationException ex) /// { /// ... /// } /// /// </code> /// </example> [Serializable] public class ConfigurationException : CacheException { /// <summary> /// default constructor. /// </summary> public ConfigurationException() { } /// <summary> /// overloaded constructor, takes the reason as parameter. /// </summary> public ConfigurationException(string reason) : base(reason) { } /// <summary> /// overloaded constructor. /// </summary> /// <param name="reason">reason for exception</param> /// <param name="inner">nested exception</param> public ConfigurationException(string reason, Exception inner) : base(reason, inner) { } #region / --- ISerializable --- / /// <summary> /// overloaded constructor, manual serialization. /// </summary> protected ConfigurationException(SerializationInfo info, StreamingContext context) : base(info, context) { } /// <summary> /// manual serialization /// </summary> /// <param name="info"></param> /// <param name="context"></param> [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); } #endregion } }
30.420455
95
0.595816
[ "Apache-2.0" ]
NCacheDev/NCache
Src/NCRuntime/Exceptions/ConfigurationException.cs
2,677
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // 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("AWSSDK.SimpleWorkflow")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Simple Workflow Service. Amazon SWF helps developers build, run, and scale background jobs that have parallel or sequential steps. You can think of Amazon SWF as a fully-managed state tracker and task coordinator in the Cloud.")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Amazon Simple Workflow Service. Amazon SWF helps developers build, run, and scale background jobs that have parallel or sequential steps. You can think of Amazon SWF as a fully-managed state tracker and task coordinator in the Cloud.")] #elif NETSTANDARD13 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3) - Amazon Simple Workflow Service. Amazon SWF helps developers build, run, and scale background jobs that have parallel or sequential steps. You can think of Amazon SWF as a fully-managed state tracker and task coordinator in the Cloud.")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - Amazon Simple Workflow Service. Amazon SWF helps developers build, run, and scale background jobs that have parallel or sequential steps. You can think of Amazon SWF as a fully-managed state tracker and task coordinator in the Cloud.")] #elif NETCOREAPP3_1 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - Amazon Simple Workflow Service. Amazon SWF helps developers build, run, and scale background jobs that have parallel or sequential steps. You can think of Amazon SWF as a fully-managed state tracker and task coordinator in the Cloud.")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.5.0.67")] [assembly: System.CLSCompliant(true)] #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
60.54717
325
0.777189
[ "Apache-2.0" ]
motoko89/aws-sdk-net-xamarin
sdk/src/Services/SimpleWorkflow/Properties/AssemblyInfo.cs
3,209
C#
// CS1057: `B.E': Static classes cannot contain protected members // Line: 6 public static class B { protected class E {} }
15.75
65
0.698413
[ "Apache-2.0" ]
121468615/mono
mcs/errors/cs1057-2.cs
126
C#
using Catalog.API.Data; using Catalog.API.Entities; using MongoDB.Driver; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Catalog.API.Repositories { public class ProductRepository: IProductRepository { private readonly ICatalogContext _context; public ProductRepository(ICatalogContext context) { _context = context ?? throw new ArgumentNullException(nameof(context)); } public async Task<IEnumerable<Product>> GetProducts() { return await _context .Products .Find(p => true) .ToListAsync(); } public async Task<Product> GetProduct(string id) { return await _context .Products .Find(p => p.Id == id) .FirstOrDefaultAsync(); } public async Task<IEnumerable<Product>> GetProductByName(string name) { FilterDefinition<Product> filter = Builders<Product>.Filter.Eq(p => p.Name, name); return await _context .Products .Find(filter) .ToListAsync(); } public async Task<IEnumerable<Product>> GetProductByCategory(string categoryName) { FilterDefinition<Product> filter = Builders<Product>.Filter.Eq(p => p.Category, categoryName); return await _context .Products .Find(filter) .ToListAsync(); } public async Task CreateProduct(Product product) { await _context.Products.InsertOneAsync(product); } public async Task<bool> UpdateProduct(Product product) { var updateResult = await _context .Products .ReplaceOneAsync(filter: g => g.Id == product.Id, replacement: product); return updateResult.IsAcknowledged && updateResult.ModifiedCount > 0; } public async Task<bool> DeleteProduct(string id) { FilterDefinition<Product> filter = Builders<Product>.Filter.Eq(p => p.Id, id); DeleteResult deleteResult = await _context .Products .DeleteOneAsync(filter); return deleteResult.IsAcknowledged && deleteResult.DeletedCount > 0; } } }
29.072289
106
0.581019
[ "MIT" ]
simhamp/AspnetMicroservices
src/Services/Catalog/Catalog.API/Repositories/ProductRepository.cs
2,415
C#
using System; using System.Collections.Generic; namespace SKIT.FlurlHttpClient.Wechat.Api.Models { /// <summary> /// <para>表示 [POST] /cgi-bin/menu/addconditional 接口的请求。</para> /// </summary> public class CgibinMenuAddConditionalRequest : WechatApiRequest { public static class Types { public class Button : CgibinMenuCreateRequest.Types.Button { } public class MatchRule { /// <summary> /// 获取或设置标签 ID。 /// </summary> [Newtonsoft.Json.JsonProperty("tag_id")] [System.Text.Json.Serialization.JsonPropertyName("tag_id")] public int? TagId { get; set; } /// <summary> /// 获取或设置客户端版本。 /// </summary> [Newtonsoft.Json.JsonProperty("client_platform_type")] [System.Text.Json.Serialization.JsonPropertyName("client_platform_type")] [System.Text.Json.Serialization.JsonNumberHandling(System.Text.Json.Serialization.JsonNumberHandling.AllowReadingFromString)] public int? ClientPlatformType { get; set; } /// <summary> /// 获取或设置语言。 /// </summary> [Newtonsoft.Json.JsonProperty("language")] [System.Text.Json.Serialization.JsonPropertyName("language")] public string? Language { get; set; } } } /// <summary> /// 获取或设置菜单列表。 /// </summary> [Newtonsoft.Json.JsonProperty("button")] [System.Text.Json.Serialization.JsonPropertyName("button")] public IList<Types.Button> ButtonList { get; set; } = new List<Types.Button>(); /// <summary> /// 获取或设置菜单匹配规则。 /// </summary> [Newtonsoft.Json.JsonProperty("matchrule")] [System.Text.Json.Serialization.JsonPropertyName("matchrule")] public Types.MatchRule MatchRule { get; set; } = new Types.MatchRule(); } }
35.637931
141
0.555878
[ "MIT" ]
arden27336/DotNetCore.SKIT.FlurlHttpClient.Wechat
src/SKIT.FlurlHttpClient.Wechat.Api/Models/CgibinMenu/Conditional/CgibinMenuAddConditionalRequest.cs
2,183
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; namespace ShaneSpace.VisualStudio.InvisibleCharacterVisualizer { internal abstract class RegexTagger<T> : ITagger<T> where T : ITag { private readonly IEnumerable<Regex> _matchExpressions; protected RegexTagger(ITextBuffer buffer, IEnumerable<Regex> matchExpressions) { var expressions = matchExpressions as IList<Regex> ?? matchExpressions.ToList(); if (expressions.Any(re => (re.Options & RegexOptions.Multiline) == RegexOptions.Multiline)) { throw new ArgumentException("Multiline regular expressions are not supported."); } _matchExpressions = expressions; buffer.Changed += (sender, args) => HandleBufferChanged(args); } public event EventHandler<SnapshotSpanEventArgs> TagsChanged; public virtual IEnumerable<ITagSpan<T>> GetTags(NormalizedSnapshotSpanCollection spans) { // Here we grab whole lines so that matches that only partially fall inside the spans argument are detected. // Note that the spans argument can contain spans that are sub-spans of lines or intersect multiple lines. foreach (var line in GetIntersectingLines(spans)) { string text = line.GetText(); foreach (var regex in _matchExpressions) { foreach (var match in regex.Matches(text).Cast<Match>()) { T tag = TryCreateTagForMatch(match); if (EqualityComparer<T>.Default.Equals(tag, default(T))) { continue; } var span = new SnapshotSpan(line.Start + match.Index, match.Length); yield return new TagSpan<T>(span, tag); } } } } /// <summary> /// Overridden in the derived implementation to provide a tag for each regular expression match. /// If the return value is <c>null</c>, this match will be skipped. /// </summary> /// <param name="match">The match to create a tag for.</param> /// <returns>The tag to return from <see cref="GetTags"/>, if non-<c>null</c>.</returns> protected abstract T TryCreateTagForMatch(Match match); /// <summary> /// Handle buffer changes. The default implementation expands changes to full lines and sends out /// a <see cref="TagsChanged"/> event for these lines. /// </summary> /// <param name="args">The buffer change arguments.</param> protected virtual void HandleBufferChanged(TextContentChangedEventArgs args) { if (args.Changes.Count == 0) { return; } var temp = TagsChanged; if (temp == null) { return; } // Combine all changes into a single span so that // the ITagger<>.TagsChanged event can be raised just once for a compound edit // with many parts. ITextSnapshot snapshot = args.After; int start = args.Changes[0].NewPosition; int end = args.Changes[args.Changes.Count - 1].NewEnd; SnapshotSpan totalAffectedSpan = new SnapshotSpan( snapshot.GetLineFromPosition(start).Start, snapshot.GetLineFromPosition(end).End); temp(this, new SnapshotSpanEventArgs(totalAffectedSpan)); } private IEnumerable<ITextSnapshotLine> GetIntersectingLines(NormalizedSnapshotSpanCollection spans) { if (spans.Count == 0) { yield break; } int lastVisitedLineNumber = -1; ITextSnapshot snapshot = spans[0].Snapshot; foreach (var span in spans) { int firstLine = snapshot.GetLineNumberFromPosition(span.Start); int lastLine = snapshot.GetLineNumberFromPosition(span.End); for (int i = Math.Max(lastVisitedLineNumber, firstLine); i <= lastLine; i++) { yield return snapshot.GetLineFromLineNumber(i); } lastVisitedLineNumber = lastLine; } } } }
38.225
120
0.576848
[ "MIT" ]
shaneray/ShaneSpace.VisualStudio.InvisibleCharacterVisualizer
src/ShaneSpace.VisualStudio.InvisibleCharacterVisualizer/RegexTagger.cs
4,589
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Vod.V20180717.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class CreateAIRecognitionTemplateRequest : AbstractModel { /// <summary> /// 视频内容识别模板名称,长度限制:64 个字符。 /// </summary> [JsonProperty("Name")] public string Name{ get; set; } /// <summary> /// 视频内容识别模板描述信息,长度限制:256 个字符。 /// </summary> [JsonProperty("Comment")] public string Comment{ get; set; } /// <summary> /// 视频片头片尾识别控制参数。 /// </summary> [JsonProperty("HeadTailConfigure")] public HeadTailConfigureInfo HeadTailConfigure{ get; set; } /// <summary> /// 视频拆条识别控制参数。 /// </summary> [JsonProperty("SegmentConfigure")] public SegmentConfigureInfo SegmentConfigure{ get; set; } /// <summary> /// 人脸识别控制参数。 /// </summary> [JsonProperty("FaceConfigure")] public FaceConfigureInfo FaceConfigure{ get; set; } /// <summary> /// 文本全文识别控制参数。 /// </summary> [JsonProperty("OcrFullTextConfigure")] public OcrFullTextConfigureInfo OcrFullTextConfigure{ get; set; } /// <summary> /// 文本关键词识别控制参数。 /// </summary> [JsonProperty("OcrWordsConfigure")] public OcrWordsConfigureInfo OcrWordsConfigure{ get; set; } /// <summary> /// 语音全文识别控制参数。 /// </summary> [JsonProperty("AsrFullTextConfigure")] public AsrFullTextConfigureInfo AsrFullTextConfigure{ get; set; } /// <summary> /// 语音关键词识别控制参数。 /// </summary> [JsonProperty("AsrWordsConfigure")] public AsrWordsConfigureInfo AsrWordsConfigure{ get; set; } /// <summary> /// 物体识别控制参数。 /// </summary> [JsonProperty("ObjectConfigure")] public ObjectConfigureInfo ObjectConfigure{ get; set; } /// <summary> /// 截帧间隔,单位为秒。当不填时,默认截帧间隔为 1 秒,最小值为 0.5 秒。 /// </summary> [JsonProperty("ScreenshotInterval")] public float? ScreenshotInterval{ get; set; } /// <summary> /// 点播[子应用](/document/product/266/14574) ID。如果要访问子应用中的资源,则将该字段填写为子应用 ID;否则无需填写该字段。 /// </summary> [JsonProperty("SubAppId")] public ulong? SubAppId{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "Name", this.Name); this.SetParamSimple(map, prefix + "Comment", this.Comment); this.SetParamObj(map, prefix + "HeadTailConfigure.", this.HeadTailConfigure); this.SetParamObj(map, prefix + "SegmentConfigure.", this.SegmentConfigure); this.SetParamObj(map, prefix + "FaceConfigure.", this.FaceConfigure); this.SetParamObj(map, prefix + "OcrFullTextConfigure.", this.OcrFullTextConfigure); this.SetParamObj(map, prefix + "OcrWordsConfigure.", this.OcrWordsConfigure); this.SetParamObj(map, prefix + "AsrFullTextConfigure.", this.AsrFullTextConfigure); this.SetParamObj(map, prefix + "AsrWordsConfigure.", this.AsrWordsConfigure); this.SetParamObj(map, prefix + "ObjectConfigure.", this.ObjectConfigure); this.SetParamSimple(map, prefix + "ScreenshotInterval", this.ScreenshotInterval); this.SetParamSimple(map, prefix + "SubAppId", this.SubAppId); } } }
35.438017
95
0.615905
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Vod/V20180717/Models/CreateAIRecognitionTemplateRequest.cs
4,690
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; using System.ComponentModel; using System.Linq; using Microsoft.Toolkit.Uwp.UI.Extensions; using Windows.ApplicationModel.DataTransfer; using Windows.Foundation.Metadata; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; namespace Microsoft.Toolkit.Uwp.UI.Controls { /// <summary> /// TabView is a control for displaying a set of tabs and their content. /// </summary> [Obsolete("Please migrate to the TabView control from WinUI, this control will be removed in a future release. https://aka.ms/winui")] [TemplatePart(Name = TabContentPresenterName, Type = typeof(ContentPresenter))] [TemplatePart(Name = TabViewContainerName, Type = typeof(Grid))] [TemplatePart(Name = TabsItemsPresenterName, Type = typeof(ItemsPresenter))] [TemplatePart(Name = TabsScrollViewerName, Type = typeof(ScrollViewer))] [TemplatePart(Name = TabsScrollBackButtonName, Type = typeof(ButtonBase))] [TemplatePart(Name = TabsScrollForwardButtonName, Type = typeof(ButtonBase))] public partial class TabView : ListViewBase { private const int ScrollAmount = 50; // TODO: Should this be based on TabWidthMode private const string TabContentPresenterName = "TabContentPresenter"; private const string TabViewContainerName = "TabViewContainer"; private const string TabsItemsPresenterName = "TabsItemsPresenter"; private const string TabsScrollViewerName = "ScrollViewer"; private const string TabsScrollBackButtonName = "ScrollBackButton"; private const string TabsScrollForwardButtonName = "ScrollForwardButton"; private ContentPresenter _tabContentPresenter; private Grid _tabViewContainer; private ItemsPresenter _tabItemsPresenter; private ScrollViewer _tabScroller; private ButtonBase _tabScrollBackButton; private ButtonBase _tabScrollForwardButton; private bool _hasLoaded; private bool _isDragging; /// <summary> /// Initializes a new instance of the <see cref="TabView"/> class. /// </summary> public TabView() { DefaultStyleKey = typeof(TabView); // Container Generation Hooks RegisterPropertyChangedCallback(ItemsSourceProperty, ItemsSource_PropertyChanged); if (ApiInformation.IsPropertyPresent("Windows.UI.Xaml.Controls.ItemsControl", "ItemContainerGenerator")) { ItemContainerGenerator.ItemsChanged += ItemContainerGenerator_ItemsChanged; } // Drag and Layout Hooks DragItemsStarting += TabView_DragItemsStarting; DragItemsCompleted += TabView_DragItemsCompleted; SizeChanged += TabView_SizeChanged; // Selection Hook SelectionChanged += TabView_SelectionChanged; } /// <summary> /// Occurs when a tab is dragged by the user outside of the <see cref="TabView"/>. Generally, this paradigm is used to create a new-window with the torn-off tab. /// The creation and handling of the new-window is left to the app's developer. /// </summary> public event EventHandler<TabDraggedOutsideEventArgs> TabDraggedOutside; /// <summary> /// Occurs when a tab's Close button is clicked. Set <see cref="CancelEventArgs.Cancel"/> to true to prevent automatic Tab Closure. /// </summary> public event EventHandler<TabClosingEventArgs> TabClosing; /// <inheritdoc/> protected override DependencyObject GetContainerForItemOverride() => new TabViewItem(); /// <inheritdoc/> protected override bool IsItemItsOwnContainerOverride(object item) { return item is TabViewItem; } /// <inheritdoc/> protected override void OnApplyTemplate() { base.OnApplyTemplate(); if (_tabItemsPresenter != null) { _tabItemsPresenter.SizeChanged -= TabView_SizeChanged; } if (_tabScroller != null) { _tabScroller.Loaded -= ScrollViewer_Loaded; } _tabContentPresenter = GetTemplateChild(TabContentPresenterName) as ContentPresenter; _tabViewContainer = GetTemplateChild(TabViewContainerName) as Grid; _tabItemsPresenter = GetTemplateChild(TabsItemsPresenterName) as ItemsPresenter; _tabScroller = GetTemplateChild(TabsScrollViewerName) as ScrollViewer; if (_tabItemsPresenter != null) { _tabItemsPresenter.SizeChanged += TabView_SizeChanged; } if (_tabScroller != null) { _tabScroller.Loaded += ScrollViewer_Loaded; } } private void ScrollViewer_Loaded(object sender, RoutedEventArgs e) { _tabScroller.Loaded -= ScrollViewer_Loaded; if (_tabScrollBackButton != null) { _tabScrollBackButton.Click -= ScrollTabBackButton_Click; } if (_tabScrollForwardButton != null) { _tabScrollForwardButton.Click -= ScrollTabForwardButton_Click; } _tabScrollBackButton = _tabScroller.FindDescendantByName(TabsScrollBackButtonName) as ButtonBase; _tabScrollForwardButton = _tabScroller.FindDescendantByName(TabsScrollForwardButtonName) as ButtonBase; if (_tabScrollBackButton != null) { _tabScrollBackButton.Click += ScrollTabBackButton_Click; } if (_tabScrollForwardButton != null) { _tabScrollForwardButton.Click += ScrollTabForwardButton_Click; } } private void ScrollTabBackButton_Click(object sender, RoutedEventArgs e) { _tabScroller.ChangeView(Math.Max(0, _tabScroller.HorizontalOffset - ScrollAmount), null, null); } private void ScrollTabForwardButton_Click(object sender, RoutedEventArgs e) { _tabScroller.ChangeView(Math.Min(_tabScroller.ScrollableWidth, _tabScroller.HorizontalOffset + ScrollAmount), null, null); } private void TabView_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (_isDragging) { // Skip if we're dragging, we'll reset when we're done. return; } if (_tabContentPresenter != null) { if (SelectedItem == null) { _tabContentPresenter.Content = null; _tabContentPresenter.ContentTemplate = null; } else { if (ContainerFromItem(SelectedItem) is TabViewItem container) { _tabContentPresenter.Content = container.Content; _tabContentPresenter.ContentTemplate = container.ContentTemplate; } } } // If our width can be effected by the selection, need to run algorithm. if (!double.IsNaN(SelectedTabWidth)) { TabView_SizeChanged(sender, null); } } /// <inheritdoc/> protected override void PrepareContainerForItemOverride(DependencyObject element, object item) { base.PrepareContainerForItemOverride(element, item); var tabitem = element as TabViewItem; tabitem.Loaded -= TabViewItem_Loaded; tabitem.Closing -= TabViewItem_Closing; tabitem.Loaded += TabViewItem_Loaded; tabitem.Closing += TabViewItem_Closing; if (tabitem.Header == null) { tabitem.Header = item; } if (tabitem.HeaderTemplate == null) { var headertemplatebinding = new Binding() { Source = this, Path = new PropertyPath(nameof(ItemHeaderTemplate)), Mode = BindingMode.OneWay }; tabitem.SetBinding(TabViewItem.HeaderTemplateProperty, headertemplatebinding); } if (tabitem.IsClosable != true && tabitem.ReadLocalValue(TabViewItem.IsClosableProperty) == DependencyProperty.UnsetValue) { var iscloseablebinding = new Binding() { Source = this, Path = new PropertyPath(nameof(CanCloseTabs)), Mode = BindingMode.OneWay, }; tabitem.SetBinding(TabViewItem.IsClosableProperty, iscloseablebinding); } } private void TabViewItem_Loaded(object sender, RoutedEventArgs e) { var tabitem = sender as TabViewItem; tabitem.Loaded -= TabViewItem_Loaded; // Only need to do this once. if (!_hasLoaded) { _hasLoaded = true; // Need to set a tab's selection on load, otherwise ListView resets to null. SetInitialSelection(); // Need to make sure ContentPresenter is set to content based on selection. TabView_SelectionChanged(this, null); // Need to make sure we've registered our removal method. ItemsSource_PropertyChanged(this, null); // Make sure we complete layout now. TabView_SizeChanged(this, null); } } private void TabViewItem_Closing(object sender, TabClosingEventArgs e) { var item = ItemFromContainer(e.Tab); var args = new TabClosingEventArgs(item, e.Tab); TabClosing?.Invoke(this, args); if (!args.Cancel) { if (ItemsSource != null) { _removeItemsSourceMethod?.Invoke(ItemsSource, new object[] { item }); } else { Items.Remove(item); } } } private void TabView_DragItemsStarting(object sender, DragItemsStartingEventArgs e) { // Keep track of drag so we don't modify content until done. _isDragging = true; } private void TabView_DragItemsCompleted(ListViewBase sender, DragItemsCompletedEventArgs args) { _isDragging = false; // args.DropResult == None when outside of area (e.g. create new window) if (args.DropResult == DataPackageOperation.None) { var item = args.Items.FirstOrDefault(); var tab = ContainerFromItem(item) as TabViewItem; if (tab == null && item is FrameworkElement fe) { tab = fe.FindParent<TabViewItem>(); } if (tab == null) { // We still don't have a TabViewItem, most likely is a static TabViewItem in the template being dragged and not selected. // This is a fallback scenario for static tabs. // Note: This can be wrong if two TabViewItems share the exact same Content (i.e. a string), this should be unlikely in any practical scenario. for (int i = 0; i < Items.Count; i++) { var tabItem = ContainerFromIndex(i) as TabViewItem; if (ReferenceEquals(tabItem.Content, item)) { tab = tabItem; break; } } } TabDraggedOutside?.Invoke(this, new TabDraggedOutsideEventArgs(item, tab)); } else { // If dragging the active tab, there's an issue with the CP blanking. TabView_SelectionChanged(this, null); } } } }
38.273006
170
0.589324
[ "MIT" ]
edparitor/Uno.WindowsCommunityToolkit
Microsoft.Toolkit.Uwp.UI.Controls/TabView/TabView.cs
12,479
C#
using Newtonsoft.Json; namespace TokenFunctionHelper.TokenStuff { public class TokenRequest { [JsonProperty("token")] public string Token { get; set; } [JsonProperty("rsaKey")] public string RsaKey { get; set; } [JsonProperty("issuer")] public string Issuer { get; set; } [JsonProperty("audience")] public string Audience { get; set; } } }
24.588235
44
0.598086
[ "MIT" ]
jakkaj/Presentation_NDCSydney2016
src/DemoApi/src/TokenFunctionHelper/TokenStuff/TokenRequest.cs
420
C#
using System; using Android.App; namespace DeepSound.Helpers.Model { public static class UserDetails { public static string AccessToken = string.Empty; public static int UserId; public static string Username = string.Empty; public static string FullName = string.Empty; public static string Password = string.Empty; public static string Email = string.Empty; public static string Cookie = string.Empty; public static string Status = string.Empty; public static string Avatar = string.Empty; public static string Cover = string.Empty; public static string DeviceId = string.Empty; public static string Lang = string.Empty; public static string IsPro = string.Empty; public static string Url = string.Empty; public static string Lat = string.Empty; public static string Lng = string.Empty; public static string LangName = string.Empty; public static bool IsLogin = false; public static string FilterGenres = "1", FilterPrice = "1"; public static int CountNotificationsStatic = 0; public static int UnixTimestamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds; public static string Time = UnixTimestamp.ToString(); public static string AndroidId = Android.Provider.Settings.Secure.GetString(Application.Context.ContentResolver, Android.Provider.Settings.Secure.AndroidId); public static void ClearAllValueUserDetails() { try { AccessToken = string.Empty; UserId = 0; Username = string.Empty; FullName = string.Empty; Password = string.Empty; Email = string.Empty; Cookie = string.Empty; Status = string.Empty; Avatar = string.Empty; Cover = string.Empty; DeviceId = string.Empty; Lang = string.Empty; Lat = string.Empty; Lng = string.Empty; LangName = string.Empty; } catch (Exception e) { Console.WriteLine(e); } } } }
39.233333
166
0.579014
[ "Unlicense" ]
CroccityJamz/Croccityjamz-android
Helpers/Model/UserDetails.cs
2,356
C#
using System; using System.Threading; namespace LeanCode.Time { public sealed class FixedTimeProvider : ITimeProvider { private static readonly FixedTimeProvider SharedInstance = new FixedTimeProvider(); private readonly AsyncLocal<DateTimeOffset> savedTime = new AsyncLocal<DateTimeOffset>(); /// <summary> /// Gets the time for <b>current async context</b> as UTC <see cref="DateTime"/>. /// </summary> public DateTime Now => savedTime.Value.UtcDateTime; /// <summary> /// Gets the time for <b>current async context</b> as <see cref="DateTimeOffset"/>. /// </summary> public DateTimeOffset NowWithOffset => savedTime.Value; private FixedTimeProvider() { } /// <summary> /// Sets this provider as current and updates time for current async context. /// </summary> /// <remarks> /// Argument cannot have <see cref="DateTimeKind"/> of <see cref="DateTimeKind.Local"/> /// and <see cref="DateTimeKind.Unspecified"/> is treated as <see cref="DateTimeKind.Utc"/>. /// </remarks> /// <exception cref="InvalidOperationException"> /// <see cref="DateTimeKind"/> of the argument is <see cref="DateTimeKind.Local"/>. /// </exception> public static void SetTo(DateTime time) { if (time.Kind == DateTimeKind.Local) { throw new InvalidOperationException( "Cannot assign local DateTime, use SetTo(DateTimeOffset) overload with correct offset instead."); } TimeProvider.Use(SharedInstance); SharedInstance.savedTime.Value = new DateTimeOffset(time, TimeSpan.Zero); } /// <summary> /// Sets this provider as current and updates time for current async context. /// </summary> public static void SetTo(DateTimeOffset time) { TimeProvider.Use(SharedInstance); SharedInstance.savedTime.Value = time; } } }
35.672414
117
0.60899
[ "Apache-2.0" ]
leancodepl/corelibrary
src/Domain/LeanCode.TimeProvider/FixedTimeProvider.cs
2,069
C#
namespace FortniteReplayReader.Core.Models { public static class ReplayEventTypes { public const string PLAYER_ELIMINATION = "playerElim"; public const string MATCH_STATS = "AthenaMatchStats"; public const string TEAM_STATS = "AthenaMatchTeamStats"; public const string ENCRYPTION_KEY = "PlayerStateEncryptionKey"; public const string CHARACTER_SAMPLE = "CharacterSampleMeta"; public const string ZONE_UPDATE = "ZoneUpdate"; public const string BATTLE_BUS = "BattleBusFlight"; } }
42.153846
72
0.720803
[ "MIT" ]
Chenglei-dev/FortniteReplayReader
src/FortniteReplayReader.Core/Models/Enums/ReplayEventTypes.cs
548
C#
/* License: The MIT License (MIT) Copyright (c) 2011 CslaGenFork project. 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. */ // -------------------------------------------------------------------------------------------------------------------- // <copyright file="NoDuplicates.cs" company=""> // Copyright (c) 2011 CslaGenFork project. Website: http://cslagenfork.codeplex.com/ // </copyright> // <summary> // Business rule for checking a name property is unique at the parent collection level. // </summary> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using Csla.Core; using Csla.Rules; namespace CslaGenFork.Rules.CollectionRules { /// <summary> /// Business rule for checking a name property is unique at the parent collection level. /// </summary> public class NoDuplicates : CommonRuleWithMessage { /// <summary> /// Initializes a new instance of the <see cref="NoDuplicates"/> class. /// </summary> /// <param name="primaryProperty">Primary property for this rule.</param> public NoDuplicates(IPropertyInfo primaryProperty) : base(primaryProperty) { InputProperties = new List<IPropertyInfo> {primaryProperty}; } /// <summary> /// Initializes a new instance of the <see cref="NoDuplicates"/> class. /// </summary> /// <param name="primaryProperty">Primary property for this rule.</param> /// <param name="message">The error message text.</param> public NoDuplicates(IPropertyInfo primaryProperty, string message) : this(primaryProperty) { MessageText = message; } /// <summary> /// Initializes a new instance of the <see cref="NoDuplicates"/> class. /// </summary> /// <param name="primaryProperty">Primary property for this rule.</param> /// <param name="messageDelegate">The error message function.</param> public NoDuplicates(IPropertyInfo primaryProperty, Func<string> messageDelegate) : this(primaryProperty) { MessageDelegate = messageDelegate; } /// <summary> /// Gets the error message. /// </summary> /// <returns> /// The error message. /// </returns> protected override string GetMessage() { return HasMessageDelegate ? base.GetMessage() : "{0} must be unique"; } /// <summary> /// Business rule implementation. /// </summary> /// <param name="context">Rule context object.</param> protected override void Execute(RuleContext context) { var value = context.InputPropertyValues[PrimaryProperty] as string; if (value == null) return; var target = (BusinessBase)context.Target; dynamic parent = target.Parent; if (parent != null) { foreach (var item in parent) { System.Reflection.PropertyInfo compare = item.GetType().GetProperty(PrimaryProperty.Name); if (value.ToUpperInvariant() == compare.GetValue(item, null).ToUpperInvariant() && !(ReferenceEquals(item, target))) { var message = string.Format(GetMessage(), PrimaryProperty.FriendlyName); context.Results.Add(new RuleResult(RuleName, PrimaryProperty, message) {Severity = Severity}); } } } } } }
43.432432
129
0.586808
[ "MIT" ]
CslaGenFork/CslaGenFork
tags/Rules sample v.1.0.0.0/CslaGenFork.Rules-4.1.0/Business Rules/NoDuplicates.cs
4,823
C#
 namespace Primavera.Platform.Geolocation { partial class TabMapCustomers { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.SuspendLayout(); // // TabMapClients // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Name = "TabMapCustomers"; this.Size = new System.Drawing.Size(709, 455); this.TabCaption = "Geolocalização"; this.Load += new System.EventHandler(this.TabMapCustomers_Load); this.Loading += new Primavera.Extensibility.Patterns.CustomTab.EventDelegate(this.TabMapCustomers_Loading); this.Saving += new Primavera.Extensibility.Patterns.CustomTab.EventDelegate(this.TabMapCustomers_Saving); this.ResumeLayout(false); } #endregion } }
33.365385
119
0.588473
[ "MIT" ]
Everest89/ERP10Extensibility
Implementation/GeolocationExtension/UserControls/TabMapCustomers.Designer.cs
1,739
C#
using System; using System.IO; using Nikki.Core; using Nikki.Utils; using Nikki.Reflection.Enum; using Nikki.Reflection.Exception; using Nikki.Support.Carbon.Class; using CoreExtensions.IO; namespace Nikki.Support.Carbon.Framework { /// <summary> /// A <see cref="Manager{T}"/> for <see cref="PresetSkin"/> collections. /// </summary> public class PresetSkinManager : Manager<PresetSkin> { /// <summary> /// Game to which the class belongs to. /// </summary> public override GameINT GameINT => GameINT.Carbon; /// <summary> /// Game string to which the class belongs to. /// </summary> public override string GameSTR => GameINT.Carbon.ToString(); /// <summary> /// Name of this <see cref="PresetSkinManager"/>. /// </summary> public override string Name => "PresetSkins"; /// <summary> /// If true, manager can export and import non-serialized collection; otherwise, false. /// </summary> public override bool AllowsNoSerialization => true; /// <summary> /// True if this <see cref="Manager{T}"/> is read-only; otherwise, false. /// </summary> public override bool IsReadOnly => false; /// <summary> /// Indicates required alighment when this <see cref="PresetSkinManager"/> is being serialized. /// </summary> public override Alignment Alignment { get; } /// <summary> /// Gets a collection and unit element type in this <see cref="PresetSkinManager"/>. /// </summary> public override Type CollectionType => typeof(PresetSkin); /// <summary> /// Initializes new instance of <see cref="PresetSkinManager"/>. /// </summary> /// <param name="db"><see cref="Datamap"/> to which this manager belongs to.</param> public PresetSkinManager(Datamap db) : base(db) { this.Extender = 5; this.Alignment = Alignment.Default; } /// <summary> /// Assembles collection data into byte buffers. /// </summary> /// <param name="bw"><see cref="BinaryWriter"/> to write data with.</param> /// <param name="mark">Watermark to put in the padding blocks.</param> internal override void Assemble(BinaryWriter bw, string mark) { if (this.Count == 0) return; bw.GeneratePadding(mark, this.Alignment); bw.WriteEnum(BinBlockID.PresetSkins); bw.Write(this.Count * PresetSkin.BaseClassSize); foreach (var collection in this) { collection.Assemble(bw); } } /// <summary> /// Disassembles data into separate collections in this <see cref="PresetSkinManager"/>. /// </summary> /// <param name="br"><see cref="BinaryReader"/> to read data with.</param> /// <param name="block"><see cref="Block"/> with offsets.</param> internal override void Disassemble(BinaryReader br, Block block) { if (Block.IsNullOrEmpty(block)) return; if (block.BlockID != BinBlockID.PresetSkins) return; for (int loop = 0; loop < block.Offsets.Count; ++loop) { br.BaseStream.Position = block.Offsets[loop] + 4; var size = br.ReadInt32(); int count = size / PresetSkin.BaseClassSize; this.Capacity += count; for (int i = 0; i < count; ++i) { var collection = new PresetSkin(br, this); try { this.Add(collection); } catch { } // skip if exists } } } /// <summary> /// Checks whether CollectionName provided allows creation of a new collection. /// </summary> /// <param name="cname">CollectionName to check.</param> internal override void CreationCheck(string cname) { if (String.IsNullOrWhiteSpace(cname)) { throw new ArgumentNullException("CollectionName cannot be null, empty or whitespace"); } if (cname.Contains(" ")) { throw new ArgumentException("CollectionName cannot contain whitespace"); } if (cname.Length > PresetSkin.MaxCNameLength) { throw new ArgumentLengthException(PresetSkin.MaxCNameLength); } if (this.Find(cname) != null) { throw new CollectionExistenceException(cname); } } /// <summary> /// Exports collection with CollectionName specified to a filename provided. /// </summary> /// <param name="cname">CollectionName of a collection to export.</param> /// <param name="bw"><see cref="BinaryWriter"/> to write data with.</param> /// <param name="serialized">True if collection exported should be serialized; /// false otherwise.</param> public override void Export(string cname, BinaryWriter bw, bool serialized = true) { var index = this.IndexOf(cname); if (index == -1) { throw new Exception($"Collection named {cname} does not exist"); } else { if (serialized) this[index].Serialize(bw); else this[index].Assemble(bw); } } /// <summary> /// Imports collection from file provided and attempts to add it to the end of /// this <see cref="Manager{T}"/> in case it does not exist. /// </summary> /// <param name="type">Type of serialization of a collection.</param> /// <param name="br"><see cref="BinaryReader"/> to read data with.</param> public override void Import(SerializeType type, BinaryReader br) { var position = br.BaseStream.Position; var header = new SerializationHeader(); header.Read(br); var collection = new PresetSkin(); if (header.ID != BinBlockID.Nikki) { br.BaseStream.Position = position; collection.Disassemble(br); } else { if (header.Game != this.GameINT) { throw new Exception($"Stated game inside collection is {header.Game}, while should be {this.GameINT}"); } if (header.Name != this.Name) { throw new Exception($"Imported collection is not a collection of type {this.Name}"); } collection.Deserialize(br); } var index = this.IndexOf(collection); if (index == -1) { collection.Manager = this; this.Add(collection); } else { switch (type) { case SerializeType.Negate: break; case SerializeType.Synchronize: case SerializeType.Override: collection.Manager = this; this.Replace(collection, index); break; default: break; } } } } }
24.146825
108
0.654725
[ "MIT" ]
SpeedReflect/Nikki
Nikki/Support.Carbon/Framework/PresetSkinManager.cs
6,087
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace LaserLumia { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> sealed partial class App : Application { /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += OnSuspending; } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (e.PrelaunchActivated == false) { if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(MainPage), e.Arguments); } // Ensure the current window is active Window.Current.Activate(); } } /// <summary> /// Invoked when Navigation to a certain page fails /// </summary> /// <param name="sender">The Frame which failed navigation</param> /// <param name="e">Details about the navigation failure</param> void OnNavigationFailed(object sender, NavigationFailedEventArgs e) { throw new Exception("Failed to load Page " + e.SourcePageType.FullName); } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); //TODO: Save application state and stop any background activity deferral.Complete(); } } }
38.831683
99
0.614227
[ "MIT" ]
DeltaDizzy/LaserLumia
src/LaserLumia/LaserLumia/App.xaml.cs
3,924
C#
using System.Collections.Generic; using System.Linq; using NewsPlus.Api.Controllers; namespace NewsPlus.Api.Models { public class NewsRepository : INewsRepository { private readonly ApplicationDbContext _applicationDbContext; public NewsRepository() { _applicationDbContext = new ApplicationDbContext(); } public List<News> GetAll() { //return new List<News>() //{ // new News {Id = 1, Title = "News 1", Body = "Body 1"}, // new News {Id = 2, Title = "News 2", Body = "Body 2"}, // new News {Id = 3, Title = "News 3", Body = "Body 3"} //}; return _applicationDbContext.Newses.ToList(); } } public interface INewsRepository { List<News> GetAll(); } }
27.290323
71
0.548463
[ "MIT" ]
akachaik/newsplus
NewsPlus.Api/Models/NewsRepository.cs
848
C#
using System; using System.Runtime.InteropServices; using System.Threading; using System.Diagnostics; namespace Gecko.Interop { /// <summary> /// COM pointer wrapper /// SHOULD be used for temporal variables /// </summary> /// <typeparam name="T"></typeparam> internal class ComPtr<T> : IDisposable, IEquatable<ComPtr<T>>, IEquatable<T> where T : class { protected T _instance; private readonly bool _releaseRCW; #region ctor & dtor public ComPtr(T instance, bool releaseRCW = true) { _instance = instance; _releaseRCW = releaseRCW; } ~ComPtr() { Free(); } public void Dispose() { Free(); GC.SuppressFinalize(this); } private void Free() { if (_instance != null && _releaseRCW) Xpcom.FreeComObject(ref _instance); _instance = null; } #endregion /// <summary> /// Finally releases COM object /// Decrement COM reference counter into zero /// </summary> public void FinalRelease() { if (_instance != null) Xpcom.FinalFreeComObject(ref _instance); _instance = null; } public T Instance { get { return _instance; } } #region Equality public bool Equals(ComPtr<T> other) { if (ReferenceEquals(this, other)) return true; if (ReferenceEquals(null, other)) return false; return _instance.GetHashCode() == other._instance.GetHashCode(); } public bool Equals(T other) { if (ReferenceEquals(null, other)) return false; return _instance.GetHashCode() == other.GetHashCode(); } public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) return true; if (ReferenceEquals(null, obj)) return false; if (!(obj is ComPtr<T>)) return false; return _instance.GetHashCode() == ((ComPtr<T>) obj)._instance.GetHashCode(); } public override int GetHashCode() { return _instance.GetHashCode(); } #endregion public ComPtr<TInterface> QueryInterface<TInterface>() where TInterface : class { var iface = Xpcom.QueryInterface<TInterface>(_instance); return iface == null ? null : new ComPtr<TInterface>(iface); } /// <summary> /// Reflection-like Mozilla API /// </summary> /// <returns></returns> internal ClassInfo GetClassInfo() { var iface = Xpcom.QueryInterface<nsIClassInfo>(_instance); return iface == null ? null : new ClassInfo(iface); } /// <summary> /// Method for getting specific function in com object /// </summary> /// <typeparam name="U"></typeparam> /// <param name="slot"></param> /// <param name="method"></param> /// <returns></returns> public bool GetComMethod<U>(int slot, out Delegate method) where U : class { IntPtr comInterfaceForObject = Marshal.GetComInterfaceForObject(_instance, typeof (T)); if (comInterfaceForObject == IntPtr.Zero) { method = null; return false; } bool flag = false; try { IntPtr ptr = Marshal.ReadIntPtr(Marshal.ReadIntPtr(comInterfaceForObject, 0), slot*IntPtr.Size); method = Marshal.GetDelegateForFunctionPointer(ptr, typeof (U)); flag = true; } finally { Marshal.Release(comInterfaceForObject); } return flag; } public int GetSlotOfComMethod(Delegate method) { if (method.Method.DeclaringType != typeof (T)) throw new ArgumentOutOfRangeException("method"); return Marshal.GetComSlotForMethodInfo(method.Method); } public T GetComMethod<T>(int slot) where T : class { Delegate method; if (!this.GetComMethod<T>(slot, out method)) throw new MethodAccessException(); return (T) (object) method; } } }
28.808917
112
0.529516
[ "MIT" ]
haga-rak/Freezer
Freezer/GeckoFX/__Core/Interop/ComPtr.cs
4,525
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Abstractions; using Swashbuckle.AspNetCore.Swagger; using Swashbuckle.AspNetCore.SwaggerGen; namespace LinCms.Web.Data { public class SwaggerFileHeaderParameter : IOperationFilter { public void Apply(Operation operation, OperationFilterContext context) { operation.Parameters = operation.Parameters ?? new List<IParameter>(); if (!context.ApiDescription.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase) && !context.ApiDescription.HttpMethod.Equals("PUT", StringComparison.OrdinalIgnoreCase)) { return; } var fileParameters = context.ApiDescription.ActionDescriptor.Parameters.Where(n => n.ParameterType == typeof(IFormFile)).ToList(); if (fileParameters.Count < 0) { return; } foreach (ParameterDescriptor fileParameter in fileParameters) { if (fileParameter.BindingInfo == null) { operation.Parameters.Add(new NonBodyParameter { Name = fileParameter.Name, In = "formData", Description = "文件上传", Required = true, Type = "file" }); operation.Consumes.Add("multipart/form-data"); } else { var parameter = operation.Parameters.Single(n => n.Name == fileParameter.Name); operation.Parameters.Remove(parameter); operation.Parameters.Add(new NonBodyParameter { Name = parameter.Name, In = "formData", Description = parameter.Description, Required = parameter.Required, Type = "file" }); operation.Consumes.Add("multipart/form-data"); } } } } }
35.484375
142
0.524879
[ "MIT" ]
crazyants/lin-cms-dotnetcore
src/LinCms.Web/Data/SwaggerFileHeaderParameter.cs
2,281
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace InventoryManagementSystemAPI.Models { public class ImageModel { [Key] public int Id { get; set; } [Required] public string ImageName { get; set; } [Required] public Uri ImageUri { get; set; } [Required] public int DepartmentId { get; set; } public DateTime CreatedAt { get; set; } } }
21.04
47
0.634981
[ "MIT" ]
Celestialy/Lagersystem-Vue-Preview
InventoryManagementSystemAPI/Models/ImageModel.cs
528
C#
// Copyright (c) KhooverSoft. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Khooversoft.Toolbox { public interface IStateManager { IReadOnlyList<IStateItem> StateItems { get; } bool IsRunning { get; } bool IsSuccessful { get; } StateContext Run(IWorkContext context); Task<StateContext> RunAsync(IWorkContext context); StateContext Test(IWorkContext context); Task<StateContext> TestAsync(IWorkContext context); } }
24.333333
111
0.716438
[ "MIT" ]
khoover768/Toolbox
Src/Dev/Khooversoft.Toolbox/Tools/StateManager/IStateManager.cs
732
C#
using Microsoft.AspNetCore.Identity; namespace Altairis.AskMe.Data.Base.Objects { public class ApplicationUser : IdentityUser<int> { } }
21
54
0.748299
[ "MIT" ]
Olbrasoft/AskMe
src/Altairis.AskMe.Data/Base/Objects/ApplicationUser.cs
149
C#
#nullable enable using System; using Content.Shared.Alert; using Content.Shared.GameObjects.Components.Mobs; using Content.Shared.GameObjects.EntitySystems; using Content.Shared.Physics; using Content.Shared.Physics.Pull; using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.GameObjects.ComponentDependencies; using Robust.Shared.GameObjects.Components; using Robust.Shared.GameObjects.Systems; using Robust.Shared.Interfaces.GameObjects; using Robust.Shared.Log; using Robust.Shared.Map; using Robust.Shared.Physics; using Robust.Shared.Serialization; namespace Content.Shared.GameObjects.Components.Pulling { public abstract class SharedPullableComponent : Component, ICollideSpecial { public override string Name => "Pullable"; public override uint? NetID => ContentNetIDs.PULLABLE; [ComponentDependency] private readonly IPhysicsComponent? _physics = default!; /// <summary> /// Only set in Puller->set! Only set in unison with _pullerPhysics! /// </summary> private IEntity? _puller; private IPhysicsComponent? _pullerPhysics; public IPhysicsComponent? PullerPhysics => _pullerPhysics; /// <summary> /// The current entity pulling this component. /// Setting this performs the entire setup process for pulling. /// </summary> public virtual IEntity? Puller { get => _puller; set { if (_puller == value) { return; } // New value. Abandon being pulled by any existing object. if (_puller != null) { var oldPuller = _puller; var oldPullerPhysics = _pullerPhysics; _puller = null; _pullerPhysics = null; if (_physics != null) { var message = new PullStoppedMessage(oldPullerPhysics, _physics); oldPuller.SendMessage(null, message); Owner.SendMessage(null, message); oldPuller.EntityManager.EventBus.RaiseEvent(EventSource.Local, message); _physics.WakeBody(); _physics.TryRemoveController<PullController>(); } // else-branch warning is handled below } // Now that is settled, prepare to be pulled by a new object. if (_physics == null) { Logger.WarningS("c.go.c.pulling", "Well now you've done it, haven't you? SharedPullableComponent on {0} didn't have an IPhysicsComponent.", Owner); return; } if (value != null) { // Pulling a new object : Perform sanity checks. if (!_canStartPull(value)) { return; } if (!value.TryGetComponent<IPhysicsComponent>(out var valuePhysics)) { return; } if (!value.TryGetComponent<SharedPullerComponent>(out var valuePuller)) { return; } // Ensure that the puller is not currently pulling anything. // If this isn't done, then it happens too late, and the start/stop messages go out of order, // and next thing you know it thinks it's not pulling anything even though it is! var oldPulling = valuePuller.Pulling; if (oldPulling != null) { if (oldPulling.TryGetComponent(out SharedPullableComponent? pullable)) { pullable.Puller = null; } else { Logger.WarningS("c.go.c.pulling", "Well now you've done it, haven't you? Someone transferred pulling to this component (on {0}) while presently pulling something that has no Pullable component (on {1})!", Owner, oldPulling); return; } } // Continue with pulling process. var pullAttempt = new PullAttemptMessage(valuePhysics, _physics); value.SendMessage(null, pullAttempt); if (pullAttempt.Cancelled) { return; } Owner.SendMessage(null, pullAttempt); if (pullAttempt.Cancelled) { return; } // Pull start confirm _puller = value; _pullerPhysics = valuePhysics; _physics.EnsureController<PullController>().Manager = this; var message = new PullStartedMessage(_pullerPhysics, _physics); _puller.SendMessage(null, message); Owner.SendMessage(null, message); _puller.EntityManager.EventBus.RaiseEvent(EventSource.Local, message); _physics.WakeBody(); } // Code here will not run if pulling a new object was attempted and failed because of the returns from the refactor. } } public bool BeingPulled => Puller != null; /// <summary> /// Sanity-check pull. This is called from Puller setter, so it will never deny a pull that's valid by setting Puller. /// It might allow an impossible pull (i.e: puller has no PhysicsComponent somehow). /// Ultimately this is only used separately to stop TryStartPull from cancelling a pull for no reason. /// </summary> private bool _canStartPull(IEntity puller) { if (!puller.HasComponent<SharedPullerComponent>()) { return false; } if (_physics == null) { return false; } if (_physics.Anchored) { return false; } if (puller == Owner) { return false; } if (!puller.IsInSameOrNoContainer(Owner)) { return false; } return true; } public bool TryStartPull(IEntity puller) { if (!_canStartPull(puller)) { return false; } TryStopPull(); Puller = puller; if (Puller != puller) { return false; } return true; } public bool TryStopPull() { if (!BeingPulled) { return false; } Puller = null; return true; } public bool TogglePull(IEntity puller) { if (BeingPulled) { if (Puller == puller) { return TryStopPull(); } else { TryStopPull(); return TryStartPull(puller); } } return TryStartPull(puller); } public bool TryMoveTo(EntityCoordinates to) { if (Puller == null) { return false; } if (_physics == null) { return false; } if (!_physics.TryGetController(out PullController controller)) { return false; } return controller.TryMoveTo(Puller.Transform.Coordinates, to); } public override ComponentState GetComponentState() { return new PullableComponentState(Puller?.Uid); } public override void HandleComponentState(ComponentState? curState, ComponentState? nextState) { base.HandleComponentState(curState, nextState); if (curState is not PullableComponentState state) { return; } if (state.Puller == null) { Puller = null; return; } if (!Owner.EntityManager.TryGetEntity(state.Puller.Value, out var entity)) { Logger.Error($"Invalid entity {state.Puller.Value} for pulling"); return; } Puller = entity; } public override void HandleMessage(ComponentMessage message, IComponent? component) { base.HandleMessage(message, component); if (message is not PullMessage pullMessage || pullMessage.Pulled.Owner != Owner) { return; } SharedAlertsComponent? pulledStatus = Owner.GetComponentOrNull<SharedAlertsComponent>(); switch (message) { case PullStartedMessage msg: if (pulledStatus != null) { pulledStatus.ShowAlert(AlertType.Pulled); } break; case PullStoppedMessage msg: if (pulledStatus != null) { pulledStatus.ClearAlert(AlertType.Pulled); } break; } } private void OnClickAlert(ClickAlertEventArgs args) { EntitySystem .Get<SharedPullingSystem>() .GetPulled(args.Player)? .GetComponentOrNull<SharedPullableComponent>()? .TryStopPull(); } public override void OnRemove() { TryStopPull(); base.OnRemove(); } public bool PreventCollide(IPhysBody collidedWith) { if (_puller == null || _physics == null) { return false; } return (_physics.CollisionLayer & collidedWith.CollisionMask) == (int) CollisionGroup.MobImpassable; } } [Serializable, NetSerializable] public class PullableComponentState : ComponentState { public readonly EntityUid? Puller; public PullableComponentState(EntityUid? puller) : base(ContentNetIDs.PULLABLE) { Puller = puller; } } }
30.785311
252
0.49376
[ "MIT" ]
BananaFlambe/space-station-14
Content.Shared/GameObjects/Components/Pulling/SharedPullableComponent.cs
10,900
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("AutoRhinoMockUnitTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("AutoRhinoMockUnitTest")] [assembly: AssemblyCopyright("Copyright © Microsoft 2010")] [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("1489ac72-1967-48b8-a302-79b2900acbe3")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.16.5.0")] [assembly: AssemblyFileVersion("3.16.5.0")]
38.783784
84
0.751916
[ "MIT" ]
amarant/AutoFixture
Src/AutoRhinoMockUnitTest/Properties/AssemblyInfo.cs
1,438
C#
// Copyright (c) Dapplo and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Newtonsoft.Json; namespace Dapplo.Jira.Entities { /// <summary> /// StatusCategory information /// </summary> [JsonObject] public class StatusCategory : BaseProperties<long> { /// <summary> /// Name of the color /// </summary> [JsonProperty("colorName")] public string ColorName { get; set; } /// <summary> /// Key for the status category /// </summary> [JsonProperty("key")] public string Key { get; set; } /// <summary> /// Name of the status category /// </summary> [JsonProperty("name")] public string Name { get; set; } } }
26.333333
101
0.565017
[ "MIT" ]
dapplo/Dapplo.Jira
src/Dapplo.Jira/Entities/StatusCategory.cs
871
C#
using System; using System.Collections.Generic; using System.Text; namespace AnyClone.Tests.TestObjects { public enum TestEnum { Test1 = 1, Test2 = 2, Test3 = 3 } }
14.5
36
0.610837
[ "Unlicense" ]
PrimusStudios/blazor-state
Tests/TestApp/Client/TestObjects/TestEnum.cs
205
C#
namespace PathFinderServer.Abilities { internal class Dexterity : Ability { public override Abilities Type { get { return Abilities.Dexterity; } } } }
19.9
47
0.58794
[ "MIT" ]
joefroh/PathfinderTool
PathfinderServer/PathFinderServer/Abilities/Dexterity.cs
201
C#
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace MvcMovie.Models { public class Movie { public int Id { get; set; } [StringLength(60, MinimumLength = 3)] public string Title { get; set; } [Display(Name = "Release Date"), DataType(DataType.Date)] public DateTime ReleaseDate { get; set; } [RegularExpression(@"^[A-Z]+[a-zA-Z""'\s-]*$"), Required, StringLength(30)] public string Genre { get; set; } [Range(1, 100), DataType(DataType.Currency)] [Column(TypeName = "decimal(18, 2)")] public decimal Price { get; set; } [RegularExpression(@"^[A-Z]+[a-zA-Z0-9""'\s-]*$"), StringLength(5)] public string Rating { get; set; } } }
29.962963
83
0.605686
[ "MIT" ]
cynicalcynic/aia
MvcMovie/Models/Movie.cs
811
C#
/** This is an automatically generated class by FairyGUI. Please do not modify it. **/ using FairyGUI; using FairyGUI.Utils; namespace GamingUI { public partial class View_effect_frozen: GComponent { public Transition t0; public const string URL = "ui://dpc3yd4tmrrjf4"; public static View_effect_frozen CreateInstance() { return (View_effect_frozen) UIPackage.CreateObject("GamingUI", "effect_frozen"); } public override void ConstructFromXML(XML xml) { base.ConstructFromXML(xml); t0 = GetTransition("t0"); } } }
25.24
92
0.637084
[ "MIT" ]
Noname-Studio/ET
Unity/Assets/Scripts/Client/UI/View/GamingUI/View_effect_frozen.cs
631
C#
using DurableLoans.LoanProcess.Models; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.DurableTask; using Microsoft.Azure.WebJobs.Extensions.SignalRService; using Microsoft.Extensions.Logging; using System; using System.Threading.Tasks; namespace DurableLoans.LoanProcess { public static partial class Functions { [FunctionName(nameof(CheckCreditAgency))] public async static Task<CreditAgencyResult> CheckCreditAgency( [ActivityTrigger] CreditAgencyRequest request, [SignalR(HubName = "dashboard")] IAsyncCollector<SignalRMessage> dashboardMessages, ILogger log) { log.LogWarning($"Checking agency {request.AgencyName} for customer {request.Application.Applicant.ToString()} for {request.Application.LoanAmount}"); await dashboardMessages.AddAsync(new SignalRMessage { Target = "agencyCheckStarted", Arguments = new object[] { request } }); var rnd = new Random(); await Task.Delay(rnd.Next(2000, 4000)); // simulate variant processing times var result = new CreditAgencyResult { IsApproved = !(request.AgencyName.Contains("Woodgrove") && request.Application.LoanAmount.Amount > 4999), Application = request.Application, AgencyId = request.AgencyId }; await dashboardMessages.AddAsync(new SignalRMessage { Target = "agencyCheckComplete", Arguments = new object[] { result } }); log.LogWarning($"Agency {request.AgencyName} {(result.IsApproved ? "APPROVED" : "DECLINED")} request by customer {request.Application.Applicant.ToString()} for {request.Application.LoanAmount}"); return result; } } }
39.44898
208
0.628039
[ "MIT" ]
bradygaster/DurableLoanProcess
DurableLoans.LoanProcess/Functions/Agencies.cs
1,933
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. Ladybugs")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("02. Ladybugs")] [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("50a52bc8-03bf-452e-af4d-ef84c4da2514")] // 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")]
37.621622
84
0.744971
[ "MIT" ]
spiderbait90/Step-By-Step-In-C-Sharp
Programming Fundamentals/Exams Practice/02. Ladybugs/Properties/AssemblyInfo.cs
1,395
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace DM.DZ1 { public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
22.727273
62
0.584
[ "MIT" ]
lukacvetkovic/DM.DZ1
DM.DZ1/App_Start/WebApiConfig.cs
502
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using AspNetMvcSample.Models; using AspNetMvcSample.Services; using Microsoft.Extensions.Options; using SaasKit.Multitenancy; using Microsoft.Extensions.Logging.Console; using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.AspNetCore.Identity; namespace AspNetMvcSample { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMultitenancy<AppTenant, CachingAppTenantResolver>(); // Add framework services. //services.AddEntityFrameworkSqlServer().AddDbContext<SqlServerApplicationDbContext>(); //services.AddIdentity<ApplicationUser, IdentityRole>() // .AddEntityFrameworkStores<SqlServerApplicationDbContext>() // .AddDefaultTokenProviders(); services.AddEntityFrameworkSqlite().AddDbContext<SqliteApplicationDbContext>(); services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<SqliteApplicationDbContext>() .AddDefaultTokenProviders(); services.AddOptions(); services.AddMvc(); services.Configure<RazorViewEngineOptions>(options => { options.ViewLocationExpanders.Add(new TenantViewLocationExpander()); }); services.Configure<MultitenancyOptions>(Configuration.GetSection("Multitenancy")); // Add application services. services.AddTransient<IEmailSender, AuthMessageSender>(); services.AddTransient<ISmsSender, AuthMessageSender>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(LogLevel.Debug); if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); // For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859 try { using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>() .CreateScope()) { serviceScope.ServiceProvider.GetService<SqlServerApplicationDbContext>() .Database.Migrate(); } } catch { } } app.UseStaticFiles(); app.UseMultitenancy<AppTenant>(); app.UseAuthentication(); // To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715 app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
35.990991
125
0.618023
[ "MIT" ]
ovidiaconescu/saaskit
samples/AspNetMvcSample/Startup.cs
3,997
C#
using System; using System.Collections.Generic; namespace WpfApp2.ChainOfResp { private List<Criteria> criterias; private Filter next; public class DurationFilter : Filter { public Filter SetNext(Filter filter) { this.next = filter; } public List<Object> filter(List<Object> objects) { // filtrer les objets selon les criteres de cette class List<Object> filtered_objects; return next.filter(filtered_objects); } } }
21.48
67
0.612663
[ "MIT" ]
metidjisidahmed/EsiCOS-SourceCode-Software-Redesign
Noyau/ChainOfResp/DurationFilter.cs
537
C#
using Assertion; using Lemonad.ErrorHandling.Extensions; using Xunit; namespace Lemonad.ErrorHandling.Unit.Result.Tests { public class ToResultTests { [Fact] public void Create_Result_From_Value_With_False_Predicate() { var predicateExecuted = false; var errorSelectorExecuted = false; "value".ToResult(x => { predicateExecuted = true; return string.IsNullOrWhiteSpace(x); }, x => { errorSelectorExecuted = true; return "ERROR"; }).AssertError("ERROR"); Assert.True(predicateExecuted); Assert.True(errorSelectorExecuted); } [Fact] public void Create_Result_From_Value_With_True_Predicate() { var predicateExecuted = false; var errorSelectorExecuted = false; "value".ToResult(x => { predicateExecuted = true; return string.IsNullOrWhiteSpace(x) == false; }, x => { errorSelectorExecuted = true; return "ERROR"; }) .AssertValue("value"); Assert.True(predicateExecuted); Assert.False(errorSelectorExecuted); } [Fact] public void Passing_None_Null_Value_With_Null_Check_Predicate_Does_Not_Throw() { var exception = Record.Exception(() => "foo".ToResult(s => s is null == false, _ => "null value").AssertValue("foo")); Assert.Null(exception); } [Fact] public void Passing_Null_Value_With_Null_Check_Predicate_Does_Not_Throw() { string x = null; var exception = Record.Exception(() => x.ToResult(s => s is null == false, s => s ?? "null value").AssertError("null value")); Assert.Null(exception); } } }
36.471698
103
0.551992
[ "MIT" ]
inputfalken/Lemonad
test/Lemonad.ErrorHandling.Unit/Result.Tests/ToResultTests.cs
1,935
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("SwaggerGenerator")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SwaggerGenerator")] [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("f9cc4f22-2e6e-4254-bde5-f1be71e28dcb")] // 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")]
37.837838
84
0.749286
[ "MIT" ]
mover5/SwaggerGenerator
SwaggerGenerator/Properties/AssemblyInfo.cs
1,403
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 codestar-notifications-2019-10-15.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.CodeStarNotifications.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.CodeStarNotifications.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for LimitExceededException Object /// </summary> public class LimitExceededExceptionUnmarshaller : IErrorResponseUnmarshaller<LimitExceededException, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public LimitExceededException Unmarshall(JsonUnmarshallerContext context) { return this.Unmarshall(context, new Amazon.Runtime.Internal.ErrorResponse()); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <param name="errorResponse"></param> /// <returns></returns> public LimitExceededException Unmarshall(JsonUnmarshallerContext context, Amazon.Runtime.Internal.ErrorResponse errorResponse) { context.Read(); LimitExceededException unmarshalledObject = new LimitExceededException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { } return unmarshalledObject; } private static LimitExceededExceptionUnmarshaller _instance = new LimitExceededExceptionUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static LimitExceededExceptionUnmarshaller Instance { get { return _instance; } } } }
35.611765
135
0.675586
[ "Apache-2.0" ]
EbstaLimited/aws-sdk-net
sdk/src/Services/CodeStarNotifications/Generated/Model/Internal/MarshallTransformations/LimitExceededExceptionUnmarshaller.cs
3,027
C#
using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Abp.Application.Services; using Abp.Application.Services.Dto; using Abp.Authorization; using Abp.Domain.Repositories; using Abp.Extensions; using Abp.IdentityFramework; using Abp.MultiTenancy; using Abp.Runtime.Security; using MediaShare.Authorization; using MediaShare.Authorization.Roles; using MediaShare.Authorization.Users; using MediaShare.Editions; using MediaShare.MultiTenancy.Dto; namespace MediaShare.MultiTenancy { [AbpAuthorize(PermissionNames.Pages_Tenants)] public class TenantAppService : AsyncCrudAppService<Tenant, TenantDto, int, PagedResultRequestDto, CreateTenantDto, TenantDto>, ITenantAppService { private readonly TenantManager _tenantManager; private readonly EditionManager _editionManager; private readonly UserManager _userManager; private readonly RoleManager _roleManager; private readonly IAbpZeroDbMigrator _abpZeroDbMigrator; private readonly IPasswordHasher<User> _passwordHasher; public TenantAppService( IRepository<Tenant, int> repository, TenantManager tenantManager, EditionManager editionManager, UserManager userManager, RoleManager roleManager, IAbpZeroDbMigrator abpZeroDbMigrator, IPasswordHasher<User> passwordHasher) : base(repository) { _tenantManager = tenantManager; _editionManager = editionManager; _userManager = userManager; _roleManager = roleManager; _abpZeroDbMigrator = abpZeroDbMigrator; _passwordHasher = passwordHasher; } public override async Task<TenantDto> Create(CreateTenantDto input) { CheckCreatePermission(); // Create tenant var tenant = ObjectMapper.Map<Tenant>(input); tenant.ConnectionString = input.ConnectionString.IsNullOrEmpty() ? null : SimpleStringCipher.Instance.Encrypt(input.ConnectionString); var defaultEdition = await _editionManager.FindByNameAsync(EditionManager.DefaultEditionName); if (defaultEdition != null) { tenant.EditionId = defaultEdition.Id; } await _tenantManager.CreateAsync(tenant); await CurrentUnitOfWork.SaveChangesAsync(); // To get new tenant's id. // Create tenant database _abpZeroDbMigrator.CreateOrMigrateForTenant(tenant); // We are working entities of new tenant, so changing tenant filter using (CurrentUnitOfWork.SetTenantId(tenant.Id)) { // Create static roles for new tenant CheckErrors(await _roleManager.CreateStaticRoles(tenant.Id)); await CurrentUnitOfWork.SaveChangesAsync(); // To get static role ids // Grant all permissions to admin role var adminRole = _roleManager.Roles.Single(r => r.Name == StaticRoleNames.Tenants.Admin); await _roleManager.GrantAllPermissionsAsync(adminRole); // Create admin user for the tenant var adminUser = User.CreateTenantAdminUser(tenant.Id, input.AdminEmailAddress); adminUser.Password = _passwordHasher.HashPassword(adminUser, User.DefaultPassword); CheckErrors(await _userManager.CreateAsync(adminUser)); await CurrentUnitOfWork.SaveChangesAsync(); // To get admin user's id // Assign admin user to role! CheckErrors(await _userManager.AddToRoleAsync(adminUser, adminRole.Name)); await CurrentUnitOfWork.SaveChangesAsync(); } return MapToEntityDto(tenant); } protected override void MapToEntity(TenantDto updateInput, Tenant entity) { // Manually mapped since TenantDto contains non-editable properties too. entity.Name = updateInput.Name; entity.TenancyName = updateInput.TenancyName; entity.IsActive = updateInput.IsActive; } public override async Task Delete(EntityDto<int> input) { CheckDeletePermission(); var tenant = await _tenantManager.GetByIdAsync(input.Id); await _tenantManager.DeleteAsync(tenant); } private void CheckErrors(IdentityResult identityResult) { identityResult.CheckErrors(LocalizationManager); } } }
39.330508
149
0.659987
[ "MIT" ]
tigeryzx/MediaShare
aspnet-core/src/MediaShare.Application/MultiTenancy/TenantAppService.cs
4,641
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.Network.Latest.Outputs { [OutputType] public sealed class ExpressRouteCircuitSkuResponse { /// <summary> /// The family of the SKU. /// </summary> public readonly string? Family; /// <summary> /// The name of the SKU. /// </summary> public readonly string? Name; /// <summary> /// The tier of the SKU. /// </summary> public readonly string? Tier; [OutputConstructor] private ExpressRouteCircuitSkuResponse( string? family, string? name, string? tier) { Family = family; Name = name; Tier = tier; } } }
24.44186
81
0.576594
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Network/Latest/Outputs/ExpressRouteCircuitSkuResponse.cs
1,051
C#
using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using CoreGraphics; using Foundation; using UIKit; using Firebase.Auth; using Firebase.CloudFirestore; namespace CloudFirestoreSample { public partial class FoldersTableViewController : UITableViewController { #region Class Variables UIBarButtonItem space; UIBarButtonItem btnNewFolder; UIRefreshControl refreshControl; UIActivityIndicatorView indicatorView; Auth auth; List<Folder> folders; // Reference that points to user data. DocumentReference userDocument; // Reference that points to user's folders CollectionReference foldersCollection; #endregion #region Constructors public FoldersTableViewController (IntPtr handle) : base (handle) { } #endregion #region Controller Life Cycle public override void ViewDidLoad () { base.ViewDidLoad (); // Perform any additional setup after loading the view, typically from a nib. InitializeComponents (); } public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); LoadFolders (); } #endregion #region User Interaction // If for some reason you cannot login anonymously, you can try again by pulling down the Table View void RefreshControl_ValueChanged (object sender, EventArgs e) { TableView.UserInteractionEnabled = false; LoadFolders (); } // Gets the folder name and verifies that folder name is written correctly void btnNewFolder_Clicked (object sender, EventArgs e) { indicatorView.StartAnimating (); UIAlertHelper.ShowMessage ("Create a new folder", "Type a folder name.\nName can contain letters, numbers, spaces, dashes and underscores only", NavigationController, "Create", new [] { "Folder name" }, HandleUIAlertControllerTextFieldResult); void HandleUIAlertControllerTextFieldResult (bool alertCanceled, string [] textfieldInputs) { if (alertCanceled) { indicatorView.StopAnimating (); return; } var folderName = textfieldInputs [0].Trim (); if (string.IsNullOrWhiteSpace (folderName)) { UIAlertHelper.ShowMessage ("Empty name!", "A folder name cannot be a space or an empty name.", NavigationController, "Ok"); return; } if (!VerifyFolderName (folderName)) { UIAlertHelper.ShowMessage ("Bad folder name!", "A name can contain letters, numbers, spaces, dashes and underscores only.", NavigationController, "Ok"); return; } if (VerifyIfFolderExists (folderName)) { UIAlertHelper.ShowMessage ("Folder exists!", "A folder with that name already exists.", NavigationController, "Ok"); return; } Task.Factory.StartNew (async () => { try { await CreateFolder (folderName); } catch (NSErrorException ex) { InvokeOnMainThread (() => { UIAlertHelper.ShowMessage ("Error while creating new folder", ex.Error.LocalizedDescription, NavigationController, "Ok"); }); } finally { InvokeOnMainThread (() => indicatorView.StopAnimating ()); } }); } } #endregion #region Navigation public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) { base.PrepareForSegue (segue, sender); if (segue.Identifier != "DefaultSegue") return; var notesTableViewController = segue.DestinationViewController as NotesTableViewController; notesTableViewController.Folder = folders [TableView.IndexPathForSelectedRow.Row]; notesTableViewController.FoldersCollection = foldersCollection; } #endregion #region UITableView Data Source public override nint NumberOfSections (UITableView tableView) => 1; public override nint RowsInSection (UITableView tableView, nint section) => folders.Count == 0 ? 1 : folders.Count; public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { if (folders.Count == 0) return tableView.DequeueReusableCell ("DefaultTableViewCell", indexPath); var folder = folders [indexPath.Row]; var cell = tableView.DequeueReusableCell (FolderTableViewCell.Key, indexPath); cell.TextLabel.Text = folder.Name; cell.DetailTextLabel.Text = folder.NotesCount.ToString (); return cell; } public override bool CanEditRow (UITableView tableView, NSIndexPath indexPath) => true; public override void CommitEditingStyle (UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath) { indicatorView.StartAnimating (); if (editingStyle != UITableViewCellEditingStyle.Delete) return; // Delete the folder from the TableView so user cannot get access to it while deleting var folder = folders [indexPath.Row]; folders.Remove (folder); if (folders.Count == 0) tableView.ReloadRows (new [] { indexPath }, UITableViewRowAnimation.Automatic); else tableView.DeleteRows (new [] { indexPath }, UITableViewRowAnimation.Automatic); Task.Factory.StartNew (async () => { try { // Remove the folder from the Cloud Firestore await DeleteFolder (folder); } catch (NSErrorException ex) { // If something fails while deleting the folder, add it again to the TableView folders.Insert (indexPath.Row, folder); InvokeOnMainThread (() => { UIAlertHelper.ShowMessage ("Error while deleting the folder", ex.Error.LocalizedDescription, NavigationController, "Ok", () => { // Due subcollections (in this case, the folder's notes) must be manually deleted, // some of them could have been deleted when we were trying to delete the folder UIAlertHelper.ShowMessage ("Error while deleting the folder", "Some notes could have been deleted during the process.\nTry deleting the folder again to finish the process.", NavigationController, "Ok"); }); if (folders.Count == 1) tableView.ReloadRows (new [] { indexPath }, UITableViewRowAnimation.Automatic); else tableView.InsertRows (new [] { indexPath }, UITableViewRowAnimation.Automatic); }); } finally { folder = null; InvokeOnMainThread (() => indicatorView.StopAnimating ()); } }); } #endregion #region Internal Functionality void InitializeComponents () { folders = new List<Folder> (); auth = Auth.DefaultInstance; space = new UIBarButtonItem (UIBarButtonSystemItem.FlexibleSpace); indicatorView = new UIActivityIndicatorView (UIActivityIndicatorViewStyle.White) { Frame = new CGRect (0, 0, 20, 20), HidesWhenStopped = true }; var btnIndicator = new UIBarButtonItem (indicatorView); btnNewFolder = new UIBarButtonItem ("New Folder", UIBarButtonItemStyle.Plain, btnNewFolder_Clicked) { TintColor = UIColor.White, }; SetToolbarItems (new [] { space, btnIndicator, space, btnNewFolder }, false); refreshControl = new UIRefreshControl (); refreshControl.AddTarget (RefreshControl_ValueChanged, UIControlEvent.ValueChanged); TableView.RefreshControl = refreshControl; } void LoadFolders () { indicatorView.StartAnimating (); btnNewFolder.Enabled = false; Task.Factory.StartNew (LoadFoldersAsync); async Task LoadFoldersAsync () { // Verify if you have already logged in to Firebase Anonymously if (string.IsNullOrWhiteSpace (AppDelegate.UserUid)) if (!await SignIn ()) return; InitializeFirestoreReferences (); try { await AddUserToFirestoreIfNeeded (); await GetFolders (); } catch (NSErrorException ex) { InvokeOnMainThread (() => { UIAlertHelper.ShowMessage ("An error has ocurred...", ex.Error.LocalizedDescription, NavigationController, "Ok"); }); } catch (Exception ex) { Console.WriteLine (ex.Message); } finally { InvokeOnMainThread (() => { indicatorView.StopAnimating (); refreshControl.EndRefreshing (); btnNewFolder.Enabled = true; TableView.UserInteractionEnabled = true; }); } } } async Task<bool> SignIn () { try { AuthDataResult authData = await auth.SignInAnonymouslyAsync (); AppDelegate.UserUid = authData.User.Uid; return true; } catch (NSErrorException ex) { AuthErrorCode errorCode; if (IntPtr.Size == 8) // 64 bits devices errorCode = (AuthErrorCode)((long)ex.Error.Code); else // 32 bits devices errorCode = (AuthErrorCode)((int)ex.Error.Code); var title = "Anonymous sign-in failed!"; var buttonTitle = "Ok"; var message = new StringBuilder (); // Posible error codes that SignInAnonymously method could throw // Visit https://firebase.google.com/docs/auth/ios/errors for more information switch (errorCode) { case AuthErrorCode.OperationNotAllowed: message.AppendLine ("The app uses Anonymous sign-in to work correctly and seems to be disabled…"); message.AppendLine ("Please, go to Firebase console and enable Anonymous login."); message.Append ("Open «Application Output» in Xamarin Studio for more information."); buttonTitle = "Ok, let me enable it!"; Console.WriteLine ("Anonymous sign-in seems to be disabled. Please, visit the following link to know how " + "to enable it: https://firebase.google.com/docs/auth/ios/anonymous-auth#before-you-begin"); break; case AuthErrorCode.NetworkError: message.AppendLine ("Seems to be the first time that you run the sample and you don't have access to internet."); message.Append ("The sample needs to run with internet at least once so you can create an Anonymous user."); break; default: message.Append ("An unknown error has ocurred…"); break; } InvokeOnMainThread (() => { indicatorView.StopAnimating (); UIAlertHelper.ShowMessage (title, message.ToString (), NavigationController, buttonTitle); }); return false; } } void InitializeFirestoreReferences () { userDocument = AppDelegate.Database.GetDocument ($"notes_app/{AppDelegate.UserUid}"); foldersCollection = userDocument.GetCollection ("folders"); } // Create user in Firebase Cloud Firestore if not exist async Task AddUserToFirestoreIfNeeded () { var user = await userDocument.GetDocumentAsync (); if (user.Exists) return; var userData = new Dictionary<object, object> { { "created", FieldValue.ServerTimestamp } }; await userDocument.SetDataAsync (userData); } // Get folders data to be shown in TableView async Task GetFolders () { folders.Clear (); var foldersQuery = await foldersCollection.OrderedBy ("lastModified", true) .GetDocumentsAsync (); foreach (var folder in foldersQuery.Documents) { var data = folder.Data; var created = data ["created"] as NSDate; var lastModified = data ["lastModified"] as NSDate; var name = data ["name"].ToString (); var notesCount = (data ["notesCount"] as NSNumber).NUIntValue; folders.Add (new Folder { Id = folder.Id, Name = name, Created = AppDelegate.GetFormattedDate (created), LastModified = AppDelegate.GetFormattedDate (lastModified), NotesCount = notesCount }); } // If we finished reading folders, refresh the Table View InvokeOnMainThread (() => TableView.ReloadData ()); } // Creates the folder in Firebase Firestore async Task CreateFolder (string folderName) { // Create folder key node var folderId = folderName.Replace (' ', '_'); folderId = char.ToLower (folderId [0]) + folderId.Substring (1, folderId.Length - 1); // Create data to be saved in node var created = FieldValue.ServerTimestamp; var folderData = new Dictionary<object, object> { { "created", created }, { "lastModified", created }, { "name", folderName }, { "notesCount", 0 } }; // Save data in folders collection await foldersCollection.GetDocument (folderId).SetDataAsync (folderData); await GetFolders (); } // Erase all data from a folder document async Task DeleteFolder (Folder folder) { var folderDocument = foldersCollection.GetDocument (folder.Id); // Note: Deleting a document does not delete its subcollections! // If you want to delete documents in subcollections when // deleting a document, you must do so manually. var notesCollection = folderDocument.GetCollection ("notes"); await DeleteNotes (folder, folderDocument, notesCollection, 10); await folderDocument.DeleteDocumentAsync (); } async Task DeleteNotes (Folder folder, DocumentReference folderDocument, CollectionReference notesCollection, int batchSize) { // Limit query to avoid out-of-memory errors on large collections. // When deleting a collection guaranteed to fit in memory, batching can be avoided entirely. var notes = await notesCollection.LimitedTo (batchSize).GetDocumentsAsync (); // There's nothing to delete. if (notes.Count == 0) return; var batch = notesCollection.Firestore.CreateBatch (); foreach (var note in notes.Documents) batch.DeleteDocument (note.Reference); var folderData = new Dictionary<object, object> { { "notesCount", folder.NotesCount - (nuint)notes.Count } }; batch.UpdateData (folderData, folderDocument); await batch.CommitAsync (); folder.NotesCount -= (nuint)notes.Count; await DeleteNotes (folder, folderDocument, notesCollection, batchSize); } bool VerifyIfFolderExists (string name) => folders.Exists (f => f.Name == name); // Verifies that name only contains alphanumeric, dashes, underscores and spaces bool VerifyFolderName (string name) => Regex.IsMatch (name, @"^[\w -]+$"); #endregion } }
32.14554
209
0.706295
[ "MIT" ]
DigitallyImported/GoogleApisForiOSComponents
samples/Firebase/CloudFirestore/CloudFirestoreSample/Controllers/FoldersTableViewController.cs
13,702
C#
using System; using System.Collections.Generic; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using static Albot.Snake.SnakeStructs; using static Albot.Snake.SnakeConstants; using static Albot.Constants; namespace Albot.Snake { internal static class SnakeJsonHandler { private static JsonSerializer serializer = new JsonSerializer { NullValueHandling = NullValueHandling.Ignore }; private static JObject SerializeBoard(SnakeBoard board) { JObject jObject = new JObject( new JProperty(JProtocol.player, JObject.FromObject(board.player)), new JProperty(JProtocol.enemy, JObject.FromObject(board.enemy)) ); //if (includeBlocked) jObject.Add(new JProperty(JProtocol.blocked, JArray.FromObject(board.GetBlockedList(false)))); return jObject; } #region CreateCommand /* internal static string CreateDirectionCommand(string direction) { JObject jsonCommand = new JObject( new JProperty(JProtocol.dir, direction) ); Console.WriteLine("Direction Command: \n" + jsonCommand + "\n"); return jsonCommand.ToString(); } */ internal static string CreateCommandPossibleMoves(SnakeBoard board) { JObject jsonCommand = new JObject( new JProperty(Constants.Fields.action, Actions.getPossMoves), new JProperty(JProtocol.player, board.GetPlayerDirection()), new JProperty(JProtocol.enemy, board.GetEnemyDirection()) ); //Console.WriteLine("PossibleMoves Command: \n" + jsonCommand + "\n"); return jsonCommand.ToString(); } internal static string CreateCommandSimulateBoth(SnakeBoard board, MovesToSimulate simMoves) { return CreateCommandSimulate(board, simMoves, Actions.simMove); } internal static string CreateCommandSimulatePlayer(SnakeBoard board, MovesToSimulate simMoves) { return CreateCommandSimulate(board, simMoves, JProtocol.simPlayerMove); } internal static string CreateCommandSimulateEnemy(SnakeBoard board, MovesToSimulate simMoves) { return CreateCommandSimulate(board, simMoves, JProtocol.simEnemyMove); } private static string CreateCommandSimulate(SnakeBoard board, MovesToSimulate simMoves, string action) { JObject jsonCommand = new JObject( new JProperty(Constants.Fields.action, action), JObject.FromObject(simMoves, serializer).Children(), new JProperty(JProtocol.board, SerializeBoard(board)) ); //Console.WriteLine("Simulate Command: \n" + jsonCommand + "\n"); return jsonCommand.ToString(); //return FixVariableNamings(jsonCommand.ToString()); } internal static string CreateCommandEvaluate(SnakeBoard board) { JObject jsonCommand = new JObject( new JProperty(Constants.Fields.action, Actions.evalBoard), new JProperty(JProtocol.board, SerializeBoard(board)) ); //Console.WriteLine("Evaluate command: \n" + jsonCommand + "\n"); return jsonCommand.ToString(); } #endregion #region ParseResponse internal static BoardStruct ParseResponseState(JObject jState) { //Console.WriteLine("Response state: " + "\n" + jResponse.ToString()); return jState.ToObject<BoardStruct>(); } internal static PossibleMoves ParseResponsePossibleMoves(string response) { PossibleMoves possMoves = JsonHandler.TryDeserialize<PossibleMoves>(response); //Console.WriteLine("Response possMoves: " + "\n" + JObject.Parse(response).ToString()); return possMoves; } internal static SnakeBoard ParseResponseSimulate(string response) { //Console.WriteLine(response); JObject jBoard = JsonHandler.TryParse(response); //Console.WriteLine("Response simulate: \n" + jBoard.ToString()); return new SnakeBoard(jBoard.ToObject<BoardStruct>()); } internal static BoardState ParseResponseEvaluate(string response) { JObject jState = JsonHandler.TryParse(response); //Console.WriteLine("Response evaluate: \n" + jState + "\n"); return JsonHandler.FetchBoardState(jState); } #endregion } }
41.141593
119
0.63519
[ "MIT" ]
Albot-Online/Albot-CSharp-Library
Albot/Snake/SnakeJsonHandler.cs
4,651
C#
using System.Drawing; using System.IO; namespace ControlLibrary { public class Tags { public static Image GetMetaImage(string MusicPath) { TagLib.File f = new TagLib.Mpeg.AudioFile(MusicPath); var pic = f.Tag.Pictures[0]; using (var ms = new MemoryStream(pic.Data.Data)) { var image = Image.FromStream(ms); return image; } } } }
21.857143
65
0.535948
[ "MIT" ]
MalauD/Musics-Free-musics-player
ControlLibrary/MusicUtils/Tags.cs
459
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Numerics; using Windows.UI; using Windows.UI.Composition; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Hosting; namespace VanArsdel { public sealed partial class Shadow : UserControl { public Shadow() { this.InitializeComponent(); } private void UserControl_Loaded(object sender, RoutedEventArgs e) { InitializeShadow(); ResizeShadow(); } private void UserControl_Unloaded(object sender, RoutedEventArgs e) { DisposeShadow(); } private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e) { ResizeShadow(); } #region ElevationProperty public static DependencyProperty ElevationProperty = DependencyProperty.Register("Elevation", typeof(double), typeof(Shadow), new PropertyMetadata((double)1, new PropertyChangedCallback(OnElevationPropertyChanged))); private static void OnElevationPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is Shadow target) { target.OnElevationChanged((double)e.OldValue, (double)e.NewValue); } } private void OnElevationChanged(double oldValue, double newValue) { UpdateShadowValues(); } public double Elevation { get { return (double)GetValue(ElevationProperty); } set { SetValue(ElevationProperty, value); } } #endregion #region ColorProperty public static readonly DependencyProperty ColorProperty = DependencyProperty.Register("Color", typeof(Color), typeof(Shadow), new PropertyMetadata(Colors.Black, new PropertyChangedCallback(OnColorPropertyChanged))); private static void OnColorPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is Shadow target) { target.OnColorChanged((Color)e.OldValue, (Color)e.NewValue); } } private void OnColorChanged(Color oldValue, Color newValue) { UpdateShadowValues(); } public Color Color { get { return (Color)GetValue(ColorProperty); } set { SetValue(ColorProperty, value); } } #endregion private ContainerVisual _shadowContainer; private DropShadow _shadowDirectional; private DropShadow _shadowAmbient; private SpriteVisual _shadowDirectionalVisual; private SpriteVisual _shadowAmbientVisual; private void InitializeShadow() { if (_shadowDirectional != null) { DisposeShadow(); } var compositor = Window.Current.Compositor; _shadowContainer = compositor.CreateContainerVisual(); _shadowAmbientVisual = compositor.CreateSpriteVisual(); _shadowAmbient = compositor.CreateDropShadow(); _shadowAmbientVisual.Shadow = _shadowAmbient; _shadowDirectionalVisual = compositor.CreateSpriteVisual(); _shadowDirectional = compositor.CreateDropShadow(); _shadowDirectionalVisual.Shadow = _shadowDirectional; _shadowContainer.Children.InsertAtTop(_shadowAmbientVisual); _shadowContainer.Children.InsertAtTop(_shadowDirectionalVisual); ElementCompositionPreview.SetElementChildVisual(PlaceholderElement, _shadowContainer); UpdateShadowValues(); } private void DisposeShadow() { if (_shadowAmbient != null) { _shadowAmbient.Dispose(); _shadowAmbient = null; } if (_shadowAmbientVisual != null) { _shadowAmbientVisual.Dispose(); _shadowAmbientVisual = null; } if (_shadowDirectional != null) { _shadowDirectional.Dispose(); _shadowDirectional = null; } if (_shadowDirectionalVisual != null) { _shadowDirectionalVisual.Dispose(); _shadowDirectionalVisual = null; } } private void ResizeShadow() { if (_shadowDirectionalVisual != null) { _shadowDirectionalVisual.Size = new Vector2((float)PlaceholderElement.ActualWidth, (float)PlaceholderElement.ActualHeight); } if (_shadowAmbientVisual != null) { _shadowAmbientVisual.Size = new Vector2((float)PlaceholderElement.ActualWidth, (float)PlaceholderElement.ActualHeight); } } private void UpdateShadowValues() { var e = (float)Elevation; var o = e < 24 ? 1 : 0.6f; if (_shadowDirectionalVisual != null) { _shadowDirectional.BlurRadius = (e * 0.9f); _shadowDirectional.Opacity = o * 0.22f; _shadowDirectional.Offset = new Vector3(0, e * 0.4f, 0); _shadowDirectional.Color = Color; } if (_shadowAmbientVisual != null) { _shadowAmbient.BlurRadius = (e * 0.225f); _shadowAmbient.Opacity = o * 0.18f; _shadowAmbient.Offset = new Vector3(0, e * 0.0075f, 0); _shadowAmbient.Color = Color; } } } }
32.611429
224
0.593306
[ "MIT" ]
Bhaskers-Blu-Org2/VanArsdel
VanArsdel/Controls/Shadow.xaml.cs
5,709
C#
using Microsoft.EntityFrameworkCore; using CarvedRock.Api.Models; namespace CarvedRock.Api.Data { public class CarvedRockContext : DbContext { public CarvedRockContext(DbContextOptions<CarvedRockContext> options) : base(options) { } public DbSet<WishlistItem> WishlistItems { get; set; } } }
22.625
77
0.651934
[ "Unlicense" ]
urlichLivonian/azure-b2c-samples
m4/CarvedRock.Api/Data/CarvedRockContext.cs
362
C#
namespace Dxw.Throttling.Asp.Keyers { using System.Net.Http; using Core.Keyers; using Core; using Core.Logging; using Core.Configuration; using System.Xml; public class URIMethodKeyer : IKeyer<IAspArgs>, IXmlConfigurable { private ILog _log; public object GetKey(IAspArgs args) { var request = args.Request; return new { request.RequestUri, request.Method }; } public void Configure(XmlNode node, IConfiguration context) { _log = context.Log; _log.Log(LogLevel.Debug, string.Format("Configuring keyer of type '{0}'", GetType().FullName)); } } }
24.642857
107
0.608696
[ "MIT" ]
dlatushkin/Dxw.Throttling
Source/Projects/Dxw.Throttling.Asp/Keyers/URIMethodKeyer.cs
692
C#
#region License /* The MIT License Copyright (c) 2008 Sky Morey 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 namespace System.Web { internal interface IActivationMethodAttribute { void InvokeMethod(); } }
36.882353
78
0.76555
[ "MIT" ]
Grimace1975/bclcontrib-web
System.WebEx/Web+Activation/IActivationMethodAttribute.cs
1,256
C#
namespace Incoding.Data { #region << Using >> using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Incoding.Extensions; #endregion public abstract class AdHocFetchSpecificationBase<TEntity> { #region Fields internal readonly List<Func<IQueryable<TEntity>, IQueryable<TEntity>>> applies = new List<Func<IQueryable<TEntity>, IQueryable<TEntity>>>(); protected readonly List<Expression> expressions = new List<Expression>(); #endregion #region Api Methods public abstract AdHocFetchSpecificationBase<TEntity> Join<TValue>(Expression<Func<TEntity, TValue>> expression); public abstract AdHocFetchSpecificationBase<TEntity> Join<TChild>(Expression<Func<TEntity, TChild>> expression, Expression<Func<TChild, object>> thenFetch); public abstract AdHocFetchSpecificationBase<TEntity> Join<TChild, TNextChild>(Expression<Func<TEntity, TChild>> expression, Expression<Func<TChild, TNextChild>> thenFetch, Expression<Func<TNextChild, object>> nextThenChild); public abstract AdHocFetchSpecificationBase<TEntity> Join<TChild, TNextChild>(Expression<Func<TEntity, TChild>> expression, Expression<Func<TChild, IEnumerable<TNextChild>>> thenFetch, Expression<Func<TNextChild, object>> thenThenFetch); public abstract AdHocFetchSpecificationBase<TEntity> JoinMany<TChild>(Expression<Func<TEntity, IEnumerable<TChild>>> fetch, Expression<Func<TChild, object>> thenFetch); public abstract AdHocFetchSpecificationBase<TEntity> JoinMany<TChild, TNextChild>(Expression<Func<TEntity, IEnumerable<TChild>>> fetch, Expression<Func<TChild, TNextChild>> thenFetch, Expression<Func<TNextChild, object>> thenThenFetch); public abstract AdHocFetchSpecificationBase<TEntity> JoinMany<TChild, TNextChild>(Expression<Func<TEntity, IEnumerable<TChild>>> fetch, Expression<Func<TChild, IEnumerable<TNextChild>>> thenFetch, Expression<Func<TNextChild, object>> thenThenFetch); #endregion #region Equals public override bool Equals(object obj) { return this.IsReferenceEquals(obj) && Equals(obj as AdHocFetchNhibernateSpecification<TEntity>); } ////ncrunch: no coverage start public override int GetHashCode() { return 0; } ////ncrunch: no coverage end /// protected bool Equals(AdHocFetchNhibernateSpecification<TEntity> other) { if (this.expressions.Count != other.expressions.Count) { Console.WriteLine(Resources.AdHocFetchSpecification_Equal_diffrent_count_expressions.F(this.expressions.Count, other.expressions.Count)); return false; } for (int i = 0; i < this.expressions.Count; i++) { if (!this.expressions[i].IsExpressionEqual(other.expressions[i])) { Console.WriteLine(Resources.AdHocFetchSpecification_Equal_diffrent_expressions.F(this.expressions[i], other.expressions[i])); return false; } } return true; } #endregion } }
41.75641
257
0.6856
[ "Apache-2.0" ]
Incoding-Software/Incoding-Framework
src/Incoding/Data/Core/Specifications/Fetch/AdHocFetchSpecificationBase.cs
3,259
C#
using Document.Library.Entity; using Document.Library.Entity.Exceptions; using Document.Library.Globals; using Document.Library.Globals.Enum; using Document.Library.Repo; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Document.Library.ServiceLayer { public static class UserServices { public static UserProfile Add(string name, string email, string phone, string password, string confirmPassword, string company) { try { bool isValidEmail = Validator.IsValidEmail(email); if (!isValidEmail) { throw new RequestForbidden(new ErrorResponse(ErrorResponseCode.InvalidRequestError, Messages.InvalidEmail)); } bool isValidPassword = Validator.IsValidPassword(password); if(!isValidPassword) { throw new RequestForbidden(new ErrorResponse(ErrorResponseCode.UserAccessDenied, Messages.InvalidPassword)); } if(IsUserExists(email)) { throw new RequestForbidden(new ErrorResponse(ErrorResponseCode.UserAccessDenied, Messages.RegisterIfEmailExists)); } //User is verified by default. Need to add code to send verification link to user. UserProfile _user = new UserRepository().Add(name, email, phone, password, company); if(_user == null) { throw new Exception(Messages.InternalServerError); } EmailServices.Send(email, "", "user registered successfully", "Please click this link to verify"); //SharingServices.UpdateSharedObjectForNewUser(_user.Id, _user.Email); return _user; } catch { throw; } } public static bool IsUserExists(string email) { return new UserRepository().IsUserExists(email); } public static void SaveName(string fullName) { new UserRepository().SaveName(fullName); } } }
29.179487
135
0.588752
[ "MIT" ]
Shivam4415/RudderStack-assignment-GarmentStore
Document.Library.ServiceLayer/UserServices.cs
2,278
C#
using System.Runtime.CompilerServices; namespace Farmhash.Sharp.Benchmarks { /// <summary> /// Taken from https://github.com/ravendb/ravendb/blob/b87a422e91dcf7d4590bad631c9266258be7cab3/Raven.Sparrow/Sparrow/Hashing.cs /// </summary> class SparrowHashing { /// <summary> /// A port of the original XXHash algorithm from Google in 32bits /// </summary> /// <<remarks>The 32bits and 64bits hashes for the same data are different. In short those are 2 entirely different algorithms</remarks> public static class XXHash32 { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe uint CalculateInline(byte* buffer, int len, uint seed = 0) { unchecked { uint h32; byte* bEnd = buffer + len; if (len >= 16) { byte* limit = bEnd - 16; uint v1 = seed + PRIME32_1 + PRIME32_2; uint v2 = seed + PRIME32_2; uint v3 = seed + 0; uint v4 = seed - PRIME32_1; do { v1 += *((uint*)buffer) * PRIME32_2; buffer += sizeof(uint); v2 += *((uint*)buffer) * PRIME32_2; buffer += sizeof(uint); v3 += *((uint*)buffer) * PRIME32_2; buffer += sizeof(uint); v4 += *((uint*)buffer) * PRIME32_2; buffer += sizeof(uint); v1 = RotateLeft32(v1, 13); v2 = RotateLeft32(v2, 13); v3 = RotateLeft32(v3, 13); v4 = RotateLeft32(v4, 13); v1 *= PRIME32_1; v2 *= PRIME32_1; v3 *= PRIME32_1; v4 *= PRIME32_1; } while (buffer <= limit); h32 = RotateLeft32(v1, 1) + RotateLeft32(v2, 7) + RotateLeft32(v3, 12) + RotateLeft32(v4, 18); } else { h32 = seed + PRIME32_5; } h32 += (uint)len; while (buffer + 4 <= bEnd) { h32 += *((uint*)buffer) * PRIME32_3; h32 = RotateLeft32(h32, 17) * PRIME32_4; buffer += 4; } while (buffer < bEnd) { h32 += (uint)(*buffer) * PRIME32_5; h32 = RotateLeft32(h32, 11) * PRIME32_1; buffer++; } h32 ^= h32 >> 15; h32 *= PRIME32_2; h32 ^= h32 >> 13; h32 *= PRIME32_3; h32 ^= h32 >> 16; return h32; } } public static unsafe uint Calculate(byte[] buf, int len = -1, uint seed = 0) { if (len == -1) len = buf.Length; fixed (byte* buffer = buf) { return CalculateInline(buffer, len, seed); } } private static uint PRIME32_1 = 2654435761U; private static uint PRIME32_2 = 2246822519U; private static uint PRIME32_3 = 3266489917U; private static uint PRIME32_4 = 668265263U; private static uint PRIME32_5 = 374761393U; [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint RotateLeft32(uint value, int count) { return (value << count) | (value >> (32 - count)); } } /// <summary> /// A port of the original XXHash algorithm from Google in 64bits /// </summary> /// <<remarks>The 32bits and 64bits hashes for the same data are different. In short those are 2 entirely different algorithms</remarks> public static class XXHash64 { public static unsafe ulong Calculate(byte* buffer, int len, ulong seed = 0) { ulong h64; byte* bEnd = buffer + len; if (len >= 32) { byte* limit = bEnd - 32; ulong v1 = seed + PRIME64_1 + PRIME64_2; ulong v2 = seed + PRIME64_2; ulong v3 = seed + 0; ulong v4 = seed - PRIME64_1; do { v1 += *((ulong*)buffer) * PRIME64_2; buffer += sizeof(ulong); v2 += *((ulong*)buffer) * PRIME64_2; buffer += sizeof(ulong); v3 += *((ulong*)buffer) * PRIME64_2; buffer += sizeof(ulong); v4 += *((ulong*)buffer) * PRIME64_2; buffer += sizeof(ulong); v1 = RotateLeft64(v1, 31); v2 = RotateLeft64(v2, 31); v3 = RotateLeft64(v3, 31); v4 = RotateLeft64(v4, 31); v1 *= PRIME64_1; v2 *= PRIME64_1; v3 *= PRIME64_1; v4 *= PRIME64_1; } while (buffer <= limit); h64 = RotateLeft64(v1, 1) + RotateLeft64(v2, 7) + RotateLeft64(v3, 12) + RotateLeft64(v4, 18); v1 *= PRIME64_2; v1 = RotateLeft64(v1, 31); v1 *= PRIME64_1; h64 ^= v1; h64 = h64 * PRIME64_1 + PRIME64_4; v2 *= PRIME64_2; v2 = RotateLeft64(v2, 31); v2 *= PRIME64_1; h64 ^= v2; h64 = h64 * PRIME64_1 + PRIME64_4; v3 *= PRIME64_2; v3 = RotateLeft64(v3, 31); v3 *= PRIME64_1; h64 ^= v3; h64 = h64 * PRIME64_1 + PRIME64_4; v4 *= PRIME64_2; v4 = RotateLeft64(v4, 31); v4 *= PRIME64_1; h64 ^= v4; h64 = h64 * PRIME64_1 + PRIME64_4; } else { h64 = seed + PRIME64_5; } h64 += (ulong)len; while (buffer + 8 <= bEnd) { ulong k1 = *((ulong*)buffer); k1 *= PRIME64_2; k1 = RotateLeft64(k1, 31); k1 *= PRIME64_1; h64 ^= k1; h64 = RotateLeft64(h64, 27) * PRIME64_1 + PRIME64_4; buffer += 8; } if (buffer + 4 <= bEnd) { h64 ^= *(uint*)buffer * PRIME64_1; h64 = RotateLeft64(h64, 23) * PRIME64_2 + PRIME64_3; buffer += 4; } while (buffer < bEnd) { h64 ^= ((ulong)*buffer) * PRIME64_5; h64 = RotateLeft64(h64, 11) * PRIME64_1; buffer++; } h64 ^= h64 >> 33; h64 *= PRIME64_2; h64 ^= h64 >> 29; h64 *= PRIME64_3; h64 ^= h64 >> 32; return h64; } public static unsafe ulong Calculate(byte[] buf, int len = -1, ulong seed = 0) { if (len == -1) len = buf.Length; fixed (byte* buffer = buf) { return Calculate(buffer, len, seed); } } private static ulong PRIME64_1 = 11400714785074694791UL; private static ulong PRIME64_2 = 14029467366897019727UL; private static ulong PRIME64_3 = 1609587929392839161UL; private static ulong PRIME64_4 = 9650029242287828579UL; private static ulong PRIME64_5 = 2870177450012600261UL; [MethodImpl(MethodImplOptions.AggressiveInlining)] private static ulong RotateLeft64(ulong value, int count) { return (value << count) | (value >> (64 - count)); } } } }
35.426295
144
0.394962
[ "MIT" ]
alexandre-lecoq/Farmhash.Sharp
Farmhash.Sharp.Benchmarks/SparrowHashing.cs
8,894
C#
/** * The MIT License (MIT) * * Copyright (c) 2012-2017 DragonBones team and other contributors * * 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 UnityEngine; using System.Collections.Generic; using UnityEditor; using System.IO; namespace DragonBones { public class AssetProcess : AssetPostprocessor { [System.Serializable] struct SubTextureClass { public string name; public float x, y, width, height, frameX, frameY, frameWidth, frameHeight; } [System.Serializable] class TextureDataClass { public string name=null; public string imagePath=null; public int width=0,height=0; public List<SubTextureClass> SubTexture=null; } //public static void OnPostprocessAllAssets(string[]imported,string[] deletedAssets,string[] movedAssets,string[]movedFromAssetPaths) //{ // if (imported.Length == 0) // { // return; // } // var atlasPaths = new List<string>(); // var imagePaths = new List<string>(); // var skeletonPaths = new List<string>(); // foreach (string str in imported) // { // string extension = Path.GetExtension(str).ToLower(); // switch (extension) // { // case ".png": // imagePaths.Add(str); // break; // case ".json": // if (str.EndsWith("_tex.json", System.StringComparison.Ordinal)) // { // atlasPaths.Add(str); // } // else if (IsValidDragonBonesData((TextAsset)AssetDatabase.LoadAssetAtPath(str, typeof(TextAsset)))) // { // skeletonPaths.Add(str); // } // else // { // atlasPaths.Add(str); // } // break; // case ".dbbin": // if (File.Exists(str)){ // string bytesPath = Path.GetDirectoryName(str) + "/" + Path.GetFileNameWithoutExtension(str) + ".bytes"; // File.Move(str,bytesPath); // AssetDatabase.Refresh(); // skeletonPaths.Add(bytesPath); // } // break; // case ".bytes": // if (IsValidDragonBonesData((TextAsset)AssetDatabase.LoadAssetAtPath(str, typeof(TextAsset)))){ // skeletonPaths.Add(str); // } // break; // } // } // if (skeletonPaths.Count == 0) // { // return; // } // foreach(string skeletonPath in skeletonPaths) // { // List<string> imgPaths = new List<string>(); // List<string> atlPaths = new List<string>(); // foreach(string atlasPath in atlasPaths) // { // if(atlasPath.IndexOf(skeletonPath.Substring(0,skeletonPath.LastIndexOf("/")))==0) // { // atlPaths.Add(atlasPath); // imgPaths.Add(atlasPath.Substring(0,atlasPath.LastIndexOf(".json"))+".png"); // } // } // ProcessTextureAtlasData(atlPaths); // } //} public static bool IsValidDragonBonesData (TextAsset asset) { if (asset.name.Contains("_ske")) { return true; } if(asset.text == "DBDT") { return true; } if (asset.text.IndexOf("\"armature\":") > 0) { return true; } return false; } static void ProcessTextureAtlasData(List<string> atlasPaths) { foreach(string path in atlasPaths) { TextAsset ta = AssetDatabase.LoadAssetAtPath<TextAsset>(path); if(ta) { TextureDataClass tdc = JsonUtility.FromJson<TextureDataClass>(ta.text); if(tdc != null && (tdc.width == 0 || tdc.height == 0)) { //add width and height string imgPath = path.Substring(0,path.IndexOf(".json"))+".png"; Texture2D texture = LoadPNG(Application.dataPath+"/"+ imgPath.Substring(6)); if(texture) { tdc.width = texture.width; tdc.height = texture.height; //save string json = JsonUtility.ToJson(tdc); File.WriteAllText(path,json); EditorUtility.SetDirty(ta); GameObject.DestroyImmediate(texture); } } } } AssetDatabase.Refresh(); AssetDatabase.SaveAssets(); } static Texture2D LoadPNG(string filePath) { Texture2D tex = null; byte[] fileData; if (File.Exists(filePath)) { fileData = File.ReadAllBytes(filePath); tex = new Texture2D(2, 2); tex.LoadImage(fileData); } return tex; } } }
36.461957
143
0.493069
[ "Apache-2.0" ]
zfiona/client
Assets/3rdParty/DragonBonesCSharp-master/Unity/src/DragonBones/Editor/AssetProcess.cs
6,711
C#
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; using static Microsoft.CodeAnalysis.CSharp.SyntaxKind; namespace Sakura.AspNetCore.SignalR.HubProxyGenerators { /// <summary> /// Provide helper method for syntax generation. This class is static. /// </summary> public static class SyntaxHelper { /// <summary> /// Get all data of a specified attribute type from a symbol definition. /// </summary> /// <typeparam name="T">The type of the attribute.</typeparam> /// <param name="symbol">The symbol object.</param> /// <returns>All the <see cref="AttributeData"/> instance with type <typeparamref name="T"/> defined on the <paramref name="symbol"/>. If no matching attribute is found, this method will returns a empty collection.</returns> public static IEnumerable<AttributeData> GetAttributes<T>(this ISymbol symbol) where T : Attribute => symbol.GetAttributes().Where(i => i.AttributeClass != null && SymbolDisplay.ToDisplayString(i.AttributeClass) == typeof(T).FullName); /// <summary> /// Get all data of a specified attribute type from a symbol definition. /// </summary> /// <typeparam name="T">The type of the attribute.</typeparam> /// <param name="symbol">The symbol object.</param> /// <returns>The <see cref="AttributeData"/> instance with type <typeparamref name="T"/> defined on the <paramref name="symbol"/>. If no matching attribute is found, this method will returns <c>null</c>; If more than one instance is defined, <see cref="InvalidOperationException"/> will be raised.</returns> /// <exception cref="InvalidOperationException">There is more than one attribute with the same type defined on the <paramref name="symbol"/>.</exception> public static AttributeData? GetAttribute<T>(this ISymbol symbol) where T : Attribute => symbol.GetAttributes<T>().SingleOrDefault(); public static T GetValue<T>(this AttributeData attributeData, string key) { var item = attributeData.NamedArguments.SingleOrDefault(i => i.Key == key); // Not found if (item.Key == null) { return default!; } return (T)item.Value.Value!; } public static StatementSyntax AsStatement(this ExpressionSyntax expression) => ExpressionStatement(expression); public static BlockSyntax AsBlock(this StatementSyntax statement) => Block(statement); public static BlockSyntax AsBlock(this IEnumerable<StatementSyntax> statements) => Block(statements); public static ParameterListSyntax ParameterList(params ParameterSyntax[] parameters) => SyntaxFactory.ParameterList(SeparatedList(parameters)); public static SeparatedSyntaxList<TNode> AsSeparatedList<TNode>(this TNode item) where TNode : SyntaxNode => SyntaxFactory.SeparatedList(new[] { item }); public static ParameterSyntax Parameter(string identifier, TypeSyntax? type = default) => SyntaxFactory.Parameter(Identifier(identifier)).WithType(type); public static ArgumentSyntax AsArgument(this ExpressionSyntax expression) => Argument(expression); public static ElementAccessExpressionSyntax Element(this ExpressionSyntax expression, params ExpressionSyntax[] indexes) => ElementAccessExpression(expression, BracketedArgumentList(SyntaxFactory.SeparatedList(indexes.Select(AsArgument)))); /// <summary> /// Access a chained member of an expression. /// </summary> /// <param name="parent">The parent expression instance.</param> /// <param name="memberName">The name of the member to be accessed for the <paramref name="parent"/>.</param> /// <param name="memberPaths">The names of all following-up members to be accessed.</param> /// <returns>The generated <see cref="MemberAccessExpressionSyntax"/> instance.</returns> public static MemberAccessExpressionSyntax MemberAccess(this ExpressionSyntax parent, string memberName, params string[] memberPaths) { // First member var result = MemberAccessExpression(SimpleMemberAccessExpression, parent, IdentifierName(memberName)); // rest members return memberPaths.Aggregate(result, (current, name) => MemberAccessExpression(SimpleMemberAccessExpression, current, IdentifierName(name))); } public static LiteralExpressionSyntax StringLiteral(string value) => LiteralExpression(StringLiteralExpression, Literal(value)); public static LiteralExpressionSyntax Int32Literal(int value) => LiteralExpression(NumericLiteralExpression, Literal(value)); /// <summary> /// Conditional access a chained member of an expression. /// </summary> /// <param name="parent">The parent expression instance.</param> /// <param name="memberName">The name of the member to be accessed for the <paramref name="parent"/>.</param> /// <param name="memberPaths">The names of all following-up members to be accessed.</param> /// <returns>The generated <see cref="ConditionalAccessExpressionSyntax"/> instance.</returns> public static ConditionalAccessExpressionSyntax ConditionalMemberAccess(this ExpressionSyntax parent, string memberName, params string[] memberPaths) { var result = ConditionalAccessExpression(parent, IdentifierName(memberName)); return memberPaths.Aggregate(result, (current, name) => ConditionalAccessExpression(current, IdentifierName(name))); } public static TypeOfExpressionSyntax TypeOf(this TypeSyntax type) => TypeOfExpression(type); public static CastExpressionSyntax Cast(this ExpressionSyntax expression, TypeSyntax type) => CastExpression(type, expression); public static AwaitExpressionSyntax Await(this ExpressionSyntax expression) => AwaitExpression(expression); public static IdentifierNameSyntax ValueKeyword => IdentifierName("value"); public static AttributeListSyntax ToList(this AttributeSyntax attribute, AttributeTargetSpecifierSyntax? target = default) => AttributeList(target, SeparatedList(attribute)); public static MemberDeclarationSyntax AddAttributes(this MemberDeclarationSyntax member, AttributeTargetSpecifierSyntax? target, params AttributeSyntax[] attributes) => member.AddAttributeLists(attributes.Select(i => i.ToList(target)).ToArray()); public static ArrayCreationExpressionSyntax ArrayWithInitializer(TypeSyntax elementType, params ExpressionSyntax[] initializingValues) { return ArrayCreationExpression(elementType.ToArrayType(Enumerable.Empty<ExpressionSyntax>()), // Type[] InitializerExpression(ArrayInitializerExpression, SeparatedList(initializingValues))); } public static InvocationExpressionSyntax Invoke(this ExpressionSyntax target, ArgumentListSyntax arguments) => InvocationExpression(target, arguments); public static InvocationExpressionSyntax Invoke(this ExpressionSyntax target, params ExpressionSyntax[] arguments) => InvocationExpression(target, ArgumentList(arguments)); public static ReturnStatementSyntax Return(this ExpressionSyntax expression) => ReturnStatement(expression); public static ArrayTypeSyntax ToArrayType(this TypeSyntax type) => ArrayType(type); public static ArrayTypeSyntax ToArrayType(this TypeSyntax type, params ArrayRankSpecifierSyntax[] arrayRanks) => ArrayType(type, SyntaxFactory.List(arrayRanks)); public static ArrayTypeSyntax ToArrayType(this TypeSyntax type, params IEnumerable<ExpressionSyntax>[] arrayRanks) => ArrayType(type, SyntaxFactory.List(arrayRanks.Select(i => ArrayRankSpecifier(SyntaxFactory.SeparatedList(i))))); public static SeparatedSyntaxList<T> SeparatedList<T>(params T[] args) where T : SyntaxNode => SyntaxFactory.SeparatedList(args); public static SyntaxList<T> List<T>(params T[] args) where T : SyntaxNode => SyntaxFactory.List(args); public static SyntaxTokenList TokenList(params SyntaxKind[] syntaxKinds) { var items = syntaxKinds.Select(Token); return SyntaxFactory.TokenList(items); } /// <summary> /// Generate the <see cref="ArgumentListSyntax"/> instance from a list of argument expressions. /// </summary> /// <param name="expressions">The array of <see cref="ExpressionSyntax"/> which represents to each argument.</param> /// <returns>The generated <see cref="ArgumentSyntax"/> instance.</returns> public static ArgumentListSyntax ArgumentList(params ExpressionSyntax[] expressions) { return SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(expressions.Select(Argument))); } public static BaseListSyntax BaseList(params BaseTypeSyntax[] items) { return SyntaxFactory.BaseList(SyntaxFactory.SeparatedList(items)); } public static AccessorListSyntax AccessorList(params AccessorDeclarationSyntax[] accessors) { return SyntaxFactory.AccessorList(List(accessors)); } /// <summary> /// Generate a Task type with the specified task result value type. /// </summary> /// <param name="model">The <see cref="SemanticModel"/> instance.</param> /// <param name="innerType">The task result type, can be <c>null</c> if the task has no result.</param> /// <returns>The generated <see cref="System.Threading.Tasks.Task"/> or <see cref="System.Threading.Tasks.Task{TResult}"/> type.</returns> public static TypeSyntax MakeTaskType(SemanticModel model, ITypeSymbol? innerType) { if (innerType == null) { return model.GetTypeSyntax<Task>(); } var baseType = model.GetEquivalentType(typeof(Task<>)); return baseType.MakeGenericType(model, innerType); } public static GenericNameSyntax MakeGenericType(this ITypeSymbol genericTypeDefinition, SemanticModel model, params ITypeSymbol[] typeArguments) => genericTypeDefinition.MakeGenericType(model, (IEnumerable<ITypeSymbol>)typeArguments); /// <summary> /// Generate a <see cref="GenericNameSyntax"/> used to present as a closed generic type. /// </summary> /// <param name="genericTypeDefinition">The type definition symbol of the generic type.</param> /// <param name="model">The <see cref="SemanticModel"/> instance.</param> /// <param name="typeArguments">Type symbols for all type arguments.</param> /// <returns>The generated <see cref="GenericNameSyntax"/> instance.</returns> public static GenericNameSyntax MakeGenericType(this ITypeSymbol genericTypeDefinition, SemanticModel model, IEnumerable<ITypeSymbol> typeArguments) { // Type arg list var typeArgs = TypeArgumentList(); typeArgs = typeArgs.AddArguments(typeArguments.Select(i => i.ToTypeSyntax(model)).ToArray()); // Omit generic args for open generic type definition var format = new SymbolDisplayFormat(genericsOptions: SymbolDisplayGenericsOptions.None); return GenericName(Identifier(genericTypeDefinition.ToMinimalDisplayString(model, 0, format))) .WithTypeArgumentList(typeArgs); } /// <summary> /// try to determine if a type represents as a task and get its result type. /// </summary> /// <param name="type">The <see cref="Type"/> to be determining.</param> /// <param name="resultType">If the <paramref name="type"/> is a task with result, returns the result type; otherwise, returns <c>null</c>.</param> /// <returns>If the <paramref name="type"/> is a task (with or without an result), returns <c>true</c>; otherwise, returns <c>false</c>.</returns> public static bool TryGetTaskResultType(Type type, out Type? resultType) { var taskFullName = typeof(Task).FullName; var taskWithResultFullName = typeof(Task<>).FullName; resultType = null; if (type.FullName == taskFullName) { return true; } if (type.IsGenericType) { var defType = type.GetGenericTypeDefinition(); if (defType.FullName == taskWithResultFullName) { resultType = type.GenericTypeArguments[0]; return true; } } return false; } } }
44.125461
309
0.753805
[ "Apache-2.0" ]
sgjsakura/SignalRHubProxyGenerator
Sakura.AspNetCore.SignalR.HubProxyGenerators/Sakura.AspNetCore.SignalR.HubProxyGenerators/SyntaxHelper.cs
11,960
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Contenedor_WebApi.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
47.222973
229
0.586588
[ "MIT" ]
livingston12/contenedor-app-API
Contenedor_WebApi/Areas/HelpPage/SampleGeneration/HelpPageSampleGenerator.cs
20,967
C#
/* * Copyright 2010-2014 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 directconnect-2012-10-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.DirectConnect.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.DirectConnect.Model.Internal.MarshallTransformations { /// <summary> /// DescribeVirtualInterfaces Request Marshaller /// </summary> public class DescribeVirtualInterfacesRequestMarshaller : IMarshaller<IRequest, DescribeVirtualInterfacesRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((DescribeVirtualInterfacesRequest)input); } public IRequest Marshall(DescribeVirtualInterfacesRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.DirectConnect"); string target = "OvertureService.DescribeVirtualInterfaces"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.HttpMethod = "POST"; string uriResourcePath = "/"; request.ResourcePath = uriResourcePath; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetConnectionId()) { context.Writer.WritePropertyName("connectionId"); context.Writer.Write(publicRequest.ConnectionId); } if(publicRequest.IsSetVirtualInterfaceId()) { context.Writer.WritePropertyName("virtualInterfaceId"); context.Writer.Write(publicRequest.VirtualInterfaceId); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } } }
36.809524
165
0.664942
[ "Apache-2.0" ]
ermshiperete/aws-sdk-net
AWSSDK_DotNet35/Amazon.DirectConnect/Model/Internal/MarshallTransformations/DescribeVirtualInterfacesRequestMarshaller.cs
3,092
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("Meticulous.SandBox")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Meticulous.SandBox")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("04209073-1f27-4e9e-b5d6-e043296c3a82")] // 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.081081
84
0.745919
[ "MIT" ]
tarik-s/Basis
SandBoxes/Basis.SandBox/Properties/AssemblyInfo.cs
1,412
C#
namespace system.runtime.compilerservices { public static class VoidHelper { // this helper class assists in casting a Span<T> to an IntPtr. // this is accomplished by caching a reference to the target object // and returning the table key id as an IntPtr, which may then be // casted back to a Span<T>. // // important: a weak reference is cached, to make it possible to // discard 'pointers' for objects that were garbage collected. // do not pass a Span/pointer to memory that is not referenced // by anything except via the passed Span object! class TrackedSpan : IdentifierWeakTable.TrackedObject { [java.attr.RetainType] public Span<object> span; public TrackedSpan(int id, object obj, java.lang.@ref.ReferenceQueue refq) : base(id, obj, refq) {} } public static long SpanToIntPtr(System.ValueType span) { // CodeSpan::ExplicitCast inserts a call to this method // when processing a call to // System.IntPtr System.IntPtr::op_Explicit(System.Void*) // // note that a void* pointer should always handled as a Span<T> // in CodeSpan, so we make sure the input is really a span. if (span == null) return 0; if ((object) span is system.Span<object> span_) { object array; var copy = span_.CloneIntoCache(out array); if (array != null) { var trackedObject = IdentifierWeakTable.Global.GetTrackedObject(array); int id = (trackedObject != null) ? trackedObject.id : IdentifierWeakTable.Global.Generate(array, (id, obj, @ref) => new TrackedSpan(id, obj, @ref) { span = copy }); // left-shift the 'address' by 32-bits, so we can detect // if an offset was added to the returned 'pointer' return ((long) id) << 32; } } // this helper class only manages Span<T> throw new System.PlatformNotSupportedException("SpanToIntPtr"); } public static System.ValueType IntPtrToSpan(long intptr) { // as above, when casting the IntPtr back to a Void* pointer, // returns the Span that was cached for the particular IntPtr // value. if casting a non-zero IntPtr value that has not // been cached earlier, then report an exception. if (intptr == 0) return null; int id = (int) (intptr >> 32); if (intptr != ((long) id) << 32) throw new System.PlatformNotSupportedException("IntPtrToSpan non-zero offset"); var trackedObject = IdentifierWeakTable.Global.GetTrackedObject(id); if (trackedObject is TrackedSpan trackedSpan) { var array = trackedSpan.get(); if (array != null) { return trackedSpan.span.CloneFromCache(array); } } throw new System.PlatformNotSupportedException("IntPtrToSpan not in table"); } } }
38.573034
95
0.542674
[ "MIT" ]
spaceflint7/bluebonnet
Baselib/src/System/Runtime/VoidHelper.cs
3,433
C#
namespace SurveySystem.Data.Common.Models { using System; public interface IDeletableEntity { bool IsDeleted { get; set; } DateTime? DeletedOn { get; set; } } }
16.333333
42
0.617347
[ "MIT" ]
viktorrr/SurveySystem
Data/SurveySystem.Data.Common/Models/IDeletableEntity.cs
198
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; /* Script que contiene las funciones para cambiar entre preguntas. Autor: Luis Ignacio Ferro Salinas A01387248 Última actualización: 27 de abril de 2021. */ public class BotonContinuarIndustrial : MonoBehaviour { // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } }
16.241379
63
0.685775
[ "Apache-2.0" ]
JoanDGG/Proyecto-Marte
Assets/Scripts/scriptsIndustrial/ScriptsPreguntas/BotonContinuarIndustrial.cs
473
C#
using System; using System.Collections; using System.IO; using System.Security.Cryptography; using System.Text; namespace TestFu.Operations { public class UniformPairWizeProductDomainTupleEnumerable : ITupleEnumerable { private IDomainCollection domains; public UniformPairWizeProductDomainTupleEnumerable(IDomainCollection domains) { if (domains == null) throw new ArgumentNullException("domains"); this.domains = domains; int count = -1; for (int i = 0; i < domains.Count; ++i) { if (i == 0) count = domains[i].Count; else { if (count != domains[i].Count) throw new ArgumentException("Domains have not uniform size"); } } } public IDomainCollection Domains { get { return this.domains; } } public ITupleEnumerator GetEnumerator() { return new UniformPairWizeProductDomainTupleEnumerator(this.Domains); } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } internal sealed class UniformPairWizeProductDomainTupleEnumerator : DomainTupleEnumeratorBase { private int m = -1; private int domainCount=-1; private ArrayList bipartiteGraphs = null; private int bipartiteGraphIndex = -1; private int leftIndex = 0; private int rightIndex = -1; private Tuple tuple = null; public UniformPairWizeProductDomainTupleEnumerator(IDomainCollection domains) :base(domains) { this.domainCount = this.Domains[0].Count; this.Reset(); } public override void Reset() { // get number of bipartite graphs m = (int)Math.Ceiling(Math.Log(this.Domains.Count, 2)); // create bipartite graphs this.bipartiteGraphs = new ArrayList(m); for (int i = 0; i < m; ++i) { // create bipartie graph BipartiteGraph bg = new BipartiteGraph(this.Domains.Count); this.bipartiteGraphs.Add(bg); // do some swapping if (i>0) bg.Swap(i-1, bg.Left.Count+i-1); } this.bipartiteGraphIndex = -1; this.leftIndex = 0; this.rightIndex = 0; this.tuple = null; } public override bool MoveNext() { do { if (this.leftIndex == this.rightIndex && this.bipartiteGraphIndex < this.bipartiteGraphs.Count) { this.bipartiteGraphIndex++; this.CreateTuple(); this.bipartiteGraphIndex = this.bipartiteGraphs.Count; return true; } else { this.bipartiteGraphIndex++; if (this.bipartiteGraphIndex < this.bipartiteGraphs.Count) { this.CreateTuple(); return true; } } // increasing index this.rightIndex++; if (this.rightIndex >= this.domainCount) { this.leftIndex++; this.rightIndex = 0; } this.bipartiteGraphIndex = -1; } while (this.leftIndex < this.domainCount && this.rightIndex < this.domainCount); return false; } private void CreateTuple() { // get bipartite graph BipartiteGraph bg = (BipartiteGraph)this.bipartiteGraphs[this.bipartiteGraphIndex]; this.tuple = new Tuple(); for (int i = 0; i < this.Domains.Count; ++i) { if (bg.Left.Contains(i)) this.tuple.Add(this.Domains[i][leftIndex]); else this.tuple.Add(this.Domains[i][rightIndex]); } } public override ITuple Current { get { return this.tuple; } } private class BipartiteGraph { private SortedList left = new SortedList(); private SortedList right = new SortedList(); public BipartiteGraph(int count) { int middle = count / 2 + count%2; int i = 0; for (i = 0; i < middle; ++i) { left.Add(i, i); } for (; i < count; ++i) right.Add(i, i); } public void Swap(int i, int j) { left.Remove(i); right.Remove(j); left.Add(j, j); right.Add(i, i); } public SortedList Left { get { return this.left; } } public SortedList Right { get { return this.right; } } public override string ToString() { StringWriter sw = new StringWriter(); sw.Write("["); foreach (object o in this.Left.Keys) sw.Write("{0} ",o); sw.Write("] ["); foreach (object o in this.Right.Keys) sw.Write("{0} ", o); sw.Write("]"); return sw.ToString(); } } } } }
32.710784
116
0.402368
[ "ECL-2.0", "Apache-2.0" ]
Gallio/mbunit-v2
src/mbunit/TestFu/Operations/UniformPairWizeProductDomainTupleEnumerable.cs
6,675
C#
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading.Tasks; namespace Project { class Program { public static event Func<int, Task> a; static void Main(string[] args) { a += Program_a; NatashaInitializer.InitializeAndPreheating(); var domainName = Test(); for (int i = 0; i < 6; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } Console.WriteLine(domainName); Console.WriteLine(DomainManagement.IsDeleted(domainName)); Console.ReadKey(); } public static async Task b() { await a(1); } private static async Task Program_a(int arg) { await Task.Delay(100); } [MethodImpl(MethodImplOptions.NoInlining)] public unsafe static string Test() { var dict2 = new Dictionary<int,string>(); var dict = new Dictionary<string, int>(); for (int i = 0; i < 10; i++) { dict[i.ToString()] = i; dict2[i] = i.ToString(); } var test = dict2.CustomerTree(item => item.ToString()); var temp = dict.HashTree(); var name = temp.GetType().Name; var result = temp["1"]; //var a = temp.GetKeys(1); //var domainName = temp.ProxyType.GetDomain().Name; Console.WriteLine(DomainManagement.IsDeleted(name)); // temp.Dispose(); for (int i = 0; i < 6; i++) { GC.Collect(); } return name; } } }
27.59375
70
0.492072
[ "MIT" ]
night-moon-studio/DynamicDictionary
samples/Project/Program.cs
1,768
C#
/* Copyright (c) 2006 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using EasyKeys.Google.GData.Extensions; namespace EasyKeys.Google.GData.ContentForShopping.Elements { public class Permission : SimpleElement { /// <summary> /// default constructor for sc:permission /// </summary> public Permission() : base( ContentForShoppingNameTable.Permission, ContentForShoppingNameTable.scDataPrefix, ContentForShoppingNameTable.BaseNamespace) { } /// <summary> /// constructor that takes status for sc:permission /// </summary> /// <param name="scope">The permission's scope.</param> /// <param name="value">The permission's value.</param> public Permission(string scope, string value) : base( ContentForShoppingNameTable.Permission, ContentForShoppingNameTable.scDataPrefix, ContentForShoppingNameTable.BaseNamespace) { Scope = scope; Value = value; } /// <summary> /// Scope property accessor /// </summary> public string Scope { get { return Convert.ToString(Attributes[ContentForShoppingNameTable.Scope]); } set { Attributes[ContentForShoppingNameTable.Scope] = value; } } } }
31.323077
87
0.605108
[ "MIT" ]
easykeys/EasyKeys.Google.GData
src/EasyKeys.Google.GData.ContentForShopping/elements/permission.cs
2,038
C#
using System; using Aop.Api.Domain; using System.Collections.Generic; using Aop.Api.Response; namespace Aop.Api.Request { /// <summary> /// AOP API: ant.merchant.expand.assetinfo.delivery.sync /// </summary> public class AntMerchantExpandAssetinfoDeliverySyncRequest : IAopRequest<AntMerchantExpandAssetinfoDeliverySyncResponse> { /// <summary> /// 配送物料信息反馈接口 /// </summary> public string BizContent { 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 string returnUrl; 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 SetReturnUrl(string returnUrl){ this.returnUrl = returnUrl; } public string GetReturnUrl(){ return this.returnUrl; } 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 "ant.merchant.expand.assetinfo.delivery.sync"; } 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("biz_content", this.BizContent); return parameters; } public AopObject GetBizModel() { return this.bizModel; } public void SetBizModel(AopObject bizModel) { this.bizModel = bizModel; } #endregion } }
23.918182
124
0.610414
[ "Apache-2.0" ]
Varorbc/alipay-sdk-net-all
AlipaySDKNet/Request/AntMerchantExpandAssetinfoDeliverySyncRequest.cs
2,651
C#
using System; namespace LedDashboardCore { public interface LightController : IDisposable { public bool Enabled { get; set; } //public void SendData(int ledCount, byte[] data, LightingMode mode); public void SendData(LEDFrame data); } }
21.230769
77
0.663043
[ "Apache-2.0" ]
Akumass/leagueoflegends-led
LedDashboardCore/LightController.cs
278
C#
using CustomUI.BeatSaber; using CustomUI.Utilities; using IPA.Loader; using IPA.Loader.Features; using IPA.Old; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UnityEngine; namespace BSIPA_ModList.UI.ViewControllers { internal interface IClickableCell { void OnSelect(ModListController cntrl); void Update(); } internal class BSIPAModCell : CustomCellInfo, IClickableCell, IDisposable { internal PluginLoader.PluginMetadata Plugin; private ModListController list; private PluginManager.PluginEnableDelegate enableDel; private PluginManager.PluginDisableDelegate disableDel; public BSIPAModCell(ModListController list, PluginLoader.PluginMetadata plugin) : base("", "", null) { Plugin = plugin; this.list = list; var thisWeakRef = new WeakReference<BSIPAModCell>(this); PluginManager.PluginDisableDelegate reflessDDel = null; reflessDDel = disableDel = (p, r) => PluginManager_PluginDisabled(p, r, thisWeakRef, reflessDDel); // some indirection to make it a weak link for GC PluginManager.PluginDisabled += reflessDDel; PluginManager.PluginEnableDelegate reflessEDel = null; reflessEDel = enableDel = (p, r) => PluginManager_PluginEnabled(p, r, thisWeakRef, reflessEDel); // some indirection to make it a weak link for GC PluginManager.PluginEnabled += reflessEDel; Update(propogate: false); } private static void PluginManager_PluginEnabled(PluginLoader.PluginInfo plugin, bool needsRestart, WeakReference<BSIPAModCell> _self, PluginManager.PluginEnableDelegate ownDel) { if (!_self.TryGetTarget(out var self)) { PluginManager.PluginEnabled -= ownDel; return; } if (plugin.Metadata != self.Plugin) return; self.Update(true, needsRestart); } private static void PluginManager_PluginDisabled(PluginLoader.PluginMetadata plugin, bool needsRestart, WeakReference<BSIPAModCell> _self, PluginManager.PluginDisableDelegate ownDel) { if (!_self.TryGetTarget(out var self)) { PluginManager.PluginDisabled -= ownDel; return; } if (plugin != self.Plugin) return; self.Update(false, needsRestart); } private ModInfoViewController infoView; public void OnSelect(ModListController cntrl) { Logger.log.Debug($"Selected BSIPAModCell {Plugin.Name} {Plugin.Version}"); if (infoView == null) { var desc = Plugin.Manifest.Description; if (string.IsNullOrWhiteSpace(desc)) desc = "*No description*"; infoView = BeatSaberUI.CreateViewController<ModInfoViewController>(); infoView.Init(icon, Plugin.Name, "v" + Plugin.Version.ToString(), subtext, desc, Plugin, Plugin.Manifest.Links, true, list.flow); } list.flow.SetSelected(infoView, immediate: list.flow.HasSelected); } void IClickableCell.Update() => Update(null, false, false); public void Update(bool? _enabled = null, bool needsRestart = false, bool propogate = true) { text = $"{Plugin.Name} <size=60%>v{Plugin.Version}"; subtext = Plugin.Manifest.Author; if (string.IsNullOrWhiteSpace(subtext)) subtext = "<color=#BFBFBF><i>Unspecified Author</i>"; var enabled = _enabled ?? !PluginManager.IsDisabled(Plugin); if (!enabled) subtext += " <color=#C2C2C2>- <i>Disabled</i>"; if (needsRestart) subtext += " <i>(Restart to apply)</i>"; icon = Plugin.GetIcon(); var desc = Plugin.Manifest.Description; if (string.IsNullOrWhiteSpace(desc)) desc = "*No description*"; infoView?.Reload(Plugin.Name, "v" + Plugin.Version.ToString(), subtext, desc); if (propogate) list.Reload(); } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { PluginManager.PluginDisabled -= disableDel; PluginManager.PluginEnabled -= enableDel; } disposedValue = true; } } public void Dispose() { Dispose(true); } #endregion } internal class BSIPAIgnoredModCell : CustomCellInfo, IClickableCell { internal PluginLoader.PluginMetadata Plugin; private ModListController list; private const string authorFormat = "{0} <color=#BFBFBF>- <i>Not loaded</i>"; private string authorText; public BSIPAIgnoredModCell(ModListController list, PluginLoader.PluginMetadata plugin) : base($"<color=#878787>{plugin.Name} <size=60%>v{plugin.Version}", "", Utilities.DefaultBSIPAIcon) { Plugin = plugin; this.list = list; if (string.IsNullOrWhiteSpace(plugin.Manifest.Author)) authorText = "<color=#BFBFBF><i>Unspecified Author</i>"; else authorText = plugin.Manifest.Author; subtext = string.Format(authorFormat, authorText); } private ModInfoViewController infoView; public void OnSelect(ModListController cntrl) { Logger.log.Debug($"Selected BSIPAIgnoredModCell {Plugin.Name} {Plugin.Version}"); if (infoView == null) { var desc = Plugin.Manifest.Description; if (string.IsNullOrWhiteSpace(desc)) desc = "*No description*"; infoView = BeatSaberUI.CreateViewController<ModInfoViewController>(); infoView.Init(icon, Plugin.Name, "v" + Plugin.Version.ToString(), authorText, desc, Plugin, Plugin.Manifest.Links); } list.flow.SetSelected(infoView, immediate: list.flow.HasSelected); } public void Update() { } } internal class LibraryModCell : CustomCellInfo, IClickableCell { internal PluginLoader.PluginMetadata Plugin; private ModListController list; public LibraryModCell(ModListController list, PluginLoader.PluginMetadata plugin) : base($"{plugin.Name} <size=60%>v{plugin.Version}", plugin.Manifest.Author, null) { Plugin = plugin; this.list = list; if (string.IsNullOrWhiteSpace(subtext)) subtext = "<color=#BFBFBF><i>Unspecified Author</i></color>"; icon = Utilities.DefaultLibraryIcon; } private ModInfoViewController infoView; public void OnSelect(ModListController cntrl) { Logger.log.Debug($"Selected LibraryModCell {Plugin.Name} {Plugin.Version}"); if (infoView == null) { var desc = Plugin.Manifest.Description; if (string.IsNullOrWhiteSpace(desc)) desc = "*No description*"; infoView = BeatSaberUI.CreateViewController<ModInfoViewController>(); infoView.Init(icon, Plugin.Name, "v" + Plugin.Version.ToString(), subtext, desc, Plugin, Plugin.Manifest.Links); } list.flow.SetSelected(infoView, immediate: list.flow.HasSelected); } public void Update() { } } #pragma warning disable CS0618 internal class IPAModCell : CustomCellInfo, IClickableCell { internal IPlugin Plugin; private ModListController list; public IPAModCell(ModListController list, IPlugin plugin) : base($"{plugin.Name} <size=60%>{plugin.Version}", "<color=#BFBFBF><i>Legacy</i>", Utilities.DefaultIPAIcon) { Plugin = plugin; this.list = list; } private ModInfoViewController infoView; public void OnSelect(ModListController cntrl) { Logger.log.Debug($"Selected IPAModCell {Plugin.Name} {Plugin.Version}"); if (infoView == null) { PluginLoader.PluginMetadata updateInfo = null; try { updateInfo = new PluginLoader.PluginMetadata { Name = Plugin.Name, Id = Plugin.Name, Version = new SemVer.Version(Plugin.Version) }; } catch (Exception e) { Logger.log.Warn($"Could not generate fake update info for {Plugin.Name}"); Logger.log.Warn(e); } infoView = BeatSaberUI.CreateViewController<ModInfoViewController>(); infoView.Init(icon, Plugin.Name, "v" + Plugin.Version.ToString(), "<color=#BFBFBF><i>Unknown Author</i>", "This mod was written for IPA.\n===\n\n## No metadata is avaliable for this mod.\n\n" + "Please contact the mod author and ask them to port it to BSIPA to provide more information.", updateInfo); } list.flow.SetSelected(infoView, immediate: list.flow.HasSelected); } public void Update() { } } #pragma warning restore }
34.795775
190
0.581967
[ "MIT" ]
VSeryi/BeatSaber-IPA-Reloaded
BSIPA-ModList/UI/ViewControllers/ModCells.cs
9,884
C#
using System; using System.Xml.Serialization; using System.Collections.Generic; using Top.Api; namespace DingTalk.Api.Response { /// <summary> /// OapiEduMainDataGetResponse. /// </summary> public class OapiEduMainDataGetResponse : DingTalkResponse { /// <summary> /// 错误码 /// </summary> [XmlElement("errcode")] public long Errcode { get; set; } /// <summary> /// 错误信息 /// </summary> [XmlElement("errmsg")] public string Errmsg { get; set; } /// <summary> /// 结果 /// </summary> [XmlElement("result")] public OpenEduBureauStatisticalDataResponseDomain Result { get; set; } /// <summary> /// 成功or失败 /// </summary> [XmlElement("success")] public bool Success { get; set; } /// <summary> /// OpenEduBureauStatisticalDataResponseDomain Data Structure. /// </summary> [Serializable] public class OpenEduBureauStatisticalDataResponseDomain : TopObject { /// <summary> /// 最近1天活跃班级圈数 /// </summary> [XmlElement("act_class_circle_cnt_1d")] public string ActClassCircleCnt1d { get; set; } /// <summary> /// 最近7天活跃班级圈数 /// </summary> [XmlElement("act_class_circle_cnt_7d")] public string ActClassCircleCnt7d { get; set; } /// <summary> /// 最近1天活跃班级群数 /// </summary> [XmlElement("act_class_group_cnt_1d")] public string ActClassGroupCnt1d { get; set; } /// <summary> /// 最近7天活跃班级群数 /// </summary> [XmlElement("act_class_group_cnt_7d")] public string ActClassGroupCnt7d { get; set; } /// <summary> /// 最近1天活跃家长数量 /// </summary> [XmlElement("act_patriarch_cnt_1d")] public string ActPatriarchCnt1d { get; set; } /// <summary> /// 最近7天活跃家长数量 /// </summary> [XmlElement("act_patriarch_cnt_7d")] public string ActPatriarchCnt7d { get; set; } /// <summary> /// 最近1天活跃教师数量 /// </summary> [XmlElement("act_teacher_cnt_1d")] public string ActTeacherCnt1d { get; set; } /// <summary> /// 最近7天活跃教师数量 /// </summary> [XmlElement("act_teacher_cnt_7d")] public string ActTeacherCnt7d { get; set; } /// <summary> /// 数字化教师数量 /// </summary> [XmlElement("auth_teacher_cnt_std")] public string AuthTeacherCntStd { get; set; } /// <summary> /// 最近1天班级打卡使用人数 /// </summary> [XmlElement("class_card_user_cnt_1d")] public string ClassCardUserCnt1d { get; set; } /// <summary> /// 最近7天班级打卡使用人数 /// </summary> [XmlElement("class_card_user_cnt_7d")] public string ClassCardUserCnt7d { get; set; } /// <summary> /// 最近1天班级圈使用人数 /// </summary> [XmlElement("class_circle_user_cnt_1d")] public string ClassCircleUserCnt1d { get; set; } /// <summary> /// 最近7天班级圈使用人数 /// </summary> [XmlElement("class_circle_user_cnt_7d")] public string ClassCircleUserCnt7d { get; set; } /// <summary> /// 注册班级数 /// </summary> [XmlElement("class_cnt_std")] public string ClassCntStd { get; set; } /// <summary> /// 最近1天班级群使用人数 /// </summary> [XmlElement("class_group_user_cnt_1d")] public string ClassGroupUserCnt1d { get; set; } /// <summary> /// 最近7天班级群使用人数 /// </summary> [XmlElement("class_group_user_cnt_7d")] public string ClassGroupUserCnt7d { get; set; } /// <summary> /// 局id /// </summary> [XmlElement("corp_id")] public string CorpId { get; set; } /// <summary> /// 注册家长数 /// </summary> [XmlElement("patriarch_cnt_std")] public string PatriarchCntStd { get; set; } /// <summary> /// 最近1天接收DING的家长数 /// </summary> [XmlElement("rcv_ding_patriarch_cnt_1d")] public string RcvDingPatriarchCnt1d { get; set; } /// <summary> /// 最近7天接收DING的家长数 /// </summary> [XmlElement("rcv_ding_patriarch_cnt_7d")] public string RcvDingPatriarchCnt7d { get; set; } /// <summary> /// 注册学校数 /// </summary> [XmlElement("school_cnt_std")] public string SchoolCntStd { get; set; } /// <summary> /// 最近1天班级圈发送数 /// </summary> [XmlElement("send_circle_post_cnt_1d")] public string SendCirclePostCnt1d { get; set; } /// <summary> /// 最近7天班级圈发送数 /// </summary> [XmlElement("send_circle_post_cnt_7d")] public string SendCirclePostCnt7d { get; set; } /// <summary> /// 统计日期 /// </summary> [XmlElement("stat_date")] public string StatDate { get; set; } /// <summary> /// 注册学生数 /// </summary> [XmlElement("student_cnt_std")] public string StudentCntStd { get; set; } /// <summary> /// 注册教师数 /// </summary> [XmlElement("teacher_cnt_std")] public string TeacherCntStd { get; set; } /// <summary> /// 最近1天教师钉消息发送数 /// </summary> [XmlElement("teacher_send_ding_cnt_1d")] public string TeacherSendDingCnt1d { get; set; } /// <summary> /// 最近7天教师钉消息发送数 /// </summary> [XmlElement("teacher_send_ding_cnt_7d")] public string TeacherSendDingCnt7d { get; set; } } } }
27.362791
78
0.521673
[ "MIT" ]
lee890720/YiShaAdmin
YiSha.Util/YsSha.Dingtalk/DingTalk/Response/OapiEduMainDataGetResponse.cs
6,367
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Pacer : MonoBehaviour { public float speed = 2.5f; //speed of the ball private float zMax = 7.5f; private float zMin = -7.5f; //starting position private int direction = 1; // positive to start // Update is called once per frame void Update () { float zNew = transform.position.z + direction * speed * Time.deltaTime; if(zNew >= zMax) { zNew = zMax; direction *= -1; } else if (zNew <= zMin) { zNew = zMin; direction *= -1; } transform.position = new Vector3(7.5f, 0.75f, zNew); } }
23.129032
79
0.566248
[ "MIT" ]
nitrogendragon/roll-da-bally
Assets/Scripts/Pacer.cs
719
C#
using System.Collections.Generic; using Unity.UIWidgets.async; using Unity.UIWidgets.editor; using Unity.UIWidgets.external.simplejson; using Unity.UIWidgets.foundation; using Unity.UIWidgets.ui; using Unity.UIWidgets.widgets; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; using RawImage = UnityEngine.UI.RawImage; using Rect = UnityEngine.Rect; using Texture = UnityEngine.Texture; namespace Unity.UIWidgets.engine { public class UIWidgetWindowAdapter : WindowAdapter { readonly UIWidgetsPanel _uiWidgetsPanel; bool _needsPaint; protected override void updateSafeArea() { this._padding = this._uiWidgetsPanel.viewPadding; this._viewInsets = this._uiWidgetsPanel.viewInsets; } protected override bool hasFocus() { return EventSystem.current != null && EventSystem.current.currentSelectedGameObject == this._uiWidgetsPanel.gameObject; } public override void scheduleFrame(bool regenerateLayerTree = true) { base.scheduleFrame(regenerateLayerTree); this._needsPaint = true; } public UIWidgetWindowAdapter(UIWidgetsPanel uiWidgetsPanel) { this._uiWidgetsPanel = uiWidgetsPanel; } public override void OnGUI(Event evt) { if (this.displayMetricsChanged()) { this._needsPaint = true; } if (evt.type == EventType.Repaint) { if (!this._needsPaint) { return; } this._needsPaint = false; } base.OnGUI(evt); } protected override Surface createSurface() { return new WindowSurfaceImpl(this._uiWidgetsPanel.applyRenderTexture); } public override GUIContent titleContent { get { return new GUIContent(this._uiWidgetsPanel.gameObject.name); } } protected override float queryDevicePixelRatio() { return this._uiWidgetsPanel.devicePixelRatio; } protected override int queryAntiAliasing() { return this._uiWidgetsPanel.antiAliasing; } protected override Vector2 queryWindowSize() { var rect = this._uiWidgetsPanel.rectTransform.rect; // Here we use ReferenceEquals instead of "==" due to // https://blogs.unity3d.com/2014/05/16/custom-operator-should-we-keep-it/ // In short, "==" is overloaded for UnityEngine.Object and will bring performance issues if (!ReferenceEquals(this._uiWidgetsPanel.canvas, null)) { var size = new Vector2(rect.width, rect.height) * this._uiWidgetsPanel.canvas.scaleFactor / this._uiWidgetsPanel.devicePixelRatio; size.x = Mathf.Round(size.x); size.y = Mathf.Round(size.y); return size; } return new Vector2(0, 0); } public Offset windowPosToScreenPos(Offset windowPos) { Camera camera = null; var canvas = this._uiWidgetsPanel.canvas; if (canvas.renderMode != RenderMode.ScreenSpaceCamera) { camera = canvas.GetComponent<GraphicRaycaster>().eventCamera; } var pos = new Vector2(windowPos.dx, windowPos.dy); pos = pos * this.queryDevicePixelRatio() / this._uiWidgetsPanel.canvas.scaleFactor; var rectTransform = this._uiWidgetsPanel.rectTransform; var rect = rectTransform.rect; pos.x += rect.min.x; pos.y = rect.max.y - pos.y; var worldPos = rectTransform.TransformPoint(new Vector2(pos.x, pos.y)); var screenPos = RectTransformUtility.WorldToScreenPoint(camera, worldPos); return new Offset(screenPos.x, Screen.height - screenPos.y); } } [RequireComponent(typeof(RectTransform))] public class UIWidgetsPanel : RawImage, IPointerDownHandler, IPointerUpHandler, IDragHandler, IPointerEnterHandler, IPointerExitHandler, WindowHost { static Event _repaintEvent; [Tooltip("set to zero if you want to use the default device pixel ratio of the target platforms; otherwise the " + "device pixel ratio will be forced to the given value on all devices.")] [SerializeField] protected float devicePixelRatioOverride; [Tooltip("set to true will enable the hardware anti-alias feature, which will improve the appearance of the UI greatly but " + "making it much slower. Enable it only when seriously required.")] [SerializeField] protected bool hardwareAntiAliasing = false; WindowAdapter _windowAdapter; Texture _texture; Vector2 _lastMouseMove; readonly HashSet<int> _enteredPointers = new HashSet<int>(); bool _viewMetricsCallbackRegistered; bool _mouseEntered { get { return !this._enteredPointers.isEmpty(); } } DisplayMetrics _displayMetrics; const int mouseButtonNum = 3; void _handleViewMetricsChanged(string method, List<JSONNode> args) { this._windowAdapter.onViewMetricsChanged(); this._displayMetrics.onViewMetricsChanged(); } protected virtual void InitWindowAdapter() { D.assert(this._windowAdapter == null); this._windowAdapter = new UIWidgetWindowAdapter(this); this._windowAdapter.OnEnable(); } protected override void OnEnable() { base.OnEnable(); //Disable the default touch -> mouse event conversion on mobile devices Input.simulateMouseWithTouches = false; this._displayMetrics = DisplayMetricsProvider.provider(); this._displayMetrics.OnEnable(); this._enteredPointers.Clear(); if (_repaintEvent == null) { _repaintEvent = new Event {type = EventType.Repaint}; } this.InitWindowAdapter(); Widget root; using (this._windowAdapter.getScope()) { root = this.createWidget(); } this._windowAdapter.attachRootWidget(root); this._lastMouseMove = Input.mousePosition; } public float devicePixelRatio { get { return this.devicePixelRatioOverride > 0 ? this.devicePixelRatioOverride : this._displayMetrics.devicePixelRatio; } } public int antiAliasing { get { return this.hardwareAntiAliasing ? Window.defaultAntiAliasing : 0; } } public WindowPadding viewPadding { get { return this._displayMetrics.viewPadding; } } public WindowPadding viewInsets { get { return this._displayMetrics.viewInsets; } } protected override void OnDisable() { D.assert(this._windowAdapter != null); this._windowAdapter.OnDisable(); this._windowAdapter = null; base.OnDisable(); } protected virtual Widget createWidget() { return null; } public void recreateWidget() { Widget root; using (this._windowAdapter.getScope()) { root = this.createWidget(); } this._windowAdapter.attachRootWidget(root); } internal void applyRenderTexture(Rect screenRect, Texture texture, Material mat) { this.texture = texture; this.material = mat; } protected virtual void Update() { this._displayMetrics.Update(); UIWidgetsMessageManager.ensureUIWidgetsMessageManagerIfNeeded(); #if UNITY_ANDROID if (Input.GetKeyDown(KeyCode.Escape)) { this._windowAdapter.withBinding(() => { WidgetsBinding.instance.handlePopRoute(); }); } #endif if (!this._viewMetricsCallbackRegistered) { this._viewMetricsCallbackRegistered = true; UIWidgetsMessageManager.instance?.AddChannelMessageDelegate("ViewportMatricsChanged", this._handleViewMetricsChanged); } if (this._mouseEntered) { if (this._lastMouseMove.x != Input.mousePosition.x || this._lastMouseMove.y != Input.mousePosition.y) { this.handleMouseMovement(); } } this._lastMouseMove = Input.mousePosition; if (this._mouseEntered) { this.handleMouseScroll(); } D.assert(this._windowAdapter != null); this._windowAdapter.Update(); this._windowAdapter.OnGUI(_repaintEvent); } void OnGUI() { this._displayMetrics.OnGUI(); if (Event.current.type == EventType.KeyDown || Event.current.type == EventType.KeyUp) { this._windowAdapter.OnGUI(Event.current); } } void handleMouseMovement() { var pos = this.getPointPosition(Input.mousePosition); if (pos == null) { return; } this._windowAdapter.postPointerEvent(new PointerData( timeStamp: Timer.timespanSinceStartup, change: PointerChange.hover, kind: PointerDeviceKind.mouse, device: this.getMouseButtonDown(), physicalX: pos.Value.x, physicalY: pos.Value.y )); } void handleMouseScroll() { if (Input.mouseScrollDelta.y != 0 || Input.mouseScrollDelta.x != 0) { var scaleFactor = this.canvas.scaleFactor; var pos = this.getPointPosition(Input.mousePosition); if (pos == null) { return; } this._windowAdapter.onScroll(Input.mouseScrollDelta.x * scaleFactor, Input.mouseScrollDelta.y * scaleFactor, pos.Value.x, pos.Value.y, InputUtils.getScrollButtonKey()); } } int getMouseButtonDown() { //default mouse button key = left mouse button var defaultKey = 0; for (int key = 0; key < mouseButtonNum; key++) { if (Input.GetMouseButton(key)) { defaultKey = key; break; } } return InputUtils.getMouseButtonKey(defaultKey); } public void OnPointerDown(PointerEventData eventData) { var position = this.getPointPosition(eventData); if (position == null) { return; } EventSystem.current.SetSelectedGameObject(this.gameObject, eventData); this._windowAdapter.postPointerEvent(new PointerData( timeStamp: Timer.timespanSinceStartup, change: PointerChange.down, kind: InputUtils.getPointerDeviceKind(eventData), device: InputUtils.getPointerDeviceKey(eventData), physicalX: position.Value.x, physicalY: position.Value.y )); } public void OnPointerUp(PointerEventData eventData) { var position = this.getPointPosition(eventData); if (position == null) { return; } this._windowAdapter.postPointerEvent(new PointerData( timeStamp: Timer.timespanSinceStartup, change: PointerChange.up, kind: InputUtils.getPointerDeviceKind(eventData), device: InputUtils.getPointerDeviceKey(eventData), physicalX: position.Value.x, physicalY: position.Value.y )); } Camera getActiveCamera() { //refer to: https://zhuanlan.zhihu.com/p/37127981 Camera eventCamera = null; if (this.canvas.renderMode != RenderMode.ScreenSpaceOverlay) { eventCamera = this.canvas.GetComponent<GraphicRaycaster>().eventCamera; } return eventCamera; } Vector2? getPointPosition(PointerEventData eventData) { Camera camera = this.getActiveCamera(); Vector2 localPoint; RectTransformUtility.ScreenPointToLocalPointInRectangle(this.rectTransform, eventData.position, camera, out localPoint); var scaleFactor = this.canvas.scaleFactor; localPoint.x = (localPoint.x - this.rectTransform.rect.min.x) * scaleFactor; localPoint.y = (this.rectTransform.rect.max.y - localPoint.y) * scaleFactor; return localPoint; } Vector2? getPointPosition(Vector2 position) { Vector2 localPoint; Camera eventCamera = this.getActiveCamera(); RectTransformUtility.ScreenPointToLocalPointInRectangle(this.rectTransform, position, eventCamera, out localPoint); var scaleFactor = this.canvas.scaleFactor; localPoint.x = (localPoint.x - this.rectTransform.rect.min.x) * scaleFactor; localPoint.y = (this.rectTransform.rect.max.y - localPoint.y) * scaleFactor; return localPoint; } public void OnDrag(PointerEventData eventData) { var position = this.getPointPosition(eventData); if (position == null) { return; } this._windowAdapter.postPointerEvent(new PointerData( timeStamp: Timer.timespanSinceStartup, change: PointerChange.move, kind: InputUtils.getPointerDeviceKind(eventData), device: InputUtils.getPointerDeviceKey(eventData), physicalX: position.Value.x, physicalY: position.Value.y )); } public void OnPointerEnter(PointerEventData eventData) { var position = this.getPointPosition(eventData); if (position == null) { return; } var pointerKey = InputUtils.getPointerDeviceKey(eventData); this._enteredPointers.Add(pointerKey); this._lastMouseMove = eventData.position; this._windowAdapter.postPointerEvent(new PointerData( timeStamp: Timer.timespanSinceStartup, change: PointerChange.hover, kind: InputUtils.getPointerDeviceKind(eventData), device: pointerKey, physicalX: position.Value.x, physicalY: position.Value.y )); } public void OnPointerExit(PointerEventData eventData) { var position = this.getPointPosition(eventData); if (position == null) { return; } var pointerKey = InputUtils.getPointerDeviceKey(eventData); this._enteredPointers.Remove(pointerKey); this._windowAdapter.postPointerEvent(new PointerData( timeStamp: Timer.timespanSinceStartup, change: PointerChange.hover, kind: InputUtils.getPointerDeviceKind(eventData), device: pointerKey, physicalX: position.Value.x, physicalY: position.Value.y )); } public Window window { get { return this._windowAdapter; } } } }
38.364286
135
0.574009
[ "Apache-2.0" ]
Luciano-0/2048-Demo
Library/PackageCache/com.unity.uiwidgets@1.5.4-preview.12/Runtime/engine/UIWidgetsPanel.cs
16,113
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using stellar_dotnet_sdk.responses.operations; using System; using System.Collections.Generic; using System.Text; using System.IO; using Newtonsoft.Json; using stellar_dotnet_sdk.responses; namespace stellar_dotnet_sdk_test.responses { [TestClass] public class OperationFeeStatsDeserializerTest { [TestMethod] public void TestDeserialize() { var json = File.ReadAllText(Path.Combine("testdata", "operationFeeStats.json")); var stats = JsonSingleton.GetInstance<OperationFeeStatsResponse>(json); AssertTestData(stats); } [TestMethod] public void TestSerializeDeserialize() { var json = File.ReadAllText(Path.Combine("testdata", "operationFeeStats.json")); var stats = JsonConvert.DeserializeObject<OperationFeeStatsResponse>(json); var serialized = JsonConvert.SerializeObject(stats); var back = JsonConvert.DeserializeObject<OperationFeeStatsResponse>(serialized); Assert.AreEqual(stats.Min, back.Min); Assert.AreEqual(stats.Mode, back.Mode); Assert.AreEqual(stats.LastLedger, back.LastLedger); Assert.AreEqual(stats.LastLedgerBaseFee, back.LastLedgerBaseFee); } public static void AssertTestData(OperationFeeStatsResponse stats) { Assert.AreEqual(20882791L, stats.LastLedger); Assert.AreEqual(100L, stats.LastLedgerBaseFee); Assert.AreEqual(101L, stats.Min); Assert.AreEqual(102L, stats.Mode); Assert.AreEqual(103L, stats.P10); Assert.AreEqual(104L, stats.P20); Assert.AreEqual(105L, stats.P30); Assert.AreEqual(106L, stats.P40); Assert.AreEqual(107L, stats.P50); Assert.AreEqual(108L, stats.P60); Assert.AreEqual(109L, stats.P70); Assert.AreEqual(110L, stats.P80); Assert.AreEqual(111L, stats.P90); Assert.AreEqual(112L, stats.P95); Assert.AreEqual(113L, stats.P99); Assert.AreEqual(0.97m, stats.LedgerCapacityUsage); } } }
37.915254
92
0.644613
[ "Apache-2.0" ]
alphapoint/dotnet-stellar-sdk
stellar-dotnet-sdk-test/responses/OperationFeeStatsDeserializerTest.cs
2,239
C#
using System.Runtime.CompilerServices; using Windows.UI.Xaml.Controls; namespace Uno.UI; internal static class MenuBar_737b513acf107ddd62b115a6fa290d25XamlApplyExtensions { public delegate void XamlApplyHandler0(ItemsControl instance); public delegate void XamlApplyHandler1(Grid instance); public delegate void XamlApplyHandler2(StackPanel instance); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ItemsControl MenuBar_737b513acf107ddd62b115a6fa290d25_XamlApply(this ItemsControl instance, XamlApplyHandler0 handler) { handler(instance); return instance; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Grid MenuBar_737b513acf107ddd62b115a6fa290d25_XamlApply(this Grid instance, XamlApplyHandler1 handler) { handler(instance); return instance; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static StackPanel MenuBar_737b513acf107ddd62b115a6fa290d25_XamlApply(this StackPanel instance, XamlApplyHandler2 handler) { handler(instance); return instance; } }
29.714286
133
0.841346
[ "MIT" ]
ljcollins25/Codeground
src/UnoApp/UnoDecompile/Uno.UI/Uno.UI/MenuBar_737b513acf107ddd62b115.cs
1,040
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Microsoft.AspNetCore.Mvc.Filters { internal readonly struct FilterFactoryResult { public FilterFactoryResult(FilterItem[] cacheableFilters, IFilterMetadata[] filters) { CacheableFilters = cacheableFilters; Filters = filters; } public FilterItem[] CacheableFilters { get; } public IFilterMetadata[] Filters { get; } } }
30.315789
111
0.680556
[ "Apache-2.0" ]
belav/aspnetcore
src/Mvc/Mvc.Core/src/Filters/FilterFactoryResult.cs
578
C#
using System; namespace UnrealEngine { public partial class UNavPathObserverInterface:UInterface { } }
11.1
58
0.765766
[ "MIT" ]
xiongfang/UnrealCS
Script/UnrealEngine/GeneratedScriptFile/UNavPathObserverInterface.cs
111
C#
// Copyright (c) Amer Koleci and contributors. // Distributed under the MIT license. See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using SharpGen.Runtime; namespace Vortice.XAudio2 { [Shadow(typeof(IXAudio2VoiceCallbackShadow))] public partial interface IXAudio2VoiceCallback { /// <summary> /// Called during each processing pass for each voice, just before XAudio2 reads data from the voice's buffer queue. /// </summary> /// <param name="bytesRequired"> The number of bytes that must be submitted immediately to avoid starvation. This allows the implementation of just-in-time streaming scenarios; the client can keep the absolute minimum data queued on the voice at all times, and pass it fresh data just before the data is required. This model provides the lowest possible latency attainable with XAudio2. For xWMA and XMA data BytesRequired will always be zero, since the concept of a frame of xWMA or XMA data is meaningless. Note In a situation where there is always plenty of data available on the source voice, BytesRequired should always report zero, because it doesn't need any samples immediately to avoid glitching. </param> void OnVoiceProcessingPassStart(int bytesRequired); /// <summary> /// Called just after the processing pass for the voice ends. /// </summary> void OnVoiceProcessingPassEnd(); /// <summary> /// Called when the voice has just finished playing a contiguous audio stream. /// </summary> void OnStreamEnd(); /// <summary> /// Called when the voice is about to start processing a new audio buffer. /// </summary> /// <param name="context"> Context pointer that was assigned to the pContext member of the <see cref="AudioBuffer"/> structure when the buffer was submitted. </param> void OnBufferStart(IntPtr context); /// <summary> /// Called when the voice finishes processing a buffer. /// </summary> /// <param name="context"> Context pointer assigned to the pContext member of the <see cref="AudioBuffer"/> structure when the buffer was submitted. </param> void OnBufferEnd(IntPtr context); /// <summary> /// Called when the voice reaches the end position of a loop. /// </summary> /// <param name="context"> Context pointer that was assigned to the pContext member of the <see cref="AudioBuffer"/> structure when the buffer was submitted. </param> void OnLoopEnd(IntPtr context); /// <summary> /// Called when a critical error occurs during voice processing. /// </summary> /// <param name="context"> Context pointer that was assigned to the pContext member of the <see cref="AudioBuffer"/> structure when the buffer was submitted. </param> /// <param name="error"> The HRESULT code of the error encountered. </param> void OnVoiceError(IntPtr context, Result error); } internal class IXAudio2VoiceCallbackShadow : CppObjectShadow { private static readonly VTable _vTable = new VTable(); protected override CppObjectVtbl Vtbl => _vTable; /// <summary> /// Return a pointer to the unmanaged version of this callback. /// </summary> /// <param name="callback">The callback.</param> /// <returns>A pointer to a shadow c++ callback</returns> public static IntPtr ToIntPtr(IXAudio2VoiceCallback callback) { return ToCallbackPtr<IXAudio2VoiceCallback>(callback); } private class VTable : CppObjectVtbl { public VTable() : base(7) { AddMethod(new IntDelegate(OnVoiceProcessingPassStartImpl)); AddMethod(new VoidDelegate(OnVoiceProcessingPassEndImpl)); AddMethod(new VoidDelegate(OnStreamEndImpl)); AddMethod(new IntPtrDelegate(OnBufferStartImpl)); AddMethod(new IntPtrDelegate(OnBufferEndImpl)); AddMethod(new IntPtrDelegate(OnLoopEndImpl)); AddMethod(new IntPtrIntDelegate(OnVoiceErrorImpl)); } [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void VoidDelegate(IntPtr thisObject); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void IntDelegate(IntPtr thisObject, int bytes); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void IntPtrDelegate(IntPtr thisObject, IntPtr address); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void IntPtrIntDelegate(IntPtr thisObject, IntPtr address, int error); static private void OnVoiceProcessingPassStartImpl(IntPtr thisObject, int bytes) { var shadow = ToShadow<IXAudio2VoiceCallbackShadow>(thisObject); var callback = (IXAudio2VoiceCallback)shadow.Callback; callback.OnVoiceProcessingPassStart(bytes); } static private void OnVoiceProcessingPassEndImpl(IntPtr thisObject) { var shadow = ToShadow<IXAudio2VoiceCallbackShadow>(thisObject); var callback = (IXAudio2VoiceCallback)shadow.Callback; callback.OnVoiceProcessingPassEnd(); } static private void OnStreamEndImpl(IntPtr thisObject) { var shadow = ToShadow<IXAudio2VoiceCallbackShadow>(thisObject); var callback = (IXAudio2VoiceCallback)shadow.Callback; callback.OnStreamEnd(); } static private void OnBufferStartImpl(IntPtr thisObject, IntPtr address) { var shadow = ToShadow<IXAudio2VoiceCallbackShadow>(thisObject); var callback = (IXAudio2VoiceCallback)shadow.Callback; callback.OnBufferStart(address); } static private void OnBufferEndImpl(IntPtr thisObject, IntPtr address) { var shadow = ToShadow<IXAudio2VoiceCallbackShadow>(thisObject); var callback = (IXAudio2VoiceCallback)shadow.Callback; callback.OnBufferEnd(address); } static private void OnLoopEndImpl(IntPtr thisObject, IntPtr address) { var shadow = ToShadow<IXAudio2VoiceCallbackShadow>(thisObject); var callback = (IXAudio2VoiceCallback)shadow.Callback; callback.OnLoopEnd(address); } static private void OnVoiceErrorImpl(IntPtr thisObject, IntPtr bufferContextRef, int error) { var shadow = ToShadow<IXAudio2VoiceCallbackShadow>(thisObject); var callback = (IXAudio2VoiceCallback)shadow.Callback; callback.OnVoiceError(bufferContextRef, new Result(error)); } } } }
47.46
722
0.65276
[ "MIT" ]
DanielElam/Vortice.Windows
src/Vortice.XAudio2/IXAudio2VoiceCallback.cs
7,119
C#
/* * FactSet Overview Report Builder API * * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = FactSet.SDK.OverviewReportBuilder.Client.OpenAPIDateConverter; namespace FactSet.SDK.OverviewReportBuilder.Model { /// <summary> /// DataPointMeta /// </summary> [JsonConverter(typeof(DataPointMetaJsonConverter))] [DataContract(Name = "DataPointMeta")] public partial class DataPointMeta : AbstractOpenAPISchema, IEquatable<DataPointMeta>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="DataPointMeta" /> class /// with the <see cref="DataPointMetaAnyOf" /> class /// </summary> /// <param name="actualInstance">An instance of DataPointMetaAnyOf.</param> public DataPointMeta(DataPointMetaAnyOf actualInstance) { this.IsNullable = false; this.SchemaType= "anyOf"; this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); } private Object _actualInstance; /// <summary> /// Gets or Sets ActualInstance /// </summary> public override Object ActualInstance { get { return _actualInstance; } set { if (value.GetType() == typeof(DataPointMetaAnyOf)) { this._actualInstance = value; } else { throw new ArgumentException("Invalid instance found. Must be the following types: DataPointMetaAnyOf"); } } } /// <summary> /// Get the actual instance of `DataPointMetaAnyOf`. If the actual instance is not `DataPointMetaAnyOf`, /// the InvalidClassException will be thrown /// </summary> /// <returns>An instance of DataPointMetaAnyOf</returns> public DataPointMetaAnyOf GetDataPointMetaAnyOf() { return (DataPointMetaAnyOf)this.ActualInstance; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class DataPointMeta {\n"); sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public override string ToJson() { return JsonConvert.SerializeObject(this.ActualInstance, DataPointMeta.SerializerSettings); } /// <summary> /// Converts the JSON string into an instance of DataPointMeta /// </summary> /// <param name="jsonString">JSON string</param> /// <returns>An instance of DataPointMeta</returns> public static DataPointMeta FromJson(string jsonString) { DataPointMeta newDataPointMeta = null; if (string.IsNullOrEmpty(jsonString)) { return newDataPointMeta; } try { newDataPointMeta = new DataPointMeta(JsonConvert.DeserializeObject<DataPointMetaAnyOf>(jsonString, DataPointMeta.SerializerSettings)); // deserialization is considered successful at this point if no exception has been thrown. return newDataPointMeta; } catch (Exception exception) { // deserialization failed, try the next one System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into DataPointMetaAnyOf: {1}", jsonString, exception.ToString())); } // no match found, throw an exception throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as DataPointMeta); } /// <summary> /// Returns true if DataPointMeta instances are equal /// </summary> /// <param name="input">Instance of DataPointMeta to be compared</param> /// <returns>Boolean</returns> public bool Equals(DataPointMeta input) { if (input == null) return false; return this.ActualInstance.Equals(input.ActualInstance); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.ActualInstance != null) hashCode = hashCode * 59 + this.ActualInstance.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } /// <summary> /// Custom JSON converter for DataPointMeta /// </summary> public class DataPointMetaJsonConverter : JsonConverter { /// <summary> /// To write the JSON string /// </summary> /// <param name="writer">JSON writer</param> /// <param name="value">Object to be converted into a JSON string</param> /// <param name="serializer">JSON Serializer</param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteRawValue((string)(typeof(DataPointMeta).GetMethod("ToJson").Invoke(value, null))); } /// <summary> /// To convert a JSON string into an object /// </summary> /// <param name="reader">JSON reader</param> /// <param name="objectType">Object type</param> /// <param name="existingValue">Existing value</param> /// <param name="serializer">JSON Serializer</param> /// <returns>The object converted from the JSON string</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if(reader.TokenType != JsonToken.Null) { return DataPointMeta.FromJson(JObject.Load(reader).ToString(Formatting.None)); } return null; } /// <summary> /// Check if the object can be converted /// </summary> /// <param name="objectType">Object type</param> /// <returns>True if the object can be converted</returns> public override bool CanConvert(Type objectType) { return false; } } }
35.846491
160
0.595497
[ "Apache-2.0" ]
factset/enterprise-sdk
code/dotnet/OverviewReportBuilder/v1/src/FactSet.SDK.OverviewReportBuilder/Model/DataPointMeta.cs
8,173
C#
//----------------------------------------------------------------------------- // Copyright : (c) Chris Moore, 2020 // License : MIT //----------------------------------------------------------------------------- namespace Z0 { public abstract class ExecutablePart<P> : Part<P>, IExecutablePart<P> where P : Part<P>, IExecutablePart<P>, new() { public static void RunPart(params string[] args) => new P().Execute(args); public abstract void Execute(params string[] args); } }
36.066667
79
0.415896
[ "BSD-3-Clause" ]
0xCM/z0
src/workflow/src/wf.shell/abstractions/ExecutablePart.cs
541
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Repository; using Repository.Seed; using System; using System.Threading.Tasks; namespace API { public class Program { public static async Task Main(string[] args) { var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var loggerFactory = services.GetRequiredService<ILoggerFactory>(); try { var context = services.GetRequiredService<ApplicationDbContext>(); await context.Database.MigrateAsync(); await StoreContextSeed.SeedAsync(context, loggerFactory); } catch(Exception e) { var logger = loggerFactory.CreateLogger<Program>(); logger.LogError(e, "An error occured during migration."); } } host.Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
32.822222
86
0.574137
[ "MIT" ]
sofire07/skinet-backend
API/Program.cs
1,477
C#
using System.Collections.Generic; using System.Threading.Tasks; namespace BlankApp1.Services { public interface IChatDataStore : IDataStore<Chat> { Task<IEnumerable<Chat>> GetChatsAsync(); } }
19.545455
54
0.72093
[ "MIT" ]
silvajnr/PrismTabbedDbContext
BlankApp1/BlankApp1/BlankApp1/Services/IChatDataStore.cs
217
C#
version https://git-lfs.github.com/spec/v1 oid sha256:c69635935108225fdef17a59ae6e3610f1a4d7e424f14c7b6780e0ea0993336d size 2318
32.25
75
0.883721
[ "MIT" ]
bakiya-sefer/bakiya-sefer
Assets/Best HTTP (Pro)/BestHTTP/SecureProtocol/math/ec/custom/sec/SecP192K1Curve.cs
129
C#
using System; using System.Runtime.Serialization; using PlatHak.Common.Maths; namespace PlatHak.Common.World { public class WorldConfig { /// <summary> /// A default world config that is setup for the entire world. /// </summary> public static readonly WorldConfig Default = new WorldConfig(new Size(675, 337), new Size(32, 32), new Size(277, 277), new Size(13, 13), new Size(1, 1), TimeSpan.FromSeconds(1 / 60f)); /// <summary> /// The size of each Tile, in meters. /// <example>1x1 meter</example> /// </summary> public Size ItemSize; /// <summary> /// The size of each chunk, in Tiles. /// </summary> public Size ChunkSize; /// <summary> /// The size of each Cluster, in Chunks. /// </summary> public Size ClusterSize; /// <summary> /// The size of each Block, in Clusters. /// </summary> public Size BlockSize; /// <summary> /// The size of the world, in blocks /// </summary> public Size WorldSize; /// <summary> /// The Max global cord (WorldSize * ChunkSize * ItemSize) /// </summary> public Size GlobalCoordinatesSize => WorldSize * BlockSize * ClusterSize * ChunkSize; public TimeSpan UpdateTimeSpan { get; set; } /// <summary> /// Creates a new World Config /// </summary> /// <param name="worldSize">size of the world in Blocks</param> /// <param name="blockSize">size of each block in clusters</param> /// <param name="clusterSize">size of each cluster in chunks</param> /// <param name="chunkSize">size of each chunk in items</param> /// <param name="itemSize">size of each item in meters</param> /// <param name="updateTimeSpan">interval for game update timer</param> private WorldConfig(Size worldSize, Size blockSize, Size clusterSize, Size chunkSize, Size itemSize, TimeSpan updateTimeSpan) { ItemSize = itemSize; ChunkSize = chunkSize; ClusterSize = clusterSize; BlockSize = blockSize; WorldSize = worldSize; UpdateTimeSpan = updateTimeSpan; } public VectorLong2 GetGlobalPosistionFromLatLon(Vector2 latLon) { var x = GlobalCoordinatesSize.Width * (180 + latLon.Y) / 360; var y = GlobalCoordinatesSize.Height * (90 - latLon.X) / 180; return new VectorLong2((long) Math.Floor(x), (long) Math.Floor(y)); } public VectorLong2 GetBlockLocalPosistion(VectorLong2 globalPosistion) { var blockItemSize = BlockSize * ClusterSize * ChunkSize; return globalPosistion / blockItemSize; } public VectorLong2 GetBlockGlobalPosistion(VectorLong2 blockLocalPosistion) { var blockItemSize = BlockSize * ClusterSize * ChunkSize; return blockLocalPosistion * blockItemSize; } public VectorLong2 GetClusterLocalPosistion(VectorLong2 globalPosistion) { var localBlockPosistion = GetBlockLocalPosistion(globalPosistion); var blockItemSize = BlockSize * ClusterSize * ChunkSize; var clusterItemSize = ClusterSize * ChunkSize; return (globalPosistion - localBlockPosistion * blockItemSize) / clusterItemSize; } public VectorLong2 GetClusterGlobalPosistion(VectorLong2 blockLocalPosistion, VectorLong2 clusterLocalPosistion) { var globalBlockPosistion = GetBlockGlobalPosistion(blockLocalPosistion); var clusterItemSize = ClusterSize * ChunkSize; return globalBlockPosistion + clusterLocalPosistion * clusterItemSize; } public VectorLong2 GetChunkLocalPosistion(VectorLong2 globalPosistion) { var localBlockPosistion = GetBlockLocalPosistion(globalPosistion); var localClusterPosistion = GetClusterLocalPosistion(globalPosistion); var blockItemSize = BlockSize * ClusterSize * ChunkSize; var clusterItemSize = ClusterSize * ChunkSize; var chunkItemSize = ChunkSize; return ((globalPosistion - localClusterPosistion * clusterItemSize) - localBlockPosistion * blockItemSize) / chunkItemSize; } public VectorLong2 GetChunkGlobalPosistion(VectorLong2 blockLocalPosistion, VectorLong2 clusterLocalPosistion, VectorLong2 chunkLocalPosistion) { var globalClusterPosistion = GetClusterGlobalPosistion(blockLocalPosistion, clusterLocalPosistion); var chunkItemSize = ChunkSize; return globalClusterPosistion + chunkLocalPosistion * chunkItemSize; } public VectorLong2 GetTileLocalPosistion(VectorLong2 globalPosistion) { var localBlockPosistion = GetBlockLocalPosistion(globalPosistion); var localClusterPosistion = GetClusterLocalPosistion(globalPosistion); var localChunkPosistion = GetChunkLocalPosistion(globalPosistion); var blockItemSize = BlockSize * ClusterSize * ChunkSize; var clusterItemSize = ClusterSize * ChunkSize; var chunkItemSize = ChunkSize; return globalPosistion - localClusterPosistion * clusterItemSize - localBlockPosistion * blockItemSize - localChunkPosistion * chunkItemSize; } public VectorLong2 GetTileGlobalPosistion(VectorLong2 blockLocalPosistion, VectorLong2 clusterLocalPosistion, VectorLong2 chunkLocalPosistion, VectorLong2 tileLocalPosistion) { var globalChunkPosistion = GetChunkGlobalPosistion(blockLocalPosistion, clusterLocalPosistion, chunkLocalPosistion); return globalChunkPosistion + tileLocalPosistion; } } }
44.606061
192
0.654721
[ "CC0-1.0" ]
coman3/PlatHak
PlatHak/PlatHak.Common/World/WorldConfig.cs
5,890
C#
using Unosquare.PocoData.Tests.DataModels; using AutoFixture; using Xunit; using FluentAssertions; using System.Linq; namespace Unosquare.PocoData.Tests { public class InsertTest : DbTest { public InsertTest() : base(QueryFactory.CreateEmployeeTable) { } [Fact] public void Insert() { var fixture = new Fixture(); using var db = new SampleDb(); var employee = fixture.Create<Employee>(); db.Employees.Insert(employee, false); Assert.NotEqual(0, employee.EmployeeId); } [Fact] public async void InsertAsync() { var fixture = new Fixture(); using var db = new SampleDb(); var employee = fixture.Create<Employee>(); await db.Employees.InsertAsync(employee, false); Assert.NotEqual(0, employee.EmployeeId); } [Fact(Skip = "Missing add trigger to generate a change and reload info")] public void InsertUpdate() { var fixture = new Fixture(); using var db = new SampleDb(); var employee = fixture.Build<Employee>() .Without(x => x.Reads) .Create(); db.Employees.Insert(employee, true); employee.Reads.Should().BeGreaterThan(0); } [Fact(Skip = "Missing add trigger to generate a change and reload info")] public async void InsertUpdateAsync() { var fixture = new Fixture(); using var db = new SampleDb(); var employee = fixture.Build<Employee>() .Without(x => x.Reads) .Create(); await db.Employees.InsertAsync(employee, true); employee.Reads.Should().BeGreaterThan(0); } [Fact] public void InsertMany() { var fixture = new Fixture(); using var db = new SampleDb(); var employees = fixture.CreateMany<Employee>(5); db.Employees.InsertMany(employees, false); employees.Count().Should().Be(5); } [Fact] public async void InsertManyAsync() { var fixture = new Fixture(); using var db = new SampleDb(); var employees = fixture.CreateMany<Employee>(5); await db.Employees.InsertManyAsync(employees, false); employees.Count().Should().Be(5); } } }
28.022989
81
0.559475
[ "MIT" ]
unosquare/pocodata
Unosquare.PocoData.Tests/InsertTest.cs
2,440
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq.Expressions; using System.Threading.Tasks; using AntDesign.Forms; using AntDesign.Internal; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Forms; namespace AntDesign { /// <summary> /// Base class for any input control that optionally supports an <see cref="EditContext"/>. /// reference:https://github.com/dotnet/aspnetcore/blob/master/src/Components/Web/src/Forms/InputBase.cs /// </summary> /// <typeparam name="TValue">the natural type of the input's value</typeparam> public abstract class AntInputComponentBase<TValue> : AntDomComponentBase, IControlValueAccessor { private readonly EventHandler<ValidationStateChangedEventArgs> _validationStateChangedHandler; private bool _previousParsingAttemptFailed; private ValidationMessageStore _parsingValidationMessages; private Type _nullableUnderlyingType; [CascadingParameter(Name = "FormItem")] private IFormItem FormItem { get; set; } [CascadingParameter(Name = "Form")] protected IForm Form { get; set; } public string[] ValidationMessages { get; set; } = Array.Empty<string>(); private string _formSize; [CascadingParameter(Name = "FormSize")] public string FormSize { get { return _formSize; } set { _formSize = value; Size = value; } } /// <summary> /// Gets or sets a collection of additional attributes that will be applied to the created element. /// </summary> [Parameter(CaptureUnmatchedValues = true)] public IReadOnlyDictionary<string, object> AdditionalAttributes { get; set; } private TValue _value; /// <summary> /// Gets or sets the value of the input. This should be used with two-way binding. /// </summary> /// <example> /// @bind-Value="model.PropertyName" /// </example> [Parameter] public virtual TValue Value { get { return _value; } set { var hasChanged = !EqualityComparer<TValue>.Default.Equals(value, Value); if (hasChanged) { _value = value; OnValueChange(value); } } } /// <summary> /// Gets or sets a callback that updates the bound value. /// </summary> [Parameter] public virtual EventCallback<TValue> ValueChanged { get; set; } /// <summary> /// Gets or sets an expression that identifies the bound value. /// </summary> [Parameter] public Expression<Func<TValue>> ValueExpression { get; set; } [Parameter] public Expression<Func<IEnumerable<TValue>>> ValuesExpression { get; set; } [Parameter] public string Size { get; set; } = AntSizeLDSType.Default; [Parameter] public virtual CultureInfo CultureInfo { get; set; } = CultureInfo.CurrentCulture; /// <summary> /// Gets the associated <see cref="EditContext"/>. /// </summary> protected EditContext EditContext { get; set; } /// <summary> /// Gets the <see cref="FieldIdentifier"/> for the bound value. /// </summary> internal FieldIdentifier FieldIdentifier { get; set; } /// <summary> /// Gets or sets the current value of the input. /// </summary> protected TValue CurrentValue { get => Value; set { var hasChanged = !EqualityComparer<TValue>.Default.Equals(value, Value); if (hasChanged) { Value = value; ValueChanged.InvokeAsync(value); if (_isNotifyFieldChanged && (Form?.ValidateOnChange == true)) { EditContext?.NotifyFieldChanged(FieldIdentifier); } } } } /// <summary> /// Gets or sets the current value of the input, represented as a string. /// </summary> protected string CurrentValueAsString { get => FormatValueAsString(CurrentValue); set { _parsingValidationMessages?.Clear(); bool parsingFailed; if (_nullableUnderlyingType != null && string.IsNullOrEmpty(value)) { // Assume if it's a nullable type, null/empty inputs should correspond to default(T) // Then all subclasses get nullable support almost automatically (they just have to // not reject Nullable<T> based on the type itself). parsingFailed = false; CurrentValue = default; } else if (TryParseValueFromString(value, out var parsedValue, out var validationErrorMessage)) { parsingFailed = false; CurrentValue = parsedValue; } else { parsingFailed = true; if (EditContext != null) { if (_parsingValidationMessages == null) { _parsingValidationMessages = new ValidationMessageStore(EditContext); } _parsingValidationMessages.Add(FieldIdentifier, validationErrorMessage); // Since we're not writing to CurrentValue, we'll need to notify about modification from here EditContext.NotifyFieldChanged(FieldIdentifier); } } // We can skip the validation notification if we were previously valid and still are if ((parsingFailed || _previousParsingAttemptFailed) && EditContext != null) { EditContext.NotifyValidationStateChanged(); _previousParsingAttemptFailed = parsingFailed; } } } private TValue _firstValue; protected bool _isNotifyFieldChanged = true; private bool _isValueGuid; /// <summary> /// Constructs an instance of <see cref="InputBase{TValue}"/>. /// </summary> protected AntInputComponentBase() { _validationStateChangedHandler = (sender, eventArgs) => StateHasChanged(); } /// <summary> /// Formats the value as a string. Derived classes can override this to determine the formating used for <see cref="CurrentValueAsString"/>. /// </summary> /// <param name="value">The value to format.</param> /// <returns>A string representation of the value.</returns> protected virtual string FormatValueAsString(TValue value) => value?.ToString(); /// <summary> /// Parses a string to create an instance of <typeparamref name="TValue"/>. Derived classes can override this to change how /// <see cref="CurrentValueAsString"/> interprets incoming values. /// </summary> /// <param name="value">The string value to be parsed.</param> /// <param name="result">An instance of <typeparamref name="TValue"/>.</param> /// <param name="validationErrorMessage">If the value could not be parsed, provides a validation error message.</param> /// <returns>True if the value could be parsed; otherwise false.</returns> protected virtual bool TryParseValueFromString(string value, out TValue result, out string validationErrorMessage) { if (string.IsNullOrWhiteSpace(value)) { result = default; validationErrorMessage = null; return true; } TValue parsedValue = default; bool success; // BindConverter.TryConvertTo<Guid> doesn't work for a incomplete Guid fragment. Remove this when the BCL bug is fixed. if (_isValueGuid) { success = Guid.TryParse(value, out Guid parsedGuidValue); if (success) parsedValue = THelper.ChangeType<TValue>(parsedGuidValue); } else { success = BindConverter.TryConvertTo(value, CultureInfo, out parsedValue); } if (success) { result = parsedValue; validationErrorMessage = null; return true; } else { result = default; validationErrorMessage = $"{FieldIdentifier.FieldName} field isn't valid."; return false; } } /// <summary> /// When this method is called, Value is only has been modified, but the ValueChanged is not triggered, so the outside bound Value is not changed. /// </summary> /// <param name="value"></param> protected virtual void OnValueChange(TValue value) { } protected override void OnInitialized() { _isValueGuid = THelper.GetUnderlyingType<TValue>() == typeof(Guid); base.OnInitialized(); FormItem?.AddControl(this); Form?.AddControl(this); _firstValue = Value; } /// <inheritdoc /> public override Task SetParametersAsync(ParameterView parameters) { parameters.SetParameterProperties(this); if (EditContext == null) { // This is the first run // Could put this logic in OnInit, but its nice to avoid forcing people who override OnInit to call base.OnInit() if (Form?.EditContext == null) { return base.SetParametersAsync(ParameterView.Empty); } if (ValueExpression == null && ValuesExpression == null) { return base.SetParametersAsync(ParameterView.Empty); } EditContext = Form?.EditContext; if (ValuesExpression == null) FieldIdentifier = FieldIdentifier.Create(ValueExpression); else FieldIdentifier = FieldIdentifier.Create(ValuesExpression); _nullableUnderlyingType = Nullable.GetUnderlyingType(typeof(TValue)); EditContext.OnValidationStateChanged += _validationStateChangedHandler; } else if (Form?.EditContext != EditContext) { // Not the first run // We don't support changing EditContext because it's messy to be clearing up state and event // handlers for the previous one, and there's no strong use case. If a strong use case // emerges, we can consider changing this. throw new InvalidOperationException($"{GetType()} does not support changing the " + $"{nameof(EditContext)} dynamically."); } // For derived components, retain the usual lifecycle with OnInit/OnParametersSet/etc. return base.SetParametersAsync(ParameterView.Empty); } protected override void Dispose(bool disposing) { if (EditContext != null) { EditContext.OnValidationStateChanged -= _validationStateChangedHandler; } base.Dispose(disposing); } internal virtual void ResetValue() { _isNotifyFieldChanged = false; CurrentValue = _firstValue; _isNotifyFieldChanged = true; } void IControlValueAccessor.Reset() { ResetValue(); } } }
36.100295
154
0.55581
[ "MIT" ]
Banyc/ant-design-blazor
components/core/Base/AntInputComponentBase.cs
12,240
C#
using System; using System.Linq; using System.Threading.Tasks; using AsyncGenerator.Analyzation; using AsyncGenerator.Core; using AsyncGenerator.TestCases; using AsyncGenerator.Tests.MethodReferences.Input; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using NUnit.Framework; namespace AsyncGenerator.Tests.MethodReferences { [TestFixture] public class Fixture : BaseFixture { [Test, Repeat(10)] public Task TestAfterTransformation() { return ReadonlyTest(nameof(ForwardCall), p => p .ConfigureAnalyzation(a => a .MethodConversion(symbol => MethodConversion.Smart) .SearchForMethodReferences(symbol => !symbol.GetAttributes().Any(o => o.AttributeClass.Name == nameof(CustomAttribute))) ) .ConfigureTransformation(t => t .AfterTransformation(result => { AssertValidAnnotations(result); Assert.AreEqual(1, result.Documents.Count); var document = result.Documents[0]; Assert.NotNull(document.OriginalModified); Assert.AreEqual(GetOutputFile(nameof(ForwardCall)), document.Transformed.ToFullString()); }) ) ); } } }
29
125
0.740053
[ "MIT" ]
bubdm/AsyncGenerator
Source/AsyncGenerator.Tests/MethodReferences/Fixture.cs
1,133
C#
namespace Lifx { // Represents a color comprised of hue and saturation. public struct Color { public Color(Hue hue, Percentage saturation) { Hue = hue; Saturation = saturation; } public static Color None { get; } = White; public static Color White { get; } = new Color(0, 0); public static Color Red { get; } = new Color(0, 1); public static Color Orange { get; } = new Color(36, 1); public static Color Yellow { get; } = new Color(60, 1); public static Color Green { get; } = new Color(120, 1); public static Color Cyan { get; } = new Color(180, 1); public static Color Blue { get; } = new Color(250, 1); public static Color Purple { get; } = new Color(280, 1); public static Color Pink { get; } = new Color(325, 1); public Hue Hue { get; } public Percentage Saturation { get; } public override string ToString() => $"[Hue: {Hue}; Saturation: {Saturation}]"; } }
29.483871
58
0.643326
[ "BSD-3-Clause" ]
OllieDay/Lifx
Lifx/Color.cs
916
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System.Linq; using System.Text.Json; using BlazorGameTemplate.Server.Extensions; using BlazorGameTemplate.Server.Repository; using BlazorGameTemplate.Shared; namespace BlazorGameTemplate.Server.Controllers { [Route("api/[controller]")] [ApiController] public class GameController : ControllerBase { private readonly ILogger<GameController> _logger; private readonly IGameRepository _gameRepository; private readonly IGameCountRepository _gameCountRepository; public GameController(ILogger<GameController> logger, IGameRepository gameRepository, IGameCountRepository gameCountRepository) { _logger = logger; _gameRepository = gameRepository; _gameCountRepository = gameCountRepository; } [HttpPut("New")] public void New(JsonElement json) { _gameRepository.CreateGame(Game.NewGame(json.GetStringProperty("GameId"), json.GetStringProperty("Name")), json.GetBooleanProperty("PrivateGame")); _gameCountRepository.IncrementGameCount(); } [HttpPost("Start")] public void StartGame(JsonElement gameIdJson) => _gameRepository.ModifyGame(gameIdJson.GetString(), game => game.StartGame()); [HttpPost("Join")] public Player Join(JsonElement gameIdJson) { return _gameRepository.ModifyGame(gameIdJson.GetString(), game => { var player = new Player { Name = $"Player {game.Players.Count}" }; game.Players.Add(player); return player; }); } [HttpPost("UpdatePlayer")] public void UpdatePlayer(JsonElement json) { _gameRepository.ModifyGame(json.GetStringProperty("GameId"), game => game.Players.Single(p => p.Name == json.GetStringProperty("OldName")).Name = json.GetStringProperty("NewName")); } [HttpPost("Save")] public void Save(JsonElement json) => _gameRepository.Save(json.Deserialize<Game>()); [HttpGet("Get")] public string Get(string id) => _gameRepository.GetGame(id).Serialize(); [HttpGet("List")] public string List() => _gameRepository.ListGames().Serialize(); [HttpGet("Count")] public int Get() => _gameCountRepository.GetGameCount(); } }
37.292308
193
0.659653
[ "MIT" ]
JustinWilkinson/BlazorGameTemplate
Server/Controllers/GameController.cs
2,426
C#
//--------------------------------------------------------- // <auto-generated> // This code was generated by a tool. Changes to this // file may cause incorrect behavior and will be lost // if the code is regenerated. // // Generated on 2020 October 09 04:48:46 UTC // </auto-generated> //--------------------------------------------------------- using System.CodeDom.Compiler; using System.Runtime.CompilerServices; #nullable enable namespace go { public static partial class runtime_package { [GeneratedCode("go2cs", "0.1.0.0")] private partial struct tmpBuf { // Value of the tmpBuf struct private readonly array<byte> m_value; public tmpBuf(array<byte> value) => m_value = value; // Enable implicit conversions between array<byte> and tmpBuf struct [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator tmpBuf(array<byte> value) => new tmpBuf(value); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator array<byte>(tmpBuf value) => value.m_value; // Enable comparisons between nil and tmpBuf struct [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(tmpBuf value, NilType nil) => value.Equals(default(tmpBuf)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(tmpBuf value, NilType nil) => !(value == nil); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(NilType nil, tmpBuf value) => value == nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(NilType nil, tmpBuf value) => value != nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator tmpBuf(NilType nil) => default(tmpBuf); } } }
39.211538
103
0.611084
[ "MIT" ]
GridProtectionAlliance/go2cs
src/go-src-converted/runtime/string_tmpBufStructOf(array(byte)).cs
2,039
C#
using MYDIPLOMA.Interface; using MYDIPLOMA.Services; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Xml.Linq; namespace MYDIPLOMA.DataInterpretor { public class TableRelationShips : SelectorInterface, ICloneable { public string RelationShip { get; set; } public string Parent_Table { get; set; } public string ParentKey { get; set; } public string Child_Table { get; set; } public string ChildKey { get; set; } public List<TableRelationShips> NextRelationShips = new List<TableRelationShips>(); public MainKey MAIN_KEY = new MainKey(); public List<Tuple<string, string>> ParentFields { get; set; } public Dictionary<Tuple<string, string>, string> ParentValues { get; set; } public Dictionary<Tuple<string, string>, List<string>> ChildValues { get; set; } public List<Tuple<string, string>> ChildFields { get; set; } //tempListForLoadig private Queue<TableRelationShips> tempRelationShips = new Queue<TableRelationShips>(); public void LoadColums() { ParentFields = DataService.getTableColumns(Parent_Table); ChildFields = DataService.getTableColumns(Child_Table); if (NextRelationShips != null) { foreach (var item in NextRelationShips) { var newl = DataService.getTableColumns(item.Parent_Table); foreach (var s in newl) { ChildFields.Add(s); } } } } public void LoadData() { try { var select = "select "; for (int i = 0; i < ParentFields.Count; i++) { if ((ParentFields.Count - 1) == i) { select += " " + ParentFields[i].Item2; } else { select += " " + ParentFields[i].Item2 + ","; } } select += " from [" + Parent_Table + "] where " + MAIN_KEY.Key + "='" + MAIN_KEY.Value + "'"; var list = DataService.getParentValue(select, ParentFields.Count); ParentValues = new Dictionary<Tuple<string, string>, string>(); for (int i = 0; i < ParentFields.Count; i++) { ParentValues.Add(new Tuple<string, string>(Parent_Table, ParentFields[i].Item2), list[i]); } LoadData2(); } catch (Exception ex) { MessageBox.Show("Nje gabim ka ndodhur ne krijimin e te dhenave" + ex.Message.ToString()); } } public void LoadData2() { var select = "select "; for (int i = 0; i < ChildFields.Count; i++) { if ((ChildFields.Count - 1) == i) { select += "[" + ChildFields[i].Item1 + "].[" + ChildFields[i].Item2+"]"; } else { select += "[" + ChildFields[i].Item1 + "].[" + ChildFields[i].Item2 + "],"; } } select += " from [" + Child_Table + "] " + getJoinPart() + " where [" + Child_Table + "]." + ChildKey + "='" + MAIN_KEY.Value + "'"; var list = DataService.getChildValue(select, ChildFields.Count); ChildValues = new Dictionary<Tuple<string, string>, List<string>>(); for (int i = 0; i < ChildFields.Count; i++) { ChildValues.Add(new Tuple<string, string>(ChildFields[i].Item1, ChildFields[i].Item2), list[i]); } } public object getFieldValue(Tuple<string, string> filed) { try { return ParentValues[Tuple.Create(filed.Item1, filed.Item2)]; } catch { return ""; } } public List<string> getFieldColumn(Tuple<string, string> filed) { try { return ChildValues[filed]; } catch(Exception e) { return new List<string>(); } } public void setValue(Tuple<string, string> t) { MAIN_KEY.Key = t.Item2; } public List<TableRelationShips> LoadNextParentForChildren() { var l = SchemaCreator.ALL_RELATIONSHIP.Where(x => x.Child_Table == Child_Table && x.Parent_Table != Parent_Table).ToList(); foreach (var item in l) { NextRelationShips.Add(item); tempRelationShips.Enqueue(item); } return l; } public List<TableRelationShips> LoadNextParentFromParent() { int oldlength = tempRelationShips.Count; var returnlist = new List<TableRelationShips>(); for (int i = 0; i < oldlength; i++) { var RemovedElement = tempRelationShips.Dequeue(); var l = SchemaCreator.ALL_RELATIONSHIP.Where(x => x.Child_Table == RemovedElement.Parent_Table && x.Parent_Table != Parent_Table).ToList(); foreach (var item in l) { NextRelationShips.Add(item); returnlist.Add(item); } } return returnlist; } public string getJoinPart() { string line = ""; if (NextRelationShips != null) { foreach (var item in NextRelationShips) { line += " join [" + item.Parent_Table + "] on [" + item.Parent_Table + "]." + item.ParentKey + "= [" + item.Child_Table + "]." + item.ChildKey + ""; } return line; } else { return ""; } } public object Clone() { return this.MemberwiseClone(); } public Tuple<string, string> getValue() { return Tuple.Create(Parent_Table, MAIN_KEY.Key); } public void reset() { NextRelationShips.Clear(); tempRelationShips.Clear(); } public XElement getXml() { var ele = new XElement("SCHEMA", new XAttribute("PT", Parent_Table), new XAttribute("PK", ParentKey), new XAttribute("CT", Child_Table), new XAttribute("CK", ChildKey), new XAttribute("FILTER", MAIN_KEY.Key),new XAttribute("INSTANCE", ((App)App.Current).Server),new XAttribute("DATABASE", ((App)App.Current).DatabaseName)); var nextel = new XElement("NEXT"); foreach (var item in NextRelationShips) { nextel.Add(new XElement("ITEM", new XAttribute("PT", item.Parent_Table), new XAttribute("PK", item.ParentKey), new XAttribute("CT", item.Child_Table), new XAttribute("CK", item.ChildKey))); } ele.Add(nextel); return ele; } } }
29.391304
335
0.494486
[ "MIT" ]
ademvelika/AReport
MYDIPLOMA/MYDIPLOMA/DataInterpretor/TableRelationShips.cs
7,438
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using UnityEngine.InputSystem; public class Controls : MonoBehaviour { [HideInInspector] public UnityEvent keyboard_w; [HideInInspector] public UnityEvent keyboard_w_up; [HideInInspector] public UnityEvent keyboard_w_down; [HideInInspector] public UnityEvent keyboard_a; [HideInInspector] public UnityEvent keyboard_a_up; [HideInInspector] public UnityEvent keyboard_a_down; [HideInInspector] public UnityEvent keyboard_s; [HideInInspector] public UnityEvent keyboard_s_up; [HideInInspector] public UnityEvent keyboard_s_down; [HideInInspector] public UnityEvent keyboard_d; [HideInInspector] public UnityEvent keyboard_d_up; [HideInInspector] public UnityEvent keyboard_d_down; [HideInInspector] public UnityEvent keyboard_o; [HideInInspector] public UnityEvent keyboard_o_up; [HideInInspector] public UnityEvent keyboard_o_down; //A [HideInInspector] public UnityEvent keyboard_k; [HideInInspector] public UnityEvent keyboard_k_up; [HideInInspector] public UnityEvent keyboard_k_down; //B [HideInInspector] public UnityEvent keyboard_return_down; //START [HideInInspector] public UnityEvent keyboard_e_down; //R [HideInInspector] public UnityEvent keyboard_q_down; //L //gamepad PlayerControls controls; bool up; bool down; bool left; bool right; void Awake() { controls = new PlayerControls(); controls.Gameplay.Interact.performed += ctx => SendODown(); //ctx serveix per dir-li a unity que sé que hi ha un context a l'acció però jo simplement vull cridar aquest mètode independentment d'aquest controls.Gameplay.Cancel.performed += ctx => SendKDown(); controls.Gameplay.Start.performed += ctx => SendReturnDown(); controls.Gameplay.L.performed += ctx => SendShoulderLDown(); controls.Gameplay.R.performed += ctx => SendShoulderRDown(); //W controls.Gameplay.MoveUp.started += ctx => SendWDown(); controls.Gameplay.MoveUp.performed += ctx => SendW(true); controls.Gameplay.MoveUp.canceled += ctx => SendW(false); //S controls.Gameplay.MoveDown.started += ctx => SendSDown(); controls.Gameplay.MoveDown.performed += ctx => SendS(true); controls.Gameplay.MoveDown.canceled += ctx => SendS(false); //A controls.Gameplay.MoveLeft.started += ctx => SendADown(); controls.Gameplay.MoveLeft.performed += ctx => SendA(true); controls.Gameplay.MoveLeft.canceled += ctx => SendA(false); //D controls.Gameplay.MoveRight.started += ctx => SendDDown(); controls.Gameplay.MoveRight.performed += ctx => SendD(true); controls.Gameplay.MoveRight.canceled += ctx => SendD(false); DontDestroyOnLoad(gameObject); } // Start is called before the first frame update void Start() { keyboard_w = new UnityEvent(); keyboard_w_up = new UnityEvent(); keyboard_w_down = new UnityEvent(); keyboard_a = new UnityEvent(); keyboard_a_up = new UnityEvent(); keyboard_a_down = new UnityEvent(); keyboard_s = new UnityEvent(); keyboard_s_up = new UnityEvent(); keyboard_s_down = new UnityEvent(); keyboard_d = new UnityEvent(); keyboard_d_up = new UnityEvent(); keyboard_d_down = new UnityEvent(); keyboard_o = new UnityEvent(); keyboard_o_up = new UnityEvent(); keyboard_o_down = new UnityEvent(); keyboard_k = new UnityEvent(); keyboard_k_up = new UnityEvent(); keyboard_k_down = new UnityEvent(); keyboard_return_down = new UnityEvent(); keyboard_e_down = new UnityEvent(); keyboard_q_down = new UnityEvent(); } // Update is called once per frame void Update() { InvokeW(); InvokeA(); InvokeS(); InvokeD(); InvokeO(); InvokeK(); InvokeReturn(); InvokeShoulderL(); InvokeShoulderR(); if (up) keyboard_w.Invoke(); if (down) keyboard_s.Invoke(); if (left) keyboard_a.Invoke(); if (right) keyboard_d.Invoke(); } void OnEnable() { controls.Gameplay.Enable(); } void OnDisable() { controls.Gameplay.Disable(); } void InvokeW() { if (Input.GetKey("w")) keyboard_w.Invoke(); if (Input.GetKeyUp("w")) keyboard_w_up.Invoke(); if (Input.GetKeyDown("w")) keyboard_w_down.Invoke(); } void SendWDown() { keyboard_w_down.Invoke(); } void SendW(bool send) { up = send; } void InvokeA() { if (Input.GetKey("a")) keyboard_a.Invoke(); if (Input.GetKeyUp("a")) keyboard_a_up.Invoke(); if (Input.GetKeyDown("a")) keyboard_a_down.Invoke(); } void SendADown() { keyboard_a_down.Invoke(); } void SendA(bool send) { left = send; } void InvokeS() { if (Input.GetKey("s")) keyboard_s.Invoke(); if (Input.GetKeyUp("s")) keyboard_s_up.Invoke(); if (Input.GetKeyDown("s")) keyboard_s_down.Invoke(); } void SendSDown() { keyboard_s_down.Invoke(); } void SendS(bool send) { down = send; } void InvokeD() { if (Input.GetKey("d")) keyboard_d.Invoke(); if (Input.GetKeyUp("d")) keyboard_d_up.Invoke(); if (Input.GetKeyDown("d")) keyboard_d_down.Invoke(); } void SendDDown() { keyboard_d_down.Invoke(); } void SendD(bool send) { right = send; } void InvokeO() { if (Input.GetKey("o")) keyboard_o.Invoke(); if (Input.GetKeyUp("o")) keyboard_o_up.Invoke(); if (Input.GetKeyDown("o")) keyboard_o_down.Invoke(); } void SendODown() { keyboard_o_down.Invoke(); } void InvokeK() { if (Input.GetKey("k")) keyboard_k.Invoke(); if (Input.GetKeyUp("k")) keyboard_k_up.Invoke(); if (Input.GetKeyDown("k")) keyboard_k_down.Invoke(); } void SendKDown() { keyboard_k_down.Invoke(); } void InvokeReturn() { if (Input.GetKeyDown("return")) keyboard_return_down.Invoke(); } void SendReturnDown() { keyboard_return_down.Invoke(); } void InvokeShoulderL() { if (Input.GetKeyDown("q")) keyboard_q_down.Invoke(); } void SendShoulderLDown() { keyboard_q_down.Invoke(); } void InvokeShoulderR() { if (Input.GetKeyDown("e")) keyboard_e_down.Invoke(); } void SendShoulderRDown() { keyboard_e_down.Invoke(); } }
24.511864
208
0.588577
[ "Unlicense" ]
albertllopart/Warpolis-TFG-Unity
Assets/Scripts/Gameplay/Controls.cs
7,237
C#
using System.Data.Common; using Microsoft.EntityFrameworkCore; namespace TakTikan.Tailor.EntityFrameworkCore { public static class TailorDbContextConfigurer { public static void Configure(DbContextOptionsBuilder<TailorDbContext> builder, string connectionString) { builder.UseSqlServer(connectionString); } public static void Configure(DbContextOptionsBuilder<TailorDbContext> builder, DbConnection connection) { builder.UseSqlServer(connection); } } }
29.944444
111
0.716141
[ "MIT" ]
vahidsaberi/TakTikan-Tailor
aspnet-core/src/TakTikan.Tailor.EntityFrameworkCore/EntityFrameworkCore/TailorDbContextConfigurer.cs
541
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschränkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; using IdentityServer4; using IdentityServer4.Models; using IdentityServer4.Stores; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Options; using Squidex.Config; using Squidex.Domain.Apps.Core.Apps; using Squidex.Domain.Apps.Entities; using Squidex.Domain.Users; using Squidex.Infrastructure; using Squidex.Infrastructure.Security; using Squidex.Shared; using Squidex.Shared.Identity; using Squidex.Shared.Users; using Squidex.Web; namespace Squidex.Areas.IdentityServer.Config { public class LazyClientStore : IClientStore { private readonly UserManager<IdentityUser> userManager; private readonly IAppProvider appProvider; private readonly Dictionary<string, Client> staticClients = new Dictionary<string, Client>(StringComparer.OrdinalIgnoreCase); public LazyClientStore( UserManager<IdentityUser> userManager, IOptions<UrlsOptions> urlsOptions, IOptions<MyIdentityOptions> identityOptions, IAppProvider appProvider) { Guard.NotNull(identityOptions, nameof(identityOptions)); Guard.NotNull(urlsOptions, nameof(urlsOptions)); Guard.NotNull(userManager, nameof(userManager)); Guard.NotNull(appProvider, nameof(appProvider)); this.userManager = userManager; this.appProvider = appProvider; CreateStaticClients(urlsOptions, identityOptions); } public async Task<Client> FindClientByIdAsync(string clientId) { var client = staticClients.GetOrDefault(clientId); if (client != null) { return client; } var (appName, appClientId) = clientId.GetClientParts(); if (!string.IsNullOrWhiteSpace(appName)) { var app = await appProvider.GetAppAsync(appName); var appClient = app?.Clients.GetOrDefault(appClientId); if (appClient != null) { return CreateClientFromApp(clientId, appClient); } } var user = await userManager.FindByIdWithClaimsAsync(clientId); if (!string.IsNullOrWhiteSpace(user?.ClientSecret())) { return CreateClientFromUser(user); } return null; } private Client CreateClientFromUser(UserWithClaims user) { return new Client { ClientId = user.Id, ClientName = $"{user.Email} Client", ClientClaimsPrefix = null, ClientSecrets = new List<Secret> { new Secret(user.ClientSecret().Sha256()) }, AccessTokenLifetime = (int)TimeSpan.FromDays(30).TotalSeconds, AllowedGrantTypes = GrantTypes.ClientCredentials, AllowedScopes = new List<string> { Constants.ApiScope, Constants.RoleScope, Constants.PermissionsScope }, Claims = new List<Claim> { new Claim(OpenIdClaims.Subject, user.Id) } }; } private static Client CreateClientFromApp(string id, AppClient appClient) { return new Client { ClientId = id, ClientName = id, ClientSecrets = new List<Secret> { new Secret(appClient.Secret.Sha256()) }, AccessTokenLifetime = (int)TimeSpan.FromDays(30).TotalSeconds, AllowedGrantTypes = GrantTypes.ClientCredentials, AllowedScopes = new List<string> { Constants.ApiScope, Constants.RoleScope, Constants.PermissionsScope } }; } private void CreateStaticClients(IOptions<UrlsOptions> urlsOptions, IOptions<MyIdentityOptions> identityOptions) { foreach (var client in CreateStaticClients(urlsOptions.Value, identityOptions.Value)) { staticClients[client.ClientId] = client; } } private static IEnumerable<Client> CreateStaticClients(UrlsOptions urlsOptions, MyIdentityOptions identityOptions) { var frontendId = Constants.FrontendClient; yield return new Client { ClientId = frontendId, ClientName = frontendId, RedirectUris = new List<string> { urlsOptions.BuildUrl("login;"), urlsOptions.BuildUrl("client-callback-silent", false), urlsOptions.BuildUrl("client-callback-popup", false) }, PostLogoutRedirectUris = new List<string> { urlsOptions.BuildUrl("logout", false) }, AllowAccessTokensViaBrowser = true, AllowedGrantTypes = GrantTypes.Implicit, AllowedScopes = new List<string> { IdentityServerConstants.StandardScopes.OpenId, IdentityServerConstants.StandardScopes.Profile, IdentityServerConstants.StandardScopes.Email, Constants.ApiScope, Constants.PermissionsScope, Constants.ProfileScope, Constants.RoleScope }, RequireConsent = false }; var internalClient = Constants.InternalClientId; yield return new Client { ClientId = internalClient, ClientName = internalClient, ClientSecrets = new List<Secret> { new Secret(Constants.InternalClientSecret) }, RedirectUris = new List<string> { urlsOptions.BuildUrl($"{Constants.PortalPrefix}/signin-internal", false), urlsOptions.BuildUrl($"{Constants.OrleansPrefix}/signin-internal", false) }, AccessTokenLifetime = (int)TimeSpan.FromDays(30).TotalSeconds, AllowedGrantTypes = GrantTypes.ImplicitAndClientCredentials, AllowedScopes = new List<string> { IdentityServerConstants.StandardScopes.OpenId, IdentityServerConstants.StandardScopes.Profile, IdentityServerConstants.StandardScopes.Email, Constants.ApiScope, Constants.PermissionsScope, Constants.ProfileScope, Constants.RoleScope }, RequireConsent = false }; if (identityOptions.IsAdminClientConfigured()) { var id = identityOptions.AdminClientId; yield return new Client { ClientId = id, ClientName = id, ClientSecrets = new List<Secret> { new Secret(identityOptions.AdminClientSecret.Sha256()) }, AccessTokenLifetime = (int)TimeSpan.FromDays(30).TotalSeconds, AllowedGrantTypes = GrantTypes.ClientCredentials, AllowedScopes = new List<string> { Constants.ApiScope, Constants.RoleScope, Constants.PermissionsScope }, Claims = new List<Claim> { new Claim(SquidexClaimTypes.Permissions, Permissions.All) } }; } } } }
36.716738
133
0.52858
[ "MIT" ]
alexisbssn/squidex
src/Squidex/Areas/IdentityServer/Config/LazyClientStore.cs
8,558
C#
using System; using TencentSDK.Exmail.Apis; using TencentSDK.Exmail.Common; namespace TencentSDK.Exmail { /// <summary> /// 腾讯企业邮箱API客户端类 /// </summary> public class TencentExmailApiClient : ApiClientBase { /// <summary> /// 成员管理接口 /// </summary> public UserApi User { get; private set; } /// <summary> /// 部门管理接口 /// </summary> public DepartmentApi Department { get; private set; } /// <summary> /// 初始化腾讯企业邮箱API客户端 /// </summary> /// <param name="corpId">企业ID</param> /// <param name="corpSecret">应用的凭证密钥</param> public TencentExmailApiClient(string corpId, string corpSecret):base(corpId, corpSecret) { Initialize(); } /// <summary> /// 初始化API Client属性 /// </summary> private void Initialize() { if (string.IsNullOrEmpty(BaseUrl)) { throw new ArgumentNullException("BaseUrl"); } if (string.IsNullOrEmpty(CorpId)) { throw new ArgumentNullException("CorpId"); } if (string.IsNullOrEmpty(CorpSecret)) { throw new ArgumentNullException("CorpSecret"); } User = new UserApi(this); Department = new DepartmentApi(this); } } }
24.947368
96
0.517581
[ "Apache-2.0" ]
arbing/WeixinSDK
src/TencentSDK.Exmail/TencentExmailApiClient.cs
1,520
C#
using System; using ElectionGuard.Encryption.Tests.Utils; using NUnit.Framework; namespace ElectionGuard.Encrypt.Tests { [TestFixture] public class TestEncrypt { readonly string manifest_json = "{\"ballot_styles\":[{\"geopolitical_unit_ids\":[\"some-geopoltical-unit-id\"],\"object_id\":\"some-ballot-style-id\"}],\"candidates\":[{\"object_id\":\"some-candidate-id-1\"},{\"object_id\":\"some-candidate-id-2\"},{\"object_id\":\"some-candidate-id-3\"}],\"contests\":[{\"ballot_selections\":[{\"candidate_id\":\"some-candidate-id-1\",\"object_id\":\"some-object-id-affirmative\",\"sequence_order\":0},{\"candidate_id\":\"some-candidate-id-2\",\"object_id\":\"some-object-id-negative\",\"sequence_order\":1}],\"electoral_district_id\":\"some-geopoltical-unit-id\",\"name\":\"some-referendum-contest-name\",\"number_elected\":1,\"object_id\":\"some-referendum-contest-object-id\",\"sequence_order\":0,\"vote_variation\":\"one_of_m\"},{\"ballot_selections\":[{\"candidate_id\":\"some-candidate-id-1\",\"object_id\":\"some-object-id-candidate-1\",\"sequence_order\":0},{\"candidate_id\":\"some-candidate-id-2\",\"object_id\":\"some-object-id-candidate-2\",\"sequence_order\":1},{\"candidate_id\":\"some-candidate-id-3\",\"object_id\":\"some-object-id-candidate-3\",\"sequence_order\":2}],\"electoral_district_id\":\"some-geopoltical-unit-id\",\"name\":\"some-candidate-contest-name\",\"number_elected\":2,\"object_id\":\"some-candidate-contest-object-id\",\"sequence_order\":1,\"vote_variation\":\"one_of_m\"}],\"election_scope_id\":\"some-scope-id\",\"end_date\":\"2021-02-04T13:30:10Z\",\"geopolitical_units\":[{\"name\":\"some-gp-unit-name\",\"object_id\":\"some-geopoltical-unit-id\",\"type\":\"unknown\"}],\"parties\":[{\"object_id\":\"some-party-id-1\"},{\"object_id\":\"some-party-id-2\"}],\"start_date\":\"2021-02-04T13:30:10Z\",\"type\":\"unknown\"}"; readonly string plaintext_json = "{\"object_id\":\"some-external-id-string-123\",\"style_id\":\"some-ballot-style-id\",\"contests\":[{\"object_id\":\"some-referendum-contest-object-id\",\"ballot_selections\":[{\"object_id\":\"some-candidate-id-1\",\"vote\":1}]}]}"; [Test] public void Test_Encrypt_Ballot_Simple_Succeeds() { // Configure the election context var keypair = ElGamalKeyPair.FromSecret(Constants.TWO_MOD_Q); var manifest = new Manifest(manifest_json); var internalManifest = new InternalManifest(manifest); var context = new CiphertextElectionContext( 1UL, 1UL, keypair.PublicKey, Constants.TWO_MOD_Q, internalManifest.ManifestHash); var device = new EncryptionDevice(12345UL, 23456UL, 34567UL, "Location"); var mediator = new EncryptionMediator(internalManifest, context, device); var ballot = new PlaintextBallot(plaintext_json); // Act var ciphertext = mediator.Encrypt(ballot); // Assert // a property Assert.That(ciphertext.ObjectId == ballot.ObjectId); // json serialization var json = ciphertext.ToJson(); var fromJson = new CiphertextBallot(json); Assert.That(ciphertext.ObjectId == fromJson.ObjectId); // TODO: // binary serialization // var bson = ciphertext.Bson; // var fromBson = CiphertextBallot.FromBson(bson); // Assert.That(ciphertext.ObjectId == fromBson.ObjectId); // TODO: submitted ballot // var submitted = SubmittedBallot.From(ciphertext, BallotBoxState.cast); // Assert.That(ciphertext.ObjectId == submitted.ObjectId); } [Test] public void Test_Compact_Encrypt_Ballot_Simple_Succeeds() { // Arrange var keypair = ElGamalKeyPair.FromSecret(Constants.TWO_MOD_Q); var manifest = new Manifest(manifest_json); // TODO: load from file //var manifest = ManifestGenerator.GetJeffersonCountyManifest(); var internalManifest = new InternalManifest(manifest); var context = new CiphertextElectionContext( 1UL, 1UL, keypair.PublicKey, Constants.TWO_MOD_Q, internalManifest.ManifestHash); var device = new EncryptionDevice(12345UL, 23456UL, 34567UL, "Location"); var mediator = new EncryptionMediator(internalManifest, context, device); var ballot = new PlaintextBallot(plaintext_json); // Act var compact = mediator.CompactEncrypt(ballot); // Assert Assert.That(compact.ObjectId == ballot.ObjectId); // Act var msgpack = compact.ToMsgPack(); var fromMsgpack = new CompactCiphertextBallot(msgpack); // Assert Assert.That(compact.ObjectId == fromMsgpack.ObjectId); } } }
58.595238
1,699
0.636327
[ "MIT" ]
Jayita10/electionguard-cpp
bindings/netstandard/ElectionGuard/ElectionGuard.Encryption.Tests/TestEncrypt.cs
4,924
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using SemVer; using NanoFabric.Core; namespace NanoFabric.AspNetCore.Tests { public class InMemoryRegistryHost : Core.IRegistryHost { private readonly List<Core.RegistryInformation> _serviceInstances = new List<RegistryInformation>(); public IList<RegistryInformation> ServiceInstances { get { return _serviceInstances; } set { foreach (var registryInformation in value) { string url = registryInformation.Address; if (registryInformation.Port >= 0) { url += $":{registryInformation.Port}"; } RegisterServiceAsync(registryInformation.Name, registryInformation.Version, new Uri(url), tags: registryInformation.Tags); } } } private Task<IDictionary<string, string[]>> GetServicesCatalogAsync() { IDictionary<string, string[]> results = ServiceInstances .GroupBy(x => x.Name, x => x.Tags) .ToDictionary(g => g.Key, g => g.SelectMany(x => x ?? Enumerable.Empty<string>()).ToArray()); return Task.FromResult(results); } public Task<IList<RegistryInformation>> FindServiceInstancesAsync() { return Task.FromResult(ServiceInstances); } public async Task<IList<RegistryInformation>> FindServiceInstancesAsync(string name) { var instances = await FindServiceInstancesAsync(); return instances.Where(x => x.Name == name).ToList(); } public async Task<IList<RegistryInformation>> FindServiceInstancesWithVersionAsync(string name, string version) { var instances = await FindServiceInstancesAsync(name); var range = new Range(version); return instances.Where(x => range.IsSatisfied(x.Version)).ToList(); } public async Task<IList<RegistryInformation>> FindServiceInstancesAsync(Predicate<KeyValuePair<string, string[]>> nameTagsPredicate, Predicate<RegistryInformation> registryInformationPredicate) { return (await GetServicesCatalogAsync()) .Where(kvp => nameTagsPredicate(kvp)) .Select(kvp => kvp.Key) .Select(FindServiceInstancesAsync) .SelectMany(task => task.Result) .Where(x => registryInformationPredicate(x)) .ToList(); } public async Task<IList<RegistryInformation>> FindServiceInstancesAsync(Predicate<KeyValuePair<string, string[]>> predicate) { return await FindServiceInstancesAsync(nameTagsPredicate: predicate, registryInformationPredicate: x => true); } public async Task<IList<RegistryInformation>> FindServiceInstancesAsync(Predicate<RegistryInformation> predicate) { return await FindServiceInstancesAsync(nameTagsPredicate: x => true, registryInformationPredicate: predicate); } public Task<IList<RegistryInformation>> FindAllServicesAsync() { return Task.FromResult(ServiceInstances); } public Task<RegistryInformation> RegisterServiceAsync(string serviceName, string version, Uri uri, Uri healthCheckUri = null, IEnumerable<string> tags = null) { var registryInformation = new RegistryInformation { Name = serviceName, Id = Guid.NewGuid().ToString(), Address = uri.Host, Port = uri.Port, Version = version, Tags = tags ?? Enumerable.Empty<string>() }; ServiceInstances.Add(registryInformation); return Task.FromResult(registryInformation); } public async Task<bool> DeregisterServiceAsync(string serviceId) { var instance = (await FindServiceInstancesAsync()).FirstOrDefault(x => x.Id == serviceId); if (instance != null) { ServiceInstances.Remove(instance); return true; } return false; } public Task<string> RegisterHealthCheckAsync(string serviceName, string serviceId, Uri checkUri, TimeSpan? interval = null, string notes = null) { return null; } public Task<bool> DeregisterHealthCheckAsync(string checkId) { return Task.FromResult(false); } } }
37.75
201
0.605426
[ "MIT" ]
AndrewChien/NanoFabric
test/NanoFabric.AspNetCore.Tests/InMemoryRegistryHost.cs
4,683
C#
using FluentMigrator.Runner.Generators.DB2; using NUnit.Framework; using NUnit.Should; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FluentMigrator.Tests.Unit.Generators.Db2 { [TestFixture] public class Db2DataTests : BaseDataTests { protected Db2Generator Generator; [SetUp] public void Setup() { Generator = new Db2Generator(); } [Test] public override void CanDeleteDataForAllRowsWithCustomSchema() { var expression = GeneratorTestHelper.GetDeleteDataAllRowsExpression(); expression.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("DELETE FROM TestSchema.TestTable1"); } [Test] public override void CanDeleteDataForAllRowsWithDefaultSchema() { var expression = GeneratorTestHelper.GetDeleteDataAllRowsExpression(); var result = Generator.Generate(expression); result.ShouldBe("DELETE FROM TestTable1"); } [Test] public override void CanDeleteDataForMultipleRowsWithCustomSchema() { var expression = GeneratorTestHelper.GetDeleteDataMultipleRowsExpression(); expression.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("DELETE FROM TestSchema.TestTable1 WHERE Name = 'Just''in' AND Website IS NULL DELETE FROM TestSchema.TestTable1 WHERE Website = 'github.com'"); } [Test] public override void CanDeleteDataForMultipleRowsWithDefaultSchema() { var expression = GeneratorTestHelper.GetDeleteDataMultipleRowsExpression(); var result = Generator.Generate(expression); result.ShouldBe("DELETE FROM TestTable1 WHERE Name = 'Just''in' AND Website IS NULL DELETE FROM TestTable1 WHERE Website = 'github.com'"); } [Test] public override void CanDeleteDataWithCustomSchema() { var expression = GeneratorTestHelper.GetDeleteDataExpression(); expression.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("DELETE FROM TestSchema.TestTable1 WHERE Name = 'Just''in' AND Website IS NULL"); } [Test] public override void CanDeleteDataWithDefaultSchema() { var expression = GeneratorTestHelper.GetDeleteDataExpression(); var result = Generator.Generate(expression); result.ShouldBe("DELETE FROM TestTable1 WHERE Name = 'Just''in' AND Website IS NULL"); } [Test] public override void CanInsertDataWithCustomSchema() { var expression = GeneratorTestHelper.GetInsertDataExpression(); expression.SchemaName = "TestSchema"; var expected = "INSERT INTO TestSchema.TestTable1 (Id, Name, Website) VALUES (1, 'Just''in', 'codethinked.com')"; expected += " INSERT INTO TestSchema.TestTable1 (Id, Name, Website) VALUES (2, 'Na\\te', 'kohari.org')"; var result = Generator.Generate(expression); result.ShouldBe(expected); } [Test] public override void CanInsertDataWithDefaultSchema() { var expression = GeneratorTestHelper.GetInsertDataExpression(); var expected = "INSERT INTO TestTable1 (Id, Name, Website) VALUES (1, 'Just''in', 'codethinked.com')"; expected += " INSERT INTO TestTable1 (Id, Name, Website) VALUES (2, 'Na\\te', 'kohari.org')"; var result = Generator.Generate(expression); result.ShouldBe(expected); } [Test] public override void CanInsertGuidDataWithCustomSchema() { var expression = GeneratorTestHelper.GetInsertGUIDExpression(); expression.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe(System.String.Format("INSERT INTO TestSchema.TestTable1 (guid) VALUES ('{0}')", GeneratorTestHelper.TestGuid)); } [Test] public override void CanInsertGuidDataWithDefaultSchema() { var expression = GeneratorTestHelper.GetInsertGUIDExpression(); var result = Generator.Generate(expression); result.ShouldBe(System.String.Format("INSERT INTO TestTable1 (guid) VALUES ('{0}')", GeneratorTestHelper.TestGuid)); } [Test] public override void CanUpdateDataForAllDataWithCustomSchema() { var expression = GeneratorTestHelper.GetUpdateDataExpressionWithAllRows(); expression.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("UPDATE TestSchema.TestTable1 SET Name = 'Just''in', Age = 25"); } [Test] public override void CanUpdateDataForAllDataWithDefaultSchema() { var expression = GeneratorTestHelper.GetUpdateDataExpressionWithAllRows(); var result = Generator.Generate(expression); result.ShouldBe("UPDATE TestTable1 SET Name = 'Just''in', Age = 25"); } [Test] public override void CanUpdateDataWithCustomSchema() { var expression = GeneratorTestHelper.GetUpdateDataExpression(); expression.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("UPDATE TestSchema.TestTable1 SET Name = 'Just''in', Age = 25 WHERE Id = 9 AND Homepage IS NULL"); } [Test] public override void CanUpdateDataWithDefaultSchema() { var expression = GeneratorTestHelper.GetUpdateDataExpression(); var result = Generator.Generate(expression); result.ShouldBe("UPDATE TestTable1 SET Name = 'Just''in', Age = 25 WHERE Id = 9 AND Homepage IS NULL"); } } }
37.475309
172
0.639433
[ "Apache-2.0" ]
BartDM/fluentmigrator
src/FluentMigrator.Tests/Unit/Generators/Db2/Db2DataTests.cs
6,073
C#
using System; namespace ObviousCode.Alchemy.Creatures.DecisionProcessing { public class AdditionOperator : OperatorValue { public override decimal GetValue () { return Stack.Pop ().GetValue () + Stack.Pop ().GetValue (); } public override OperatorValue CreateNew () { return new AdditionOperator (); } public override string Describe () { return string.Format (" ( {0} + {1} ) " , Stack [1].Describe () , Stack [0].Describe ()); } } }
18.692308
62
0.635802
[ "MIT" ]
lagerdalek/alchemy
ObviousCode.Alchemy.Creatures/ObviousCode.Alchemy.Creatures.DecisionProcessing/Operators/AdditionOperator.cs
488
C#