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
sequence
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System.Collections.Generic; using System.Linq; using PatternPal.Recognizers.Abstractions; using SyntaxTree.Abstractions.Entities; namespace PatternPal.Recognizers.Models.Output { public class Result : IResult { public Dictionary<IEntity, string> RelatedSubTypes = new Dictionary<IEntity, string>(); public List<ICheckResult> Results { get; set; } = new List<ICheckResult>(); public int GetScore() { var total = Results.Sum(x => x.GetTotalChecks()); var green = Results.Sum(x => x.GetScore()); return total <= 0 ? 0 : (int)(green / total * 100f); } public IList<ICheckResult> GetResults() { return Results; } public IDictionary<IEntity, string> GetRelatedSubTypes() { return RelatedSubTypes; } } }
28
95
0.611751
[ "MIT" ]
PatternPal/PatternPal
PatternPal/PatternPal.Regonizers/Models/Output/Result.cs
870
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Cmdlets { using static Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Extensions; /// <summary>Creates a new firewall rule or updates an existing firewall rule.</summary> /// <remarks> /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{serverName}/firewallRules/{firewallRuleName}" /// </remarks> [global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.InternalExport] [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzPostgreSqlFlexibleServerFirewallRule_CreateViaIdentityExpanded", SupportsShouldProcess = true)] [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.IFirewallRuleAutoGenerated))] [global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Description(@"Creates a new firewall rule or updates an existing firewall rule.")] [global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Generated] public partial class NewAzPostgreSqlFlexibleServerFirewallRule_CreateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener { /// <summary>A unique id generatd for the this cmdlet when it is instantiated.</summary> private string __correlationId = System.Guid.NewGuid().ToString(); /// <summary>A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet)</summary> private global::System.Management.Automation.InvocationInfo __invocationInfo; /// <summary>A unique id generatd for the this cmdlet when ProcessRecord() is called.</summary> private string __processRecordId; /// <summary> /// The <see cref="global::System.Threading.CancellationTokenSource" /> for this operation. /// </summary> private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); /// <summary>when specified, runs this cmdlet as a PowerShell job</summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] [global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter AsJob { get; set; } /// <summary>Wait for .NET debugger to attach</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] [global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter Break { get; set; } /// <summary>The reference to the client API class.</summary> public Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.PostgreSql Client => Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Module.Instance.ClientAPI; /// <summary> /// The credentials, account, tenant, and subscription used for communication with Azure /// </summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] [global::System.Management.Automation.ValidateNotNull] [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] [global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.ParameterCategory.Azure)] public global::System.Management.Automation.PSObject DefaultProfile { get; set; } /// <summary>The end IP address of the server firewall rule. Must be IPv4 format.</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The end IP address of the server firewall rule. Must be IPv4 format.")] [global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.ParameterCategory.Body)] [Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Info( Required = true, ReadOnly = false, Description = @"The end IP address of the server firewall rule. Must be IPv4 format.", SerializedName = @"endIpAddress", PossibleTypes = new [] { typeof(string) })] public string EndIPAddress { get => ParametersBody.EndIPAddress ?? null; set => ParametersBody.EndIPAddress = value; } /// <summary>SendAsync Pipeline Steps to be appended to the front of the pipeline</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.ParameterCategory.Runtime)] public Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } /// <summary>SendAsync Pipeline Steps to be prepended to the front of the pipeline</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.ParameterCategory.Runtime)] public Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } /// <summary>Backing field for <see cref="InputObject" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.IPostgreSqlIdentity _inputObject; /// <summary>Identity Parameter</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] [global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.ParameterCategory.Path)] public Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.IPostgreSqlIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } /// <summary>Accessor for our copy of the InvocationInfo.</summary> public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } /// <summary> /// <see cref="IEventListener" /> cancellation delegate. Stops the cmdlet when called. /// </summary> global::System.Action Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; /// <summary><see cref="IEventListener" /> cancellation token.</summary> global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener.Token => _cancellationTokenSource.Token; /// <summary> /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue /// asynchronously. /// </summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] [global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter NoWait { get; set; } /// <summary>Backing field for <see cref="ParametersBody" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.IFirewallRuleAutoGenerated _parametersBody= new Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.FirewallRuleAutoGenerated(); /// <summary>Represents a server firewall rule.</summary> private Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.IFirewallRuleAutoGenerated ParametersBody { get => this._parametersBody; set => this._parametersBody = value; } /// <summary> /// The instance of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.HttpPipeline" /> that the remote call will use. /// </summary> private Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.HttpPipeline Pipeline { get; set; } /// <summary>The URI for the proxy server to use</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] [global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.ParameterCategory.Runtime)] public global::System.Uri Proxy { get; set; } /// <summary>Credentials for a proxy server to use for the remote call</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.ParameterCategory.Runtime)] public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } /// <summary>Use the default credentials for the proxy</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] [global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } /// <summary>The start IP address of the server firewall rule. Must be IPv4 format.</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The start IP address of the server firewall rule. Must be IPv4 format.")] [global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.ParameterCategory.Body)] [Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Info( Required = true, ReadOnly = false, Description = @"The start IP address of the server firewall rule. Must be IPv4 format.", SerializedName = @"startIpAddress", PossibleTypes = new [] { typeof(string) })] public string StartIPAddress { get => ParametersBody.StartIPAddress ?? null; set => ParametersBody.StartIPAddress = value; } /// <summary> /// <c>overrideOnDefault</c> will be called before the regular onDefault has been processed, allowing customization of what /// happens on that response. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201.ICloudError" /// /> from the remote call</param> /// <param name="returnNow">/// Determines if the rest of the onDefault method should be processed, or if the method should /// return immediately (set to true to skip further processing )</param> partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201.ICloudError> response, ref global::System.Threading.Tasks.Task<bool> returnNow); /// <summary> /// <c>overrideOnOk</c> will be called before the regular onOk has been processed, allowing customization of what happens /// on that response. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.IFirewallRuleAutoGenerated" /// /> from the remote call</param> /// <param name="returnNow">/// Determines if the rest of the onOk method should be processed, or if the method should return /// immediately (set to true to skip further processing )</param> partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.IFirewallRuleAutoGenerated> response, ref global::System.Threading.Tasks.Task<bool> returnNow); /// <summary> /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) /// </summary> protected override void BeginProcessing() { Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); if (Break) { Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.AttachDebugger.Break(); } ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } /// <summary>Creates a duplicate instance of this cmdlet (via JSON serialization).</summary> /// <returns> /// a duplicate instance of NewAzPostgreSqlFlexibleServerFirewallRule_CreateViaIdentityExpanded /// </returns> public Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Cmdlets.NewAzPostgreSqlFlexibleServerFirewallRule_CreateViaIdentityExpanded Clone() { var clone = new NewAzPostgreSqlFlexibleServerFirewallRule_CreateViaIdentityExpanded(); clone.__correlationId = this.__correlationId; clone.__processRecordId = this.__processRecordId; clone.DefaultProfile = this.DefaultProfile; clone.InvocationInformation = this.InvocationInformation; clone.Proxy = this.Proxy; clone.Pipeline = this.Pipeline; clone.AsJob = this.AsJob; clone.Break = this.Break; clone.ProxyCredential = this.ProxyCredential; clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; clone.HttpPipelinePrepend = this.HttpPipelinePrepend; clone.HttpPipelineAppend = this.HttpPipelineAppend; clone.ParametersBody = this.ParametersBody; return clone; } /// <summary>Performs clean-up after the command execution</summary> protected override void EndProcessing() { ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } /// <summary>Handles/Dispatches events during the call to the REST service.</summary> /// <param name="id">The message id</param> /// <param name="token">The message cancellation token. When this call is cancelled, this should be <c>true</c></param> /// <param name="messageData">Detailed message data for the message event.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the message is completed. /// </returns> async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.EventData> messageData) { using( NoSynchronizationContext ) { if (token.IsCancellationRequested) { return ; } switch ( id ) { case Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.Verbose: { WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.Warning: { WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.Information: { // When an operation supports asjob, Information messages must go thru verbose. WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.Debug: { WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.Error: { WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); return ; } case Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.DelayBeforePolling: { if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) { var data = messageData(); if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) { var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); var location = response.GetFirstHeader(@"Location"); var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); // do nothing more. data.Cancel(); return; } } break; } } await Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); if (token.IsCancellationRequested) { return ; } WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); } } /// <summary> /// Intializes a new instance of the <see cref="NewAzPostgreSqlFlexibleServerFirewallRule_CreateViaIdentityExpanded" /> cmdlet /// class. /// </summary> public NewAzPostgreSqlFlexibleServerFirewallRule_CreateViaIdentityExpanded() { } /// <summary>Performs execution of the command.</summary> protected override void ProcessRecord() { ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } __processRecordId = System.Guid.NewGuid().ToString(); try { // work if (ShouldProcess($"Call remote 'FlexibleServerFirewallRulesCreateOrUpdate' operation")) { if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) { var instance = this.Clone(); var job = new Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); JobRepository.Add(job); var task = instance.ProcessRecordAsync(); job.Monitor(task); WriteObject(job); } else { using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Token) ) { asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Token); } } } } catch (global::System.AggregateException aggregateException) { // unroll the inner exceptions to get the root cause foreach( var innerException in aggregateException.Flatten().InnerExceptions ) { ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } // Write exception out to error channel. WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); } } catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) { ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } // Write exception out to error channel. WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); } finally { ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.CmdletProcessRecordEnd).Wait(); } } /// <summary>Performs execution of the command, working asynchronously if required.</summary> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> protected async global::System.Threading.Tasks.Task ProcessRecordAsync() { using( NoSynchronizationContext ) { await ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } await ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } Pipeline = Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); if (null != HttpPipelinePrepend) { Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); } if (null != HttpPipelineAppend) { Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); } // get the client instance try { await ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } if (InputObject?.Id != null) { await this.Client.FlexibleServerFirewallRulesCreateOrUpdateViaIdentity(InputObject.Id, ParametersBody, onOk, onDefault, this, Pipeline); } else { // try to call with PATH parameters from Input Object if (null == InputObject.SubscriptionId) { ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); } if (null == InputObject.ResourceGroupName) { ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); } if (null == InputObject.ServerName) { ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ServerName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); } if (null == InputObject.FirewallRuleName) { ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FirewallRuleName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); } await this.Client.FlexibleServerFirewallRulesCreateOrUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.ServerName ?? null, InputObject.FirewallRuleName ?? null, ParametersBody, onOk, onDefault, this, Pipeline); } await ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } catch (Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.UndeclaredResponseException urexception) { WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ParametersBody}) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } }); } finally { await ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Events.CmdletProcessRecordAsyncEnd); } } } /// <summary>Interrupts currently running code within the command.</summary> protected override void StopProcessing() { ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.IEventListener)this).Cancel(); base.StopProcessing(); } /// <summary> /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201.ICloudError" /// /> from the remote call</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201.ICloudError> response) { using( NoSynchronizationContext ) { var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false); overrideOnDefault(responseMessage, response, ref _returnNow); // if overrideOnDefault has returned true, then return right away. if ((null != _returnNow && await _returnNow)) { return ; } // Error Response : default var code = (await response)?.Code; var message = (await response)?.Message; if ((null == code || null == message)) { // Unrecognized Response. Create an error record based on what we have. var ex = new Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.RestException<Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201.ICloudError>(responseMessage, await response); WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ParametersBody }) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } }); } else { WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ParametersBody }) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } }); } } } /// <summary>a delegate that is called when the remote service returns 200 (OK).</summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.IFirewallRuleAutoGenerated" /// /> from the remote call</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.IFirewallRuleAutoGenerated> response) { using( NoSynchronizationContext ) { var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false); overrideOnOk(responseMessage, response, ref _returnNow); // if overrideOnOk has returned true, then return right away. if ((null != _returnNow && await _returnNow)) { return ; } // onOk - response for 200 / application/json // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.IFirewallRuleAutoGenerated WriteObject((await response)); } } } }
75.425
471
0.664346
[ "MIT" ]
AndriiKalinichenko/azure-powershell
src/PostgreSql/generated/cmdlets/NewAzPostgreSqlFlexibleServerFirewallRule_CreateViaIdentityExpanded.cs
35,725
C#
using System; using System.Collections.Generic; using System.Text; namespace EscolaMS_Domain.Entities { public class Responsavel { public int ResponsavelId { get; set; } public string Nome { get; set; } public DateTime DataNascimento { get; set; } public string CPF { get; set; } public virtual IEnumerable<Aluno> Alunos { get; set; } } } //- O Responsável deve ter no mínimo 18 anos de idade; //- O nome deve ter máximo de 180 e mínimo de 3 caracteres; //- CPF é obrigatório;
26.6
62
0.663534
[ "MIT" ]
AecioDev/Escolas-MS
EscolasMS/EscolaMS_Domain/Entities/Responsavel.cs
540
C#
using System; namespace Studio.Wizet.Audio.MediaFoundation { /// <summary> /// Indicates whether a Media Foundation transform (MFT) can produce output data. /// </summary> [Flags] public enum _MFT_OUTPUT_STATUS_FLAGS { /// <summary> /// None /// </summary> None = 0, /// <summary> /// There is a sample available for at least one output stream. /// </summary> MFT_OUTPUT_STATUS_SAMPLE_READY = 0x00000001 } }
25.05
85
0.58483
[ "MIT" ]
Iciclelz/wizet-studio
Wizet Studio/Studio.Wizet.Audio/MediaFoundation/_MFT_OUTPUT_STATUS_FLAGS.cs
503
C#
using System; using System.Diagnostics; using System.IO; using System.Windows.Forms; using ADODB; // ReSharper disable once CheckNamespace namespace hoTools.Utils.ODBC { /// <summary> /// ODBC connection. Note: Wildcard is '%', also for Access /// </summary> public class Odbc { EA.Repository _rep; ADODB.Connection _cn; ADODB.Command _cmd; ADODB.Recordset _rs; public Connection Cn { get => _cn; set => _cn = value; } public Command Cmd { get => _cmd; set => _cmd = value; } public Recordset Rs { get => _rs; set => _rs = value; } /// <summary> /// ODBC connection. Note: Wildcard is '%', also for Access /// </summary> /// <param name="rep"></param> public Odbc(EA.Repository rep) { _rep = rep; _rs = new ADODB.Recordset(); _cmd = new ADODB.Command(); _cmd.CommandTimeout = 180; int start; string connectionString = _rep.ConnectionString; if (connectionString.Contains("Connect=")) { start = connectionString.IndexOf("Connect=", StringComparison.Ordinal) + 8; connectionString = connectionString.Substring(start); } else { connectionString = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + connectionString; } try { _cn = new ADODB.Connection(); _cn.CommandTimeout = 60; _cn.ConnectionTimeout = 60; _cn.Open(connectionString, "", "", 0); } catch (Exception ex) { // check if shortcut was chosen // The first line contains the connection string connectionString = connectionString.ToUpper(); if (connectionString.Contains(".EAP")) { start = connectionString.IndexOf(@"DATA SOURCE=", StringComparison.Ordinal) + 12; connectionString = connectionString.Substring(start); TextReader tr = new StreamReader(connectionString); string shortcut = tr.ReadLine(); tr.Close(); Debug.Assert(shortcut != null, nameof(shortcut) + " != null"); if (shortcut.Contains("Connect=")) { start = shortcut.IndexOf("Connect=", StringComparison.Ordinal) + 8; connectionString = shortcut.Substring(start); try { _cn = new ADODB.Connection(); _cn.Open(connectionString, "", "", 0); _cmd.ActiveConnection = _cn; _rs.ActiveConnection = _cn; } catch (Exception ex1) { MessageBox.Show("Error in ADODB connect: '" + connectionString + "'\n" + "Don't start EA with a shortcut like SDTL.eap!\n\n" + ex1.Message); } } } MessageBox.Show("Error in ADODB connect: '" + connectionString + "'\n" + "Don't start EA with a shortcut like SDTL.eap!\n\n" + ex.Message); } _cmd.ActiveConnection = _cn; _rs.ActiveConnection = _cn; } public bool OdbcCmd(string sql) { if (_cmd == null) { _cmd = new ADODB.Command(); _cmd.ActiveConnection = _cn; } ADODB.Recordset rs1 = new ADODB.Recordset(); rs1.ActiveConnection = _cn; _cmd.CommandText = sql; _cmd.CommandType = ADODB.CommandTypeEnum.adCmdText; object dummy = Type.Missing; try { _cmd.Execute(out dummy, ref dummy, 0); } catch (Exception ex) { MessageBox.Show("Error in ADODB Execute" + _rep.ConnectionString + "\n'" + _cmd.CommandText + "'\n'" + ex.Message + "'"); return false; } return true; } public void Close() { if (_cn != null) { try { _cn.Close(); } catch (Exception) { // ignored } } _cn = null; _rs = null; _cmd = null; } } }
33.121429
168
0.467759
[ "BSD-2-Clause" ]
CuchulainX/EnterpriseArchitect_hoTools
Util/ODBC.cs
4,639
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; internal static partial class Interop { internal static partial class ComCtl32 { public struct TBBUTTON { public int iBitmap; public int idCommand; public TBSTATE fsState; public byte fsStyle; public byte bReserved0; public byte bReserved1; public IntPtr dwData; public IntPtr iString; } } }
26.833333
71
0.624224
[ "MIT" ]
Amy-Li02/winforms
src/Common/src/Interop/ComCtl32/Interop.TBBUTTON.cs
646
C#
using System; using System.Data.SqlClient; namespace Supply_Manager.Controllers { public class DatabaseConnectionSchema { public SqlConnection con; public SqlConnection GetConnection() { return con; } public void ConnectionSchema() { string connectionString = null; connectionString = "Data Source=localhost,1433;Initial Catalog=supply_chain_manager;Integrated Security=false;User ID=sa;Password=Root3234!!!;MultipleActiveResultSets=True"; con = new SqlConnection(connectionString); //con.Open(); Console.WriteLine("connecting to MSSQL Database"); //try //{ // con.Open(); // Console.WriteLine("connection block"); //} //catch(Exception e) //{ // Console.WriteLine(e); //} //return "testing Database Connection"; } public void CloseConnection() { con.Close(); Console.WriteLine("Closing Connection"); } } }
26.302326
185
0.548187
[ "MIT" ]
odeladetunji/Supply_Chain_Manager
Supply_Manager/Supply_Manager/Controllers/DatabaseConnectionSchema.cs
1,133
C#
// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "<Pending>", Scope = "member", Target = "~M:Grid_Generator.Start")] [assembly: SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "<Pending>", Scope = "type", Target = "~T:Grid_Generator.nodeDirection")]
58.4
150
0.751712
[ "Apache-2.0" ]
jesusmayor/VRPortalsUnity
GlobalSuppressions3.cs
586
C#
//------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.42000 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ using NMF.Collections.Generic; using NMF.Collections.ObjectModel; using NMF.Expressions; using NMF.Expressions.Linq; using NMF.Models; using NMF.Models.Collections; using NMF.Models.Expressions; using NMF.Models.Meta; using NMF.Models.Repository; using NMF.Serialization; using NMF.Utilities; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Linq; using TTC2017.SmartGrids.COSEM.InterfaceClasses; namespace TTC2017.SmartGrids.COSEM.COSEMObjects { /// <summary> /// The default implementation of the PRIME_NB_OFDM_PLC_Physical_layer_counters_object class /// </summary> [XmlNamespaceAttribute("objects")] [XmlNamespacePrefixAttribute("objects")] [ModelRepresentationClassAttribute("http://www.transformation-tool-contest.eu/2017/smartGrids/cosem#//COSEMObjects/PR" + "IME_NB_OFDM_PLC_Physical_layer_counters_object")] public partial class PRIME_NB_OFDM_PLC_Physical_layer_counters_object : PRIME_NB_OFDM_PLC_Phy_layer_counters, IPRIME_NB_OFDM_PLC_Physical_layer_counters_object, IModelElement { private static IClass _classInstance; /// <summary> /// Gets the Class model for this type /// </summary> public new static IClass ClassInstance { get { if ((_classInstance == null)) { _classInstance = ((IClass)(MetaRepository.Instance.Resolve("http://www.transformation-tool-contest.eu/2017/smartGrids/cosem#//COSEMObjects/PR" + "IME_NB_OFDM_PLC_Physical_layer_counters_object"))); } return _classInstance; } } /// <summary> /// Gets the Class for this model element /// </summary> public override IClass GetClass() { if ((_classInstance == null)) { _classInstance = ((IClass)(MetaRepository.Instance.Resolve("http://www.transformation-tool-contest.eu/2017/smartGrids/cosem#//COSEMObjects/PR" + "IME_NB_OFDM_PLC_Physical_layer_counters_object"))); } return _classInstance; } } }
35.397436
178
0.628033
[ "MIT" ]
georghinkel/ttc2017smartGrids
generator/COSEM/COSEMObjects/PRIME_NB_OFDM_PLC_Physical_layer_counters_object.cs
2,763
C#
using System; namespace Work.Encryption { public class Class1 { } }
9.111111
25
0.621951
[ "Apache-2.0" ]
lijiadao/work.common.utility
work.common.utility/Work.Encryption/Class1.cs
84
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. using System.Collections.Generic; using System.Text; using Microsoft.EntityFrameworkCore.Update; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.EntityFrameworkCore.SqlServer.Update.Internal { /// <summary> /// <para> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </para> /// <para> /// The service lifetime is <see cref="ServiceLifetime.Singleton" />. This means a single instance /// is used by many <see cref="DbContext" /> instances. The implementation must be thread-safe. /// This service cannot depend on services registered as <see cref="ServiceLifetime.Scoped" />. /// </para> /// </summary> public interface ISqlServerUpdateSqlGenerator : IUpdateSqlGenerator { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> ResultSetMapping AppendBulkInsertOperation( StringBuilder commandStringBuilder, IReadOnlyList<ModificationCommand> modificationCommands, int commandPosition ); } }
54.473684
113
0.686957
[ "Apache-2.0" ]
belav/efcore
src/EFCore.SqlServer/Update/Internal/ISqlServerUpdateSqlGenerator.cs
2,070
C#
/* Yet Another Forum.NET * Copyright (C) 2003-2005 Bjørnar Henden * Copyright (C) 2006-2013 Jaben Cargman * Copyright (C) 2014-2021 Ingo Herbote * https://www.yetanotherforum.net/ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * https://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace YAF.Types.Models { using System; using ServiceStack.DataAnnotations; using ServiceStack.OrmLite; using YAF.Types.Interfaces.Data; /// <summary> /// A class which represents the ProfileCustom table. /// </summary> [Serializable] [CompositePrimaryKey(nameof(ProfileDefinitionID), nameof(UserID))] public class ProfileCustom : IEntity { #region Properties /// <summary> /// Gets or sets the profile definition id. /// </summary> [References(typeof(ProfileDefinition))] [Required] public int ProfileDefinitionID { get; set; } /// <summary> /// Gets or sets the user id. /// </summary> [References(typeof(User))] [Required] public int UserID { get; set; } /// <summary> /// Gets or sets the value. /// </summary> [CustomField(OrmLiteVariables.MaxText)] public string Value { get; set; } #endregion } }
31.769231
71
0.644552
[ "Apache-2.0" ]
Spinks90/YAFNET
yafsrc/YAF.Types/Models/ProfileCustom.cs
2,002
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="StructuremapWebApi.cs" company="Web Advanced"> // Copyright 2012 Web Advanced (www.webadvanced.com) // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using Upchurch.Ingress.DependencyResolution; [assembly: WebActivatorEx.PostApplicationStartMethod(typeof(Upchurch.Ingress.App_Start.StructuremapWebApi), "Start")] namespace Upchurch.Ingress.App_Start { public static class StructuremapWebApi { public static void Start() { var container = StructuremapMvc.StructureMapDependencyScope.Container; System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = new StructureMapWebApiDependencyResolver(container); } } }
50.586207
136
0.627812
[ "MIT" ]
CecilCable/Ingress-ScoreKeeper
Upchurch.Ingress/App_Start/StructuremapWebApi.cs
1,467
C#
//******************************************************************************************************************************************************************************************// // Copyright (c) 2011 George Mamaladze // // // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), // // to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, // // and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // //******************************************************************************************************************************************************************************************// using System; namespace Neos.IdentityServer.MultiFactor.QrEncoding.Masking { internal class Pattern1 : Pattern { public override bool this[int i, int j] { get { return j % 2 == 0; } set { throw new NotSupportedException(); } } public override MaskPatternType MaskPatternType { get { return MaskPatternType.Type1; } } } }
91.029412
191
0.35412
[ "MIT" ]
anorstrom/adfsmfa
Neos.IdentityServer 2.0/Neos.IdentityServer.QrCodeNet/Masking/Pattern1.cs
3,097
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Bullseye; using CliWrap; using CliWrap.Buffered; using Stl.IO; using static Bullseye.Targets; namespace Build { // DragonFruit isn't the best option here (e.g. currently it doesn't support aliases), // but it does the job. internal static class Program { /// <summary>Build project for this repository.</summary> /// <param name="arguments">A list of targets to run or list.</param> /// <param name="clear">Clear the console before execution.</param> /// <param name="dryRun">Do a dry run without executing actions.</param> /// <param name="host">Force the mode for a specific host environment (normally auto-detected).</param> /// <param name="listDependencies">List all (or specified) targets and dependencies, then exit.</param> /// <param name="listInputs">List all (or specified) targets and inputs, then exit.</param> /// <param name="listTargets">List all (or specified) targets, then exit.</param> /// <param name="listTree">List all (or specified) targets and dependency trees, then exit.</param> /// <param name="noColor">Disable colored output.</param> /// <param name="parallel">Run targets in parallel.</param> /// <param name="skipDependencies">Do not run targets' dependencies.</param> /// <param name="verbose">Enable verbose output.</param> /// <param name="cancellationToken"></param> /// <param name="configuration">The configuration for building</param> /// <param name="framework">The framework to build for</param> /// <param name="isPublicRelease">You can redefine PublicRelease property for Nerdbank.GitVersioning</param> private static async Task Main( string[] arguments, bool clear, bool dryRun, Host host, bool listDependencies, bool listInputs, bool listTargets, bool listTree, bool noColor, bool parallel, bool skipDependencies, bool verbose, CancellationToken cancellationToken, // Our own options string configuration = "", string framework = "", bool isPublicRelease = true) { SetDefaults("Stl.Fusion.sln"); var options = new Options { Clear = clear, DryRun = dryRun, Host = host, ListDependencies = listDependencies, ListInputs = listInputs, ListTargets = listTargets, ListTree = listTree, NoColor = noColor, Parallel = parallel, SkipDependencies = skipDependencies, Verbose = verbose, }; var artifactsPath = FilePath.New("artifacts").FullPath; var nupkgPath = artifactsPath & "nupkg"; var testOutputPath = artifactsPath & "tests" & "output"; var dotnetExePath = TryFindDotNetExePath() ?? throw new FileNotFoundException( "'dotnet' command isn't found. Use DOTNET_ROOT env. var to specify the path to custom 'dotnet' tool."); // For Nerdbank.GitVersioning: https://github.com/dotnet/Nerdbank.GitVersioning/blob/master/doc/public_vs_stable.md var isPublicReleaseOverride = bool.TryParse(Environment.GetEnvironmentVariable("NBGV_PublicRelease")?.Trim() ?? "", out var v) ? (bool?) v : null; var publicReleaseProperty = $"-p:PublicRelease={isPublicReleaseOverride ?? isPublicRelease} "; Target("clean", () => { DeleteDir(artifactsPath); CreateDir(nupkgPath, true); }); Target("clean-nupkg", () => { DeleteDir(nupkgPath); CreateDir(nupkgPath, true); }); Target("restore-tools", async () => { await Cli.Wrap(dotnetExePath).WithArguments(new[] {"tool", "restore", "--ignore-failed-sources"}) .ToConsole() .ExecuteAsync(cancellationToken).ConfigureAwait(false); }); Target("restore", async () => { await Cli.Wrap(dotnetExePath).WithArguments(new[] { "msbuild", "-noLogo", "-t:Restore", "-p:RestoreForce=true", "-p:RestoreIgnoreFailedSources=True", publicReleaseProperty }).ToConsole() .ExecuteAsync(cancellationToken).ConfigureAwait(false); }); Target("build", async () => { await Cli.Wrap(dotnetExePath).WithArguments(args => args .Add("build") .Add("-noLogo") .AddOption("-c", configuration) .AddOption("-f", framework) .Add("--no-restore") .Add(publicReleaseProperty) ) .ToConsole() .ExecuteAsync(cancellationToken).ConfigureAwait(false); }); // Technically it should depend on "build" target, but such a setup fails // due to https://github.com/dotnet/orleans/issues/6073 , // that's why we make "pack" to run "build" too here Target("pack", DependsOn("clean", "restore"), async () => { await Cli.Wrap(dotnetExePath).WithArguments(args => args .Add("pack") .Add("-noLogo") .AddOption("-c", configuration) .AddOption("-f", framework) .Add("--no-restore") .Add(publicReleaseProperty) ) .ToConsole() .ExecuteAsync(cancellationToken).ConfigureAwait(false); }); Target("publish", DependsOn("clean-nupkg", "pack"), async () => { const string feed = "https://api.nuget.org/v3/index.json"; var nugetOrgApiKey = Environment.GetEnvironmentVariable("NUGET_ORG_API_KEY") ?? ""; if (string.IsNullOrWhiteSpace(nugetOrgApiKey)) throw new InvalidOperationException("NUGET_ORG_API_KEY env. var isn't set."); var nupkgPaths = Directory .EnumerateFiles(nupkgPath.FullPath, "*.nupkg", SearchOption.TopDirectoryOnly) .Select(FilePath.New) .ToArray(); foreach (var nupkgPath in nupkgPaths) { await Cli.Wrap(dotnetExePath).WithArguments(new string[] { "nuget", "push", nupkgPath, "--force-english-output", "--timeout", "60", "--api-key", nugetOrgApiKey, "--source", feed, "--skip-duplicate" }) .ToConsole() .ExecuteAsync(cancellationToken) .ConfigureAwait(false); } }); Target("coverage", DependsOn("build"), async () => { CreateDir(testOutputPath); var cmd = await Cli.Wrap(dotnetExePath) .WithArguments(args => args .Add("test") .Add("--nologo") .Add("--no-restore") .Add("--blame") .Add("--collect:\"XPlat Code Coverage\"") .Add("--results-directory").Add(testOutputPath) .AddOption("-c", configuration) .AddOption("-f", framework) .Add("--") .Add("DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.Format=json,cobertura") ).ToConsole() .ExecuteBufferedAsync(cancellationToken) .ConfigureAwait(false); MoveCoverageOutputFiles(testOutputPath); // Removes all files in inner folders, workaround for https://github.com/microsoft/vstest/issues/2334 foreach (var path in Directory.EnumerateDirectories(testOutputPath).Select(FilePath.New)) DeleteDir(path); }); Target("default", DependsOn("build")); try { // RunTargetsAndExitAsync hangs Target on Ctrl+C await RunTargetsWithoutExitingAsync(arguments, options, ex => ex is OperationCanceledException).ConfigureAwait(false); } catch (TargetFailedException tfe) { if (tfe.InnerException is OperationCanceledException oce) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(oce.Message); Console.ResetColor(); } } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"Unhandled exception: {ex}"); Console.ResetColor(); } } private static void SetDefaults(string solutionName) { var slnPath = FindNearest(Environment.CurrentDirectory, solutionName) ?? FindNearest(FilePath.New(Assembly.GetExecutingAssembly().Location).DirectoryPath, solutionName) ?? throw new InvalidOperationException($"Can't find '{solutionName}'."); Environment.CurrentDirectory = slnPath.DirectoryPath; Environment.SetEnvironmentVariable("DOTNET_CLI_TELEMETRY_OPTOUT", "1"); Environment.SetEnvironmentVariable("DOTNET_SVCUTIL_TELEMETRY_OPTOUT", "1"); Environment.SetEnvironmentVariable("DOTNET_SKIP_FIRST_TIME_EXPERIENCE", "1"); Environment.SetEnvironmentVariable("DOTNET_NOLOGO", "1"); Environment.SetEnvironmentVariable("POWERSHELL_TELEMETRY_OPTOUT", "1"); Environment.SetEnvironmentVariable("POWERSHELL_UPDATECHECK_OPTOUT", "1"); Environment.SetEnvironmentVariable("DOTNET_CLI_UI_LANGUAGE", "en"); Environment.SetEnvironmentVariable("PUBLIC_BUILD", "1"); } static void MoveCoverageOutputFiles(FilePath testOutputPath) { // Moves coverage reports from GUID folders to the output path. A workaround for: // - https://github.com/microsoft/vstest/issues/2378 // - https://github.com/microsoft/vstest/issues/2334 var dirPaths = ( from dirPath in Directory.EnumerateDirectories(testOutputPath).Select(FilePath.New) let createTime = Directory.GetCreationTime(dirPath) orderby createTime select dirPath ).ToArray(); var dirIndex = 1; foreach (var dirPath in dirPaths) { var dirName = dirPath.FileName; foreach (var filePath in Directory.EnumerateFiles(dirPath, "coverage.*").Select(FilePath.New).ToArray()) { var newFilePath = testOutputPath & $"{dirIndex}-{filePath.FileName}"; Console.WriteLine($"Moving: {filePath} -> {newFilePath}"); File.Move(filePath, newFilePath, true); } DeleteDir(dirPath); dirIndex++; } } private static FilePath? FindNearest(FilePath basePath, string fileName) { var path = basePath.ToAbsolute(); while (true) { if (File.Exists(path & fileName)) return path & fileName; var nextPath = (path & "..").FullPath; if (nextPath == path) return null; path = nextPath; } } private static FilePath? TryFindDotNetExePath() { var dotnetExe = "dotnet"; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) dotnetExe += ".exe"; var mainModulePath = FilePath.New(Process.GetCurrentProcess().MainModule?.FileName); if (mainModulePath.Value != "" && mainModulePath.FileName.Value.Equals(dotnetExe, StringComparison.OrdinalIgnoreCase)) return mainModulePath; var dotnetRoot = FilePath.New(Environment.GetEnvironmentVariable("DOTNET_ROOT")); if (dotnetRoot.Value != "") return dotnetRoot & dotnetExe; return FindInPath(dotnetExe); } private static FilePath? FindInPath(string fileName) { var paths = Environment.GetEnvironmentVariable("PATH"); if (paths == null) return null; foreach (var path in paths.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) { var fullPath = FilePath.New(path) & fileName; if (File.Exists(fullPath)) return fullPath; } return null; } private static bool CreateDir(FilePath path, bool failOnError = false) { if (Directory.Exists(path)) return true; Console.WriteLine($"Creating Directory: {path}"); try { Directory.CreateDirectory(path); return true; } catch { if (failOnError) throw; return false; } } private static bool DeleteDir(FilePath path, bool failOnError = false) { if (!Directory.Exists(path)) return true; Console.WriteLine($"Deleting Directory: {path}"); try { Directory.Delete(path, true); return true; } catch { if (failOnError) throw; return false; } } } }
44.006061
158
0.536703
[ "MIT" ]
MessiDaGod/Stl.Fusion
build/Program.cs
14,522
C#
// Copyright (c) Microsoft Corporation. All rights reserved. using System; using System.Diagnostics; using System.Globalization; using System.Security; using System.Security.Cryptography; namespace LibUA.Security.Cryptography { /// <summary> /// Generic implementation of HMAC which is implemented by the BCrypt layer of Cng. Concrete HMAC /// classes should contain an instance of the BCryptHMAC type and delegate their work to that object. /// </summary> internal sealed class BCryptHMAC : HMAC, ICngAlgorithm { private SafeBCryptAlgorithmHandle m_algorithm; private SafeBCryptHashHandle m_hash; private CngProvider m_implementation; [SecurityCritical] [SecuritySafeCritical] internal BCryptHMAC(CngAlgorithm algorithm, CngProvider algorithmProvider, string hashName, int blockSize, byte[] key) { Debug.Assert(algorithm != null, "algorithm != null"); Debug.Assert(algorithmProvider != null, "algorithmProvider != null"); Debug.Assert(!String.IsNullOrEmpty(hashName), "!String.IsNullOrEmpty(hashName)"); Debug.Assert(blockSize > 0, "blockSize > 0"); Debug.Assert(key != null, "key != null"); BlockSizeValue = blockSize; // We set the HashName up to be the CNG version of the hash, since the base type will instantiate // the algorithm, and the CNG versions have different FIPS characteristics than the standard implementations. HashName = String.Format(CultureInfo.InvariantCulture, "System.Security.Cryptography.{0}Cng, {1}", hashName, typeof(SHA256Cng).Assembly.FullName); m_implementation = algorithmProvider; m_algorithm = BCryptNative.OpenAlgorithm(algorithm.Algorithm, algorithmProvider.Provider, BCryptNative.AlgorithmProviderOptions.HmacAlgorithm); // Resetting the key will call Initialize for us, and get us setup with a hash handle, // so we don't need to create the hash handle ourselves Key = key; HashSizeValue = BCryptNative.GetInt32Property(m_hash, BCryptNative.HashPropertyName.HashLength) * 8; } public override bool CanReuseTransform { get { return true; } } public override bool CanTransformMultipleBlocks { get { return true; } } public override byte[] Key { set { // HMAC's Key setter will ensure that we're in a valid state to change the key base.Key = value; // Changing the key value requires us to create a new hash handle, so we need to reset Initialize(); } } public CngProvider Provider { get { return m_implementation; } } [SecurityCritical] [SecuritySafeCritical] protected override void Dispose(bool disposing) { try { if (disposing) { if (m_hash != null) { m_hash.Dispose(); } if (m_algorithm != null) { m_algorithm.Dispose(); } } } finally { base.Dispose(disposing); } } protected override void HashCore(byte[] rgb, int ib, int cb) { HashCoreImpl(rgb, ib, cb); } [SecurityCritical] [SecuritySafeCritical] internal void HashCoreImpl(byte[] rgb, int ib, int cb) { if (rgb == null) throw new ArgumentNullException("rgb"); if (ib < 0 || ib > rgb.Length - cb) throw new ArgumentOutOfRangeException("ib"); if (cb < 0 || cb > rgb.Length) throw new ArgumentOutOfRangeException("cb"); // Tell the base class that resetting the key is no longer allowed State = 1; byte[] data = new byte[cb]; Buffer.BlockCopy(rgb, ib, data, 0, data.Length); BCryptNative.HashData(m_hash, data); } protected override byte[] HashFinal() { return HashFinalImpl(); } [SecurityCritical] [SecuritySafeCritical] internal byte[] HashFinalImpl() { return BCryptNative.FinishHash(m_hash); } [SecurityCritical] [SecuritySafeCritical] public override void Initialize() { Debug.Assert(m_algorithm != null, "m_algorithm != null"); base.Initialize(); // If we have a previously used hash handle, we can clean it up now if (m_hash != null) { m_hash.Dispose(); } m_hash = BCryptNative.CreateHash(m_algorithm, KeyValue); // We're allowed to reset the key at this point State = 0; } } }
32.96988
121
0.528412
[ "Apache-2.0" ]
Introsys/LibUA
NET/LibUA/Security.Cryptography/BCryptHMAC.cs
5,473
C#
namespace AspNetUpgrade.Model { public enum ProjectType { Library, Application } }
13.75
29
0.6
[ "MIT" ]
dazinator/AspNetRC1toRC2UpgradeTool
src/AspNetUpgrade/AspNetUpgrade/Model/ProjectType.cs
110
C#
using System; using System.Threading; using System.Threading.Tasks; using Application.Common.Interfaces; using FluentValidation; using MediatR; using Microsoft.EntityFrameworkCore; namespace Application.Features.Users { public class DeleteUser { public class Command : IRequest { private Command() {} public Command( int id) { Id = id; } public int Id { get; set; } } public class CommandValidator : AbstractValidator<Command> { public CommandValidator() { RuleFor(x => x.Id).NotNull().NotEmpty(); } } public class Handler : IRequestHandler<Command, Unit> { private readonly IApplicationDbContext _dbContext; public Handler( IApplicationDbContext dbContext) { _dbContext = dbContext; } public async Task<Unit> Handle( Command request, CancellationToken cancellationToken) { var user = await _dbContext.Users.FirstAsync( x => x.Id == request.Id, cancellationToken); if (user == null) { throw new Exception("Not Found"); } user.Archive(); await _dbContext.SaveChangesAsync(cancellationToken); return Unit.Value; } } } }
25
69
0.499683
[ "MIT" ]
simplyvinay/api-starter-template
Application/Features/Users/DeleteUser.cs
1,577
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace _04.Weather { public class WeatherInfo { public double Temperature { get; set; } public string Weather { get; set; } } class Weather { static void Main(string[] args) { var input = Console.ReadLine(); var weatherInfos = new Dictionary<string, WeatherInfo>(); while (input != "end") { var pattern = @"(?<city>[A-Z]{2})(?<temp>\d{2}\.\d+)(?<weather>[a-zA-Z]+)\|"; var match = Regex.Match(input, pattern); if (match.Success) { var city = match.Groups["city"].Value; var temp = double.Parse(match.Groups["temp"].Value); var weather = match.Groups["weather"].Value; var weatherInfo = new WeatherInfo() { Temperature = temp, Weather = weather }; weatherInfos[city] = weatherInfo; } input = Console.ReadLine(); } weatherInfos = weatherInfos.OrderBy(a => a.Value.Temperature).ToDictionary(a => a.Key, a => a.Value); foreach (var info in weatherInfos) { Console.WriteLine($"{info.Key} => {info.Value.Temperature:F2} => {info.Value.Weather}"); } } } }
28.518519
113
0.482468
[ "MIT" ]
vpaleshnikov/SoftUni-TechModule
ProgrammingFundamentals/20.RegularExpressions(RegEx)-Exercises/04.Weather/Weather.cs
1,542
C#
using System; using System.Xml.Serialization; using Microsoft.Xna.Framework; using Newtonsoft.Json; using Ship_Game.AI; using Ship_Game.Fleets; using Ship_Game.Ships; namespace Ship_Game { public sealed class FleetDataNode { [XmlIgnore][JsonIgnore] public Ship Ship { get; set; } [Serialize(0)] public Guid ShipGuid; [Serialize(1)] public Guid GoalGUID; [Serialize(2)] public string ShipName; [Serialize(3)] public Vector2 FleetOffset; [Serialize(4)] public float VultureWeight = 0.5f; [Serialize(5)] public float AttackShieldedWeight = 0.5f; [Serialize(6)] public float AssistWeight = 0.5f; [Serialize(7)] public float DefenderWeight = 0.5f; [Serialize(8)] public float DPSWeight = 0.5f; [Serialize(9)] public float SizeWeight = 0.5f; [Serialize(10)] public float ArmoredWeight = 0.5f; [XmlElement(ElementName = "orders")] [Serialize(11)] public Orders Order; [Serialize(12)] public CombatState CombatState; [Serialize(13)] public Vector2 OrdersOffset; [Serialize(14)] public float OrdersRadius = 500000;//0.5f; public float ApplyWeight(float shipStat, float statAvg, float fleetWeight) { if (fleetWeight > 0.49f && fleetWeight < 0.51f) return 0; return shipStat > statAvg ? 2 * (-0.5f + fleetWeight) : 4 * ( 0.5f - fleetWeight); } public float ApplyFleetWeight(Fleet fleet, Ship potential) { float weight = 0; if ((DefenderWeight > 0.49f && DefenderWeight < 0.51f) || (AssistWeight > 0.49f && AssistWeight < 0.51f)) return weight; foreach (Ship ship in fleet.Ships) { if (potential.AI.Target == ship) weight -= 0.5f + DefenderWeight; if (ship.AI.Target == potential) weight -= 5.0f + AssistWeight; } return weight; } public FleetDataNode Clone() { return (FleetDataNode)MemberwiseClone(); } } public sealed class FleetDesign { [Serialize(0)] public Array<FleetDataNode> Data = new Array<FleetDataNode>(); [Serialize(1)] public int FleetIconIndex; [Serialize(2)] public string Name; [XmlIgnore][JsonIgnore] public SubTexture Icon => ResourceManager.FleetIcon(FleetIconIndex); public void Rotate(float facing) { foreach (FleetDataNode node in Data) { float radians = facing + Vector2.Zero.RadiansToTarget(node.FleetOffset); float distance = node.FleetOffset.Length(); node.FleetOffset = Vector2.Zero.PointFromRadians(radians, distance); } } } }
36.728395
101
0.568739
[ "MIT" ]
UnGaucho/StarDrive
Ship_Game/FleetDesign.cs
2,975
C#
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; namespace Tasks { public class A { static void Main(string[] args) { var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; Console.SetOut(sw); Solve(); Console.Out.Flush(); } public static void Solve() { var K = Scanner.Scan<int>(); var (A, B) = Scanner.Scan<int, int>(); var answer = false; for (var i = A; i <= B && !answer; i++) if (i % K == 0) answer = true; Console.WriteLine(answer ? "OK" : "NG"); } public static class Scanner { private static Queue<string> queue = new Queue<string>(); public static T Next<T>() { if (!queue.Any()) foreach (var item in Console.ReadLine().Trim().Split(" ")) queue.Enqueue(item); return (T)Convert.ChangeType(queue.Dequeue(), typeof(T)); } public static T Scan<T>() => Next<T>(); public static (T1, T2) Scan<T1, T2>() => (Next<T1>(), Next<T2>()); public static (T1, T2, T3) Scan<T1, T2, T3>() => (Next<T1>(), Next<T2>(), Next<T3>()); public static (T1, T2, T3, T4) Scan<T1, T2, T3, T4>() => (Next<T1>(), Next<T2>(), Next<T3>(), Next<T4>()); public static (T1, T2, T3, T4, T5) Scan<T1, T2, T3, T4, T5>() => (Next<T1>(), Next<T2>(), Next<T3>(), Next<T4>(), Next<T5>()); public static IEnumerable<T> ScanEnumerable<T>() => Console.ReadLine().Trim().Split(" ").Select(x => (T)Convert.ChangeType(x, typeof(T))); } } }
38.065217
150
0.504854
[ "CC0-1.0" ]
AconCavy/AtCoder.Tasks.CS
ABC/ABC165/Tasks/A.cs
1,751
C#
namespace TexasHoldem.AI.RaiseTwoSevenTestPlayer.Loggers { public interface ILogger { void Log(string message); } }
17.125
57
0.686131
[ "MIT" ]
DataBaseExam/DatabaseExam
Source/TexasHoldem.AI.RaiseTwoSevenTestPlayer/Loggers/Ilogger.cs
139
C#
using UnityEngine; using UnityEngine.SceneManagement; namespace Eflatun.CodePatterns { /// <summary> /// <para>Base class for a singleton MonoBehaviour that gets destroyed if current scene changes.</para> /// <para>If you want to use OnApplicationQuit method in implementator, use 'new' keyword in method signature /// and call 'base.OnApplicationQuit()' in the first line of your method.</para> /// <para>Be aware this will not prevent a non singleton constructor such as `T myT = new T();` /// To prevent that, add `protected T () {}` to your singleton class. /// This type inherits from MonoBehaviour so we can use Coroutines.</para> /// </summary> public class SceneSingleton<T> : MonoBehaviour where T : MonoBehaviour { // // Original: http://wiki.unity3d.com/index.php/Singleton // This is a heavily modified version. // private static T _instance; private static readonly object Lock = new object(); protected SceneSingleton() { } /// <summary> /// Returns the singleton instance of <see cref="T"/> for this scene. Please double check you are in the correct scene before calling this. /// </summary> public static T Instance { get { if (_applicationIsQuitting) { Debug.LogWarning(string.Format( "[SceneSingleton ({0})] Application is quitting! Returning null instead of '{1}'.", SceneManager.GetActiveScene().name, typeof(T))); return null; } lock (Lock) { if (_instance == null) { _instance = (T) FindObjectOfType(typeof(T)); if (FindObjectsOfType(typeof(T)).Length > 1) { Debug.LogError(string.Format( "[SceneSingleton ({0})] Something went really wrong - there should never be more than 1 singleton! Reopening the scene might fix it.", SceneManager.GetActiveScene().name)); } else if (_instance == null) { var container = new GameObject(); _instance = container.AddComponent<T>(); container.name = string.Format("(scene singleton) {0}", typeof(T)); Debug.Log(string.Format( "[SceneSingleton ({0})] An instance of {1} is needed in the scene, so '{2}' was created.", SceneManager.GetActiveScene().name, typeof(T), container)); } else { Debug.Log(string.Format("[SceneSingleton ({0})] Using instance already created: {1}", SceneManager.GetActiveScene().name, _instance.gameObject.name)); } } return _instance; } } } private static bool _applicationIsQuitting = false; /// <summary> /// When Unity quits, it destroys objects in a random order. /// If any script calls Instance after Singleton have been destroyed, /// it will create a buggy ghost object that will stay on the Editor scene /// even after stopping playing the Application. Really bad! /// So, this was made to be sure we're not creating that buggy ghost object. /// </summary> protected void OnApplicationQuit() { _applicationIsQuitting = true; } // NOTE: Duplicate checking in Awake() is not necessary for SceneSingletons, since // they don't have DontDestroyOnLoad, they won't get duplicated on scene load. } }
42.125
166
0.526459
[ "MIT" ]
fossabot/Eflatun.CodePatterns
Eflatun.CodePatterns/Packages/com.eflatun.codepatterns/SceneSingleton.cs
4,044
C#
using System; using System.Collections.Generic; using System.Linq; namespace OCM.API.Common.Model.Extensions { public class MetadataValue { public static Model.MetadataValue FromDataModel(Core.Data.MetadataValue source) { if (source == null) return null; return new Model.MetadataValue { ID = source.ID, MetadataFieldID =source.MetadataFieldID, MetadataFieldOption = MetadataFieldOption.FromDataModel(source.MetadataFieldOption), ItemValue = source.ItemValue }; } } }
28.090909
100
0.614887
[ "MIT" ]
cybersol795/ocm-system
API/OCM.Net/OCM.API.Core/Common/Extensions/MetadataValue.cs
620
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 Microsoft.SymbolStore; using System; using System.Collections.Immutable; using System.IO; namespace Microsoft.Diagnostics.DebugServices { public interface ISymbolService { /// <summary> /// Symbol file reader instance /// </summary> public class SymbolFile : IDisposable { public virtual void Dispose() { } } /// <summary> /// Invoked when anything changes in the symbol service (adding servers, caches, or directories, clearing store, etc.) /// </summary> IServiceEvent OnChangeEvent { get; } /// <summary> /// Returns true if symbol download has been enabled. /// </summary> bool IsSymbolStoreEnabled { get; } /// <summary> /// The default symbol cache path: /// /// * dbgeng on Windows uses the dbgeng symbol cache path: %PROGRAMDATA%\dbg\sym /// * dotnet-dump on Windows uses the VS symbol cache path: %TEMPDIR%\SymbolCache /// * dotnet-dump/lldb on Linux/MacOS uses: $HOME/.dotnet/symbolcache /// </summary> string DefaultSymbolCache { get; set; } /// <summary> /// Parses the Windows debugger symbol path (srv*, cache*, etc.). /// </summary> /// <param name="symbolPath">Windows symbol path</param> /// <returns>if false, error parsing symbol path</returns> bool ParseSymbolPath(string symbolPath); /// <summary> /// Add symbol server to search path. /// </summary> /// <param name="msdl">if true, use the public Microsoft server</param> /// <param name="symweb">if true, use symweb internal server and protocol (file.ptr)</param> /// <param name="symbolServerPath">symbol server url (optional)</param> /// <param name="authToken"></param> /// <param name="timeoutInMinutes">symbol server timeout in minutes (optional)</param> /// <returns>if false, failure</returns> bool AddSymbolServer(bool msdl, bool symweb, string symbolServerPath, string authToken, int timeoutInMinutes); /// <summary> /// Add cache path to symbol search path /// </summary> /// <param name="symbolCachePath">symbol cache directory path (optional)</param> void AddCachePath(string symbolCachePath); /// <summary> /// Add directory path to symbol search path /// </summary> /// <param name="symbolDirectoryPath">symbol directory path to search (optional)</param> void AddDirectoryPath(string symbolDirectoryPath); /// <summary> /// This function disables any symbol downloading support. /// </summary> void DisableSymbolStore(); /// <summary> /// Downloads module file /// </summary> /// <param name="module">module interface</param> /// <returns>module path or null</returns> string DownloadModule(IModule module); /// <summary> /// Download a file from the symbol stores/server. /// </summary> /// <param name="key">index of the file to download</param> /// <returns>path to the downloaded file either in the cache or in the temp directory or null if error</returns> string DownloadFile(SymbolStoreKey key); /// <summary> /// Returns the metadata for the assembly /// </summary> /// <param name="imagePath">file name and path to module</param> /// <param name="imageTimestamp">module timestamp</param> /// <param name="imageSize">size of PE image</param> /// <returns>metadata</returns> ImmutableArray<byte> GetMetadata(string imagePath, uint imageTimestamp, uint imageSize); /// <summary> /// Returns the portable PDB reader for the assembly path /// </summary> /// <param name="assemblyPath">file path of the assembly or null if the module is in-memory or dynamic</param> /// <param name="isFileLayout">type of in-memory PE layout, if true, file based layout otherwise, loaded layout</param> /// <param name="peStream">in-memory PE stream</param> /// <returns>symbol file or null</returns> /// <remarks> /// Assumes that neither PE image nor PDB loaded into memory can be unloaded or moved around. /// </remarks> ISymbolFile OpenSymbolFile(string assemblyPath, bool isFileLayout, Stream peStream); /// <summary> /// Returns the portable PDB reader for the portable PDB stream /// </summary> /// <param name="pdbStream">portable PDB memory or file stream</param> /// <returns>symbol file or null</returns> /// <remarks> /// Assumes that the PDB loaded into memory can be unloaded or moved around. /// </remarks> ISymbolFile OpenSymbolFile(Stream pdbStream); } }
41.637097
127
0.61534
[ "MIT" ]
AndyAyersMS/diagnostics
src/Microsoft.Diagnostics.DebugServices/ISymbolService.cs
5,163
C#
using CosmosStack.Sniffers.FileTypeSniffers.Registering; // ReSharper disable InconsistentNaming namespace CosmosStack.Sniffers.FileTypeSniffers.Library { [FileTypeExtensionNames("dex")] [FileTypeHex("64 65 78 0A 30 33 35 00")] public class _Dex_Fingerprint : IFileTypeFingerprint { } }
30.1
60
0.780731
[ "Apache-2.0" ]
cosmos-open/FileExtensionInfer
src/CosmosStack.Extensions.FileTypeSniffer.Library.Development/CosmosStack/Sniffers/FileTypeSniffers/Library/Fingerprint.dex.cs
303
C#
using System; using System.Threading.Tasks; namespace RStein.Async.Schedulers { public class QueueTasksParams { public QueueTasksParams(int maxNumberOfQueuedTasks = Int32.MaxValue, Action<Task> beforeTaskQueuedAction = null, Action<Task> taskContinuation = null, Action<Task> afterTaskQueuedAction = null) { MaxNumberOfQueuedTasks = maxNumberOfQueuedTasks; BeforeTaskQueuedAction = beforeTaskQueuedAction; TaskContinuation = taskContinuation; AfterTaskQueuedAction = afterTaskQueuedAction; } public Action<Task> BeforeTaskQueuedAction { get; } public Action<Task> TaskContinuation { get; } public Action<Task> AfterTaskQueuedAction { get; } public int MaxNumberOfQueuedTasks { get; } } }
22.102564
73
0.656613
[ "MIT" ]
renestein/rstein.async
RStein.Async/Schedulers/QueueTasksParams.cs
862
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http.Headers; using System.Security.Principal; using System.Text; using System.Threading; using System.Web; namespace CRM { public class BasicAuthHttpModule : IHttpModule { private const string Realm = "CRM Web API"; public void Init(HttpApplication context) { // Register event handlers context.AuthenticateRequest += OnApplicationAuthenticateRequest; context.EndRequest += OnApplicationEndRequest; } private static void SetPrincipal(IPrincipal principal) { Thread.CurrentPrincipal = principal; if (HttpContext.Current != null) { HttpContext.Current.User = principal; } } // TODO: Here is where you would validate the username and password. private static bool CheckPassword(string username, string password) { return username == "crmwebapi" && password == "crmwebapi"; } private static void AuthenticateUser(string credentials) { try { var encoding = Encoding.GetEncoding("iso-8859-1"); credentials = encoding.GetString(Convert.FromBase64String(credentials)); int separator = credentials.IndexOf(':'); string name = credentials.Substring(0, separator); string password = credentials.Substring(separator + 1); if (CheckPassword(name, password)) { var identity = new GenericIdentity(name); SetPrincipal(new GenericPrincipal(identity, null)); } else { // Invalid username or password. HttpContext.Current.Response.StatusCode = 401; } } catch (FormatException) { // Credentials were not formatted correctly. HttpContext.Current.Response.StatusCode = 401; } } private static void OnApplicationAuthenticateRequest(object sender, EventArgs e) { var request = HttpContext.Current.Request; var authHeader = request.Headers["Authorization"]; if (authHeader != null) { var authHeaderVal = AuthenticationHeaderValue.Parse(authHeader); // RFC 2617 sec 1.2, "scheme" name is case-insensitive if (authHeaderVal.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase) && authHeaderVal.Parameter != null) { AuthenticateUser(authHeaderVal.Parameter); } } } // If the request was unauthorized, add the WWW-Authenticate header // to the response. private static void OnApplicationEndRequest(object sender, EventArgs e) { var response = HttpContext.Current.Response; if (response.StatusCode == 401) { response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", Realm)); } } public void Dispose() { } } }
33.405941
88
0.553646
[ "MIT" ]
siecola/WebAPIBook2
CRM/BasicAuthHttpModule.cs
3,376
C#
using System; using System.Collections.Generic; using System.Text; using System.IO; using PluginCore.Managers; using ASCompletion.Context; using ASCompletion.Model; using PluginCore; using System.Collections; using System.Text.RegularExpressions; using PluginCore.Controls; using PluginCore.Localization; using AS3Context.Compiler; using PluginCore.Helpers; using System.Timers; using ASCompletion.Completion; namespace AS3Context { public class Context : AS2Context.Context { static readonly protected Regex re_genericType = new Regex("(?<gen>[^<]+)\\.<(?<type>.+)>$", RegexOptions.Compiled | RegexOptions.IgnoreCase); // C:\path\to\Main.as$raw$:31: col: 1: Error #1084: Syntax error: expecting rightbrace before end of program. static readonly protected Regex re_syntaxError = new Regex("(?<filename>.*)\\$raw\\$:(?<line>[0-9]+): col: (?<col>[0-9]+):(?<desc>.*)", RegexOptions.Compiled); static readonly protected Regex re_customAPI = new Regex("[/\\\\](playerglobal|airglobal|builtin)\\.swc", RegexOptions.Compiled | RegexOptions.IgnoreCase); #region initialization private AS3Settings as3settings; private bool hasAIRSupport; private bool hasMobileSupport; private MxmlFilterContext mxmlFilterContext; // extract inlined AS3 ranges & MXML tags private System.Timers.Timer timerCheck; private string fileWithSquiggles; protected bool mxmlEnabled; /// <summary> /// Do not call directly /// </summary> public Context() { } public Context(AS3Settings initSettings) { as3settings = initSettings; /* AS-LIKE OPTIONS */ hasLevels = false; docType = "flash.display.MovieClip"; /* DESCRIBE LANGUAGE FEATURES */ mxmlEnabled = true; // language constructs features.hasPackages = true; features.hasNamespaces = true; features.hasImports = true; features.hasImportsWildcard = true; features.hasClasses = true; features.hasExtends = true; features.hasImplements = true; features.hasInterfaces = true; features.hasEnums = false; features.hasGenerics = true; features.hasEcmaTyping = true; features.hasVars = true; features.hasConsts = true; features.hasMethods = true; features.hasStatics = true; features.hasOverride = true; features.hasTryCatch = true; features.hasE4X = true; features.hasStaticInheritance = true; features.checkFileName = true; // allowed declarations access modifiers Visibility all = Visibility.Public | Visibility.Internal | Visibility.Protected | Visibility.Private; features.classModifiers = all; features.varModifiers = all; features.constModifiers = all; features.methodModifiers = all; // default declarations access modifiers features.classModifierDefault = Visibility.Internal; features.varModifierDefault = Visibility.Internal; features.methodModifierDefault = Visibility.Internal; // keywords features.dot = "."; features.voidKey = "void"; features.objectKey = "Object"; features.booleanKey = "Boolean"; features.numberKey = "Number"; features.arrayKey = "Array"; features.importKey = "import"; features.typesPreKeys = new string[] { "import", "new", "typeof", "is", "as", "extends", "implements" }; features.codeKeywords = new string[] { "class", "interface", "var", "function", "const", "new", "delete", "typeof", "is", "as", "return", "break", "continue", "if", "else", "for", "each", "in", "while", "do", "switch", "case", "default", "with", "null", "true", "false", "try", "catch", "finally", "throw", "use", "namespace" }; features.varKey = "var"; features.constKey = "const"; features.functionKey = "function"; features.getKey = "get"; features.setKey = "set"; features.staticKey = "static"; features.finalKey = "final"; features.overrideKey = "override"; features.publicKey = "public"; features.internalKey = "internal"; features.protectedKey = "protected"; features.privateKey = "private"; features.intrinsicKey = "extern"; features.namespaceKey = "namespace"; /* INITIALIZATION */ settings = initSettings; //BuildClassPath(); // defered to first use // live syntax checking timerCheck = new Timer(500); timerCheck.SynchronizingObject = PluginBase.MainForm as System.Windows.Forms.Form; timerCheck.AutoReset = false; timerCheck.Elapsed += new ElapsedEventHandler(timerCheck_Elapsed); FlexShells.SyntaxError += new SyntaxErrorHandler(FlexShell_SyntaxError); } #endregion #region classpath management /// <summary> /// Classpathes & classes cache initialisation /// </summary> public override void BuildClassPath() { ReleaseClasspath(); started = true; if (as3settings == null) throw new Exception("BuildClassPath() must be overridden"); if (contextSetup == null) { contextSetup = new ContextSetupInfos(); contextSetup.Lang = settings.LanguageId; contextSetup.Platform = "Flash Player"; contextSetup.Version = as3settings.DefaultFlashVersion; } // external version definition platform = contextSetup.Platform; majorVersion = 10; minorVersion = 0; ParseVersion(contextSetup.Version, ref majorVersion, ref minorVersion); hasAIRSupport = platform == "AIR" || platform == "AIR Mobile"; hasMobileSupport = platform == "AIR Mobile"; string cpCheck = contextSetup.Classpath != null ? String.Join(";", contextSetup.Classpath).Replace('\\', '/') : ""; // check if CP contains a custom playerglobal.swc bool hasCustomAPI = re_customAPI.IsMatch(cpCheck); // // Class pathes // classPath = new List<PathModel>(); MxmlFilter.ClearCatalogs(); MxmlFilter.AddProjectManifests(); // SDK string compiler = PluginBase.CurrentProject != null ? PluginBase.CurrentProject.CurrentSDK : as3settings.GetDefaultSDK().Path; char S = Path.DirectorySeparatorChar; if (compiler == null) compiler = Path.Combine(PathHelper.ToolDir, "flexlibs"); string frameworks = compiler + S + "frameworks"; string sdkLibs = frameworks + S + "libs"; string sdkLocales = frameworks + S + "locale" + S + PluginBase.MainForm.Settings.LocaleVersion; string fallbackLibs = PathHelper.ResolvePath(PathHelper.ToolDir + S + "flexlibs" + S + "frameworks" + S + "libs"); string fallbackLocale = PathHelper.ResolvePath(PathHelper.ToolDir + S + "flexlibs" + S + "frameworks" + S + "locale" + S + "en_US"); List<string> addLibs = new List<string>(); List<string> addLocales = new List<string>(); if (!Directory.Exists(sdkLibs) && !sdkLibs.StartsWith("$")) // fallback { sdkLibs = PathHelper.ResolvePath(PathHelper.ToolDir + S + "flexlibs" + S + "frameworks" + S + "libs" + S + "player"); } if (majorVersion > 0 && !String.IsNullOrEmpty(sdkLibs) && Directory.Exists(sdkLibs)) { // core API SWC if (!hasCustomAPI) if (hasAIRSupport) { addLibs.Add("air" + S + "airglobal.swc"); addLibs.Add("air" + S + "aircore.swc"); addLibs.Add("air" + S + "applicationupdater.swc"); } else { bool swcPresent = false; string playerglobal = MatchPlayerGlobalExact(majorVersion, minorVersion, sdkLibs); if (playerglobal != null) swcPresent = true; else playerglobal = MatchPlayerGlobalExact(majorVersion, minorVersion, fallbackLibs); if (playerglobal == null) playerglobal = MatchPlayerGlobalAny(ref majorVersion, ref minorVersion, fallbackLibs); if (playerglobal == null) playerglobal = MatchPlayerGlobalAny(ref majorVersion, ref minorVersion, sdkLibs); if (playerglobal != null) { // add missing SWC in new SDKs if (!swcPresent && sdkLibs.IndexOf(S + "flexlibs") < 0 && Directory.Exists(compiler)) { string swcDir = sdkLibs + S + "player" + S; if (!Directory.Exists(swcDir + "9") && !Directory.Exists(swcDir + "10")) swcDir += majorVersion + "." + minorVersion; else swcDir += majorVersion; try { if (!File.Exists(swcDir + S + "playerglobal.swc")) { Directory.CreateDirectory(swcDir); File.Copy(playerglobal, swcDir + S + "playerglobal.swc"); File.WriteAllText(swcDir + S + "FlashDevelopNotice.txt", "This 'playerglobal.swc' was copied here automatically by FlashDevelop from:\r\n" + playerglobal); } playerglobal = swcDir + S + "playerglobal.swc"; } catch { } } addLibs.Add(playerglobal); } } addLocales.Add("playerglobal_rb.swc"); // framework SWCs string as3Fmk = PathHelper.ResolvePath("Library" + S + "AS3" + S + "frameworks"); // Flex core - ie. (Bitmap|Font|ByteArray|...)Asset / Flex(Sprite|MobieClip|Loader...) addLibs.Add("flex.swc"); addLibs.Add("core.swc"); // Flex framework if (cpCheck.IndexOf("Library/AS3/frameworks/Flex", StringComparison.OrdinalIgnoreCase) >= 0) { addLibs.Add("framework.swc"); addLibs.Add("mx/mx.swc"); addLibs.Add("rpc.swc"); addLibs.Add("datavisualization.swc"); addLibs.Add("flash-integration.swc"); addLocales.Add("framework_rb.swc"); addLocales.Add("mx_rb.swc"); addLocales.Add("rpc_rb.swc"); addLocales.Add("datavisualization_rb.swc"); addLocales.Add("flash-integration_rb.swc"); if (hasAIRSupport) { addLibs.Add("air" + S + "airframework.swc"); addLocales.Add("airframework_rb.swc"); } if (cpCheck.IndexOf("Library/AS3/frameworks/Flex4", StringComparison.OrdinalIgnoreCase) >= 0) { addLibs.Add("spark.swc"); addLibs.Add("spark_dmv.swc"); addLibs.Add("sparkskins.swc"); //addLibs.Add("textLayout.swc"); addLibs.Add("osmf.swc"); addLocales.Add("spark_rb.swc"); //addLocales.Add("textLayout_rb.swc"); addLocales.Add("osmf_rb.swc"); if (hasAIRSupport) { addLibs.Add("air" + S + "airspark.swc"); addLocales.Add("airspark_rb.swc"); if (hasMobileSupport) { addLibs.Add("mobile" + S + "mobilecomponents.swc"); addLocales.Add("mobilecomponents_rb.swc"); } } MxmlFilter.AddManifest("http://ns.adobe.com/mxml/2009", as3Fmk + S + "Flex4" + S + "manifest.xml"); } else { MxmlFilter.AddManifest(MxmlFilter.OLD_MX, as3Fmk + S + "Flex3" + S + "manifest.xml"); } } } foreach (string file in addLocales) { string swcItem = sdkLocales + S + file; if (!File.Exists(swcItem)) swcItem = fallbackLocale + S + file; AddPath(swcItem); } foreach (string file in addLibs) { if (File.Exists(file)) AddPath(file); else AddPath(sdkLibs + S + file); } // intrinsics (deprecated, excepted for FP10 Vector.<T>) string fp9cp = as3settings.AS3ClassPath + S + "FP9"; AddPath(PathHelper.ResolvePath(fp9cp)); if (majorVersion > 9) { string fp10cp = as3settings.AS3ClassPath + S + "FP" + majorVersion; AddPath(PathHelper.ResolvePath(fp10cp)); string fp101cp = as3settings.AS3ClassPath + S + "FP" + majorVersion + "." + minorVersion; AddPath(PathHelper.ResolvePath(fp101cp)); } // add external pathes List<PathModel> initCP = classPath; classPath = new List<PathModel>(); if (contextSetup.Classpath != null) { foreach (string cpath in contextSetup.Classpath) AddPath(cpath.Trim()); } // add library AddPath(PathHelper.LibraryDir + S + "AS3" + S + "classes"); // add user pathes from settings if (settings.UserClasspath != null && settings.UserClasspath.Length > 0) { foreach (string cpath in settings.UserClasspath) AddPath(cpath.Trim()); } // add initial pathes foreach (PathModel mpath in initCP) AddPath(mpath); // parse top-level elements InitTopLevelElements(); if (cFile != null) UpdateTopLevelElements(); // add current temporaty path if (temporaryPath != null) { string tempPath = temporaryPath; temporaryPath = null; SetTemporaryPath(tempPath); } FinalizeClasspath(); } /// <summary> /// Find any playerglobal.swc /// </summary> private string MatchPlayerGlobalAny(ref int majorVersion, ref int minorVersion, string sdkLibs) { char S = Path.DirectorySeparatorChar; string libPlayer = sdkLibs + S + "player"; string playerglobal = null; for (int i = minorVersion; i >= 0; i--) { string version = majorVersion + "." + i; if (Directory.Exists(libPlayer + S + version)) { minorVersion = i; return libPlayer + S + version + S + "playerglobal.swc"; } } if (playerglobal == null && Directory.Exists(libPlayer + S + majorVersion)) playerglobal = "player" + S + majorVersion + S + "playerglobal.swc"; if (playerglobal == null && majorVersion > 9) { int tempMajor = majorVersion - 1; int tempMinor = 9; playerglobal = MatchPlayerGlobalAny(ref tempMajor, ref tempMinor, sdkLibs); if (playerglobal != null) { majorVersion = tempMajor; minorVersion = tempMinor; return playerglobal; } } return playerglobal; } /// <summary> /// Find version-matching playerglobal.swc /// </summary> private string MatchPlayerGlobalExact(int majorVersion, int minorVersion, string sdkLibs) { string playerglobal = null; char S = Path.DirectorySeparatorChar; string libPlayer = sdkLibs + S + "player"; if (Directory.Exists(libPlayer + S + majorVersion + "." + minorVersion)) playerglobal = libPlayer + S + majorVersion + "." + minorVersion + S + "playerglobal.swc"; if (minorVersion == 0 && Directory.Exists(libPlayer + S + majorVersion)) playerglobal = libPlayer + S + majorVersion + S + "playerglobal.swc"; return playerglobal; } /// <summary> /// Build a list of file mask to explore the classpath /// </summary> public override string[] GetExplorerMask() { string[] mask = as3settings.AS3FileTypes; if (mask == null || mask.Length == 0 || (mask.Length == 1 && mask[1] == "")) { as3settings.AS3FileTypes = mask = new string[] { "*.as", "*.mxml" }; return mask; } else { List<string> patterns = new List<string>(); for (int i = 0; i < mask.Length; i++) { string m = mask[i]; if (string.IsNullOrEmpty(m)) continue; if (m[1] != '.' && m[0] != '.') m = '.' + m; if (m[0] != '*') m = '*' + m; patterns.Add(m); } return patterns.ToArray(); } } /// <summary> /// Parse a packaged library file /// </summary> /// <param name="path">Models owner</param> public override void ExploreVirtualPath(PathModel path) { if (path.WasExplored) { if (MxmlFilter.HasCatalog(path.Path)) MxmlFilter.AddCatalog(path.Path); if (path.FilesCount != 0) // already parsed return; } try { if (File.Exists(path.Path) && !path.WasExplored) { bool isRefresh = path.FilesCount > 0; //TraceManager.AddAsync("parse " + path.Path); lock (path) { path.WasExplored = true; SwfOp.ContentParser parser = new SwfOp.ContentParser(path.Path); parser.Run(); AbcConverter.Convert(parser, path, this); } // reset FCSH if (isRefresh) { EventManager.DispatchEvent(this, new DataEvent(EventType.Command, "ProjectManager.RestartFlexShell", path.Path)); } } } catch (Exception ex) { string message = TextHelper.GetString("Info.ExceptionWhileParsing"); TraceManager.AddAsync(message + " " + path.Path); TraceManager.AddAsync(ex.Message); TraceManager.AddAsync(ex.StackTrace); } } /// <summary> /// Delete current class's cached file /// </summary> public override void RemoveClassCompilerCache() { // not implemented - is there any? } /// <summary> /// Create a new file model without parsing file /// </summary> /// <param name="fileName">Full path</param> /// <returns>File model</returns> public override FileModel CreateFileModel(string fileName) { if (string.IsNullOrEmpty(fileName) || !File.Exists(fileName)) return new FileModel(fileName); fileName = PathHelper.GetLongPathName(fileName); if (mxmlEnabled && fileName.EndsWith(".mxml", StringComparison.OrdinalIgnoreCase)) { FileModel nFile = new FileModel(fileName); nFile.Context = this; nFile.HasFiltering = true; return nFile; } else return base.CreateFileModel(fileName); } private void GuessPackage(string fileName, FileModel nFile) { foreach(PathModel aPath in classPath) if (fileName.StartsWith(aPath.Path, StringComparison.OrdinalIgnoreCase)) { string local = fileName.Substring(aPath.Path.Length); char sep = Path.DirectorySeparatorChar; local = local.Substring(0, local.LastIndexOf(sep)).Replace(sep, '.'); nFile.Package = local.Length > 0 ? local.Substring(1) : ""; nFile.HasPackage = true; } } /// <summary> /// Build the file DOM /// </summary> /// <param name="filename">File path</param> protected override void GetCurrentFileModel(string fileName) { base.GetCurrentFileModel(fileName); } /// <summary> /// Refresh the file model /// </summary> /// <param name="updateUI">Update outline view</param> public override void UpdateCurrentFile(bool updateUI) { if (mxmlEnabled && cFile != null && cFile != FileModel.Ignore && cFile.FileName.EndsWith(".mxml", StringComparison.OrdinalIgnoreCase)) cFile.HasFiltering = true; base.UpdateCurrentFile(updateUI); if (cFile.HasFiltering) { MxmlComplete.mxmlContext = mxmlFilterContext; MxmlComplete.context = this; } } /// <summary> /// Update the class/member context for the given line number. /// Be carefull to restore the context after calling it with a custom line number /// </summary> /// <param name="line"></param> public override void UpdateContext(int line) { base.UpdateContext(line); } /// <summary> /// Called if a FileModel needs filtering /// - define inline AS3 ranges /// </summary> /// <param name="src"></param> /// <returns></returns> public override string FilterSource(string fileName, string src) { mxmlFilterContext = new MxmlFilterContext(); return MxmlFilter.FilterSource(Path.GetFileNameWithoutExtension(fileName), src, mxmlFilterContext); } /// <summary> /// Called if a FileModel needs filtering /// - modify parsed model /// </summary> /// <param name="model"></param> /// <returns></returns> public override void FilterSource(FileModel model) { GuessPackage(model.FileName, model); if (mxmlFilterContext != null) MxmlFilter.FilterSource(model, mxmlFilterContext); } #endregion #region syntax checking internal void OnFileOperation(NotifyEvent e) { timerCheck.Stop(); foreach (ITabbedDocument doc in PluginBase.MainForm.Documents) if (doc.FileName == fileWithSquiggles) ClearSquiggles(doc.SciControl); } public override void TrackTextChange(ScintillaNet.ScintillaControl sender, int position, int length, int linesAdded) { base.TrackTextChange(sender, position, length, linesAdded); if (as3settings != null && !as3settings.DisableLiveChecking && IsFileValid) { timerCheck.Stop(); timerCheck.Start(); } } private void timerCheck_Elapsed(object sender, ElapsedEventArgs e) { BackgroundSyntaxCheck(); } /// <summary> /// Checking syntax of current file /// </summary> private void BackgroundSyntaxCheck() { if (!IsFileValid) return; ScintillaNet.ScintillaControl sci = CurSciControl; if (sci == null) return; ClearSquiggles(sci); string src = CurSciControl.Text; string sdk = PluginBase.CurrentProject != null && PluginBase.CurrentProject.Language == "as3" ? PluginBase.CurrentProject.CurrentSDK : as3settings.GetDefaultSDK().Path; FlexShells.Instance.CheckAS3(CurrentFile, sdk, src); } private void ClearSquiggles(ScintillaNet.ScintillaControl sci) { if (sci == null) return; try { int es = sci.EndStyled; int mask = (1 << sci.StyleBits); sci.StartStyling(0, mask); sci.SetStyling(sci.TextLength, 0); sci.StartStyling(es, mask - 1); } finally { fileWithSquiggles = null; } } private void FlexShell_SyntaxError(string error) { if (!IsFileValid) return; Match m = re_syntaxError.Match(error); if (!m.Success) return; ITabbedDocument document = PluginBase.MainForm.CurrentDocument; if (document == null || !document.IsEditable) return; ScintillaNet.ScintillaControl sci = document.SplitSci1; ScintillaNet.ScintillaControl sci2 = document.SplitSci2; if (m.Groups["filename"].Value != CurrentFile) return; try { int line = int.Parse(m.Groups["line"].Value) - 1; if (sci.LineCount < line) return; int start = MBSafeColumn(sci, line, int.Parse(m.Groups["col"].Value) - 1); if (line == sci.LineCount && start == 0 && line > 0) start = -1; AddSquiggles(sci, line, start, start + 1); AddSquiggles(sci2, line, start, start + 1); } catch { } } /// <summary> /// Convert multibyte column to byte length /// </summary> private int MBSafeColumn(ScintillaNet.ScintillaControl sci, int line, int length) { String text = sci.GetLine(line) ?? ""; length = Math.Min(length, text.Length); return sci.MBSafeTextLength(text.Substring(0, length)); } private void AddSquiggles(ScintillaNet.ScintillaControl sci, int line, int start, int end) { if (sci == null) return; fileWithSquiggles = CurrentFile; int position = sci.PositionFromLine(line) + start; int es = sci.EndStyled; int mask = 1 << sci.StyleBits; sci.SetIndicStyle(0, (int)ScintillaNet.Enums.IndicatorStyle.Squiggle); sci.SetIndicFore(0, 0x000000ff); sci.StartStyling(position, mask); sci.SetStyling(end - start, mask); sci.StartStyling(es, mask - 1); } #endregion #region class resolution /// <summary> /// Evaluates the visibility of one given type from another. /// Caller is responsible of calling ResolveExtends() on 'inClass' /// </summary> /// <param name="inClass">Completion context</param> /// <param name="withClass">Completion target</param> /// <returns>Completion visibility</returns> public override Visibility TypesAffinity(ClassModel inClass, ClassModel withClass) { if (inClass == null || withClass == null) return Visibility.Public; // same file if (inClass.InFile == withClass.InFile) return Visibility.Public | Visibility.Internal | Visibility.Protected | Visibility.Private; // same package Visibility acc = Visibility.Public; if (inClass.InFile.Package == withClass.InFile.Package) acc |= Visibility.Internal; // inheritance affinity ClassModel tmp = inClass; while (!tmp.IsVoid()) { if (tmp.Type == withClass.Type) { acc |= Visibility.Protected; break; } tmp = tmp.Extends; } return acc; } /// <summary> /// Return the full project classes list /// </summary> /// <returns></returns> public override MemberList GetAllProjectClasses() { // from cache if (!completionCache.IsDirty && completionCache.AllTypes != null) return completionCache.AllTypes; MemberList fullList = new MemberList(); ClassModel aClass; MemberModel item; // public & internal classes string package = CurrentModel.Package; foreach (PathModel aPath in classPath) if (aPath.IsValid && !aPath.Updating) { aPath.ForeachFile((aFile) => { if (!aFile.HasPackage) return true; // skip aClass = aFile.GetPublicClass(); if (!aClass.IsVoid() && aClass.IndexType == null) { if (aClass.Access == Visibility.Public || (aClass.Access == Visibility.Internal && aFile.Package == package)) { item = aClass.ToMemberModel(); item.Name = item.Type; fullList.Add(item); } } if (aFile.Package.Length > 0 && aFile.Members.Count > 0) { foreach (MemberModel member in aFile.Members) { item = member.Clone() as MemberModel; item.Name = aFile.Package + "." + item.Name; fullList.Add(item); } } else if (aFile.Members.Count > 0) { foreach (MemberModel member in aFile.Members) { item = member.Clone() as MemberModel; fullList.Add(item); } } return true; }); } // void fullList.Add(new MemberModel(features.voidKey, features.voidKey, FlagType.Class | FlagType.Intrinsic, 0)); // private classes fullList.Add(GetPrivateClasses()); // in cache fullList.Sort(); completionCache.AllTypes = fullList; return fullList; } public override bool OnCompletionInsert(ScintillaNet.ScintillaControl sci, int position, string text, char trigger) { if (text == "Vector") { string insert = null; string line = sci.GetLine(sci.LineFromPosition(position)); Match m = Regex.Match(line, @"\svar\s+(?<varname>.+)\s*:\s*Vector\.<(?<indextype>.+)(?=(>\s*=))"); if (m.Success) { insert = String.Format(".<{0}>", m.Groups["indextype"].Value); } else { m = Regex.Match(line, @"\s*=\s*new"); if (m.Success) { ASResult result = ASComplete.GetExpressionType(sci, sci.PositionFromLine(sci.LineFromPosition(position)) + m.Index); if (result != null && !result.IsNull() && result.Member != null && result.Member.Type != null) { m = Regex.Match(result.Member.Type, @"(?<=<).+(?=>)"); if (m.Success) { insert = String.Format(".<{0}>", m.Value); } } } if (insert == null) { if (trigger == '.' || trigger == '(') return true; insert = ".<>"; sci.InsertText(position + text.Length, insert); sci.CurrentPos = position + text.Length + 2; sci.SetSel(sci.CurrentPos, sci.CurrentPos); ASComplete.HandleAllClassesCompletion(sci, "", false, true); return true; } } if (insert == null) return false; if (trigger == '.') { sci.InsertText(position + text.Length, insert.Substring(1)); sci.CurrentPos = position + text.Length; } else { sci.InsertText(position + text.Length, insert); sci.CurrentPos = position + text.Length + insert.Length; } sci.SetSel(sci.CurrentPos, sci.CurrentPos); return true; } return false; } /// <summary> /// Check if a type is already in the file's imports /// Throws an Exception if the type name is ambiguous /// (ie. same name as an existing import located in another package) /// </summary> /// <param name="member">Element to search in imports</param> /// <param name="atLine">Position in the file</param> public override bool IsImported(MemberModel member, int atLine) { FileModel cFile = ASContext.Context.CurrentModel; // same package is auto-imported string package = member.Type.Length > member.Name.Length ? member.Type.Substring(0, member.Type.Length - member.Name.Length - 1) : ""; if (package == cFile.Package) return true; return base.IsImported(member, atLine); } /// <summary> /// Retrieves a class model from its name /// </summary> /// <param name="cname">Class (short or full) name</param> /// <param name="inClass">Current file</param> /// <returns>A parsed class or an empty ClassModel if the class is not found</returns> public override ClassModel ResolveType(string cname, FileModel inFile) { // handle generic types if (cname != null && cname.IndexOf('<') > 0) { Match genType = re_genericType.Match(cname); if (genType.Success) return ResolveGenericType(genType.Groups["gen"].Value, genType.Groups["type"].Value, inFile); else return ClassModel.VoidClass; } return base.ResolveType(cname, inFile); } /// <summary> /// Retrieve/build typed copies of generic types /// </summary> private ClassModel ResolveGenericType(string baseType, string indexType, FileModel inFile) { ClassModel originalClass = base.ResolveType(baseType, inFile); if (originalClass.IsVoid()) return originalClass; ClassModel indexClass = ResolveType(indexType, inFile); if (indexClass.IsVoid()) return originalClass; indexType = indexClass.QualifiedName; FileModel aFile = originalClass.InFile; // is the type already cloned? foreach (ClassModel otherClass in aFile.Classes) if (otherClass.IndexType == indexType) return otherClass; // clone the type ClassModel aClass = originalClass.Clone() as ClassModel; aClass.Name = baseType + ".<" + indexType + ">"; aClass.IndexType = indexType; string typed = "<" + indexType + ">"; foreach (MemberModel member in aClass.Members) { if (member.Name == baseType) member.Name = baseType.Replace("<T>", typed); if (member.Type != null && member.Type.IndexOf('T') >= 0) { if (member.Type == "T") member.Type = indexType; else member.Type = member.Type.Replace("<T>", typed); } if (member.Parameters != null) { foreach (MemberModel param in member.Parameters) { if (param.Type != null && param.Type.IndexOf('T') >= 0) { if (param.Type == "T") param.Type = indexType; else param.Type = param.Type.Replace("<T>", typed); } } } } aFile.Classes.Add(aClass); return aClass; } protected MemberList GetPrivateClasses() { MemberList list = new MemberList(); // private classes foreach(ClassModel model in cFile.Classes) if (model.Access == Visibility.Private) { MemberModel item = model.ToMemberModel(); item.Type = item.Name; item.Access = Visibility.Private; list.Add(item); } // 'Class' members if (cClass != null) foreach (MemberModel member in cClass.Members) if (member.Type == "Class") list.Add(member); return list; } /// <summary> /// Prepare AS3 intrinsic known vars/methods/classes /// </summary> protected override void InitTopLevelElements() { string filename = "toplevel.as"; topLevel = new FileModel(filename); if (topLevel.Members.Search("this", 0, 0) == null) topLevel.Members.Add(new MemberModel("this", "", FlagType.Variable | FlagType.Intrinsic, Visibility.Public)); if (topLevel.Members.Search("super", 0, 0) == null) topLevel.Members.Add(new MemberModel("super", "", FlagType.Variable | FlagType.Intrinsic, Visibility.Public)); if (topLevel.Members.Search(features.voidKey, 0, 0) == null) topLevel.Members.Add(new MemberModel(features.voidKey, "", FlagType.Intrinsic, Visibility.Public)); topLevel.Members.Sort(); } #endregion #region Command line compiler /// <summary> /// Retrieve the context's default compiler path /// </summary> public override string GetCompilerPath() { return as3settings.GetDefaultSDK().Path ?? "Tools\\flexsdk"; } /// <summary> /// Check current file's syntax /// </summary> public override void CheckSyntax() { if (IsFileValid && cFile.InlinedIn == null) { PluginBase.MainForm.CallCommand("Save", null); string sdk = PluginBase.CurrentProject != null ? PluginBase.CurrentProject.CurrentSDK : PathHelper.ResolvePath(as3settings.GetDefaultSDK().Path); FlexShells.Instance.CheckAS3(cFile.FileName, sdk); } } /// <summary> /// Run MXMLC compiler in the current class's base folder with current classpath /// </summary> /// <param name="append">Additional comiler switches</param> public override void RunCMD(string append) { if (!IsCompilationTarget()) { MessageBar.ShowWarning(TextHelper.GetString("Info.InvalidClass")); return; } string command = (append ?? "") + " -- " + CurrentFile; FlexShells.Instance.RunMxmlc(command, as3settings.GetDefaultSDK().Path); } private bool IsCompilationTarget() { return (!MainForm.CurrentDocument.IsUntitled && CurrentModel.Version >= 3); } /// <summary> /// Calls RunCMD with additional parameters taken from the classes @mxmlc doc tag /// </summary> public override bool BuildCMD(bool failSilently) { if (!IsCompilationTarget()) { MessageBar.ShowWarning(TextHelper.GetString("Info.InvalidClass")); return false; } MainForm.CallCommand("SaveAllModified", null); string sdk = PluginBase.CurrentProject != null ? PluginBase.CurrentProject.CurrentSDK : as3settings.GetDefaultSDK().Path; FlexShells.Instance.QuickBuild(CurrentModel, sdk, failSilently, as3settings.PlayAfterBuild); return true; } #endregion } }
40.763969
144
0.507504
[ "MIT" ]
gamebytes/flashdevelop
External/Plugins/AS3Context/Context.cs
42,313
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 Xunit; namespace System.Text.Json.Serialization.Tests { public static partial class CustomConverterTests { [Fact] public static void MultipleConvertersInObjectArray() { const string expectedJson = @"[""?"",{""TypeDiscriminator"":1,""CreditLimit"":100,""Name"":""C""},null]"; var options = new JsonSerializerOptions(); options.Converters.Add(new MyBoolEnumConverter()); options.Converters.Add(new PersonConverterWithTypeDiscriminator()); Customer customer = new Customer(); customer.CreditLimit = 100; customer.Name = "C"; MyBoolEnum myBoolEnum = MyBoolEnum.Unknown; MyBoolEnum? myNullBoolEnum = null; string json = JsonSerializer.Serialize(new object[] { myBoolEnum, customer, myNullBoolEnum }, options); Assert.Equal(expectedJson, json); JsonElement jsonElement = JsonSerializer.Deserialize<JsonElement>(json, options); string jsonElementString = jsonElement.ToString(); Assert.Equal(expectedJson, jsonElementString); } [Fact] public static void OptionsArePassedToCreateConverter() { TestFactory factory = new TestFactory(); JsonSerializerOptions options = new JsonSerializerOptions { Converters = { factory } }; string json = JsonSerializer.Serialize("Test", options); Assert.Equal(@"""Test""", json); Assert.Same(options, factory.Options); } public class TestFactory : JsonConverterFactory { public JsonSerializerOptions Options { get; private set; } public override bool CanConvert(Type typeToConvert) => true; public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) { Options = options; return new SimpleConverter(); } public class SimpleConverter : JsonConverter<string> { public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { throw new NotImplementedException(); } public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) => writer.WriteStringValue(value); } } private class ConverterReturningNull : JsonConverter<Customer> { public override Customer Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { Assert.Equal(JsonTokenType.StartObject, reader.TokenType); bool rc = reader.Read(); Assert.True(rc); Assert.Equal(JsonTokenType.EndObject, reader.TokenType); return null; } public override void Write(Utf8JsonWriter writer, Customer value, JsonSerializerOptions options) { throw new NotSupportedException(); } } [Fact] public static void VerifyConverterWithTrailingWhitespace() { string json = "{} "; var options = new JsonSerializerOptions(); options.Converters.Add(new ConverterReturningNull()); byte[] utf8 = Encoding.UTF8.GetBytes(json); // The serializer will finish reading the whitespace and no exception will be thrown. Customer c = JsonSerializer.Deserialize<Customer>(utf8, options); Assert.Null(c); } [Fact] public static void VerifyConverterWithTrailingComments() { string json = "{} //"; byte[] utf8 = Encoding.UTF8.GetBytes(json); // Disallow comments var options = new JsonSerializerOptions(); options.Converters.Add(new ConverterReturningNull()); Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<Customer>(utf8, options)); // Skip comments options = new JsonSerializerOptions(); options.Converters.Add(new ConverterReturningNull()); options.ReadCommentHandling = JsonCommentHandling.Skip; Customer c = JsonSerializer.Deserialize<Customer>(utf8, options); Assert.Null(c); } } }
37.312
121
0.610206
[ "MIT" ]
06needhamt/runtime
src/libraries/System.Text.Json/tests/Serialization/CustomConverterTests/CustomConverterTests.cs
4,666
C#
using System; using UltimaOnline.Items; namespace UltimaOnline.Items { public class PlateBattleKabuto : BaseArmor { public override int BasePhysicalResistance { get { return 6; } } public override int BaseFireResistance { get { return 2; } } public override int BaseColdResistance { get { return 2; } } public override int BasePoisonResistance { get { return 2; } } public override int BaseEnergyResistance { get { return 3; } } public override int InitMinHits { get { return 60; } } public override int InitMaxHits { get { return 65; } } public override int AosStrReq { get { return 70; } } public override int OldStrReq { get { return 70; } } public override int ArmorBase { get { return 3; } } public override ArmorMaterialType MaterialType { get { return ArmorMaterialType.Plate; } } [Constructable] public PlateBattleKabuto() : base(0x2785) { Weight = 6.0; } public PlateBattleKabuto(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } }
31.826087
99
0.588798
[ "MIT" ]
netcode-gamer/game.ultimaonline.io
UltimaOnline.Data/Items/Armor/Plate/PlateBattleKabuto.cs
1,464
C#
namespace WFw.GeTui.Models.Message { /// <summary> /// 推送目标 /// </summary> public class Audience { /// <summary> /// 别名 /// </summary> public string[] Alias { get; set; } /// <summary> /// cid /// </summary> public string[] Cid { get; set; } } }
15.409091
43
0.424779
[ "MIT" ]
litesz/WFw
WFw.GeTui/Models/Push/Audience.cs
353
C#
using System; using System.Collections.Generic; using System.Linq; namespace VeryNaiveDatalog { /// <summary> /// A substitution (or environment) denotes a mapping from variables to terms. /// </summary> public class Substitution : Dictionary<Variable, ITerm> { public Substitution() {} public Substitution(Substitution that) : base(that) {} // The condition v != t is just to avoid inserting // redundant mappings like "x -> x". public new bool TryAdd(Variable v, ITerm t) => v != t && base.TryAdd(v, t); public override bool Equals(object? obj) => obj switch { Substitution that => this.ToHashSet().SetEquals(that), _ => false }; public override int GetHashCode() => this.Aggregate(0, (acc, p) => HashCode.Combine(acc, p.Key, p.Value)); } }
31.862069
114
0.575758
[ "Unlicense" ]
xavierpinho/VeryNaiveDatalog
VeryNaiveDatalog/Substitution.cs
924
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Text.Json; using Azure.Core; using Azure.ResourceManager.Models; using Azure.ResourceManager.Sql.Models; namespace Azure.ResourceManager.Sql { public partial class SqlJobData : IUtf8JsonSerializable { void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); writer.WritePropertyName("properties"); writer.WriteStartObject(); if (Optional.IsDefined(Description)) { writer.WritePropertyName("description"); writer.WriteStringValue(Description); } if (Optional.IsDefined(Schedule)) { writer.WritePropertyName("schedule"); writer.WriteObjectValue(Schedule); } writer.WriteEndObject(); writer.WriteEndObject(); } internal static SqlJobData DeserializeSqlJobData(JsonElement element) { ResourceIdentifier id = default; string name = default; ResourceType type = default; SystemData systemData = default; Optional<string> description = default; Optional<int> version = default; Optional<JobSchedule> schedule = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("id")) { id = new ResourceIdentifier(property.Value.GetString()); continue; } if (property.NameEquals("name")) { name = property.Value.GetString(); continue; } if (property.NameEquals("type")) { type = property.Value.GetString(); continue; } if (property.NameEquals("systemData")) { systemData = JsonSerializer.Deserialize<SystemData>(property.Value.ToString()); continue; } if (property.NameEquals("properties")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } foreach (var property0 in property.Value.EnumerateObject()) { if (property0.NameEquals("description")) { description = property0.Value.GetString(); continue; } if (property0.NameEquals("version")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } version = property0.Value.GetInt32(); continue; } if (property0.NameEquals("schedule")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } schedule = JobSchedule.DeserializeJobSchedule(property0.Value); continue; } } continue; } } return new SqlJobData(id, name, type, systemData, description.Value, Optional.ToNullable(version), schedule.Value); } } }
37.412844
127
0.464198
[ "MIT" ]
AikoBB/azure-sdk-for-net
sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/Models/SqlJobData.Serialization.cs
4,078
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 acm-pca-2017-08-22.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ACMPCA.Model { /// <summary> /// Container for the parameters to the GetCertificate operation. /// Retrieves a certificate from your private CA. The ARN of the certificate is returned /// when you call the <a>IssueCertificate</a> operation. You must specify both the ARN /// of your private CA and the ARN of the issued certificate when calling the <b>GetCertificate</b> /// operation. You can retrieve the certificate if it is in the <b>ISSUED</b> state. You /// can call the <a>CreateCertificateAuthorityAuditReport</a> operation to create a report /// that contains information about all of the certificates issued and revoked by your /// private CA. /// </summary> public partial class GetCertificateRequest : AmazonACMPCARequest { private string _certificateArn; private string _certificateAuthorityArn; /// <summary> /// Gets and sets the property CertificateArn. /// <para> /// The ARN of the issued certificate. The ARN contains the certificate serial number /// and must be in the following form: /// </para> /// /// <para> /// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i>/certificate/<i>286535153982981100925020015808220737245</i> /// </code> /// </para> /// </summary> [AWSProperty(Required=true, Min=5, Max=200)] public string CertificateArn { get { return this._certificateArn; } set { this._certificateArn = value; } } // Check to see if CertificateArn property is set internal bool IsSetCertificateArn() { return this._certificateArn != null; } /// <summary> /// Gets and sets the property CertificateAuthorityArn. /// <para> /// The Amazon Resource Name (ARN) that was returned when you called <a>CreateCertificateAuthority</a>. /// This must be of the form: /// </para> /// /// <para> /// <code>arn:aws:acm-pca:<i>region</i>:<i>account</i>:certificate-authority/<i>12345678-1234-1234-1234-123456789012</i> /// </code>. /// </para> /// </summary> [AWSProperty(Required=true, Min=5, Max=200)] public string CertificateAuthorityArn { get { return this._certificateAuthorityArn; } set { this._certificateAuthorityArn = value; } } // Check to see if CertificateAuthorityArn property is set internal bool IsSetCertificateAuthorityArn() { return this._certificateAuthorityArn != null; } } }
37.90625
188
0.643309
[ "Apache-2.0" ]
FoxBearBear/aws-sdk-net
sdk/src/Services/ACMPCA/Generated/Model/GetCertificateRequest.cs
3,639
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Fortnox.SDK; using Fortnox.SDK.Entities; using Fortnox.SDK.Search; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace FortnoxSDK.Tests.ConnectorTests { [TestClass] public class SupplierInvoiceTests { public FortnoxClient FortnoxClient = TestUtils.DefaultFortnoxClient; [TestMethod] public async Task Test_SupplierInvoice_CRUD() { #region Arrange var tmpSupplier = await FortnoxClient.SupplierConnector.CreateAsync(new Supplier() {Name = "TmpSupplier"}); var tmpArticle = await FortnoxClient.ArticleConnector.CreateAsync(new Article(){Description = "TmpArticle", PurchasePrice = 100}); #endregion Arrange var connector = FortnoxClient.SupplierInvoiceConnector; #region CREATE var newSupplierInvoice = new SupplierInvoice() { SupplierNumber = tmpSupplier.SupplierNumber, Comments = "InvoiceComments", InvoiceDate = new DateTime(2010,1,1), DueDate = new DateTime(2010,2,1), SalesType = SalesType.Stock, OCR = "123456789", Total = 5000, SupplierInvoiceRows = new List<SupplierInvoiceRow>() { new SupplierInvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, Quantity = 10, Price = 100}, new SupplierInvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, Quantity = 20, Price = 100}, new SupplierInvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, Quantity = 20, Price = 100} } }; var createdSupplierInvoice = await connector.CreateAsync(newSupplierInvoice); Assert.AreEqual("InvoiceComments", createdSupplierInvoice.Comments); Assert.AreEqual("TmpSupplier", createdSupplierInvoice.SupplierName); Assert.AreEqual(3 + 1, createdSupplierInvoice.SupplierInvoiceRows.Count); //3 + 1 => A row "Leverant�rsskulder" is created by default #endregion CREATE #region UPDATE createdSupplierInvoice.Comments = "UpdatedInvoiceComments"; var updatedSupplierInvoice = await connector.UpdateAsync(createdSupplierInvoice); Assert.AreEqual("UpdatedInvoiceComments", updatedSupplierInvoice.Comments); #endregion UPDATE #region READ / GET var retrievedSupplierInvoice = await connector.GetAsync(createdSupplierInvoice.GivenNumber); Assert.AreEqual("UpdatedInvoiceComments", retrievedSupplierInvoice.Comments); #endregion READ / GET #region DELETE //Not supported await connector.CancelAsync(createdSupplierInvoice.GivenNumber); var cancelledInvoice = await connector.GetAsync(createdSupplierInvoice.GivenNumber); Assert.AreEqual(true, cancelledInvoice.Cancelled); #endregion DELETE #region Delete arranged resources await FortnoxClient.SupplierConnector.DeleteAsync(tmpSupplier.SupplierNumber); await FortnoxClient.ArticleConnector.DeleteAsync(tmpArticle.ArticleNumber); #endregion Delete arranged resources } [TestMethod] public async Task Test_Find() { #region Arrange var tmpSupplier = await FortnoxClient.SupplierConnector.CreateAsync(new Supplier() { Name = "TmpSupplier" }); var tmpArticle = await FortnoxClient.ArticleConnector.CreateAsync(new Article() { Description = "TmpArticle", PurchasePrice = 100 }); #endregion Arrange var connector = FortnoxClient.SupplierInvoiceConnector; var newSupplierInvoice = new SupplierInvoice() { SupplierNumber = tmpSupplier.SupplierNumber, Comments = "InvoiceComments", InvoiceDate = new DateTime(2010, 1, 1), DueDate = new DateTime(2010, 2, 1), SalesType = SalesType.Stock, OCR = "123456789", Total = 5000, SupplierInvoiceRows = new List<SupplierInvoiceRow>() { new SupplierInvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, Quantity = 10, Price = 100}, new SupplierInvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, Quantity = 20, Price = 100}, new SupplierInvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, Quantity = 20, Price = 100} } }; //Add entries for (var i = 0; i < 5; i++) { await connector.CreateAsync(newSupplierInvoice); } //Apply base test filter var searchSettings = new SupplierInvoiceSearch(); searchSettings.SupplierNumber = tmpSupplier.SupplierNumber; var fullCollection = await connector.FindAsync(searchSettings); Assert.AreEqual(5, fullCollection.TotalResources); Assert.AreEqual(5, fullCollection.Entities.Count); Assert.AreEqual(1, fullCollection.TotalPages); Assert.AreEqual(tmpSupplier.SupplierNumber, fullCollection.Entities.First().SupplierNumber); //Apply Limit searchSettings.Limit = 2; var limitedCollection = await connector.FindAsync(searchSettings); Assert.AreEqual(5, limitedCollection.TotalResources); Assert.AreEqual(2, limitedCollection.Entities.Count); Assert.AreEqual(3, limitedCollection.TotalPages); //Delete entries (DELETE not supported) foreach (var invoice in fullCollection.Entities) await connector.CancelAsync(invoice.GivenNumber); #region Delete arranged resources await FortnoxClient.SupplierConnector.DeleteAsync(tmpSupplier.SupplierNumber); await FortnoxClient.ArticleConnector.DeleteAsync(tmpArticle.ArticleNumber); #endregion Delete arranged resources } [TestMethod] public async Task Test_Book() { #region Arrange var tmpSupplier = await FortnoxClient.SupplierConnector.CreateAsync(new Supplier() { Name = "TmpSupplier" }); var tmpArticle = await FortnoxClient.ArticleConnector.CreateAsync(new Article() { Description = "TmpArticle", PurchasePrice = 100 }); #endregion Arrange var connector = FortnoxClient.SupplierInvoiceConnector; var newSupplierInvoice = new SupplierInvoice() { SupplierNumber = tmpSupplier.SupplierNumber, Comments = "InvoiceComments", InvoiceDate = new DateTime(2020, 1, 1), DueDate = new DateTime(2020, 2, 1), SalesType = SalesType.Stock, OCR = "123456789", Total = 5000, SupplierInvoiceRows = new List<SupplierInvoiceRow>() { new SupplierInvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, Quantity = 10, Price = 100}, new SupplierInvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, Quantity = 20, Price = 100}, new SupplierInvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, Quantity = 20, Price = 100} } }; var createdSupplierInvoice = await connector.CreateAsync(newSupplierInvoice); //Act await connector.BookkeepAsync(createdSupplierInvoice.GivenNumber); var bookedInvoice = await connector.GetAsync(createdSupplierInvoice.GivenNumber); //Assert Assert.AreEqual(true, bookedInvoice.Booked); Assert.AreEqual(1, bookedInvoice.Vouchers.Count); Assert.AreEqual(ReferenceType.SupplierInvoice, bookedInvoice.Vouchers.First().ReferenceType); #region Delete arranged resources //Can not cancel booked invoice /* connector.Cancel(createdSupplierInvoice.GivenNumber); FortnoxClient.SupplierConnector.Delete(tmpSupplier.SupplierNumber); FortnoxClient.ArticleConnector.Delete(tmpArticle.ArticleNumber);*/ #endregion Delete arranged resources } } }
44.684211
145
0.631684
[ "MIT" ]
vanillajonathan/csharp-api-sdk
FortnoxSDK.Tests/ConnectorTests/SupplierInvoiceTests.cs
8,492
C#
/* * Copyright 2012-2017 The Pkcs11Interop Project * * 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. */ /* * Written for the Pkcs11Interop project by: * Jaroslav IMRICH <[email protected]> */ using System; using Net.Pkcs11Interop.Common; namespace Net.Pkcs11Interop.HighLevelAPI.MechanismParams { /// <summary> /// Parameters for the CKM_TLS_PRF mechanism /// </summary> public class CkTlsPrfParams : IMechanismParams, IDisposable { /// <summary> /// Flag indicating whether instance has been disposed /// </summary> private bool _disposed = false; /// <summary> /// Platform specific CkTlsPrfParams /// </summary> private HighLevelAPI40.MechanismParams.CkTlsPrfParams _params40 = null; /// <summary> /// Platform specific CkTlsPrfParams /// </summary> private HighLevelAPI41.MechanismParams.CkTlsPrfParams _params41 = null; /// <summary> /// Platform specific CkTlsPrfParams /// </summary> private HighLevelAPI80.MechanismParams.CkTlsPrfParams _params80 = null; /// <summary> /// Platform specific CkTlsPrfParams /// </summary> private HighLevelAPI81.MechanismParams.CkTlsPrfParams _params81 = null; /// <summary> /// Output of the operation /// </summary> public byte[] Output { get { if (this._disposed) throw new ObjectDisposedException(this.GetType().FullName); if (Platform.UnmanagedLongSize == 4) return (Platform.StructPackingSize == 0) ? _params40.Output : _params41.Output; else return (Platform.StructPackingSize == 0) ? _params80.Output : _params81.Output; } } /// <summary> /// Initializes a new instance of the CkTlsPrfParams class. /// </summary> /// <param name='seed'>Input seed</param> /// <param name='label'>Identifying label</param> /// <param name='outputLen'>Length in bytes that the output to be created shall have</param> public CkTlsPrfParams(byte[] seed, byte[] label, ulong outputLen) { if (Platform.UnmanagedLongSize == 4) { if (Platform.StructPackingSize == 0) _params40 = new HighLevelAPI40.MechanismParams.CkTlsPrfParams(seed, label, Convert.ToUInt32(outputLen)); else _params41 = new HighLevelAPI41.MechanismParams.CkTlsPrfParams(seed, label, Convert.ToUInt32(outputLen)); } else { if (Platform.StructPackingSize == 0) _params80 = new HighLevelAPI80.MechanismParams.CkTlsPrfParams(seed, label, outputLen); else _params81 = new HighLevelAPI81.MechanismParams.CkTlsPrfParams(seed, label, outputLen); } } #region IMechanismParams /// <summary> /// Returns managed object that can be marshaled to an unmanaged block of memory /// </summary> /// <returns>A managed object holding the data to be marshaled. This object must be an instance of a formatted class.</returns> public object ToMarshalableStructure() { if (this._disposed) throw new ObjectDisposedException(this.GetType().FullName); if (Platform.UnmanagedLongSize == 4) return (Platform.StructPackingSize == 0) ? _params40.ToMarshalableStructure() : _params41.ToMarshalableStructure(); else return (Platform.StructPackingSize == 0) ? _params80.ToMarshalableStructure() : _params81.ToMarshalableStructure(); } #endregion #region IDisposable /// <summary> /// Disposes object /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Disposes object /// </summary> /// <param name="disposing">Flag indicating whether managed resources should be disposed</param> protected virtual void Dispose(bool disposing) { if (!this._disposed) { if (disposing) { // Dispose managed objects if (_params40 != null) { _params40.Dispose(); _params40 = null; } if (_params41 != null) { _params41.Dispose(); _params41 = null; } if (_params80 != null) { _params80.Dispose(); _params80 = null; } if (_params81 != null) { _params81.Dispose(); _params81 = null; } } // Dispose unmanaged objects _disposed = true; } } /// <summary> /// Class destructor that disposes object if caller forgot to do so /// </summary> ~CkTlsPrfParams() { Dispose(false); } #endregion } }
33.624309
135
0.539763
[ "Apache-2.0" ]
arkkadin/pkcs11Interop
src/Pkcs11Interop/Pkcs11Interop/HighLevelAPI/MechanismParams/CkTlsPrfParams.cs
6,086
C#
using Microsoft.AspNetCore.Identity; using System; using System.Collections.Generic; using System.Text; namespace CleanBlog.Domain.Identity { public class Role : IdentityRole<Guid> { public Role(string name) { Name = name; } public virtual ICollection<UserRole> UserRoles { get; set; } } }
20.470588
68
0.646552
[ "MIT" ]
alijam93/CleanBlog
src/CleanBlog.Domain/Identity/Role.cs
350
C#
using System.Collections.Generic; using System.Threading.Tasks; using Nop.Core; using Nop.Core.Domain.Catalog; namespace Nop.Services.Catalog { /// <summary> /// Specification attribute service interface /// </summary> public partial interface ISpecificationAttributeService { #region Specification attribute group /// <summary> /// Gets a specification attribute group /// </summary> /// <param name="specificationAttributeGroupId">The specification attribute group identifier</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the specification attribute group /// </returns> Task<SpecificationAttributeGroup> GetSpecificationAttributeGroupByIdAsync(int specificationAttributeGroupId); /// <summary> /// Gets specification attribute groups /// </summary> /// <param name="pageIndex">Page index</param> /// <param name="pageSize">Page size</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the specification attribute groups /// </returns> Task<IPagedList<SpecificationAttributeGroup>> GetSpecificationAttributeGroupsAsync(int pageIndex = 0, int pageSize = int.MaxValue); /// <summary> /// Gets product specification attribute groups /// </summary> /// <param name="productId">Product identifier</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the specification attribute groups /// </returns> Task<IList<SpecificationAttributeGroup>> GetProductSpecificationAttributeGroupsAsync(int productId); /// <summary> /// Deletes a specification attribute group /// </summary> /// <param name="specificationAttributeGroup">The specification attribute group</param> /// <returns>A task that represents the asynchronous operation</returns> Task DeleteSpecificationAttributeGroupAsync(SpecificationAttributeGroup specificationAttributeGroup); /// <summary> /// Inserts a specification attribute group /// </summary> /// <param name="specificationAttributeGroup">The specification attribute group</param> /// <returns>A task that represents the asynchronous operation</returns> Task InsertSpecificationAttributeGroupAsync(SpecificationAttributeGroup specificationAttributeGroup); /// <summary> /// Updates the specification attribute group /// </summary> /// <param name="specificationAttributeGroup">The specification attribute group</param> /// <returns>A task that represents the asynchronous operation</returns> Task UpdateSpecificationAttributeGroupAsync(SpecificationAttributeGroup specificationAttributeGroup); #endregion #region Specification attribute /// <summary> /// Gets a specification attribute /// </summary> /// <param name="specificationAttributeId">The specification attribute identifier</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the specification attribute /// </returns> Task<SpecificationAttribute> GetSpecificationAttributeByIdAsync(int specificationAttributeId); /// <summary> /// Gets specification attributes /// </summary> /// <param name="specificationAttributeIds">The specification attribute identifiers</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the specification attributes /// </returns> Task<IList<SpecificationAttribute>> GetSpecificationAttributeByIdsAsync(int[] specificationAttributeIds); /// <summary> /// Gets specification attributes /// </summary> /// <param name="pageIndex">Page index</param> /// <param name="pageSize">Page size</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the specification attributes /// </returns> Task<IPagedList<SpecificationAttribute>> GetSpecificationAttributesAsync(int pageIndex = 0, int pageSize = int.MaxValue); /// <summary> /// Gets specification attributes that have options /// </summary> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the specification attributes that have available options /// </returns> Task<IList<SpecificationAttribute>> GetSpecificationAttributesWithOptionsAsync(); /// <summary> /// Gets specification attributes by group identifier /// </summary> /// <param name="specificationAttributeGroupId">The specification attribute group identifier</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the specification attributes /// </returns> Task<IList<SpecificationAttribute>> GetSpecificationAttributesByGroupIdAsync(int? specificationAttributeGroupId = null); /// <summary> /// Deletes a specification attribute /// </summary> /// <param name="specificationAttribute">The specification attribute</param> /// <returns>A task that represents the asynchronous operation</returns> Task DeleteSpecificationAttributeAsync(SpecificationAttribute specificationAttribute); /// <summary> /// Deletes specifications attributes /// </summary> /// <param name="specificationAttributes">Specification attributes</param> /// <returns>A task that represents the asynchronous operation</returns> Task DeleteSpecificationAttributesAsync(IList<SpecificationAttribute> specificationAttributes); /// <summary> /// Inserts a specification attribute /// </summary> /// <param name="specificationAttribute">The specification attribute</param> /// <returns>A task that represents the asynchronous operation</returns> Task InsertSpecificationAttributeAsync(SpecificationAttribute specificationAttribute); /// <summary> /// Updates the specification attribute /// </summary> /// <param name="specificationAttribute">The specification attribute</param> /// <returns>A task that represents the asynchronous operation</returns> Task UpdateSpecificationAttributeAsync(SpecificationAttribute specificationAttribute); #endregion #region Specification attribute option /// <summary> /// Gets a specification attribute option /// </summary> /// <param name="specificationAttributeOption">The specification attribute option</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the specification attribute option /// </returns> Task<SpecificationAttributeOption> GetSpecificationAttributeOptionByIdAsync(int specificationAttributeOption); /// <summary> /// Get specification attribute options by identifiers /// </summary> /// <param name="specificationAttributeOptionIds">Identifiers</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the specification attribute options /// </returns> Task<IList<SpecificationAttributeOption>> GetSpecificationAttributeOptionsByIdsAsync(int[] specificationAttributeOptionIds); /// <summary> /// Gets a specification attribute option by specification attribute id /// </summary> /// <param name="specificationAttributeId">The specification attribute identifier</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the specification attribute option /// </returns> Task<IList<SpecificationAttributeOption>> GetSpecificationAttributeOptionsBySpecificationAttributeAsync(int specificationAttributeId); /// <summary> /// Deletes a specification attribute option /// </summary> /// <param name="specificationAttributeOption">The specification attribute option</param> /// <returns>A task that represents the asynchronous operation</returns> Task DeleteSpecificationAttributeOptionAsync(SpecificationAttributeOption specificationAttributeOption); /// <summary> /// Inserts a specification attribute option /// </summary> /// <param name="specificationAttributeOption">The specification attribute option</param> /// <returns>A task that represents the asynchronous operation</returns> Task InsertSpecificationAttributeOptionAsync(SpecificationAttributeOption specificationAttributeOption); /// <summary> /// Updates the specification attribute /// </summary> /// <param name="specificationAttributeOption">The specification attribute option</param> /// <returns>A task that represents the asynchronous operation</returns> Task UpdateSpecificationAttributeOptionAsync(SpecificationAttributeOption specificationAttributeOption); /// <summary> /// Returns a list of IDs of not existing specification attribute options /// </summary> /// <param name="attributeOptionIds">The IDs of the attribute options to check</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the list of IDs not existing specification attribute options /// </returns> Task<int[]> GetNotExistingSpecificationAttributeOptionsAsync(int[] attributeOptionIds); /// <summary> /// Gets the filtrable specification attribute options by category id /// </summary> /// <param name="categoryId">The category id</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the specification attribute options /// </returns> Task<IList<SpecificationAttributeOption>> GetFiltrableSpecificationAttributeOptionsByCategoryIdAsync(int categoryId); /// <summary> /// Gets the filtrable specification attribute options by manufacturer id /// </summary> /// <param name="manufacturerId">The manufacturer id</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the specification attribute options /// </returns> Task<IList<SpecificationAttributeOption>> GetFiltrableSpecificationAttributeOptionsByManufacturerIdAsync(int manufacturerId); #endregion #region Product specification attribute /// <summary> /// Deletes a product specification attribute mapping /// </summary> /// <param name="productSpecificationAttribute">Product specification attribute</param> /// <returns>A task that represents the asynchronous operation</returns> Task DeleteProductSpecificationAttributeAsync(ProductSpecificationAttribute productSpecificationAttribute); /// <summary> /// Gets a product specification attribute mapping collection /// </summary> /// <param name="productId">Product identifier; 0 to load all records</param> /// <param name="specificationAttributeOptionId">Specification attribute option identifier; 0 to load all records</param> /// <param name="allowFiltering">0 to load attributes with AllowFiltering set to false, 1 to load attributes with AllowFiltering set to true, null to load all attributes</param> /// <param name="showOnProductPage">0 to load attributes with ShowOnProductPage set to false, 1 to load attributes with ShowOnProductPage set to true, null to load all attributes</param> /// <param name="specificationAttributeGroupId">Specification attribute group identifier; 0 to load all records; null to load attributes without group</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the product specification attribute mapping collection /// </returns> Task<IList<ProductSpecificationAttribute>> GetProductSpecificationAttributesAsync(int productId = 0, int specificationAttributeOptionId = 0, bool? allowFiltering = null, bool? showOnProductPage = null, int? specificationAttributeGroupId = 0); /// <summary> /// Gets a product specification attribute mapping /// </summary> /// <param name="productSpecificationAttributeId">Product specification attribute mapping identifier</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the product specification attribute mapping /// </returns> Task<ProductSpecificationAttribute> GetProductSpecificationAttributeByIdAsync(int productSpecificationAttributeId); /// <summary> /// Inserts a product specification attribute mapping /// </summary> /// <param name="productSpecificationAttribute">Product specification attribute mapping</param> /// <returns>A task that represents the asynchronous operation</returns> Task InsertProductSpecificationAttributeAsync(ProductSpecificationAttribute productSpecificationAttribute); /// <summary> /// Updates the product specification attribute mapping /// </summary> /// <param name="productSpecificationAttribute">Product specification attribute mapping</param> /// <returns>A task that represents the asynchronous operation</returns> Task UpdateProductSpecificationAttributeAsync(ProductSpecificationAttribute productSpecificationAttribute); /// <summary> /// Gets a count of product specification attribute mapping records /// </summary> /// <param name="productId">Product identifier; 0 to load all records</param> /// <param name="specificationAttributeOptionId">The specification attribute option identifier; 0 to load all records</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the count /// </returns> Task<int> GetProductSpecificationAttributeCountAsync(int productId = 0, int specificationAttributeOptionId = 0); /// <summary> /// Get mapped products for specification attribute /// </summary> /// <param name="specificationAttributeId">The specification attribute identifier</param> /// <param name="pageIndex">Page index</param> /// <param name="pageSize">Page size</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the products /// </returns> Task<IPagedList<Product>> GetProductsBySpecificationAttributeIdAsync(int specificationAttributeId, int pageIndex, int pageSize); #endregion } }
50.090323
194
0.683475
[ "CC0-1.0" ]
peterthomet/BioPuur
nopCommerce 4.4/src/Libraries/Nop.Services/Catalog/ISpecificationAttributeService.cs
15,530
C#
using System; using Aop.Api.Domain; using System.Collections.Generic; using Aop.Api.Response; namespace Aop.Api.Request { /// <summary> /// AOP API: alipay.eco.edu.kt.settleinfo.query /// </summary> public class AlipayEcoEduKtSettleinfoQueryRequest : IAopRequest<AlipayEcoEduKtSettleinfoQueryResponse> { /// <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; private Dictionary<string, string> udfParams; //add user-defined text parameters 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 "alipay.eco.edu.kt.settleinfo.query"; } public void SetApiVersion(string apiVersion){ this.apiVersion=apiVersion; } public string GetApiVersion(){ return this.apiVersion; } public void PutOtherTextParam(string key, string value) { if(this.udfParams == null) { this.udfParams = new Dictionary<string, string>(); } this.udfParams.Add(key, value); } public IDictionary<string, string> GetParameters() { AopDictionary parameters = new AopDictionary(); parameters.Add("biz_content", this.BizContent); if(udfParams != null) { parameters.AddAll(this.udfParams); } return parameters; } public AopObject GetBizModel() { return this.bizModel; } public void SetBizModel(AopObject bizModel) { this.bizModel = bizModel; } #endregion } }
25.846774
107
0.564431
[ "Apache-2.0" ]
554393109/alipay-sdk-net-all
AlipaySDKNet.Standard/Request/AlipayEcoEduKtSettleinfoQueryRequest.cs
3,227
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using Internal.TypeSystem; using ILCompiler.DependencyAnalysis; using Debug = System.Diagnostics.Debug; namespace ILCompiler { /// <summary> /// Structure that specifies how a generic dictionary lookup should be performed. /// </summary> public struct GenericDictionaryLookup { private const short UseHelperOffset = -1; private readonly object _helperObject; private readonly short _offset1; private readonly short _offset2; private readonly bool _indirectLastOffset; /// <summary> /// Gets the information about the source of the generic context for shared code. /// </summary> public readonly GenericContextSource ContextSource; /// <summary> /// Gets the target object of the lookup. Only valid when <see cref="UseHelper"/> is true. /// This is typically a <see cref="TypeDesc"/> whose <see cref="TypeDesc.IsRuntimeDeterminedSubtype"/> /// is true, a <see cref="FieldDesc"/> on a runtime determined type, a <see cref="MethodDesc"/>, or /// a <see cref="DelegateCreationInfo"/>. /// </summary> public object HelperObject { get { Debug.Assert(_offset1 == UseHelperOffset); return _helperObject; } } /// <summary> /// Gets the ID of the helper to use if <see cref="UseHelper"/> is true. /// </summary> public ReadyToRunHelperId HelperId { get { Debug.Assert(_offset1 == UseHelperOffset); return (ReadyToRunHelperId)_offset2; } } /// <summary> /// Gets a value indicating whether the lookup needs to be performed by calling a helper method. /// </summary> public bool UseHelper { get { return _offset1 == UseHelperOffset; } } /// <summary> /// Gets the number of indirections to follow. Only valid if <see cref="UseHelper"/> is false. /// </summary> public int NumberOfIndirections { get { Debug.Assert(!UseHelper); return ContextSource == GenericContextSource.MethodParameter ? 1 : 2; } } public int this[int index] { get { Debug.Assert(!UseHelper); Debug.Assert(index < NumberOfIndirections); switch (index) { case 0: return _offset1; case 1: return _offset2; } // Should be unreachable. throw new NotSupportedException(); } } public bool IndirectLastOffset { get { Debug.Assert(!UseHelper); return _indirectLastOffset; } } private GenericDictionaryLookup(GenericContextSource contextSource, int offset1, int offset2, object helperObject, bool indirectLastOffset) { ContextSource = contextSource; _offset1 = checked((short)offset1); _offset2 = checked((short)offset2); _helperObject = helperObject; _indirectLastOffset = indirectLastOffset; } public static GenericDictionaryLookup CreateFixedLookup(GenericContextSource contextSource, int offset1, int offset2 = UseHelperOffset, bool indirectLastOffset = false) { Debug.Assert(offset1 != UseHelperOffset); return new GenericDictionaryLookup(contextSource, offset1, offset2, null, indirectLastOffset); } public static GenericDictionaryLookup CreateHelperLookup(GenericContextSource contextSource, ReadyToRunHelperId helperId, object helperObject) { return new GenericDictionaryLookup(contextSource, UseHelperOffset, checked((short)helperId), helperObject, indirectLastOffset: false); } } /// <summary> /// Specifies to source of the generic context. /// </summary> public enum GenericContextSource { /// <summary> /// Generic context is specified by a hidden parameter that has a method dictionary. /// </summary> MethodParameter, /// <summary> /// Generic context is specified by a hidden parameter that has a type. /// </summary> TypeParameter, /// <summary> /// Generic context is specified implicitly by the `this` object. /// </summary> ThisObject, } }
32.370861
176
0.574264
[ "MIT" ]
333fred/runtime
src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/GenericDictionaryLookup.cs
4,888
C#
namespace Nager.Country.Translation.CountryInfos { /// <summary> /// Malaysia /// </summary> public class MalaysiaCountryTranslation : ICountryTranslation { ///<inheritdoc/> public TranslationInfo[] Translations => new [] { new TranslationInfo(LanguageCode.AR, "ماليزيا"), new TranslationInfo(LanguageCode.AZ, "Malayziya"), new TranslationInfo(LanguageCode.BE, "Малайзія"), new TranslationInfo(LanguageCode.BG, "Малайзия"), new TranslationInfo(LanguageCode.BS, "Malezija"), new TranslationInfo(LanguageCode.CA, "Malàisia"), new TranslationInfo(LanguageCode.CS, "Malajsie"), new TranslationInfo(LanguageCode.DA, "Malaysia"), new TranslationInfo(LanguageCode.DE, "Malaysia"), new TranslationInfo(LanguageCode.EL, "Μαλαισία"), new TranslationInfo(LanguageCode.EN, "Malaysia"), new TranslationInfo(LanguageCode.ES, "Malasia"), new TranslationInfo(LanguageCode.ET, "Malaisia"), new TranslationInfo(LanguageCode.FA, "مالزی"), new TranslationInfo(LanguageCode.FI, "Malesia"), new TranslationInfo(LanguageCode.FR, "Malaisie"), new TranslationInfo(LanguageCode.HE, "מלזיה"), new TranslationInfo(LanguageCode.HR, "Malezija"), new TranslationInfo(LanguageCode.HU, "Malajzia"), new TranslationInfo(LanguageCode.HY, "Մալայզիա"), new TranslationInfo(LanguageCode.ID, "Malaysia"), new TranslationInfo(LanguageCode.IT, "Malesia"), new TranslationInfo(LanguageCode.JA, "マレーシア"), new TranslationInfo(LanguageCode.KA, "მალაიზია"), new TranslationInfo(LanguageCode.KK, "Малайзия"), new TranslationInfo(LanguageCode.KO, "말레이시아"), new TranslationInfo(LanguageCode.KY, "Малайзия"), new TranslationInfo(LanguageCode.LT, "Malaizija"), new TranslationInfo(LanguageCode.LV, "Malaizija"), new TranslationInfo(LanguageCode.MK, "Малезија"), new TranslationInfo(LanguageCode.MN, "Малайз"), new TranslationInfo(LanguageCode.NB, "Malaysia"), new TranslationInfo(LanguageCode.NL, "Maleisië"), new TranslationInfo(LanguageCode.NN, "Malaysia"), new TranslationInfo(LanguageCode.PL, "Malezja"), new TranslationInfo(LanguageCode.PT, "Malásia"), new TranslationInfo(LanguageCode.RO, "Malaysia"), new TranslationInfo(LanguageCode.RU, "Малайзия"), new TranslationInfo(LanguageCode.SK, "Malajzia"), new TranslationInfo(LanguageCode.SL, "Malezija"), new TranslationInfo(LanguageCode.SR, "Малезија"), new TranslationInfo(LanguageCode.SV, "Malaysia"), new TranslationInfo(LanguageCode.TR, "Malezya"), new TranslationInfo(LanguageCode.UK, "Малайзія"), new TranslationInfo(LanguageCode.UZ, "Malayziya"), new TranslationInfo(LanguageCode.ZH, "马来西亚"), }; } }
51.262295
65
0.635433
[ "MIT" ]
OpenBoxLab/Nager.Country
src/Nager.Country.Translation/CountryTranslations/MalaysiaCountryTranslation.cs
3,277
C#
using System; using System.Collections.Generic; using UnityEngine; namespace UnityEditor.Experimental.Rendering.Universal.Path2D { internal class MultipleEditablePathController : IEditablePathController { private IEditablePathController m_Controller = new EditablePathController(); private List<IEditablePath> m_Paths = new List<IEditablePath>(); private float m_ClosestDistance = float.MaxValue; private IEditablePath m_ClosestPath; public IEditablePath editablePath { get { return m_Controller.editablePath; } set { m_Controller.editablePath = value; } } public IEditablePath closestEditablePath { get; private set; } public ISnapping<Vector3> snapping { get { return m_Controller.snapping; } set { m_Controller.snapping = value; } } public bool enableSnapping { get { return m_Controller.enableSnapping; } set { m_Controller.enableSnapping = value; } } public void ClearPaths() { m_Paths.Clear(); } public void AddPath(IEditablePath path) { if (!m_Paths.Contains(path)) m_Paths.Add(path); } public void RemovePath(IEditablePath path) { m_Paths.Remove(path); } public void RegisterUndo(string name) { var current = editablePath; ForEach((s) => { editablePath = s; m_Controller.RegisterUndo(name); }); editablePath = current; } public void ClearSelection() { var current = editablePath; ForEach((s) => { editablePath = s; m_Controller.ClearSelection(); }); editablePath = current; } public void SelectPoint(int index, bool select) { m_Controller.SelectPoint(index, select); } public void CreatePoint(int index, Vector3 position) { m_Controller.CreatePoint(index, position); } public void RemoveSelectedPoints() { var current = editablePath; ForEach((s) => { editablePath = s; m_Controller.RemoveSelectedPoints(); }); editablePath = current; } public void MoveSelectedPoints(Vector3 delta) { var current = editablePath; ForEach((s) => { editablePath = s; m_Controller.MoveSelectedPoints(delta); }); editablePath = current; } public void MoveEdge(int index, Vector3 delta) { m_Controller.MoveEdge(index, delta); } public void SetLeftTangent(int index, Vector3 position, bool setToLinear, bool mirror, Vector3 cachedRightTangent) { m_Controller.SetLeftTangent(index, position, setToLinear, mirror, cachedRightTangent); } public void SetRightTangent(int index, Vector3 position, bool setToLinear, bool mirror, Vector3 cachedLeftTangent) { m_Controller.SetRightTangent(index, position, setToLinear, mirror, cachedLeftTangent); } public void ClearClosestPath() { m_ClosestDistance = float.MaxValue; closestEditablePath = null; } public void AddClosestPath(float distance) { if (distance <= m_ClosestDistance) { m_ClosestDistance = distance; closestEditablePath = editablePath; } } private void ForEach(Action<IEditablePath> action) { foreach(var path in m_Paths) { if (path == null) continue; action(path); } } } }
27.344156
123
0.523391
[ "MIT" ]
AlePPisa/GameJamPractice1
Cellular/Library/PackageCache/[email protected]/Editor/2D/ShapeEditor/EditablePath/MultipleEditablePathController.cs
4,211
C#
namespace BirdAtlasMaui.API.Models { public enum HabitatType { Forest, Grassland, Tundra, Desert, Wetland, Ocean, UrbanSuburban } }
16.307692
36
0.490566
[ "MIT" ]
AppCreativity/BirdAtlas
frontend_maui/BirdAtlasMaui/Models/HabitatType.cs
214
C#
using System.Collections.Generic; using Newtonsoft.Json; namespace io.nem1.sdk.Model.Wallet { public class WalletAccount { [JsonProperty("brain")] public bool Brain { get; set; } [JsonProperty("algo")] public string Algo { get; set; } [JsonProperty("encrypted")] public string Encrypted { get; set; } [JsonProperty("iv")] public string Iv { get; set; } [JsonProperty("address")] public string Address { get; set; } [JsonProperty("label")] public string Label { get; set; } [JsonProperty("network")] public int Network { get; set; } [JsonProperty("child")] public string Child { get; set; } } public class WalletAccounts { [JsonProperty("account")] public List<WalletAccount> Account { get; set; } } public class WalletObject { [JsonProperty("privateKey")] public string PrivateKey { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("accounts")] public WalletAccounts Accounts { get; set; } } }
22.901961
56
0.572774
[ "Apache-2.0" ]
LykkeCity/nem1-sdk-csharp
src/nem1-sdk/src/Model/Wallet/WalletObject.cs
1,170
C#
namespace WSCT.Fake.TB100Like.Core { internal class Constants { public const byte INS_GENERATE_RANDOM = 0xC4; public const byte INS_CREATE_FILE = 0xE0; public const byte INS_DELETE_FILE = 0xE4; public const byte INS_SELECT = 0xA4; public const byte INS_FSEARCH = 0xA0; public const byte INS_READ_BINARY = 0xB0; public const byte INS_WRITE_BINARY = 0xD0; public const byte INS_ERASE = 0x0E; public const byte INS_GET_DATA = 0xCA; public const byte INS_PUT_DATA = 0xDA; // TODO: Remove these constants. public static byte P1_CREATE_FILE_DF = 0x01; public static byte P1_CREATE_FILE_EF = 0x02; /// <summary> /// Response status: Not enough memory space in the file = 6A84 /// </summary> public const short SW_NOT_ENOUGH_SPACE_IN_FILE = 0x6A84; public const short SW_DATA_NOT_FOUND = 0x6A88; internal static readonly byte[] MF_HEADER = new byte[] { 0x3F, 0x00, 0x02, 0xA1, 0xFF, 0xFF, 0x9E, 0x81 }; public static readonly byte[] FCI_APPLET = new byte[] { (byte)'T', (byte)'B', (byte)'1', (byte)'0', (byte)'0', (byte)'L', (byte)'I', (byte)'K', (byte)'E' }; internal const short FILESYSTEM_SIZE = 0x02A1; internal const byte DF_MAX = 0x08; internal const byte EF_MAX = 0x10; } }
40.411765
164
0.637555
[ "MIT" ]
wsct/WSCT-Fake-TB100Like
WSCT.Fake.TB100Like/Core/Constants.cs
1,376
C#
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace Security { public class RegisterModelBase<T> : PageModel { public RegisterModelBase ( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, ILogger<T> logger, IEmailSender emailSender ) { this.UserManager = userManager; this.SignInManager = signInManager; this.Logger = logger; this.EmailSender = emailSender; } protected readonly SignInManager<ApplicationUser> SignInManager; protected readonly UserManager<ApplicationUser> UserManager; protected readonly ILogger<T> Logger; protected readonly IEmailSender EmailSender; [BindProperty] public UserRegistrationViewModel UserRegistrationViewModel { get; set; } protected ApplicationUser GetApplicationUser() { var user = new ApplicationUser(); user.UserName = this.UserRegistrationViewModel.Email; user.Email = this.UserRegistrationViewModel.Email; user.FirstName = this.UserRegistrationViewModel.FirstName; user.LastName = this.UserRegistrationViewModel.LastName; user.City = this.UserRegistrationViewModel.City; user.Occupation = this.UserRegistrationViewModel.Occupation; return user; } } }
33.612245
81
0.653916
[ "MIT" ]
pragmatic-applications/AspNet_Host_Service
Lib_Host_Service/Security/RegisterModelBase.cs
1,649
C#
// Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; namespace Hazelcast.IO.Serialization { [Serializable] internal class IncompatibleClassChangeError : SystemException { } internal class MorphingPortableReader : DefaultPortableReader { public MorphingPortableReader(PortableSerializer serializer, IBufferObjectDataInput input, IClassDefinition cd) : base(serializer, input, cd) { } /// <exception cref="System.IO.IOException"></exception> public override bool ReadBoolean(string fieldName) { var fd = Cd.GetField(fieldName); if (fd == null) { return false; } if (fd.GetFieldType() != FieldType.Boolean) { throw new IncompatibleClassChangeError(); } return base.ReadBoolean(fieldName); } /// <exception cref="System.IO.IOException"></exception> public override byte ReadByte(string fieldName) { var fd = Cd.GetField(fieldName); if (fd == null) { return 0; } if (fd.GetFieldType() != FieldType.Byte) { throw new IncompatibleClassChangeError(); } return base.ReadByte(fieldName); } /// <exception cref="System.IO.IOException"></exception> public override byte[] ReadByteArray(string fieldName) { var fd = Cd.GetField(fieldName); if (fd == null) { return null; } if (fd.GetFieldType() != FieldType.ByteArray) { throw new IncompatibleClassChangeError(); } return base.ReadByteArray(fieldName); } /// <exception cref="System.IO.IOException"></exception> public override char ReadChar(string fieldName) { var fd = Cd.GetField(fieldName); if (fd == null) { return '\0'; } if (fd.GetFieldType() != FieldType.Char) { throw new IncompatibleClassChangeError(); } return base.ReadChar(fieldName); } /// <exception cref="System.IO.IOException"></exception> public override char[] ReadCharArray(string fieldName) { var fd = Cd.GetField(fieldName); if (fd == null) { return null; } if (fd.GetFieldType() != FieldType.CharArray) { throw new IncompatibleClassChangeError(); } return base.ReadCharArray(fieldName); } /// <exception cref="System.IO.IOException"></exception> public override double ReadDouble(string fieldName) { var fd = Cd.GetField(fieldName); if (fd == null) { return 0d; } switch (fd.GetFieldType()) { case FieldType.Double: { return base.ReadDouble(fieldName); } case FieldType.Long: { return base.ReadLong(fieldName); } case FieldType.Float: { return base.ReadFloat(fieldName); } case FieldType.Int: { return base.ReadInt(fieldName); } case FieldType.Byte: { return base.ReadByte(fieldName); } case FieldType.Char: { return base.ReadChar(fieldName); } case FieldType.Short: { return base.ReadShort(fieldName); } default: { throw new IncompatibleClassChangeError(); } } } /// <exception cref="System.IO.IOException"></exception> public override double[] ReadDoubleArray(string fieldName) { var fd = Cd.GetField(fieldName); if (fd == null) { return null; } if (fd.GetFieldType() != FieldType.DoubleArray) { throw new IncompatibleClassChangeError(); } return base.ReadDoubleArray(fieldName); } /// <exception cref="System.IO.IOException"></exception> public override float ReadFloat(string fieldName) { var fd = Cd.GetField(fieldName); if (fd == null) { return 0f; } switch (fd.GetFieldType()) { case FieldType.Float: { return base.ReadFloat(fieldName); } case FieldType.Int: { return base.ReadInt(fieldName); } case FieldType.Byte: { return base.ReadByte(fieldName); } case FieldType.Char: { return base.ReadChar(fieldName); } case FieldType.Short: { return base.ReadShort(fieldName); } default: { throw new IncompatibleClassChangeError(); } } } /// <exception cref="System.IO.IOException"></exception> public override float[] ReadFloatArray(string fieldName) { var fd = Cd.GetField(fieldName); if (fd == null) { return null; } if (fd.GetFieldType() != FieldType.FloatArray) { throw new IncompatibleClassChangeError(); } return base.ReadFloatArray(fieldName); } /// <exception cref="System.IO.IOException"></exception> public override int ReadInt(string fieldName) { var fd = Cd.GetField(fieldName); if (fd == null) { return 0; } switch (fd.GetFieldType()) { case FieldType.Int: { return base.ReadInt(fieldName); } case FieldType.Byte: { return base.ReadByte(fieldName); } case FieldType.Char: { return base.ReadChar(fieldName); } case FieldType.Short: { return base.ReadShort(fieldName); } default: { throw new IncompatibleClassChangeError(); } } } /// <exception cref="System.IO.IOException"></exception> public override int[] ReadIntArray(string fieldName) { var fd = Cd.GetField(fieldName); if (fd == null) { return null; } if (fd.GetFieldType() != FieldType.IntArray) { throw new IncompatibleClassChangeError(); } return base.ReadIntArray(fieldName); } /// <exception cref="System.IO.IOException"></exception> public override long ReadLong(string fieldName) { var fd = Cd.GetField(fieldName); if (fd == null) { return 0L; } switch (fd.GetFieldType()) { case FieldType.Long: { return base.ReadLong(fieldName); } case FieldType.Int: { return base.ReadInt(fieldName); } case FieldType.Byte: { return base.ReadByte(fieldName); } case FieldType.Char: { return base.ReadChar(fieldName); } case FieldType.Short: { return base.ReadShort(fieldName); } default: { throw new IncompatibleClassChangeError(); } } } /// <exception cref="System.IO.IOException"></exception> public override long[] ReadLongArray(string fieldName) { var fd = Cd.GetField(fieldName); if (fd == null) { return null; } if (fd.GetFieldType() != FieldType.LongArray) { throw new IncompatibleClassChangeError(); } return base.ReadLongArray(fieldName); } /// <exception cref="System.IO.IOException"></exception> public override TPortable ReadPortable<TPortable>(string fieldName) { var fd = Cd.GetField(fieldName); if (fd == null) { return default(TPortable); } if (fd.GetFieldType() != FieldType.Portable) { throw new IncompatibleClassChangeError(); } return base.ReadPortable<TPortable>(fieldName); } /// <exception cref="System.IO.IOException"></exception> public override IPortable[] ReadPortableArray(string fieldName) { var fd = Cd.GetField(fieldName); if (fd == null) { return null; } if (fd.GetFieldType() != FieldType.PortableArray) { throw new IncompatibleClassChangeError(); } return base.ReadPortableArray(fieldName); } /// <exception cref="System.IO.IOException"></exception> public override short ReadShort(string fieldName) { var fd = Cd.GetField(fieldName); if (fd == null) { return 0; } switch (fd.GetFieldType()) { case FieldType.Short: { return base.ReadShort(fieldName); } case FieldType.Byte: { return base.ReadByte(fieldName); } default: { throw new IncompatibleClassChangeError(); } } } /// <exception cref="System.IO.IOException"></exception> public override short[] ReadShortArray(string fieldName) { var fd = Cd.GetField(fieldName); if (fd == null) { return null; } if (fd.GetFieldType() != FieldType.ShortArray) { throw new IncompatibleClassChangeError(); } return base.ReadShortArray(fieldName); } /// <exception cref="System.IO.IOException"></exception> public override string ReadUTF(string fieldName) { var fd = Cd.GetField(fieldName); if (fd == null) { return null; } if (fd.GetFieldType() != FieldType.Utf) { throw new IncompatibleClassChangeError(); } return base.ReadUTF(fieldName); } } }
29.161972
119
0.459712
[ "Apache-2.0" ]
asimarslan/hazelcast-csharp-client
Hazelcast.Net/Hazelcast.IO.Serialization/MorphingPortableReader.cs
12,423
C#
using System.Collections.Generic; using System.IO; using System.Reflection; using System.Reflection.Emit; using Harmony; using Microsoft.Xna.Framework; using Terraria; using Terraria.IO; using Terraria.Localization; // ReSharper disable InconsistentNaming // ReSharper disable UnusedType.Global // ReSharper disable UnusedMember.Local // ReSharper disable ArrangeTypeModifiers namespace TerrariaStreamIntegration { [HarmonyPatch(typeof(Main), "QuitGame")] class Main_QuitGame_Patch { private static void Prefix() { MyModServer.Instance.Unload(); } } [HarmonyPatch(typeof(Main), "Initialize_AlmostEverything")] class Main_Initialize_AlmostEverything_Patch { private static void Postfix() { MyModServer.Instance.Load(); } } [HarmonyPatch(typeof(WorldGen), "UpdateWorld")] class WorldGen_UpdateWorld_Patch { private static void Prefix() { MyModServer.Instance.UpdateWorld(); } } [HarmonyPatch(typeof(WorldFile), "LoadHeader", typeof(BinaryReader))] class WorldFile_LoadHeader_Patch { private static void Postfix() { MyModServer.Instance.DeathCounter.Load(); } } [HarmonyPatch(typeof(WorldFile), "SaveWorldHeader", typeof(BinaryWriter))] class WorldFile_SaveWorldHeader_Patch { private static void Postfix() { MyModServer.Instance.DeathCounter.Save(); } } [HarmonyPatch(typeof(Player), "DropTombstone", typeof(int), typeof(NetworkText), typeof(int))] class Player_DropTombstone_Patch { private static void Postfix(Player __instance) { MyModServer.Instance.DeathCounter.OnPlayerDeath(__instance); } } [HarmonyPatch(typeof(NPC), "NewNPC", typeof(int), typeof(int), typeof(int), typeof(int), typeof(float), typeof(float), typeof(float), typeof(float), typeof(int))] class NPC_NewNPC_Patch { private static void Postfix(int __result) { Utils.LatestSpawn = __result; } } [HarmonyPatch(typeof(MessageBuffer), "GetData", new[] {typeof(int), typeof(int), typeof(int)}, new[] {ArgumentType.Normal, ArgumentType.Normal, ArgumentType.Out})] class MessageBuffer_GetData_Patch { private static readonly MethodInfo _handleNetMethod = SymbolExtensions.GetMethodInfo(() => MyModServer.HandleModPacket(0, 0, null)); private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { var patched = false; foreach (var instruction in instructions) { if (!patched) { if (instruction.opcode == OpCodes.Stind_I4) { patched = true; yield return instruction; yield return new CodeInstruction(OpCodes.Ldloc_0); yield return new CodeInstruction(OpCodes.Ldloc_1); yield return new CodeInstruction(OpCodes.Ldarg_0); yield return new CodeInstruction(OpCodes.Call, _handleNetMethod); yield return new CodeInstruction(OpCodes.Nop); continue; } } yield return instruction; } } } /*[HarmonyPatch(typeof(MessageBuffer), "GetData", new[]{typeof(int), typeof(int), typeof(int)}, new[]{ArgumentType.Normal, ArgumentType.Normal, ArgumentType.Out})] class MessageBuffer_GetData_Patch { private static readonly FieldInfo _maxMsgField = AccessTools.Field(typeof(Main), "maxMsg"); private static readonly FieldInfo _activeNetDiagnosticsUIField = AccessTools.Field(typeof(Main), "ActiveNetDiagnosticsUI"); private static readonly FieldInfo _netModeField = AccessTools.Field(typeof(Main), "netMode"); private static readonly MethodInfo _handleNetMethod = SymbolExtensions.GetMethodInfo(() => MyModServer.HandleModPacket(null)); private static readonly MethodInfo _hijack = SymbolExtensions.GetMethodInfo(() => MyModServer.Hijack(0, null)); private static readonly MemberInfo _setPosition = AccessTools.Property(typeof(Stream), "Position").SetMethod; private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator) { var handleNetLabel = generator.DefineLabel(); var stelem = 0; var handleSwitchInjected = false; var lodloc = 0; var patchPacketId = true; var droppingInstructions = false; var packetIfLabel = generator.DefineLabel(); foreach (var instruction in instructions) { // Allow higher packet ids if (patchPacketId) { if (instruction.opcode == OpCodes.Ldloc_0 && lodloc < 2) { lodloc++; if (lodloc == 2) { droppingInstructions = true; } } if (droppingInstructions) { if (instruction.opcode == OpCodes.Ret) { droppingInstructions = false; } continue; } if (instruction.opcode == OpCodes.Ldsfld && (FieldInfo) instruction.operand == _activeNetDiagnosticsUIField) { yield return new CodeInstruction(OpCodes.Ldloc_0); yield return new CodeInstruction(OpCodes.Ldc_I4, 140); yield return new CodeInstruction(OpCodes.Clt); yield return new CodeInstruction(OpCodes.Stloc_2); yield return new CodeInstruction(OpCodes.Ldloc_2); yield return new CodeInstruction(OpCodes.Brfalse_S, packetIfLabel); } if (instruction.opcode == OpCodes.Ldsfld && (FieldInfo) instruction.operand == _netModeField) { instruction.labels.Add(packetIfLabel); patchPacketId = false; } } // Hijack net ids //if (instruction.opcode == OpCodes.Callvirt && (MemberInfo) instruction.operand == _setPosition) //{ // yield return instruction; // yield return new CodeInstruction(OpCodes.Ldloc_0); // yield return new CodeInstruction(OpCodes.Ldarg_0); // yield return new CodeInstruction(OpCodes.Call, _hijack); // continue; //} // HandlePacket switch case if (instruction.opcode == OpCodes.Switch && !handleSwitchInjected) { handleSwitchInjected = true; yield return instruction; yield return new CodeInstruction(OpCodes.Ldloc_0); yield return new CodeInstruction(OpCodes.Ldc_I4, 250); yield return new CodeInstruction(OpCodes.Sub); yield return new CodeInstruction(OpCodes.Switch, new []{handleNetLabel}); } else { if (stelem == 5) { yield return new CodeInstruction(OpCodes.Ret); var handle250 = new CodeInstruction(OpCodes.Ldarg_0); handle250.labels.Add(handleNetLabel); yield return handle250; yield return new CodeInstruction(OpCodes.Call, _handleNetMethod); } if (instruction.opcode == OpCodes.Stelem_I1) { stelem++; } yield return instruction; } } } }*/ }
39.58216
167
0.55035
[ "MIT" ]
GoryMoon/TerrariaStreamIntegration
TerrariaStreamIntegrationNativeServer/Patches.cs
8,435
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Chiota.Models; using Chiota.Models.Database; using Chiota.Services.Database.Base; using SQLite; namespace Chiota.Services.Database.Repositories { public class TransactionCacheRepository : SecureRepository<DbTransactionCache> { #region Constructors public TransactionCacheRepository(SQLiteConnection database, EncryptionKey encryptionKey) : base(database, encryptionKey) { } #endregion #region GetTransactionCacheByChatAddress /// <summary> /// Get all objects of the table by the public key address. /// </summary> /// <returns>List of the table objects</returns> public List<DbTransactionCache> GetTransactionCacheByChatAddress(string chatAddress) { try { var value = Encrypt(chatAddress); var query = Database.Query(TableMapping, "SELECT * FROM " + TableMapping.TableName + " WHERE " + nameof(DbMessage.ChatAddress) + "=?;", value).Cast<DbTransactionCache>().ToList(); for (var i = 0; i < query.Count; i++) query[i] = DecryptModel(query[i]); return query; } catch (Exception e) { Console.WriteLine(e); return null; } } #endregion } }
28.98
195
0.602484
[ "MIT" ]
Noc2/Chiota
Chiota/Chiota/Services/Database/Repositories/TransactionCacheRepository.cs
1,451
C#
using DNTFrameworkCore.EFCore.Application; using DNTFrameworkCore.EFCore.Context; using DNTFrameworkCore.TestTenancy.Application.Identity.Models; using DNTFrameworkCore.TestTenancy.Domain.Identity; namespace DNTFrameworkCore.TestTenancy.Application.Identity { public interface IUserService : ICrudService<long, UserReadModel, UserModel> { } public class UserService : CrudService<User, long, UserReadModel, UserModel>, IUserService { private readonly IMapper _mapper; private readonly IUserPasswordHashAlgorithm _password; public UserService( IUnitOfWork uow, IEventBus bus, IUserPasswordHashAlgorithm password, IMapper mapper) : base(uow, bus) { _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); _password = password ?? throw new ArgumentNullException(nameof(password)); } protected override IQueryable<User> BuildFindQuery() { return base.BuildFindQuery() .Include(u => u.Roles) .Include(u => u.Permissions); } protected override IQueryable<UserReadModel> BuildReadQuery(FilteredPagedQueryModel model) { return EntitySet.AsNoTracking() .Select(u => new UserReadModel { Id = u.Id, IsActive = u.IsActive, UserName = u.UserName, DisplayName = u.DisplayName, LastLoggedInDateTime = u.LastLoggedInDateTime }); } protected override Task<Result> BeforeEditAsync(IReadOnlyList<ModifiedModel<UserModel>> models, IReadOnlyList<User> entities) { return base.BeforeEditAsync(models, entities); } protected override void MapToEntity(UserModel model, User user) { _mapper.Map(model, user); MapSerialNumber(user, model); MapPasswordHash(user, model); } protected override UserModel MapToModel(User user) { return _mapper.Map<UserModel>(user); } private void MapSerialNumber(User user, UserModel model) { if (!model.ShouldMapSerialNumber()) return; user.SerialNumber = user.NewSerialNumber(); } private void MapPasswordHash(User user, UserModel model) { if (!model.ShouldMapPasswordHash()) return; user.PasswordHash = _password.HashPassword(model.Password); } } }
33.025316
133
0.609812
[ "Apache-2.0" ]
hueifeng/DNTFrameworkCore
test/DNTFrameworkCore.TestTenancy/Application/Identity/UserService.cs
2,609
C#
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // using System.Globalization; using System.IO; using System.Text; namespace DiscUtils.Diagnostics { internal sealed class NullTextWriter : TextWriter { public NullTextWriter() : base(CultureInfo.InvariantCulture) { } public override Encoding Encoding { get { return Encoding.Unicode; } } public override void Write(char value) { } } }
33.617021
78
0.706329
[ "MIT" ]
AssafTzurEl/DiscUtils
Utilities/DiscUtils.Diagnostics/NullTextWriter.cs
1,580
C#
/* *************************************************************************** * This file is part of SharpNEAT - Evolution of Neural Networks. * * Copyright 2004-2006, 2009-2010 Colin Green ([email protected]) * * SharpNEAT is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SharpNEAT is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SharpNEAT. If not, see <http://www.gnu.org/licenses/>. */ namespace SharpNeat.Domains { public interface IGuiNeatExperiment : INeatExperiment { /// <summary> /// Create a System.Windows.Forms derived object for displaying genomes. /// </summary> AbstractGenomeView CreateGenomeView(); /// <summary> /// Create a System.Windows.Forms derived object for displaying output for a domain (e.g. show best genome's output/performance/behaviour in the domain). /// </summary> AbstractDomainView CreateDomainView(); } }
39.828571
162
0.667145
[ "MIT" ]
devluz/SharpNeatForUnity
src/SharpNeatDomains/IGuiNeatExperiment.cs
1,396
C#
using Microsoft.Extensions.Logging; using Project2.UserService.Controllers; using Project2.UserService.Models; using Project2.UserService.Storage; using Project2.UserService.Storage.Repositories; using Xunit; namespace Project2.Testing.Specs { public class UserAPITests { private readonly UserRepository _ur; private static UserDbContext _db; private readonly ILogger<UserController> logger = LoggerFactory.Create(o => o.SetMinimumLevel(LogLevel.Debug)).CreateLogger<UserController>(); // [Theory] // [InlineData("Randall1", "password")] // public void Test_GetByUsernameAndPassword(string u, string p) // { // var sut = new UserController(_ur); // var actual = sut.Get(u, p); // Assert.IsType<string>(actual); // } // [Theory] // [InlineData("Randall1")] // public void Test_FindUser(string u) // { // var sut = new UserRepository(_db); // var actual = sut.FindUser(u); // Assert.IsType<UserModel>(actual); // } } }
28.416667
146
0.674487
[ "MIT" ]
revature-p2-ranbiajim/P2
Project2/Project2.Testing/Specs/UserAPITests.cs
1,023
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("Rectangle of 10x10 Stars")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Rectangle of 10x10 Stars")] [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("d7ffd3ef-43c9-4f11-a898-c466bbd24f9a")] // 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.405405
84
0.74525
[ "MIT" ]
BlueDress/School
Programming Basics C#/Draw-with- Loops/Rectangle of 10x10 Stars/Properties/AssemblyInfo.cs
1,424
C#
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.Collections.Generic; using System.Linq; using QuantConnect.Benchmarks; using QuantConnect.Orders; using QuantConnect.Orders.Fees; using QuantConnect.Securities; using QuantConnect.Util; namespace QuantConnect.Brokerages { /// <summary> /// Kraken Brokerage model /// </summary> public class KrakenBrokerageModel : DefaultBrokerageModel { private readonly List<string> _fiatsAvailableMargin = new() {"USD", "EUR"}; private readonly List<string> _onlyFiatsAvailableMargin = new() {"BTC", "USDT", "USDC"}; private readonly List<string> _ethAvailableMargin = new() {"REP", "XTZ", "ADA", "EOS", "TRX", "LINK" }; /// <summary> /// Gets a map of the default markets to be used for each security type /// </summary> public override IReadOnlyDictionary<SecurityType, string> DefaultMarkets { get; } = GetDefaultMarkets(); /// <summary> /// Leverage map of different coins /// </summary> public IReadOnlyDictionary<string, decimal> CoinLeverage { get; } = new Dictionary<string, decimal> { {"BTC", 5}, // only with fiats {"ETH", 5}, {"USDT", 2}, // only with fiats {"XMR", 2}, {"REP", 2}, // eth available {"XRP", 3}, {"BCH", 2}, {"XTZ", 2}, // eth available {"LTC", 3}, {"ADA", 3}, // eth available {"EOS", 3}, // eth available {"DASH", 3}, {"TRX", 3}, // eth available {"LINK", 3}, // eth available {"USDC", 3}, // only with fiats }; /// <summary> /// Constructor for Kraken brokerage model /// </summary> /// <param name="accountType">Cash or Margin</param> public KrakenBrokerageModel(AccountType accountType = AccountType.Cash) : base(accountType) { } /// <summary> /// Returns true if the brokerage could accept this order. This takes into account /// order type, security type, and order size limits. /// </summary> /// <remarks> /// For example, a brokerage may have no connectivity at certain times, or an order rate/size limit /// </remarks> /// <param name="security">The security of the order</param> /// <param name="order">The order to be processed</param> /// <param name="message">If this function returns false, a brokerage message detailing why the order may not be submitted</param> /// <returns>True if the brokerage could process the order, false otherwise</returns> public override bool CanSubmitOrder(Security security, Order order, out BrokerageMessageEvent message) { if (!IsValidOrderSize(security, order.Quantity, out message)) { return false; } message = null; if (security.Type != SecurityType.Crypto) { message = new BrokerageMessageEvent(BrokerageMessageType.Warning, "NotSupported", StringExtensions.Invariant($"The {nameof(KrakenBrokerageModel)} does not support {security.Type} security type.") ); return false; } return base.CanSubmitOrder(security, order, out message); } /// <summary> /// Kraken does not support update of orders /// </summary> /// <param name="security">Security</param> /// <param name="order">Order that should be updated</param> /// <param name="request">Update request</param> /// <param name="message">Outgoing message</param> /// <returns>Always false as Kraken does not support update of orders</returns> public override bool CanUpdateOrder(Security security, Order order, UpdateOrderRequest request, out BrokerageMessageEvent message) { message = new BrokerageMessageEvent(BrokerageMessageType.Warning, 0, "Brokerage does not support update. You must cancel and re-create instead."); ; return false; } /// <summary> /// Provides Kraken fee model /// </summary> /// <param name="security">Security</param> /// <returns>Kraken fee model</returns> public override IFeeModel GetFeeModel(Security security) { return new KrakenFeeModel(); } /// <summary> /// Gets a new buying power model for the security, returning the default model with the security's configured leverage. /// For cash accounts, leverage = 1 is used. /// For margin trading, max leverage = 5 /// </summary> /// <param name="security">The security to get a buying power model for</param> /// <returns>The buying power model for this brokerage/security</returns> public override IBuyingPowerModel GetBuyingPowerModel(Security security) { if (AccountType == AccountType.Margin) { return new SecurityMarginModel(GetLeverage(security)); } return new CashBuyingPowerModel(); } /// <summary> /// Kraken global leverage rule /// </summary> /// <param name="security"></param> /// <returns></returns> public override decimal GetLeverage(Security security) { if (AccountType == AccountType.Cash) { return 1m; } // first check whether this security support margin only with fiats. foreach (var coin in _onlyFiatsAvailableMargin.Where(coin => security.Symbol.ID.Symbol.StartsWith(coin)).Where(coin => _fiatsAvailableMargin.Any(rightFiat => security.Symbol.Value.EndsWith(rightFiat)))) { return CoinLeverage[coin]; } List<string> extendedCoinArray = new() {"BTC", "ETH"}; extendedCoinArray.AddRange(_fiatsAvailableMargin); // Then check whether this security support margin with ETH. foreach (var coin in _ethAvailableMargin.Where(coin => security.Symbol.ID.Symbol.StartsWith(coin)).Where(coin => extendedCoinArray.Any(rightFiat => security.Symbol.Value.EndsWith(rightFiat)))) { return CoinLeverage[coin]; } extendedCoinArray.Remove("ETH"); // At the end check all others. foreach (var coin in CoinLeverage.Keys.Where(coin => security.Symbol.ID.Symbol.StartsWith(coin)).Where(coin => extendedCoinArray.Any(rightFiat => security.Symbol.Value.EndsWith(rightFiat)))) { return CoinLeverage[coin]; } return 1m; } /// <summary> /// Get the benchmark for this model /// </summary> /// <param name="securities">SecurityService to create the security with if needed</param> /// <returns>The benchmark for this brokerage</returns> public override IBenchmark GetBenchmark(SecurityManager securities) { var symbol = Symbol.Create("BTCUSD", SecurityType.Crypto, Market.Kraken); return SecurityBenchmark.CreateInstance(securities, symbol); } /// <summary> /// Get default markets and specify Kraken as crypto market /// </summary> /// <returns>default markets</returns> private static IReadOnlyDictionary<SecurityType, string> GetDefaultMarkets() { var map = DefaultMarketMap.ToDictionary(); map[SecurityType.Crypto] = Market.Kraken; return map.ToReadOnlyDictionary(); } } }
41.970297
214
0.603916
[ "Apache-2.0" ]
ArthurAsenheimer/Lean
Common/Brokerages/KrakenBrokerageModel.cs
8,478
C#
using System.Drawing; using Top_Down_shooter.Scripts.Source; namespace Top_Down_shooter.Scripts.Renders { interface IAnimationRender : IRender { void Draw(D2DGraphicsDevice device, Point startSlice, Size sizeSlice); void PlayAnimation(); void ChangeTypeAnimation(); } }
20.666667
78
0.716129
[ "MIT" ]
TheTMGaming/Draft
Scripts/Renders/IAnimationRender.cs
312
C#
using System; using Fork.ViewModel; namespace Fork.Logic.Model.ProxyModels { public class NetworkForkServer : NetworkServer { private string motdEscaped; public string Name { get; set; } public string Motd { get { return motdEscaped.Replace("\\n", "\n"); } set { motdEscaped = value.Replace("\n", "\\n").Replace("\r", ""); } } public string Address { get; set; } public bool Restricted { get; set; } public Settings.Server ProxyServer => new Settings.Server{address = Address, motd = motdEscaped, restricted = Restricted, ForkServer = IsForkServer, ForkServerUid = ServerViewModel.Server.UID}; public bool IsForkServer => true; public ServerViewModel ServerViewModel { get; set; } public NetworkForkServer(ServerViewModel serverViewModel, Settings.Server server, string name) { ServerViewModel = serverViewModel; Name = name; Motd = server.motd; Address = server.address; Restricted = server.restricted; } public int CompareTo(NetworkServer otherNetworkServer) { int isForkServerCompare = otherNetworkServer.IsForkServer.CompareTo(IsForkServer); if (isForkServerCompare != 0) { return isForkServerCompare; } return string.Compare(Name, otherNetworkServer.Name, StringComparison.Ordinal); } } }
32.826087
201
0.611921
[ "MIT" ]
42sol-eu/Fork
logic/model/ProxyModels/NetworkForkServer.cs
1,510
C#
using System.Diagnostics; using System.Windows.Forms; using Microsoft.Win32; namespace KBS.Modules { internal class PowerLineModule : Module { private PowerLineStatus _currentPowerLineStatus; /// <summary> /// Module constructor ///Subscribe module on event and depending on the power status select a power plan /// </summary> public PowerLineModule(NotifyIcon notifyIcon) : base(notifyIcon) { SystemEvents.PowerModeChanged += HandleEvent; switch (SystemInformation.PowerStatus.PowerLineStatus) { case PowerLineStatus.Online: DisablePowerSaving(); break; case PowerLineStatus.Offline: EnablePowerSaving(); break; case PowerLineStatus.Unknown: NotifyUser("Unknown Power Line Status", "Power Line Status Changed", ToolTipIcon.Error); break; default: NotifyUser("Unknown Power Line Status", "Power Line Status Changed", ToolTipIcon.Error); break; } _currentPowerLineStatus = SystemInformation.PowerStatus.PowerLineStatus; } /// <summary> /// Processing events Switching power plan and notifications to users /// </summary> private void HandleEvent(object sender, PowerModeChangedEventArgs e) { if (e.Mode != PowerModes.StatusChange) return; switch (SystemInformation.PowerStatus.PowerLineStatus) { case PowerLineStatus.Online: if (_currentPowerLineStatus != PowerLineStatus.Online) { DisablePowerSaving(); NotifyUser("Disable Power Saving", "Power Line Status Changed", ToolTipIcon.None); } break; case PowerLineStatus.Offline: if (_currentPowerLineStatus != PowerLineStatus.Offline) { EnablePowerSaving(); NotifyUser("Enable Power Saving", "Power Line Status Changed", ToolTipIcon.None); } break; default: if (_currentPowerLineStatus != PowerLineStatus.Unknown) NotifyUser("Unknown Power Line Status", "Power Line Status Changed", ToolTipIcon.Error); break; } _currentPowerLineStatus = SystemInformation.PowerStatus.PowerLineStatus; } /// <summary> /// Wrapper for subscription to PowerModeChanged event /// </summary> public override void EnableModule() { SystemEvents.PowerModeChanged += HandleEvent; } /// <summary> /// Wrapper to unsubscribe from PowerModeChanged event /// </summary> public override void DisableModule() { SystemEvents.PowerModeChanged -= HandleEvent; } /// <summary> /// Makes energy saving power scheme active on /// </summary> private void EnablePowerSaving() => RunCmdCommand("powercfg /s a1841308-3541-4fab-bc81-f71556f20b4a"); /// <summary> /// Makes high performance power scheme active on /// </summary> private void DisablePowerSaving() => RunCmdCommand("powercfg /s 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c"); /// <summary> /// Wrapper for the command /// </summary> private static void RunCmdCommand(string command) { var cmd = new Process { StartInfo = { FileName = "cmd.exe", RedirectStandardInput = true, RedirectStandardOutput = true, CreateNoWindow = true, UseShellExecute = false } }; cmd.Start(); cmd.StandardInput.WriteLine(command); cmd.StandardInput.Flush(); cmd.StandardInput.Close(); cmd.WaitForExit(); } } }
35.716667
112
0.536864
[ "MIT" ]
Kriger/KrimmelBatterySaver
KBS/Modules/PowerLineModule.cs
4,288
C#
using System; class RollingHash { public long Data { get; private set; } public long Size { get; private set; } private const long alphabetSize = 255; public void Append(char c) { Data = (Data * alphabetSize + c); Size++; } public void Skip(char c) { Data = Data - (long) Math.Pow(alphabetSize, Size - 1) * c; Size--; } public bool Equals(RollingHash other) { return Data == other.Data; } } class Program { static int Search(String s, String t) { RollingHash sh = new RollingHash(); foreach (char c in s) { sh.Append(c); } RollingHash th = new RollingHash(); for (int i = 0; i < t.Length; i++) { if (th.Size == s.Length) { th.Skip(t[i - s.Length]); } th.Append(t[i]); if (sh.Equals(th)){ if (Match(s, t, i - s.Length + 1)) { return i; } } } return -1; } static bool Match(String s, String t, int start) { int sidx = 0; while (sidx < s.Length && s[sidx] == t[start]) { sidx++; start++; } return sidx == s.Length; } static void Main() { Console.WriteLine(Search("abcdefg","aaaaaabcdefgaaa")); Console.WriteLine(Search("abcdefgh","aaaaaabcdefgaaa")); } }
23.42623
66
0.482855
[ "MIT" ]
Gerula/interviews
VariousArtists/karp_rabin.cs
1,429
C#
// Copyright 2018 Andrew White // // 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 Finbuckle.MultiTenant.AspNetCore { /// <summary> /// Constant values for use with Finbuckle.MultiTenant.AspNetCore. /// </summary> internal static class Constants { public const string HttpContextMultiTenantContext = "Finbuckle.MultiTenant.AspNetCore.MultiTenantContext"; } }
36.692308
78
0.701258
[ "Apache-2.0" ]
GordonBlahut/Finbuckle.MultiTenant
src/Finbuckle.MultiTenant.AspNetCore/Internal/Constants.cs
956
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("RectangularArea1")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RectangularArea1")] [assembly: AssemblyCopyright("Copyright © 2019")] [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("36069187-5bec-49cd-8872-93c38ec53737")] // 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" ]
galin-kostadinov/Software-Engineering
C#/Programming Basics with C#/01. First Steps in Coding/RectangularArea/RectangularArea1/Properties/AssemblyInfo.cs
1,403
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.WindowsAzure.Commands.ScenarioTest; using Microsoft.WindowsAzure.Commands.Test.Utilities.Common; using Xunit; namespace Microsoft.Azure.Commands.Insights.Test.ScenarioTests { public class AutoscaleTests : RMTestBase { public AutoscaleTests(Xunit.Abstractions.ITestOutputHelper output) { ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output)); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestAddAzureRmAutoscaleSetting() { TestsController.NewInstance.RunPsTest("Test-AddAzureRmAutoscaleSetting"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestGetAzureRmAutoscaleSetting() { TestsController.NewInstance.RunPsTest("Test-GetAzureRmAutoscaleSetting"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestRemoveAzureRmAutoscaleSetting() { TestsController.NewInstance.RunPsTest("Test-RemoveAzureRmAutoscaleSetting"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestGetAzureRmAutoscaleHistory() { TestsController.NewInstance.RunPsTest("Test-GetAzureRmAutoscaleHistory"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestNewAzureRmAutoscaleNotification() { TestsController.NewInstance.RunPsTest("Test-NewAzureRmAutoscaleNotification"); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void TestNewAzureRmAutoscaleWebhook() { TestsController.NewInstance.RunPsTest("Test-NewAzureRmAutoscaleWebhook"); } } }
38.676056
153
0.638747
[ "MIT" ]
hchungmsft/azure-powershell
src/ResourceManager/Insights/Commands.Insights.Test/ScenarioTests/AutoscaleTests.cs
2,678
C#
using UnityEngine; using UnityEditor; using mulova.commons; using System.Collections.Generic.Ex; namespace mulova.unicore { public class AssetLabel : EnumClass<AssetLabel> { public static readonly AssetLabel ALPHA_SD = new AssetLabel("Alpha_sd"); private AssetLabel(string label) : base(label) {} public bool Is(Object asset) { string[] labels = AssetDatabase.GetLabels(asset); if (!labels.IsEmpty()) { foreach (string l in labels) { if (id == l) { return true; } } } return false; } } }
24.933333
80
0.486631
[ "MIT" ]
mulova/commons
Editor/config/AssetLabel.cs
750
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace FlightsASPMVC.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; public partial class passenger { public passenger() { this.baggage = new HashSet<baggage>(); this.ticket = new HashSet<ticket>(); } [Display(Name = "Passenger identifier")] public int id { get; set; } [Display(Name = "Passenger name")] public string name { get; set; } [Display(Name = "Passenger lastname")] public string lastname { get; set; } [Display(Name = "Passenger patronymic")] public string patronymic { get; set; } [Display(Name = "Phone")] public string phone { get; set; } [Display(Name = "Additional phone")] public string additional_phone { get; set; } [Display(Name = "Comment")] public string comment { get; set; } [Display(Name = "City")] public int city { get; set; } [Display(Name = "Age")] public sbyte age { get; set; } [Display(Name = "Passport number")] public int passport_num { get; set; } [Display(Name = "Internationlal passport number")] public int internationlal_passport_num { get; set; } public virtual ICollection<baggage> baggage { get; set; } public virtual city city1 { get; set; } public virtual ICollection<ticket> ticket { get; set; } } }
30.967742
85
0.548438
[ "MIT" ]
pahomovda/airports-database-aspmvc
FlightsASPMVC/Models/passenger.cs
1,920
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using Aliyun.Acs.Core.Transform; using Aliyun.Acs.CloudPhoto.Model.V20170711; using System; using System.Collections.Generic; namespace Aliyun.Acs.CloudPhoto.Transform.V20170711 { public class FetchMomentPhotosResponseUnmarshaller { public static FetchMomentPhotosResponse Unmarshall(UnmarshallerContext context) { FetchMomentPhotosResponse fetchMomentPhotosResponse = new FetchMomentPhotosResponse(); fetchMomentPhotosResponse.HttpResponse = context.HttpResponse; fetchMomentPhotosResponse.Code = context.StringValue("FetchMomentPhotos.Code"); fetchMomentPhotosResponse.Message = context.StringValue("FetchMomentPhotos.Message"); fetchMomentPhotosResponse.TotalCount = context.IntegerValue("FetchMomentPhotos.TotalCount"); fetchMomentPhotosResponse.RequestId = context.StringValue("FetchMomentPhotos.RequestId"); fetchMomentPhotosResponse.Action = context.StringValue("FetchMomentPhotos.Action"); List<FetchMomentPhotosResponse.FetchMomentPhotos_Photo> fetchMomentPhotosResponse_photos = new List<FetchMomentPhotosResponse.FetchMomentPhotos_Photo>(); for (int i = 0; i < context.Length("FetchMomentPhotos.Photos.Length"); i++) { FetchMomentPhotosResponse.FetchMomentPhotos_Photo photo = new FetchMomentPhotosResponse.FetchMomentPhotos_Photo(); photo.Id = context.LongValue("FetchMomentPhotos.Photos["+ i +"].Id"); photo.IdStr = context.StringValue("FetchMomentPhotos.Photos["+ i +"].IdStr"); photo.Title = context.StringValue("FetchMomentPhotos.Photos["+ i +"].Title"); photo.FileId = context.StringValue("FetchMomentPhotos.Photos["+ i +"].FileId"); photo.Location = context.StringValue("FetchMomentPhotos.Photos["+ i +"].Location"); photo.State = context.StringValue("FetchMomentPhotos.Photos["+ i +"].State"); photo.Md5 = context.StringValue("FetchMomentPhotos.Photos["+ i +"].Md5"); photo.IsVideo = context.BooleanValue("FetchMomentPhotos.Photos["+ i +"].IsVideo"); photo.Remark = context.StringValue("FetchMomentPhotos.Photos["+ i +"].Remark"); photo.Size = context.LongValue("FetchMomentPhotos.Photos["+ i +"].Size"); photo.Width = context.LongValue("FetchMomentPhotos.Photos["+ i +"].Width"); photo.Height = context.LongValue("FetchMomentPhotos.Photos["+ i +"].Height"); photo.Ctime = context.LongValue("FetchMomentPhotos.Photos["+ i +"].Ctime"); photo.Mtime = context.LongValue("FetchMomentPhotos.Photos["+ i +"].Mtime"); photo.TakenAt = context.LongValue("FetchMomentPhotos.Photos["+ i +"].TakenAt"); photo.InactiveTime = context.LongValue("FetchMomentPhotos.Photos["+ i +"].InactiveTime"); photo.ShareExpireTime = context.LongValue("FetchMomentPhotos.Photos["+ i +"].ShareExpireTime"); fetchMomentPhotosResponse_photos.Add(photo); } fetchMomentPhotosResponse.Photos = fetchMomentPhotosResponse_photos; return fetchMomentPhotosResponse; } } }
56.044776
157
0.748069
[ "Apache-2.0" ]
brightness007/unofficial-aliyun-openapi-net-sdk
aliyun-net-sdk-cloudphoto/CloudPhoto/Transform/V20170711/FetchMomentPhotosResponseUnmarshaller.cs
3,755
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Abp.Authorization.Users; using Abp.Domain.Services; using Abp.IdentityFramework; using Abp.Runtime.Session; using Abp.UI; using expensejar.Authorization.Roles; using expensejar.MultiTenancy; namespace expensejar.Authorization.Users { public class UserRegistrationManager : DomainService { public IAbpSession AbpSession { get; set; } private readonly TenantManager _tenantManager; private readonly UserManager _userManager; private readonly RoleManager _roleManager; private readonly IPasswordHasher<User> _passwordHasher; public UserRegistrationManager( TenantManager tenantManager, UserManager userManager, RoleManager roleManager, IPasswordHasher<User> passwordHasher) { _tenantManager = tenantManager; _userManager = userManager; _roleManager = roleManager; _passwordHasher = passwordHasher; AbpSession = NullAbpSession.Instance; } public async Task<User> RegisterAsync(string name, string surname, string emailAddress, string userName, string plainPassword, bool isEmailConfirmed) { CheckForTenant(); var tenant = await GetActiveTenantAsync(); var user = new User { TenantId = tenant.Id, Name = name, Surname = surname, EmailAddress = emailAddress, IsActive = true, UserName = userName, IsEmailConfirmed = isEmailConfirmed, Roles = new List<UserRole>() }; user.SetNormalizedNames(); foreach (var defaultRole in await _roleManager.Roles.Where(r => r.IsDefault).ToListAsync()) { user.Roles.Add(new UserRole(tenant.Id, user.Id, defaultRole.Id)); } await _userManager.InitializeOptionsAsync(tenant.Id); CheckErrors(await _userManager.CreateAsync(user, plainPassword)); await CurrentUnitOfWork.SaveChangesAsync(); return user; } private void CheckForTenant() { if (!AbpSession.TenantId.HasValue) { throw new InvalidOperationException("Can not register host users!"); } } private async Task<Tenant> GetActiveTenantAsync() { if (!AbpSession.TenantId.HasValue) { return null; } return await GetActiveTenantAsync(AbpSession.TenantId.Value); } private async Task<Tenant> GetActiveTenantAsync(int tenantId) { var tenant = await _tenantManager.FindByIdAsync(tenantId); if (tenant == null) { throw new UserFriendlyException(L("UnknownTenantId{0}", tenantId)); } if (!tenant.IsActive) { throw new UserFriendlyException(L("TenantIdIsNotActive{0}", tenantId)); } return tenant; } protected virtual void CheckErrors(IdentityResult identityResult) { identityResult.CheckErrors(LocalizationManager); } } }
30.610619
157
0.602775
[ "MIT" ]
raxIsBlur/expensejar
aspnet-core/src/expensejar.Core/Authorization/Users/UserRegistrationManager.cs
3,461
C#
using StackExchange.Redis; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace Zzll.Net.Framework.RedisMQ { /// <summary> /// Redis缓存数据库处理 /// </summary> public class RedisClient : IDisposable { private int DbNum { get; } private readonly ConnectionMultiplexer _conn; /// <summary> /// 系统自定义Key前缀 /// </summary> public string CustomKey { get; set; } #region 构造函数 /// <summary> /// 构造函数 /// </summary> /// <param name="dbNum">数据库编码</param> public RedisClient(int dbNum = 0) : this(dbNum, null) { } /// <summary> /// 构造函数 /// </summary> /// <param name="dbNum">数据库编码</param> /// <param name="readWriteHosts">读写Redis链接字符串</param> public RedisClient(int dbNum, string readWriteHosts) { DbNum = dbNum; if (string.IsNullOrWhiteSpace(readWriteHosts)) _conn = RedisConnection.Instance; else _conn = RedisConnection.GetConnectionMultiplexer(readWriteHosts); } #endregion 构造函数 #region String #region 同步方法 /// <summary> /// 保存单个key value /// </summary> /// <param name="key">Redis Key</param> /// <param name="value">保存的值</param> /// <param name="expiry">过期时间</param> /// <returns></returns> public bool StringSet(string key, string value, TimeSpan? expiry = default(TimeSpan?)) { key = AddSysCustomKey(key); return Do(db => db.StringSet(key, value, expiry)); } /// <summary> /// 保存多个key value /// </summary> /// <param name="keyValues">键值对</param> /// <returns></returns> public bool StringSet(List<KeyValuePair<RedisKey, RedisValue>> keyValues) { List<KeyValuePair<RedisKey, RedisValue>> newkeyValues = keyValues.Select(p => new KeyValuePair<RedisKey, RedisValue>(AddSysCustomKey(p.Key), p.Value)).ToList(); return Do(db => db.StringSet(newkeyValues.ToArray())); } /// <summary> /// 保存一个对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="obj"></param> /// <param name="expiry"></param> /// <returns></returns> public bool StringSet<T>(string key, T obj, TimeSpan? expiry = default(TimeSpan?)) { key = AddSysCustomKey(key); string json = ConvertJson(obj); return Do(db => db.StringSet(key, json, expiry)); } /// <summary> /// 获取单个key的值 /// </summary> /// <param name="key">Redis Key</param> /// <returns></returns> public string StringGet(string key) { key = AddSysCustomKey(key); return Do(db => db.StringGet(key)); } /// <summary> /// 获取多个Key /// </summary> /// <param name="listKey">Redis Key集合</param> /// <returns></returns> public RedisValue[] StringGet(List<string> listKey) { List<string> newKeys = listKey.Select(AddSysCustomKey).ToList(); return Do(db => db.StringGet(ConvertRedisKeys(newKeys))); } /// <summary> /// 获取一个key的对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <returns></returns> public T StringGet<T>(string key) { if (KeyExists(key)) { key = AddSysCustomKey(key); return Do(db => ConvertObj<T>(db.StringGet(key))); } else return default(T); } /// <summary> /// 为数字增长val /// </summary> /// <param name="key"></param> /// <param name="val">可以为负</param> /// <returns>增长后的值</returns> public double StringIncrement(string key, double val = 1) { key = AddSysCustomKey(key); return Do(db => db.StringIncrement(key, val)); } /// <summary> /// 为数字减少val /// </summary> /// <param name="key"></param> /// <param name="val">可以为负</param> /// <returns>减少后的值</returns> public double StringDecrement(string key, double val = 1) { key = AddSysCustomKey(key); return Do(db => db.StringDecrement(key, val)); } #endregion 同步方法 #region 异步方法 /// <summary> /// 保存单个key value /// </summary> /// <param name="key">Redis Key</param> /// <param name="value">保存的值</param> /// <param name="expiry">过期时间</param> /// <returns></returns> public async Task<bool> StringSetAsync(string key, string value, TimeSpan? expiry = default(TimeSpan?)) { key = AddSysCustomKey(key); return await Do(db => db.StringSetAsync(key, value, expiry)); } /// <summary> /// 保存多个key value /// </summary> /// <param name="keyValues">键值对</param> /// <returns></returns> public async Task<bool> StringSetAsync(List<KeyValuePair<RedisKey, RedisValue>> keyValues) { List<KeyValuePair<RedisKey, RedisValue>> newkeyValues = keyValues.Select(p => new KeyValuePair<RedisKey, RedisValue>(AddSysCustomKey(p.Key), p.Value)).ToList(); return await Do(db => db.StringSetAsync(newkeyValues.ToArray())); } /// <summary> /// 保存一个对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="obj"></param> /// <param name="expiry"></param> /// <returns></returns> public async Task<bool> StringSetAsync<T>(string key, T obj, TimeSpan? expiry = default(TimeSpan?)) { key = AddSysCustomKey(key); string json = ConvertJson(obj); return await Do(db => db.StringSetAsync(key, json, expiry)); } /// <summary> /// 获取单个key的值 /// </summary> /// <param name="key">Redis Key</param> /// <returns></returns> public async Task<string> StringGetAsync(string key) { key = AddSysCustomKey(key); return await Do(db => db.StringGetAsync(key)); } /// <summary> /// 获取多个Key /// </summary> /// <param name="listKey">Redis Key集合</param> /// <returns></returns> public async Task<RedisValue[]> StringGetAsync(List<string> listKey) { List<string> newKeys = listKey.Select(AddSysCustomKey).ToList(); return await Do(db => db.StringGetAsync(ConvertRedisKeys(newKeys))); } /// <summary> /// 获取一个key的对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <returns></returns> public async Task<T> StringGetAsync<T>(string key) { key = AddSysCustomKey(key); string result = await Do(db => db.StringGetAsync(key)); if (string.IsNullOrEmpty(result)) return default(T); return ConvertObj<T>(result); } /// <summary> /// 为数字增长val /// </summary> /// <param name="key"></param> /// <param name="val">可以为负</param> /// <returns>增长后的值</returns> public async Task<double> StringIncrementAsync(string key, double val = 1) { key = AddSysCustomKey(key); return await Do(db => db.StringIncrementAsync(key, val)); } /// <summary> /// 为数字减少val /// </summary> /// <param name="key"></param> /// <param name="val">可以为负</param> /// <returns>减少后的值</returns> public async Task<double> StringDecrementAsync(string key, double val = 1) { key = AddSysCustomKey(key); return await Do(db => db.StringDecrementAsync(key, val)); } #endregion 异步方法 #endregion String #region Hash #region 同步方法 /// <summary> /// 判断某个数据是否已经被缓存 /// </summary> /// <param name="key"></param> /// <param name="dataKey"></param> /// <returns></returns> public bool HashExists(string key, string dataKey) { key = AddSysCustomKey(key); return Do(db => db.HashExists(key, dataKey)); } /// <summary> /// 存储数据到hash表 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="dataKey"></param> /// <param name="t"></param> /// <returns></returns> public bool HashSet<T>(string key, string dataKey, T t) { key = AddSysCustomKey(key); return Do(db => { string json = ConvertJson(t); return db.HashSet(key, dataKey, json); }); } /// <summary> /// 移除hash中的某值 /// </summary> /// <param name="key"></param> /// <param name="dataKey"></param> /// <returns></returns> public bool HashDelete(string key, string dataKey) { key = AddSysCustomKey(key); return Do(db => db.HashDelete(key, dataKey)); } /// <summary> /// 移除hash中的多个值 /// </summary> /// <param name="key"></param> /// <param name="dataKeys"></param> /// <returns></returns> public long HashDelete(string key, List<RedisValue> dataKeys) { key = AddSysCustomKey(key); //List<RedisValue> dataKeys1 = new List<RedisValue>() {"1","2"}; return Do(db => db.HashDelete(key, dataKeys.ToArray())); } /// <summary> /// 从hash表获取数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="dataKey"></param> /// <returns></returns> public T HashGet<T>(string key, string dataKey) { key = AddSysCustomKey(key); return Do(db => { string value = db.HashGet(key, dataKey); if (string.IsNullOrEmpty(value)) return default(T); return ConvertObj<T>(value); }); } /// <summary> /// 为数字增长val /// </summary> /// <param name="key"></param> /// <param name="dataKey"></param> /// <param name="val">可以为负</param> /// <returns>增长后的值</returns> public double HashIncrement(string key, string dataKey, double val = 1) { key = AddSysCustomKey(key); return Do(db => db.HashIncrement(key, dataKey, val)); } /// <summary> /// 为数字减少val /// </summary> /// <param name="key"></param> /// <param name="dataKey"></param> /// <param name="val">可以为负</param> /// <returns>减少后的值</returns> public double HashDecrement(string key, string dataKey, double val = 1) { key = AddSysCustomKey(key); return Do(db => db.HashDecrement(key, dataKey, val)); } /// <summary> /// 获取hashkey所有Redis key /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <returns></returns> public List<T> HashKeys<T>(string key) { key = AddSysCustomKey(key); return Do(db => { RedisValue[] values = db.HashKeys(key); return ConvetList<T>(values); }); } #endregion 同步方法 #region 异步方法 /// <summary> /// 判断某个数据是否已经被缓存 /// </summary> /// <param name="key"></param> /// <param name="dataKey"></param> /// <returns></returns> public async Task<bool> HashExistsAsync(string key, string dataKey) { key = AddSysCustomKey(key); return await Do(db => db.HashExistsAsync(key, dataKey)); } /// <summary> /// 存储数据到hash表 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="dataKey"></param> /// <param name="t"></param> /// <returns></returns> public async Task<bool> HashSetAsync<T>(string key, string dataKey, T t) { key = AddSysCustomKey(key); return await Do(db => { string json = ConvertJson(t); return db.HashSetAsync(key, dataKey, json); }); } /// <summary> /// 移除hash中的某值 /// </summary> /// <param name="key"></param> /// <param name="dataKey"></param> /// <returns></returns> public async Task<bool> HashDeleteAsync(string key, string dataKey) { key = AddSysCustomKey(key); return await Do(db => db.HashDeleteAsync(key, dataKey)); } /// <summary> /// 移除hash中的多个值 /// </summary> /// <param name="key"></param> /// <param name="dataKeys"></param> /// <returns></returns> public async Task<long> HashDeleteAsync(string key, List<RedisValue> dataKeys) { key = AddSysCustomKey(key); //List<RedisValue> dataKeys1 = new List<RedisValue>() {"1","2"}; return await Do(db => db.HashDeleteAsync(key, dataKeys.ToArray())); } /// <summary> /// 从hash表获取数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="dataKey"></param> /// <returns></returns> public async Task<T> HashGeAsync<T>(string key, string dataKey) { key = AddSysCustomKey(key); string value = await Do(db => db.HashGetAsync(key, dataKey)); return ConvertObj<T>(value); } /// <summary> /// 为数字增长val /// </summary> /// <param name="key"></param> /// <param name="dataKey"></param> /// <param name="val">可以为负</param> /// <returns>增长后的值</returns> public async Task<double> HashIncrementAsync(string key, string dataKey, double val = 1) { key = AddSysCustomKey(key); return await Do(db => db.HashIncrementAsync(key, dataKey, val)); } /// <summary> /// 为数字减少val /// </summary> /// <param name="key"></param> /// <param name="dataKey"></param> /// <param name="val">可以为负</param> /// <returns>减少后的值</returns> public async Task<double> HashDecrementAsync(string key, string dataKey, double val = 1) { key = AddSysCustomKey(key); return await Do(db => db.HashDecrementAsync(key, dataKey, val)); } /// <summary> /// 获取hashkey所有Redis key /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <returns></returns> public async Task<List<T>> HashKeysAsync<T>(string key) { key = AddSysCustomKey(key); RedisValue[] values = await Do(db => db.HashKeysAsync(key)); return ConvetList<T>(values); } #endregion 异步方法 #endregion Hash #region List #region 同步方法 /// <summary> /// 移除指定ListId的内部List的值 /// </summary> /// <param name="key"></param> /// <param name="value"></param> public void ListRemove<T>(string key, T value) { key = AddSysCustomKey(key); Do(db => db.ListRemove(key, ConvertJson(value))); } /// <summary> /// 获取指定key的List /// </summary> /// <param name="key"></param> /// <returns></returns> public List<T> ListRange<T>(string key) { key = AddSysCustomKey(key); return Do(redis => { var values = redis.ListRange(key); return ConvetList<T>(values); }); } /// <summary> /// 入队 /// </summary> /// <param name="key"></param> /// <param name="value"></param> public void ListRightPush<T>(string key, T value) { key = AddSysCustomKey(key); Do(db => db.ListRightPush(key, ConvertJson(value))); } /// <summary> /// 出队 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <returns></returns> public T ListRightPop<T>(string key) { key = AddSysCustomKey(key); return Do(db => { var value = db.ListRightPop(key); if (string.IsNullOrEmpty(value)) return default(T); return ConvertObj<T>(value); }); } /// <summary> /// 入栈 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="value"></param> public void ListLeftPush<T>(string key, T value) { key = AddSysCustomKey(key); Do(db => db.ListLeftPush(key, ConvertJson(value))); } /// <summary> /// 出栈 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <returns></returns> public T ListLeftPop<T>(string key) { key = AddSysCustomKey(key); return Do(db => { var value = db.ListLeftPop(key); if (string.IsNullOrEmpty(value)) return default(T); return ConvertObj<T>(value); }); } /// <summary> /// 获取集合中的数量 /// </summary> /// <param name="key"></param> /// <returns></returns> public long ListLength(string key) { key = AddSysCustomKey(key); return Do(redis => redis.ListLength(key)); } #endregion 同步方法 #region 异步方法 /// <summary> /// 移除指定ListId的内部List的值 /// </summary> /// <param name="key"></param> /// <param name="value"></param> public async Task<long> ListRemoveAsync<T>(string key, T value) { key = AddSysCustomKey(key); return await Do(db => db.ListRemoveAsync(key, ConvertJson(value))); } /// <summary> /// 获取指定key的List /// </summary> /// <param name="key"></param> /// <returns></returns> public async Task<List<T>> ListRangeAsync<T>(string key) { key = AddSysCustomKey(key); var values = await Do(redis => redis.ListRangeAsync(key)); return ConvetList<T>(values); } /// <summary> /// 入队 /// </summary> /// <param name="key"></param> /// <param name="value"></param> public async Task<long> ListRightPushAsync<T>(string key, T value) { key = AddSysCustomKey(key); return await Do(db => db.ListRightPushAsync(key, ConvertJson(value))); } /// <summary> /// 出队 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <returns></returns> public async Task<T> ListRightPopAsync<T>(string key) { key = AddSysCustomKey(key); var value = await Do(db => db.ListRightPopAsync(key)); return ConvertObj<T>(value); } /// <summary> /// 入栈 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="value"></param> public async Task<long> ListLeftPushAsync<T>(string key, T value) { key = AddSysCustomKey(key); return await Do(db => db.ListLeftPushAsync(key, ConvertJson(value))); } /// <summary> /// 出栈 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <returns></returns> public async Task<T> ListLeftPopAsync<T>(string key) { key = AddSysCustomKey(key); var value = await Do(db => db.ListLeftPopAsync(key)); if (string.IsNullOrEmpty(value)) return default(T); return ConvertObj<T>(value); } /// <summary> /// 获取集合中的数量 /// </summary> /// <param name="key"></param> /// <returns></returns> public async Task<long> ListLengthAsync(string key) { key = AddSysCustomKey(key); return await Do(redis => redis.ListLengthAsync(key)); } #endregion 异步方法 #endregion List #region SortedSet 有序集合 #region 同步方法 /// <summary> /// 添加 /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="score"></param> public bool SortedSetAdd<T>(string key, T value, double score) { key = AddSysCustomKey(key); return Do(redis => redis.SortedSetAdd(key, ConvertJson<T>(value), score)); } /// <summary> /// 删除 /// </summary> /// <param name="key"></param> /// <param name="value"></param> public bool SortedSetRemove<T>(string key, T value) { key = AddSysCustomKey(key); return Do(redis => redis.SortedSetRemove(key, ConvertJson(value))); } /// <summary> /// 获取全部 /// </summary> /// <param name="key"></param> /// <returns></returns> public List<T> SortedSetRangeByRank<T>(string key) { key = AddSysCustomKey(key); return Do(redis => { var values = redis.SortedSetRangeByRank(key); return ConvetList<T>(values); }); } /// <summary> /// 获取集合中的数量 /// </summary> /// <param name="key"></param> /// <returns></returns> public long SortedSetLength(string key) { key = AddSysCustomKey(key); return Do(redis => redis.SortedSetLength(key)); } #endregion 同步方法 #region 异步方法 /// <summary> /// 添加 /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="score"></param> public async Task<bool> SortedSetAddAsync<T>(string key, T value, double score) { key = AddSysCustomKey(key); return await Do(redis => redis.SortedSetAddAsync(key, ConvertJson<T>(value), score)); } /// <summary> /// 删除 /// </summary> /// <param name="key"></param> /// <param name="value"></param> public async Task<bool> SortedSetRemoveAsync<T>(string key, T value) { key = AddSysCustomKey(key); return await Do(redis => redis.SortedSetRemoveAsync(key, ConvertJson(value))); } /// <summary> /// 获取全部 /// </summary> /// <param name="key"></param> /// <returns></returns> public async Task<List<T>> SortedSetRangeByRankAsync<T>(string key) { key = AddSysCustomKey(key); var values = await Do(redis => redis.SortedSetRangeByRankAsync(key)); return ConvetList<T>(values); } /// <summary> /// 获取集合中的数量 /// </summary> /// <param name="key"></param> /// <returns></returns> public async Task<long> SortedSetLengthAsync(string key) { key = AddSysCustomKey(key); return await Do(redis => redis.SortedSetLengthAsync(key)); } #endregion 异步方法 #endregion SortedSet 有序集合 #region key /// <summary> /// 删除单个key /// </summary> /// <param name="key">redis key</param> /// <returns>是否删除成功</returns> public bool KeyDelete(string key) { key = AddSysCustomKey(key); return Do(db => db.KeyDelete(key)); } /// <summary> /// 删除多个key /// </summary> /// <param name="keys">rediskey</param> /// <returns>成功删除的个数</returns> public long KeyDelete(List<string> keys) { List<string> newKeys = keys.Select(AddSysCustomKey).ToList(); return Do(db => db.KeyDelete(ConvertRedisKeys(newKeys))); } /// <summary> /// 判断key是否存储 /// </summary> /// <param name="key">redis key</param> /// <returns></returns> public bool KeyExists(string key) { key = AddSysCustomKey(key); return Do(db => db.KeyExists(key)); } /// <summary> /// 重新命名key /// </summary> /// <param name="key">就的redis key</param> /// <param name="newKey">新的redis key</param> /// <returns></returns> public bool KeyRename(string key, string newKey) { key = AddSysCustomKey(key); return Do(db => db.KeyRename(key, newKey)); } /// <summary> /// 设置Key的时间 /// </summary> /// <param name="key">redis key</param> /// <param name="expiry"></param> /// <returns></returns> public bool KeyExpire(string key, TimeSpan? expiry = default(TimeSpan?)) { key = AddSysCustomKey(key); return Do(db => db.KeyExpire(key, expiry)); } #endregion key #region 发布订阅 /// <summary> /// Redis发布订阅 订阅 /// </summary> /// <param name="subChannel"></param> /// <param name="handler"></param> public void Subscribe(string subChannel, Action<RedisChannel, RedisValue> handler = null) { ISubscriber sub = _conn.GetSubscriber(); sub.Subscribe(subChannel, (channel, message) => { if (handler == null) { Console.WriteLine(subChannel + " 订阅收到消息:" + message); } else { handler(channel, message); } }); } /// <summary> /// Redis发布订阅 发布 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="channel"></param> /// <param name="msg"></param> /// <returns></returns> public long Publish<T>(string channel, T msg) { ISubscriber sub = _conn.GetSubscriber(); return sub.Publish(channel, ConvertJson(msg)); } /// <summary> /// Redis发布订阅 取消订阅 /// </summary> /// <param name="channel"></param> public void Unsubscribe(string channel) { ISubscriber sub = _conn.GetSubscriber(); sub.Unsubscribe(channel); } /// <summary> /// Redis发布订阅 取消全部订阅 /// </summary> public void UnsubscribeAll() { ISubscriber sub = _conn.GetSubscriber(); sub.UnsubscribeAll(); } #endregion 发布订阅 #region 其他 /// <summary> /// 创建事物 /// </summary> /// <returns></returns> public ITransaction CreateTransaction() { return GetDatabase().CreateTransaction(); } /// <summary> /// 获取缓存库 /// </summary> /// <returns></returns> public IDatabase GetDatabase() { return _conn.GetDatabase(DbNum); } /// <summary> /// 根据链接地址获取Redis缓存 /// </summary> /// <param name="hostAndPort"></param> /// <returns></returns> public IServer GetServer(string hostAndPort) { return _conn.GetServer(hostAndPort); } /// <summary> /// 设置前缀 /// </summary> /// <param name="customKey"></param> public void SetSysCustomKey(string customKey) { CustomKey = customKey; } #endregion 其他 #region 辅助方法 /// <summary> /// 追加系统缓存Key前缀 /// </summary> /// <param name="oldKey"></param> /// <returns></returns> private string AddSysCustomKey(string oldKey) { var prefixKey = CustomKey ?? RedisConnection.SysCustomKey; return prefixKey + oldKey; } private T Do<T>(Func<IDatabase, T> func) { IDatabase database = _conn.GetDatabase(DbNum); return func(database); } public string ConvertJson<T>(T value) { string result = value is string ? value.ToString() : JsonConvert.SerializeObject(value); return result; } public T ConvertObj<T>(RedisValue value) { return JsonConvert.DeserializeObject<T>(value); } private List<T> ConvetList<T>(RedisValue[] values) { List<T> result = new List<T>(); foreach (var item in values) { var model = ConvertObj<T>(item); result.Add(model); } return result; } private RedisKey[] ConvertRedisKeys(List<string> redisKeys) { return redisKeys.Select(redisKey => (RedisKey)redisKey).ToArray(); } public void Dispose() { return; } #endregion 辅助方法 } }
29.908555
120
0.490614
[ "Apache-2.0" ]
AClumsy/ALCoder
AL.Framework.Net/RedisMQ/RedisClient.cs
31,665
C#
namespace FitPlan.Schedule { using System; using System.Collections; using System.ComponentModel; public class DayCollection : CollectionBase { public event CollectionChangeEventHandler CollectionChanged; public DayCollection() { } public Day this[int index] { get { return (Day)this.List[index]; } set { this.List[index] = value; } } public new int Count { get { return this.List.Count; } } /// <summary> /// Adds a day to the list. Days are sorted afterward to maintain proper order. /// </summary> /// <param name="Day">New day to add</param> public void Add(Day day) { this.List.Add(day); day.PropertyChanged += new PropertyChangedEventHandler(day_PropertyChanged); Sort(); if (CollectionChanged != null) CollectionChanged.Invoke(this, new CollectionChangeEventArgs(CollectionChangeAction.Add, day)); } /// <summary> /// Removes a day from the list. /// </summary> /// <param name="Day">Day to remove</param> public void Remove(Day day) { if (this.List.Contains(day)) { this.List.Remove(day); } } protected override void OnRemove(int index, object value) { Day day = value as Day; day.PropertyChanged -= day_PropertyChanged; base.OnRemove(index, value); if (CollectionChanged != null) CollectionChanged.Invoke(this, new CollectionChangeEventArgs(CollectionChangeAction.Remove, day)); } public void Sort() { this.InnerList.Sort(); } public bool Contains(object value) { return this.List.Contains(value); } /// <summary> /// Determines the index of a specific Day in the list. /// </summary> /// <param name="Day">The Day to locate in the list</param> /// <returns></returns> public int IndexOf(Day day) { return List.IndexOf(day); } protected override void OnValidate(object value) { base.OnValidate(value); if (!(value is Day)) throw new ArgumentException("Collection only supports Day objects"); } private void day_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (CollectionChanged != null) CollectionChanged.Invoke(this, new CollectionChangeEventArgs(CollectionChangeAction.Refresh, sender)); } } }
27.73
118
0.547061
[ "Apache-2.0" ]
mechgt/fitplan
FitPlan/Schedule/DayCollection.cs
2,775
C#
using System; using FluentAssertions; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using Xunit; namespace Lsp.Tests.Models { public class DocumentFormattingParamsTests { [Theory] [JsonFixture] public void SimpleTest(string expected) { var model = new DocumentFormattingParams { Options = new FormattingOptions { { "abc", 1 } }, TextDocument = new TextDocumentIdentifier(new Uri("file:///abc123.cs")) }; var result = Fixture.SerializeObject(model); result.Should().Be(expected); var deresult = new Serializer(ClientVersion.Lsp3).DeserializeObject<DocumentFormattingParams>(expected); deresult.Should().BeEquivalentTo(model); } } }
31.516129
116
0.647902
[ "MIT" ]
kamit9171/csharp-language-server-protocol
test/Lsp.Tests/Models/DocumentFormattingParamsTests.cs
977
C#
using PropertyChanged; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace ee.iLawyer.Ops.Contact.DTO { /// <summary> /// 法院信息 /// </summary> [AddINotifyPropertyChangedInterface] [DataContract] public class Court:ICloneable { /// <summary> /// 主键 /// </summary> [DataMember] public int Id { get; set; } /// <summary> /// 法院名 /// </summary> [DataMember] public string Name { get; set; } /// <summary> /// 级别 /// </summary> [DataMember] public CourtRank Rank { get; set; } /// <summary> /// 省 /// </summary> [DataMember] public string Province { get; set; } /// <summary> /// 市 /// </summary> [DataMember] public string City { get; set; } /// <summary> /// 区 /// </summary> [DataMember] public string County { get; set; } /// <summary> /// 地址 /// </summary> [DataMember] public string Address { get; set; } /// <summary> /// 联系电话 /// </summary> [DataMember] public string ContactNo { get; set; } public object Clone() { return this.MemberwiseClone(); } } }
21.455882
45
0.483208
[ "Apache-2.0" ]
Egoily/iLawyer
02.Domain/ee.iLawyer.Ops.Contact/DTO/Court.cs
1,501
C#
using System; using System.IO; using System.Linq; namespace GBAEmulator.Memory.Backup { class BackupSRAM : IBackup { byte[] Storage = new byte[0x8000]; public void Init() { for (int i = 0; i < 0x8000; i++) { Storage[i] = 0xff; } } public void Dump(string FileName) { try { File.WriteAllBytes(FileName, this.Storage); } catch (Exception e) { // something went wrong Console.Error.WriteLine("Something went wrong while dumping the save data... " + e.Message); } } public void Load(string FileName) { try { this.Storage = File.ReadAllBytes(FileName); } catch (Exception e) { // something went wrong Console.Error.WriteLine("Something went wrong while dumping the save data... " + e.Message); } } public byte Read(uint address) { return this.Storage[address & 0x7fff]; } public bool Write(uint address, byte value) { this.Storage[address & 0x7fff] = value; return true; } } }
24.035714
108
0.465825
[ "MIT" ]
DenSinH/GBAC-
GBAEmulator/Memory/Backup/Memory.Backup.SRAM.cs
1,348
C#
using System; using System.Collections.Generic; namespace Database { public class DupesVsSolidTransferArmFetch : ColonyAchievementRequirement, AchievementRequirementSerialization_Deprecated { public float percentage; public int numCycles; public int currentCycleCount; public bool armsOutPerformingDupesThisCycle; public DupesVsSolidTransferArmFetch(float percentage, int numCycles) { this.percentage = percentage; this.numCycles = numCycles; } public override bool Success() { Dictionary<int, int> fetchDupeChoreDeliveries = SaveGame.Instance.GetComponent<ColonyAchievementTracker>().fetchDupeChoreDeliveries; Dictionary<int, int> fetchAutomatedChoreDeliveries = SaveGame.Instance.GetComponent<ColonyAchievementTracker>().fetchAutomatedChoreDeliveries; int num = 0; currentCycleCount = 0; for (int i = GameClock.Instance.GetCycle() - numCycles; i < GameClock.Instance.GetCycle(); i++) { if (fetchAutomatedChoreDeliveries.ContainsKey(i) && (!fetchDupeChoreDeliveries.ContainsKey(i) || (float)fetchDupeChoreDeliveries[i] < (float)fetchAutomatedChoreDeliveries[i] * percentage)) { num++; if (num >= numCycles) { currentCycleCount = numCycles; return true; } } else { currentCycleCount = Math.Max(currentCycleCount, num); num = 0; } } return false; } public void Deserialize(IReader reader) { numCycles = reader.ReadInt32(); percentage = reader.ReadSingle(); } } }
27.272727
192
0.731333
[ "MIT" ]
undancer/oni-data
Managed/main/Database/DupesVsSolidTransferArmFetch.cs
1,500
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace batch08162021dockerdemo { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
26.111111
70
0.651064
[ "MIT" ]
08162021-dotnet-uta/08162021-batch-repo
demos/DockerDemo/batch08162021dockerdemo/Program.cs
705
C#
using System.ComponentModel.Composition; using AssemblyToProcess.Core; namespace AssemblyToProcess.Signed { [Export(typeof(IExportable))] public class AlreadyExportedInstance : IExportable { } }
19.363636
54
0.760563
[ "MIT" ]
jasonwoods-7/Vandelay.PostSharp
Tests/AssemblyToProcess/Signed/AlreadyExportedInstance.cs
215
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace rdip_server { interface IPacketReceiver { void receivePacket(string addr, int port, string packet); } }
18
66
0.683761
[ "BSD-3-Clause" ]
cheesestraws/rdip
rdip-server/rdip-server/IPacketReceiver.cs
236
C#
using System; using FluentMigrator.Runner.Generators.Oracle; using NUnit.Framework; using NUnit.Should; namespace FluentMigrator.Tests.Unit.Generators.Oracle { [TestFixture] public class OracleDataTests : BaseDataTests { protected OracleGenerator Generator; [SetUp] public void Setup() { Generator = new OracleGenerator(); } [Test] public override void CanDeleteDataForAllRowsWithCustomSchema() { var expression = GeneratorTestHelper.GetDeleteDataAllRowsExpression(); expression.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("DELETE FROM TestSchema.TestTable1 WHERE 1 = 1"); } [Test] public override void CanDeleteDataForAllRowsWithDefaultSchema() { var expression = GeneratorTestHelper.GetDeleteDataAllRowsExpression(); var result = Generator.Generate(expression); result.ShouldBe("DELETE FROM TestTable1 WHERE 1 = 1"); } [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" + Environment.NewLine + ";" + Environment.NewLine + "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" + Environment.NewLine + ";" + Environment.NewLine + "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 CanDeleteDataWithDbNullCriteria() { var expression = GeneratorTestHelper.GetDeleteDataExpressionWithDbNullValue(); 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 ALL INTO TestSchema.TestTable1 (Id, Name, Website) VALUES (1, 'Just''in', 'codethinked.com')"; expected += " INTO TestSchema.TestTable1 (Id, Name, Website) VALUES (2, 'Na\\te', 'kohari.org')"; expected += " SELECT 1 FROM DUAL"; var result = Generator.Generate(expression); result.ShouldBe(expected); } [Test] public override void CanInsertDataWithDefaultSchema() { var expression = GeneratorTestHelper.GetInsertDataExpression(); var expected = "INSERT ALL INTO TestTable1 (Id, Name, Website) VALUES (1, 'Just''in', 'codethinked.com')"; expected += " INTO TestTable1 (Id, Name, Website) VALUES (2, 'Na\\te', 'kohari.org')"; expected += " SELECT 1 FROM DUAL"; var result = Generator.Generate(expression); result.ShouldBe(expected); } [Test] public override void CanInsertGuidDataWithCustomSchema() { //Oracle can not insert GUID data using string representation var expression = GeneratorTestHelper.GetInsertGUIDExpression(new Guid("7E487B79-626C-4E7D-811C-BC30AB31C564")); expression.SchemaName = "TestSchema"; var result = Generator.Generate(expression); result.ShouldBe("INSERT ALL INTO TestSchema.TestTable1 (guid) VALUES ('797B487E6C627D4E811CBC30AB31C564') SELECT 1 FROM DUAL"); } [Test] public override void CanInsertGuidDataWithDefaultSchema() { //Oracle can not insert GUID data using string representation var expression = GeneratorTestHelper.GetInsertGUIDExpression(new Guid("7E487B79-626C-4E7D-811C-BC30AB31C564")); var result = Generator.Generate(expression); result.ShouldBe("INSERT ALL INTO TestTable1 (guid) VALUES ('797B487E6C627D4E811CBC30AB31C564') SELECT 1 FROM DUAL"); } [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 WHERE 1 = 1"); } [Test] public override void CanUpdateDataForAllDataWithDefaultSchema() { var expression = GeneratorTestHelper.GetUpdateDataExpressionWithAllRows(); var result = Generator.Generate(expression); result.ShouldBe("UPDATE TestTable1 SET Name = 'Just''in', Age = 25 WHERE 1 = 1"); } [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"); } [Test] public override void CanUpdateDataWithDbNullCriteria() { var expression = GeneratorTestHelper.GetUpdateDataExpressionWithDbNullValue(); var result = Generator.Generate(expression); result.ShouldBe("UPDATE TestTable1 SET Name = 'Just''in', Age = 25 WHERE Id = 9 AND Homepage IS NULL"); } } }
39.090909
139
0.632285
[ "Apache-2.0" ]
quesadaao/fluentmigrator
test/FluentMigrator.Tests/Unit/Generators/Oracle/OracleDataTests.cs
7,310
C#
using System; using System.Threading.Tasks; using RetailOnTheEdge.Web.Models; namespace RetailOnTheEdge.Web.Services.Interfaces { public interface IIoTCentralService { Task<IoTCentralApiDeviceState> GetDeviceState(); Task SetVideoPathProperty(string value); } }
19.857143
52
0.791367
[ "MIT" ]
AIcadium/IoTDemos
RetailDemo/src/RetailOnTheEdge.Web/Services/Interfaces/IIoTCentralService.cs
278
C#
using Avalonia.Controls; using Avalonia.Markup.Xaml; namespace WalletWasabi.Gui.Controls.WalletExplorer { public class WalletExplorerView : UserControl { public WalletExplorerView() { InitializeComponent(); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } } }
16.105263
50
0.748366
[ "MIT" ]
0racl3z/WalletWasabi
WalletWasabi.Gui/Controls/WalletExplorer/WalletExplorerView.xaml.cs
306
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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void BlendInt164() { var test = new ImmBinaryOpTest__BlendInt164(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmBinaryOpTest__BlendInt164 { private struct TestStruct { public Vector256<Int16> _fld1; public Vector256<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__BlendInt164 testClass) { var result = Avx2.Blend(_fld1, _fld2, 4); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector256<Int16> _clsVar1; private static Vector256<Int16> _clsVar2; private Vector256<Int16> _fld1; private Vector256<Int16> _fld2; private SimpleBinaryOpTest__DataTable<Int16, Int16, Int16> _dataTable; static ImmBinaryOpTest__BlendInt164() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); } public ImmBinaryOpTest__BlendInt164() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new SimpleBinaryOpTest__DataTable<Int16, Int16, Int16>(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.Blend( Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr), 4 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.Blend( Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)), 4 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.Blend( Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)), 4 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr), (byte)4 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)), (byte)4 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)), (byte)4 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.Blend( _clsVar1, _clsVar2, 4 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr); var result = Avx2.Blend(left, right, 4); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)); var result = Avx2.Blend(left, right, 4); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)); var result = Avx2.Blend(left, right, 4); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { var test = new ImmBinaryOpTest__BlendInt164(); var result = Avx2.Blend(test._fld1, test._fld2, 4); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { var result = Avx2.Blend(_fld1, _fld2, 4); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { var test = TestStruct.Create(); var result = Avx2.Blend(test._fld1, test._fld2, 4); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Int16> left, Vector256<Int16> right, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { if (result[0] != (((4 & (1 << 0)) == 0) ? left[0] : right[0])) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((i < 8) ? (((4 & (1 << i)) == 0) ? left[i] : right[i]) : (((4 & (1 << (i - 8))) == 0) ? left[i] : right[i]))) { Succeeded = false; break; } } } if (!Succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Blend)}<Int16>(Vector256<Int16>.4, Vector256<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); } } } }
43.317585
187
0.571619
[ "MIT" ]
MSHOY/coreclr
tests/src/JIT/HardwareIntrinsics/X86/Avx2/Blend.Int16.4.cs
16,504
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. namespace System.Data.Entity.Migrations.Infrastructure { using System.Collections.Generic; using System.Data.Common; using System.Data.Entity.Core.Common.CommandTrees; using System.Data.Entity.Core.Metadata.Edm; using System.Data.Entity.Core.Objects; using System.Data.Entity.Infrastructure; using System.Data.Entity.Internal; using System.Data.Entity.ModelConfiguration.Edm; using System.Data.Entity.Spatial; using System.Data.Entity.Utilities; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; internal class ModificationCommandTreeGenerator { private readonly DbCompiledModel _compiledModel; private readonly DbConnection _connection; private readonly MetadataWorkspace _metadataWorkspace; private class TempDbContext : DbContext { [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public TempDbContext(DbCompiledModel model) : base(model) { InternalContext.InitializerDisabled = true; } [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public TempDbContext(DbConnection connection, DbCompiledModel model) : base(connection, model, false) { InternalContext.InitializerDisabled = true; } } public ModificationCommandTreeGenerator(DbModel model, DbConnection connection = null) { DebugCheck.NotNull(model); _compiledModel = model.Compile(); _connection = connection; using (var context = CreateContext()) { _metadataWorkspace = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace; } } private DbContext CreateContext() { return _connection == null ? new TempDbContext(_compiledModel) : new TempDbContext(_connection, _compiledModel); } public IEnumerable<DbInsertCommandTree> GenerateAssociationInsert(string associationIdentity) { DebugCheck.NotEmpty(associationIdentity); return GenerateAssociation<DbInsertCommandTree>(associationIdentity, EntityState.Added); } public IEnumerable<DbDeleteCommandTree> GenerateAssociationDelete(string associationIdentity) { DebugCheck.NotEmpty(associationIdentity); return GenerateAssociation<DbDeleteCommandTree>(associationIdentity, EntityState.Deleted); } private IEnumerable<TCommandTree> GenerateAssociation<TCommandTree>(string associationIdentity, EntityState state) where TCommandTree : DbCommandTree { DebugCheck.NotEmpty(associationIdentity); var associationType = _metadataWorkspace .GetItem<AssociationType>(associationIdentity, DataSpace.CSpace); using (var context = CreateContext()) { var sourceEntityType = associationType.SourceEnd.GetEntityType(); var sourceEntity = InstantiateAndAttachEntity(sourceEntityType, context); var targetEntityType = associationType.TargetEnd.GetEntityType(); var targetEntity = sourceEntityType.GetRootType() == targetEntityType.GetRootType() ? sourceEntity : InstantiateAndAttachEntity(targetEntityType, context); var objectStateManager = ((IObjectContextAdapter)context) .ObjectContext .ObjectStateManager; objectStateManager .ChangeRelationshipState( sourceEntity, targetEntity, associationType.FullName, associationType.TargetEnd.Name, state == EntityState.Deleted ? state : EntityState.Added ); using (var commandTracer = new CommandTracer(context)) { context.SaveChanges(); foreach (var commandTree in commandTracer.CommandTrees) { yield return (TCommandTree)commandTree; } } } } private object InstantiateAndAttachEntity(EntityType entityType, DbContext context) { DebugCheck.NotNull(entityType); DebugCheck.NotNull(context); var clrType = entityType.GetClrType(); var set = context.Set(clrType); var entity = InstantiateEntity(entityType, context, clrType, set); SetFakeReferenceKeyValues(entity, entityType); SetFakeKeyValues(entity, entityType); set.Attach(entity); return entity; } private object InstantiateEntity(EntityType entityType, DbContext context, Type clrType, DbSet set) { DebugCheck.NotNull(entityType); DebugCheck.NotNull(context); DebugCheck.NotNull(clrType); DebugCheck.NotNull(set); object entity; if (!clrType.IsAbstract()) { entity = set.Create(); } else { var derivedEntityType = _metadataWorkspace .GetItems<EntityType>(DataSpace.CSpace) .First(et => entityType.IsAncestorOf(et) && !et.Abstract); entity = context.Set(derivedEntityType.GetClrType()).Create(); } InstantiateComplexProperties(entity, entityType.Properties); return entity; } public IEnumerable<DbModificationCommandTree> GenerateInsert(string entityIdentity) { DebugCheck.NotEmpty(entityIdentity); return Generate(entityIdentity, EntityState.Added); } public IEnumerable<DbModificationCommandTree> GenerateUpdate(string entityIdentity) { DebugCheck.NotEmpty(entityIdentity); return Generate(entityIdentity, EntityState.Modified); } public IEnumerable<DbModificationCommandTree> GenerateDelete(string entityIdentity) { DebugCheck.NotEmpty(entityIdentity); return Generate(entityIdentity, EntityState.Deleted); } private IEnumerable<DbModificationCommandTree> Generate(string entityIdentity, EntityState state) { DebugCheck.NotEmpty(entityIdentity); var entityType = _metadataWorkspace .GetItem<EntityType>(entityIdentity, DataSpace.CSpace); using (var context = CreateContext()) { var entity = InstantiateAndAttachEntity(entityType, context); if (state != EntityState.Deleted) { // For deletes, we need to set the state // _after_ dealing with IAs. context.Entry(entity).State = state; } ChangeRelationshipStates(context, entityType, entity, state); if (state == EntityState.Deleted) { context.Entry(entity).State = state; } HandleTableSplitting(context, entityType, entity, state); using (var commandTracer = new CommandTracer(context)) { ((IObjectContextAdapter)context).ObjectContext.SaveChanges(SaveOptions.None); foreach (var commandTree in commandTracer.CommandTrees) { yield return (DbModificationCommandTree)commandTree; } } } } private void ChangeRelationshipStates(DbContext context, EntityType entityType, object entity, EntityState state) { DebugCheck.NotNull(context); DebugCheck.NotNull(entityType); DebugCheck.NotNull(entity); var objectStateManager = ((IObjectContextAdapter)context) .ObjectContext .ObjectStateManager; var associationTypes = _metadataWorkspace .GetItems<AssociationType>(DataSpace.CSpace) .Where( at => !at.IsForeignKey && !at.IsManyToMany() && (at.SourceEnd.GetEntityType().IsAssignableFrom(entityType) || at.TargetEnd.GetEntityType().IsAssignableFrom(entityType))); foreach (var associationType in associationTypes) { AssociationEndMember principalEnd, dependentEnd; if (!associationType.TryGuessPrincipalAndDependentEnds(out principalEnd, out dependentEnd)) { principalEnd = associationType.SourceEnd; dependentEnd = associationType.TargetEnd; } if (dependentEnd.GetEntityType().IsAssignableFrom(entityType)) { var principalEntityType = principalEnd.GetEntityType(); var principalClrType = principalEntityType.GetClrType(); var set = context.Set(principalClrType); var principalStub = set.Local.Cast<object>().SingleOrDefault(); if ((principalStub == null) || (ReferenceEquals(entity, principalStub) && state == EntityState.Added)) { principalStub = InstantiateEntity(principalEntityType, context, principalClrType, set); SetFakeReferenceKeyValues(principalStub, principalEntityType); set.Attach(principalStub); } if (principalEnd.IsRequired() && state == EntityState.Modified) { // For updates with a required principal, // we need to fake delete the relationship first. var principalStubForDelete = InstantiateEntity(principalEntityType, context, principalClrType, set); SetFakeKeyValues(principalStubForDelete, principalEntityType); set.Attach(principalStubForDelete); objectStateManager .ChangeRelationshipState( entity, principalStubForDelete, associationType.FullName, principalEnd.Name, EntityState.Deleted ); } objectStateManager .ChangeRelationshipState( entity, principalStub, associationType.FullName, principalEnd.Name, state == EntityState.Deleted ? state : EntityState.Added ); } } } private void HandleTableSplitting(DbContext context, EntityType entityType, object entity, EntityState state) { DebugCheck.NotNull(context); DebugCheck.NotNull(entityType); DebugCheck.NotNull(entity); var associationTypes = _metadataWorkspace .GetItems<AssociationType>(DataSpace.CSpace) .Where( at => at.IsForeignKey && at.IsRequiredToRequired() && !at.IsSelfReferencing() && (at.SourceEnd.GetEntityType().IsAssignableFrom(entityType) || at.TargetEnd.GetEntityType().IsAssignableFrom(entityType)) && _metadataWorkspace.GetItems<AssociationType>(DataSpace.SSpace) .All(fk => fk.Name != at.Name)); // no store FK == shared table foreach (var associationType in associationTypes) { AssociationEndMember principalEnd, dependentEnd; if (!associationType.TryGuessPrincipalAndDependentEnds(out principalEnd, out dependentEnd)) { principalEnd = associationType.SourceEnd; dependentEnd = associationType.TargetEnd; } EntityType otherEntityType; var entityTypeIsPrincipal = false; if (principalEnd.GetEntityType().GetRootType() == entityType.GetRootType()) { entityTypeIsPrincipal = true; otherEntityType = dependentEnd.GetEntityType(); } else { otherEntityType = principalEnd.GetEntityType(); } var otherEntity = InstantiateAndAttachEntity(otherEntityType, context); if (!entityTypeIsPrincipal) { if (state == EntityState.Added) { // Rewrite dependent insert to update context.Entry(entity).State = EntityState.Modified; } else if (state == EntityState.Deleted) { // Rewrite dependent delete to no-op context.Entry(entity).State = EntityState.Unchanged; } } else if (state != EntityState.Modified) { context.Entry(otherEntity).State = state; } } } private static void SetFakeReferenceKeyValues(object entity, EntityType entityType) { DebugCheck.NotNull(entity); DebugCheck.NotNull(entityType); foreach (var property in entityType.KeyProperties) { var clrPropertyInfo = property.GetClrPropertyInfo(); var value = GetFakeReferenceKeyValue(property.UnderlyingPrimitiveType.PrimitiveTypeKind); if (value != null) { clrPropertyInfo.GetPropertyInfoForSet().SetValue(entity, value, null); } } } private static object GetFakeReferenceKeyValue(PrimitiveTypeKind primitiveTypeKind) { switch (primitiveTypeKind) { case PrimitiveTypeKind.Binary: return new byte[0]; case PrimitiveTypeKind.String: return "42"; case PrimitiveTypeKind.Geometry: return DefaultSpatialServices.Instance.GeometryFromText("POINT (4 2)"); case PrimitiveTypeKind.Geography: return DefaultSpatialServices.Instance.GeographyFromText("POINT (4 2)"); } return null; } private static void SetFakeKeyValues(object entity, EntityType entityType) { DebugCheck.NotNull(entity); DebugCheck.NotNull(entityType); foreach (var property in entityType.KeyProperties) { var clrPropertyInfo = property.GetClrPropertyInfo(); var value = GetFakeKeyValue(property.UnderlyingPrimitiveType.PrimitiveTypeKind); Debug.Assert(value != null); clrPropertyInfo.GetPropertyInfoForSet().SetValue(entity, value, null); } } private static object GetFakeKeyValue(PrimitiveTypeKind primitiveTypeKind) { switch (primitiveTypeKind) { case PrimitiveTypeKind.Binary: return new byte[] { 0x42 }; case PrimitiveTypeKind.Boolean: return true; case PrimitiveTypeKind.Byte: return (byte)0x42; case PrimitiveTypeKind.DateTime: return DateTime.Now; case PrimitiveTypeKind.Decimal: return 42m; case PrimitiveTypeKind.Double: return 42.0; case PrimitiveTypeKind.Guid: return Guid.NewGuid(); case PrimitiveTypeKind.Single: return 42f; case PrimitiveTypeKind.SByte: return (sbyte)42; case PrimitiveTypeKind.Int16: return (short)42; case PrimitiveTypeKind.Int32: return 42; case PrimitiveTypeKind.Int64: return 42L; case PrimitiveTypeKind.String: return "42'"; case PrimitiveTypeKind.Time: return TimeSpan.FromMilliseconds(42); case PrimitiveTypeKind.DateTimeOffset: return DateTimeOffset.Now; case PrimitiveTypeKind.Geometry: return DefaultSpatialServices.Instance.GeometryFromText("POINT (4 3)"); case PrimitiveTypeKind.Geography: return DefaultSpatialServices.Instance.GeographyFromText("POINT (4 3)"); default: Debug.Fail("Unexpected key PrimitiveTypeKind!"); break; } return null; } private static void InstantiateComplexProperties(object structuralObject, IEnumerable<EdmProperty> properties) { DebugCheck.NotNull(structuralObject); DebugCheck.NotNull(properties); foreach (var property in properties) { if (property.IsComplexType) { var clrPropertyInfo = property.GetClrPropertyInfo(); var complexObject = Activator.CreateInstance(clrPropertyInfo.PropertyType); InstantiateComplexProperties(complexObject, property.ComplexType.Properties); clrPropertyInfo.GetPropertyInfoForSet().SetValue(structuralObject, complexObject, null); } } } } }
37.155642
145
0.543879
[ "MIT" ]
dotnet/ef6tools
src/EntityFramework/Migrations/Infrastructure/ModificationCommandTreeGenerator.cs
19,100
C#
using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using HuaweiCloud.SDK.Core; namespace HuaweiCloud.SDK.Ecs.V2.Model { /// <summary> /// Response Object /// </summary> public class BatchDeleteServerNicsResponse : SdkResponse { /// <summary> /// 提交任务成功后返回的任务ID,用户可以使用该ID对任务执行情况进行查询。 /// </summary> [JsonProperty("job_id", NullValueHandling = NullValueHandling.Ignore)] public string JobId { get; set; } /// <summary> /// Get the string /// </summary> public override string ToString() { var sb = new StringBuilder(); sb.Append("class BatchDeleteServerNicsResponse {\n"); sb.Append(" jobId: ").Append(JobId).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns true if objects are equal /// </summary> public override bool Equals(object input) { return this.Equals(input as BatchDeleteServerNicsResponse); } /// <summary> /// Returns true if objects are equal /// </summary> public bool Equals(BatchDeleteServerNicsResponse input) { if (input == null) return false; return ( this.JobId == input.JobId || (this.JobId != null && this.JobId.Equals(input.JobId)) ); } /// <summary> /// Get hash code /// </summary> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.JobId != null) hashCode = hashCode * 59 + this.JobId.GetHashCode(); return hashCode; } } } }
26.855263
78
0.517883
[ "Apache-2.0" ]
Huaweicloud-SDK/huaweicloud-sdk-net-v3
Services/Ecs/V2/Model/BatchDeleteServerNicsResponse.cs
2,105
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("Features")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Features")] [assembly: AssemblyCopyright("Copyright © 2019")] [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("6584fb12-233c-447a-8537-bf0b99eb6034")] // 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.378378
84
0.746927
[ "MIT" ]
carlosefrias/csharp-linq-learning
Introduction/Features/Properties/AssemblyInfo.cs
1,384
C#
using System; using UnityEngine; namespace GraphQlClient.EventCallbacks { public abstract class Event<T> where T : Event<T> { /* * The base Event, * might have some generic text * for doing Debug.Log? */ public string Description; private bool hasFired; public delegate void EventListener(T info); private static event EventListener listeners; public static void RegisterListener(EventListener listener) { listeners += listener; } public static void UnregisterListener(EventListener listener) { listeners -= listener; } public void FireEvent() { if (hasFired) { throw new Exception("This event has already fired, to prevent infinite loops you can't refire an event"); } hasFired = true; if (listeners != null) { listeners(this as T); } } } }
27.243243
121
0.5625
[ "Apache-2.0" ]
Chefty/graphQL-client-unity
Assets/graphQl-client/Scripts/EventCallbacks/Event.cs
1,010
C#
using System; using Newtonsoft.Json; namespace TdLib { /// <summary> /// Autogenerated TDLib APIs /// </summary> public static partial class TdApi { /// <summary> /// The order of the chat in the chat list has changed. Instead of this update updateChatLastMessage, updateChatIsPinned, updateChatDraftMessage, or updateChatIsSponsored might be sent /// </summary> public partial class Update : Object { /// <summary> /// The order of the chat in the chat list has changed. Instead of this update updateChatLastMessage, updateChatIsPinned, updateChatDraftMessage, or updateChatIsSponsored might be sent /// </summary> public class UpdateChatOrder : Update { /// <summary> /// Data type for serialization /// </summary> [JsonProperty("@type")] public override string DataType { get; set; } = "updateChatOrder"; /// <summary> /// Extra data attached to the message /// </summary> [JsonProperty("@extra")] public override string Extra { get; set; } /// <summary> /// Chat identifier /// </summary> [JsonConverter(typeof(Converter))] [JsonProperty("chat_id")] public long ChatId { get; set; } /// <summary> /// New value of the order /// </summary> [JsonConverter(typeof(Converter.Int64))] [JsonProperty("order")] public Int64 Order { get; set; } } } } }
35.734694
197
0.515134
[ "MIT" ]
slctr/tdsharp
TDLib.Api/Objects/UpdateChatOrder.cs
1,751
C#
using UnityEngine; namespace FairyGUI { /// <summary> /// /// </summary> public class TextFormat { /// <summary> /// /// </summary> public int size; /// <summary> /// /// </summary> public string font; /// <summary> /// /// </summary> public Color color; /// <summary> /// /// </summary> public int lineSpacing; /// <summary> /// /// </summary> public int letterSpacing; /// <summary> /// /// </summary> public bool bold; /// <summary> /// /// </summary> public bool underline; /// <summary> /// /// </summary> public bool italic; /// <summary> /// /// </summary> public Color32[] gradientColor; /// <summary> /// /// </summary> public AlignType align; /// <summary> /// /// </summary> /// <param name="value"></param> public void SetColor(uint value) { uint rr = (value >> 16) & 0x0000ff; uint gg = (value >> 8) & 0x0000ff; uint bb = value & 0x0000ff; float r = rr / 255.0f; float g = gg / 255.0f; float b = bb / 255.0f; color = new Color(r, g, b, 1); } /// <summary> /// /// </summary> /// <param name="aFormat"></param> /// <returns></returns> public bool EqualStyle(TextFormat aFormat) { return size == aFormat.size && color.Equals(aFormat.color) && bold == aFormat.bold && underline == aFormat.underline && italic == aFormat.italic && gradientColor == aFormat.gradientColor && align == aFormat.align; } /// <summary> /// /// </summary> /// <param name="source"></param> public void CopyFrom(TextFormat source) { this.size = source.size; this.font = source.font; this.color = source.color; this.lineSpacing = source.lineSpacing; this.letterSpacing = source.letterSpacing; this.bold = source.bold; this.underline = source.underline; this.italic = source.italic; if (source.gradientColor != null) { this.gradientColor = new Color32[4]; source.gradientColor.CopyTo(this.gradientColor, 0); } else this.gradientColor = null; this.align = source.align; } } }
18.473684
61
0.57265
[ "MIT" ]
corefan/CatLib
CatLib.Unity/Assets/CatLib/Lib/FairyGUI/FairyGUI/Core/Text/TextFormat.cs
2,108
C#
using _2STBV.Common.Classes; using _2STBV.Util; using System.Configuration; using System.Net; using System.Net.Http; using System.Web.Http; namespace _2STBV.Controllers { public class AuthenticationController : ApiController { private string _telegramApiUrl; public AuthenticationController() { _telegramApiUrl = ConfigurationManager.AppSettings.Get("TelegramApiUrl"); } public HttpResponseMessage EnqueueOTP(string token, string OTP, [FromBody]User user) { var sendMessageUrl = _telegramApiUrl + "/sendMessage"; if (!RequestStorage.Storage.ContainsKey(user.id)) RequestStorage.Storage.Add(user.id, OTP); return new HttpResponseMessage(HttpStatusCode.OK); } } }
27.448276
103
0.677136
[ "MIT" ]
azzimuth/2STBV
2STBV/Controllers/AuthenticationController.cs
798
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using BTCPayServer.Payments; using BTCPayServer.Services; using Microsoft.AspNetCore.Mvc.Rendering; namespace BTCPayServer.Models.StoreViewModels { public class CheckoutAppearanceViewModel { public class Format { public string Name { get; set; } public string Value { get; set; } public PaymentMethodId PaymentId { get; set; } } public SelectList PaymentMethods { get; set; } public void SetLanguages(LanguageService langService, string defaultLang) { defaultLang = langService.GetLanguages().Any(language => language.Code == defaultLang) ? defaultLang : "en"; var choices = langService.GetLanguages().Select(o => new Format() { Name = o.DisplayName, Value = o.Code }).ToArray().OrderBy(o => o.Name); var chosen = choices.FirstOrDefault(f => f.Value == defaultLang) ?? choices.FirstOrDefault(); Languages = new SelectList(choices, nameof(chosen.Value), nameof(chosen.Name), chosen); DefaultLang = chosen.Value; } public SelectList Languages { get; set; } [Display(Name = "Default payment method on checkout")] public string DefaultPaymentMethod { get; set; } [Display(Name = "Requires a refund email")] public bool RequiresRefundEmail { get; set; } [Display(Name = "Only enable the payment method after user explicitly chooses it")] public bool LazyPaymentMethods { get; set; } [Display(Name = "Redirect invoice to redirect url automatically after paid")] public bool RedirectAutomatically { get; set; } [Display(Name = "Auto-detect language on checkout")] public bool AutoDetectLanguage { get; set; } [Display(Name = "Default language on checkout")] public string DefaultLang { get; set; } [Display(Name = "Link to a custom CSS stylesheet")] public string CustomCSS { get; set; } [Display(Name = "Link to a custom logo")] public string CustomLogo { get; set; } [Display(Name = "Custom HTML title to display on Checkout page")] public string HtmlTitle { get; set; } public List<PaymentMethodCriteriaViewModel> PaymentMethodCriteria { get; set; } } public class PaymentMethodCriteriaViewModel { public string PaymentMethod { get; set; } public string Value { get; set; } public CriteriaType Type { get; set; } public enum CriteriaType { GreaterThan, LessThan } public static string ToString(CriteriaType type) { switch (type) { case CriteriaType.GreaterThan: return "Greater than"; case CriteriaType.LessThan: return "Less than"; default: throw new ArgumentOutOfRangeException(nameof(type), type, null); } } } }
35.793103
151
0.618818
[ "MIT" ]
BTCparadigm/btcpayserver
BTCPayServer/Models/StoreViewModels/CheckoutAppearanceViewModel.cs
3,114
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Alabo.Domains.Entities; using Alabo.Domains.Repositories.Mongo.Extension; using Alabo.Industry.Shop.AfterSales.Domain.Enums; using MongoDB.Bson; using Newtonsoft.Json; namespace Alabo.Industry.Shop.AfterSales.Domain.Entities { /// <summary> /// 售后,订单完成以后开始 /// 比如冰箱等 /// </summary> [Table("AfterSale_AfterSale")] public class AfterSale : AggregateMongodbUserRoot<AfterSale> { /// <summary> /// 商品ID /// </summary> [Required] public long ProductId { get; set; } /// <summary> /// 店铺ID,该字段为冗余字段,方便以后查询 /// </summary> [Required] [JsonConverter(typeof(ObjectIdConverter))] public ObjectId StoreId { get; set; } /// <summary> /// 订单ID /// </summary> [Required] public long OrderId { get; set; } /// <summary> /// 状态 1已发货 0 未发货 /// </summary> public AfterSaleStatus Status { get; set; } /// <summary> /// 原因 选择 /// </summary> [Required] public string Reason { get; set; } /// <summary> /// 金额 包含运费,默认为商品金额 /// </summary> [Required] public decimal Amount { get; set; } /// <summary> /// 说明 /// </summary> public string Description { get; set; } /// <summary> /// 凭证,图片(路径 最多五张 /// </summary> public List<string> Images { get; set; } } }
25.671875
88
0.53804
[ "MIT" ]
tongxin3267/alabo
src/04.industry/02-Alabo.Industry.Shop/AfterSales/Domain/Entities/AfterSale.cs
1,791
C#
// https://github.com/electron/electron/blob/master/atom/common/keyboard_util.cc using System; namespace WebSharpJs.Electron { internal static class KeyboardUtilities { public static (string, bool) KeyboardCodeFromCharCode(char c) { c = Char.ToLower(c); bool shifted = false; switch (c) { case (char)0x08: // backspace return (AcceleratorKeys.Backspace.ToString(), false); case (char)0x7F: // delete return (AcceleratorKeys.Delete.ToString(), false); case (char)0x09: // tab return (AcceleratorKeys.Tab.ToString(), false); case (char)0x0D: // return return (AcceleratorKeys.Return.ToString(), false); case (char)0x1B: // escape return (AcceleratorKeys.Escape.ToString(), false); case ' ': // space return (AcceleratorKeys.Space.ToString(), false); case 'a': return ("A", false); case 'b': return ("B", false); case 'c': return ("C", false); case 'd': return ("D", false); case 'e': return ("E", false); case 'f': return ("F", false); case 'g': return ("G", false); case 'h': return ("H", false); case 'i': return ("I", false); case 'j': return ("J", false); case 'k': return ("K", false); case 'l': return ("L", false); case 'm': return ("M", false); case 'n': return ("N", false); case 'o': return ("O", false); case 'p': return ("P", false); case 'q': return ("Q", false); case 'r': return ("R", false); case 's': return ("S", false); case 't': return ("T", false); case 'u': return ("U", false); case 'v': return ("V", false); case 'w': return ("W", false); case 'x': return ("X", false); case 'y': return ("Y", false); case 'z': return ("Z", false); case ')': return ("0", true); case '0': return ("0", false); case '!': return ("1", true); case '1': return ("1", false); case '@': return ("2", true); case '2': return ("2", false); case '#': return ("3", true); case '3': return ("3", false); case '$': return ("4", true); case '4': return ("4", false); case '%': return ("5", true); case '5': return ("5", false); case '^': return ("6", true); case '6': return ("6", false); case '&': return ("7", true); case '7': return ("7", false); case '*': return ("8", true); case '8': return ("8", false); case '(': return ("9", true); case '9': return ("9", false); case ':': return (";", true); case ';': return (";", false); case '+': return ("=", true); case '=': return ("=", false); case '<': return (",", true); case ',': return (",", false); case '_': return ("-", true); case '-': return ("-", false); case '>': return (".", true); case '.': return (".", false); case '?': return ("/", true); case '/': return ("/", false); case '~': return ("`", true); case '`': return ("`", false); case '{': return ("[", true); case '[': return ("[", false); case '|': return ("\\", true); case '\\': return ("\\", false); case '}': return ("]", true); case ']': return ("]", false); case '"': return ("\'", true); case '\'': return ("\'", false); } return (c.ToString().ToUpper(), shifted); } } }
40.317757
81
0.388271
[ "MIT" ]
xamarin/WebSharp
electron-dotnet/src/websharpjs/WebSharp.js/dotnet/WebSharpJs.Electron/KeyboardUtilities.cs
4,316
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Security; using System.Threading; namespace System.Runtime.Serialization { /// <summary>The structure for holding all of the data needed for object serialization and deserialization.</summary> public sealed class SerializationInfo { private const int DefaultSize = 4; // Even though we have a dictionary, we're still keeping all the arrays around for back-compat. // Otherwise we may run into potentially breaking behaviors like GetEnumerator() not returning entries in the same order they were added. private string[] _names; private object?[] _values; private Type[] _types; private int _count; private readonly Dictionary<string, int> _nameToIndex; private readonly IFormatterConverter _converter; private string _rootTypeName; private string _rootTypeAssemblyName; private Type _rootType; internal static AsyncLocal<bool> AsyncDeserializationInProgress { get; } = new AsyncLocal<bool>(); #if !CORECLR // On AoT, assume private members are reflection blocked, so there's no further protection required // for the thread's DeserializationTracker [ThreadStatic] private static DeserializationTracker? t_deserializationTracker; private static DeserializationTracker GetThreadDeserializationTracker() => t_deserializationTracker ??= new DeserializationTracker(); #endif // !CORECLR // Returns true if deserialization is currently in progress public static bool DeserializationInProgress { #if CORECLR [DynamicSecurityMethod] // Methods containing StackCrawlMark local var must be marked DynamicSecurityMethod #endif get { if (AsyncDeserializationInProgress.Value) { return true; } #if CORECLR StackCrawlMark stackMark = StackCrawlMark.LookForMe; DeserializationTracker tracker = Thread.GetThreadDeserializationTracker(ref stackMark); #else DeserializationTracker tracker = GetThreadDeserializationTracker(); #endif bool result = tracker.DeserializationInProgress; return result; } } // Throws a SerializationException if dangerous deserialization is currently // in progress public static void ThrowIfDeserializationInProgress() { if (DeserializationInProgress) { throw new SerializationException(SR.Serialization_DangerousDeserialization); } } // Throws a DeserializationBlockedException if dangerous deserialization is currently // in progress and the AppContext switch Switch.System.Runtime.Serialization.SerializationGuard.{switchSuffix} // is not true. The value of the switch is cached in cachedValue to avoid repeated lookups: // 0: No value cached // 1: The switch is true // -1: The switch is false public static void ThrowIfDeserializationInProgress(string switchSuffix, ref int cachedValue) { const string SwitchPrefix = "Switch.System.Runtime.Serialization.SerializationGuard."; if (switchSuffix == null) { throw new ArgumentNullException(nameof(switchSuffix)); } if (string.IsNullOrWhiteSpace(switchSuffix)) { throw new ArgumentException(SR.Argument_EmptyName, nameof(switchSuffix)); } if (cachedValue == 0) { bool isEnabled = false; if (AppContext.TryGetSwitch(SwitchPrefix + switchSuffix, out isEnabled) && isEnabled) { cachedValue = 1; } else { cachedValue = -1; } } if (cachedValue == 1) { return; } else if (cachedValue == -1) { if (DeserializationInProgress) { throw new SerializationException(SR.Format(SR.Serialization_DangerousDeserialization_Switch, SwitchPrefix + switchSuffix)); } } else { throw new ArgumentOutOfRangeException(nameof(cachedValue)); } } // Declares that the current thread and async context have begun deserialization. // In this state, if the SerializationGuard or other related AppContext switches are set, // actions likely to be dangerous during deserialization, such as starting a process will be blocked. // Returns a DeserializationToken that must be disposed to remove the deserialization state. #if CORECLR [DynamicSecurityMethod] // Methods containing StackCrawlMark local var must be marked DynamicSecurityMethod #endif public static DeserializationToken StartDeserialization() { if (LocalAppContextSwitches.SerializationGuard) { #if CORECLR StackCrawlMark stackMark = StackCrawlMark.LookForMe; DeserializationTracker tracker = Thread.GetThreadDeserializationTracker(ref stackMark); #else DeserializationTracker tracker = GetThreadDeserializationTracker(); #endif if (!tracker.DeserializationInProgress) { lock (tracker) { if (!tracker.DeserializationInProgress) { AsyncDeserializationInProgress.Value = true; tracker.DeserializationInProgress = true; return new DeserializationToken(tracker); } } } } return new DeserializationToken(null); } [CLSCompliant(false)] public SerializationInfo(Type type, IFormatterConverter converter) { if ((object)type == null) { throw new ArgumentNullException(nameof(type)); } if (converter == null) { throw new ArgumentNullException(nameof(converter)); } _rootType = type; _rootTypeName = type.FullName!; _rootTypeAssemblyName = type.Module.Assembly.FullName!; _names = new string[DefaultSize]; _values = new object[DefaultSize]; _types = new Type[DefaultSize]; _nameToIndex = new Dictionary<string, int>(); _converter = converter; } [CLSCompliant(false)] public SerializationInfo(Type type, IFormatterConverter converter, bool requireSameTokenInPartialTrust) : this(type, converter) { // requireSameTokenInPartialTrust is a vacuous parameter in a platform that does not support partial trust. } public string FullTypeName { get => _rootTypeName; set { if (null == value) { throw new ArgumentNullException(nameof(value)); } _rootTypeName = value; IsFullTypeNameSetExplicit = true; } } public string AssemblyName { get => _rootTypeAssemblyName; set { if (null == value) { throw new ArgumentNullException(nameof(value)); } _rootTypeAssemblyName = value; IsAssemblyNameSetExplicit = true; } } public bool IsFullTypeNameSetExplicit { get; private set; } public bool IsAssemblyNameSetExplicit { get; private set; } public void SetType(Type type) { if ((object)type == null) { throw new ArgumentNullException(nameof(type)); } if (!ReferenceEquals(_rootType, type)) { _rootType = type; _rootTypeName = type.FullName!; _rootTypeAssemblyName = type.Module.Assembly.FullName!; IsFullTypeNameSetExplicit = false; IsAssemblyNameSetExplicit = false; } } public int MemberCount => _count; public Type ObjectType => _rootType; public SerializationInfoEnumerator GetEnumerator() => new SerializationInfoEnumerator(_names, _values, _types, _count); private void ExpandArrays() { int newSize; Debug.Assert(_names.Length == _count, "[SerializationInfo.ExpandArrays]_names.Length == _count"); newSize = (_count * 2); // In the pathological case, we may wrap if (newSize < _count) { if (int.MaxValue > _count) { newSize = int.MaxValue; } } // Allocate more space and copy the data string[] newMembers = new string[newSize]; object[] newData = new object[newSize]; Type[] newTypes = new Type[newSize]; Array.Copy(_names, 0, newMembers, 0, _count); Array.Copy(_values, 0, newData, 0, _count); Array.Copy(_types, 0, newTypes, 0, _count); // Assign the new arrays back to the member vars. _names = newMembers; _values = newData; _types = newTypes; } public void AddValue(string name, object? value, Type type) { if (null == name) { throw new ArgumentNullException(nameof(name)); } if ((object)type == null) { throw new ArgumentNullException(nameof(type)); } AddValueInternal(name, value, type); } public void AddValue(string name, object? value) { if (null == value) { AddValue(name, value, typeof(object)); } else { AddValue(name, value, value.GetType()); } } public void AddValue(string name, bool value) { AddValue(name, (object)value, typeof(bool)); } public void AddValue(string name, char value) { AddValue(name, (object)value, typeof(char)); } [CLSCompliant(false)] public void AddValue(string name, sbyte value) { AddValue(name, (object)value, typeof(sbyte)); } public void AddValue(string name, byte value) { AddValue(name, (object)value, typeof(byte)); } public void AddValue(string name, short value) { AddValue(name, (object)value, typeof(short)); } [CLSCompliant(false)] public void AddValue(string name, ushort value) { AddValue(name, (object)value, typeof(ushort)); } public void AddValue(string name, int value) { AddValue(name, (object)value, typeof(int)); } [CLSCompliant(false)] public void AddValue(string name, uint value) { AddValue(name, (object)value, typeof(uint)); } public void AddValue(string name, long value) { AddValue(name, (object)value, typeof(long)); } [CLSCompliant(false)] public void AddValue(string name, ulong value) { AddValue(name, (object)value, typeof(ulong)); } public void AddValue(string name, float value) { AddValue(name, (object)value, typeof(float)); } public void AddValue(string name, double value) { AddValue(name, (object)value, typeof(double)); } public void AddValue(string name, decimal value) { AddValue(name, (object)value, typeof(decimal)); } public void AddValue(string name, DateTime value) { AddValue(name, (object)value, typeof(DateTime)); } internal void AddValueInternal(string name, object? value, Type type) { if (_nameToIndex.ContainsKey(name)) { throw new SerializationException(SR.Serialization_SameNameTwice); } _nameToIndex.Add(name, _count); // If we need to expand the arrays, do so. if (_count >= _names.Length) { ExpandArrays(); } // Add the data and then advance the counter. _names[_count] = name; _values[_count] = value; _types[_count] = type; _count++; } /// <summary> /// Finds the value if it exists in the current data. If it does, we replace /// the values, if not, we append it to the end. This is useful to the /// ObjectManager when it's performing fixups. /// /// All error checking is done with asserts. Although public in coreclr, /// it's not exposed in a contract and is only meant to be used by corefx. /// /// This isn't a public API, but it gets invoked dynamically by /// BinaryFormatter /// /// This should not be used by clients: exposing out this functionality would allow children /// to overwrite their parent's values. It is public in order to give corefx access to it for /// its ObjectManager implementation, but it should not be exposed out of a contract. /// </summary> /// <param name="name"> The name of the data to be updated.</param> /// <param name="value"> The new value.</param> /// <param name="type"> The type of the data being added.</param> public void UpdateValue(string name, object value, Type type) { Debug.Assert(null != name, "[SerializationInfo.UpdateValue]name!=null"); Debug.Assert(null != value, "[SerializationInfo.UpdateValue]value!=null"); Debug.Assert(null != (object)type, "[SerializationInfo.UpdateValue]type!=null"); int index = FindElement(name); if (index < 0) { AddValueInternal(name, value, type); } else { _values[index] = value; _types[index] = type; } } private int FindElement(string name) { if (null == name) { throw new ArgumentNullException(nameof(name)); } int index; if (_nameToIndex.TryGetValue(name, out index)) { return index; } return -1; } /// <summary> /// Gets the location of a particular member and then returns /// the value of the element at that location. The type of the member is /// returned in the foundType field. /// </summary> /// <param name="name"> The name of the element to find.</param> /// <param name="foundType"> The type of the element associated with the given name.</param> /// <returns>The value of the element at the position associated with name.</returns> private object? GetElement(string name, out Type foundType) { int index = FindElement(name); if (index == -1) { throw new SerializationException(SR.Format(SR.Serialization_NotFound, name)); } Debug.Assert(index < _values.Length, "[SerializationInfo.GetElement]index<_values.Length"); Debug.Assert(index < _types.Length, "[SerializationInfo.GetElement]index<_types.Length"); foundType = _types[index]; Debug.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null"); return _values[index]; } private object? GetElementNoThrow(string name, out Type? foundType) { int index = FindElement(name); if (index == -1) { foundType = null; return null; } Debug.Assert(index < _values.Length, "[SerializationInfo.GetElement]index<_values.Length"); Debug.Assert(index < _types.Length, "[SerializationInfo.GetElement]index<_types.Length"); foundType = _types[index]; Debug.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null"); return _values[index]; } public object? GetValue(string name, Type type) { if ((object)type == null) { throw new ArgumentNullException(nameof(type)); } if (!type.IsRuntimeImplemented()) throw new ArgumentException(SR.Argument_MustBeRuntimeType); Type foundType; object? value = GetElement(name, out foundType); if (ReferenceEquals(foundType, type) || type.IsAssignableFrom(foundType) || value == null) { return value; } Debug.Assert(_converter != null, "[SerializationInfo.GetValue]_converter!=null"); return _converter.Convert(value, type); } internal object? GetValueNoThrow(string name, Type type) { Debug.Assert((object)type != null, "[SerializationInfo.GetValue]type ==null"); Debug.Assert(type.IsRuntimeImplemented(), "[SerializationInfo.GetValue]type is not a runtime type"); Type? foundType; object? value = GetElementNoThrow(name, out foundType); if (value == null) return null; if (ReferenceEquals(foundType, type) || type.IsAssignableFrom(foundType)) { return value; } Debug.Assert(_converter != null, "[SerializationInfo.GetValue]_converter!=null"); return _converter.Convert(value, type); } public bool GetBoolean(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(bool)) ? (bool)value! : _converter.ToBoolean(value!); // if value is null To* method will either deal with it or throw } public char GetChar(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(char)) ? (char)value! : _converter.ToChar(value!); } [CLSCompliant(false)] public sbyte GetSByte(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(sbyte)) ? (sbyte)value! : _converter.ToSByte(value!); } public byte GetByte(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(byte)) ? (byte)value! : _converter.ToByte(value!); } public short GetInt16(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(short)) ? (short)value! : _converter.ToInt16(value!); } [CLSCompliant(false)] public ushort GetUInt16(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(ushort)) ? (ushort)value! : _converter.ToUInt16(value!); } public int GetInt32(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(int)) ? (int)value! : _converter.ToInt32(value!); } [CLSCompliant(false)] public uint GetUInt32(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(uint)) ? (uint)value! : _converter.ToUInt32(value!); } public long GetInt64(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(long)) ? (long)value! : _converter.ToInt64(value!); } [CLSCompliant(false)] public ulong GetUInt64(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(ulong)) ? (ulong)value! : _converter.ToUInt64(value!); } public float GetSingle(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(float)) ? (float)value! : _converter.ToSingle(value!); } public double GetDouble(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(double)) ? (double)value! : _converter.ToDouble(value!); } public decimal GetDecimal(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(decimal)) ? (decimal)value! : _converter.ToDecimal(value!); } public DateTime GetDateTime(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(DateTime)) ? (DateTime)value! : _converter.ToDateTime(value!); } public string? GetString(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(string)) || value == null ? (string?)value : _converter.ToString(value); } } }
35.446345
171
0.568445
[ "MIT" ]
6opuc/coreclr
src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationInfo.cs
22,792
C#
using System; using System.Collections.Generic; using System.Text; namespace Spice.Exceptions { class ParseException : SpiceException { public ParseException(string message) : base(message) { } } }
16.857143
61
0.661017
[ "MIT" ]
Slord6/Spice
Spice/Spice/Exceptions/ParseException.cs
238
C#
namespace Cedar.CommandHandling.Http { using System; using System.IO; /// <summary> /// Represents an operation to custom deserialize a command. /// </summary> /// <param name="commandReader">The command reader.</param> /// <param name="commandType">Type of the command.</param> /// <returns></returns> public delegate object DeserializeCommand( TextReader commandReader, Type commandType); }
29.666667
64
0.658427
[ "MIT" ]
heynickc/Cedar.CommandHandling
src/Cedar.CommandHandling.Http/Http/DeserializeCommand.cs
445
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SimulareExamenProblema2 { public class Rectangle : Shape { public Rectangle(Point topLeft, int width, int height) { // make sure that topLeft is not null before // using it for calculations topLeft ??= new Point(0, 0); // create all the coordinates of the rectangle // based on topLeft and width and height // this way we can guarantee that it's indeed // a rectangle TopLeft = topLeft; // on computers coordinates origin is on the top-left // corner of the screen TopRight = new Point(topLeft.X + width, topLeft.Y); BottomRight = new Point(topLeft.X + width, topLeft.Y + height); BottomLeft = new Point(topLeft.X, topLeft.Y + height); // save also width and height for printing Width = width; Height = height; } public Point TopLeft { get; } public Point TopRight { get; } public Point BottomRight { get; } public Point BottomLeft { get; } public int Width { get; } public int Height { get; } public override void Translate(int dx, int dy) { // the translation of rectangle means // the translation of its points TopLeft.Translate(dx, dy); TopRight.Translate(dx, dy); BottomRight.Translate(dx, dy); BottomLeft.Translate(dx, dy); } public override void Print() { Console.WriteLine("I am a rectangle with the following coordinates:"); Console.WriteLine($" - TopLeft: (x = {TopLeft.X}, y={TopLeft.Y})"); Console.WriteLine($" - TopRight: (x = {TopRight.X}, y={TopRight.Y})"); Console.WriteLine($" - BottomRight: (x = {BottomRight.X}, y={BottomRight.Y})"); Console.WriteLine($" - BottomRight: (x = {BottomLeft.X}, y={BottomLeft.Y})"); Console.WriteLine($" - Width: {Width}"); Console.WriteLine($" - Height: {Height}"); } } }
33.220588
94
0.558212
[ "MIT" ]
UEO-BazeleInformaticii-2021/simulare-examen-pb2
SimulareExamenProblema2/SimulareExamenProblema2/Rectangle.cs
2,261
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace BioinformaticsSuite.Shell.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("BioinformaticsSuite.Shell.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
43.953125
191
0.616424
[ "MIT" ]
jemd321/Bioinformatics-Suite
BioinformaticsSuite.Shell/Properties/Resources.Designer.cs
2,815
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace genshin_sim { public enum ElementalReactions { None, VaporizePyro, VaporizeHydro, MeltPyro, MeltCryo, Superconduct, Swirl, Burning, ElectorCharged, Shattered, Overloaded, } public class Enemy { public string Name { get; private set; } public int Level { get; private set; } public double DEF { get; private set; } public double[] Resistances { get; private set; } public ElementalType Element { get; private set; } public string Description { get { return string.Format("防御: {0}\r\n物理: {1}\r\n火: {2}\r\n水: {3}\r\n冰: {4}\r\n草: {5}\r\n雷: {6}\r\n风: {7}\r\n岩: {8}", DEF, Resistances[0].ToString("0.0%"), Resistances[1].ToString("0.0%"), Resistances[2].ToString("0.0%"), Resistances[3].ToString("0.0%"), Resistances[4].ToString("0.0%"), Resistances[5].ToString("0.0%"), Resistances[6].ToString("0.0%"), Resistances[7].ToString("0.0%") ); } } public Enemy(string name, int lv, double def, double[] res) { this.Name = name; this.Level = lv; this.DEF = def; this.Resistances = res; this.Element = ElementalType.None; } public void SetLevel(int lv) { this.Level = lv < 1 ? 1 : (lv > 100 ? 100 : lv); } public void SetElement(ElementalType type) { this.Element = type; } } }
27.333333
128
0.4772
[ "MIT" ]
SoildFaker/genshin_sim
Enemy.cs
1,910
C#
using System.Windows.Forms; namespace PSY_questionary { partial class Form1 { /// <summary> /// 設計工具所需的變數。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清除任何使用中的資源。 /// </summary> /// <param name="disposing">如果應該處置受控資源則為 true,否則為 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form 設計工具產生的程式碼 /// <summary> /// 此為設計工具支援所需的方法 - 請勿使用程式碼編輯器修改 /// 這個方法的內容。 /// </summary> private void InitializeComponent() { this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.progress_word = new System.Windows.Forms.TextBox(); this.progressBar = new System.Windows.Forms.ProgressBar(); this.clear_show = new System.Windows.Forms.Button(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.showData_all = new System.Windows.Forms.Button(); this.outCSV_all = new System.Windows.Forms.Button(); this.show_whichForAll = new System.Windows.Forms.TextBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.show_qn_name = new System.Windows.Forms.Label(); this.showOnDatagrid = new System.Windows.Forms.Button(); this.show_which_qn = new System.Windows.Forms.TrackBar(); this.outCSV_one = new System.Windows.Forms.Button(); this.dataTransform = new System.Windows.Forms.Button(); this.backup = new System.Windows.Forms.Button(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.show = new System.Windows.Forms.TextBox(); this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog(); this.dataGridView = new System.Windows.Forms.DataGridView(); this.ListNumber = new System.Windows.Forms.ListBox(); this.delete = new System.Windows.Forms.Button(); this.reverse = new System.Windows.Forms.Button(); this.button1 = new System.Windows.Forms.Button(); this.path_to_server = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.delete_middle = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.tabControl1.SuspendLayout(); this.tabPage1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.groupBox1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.show_which_qn)).BeginInit(); this.tabPage2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); this.SuspendLayout(); // // tabControl1 // this.tabControl1.Controls.Add(this.tabPage1); this.tabControl1.Controls.Add(this.tabPage2); this.tabControl1.Location = new System.Drawing.Point(12, 12); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(776, 426); this.tabControl1.TabIndex = 0; // // tabPage1 // this.tabPage1.Controls.Add(this.ListNumber); this.tabPage1.Controls.Add(this.progress_word); this.tabPage1.Controls.Add(this.progressBar); this.tabPage1.Controls.Add(this.clear_show); this.tabPage1.Controls.Add(this.groupBox2); this.tabPage1.Controls.Add(this.groupBox1); this.tabPage1.Controls.Add(this.dataTransform); this.tabPage1.Controls.Add(this.backup); this.tabPage1.Location = new System.Drawing.Point(4, 28); this.tabPage1.Name = "tabPage1"; this.tabPage1.Padding = new System.Windows.Forms.Padding(3); this.tabPage1.Size = new System.Drawing.Size(768, 394); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "常用"; this.tabPage1.UseVisualStyleBackColor = true; // // progress_word // this.progress_word.Font = new System.Drawing.Font("新細明體", 12F); this.progress_word.Location = new System.Drawing.Point(15, 127); this.progress_word.Name = "progress_word"; this.progress_word.ReadOnly = true; this.progress_word.Size = new System.Drawing.Size(360, 36); this.progress_word.TabIndex = 15; this.progress_word.Text = "程式初始化:"; // // progressBar // this.progressBar.Location = new System.Drawing.Point(15, 169); this.progressBar.Name = "progressBar"; this.progressBar.Size = new System.Drawing.Size(363, 34); this.progressBar.Step = 1; this.progressBar.TabIndex = 13; this.progressBar.Value = 100; // // clear_show // this.clear_show.Location = new System.Drawing.Point(387, 317); this.clear_show.Name = "clear_show"; this.clear_show.Size = new System.Drawing.Size(372, 63); this.clear_show.TabIndex = 12; this.clear_show.Text = "清除右方文字框"; this.clear_show.UseVisualStyleBackColor = true; this.clear_show.Click += new System.EventHandler(this.Button1_Click); // // groupBox2 // this.groupBox2.Controls.Add(this.showData_all); this.groupBox2.Controls.Add(this.outCSV_all); this.groupBox2.Controls.Add(this.show_whichForAll); this.groupBox2.Location = new System.Drawing.Point(384, 185); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(381, 126); this.groupBox2.TabIndex = 11; this.groupBox2.TabStop = false; this.groupBox2.Text = "輸出單一表格合併資料"; // // showData_all // this.showData_all.Location = new System.Drawing.Point(6, 24); this.showData_all.Name = "showData_all"; this.showData_all.Size = new System.Drawing.Size(108, 96); this.showData_all.TabIndex = 7; this.showData_all.Text = "關係連結圖"; this.showData_all.UseVisualStyleBackColor = true; this.showData_all.Click += new System.EventHandler(this.showData_all_Click); // // outCSV_all // this.outCSV_all.Enabled = false; this.outCSV_all.Location = new System.Drawing.Point(120, 63); this.outCSV_all.Name = "outCSV_all"; this.outCSV_all.Size = new System.Drawing.Size(255, 57); this.outCSV_all.TabIndex = 8; this.outCSV_all.Text = "(多)輸出下方表格"; this.outCSV_all.UseVisualStyleBackColor = true; this.outCSV_all.Click += new System.EventHandler(this.outCSV_all_Click); // // show_whichForAll // this.show_whichForAll.ForeColor = System.Drawing.SystemColors.WindowFrame; this.show_whichForAll.Location = new System.Drawing.Point(120, 28); this.show_whichForAll.Name = "show_whichForAll"; this.show_whichForAll.Size = new System.Drawing.Size(255, 29); this.show_whichForAll.TabIndex = 9; this.show_whichForAll.Text = "請填寫0~8任意個數字 ex:0123"; this.show_whichForAll.Enter += new System.EventHandler(this.Show_whichForAll_Enter); // // groupBox1 // this.groupBox1.Controls.Add(this.show_qn_name); this.groupBox1.Controls.Add(this.showOnDatagrid); this.groupBox1.Controls.Add(this.show_which_qn); this.groupBox1.Controls.Add(this.outCSV_one); this.groupBox1.Location = new System.Drawing.Point(381, 14); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(381, 165); this.groupBox1.TabIndex = 10; this.groupBox1.TabStop = false; this.groupBox1.Text = "輸出單一表格所有填答"; // // show_qn_name // this.show_qn_name.AutoSize = true; this.show_qn_name.Font = new System.Drawing.Font("新細明體", 12F); this.show_qn_name.Location = new System.Drawing.Point(164, 118); this.show_qn_name.Name = "show_qn_name"; this.show_qn_name.Size = new System.Drawing.Size(165, 24); this.show_qn_name.TabIndex = 7; this.show_qn_name.Text = "顯示第0份問卷"; // // showOnDatagrid // this.showOnDatagrid.Location = new System.Drawing.Point(6, 24); this.showOnDatagrid.Name = "showOnDatagrid"; this.showOnDatagrid.Size = new System.Drawing.Size(156, 60); this.showOnDatagrid.TabIndex = 3; this.showOnDatagrid.Text = "表格show"; this.showOnDatagrid.UseVisualStyleBackColor = true; this.showOnDatagrid.Click += new System.EventHandler(this.showOnDatagrid_Click); // // show_which_qn // this.show_which_qn.Location = new System.Drawing.Point(9, 90); this.show_which_qn.Maximum = 8; this.show_which_qn.Name = "show_which_qn"; this.show_which_qn.Size = new System.Drawing.Size(142, 69); this.show_which_qn.TabIndex = 6; this.show_which_qn.Scroll += new System.EventHandler(this.Show_which_qn_Scroll); this.show_which_qn.ValueChanged += new System.EventHandler(this.Show_which_qn_ValueChanged); // // outCSV_one // this.outCSV_one.Enabled = false; this.outCSV_one.Location = new System.Drawing.Point(168, 24); this.outCSV_one.Name = "outCSV_one"; this.outCSV_one.Size = new System.Drawing.Size(187, 60); this.outCSV_one.TabIndex = 1; this.outCSV_one.Text = "(單一)輸出下方表格"; this.outCSV_one.UseVisualStyleBackColor = true; this.outCSV_one.Click += new System.EventHandler(this.outCSV_one_Click); // // dataTransform // this.dataTransform.Enabled = false; this.dataTransform.Location = new System.Drawing.Point(198, 6); this.dataTransform.Name = "dataTransform"; this.dataTransform.Size = new System.Drawing.Size(177, 120); this.dataTransform.TabIndex = 2; this.dataTransform.Text = "插入表格到SQL"; this.dataTransform.UseVisualStyleBackColor = true; this.dataTransform.Click += new System.EventHandler(this.dataTransform_Click); // // backup // this.backup.Location = new System.Drawing.Point(12, 6); this.backup.Name = "backup"; this.backup.Size = new System.Drawing.Size(180, 120); this.backup.TabIndex = 0; this.backup.Text = "備分"; this.backup.UseVisualStyleBackColor = true; this.backup.Click += new System.EventHandler(this.backup_Click); // // tabPage2 // this.tabPage2.Controls.Add(this.label2); this.tabPage2.Controls.Add(this.delete_middle); this.tabPage2.Controls.Add(this.label1); this.tabPage2.Controls.Add(this.path_to_server); this.tabPage2.Controls.Add(this.reverse); this.tabPage2.Controls.Add(this.button1); this.tabPage2.Controls.Add(this.delete); this.tabPage2.Location = new System.Drawing.Point(4, 28); this.tabPage2.Name = "tabPage2"; this.tabPage2.Padding = new System.Windows.Forms.Padding(3); this.tabPage2.Size = new System.Drawing.Size(768, 394); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "謹慎使用"; this.tabPage2.UseVisualStyleBackColor = true; // // show // this.show.Font = new System.Drawing.Font("新細明體", 14F); this.show.Location = new System.Drawing.Point(790, 40); this.show.Multiline = true; this.show.Name = "show"; this.show.ReadOnly = true; this.show.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.show.Size = new System.Drawing.Size(454, 394); this.show.TabIndex = 1; // // dataGridView // this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView.Location = new System.Drawing.Point(12, 444); this.dataGridView.Name = "dataGridView"; this.dataGridView.RowHeadersWidth = 62; this.dataGridView.RowTemplate.Height = 31; this.dataGridView.Size = new System.Drawing.Size(1232, 517); this.dataGridView.TabIndex = 2; // // ListNumber // this.ListNumber.Font = new System.Drawing.Font("新細明體", 13F); this.ListNumber.FormattingEnabled = true; this.ListNumber.ItemHeight = 26; this.ListNumber.Location = new System.Drawing.Point(15, 213); this.ListNumber.Name = "ListNumber"; this.ListNumber.Size = new System.Drawing.Size(360, 160); this.ListNumber.TabIndex = 16; // // delete // this.delete.Location = new System.Drawing.Point(7, 26); this.delete.Name = "delete"; this.delete.Size = new System.Drawing.Size(205, 44); this.delete.TabIndex = 0; this.delete.Text = "清空使用中資料庫"; this.delete.UseVisualStyleBackColor = true; this.delete.Click += new System.EventHandler(this.Delete_Click); // // reverse // this.reverse.Location = new System.Drawing.Point(429, 26); this.reverse.Name = "reverse"; this.reverse.Size = new System.Drawing.Size(205, 44); this.reverse.TabIndex = 1; this.reverse.Text = "抓取備分資料庫"; this.reverse.UseVisualStyleBackColor = true; this.reverse.Click += new System.EventHandler(this.Reverse_Click); // // button1 // this.button1.Location = new System.Drawing.Point(7, 92); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(205, 48); this.button1.TabIndex = 2; this.button1.Text = "抓取非本地全數資料"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.Button1_Click_1); // // path_to_server // this.path_to_server.Location = new System.Drawing.Point(473, 102); this.path_to_server.Name = "path_to_server"; this.path_to_server.Size = new System.Drawing.Size(289, 29); this.path_to_server.TabIndex = 3; // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("新細明體", 12F); this.label1.Location = new System.Drawing.Point(219, 104); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(234, 24); this.label1.TabIndex = 4; this.label1.Text = "server備分資料庫地址"; // // delete_middle // this.delete_middle.Location = new System.Drawing.Point(218, 26); this.delete_middle.Name = "delete_middle"; this.delete_middle.Size = new System.Drawing.Size(205, 42); this.delete_middle.TabIndex = 5; this.delete_middle.Text = "清空中繼資料庫"; this.delete_middle.UseVisualStyleBackColor = true; this.delete_middle.Click += new System.EventHandler(this.Delete_middle_Click); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(220, 138); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(243, 18); this.label2.TabIndex = 6; this.label2.Text = "(非server無法使用關係連結圖)"; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 18F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1256, 1050); this.Controls.Add(this.dataGridView); this.Controls.Add(this.show); this.Controls.Add(this.tabControl1); this.Name = "Form1"; this.Text = "Form1"; this.tabControl1.ResumeLayout(false); this.tabPage1.ResumeLayout(false); this.tabPage1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.show_which_qn)).EndInit(); this.tabPage2.ResumeLayout(false); this.tabPage2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabPage1; private System.Windows.Forms.TabPage tabPage2; private System.Windows.Forms.TextBox show; private System.Windows.Forms.Button backup; private System.Windows.Forms.Button outCSV_one; private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1; private System.Windows.Forms.Button dataTransform; private System.Windows.Forms.DataGridView dataGridView; private System.Windows.Forms.Button showOnDatagrid; private System.Windows.Forms.TrackBar show_which_qn; private System.Windows.Forms.Button showData_all; private Button outCSV_all; private TextBox show_whichForAll; private GroupBox groupBox2; private GroupBox groupBox1; private Label show_qn_name; private Button clear_show; private ProgressBar progressBar; private TextBox progress_word; private ListBox ListNumber; private Button reverse; private Button delete; private Label label1; private TextBox path_to_server; private Button button1; private Button delete_middle; private Label label2; } }
46.480861
130
0.588708
[ "MIT" ]
leon123858/questionareSystem
ACS/PSY_questionary/PSY_questionary/Form1.Designer.cs
19,891
C#
using System; using System.Collections.Generic; using System.Linq; using SharpFightingEngine.Engines; using SharpFightingEngine.Engines.Ticks; using SharpFightingEngine.Fighters; using SharpFightingEngine.Skills.Conditions; using SharpFightingEngine.Skills.General; using SharpFightingEngine.Utilities; namespace SharpFightingEngine.Skills.Melee { public class CripplingSmash : DamageSkillBase { public override Guid Id => new Guid("41E9B654-BCB2-454C-A8FA-E68C7B21C46A"); public override string Name => "Crippling Smash"; public override int DamageLow => 5; public override int DamageHigh => 8; public override float Range => 1; public override int Cooldown => 1; public override bool CanBeReflected => false; public override IEnumerable<EngineTick> Perform(IFighterStats actor, IFighterStats target, EngineCalculationValues calculationValues) { if (25F.Chance()) { return Enumerable.Empty<EngineTick>(); } var condition = new CrippleSkillCondition(actor); target.States.Add(condition); return new FighterConditionAppliedTick() { Condition = condition, Fighter = actor.AsStruct(), Target = target.AsStruct(), }.Yield(); } } }
25.816327
137
0.717787
[ "Unlicense" ]
Alexxtheonly/SharpFightingEngine
SharpFightingEngine.Skills/Melee/CripplingSmash.cs
1,267
C#
using Common.Server.Interfaces; using SocksTunnel.Interfaces; using System; using System.Collections.Generic; using SharpSocksServer.Source.ImplantCommsHTTPServer.Interfaces; using SharpSocksServer.Source.Transport.SSL; using System.Security.Cryptography.X509Certificates; using System.Collections; using System.Resources; using System.Reflection; using System.Globalization; using System.Linq; using System.Linq.Expressions; namespace SocksTunnel.Classes { public class HttpAsyncListener : IServiceController { System.Net.HttpListener _listener = null; IProcessRequest _iprocessRequest; public ILogOutput ServerComms { get; set; } public HttpAsyncListener(IProcessRequest processRequest, ILogOutput logOutput) { _iprocessRequest = processRequest; ServerComms = logOutput; } public void Stop() { _listener.Close(); } public void CreateListener(Dictionary<String, X509Certificate2> prefixes) { var certProc = new CertificateProcessor(ServerComms); _listener = new System.Net.HttpListener(); foreach (string s in prefixes.Keys) { certProc.AddCertificateToHost(s, prefixes[s]); _listener.Prefixes.Add(s); } _listener.Start(); System.Threading.Tasks.Task.Factory.StartNew( () => { while (_listener.IsListening) { var result = _listener.BeginGetContext(new AsyncCallback(ListenerCallback), _listener); result.AsyncWaitHandle.WaitOne(); } }); } X509Certificate2 GetDefaultSelfSignedCertFromResource() { var currasm = Assembly.GetExecutingAssembly(); var pfxcmp = SharpSocksServer.SharpSocks.host2cert_pfx ; X509Certificate2 x5092 = null; using (var pfxcmpbts = new System.IO.MemoryStream(pfxcmp)) using (var decompressedCert = new System.IO.MemoryStream()) { using (var decompressionStream = new System.IO.Compression.DeflateStream(pfxcmpbts, System.IO.Compression.CompressionMode.Decompress)) { decompressionStream.CopyTo(decompressedCert); decompressionStream.Close(); var sc = new System.Security.SecureString(); "SharpSocksKey".ToCharArray().ToList().ForEach(x => { sc.AppendChar(x); }); x5092 = new X509Certificate2(decompressedCert.ToArray(), sc); } } return x5092; } public void ListenerCallback(IAsyncResult result) { try { System.Net.HttpListener listener = (System.Net.HttpListener)result.AsyncState; System.Net.HttpListenerContext context = listener.EndGetContext(result); System.Net.HttpListenerRequest request = context.Request; System.Net.HttpListenerResponse response = context.Response; _iprocessRequest.ProcessRequest(context); } catch (Exception ex) { ServerComms.LogError($"Http Listener falled {ex.Message}"); _listener.BeginGetContext(new AsyncCallback(ListenerCallback), _listener); } } } }
34.867347
150
0.619257
[ "BSD-3-Clause" ]
FDlucifer/SharpSocks
SharpSocksServer/SharpSocksServerCore/ImplantCommsHTTPServer/Classes/HTTPAsyncListener.cs
3,419
C#
using FluentValidation; namespace Application.Features.PedidosDet.Commands.EliminarPedidosCommand { public class EliminarPedidoDetValidation : AbstractValidator<EliminarPedidoDetCommand> { public EliminarPedidoDetValidation() { RuleFor(p => p.Id) .NotNull().WithMessage("'{PropetyName}' : No debe ser nulo") .GreaterThan(0).WithMessage("'{PropertyName}' : Debe ser mayor a 0"); } } }
31.2
90
0.647436
[ "MIT" ]
NSysX/NSysC
NSysApiPedidos/src/Core/Application/Features/PedidosDet/Commands/EliminarPedidosCommand/EliminarPedidoDetValidation.cs
470
C#