content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System.Runtime.CompilerServices; using UnityEngine; namespace Realmar.DataBindings.Examples.NonVirtual { public class Model { private string _surname; private string _lastname; private int _age; public string Surname { get => _surname; set { _surname = value; Print(); } } public string Lastname { get => _lastname; set { _lastname = value; Print(); } } public int Age { get => _age; set { _age = value; Print(); } } private void Print([CallerMemberName] string name = null) { Debug.Log($"{nameof(Model)}::{name} = {GetType().GetProperty(name).GetValue(this)}"); } } }
14.083333
88
0.610947
[ "MIT" ]
laicasaane/unity-data-binding
Assets/DataBindings/Examples/NonVirtual/Model.cs
676
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Azure.ServiceBus { /// <summary> /// Manages a ServiceBus Subscription. /// /// ## Example Usage /// /// ```csharp /// using Pulumi; /// using Azure = Pulumi.Azure; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var exampleResourceGroup = new Azure.Core.ResourceGroup("exampleResourceGroup", new Azure.Core.ResourceGroupArgs /// { /// Location = "West Europe", /// }); /// var exampleNamespace = new Azure.ServiceBus.Namespace("exampleNamespace", new Azure.ServiceBus.NamespaceArgs /// { /// Location = exampleResourceGroup.Location, /// ResourceGroupName = exampleResourceGroup.Name, /// Sku = "Standard", /// Tags = /// { /// { "source", "example" }, /// }, /// }); /// var exampleTopic = new Azure.ServiceBus.Topic("exampleTopic", new Azure.ServiceBus.TopicArgs /// { /// ResourceGroupName = exampleResourceGroup.Name, /// NamespaceName = exampleNamespace.Name, /// EnablePartitioning = true, /// }); /// var exampleSubscription = new Azure.ServiceBus.Subscription("exampleSubscription", new Azure.ServiceBus.SubscriptionArgs /// { /// ResourceGroupName = exampleResourceGroup.Name, /// NamespaceName = exampleNamespace.Name, /// TopicName = exampleTopic.Name, /// MaxDeliveryCount = 1, /// }); /// } /// /// } /// ``` /// /// ## Import /// /// Service Bus Subscriptions can be imported using the `resource id`, e.g. /// /// ```sh /// $ pulumi import azure:servicebus/subscription:Subscription example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mygroup1/providers/microsoft.servicebus/namespaces/sbns1/topics/sntopic1/subscriptions/sbsub1 /// ``` /// </summary> [AzureResourceType("azure:servicebus/subscription:Subscription")] public partial class Subscription : Pulumi.CustomResource { /// <summary> /// The idle interval after which the topic is automatically deleted as an [ISO 8601 duration](https://en.wikipedia.org/wiki/ISO_8601#Durations). The minimum duration is `5` minutes or `P5M`. /// </summary> [Output("autoDeleteOnIdle")] public Output<string> AutoDeleteOnIdle { get; private set; } = null!; /// <summary> /// Boolean flag which controls whether the Subscription has dead letter support on filter evaluation exceptions. Defaults to `true`. /// </summary> [Output("deadLetteringOnFilterEvaluationError")] public Output<bool?> DeadLetteringOnFilterEvaluationError { get; private set; } = null!; /// <summary> /// Boolean flag which controls whether the Subscription has dead letter support when a message expires. Defaults to `false`. /// </summary> [Output("deadLetteringOnMessageExpiration")] public Output<bool?> DeadLetteringOnMessageExpiration { get; private set; } = null!; /// <summary> /// The Default message timespan to live as an [ISO 8601 duration](https://en.wikipedia.org/wiki/ISO_8601#Durations). This is the duration after which the message expires, starting from when the message is sent to Service Bus. This is the default value used when TimeToLive is not set on a message itself. /// </summary> [Output("defaultMessageTtl")] public Output<string> DefaultMessageTtl { get; private set; } = null!; /// <summary> /// Boolean flag which controls whether the Subscription supports batched operations. Defaults to `false`. /// </summary> [Output("enableBatchedOperations")] public Output<bool?> EnableBatchedOperations { get; private set; } = null!; /// <summary> /// The name of a Queue or Topic to automatically forward Dead Letter messages to. /// </summary> [Output("forwardDeadLetteredMessagesTo")] public Output<string?> ForwardDeadLetteredMessagesTo { get; private set; } = null!; /// <summary> /// The name of a Queue or Topic to automatically forward messages to. /// </summary> [Output("forwardTo")] public Output<string?> ForwardTo { get; private set; } = null!; /// <summary> /// The lock duration for the subscription as an [ISO 8601 duration](https://en.wikipedia.org/wiki/ISO_8601#Durations). The default value is `1` minute or `P1M`. /// </summary> [Output("lockDuration")] public Output<string> LockDuration { get; private set; } = null!; /// <summary> /// The maximum number of deliveries. /// </summary> [Output("maxDeliveryCount")] public Output<int> MaxDeliveryCount { get; private set; } = null!; /// <summary> /// Specifies the name of the ServiceBus Subscription resource. Changing this forces a new resource to be created. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The name of the ServiceBus Namespace to create this Subscription in. Changing this forces a new resource to be created. /// </summary> [Output("namespaceName")] public Output<string> NamespaceName { get; private set; } = null!; /// <summary> /// Boolean flag which controls whether this Subscription supports the concept of a session. Defaults to `false`. Changing this forces a new resource to be created. /// </summary> [Output("requiresSession")] public Output<bool?> RequiresSession { get; private set; } = null!; /// <summary> /// The name of the resource group in which to create the namespace. Changing this forces a new resource to be created. /// </summary> [Output("resourceGroupName")] public Output<string> ResourceGroupName { get; private set; } = null!; /// <summary> /// The status of the Subscription. Possible values are `Active`,`ReceiveDisabled`, or `Disabled`. Defaults to `Active`. /// </summary> [Output("status")] public Output<string?> Status { get; private set; } = null!; /// <summary> /// The name of the ServiceBus Topic to create this Subscription in. Changing this forces a new resource to be created. /// </summary> [Output("topicName")] public Output<string> TopicName { get; private set; } = null!; /// <summary> /// Create a Subscription resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public Subscription(string name, SubscriptionArgs args, CustomResourceOptions? options = null) : base("azure:servicebus/subscription:Subscription", name, args ?? new SubscriptionArgs(), MakeResourceOptions(options, "")) { } private Subscription(string name, Input<string> id, SubscriptionState? state = null, CustomResourceOptions? options = null) : base("azure:servicebus/subscription:Subscription", name, state, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure:eventhub/subscription:Subscription"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing Subscription resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="state">Any extra arguments used during the lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static Subscription Get(string name, Input<string> id, SubscriptionState? state = null, CustomResourceOptions? options = null) { return new Subscription(name, id, state, options); } } public sealed class SubscriptionArgs : Pulumi.ResourceArgs { /// <summary> /// The idle interval after which the topic is automatically deleted as an [ISO 8601 duration](https://en.wikipedia.org/wiki/ISO_8601#Durations). The minimum duration is `5` minutes or `P5M`. /// </summary> [Input("autoDeleteOnIdle")] public Input<string>? AutoDeleteOnIdle { get; set; } /// <summary> /// Boolean flag which controls whether the Subscription has dead letter support on filter evaluation exceptions. Defaults to `true`. /// </summary> [Input("deadLetteringOnFilterEvaluationError")] public Input<bool>? DeadLetteringOnFilterEvaluationError { get; set; } /// <summary> /// Boolean flag which controls whether the Subscription has dead letter support when a message expires. Defaults to `false`. /// </summary> [Input("deadLetteringOnMessageExpiration")] public Input<bool>? DeadLetteringOnMessageExpiration { get; set; } /// <summary> /// The Default message timespan to live as an [ISO 8601 duration](https://en.wikipedia.org/wiki/ISO_8601#Durations). This is the duration after which the message expires, starting from when the message is sent to Service Bus. This is the default value used when TimeToLive is not set on a message itself. /// </summary> [Input("defaultMessageTtl")] public Input<string>? DefaultMessageTtl { get; set; } /// <summary> /// Boolean flag which controls whether the Subscription supports batched operations. Defaults to `false`. /// </summary> [Input("enableBatchedOperations")] public Input<bool>? EnableBatchedOperations { get; set; } /// <summary> /// The name of a Queue or Topic to automatically forward Dead Letter messages to. /// </summary> [Input("forwardDeadLetteredMessagesTo")] public Input<string>? ForwardDeadLetteredMessagesTo { get; set; } /// <summary> /// The name of a Queue or Topic to automatically forward messages to. /// </summary> [Input("forwardTo")] public Input<string>? ForwardTo { get; set; } /// <summary> /// The lock duration for the subscription as an [ISO 8601 duration](https://en.wikipedia.org/wiki/ISO_8601#Durations). The default value is `1` minute or `P1M`. /// </summary> [Input("lockDuration")] public Input<string>? LockDuration { get; set; } /// <summary> /// The maximum number of deliveries. /// </summary> [Input("maxDeliveryCount", required: true)] public Input<int> MaxDeliveryCount { get; set; } = null!; /// <summary> /// Specifies the name of the ServiceBus Subscription resource. Changing this forces a new resource to be created. /// </summary> [Input("name")] public Input<string>? Name { get; set; } /// <summary> /// The name of the ServiceBus Namespace to create this Subscription in. Changing this forces a new resource to be created. /// </summary> [Input("namespaceName", required: true)] public Input<string> NamespaceName { get; set; } = null!; /// <summary> /// Boolean flag which controls whether this Subscription supports the concept of a session. Defaults to `false`. Changing this forces a new resource to be created. /// </summary> [Input("requiresSession")] public Input<bool>? RequiresSession { get; set; } /// <summary> /// The name of the resource group in which to create the namespace. Changing this forces a new resource to be created. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// The status of the Subscription. Possible values are `Active`,`ReceiveDisabled`, or `Disabled`. Defaults to `Active`. /// </summary> [Input("status")] public Input<string>? Status { get; set; } /// <summary> /// The name of the ServiceBus Topic to create this Subscription in. Changing this forces a new resource to be created. /// </summary> [Input("topicName", required: true)] public Input<string> TopicName { get; set; } = null!; public SubscriptionArgs() { } } public sealed class SubscriptionState : Pulumi.ResourceArgs { /// <summary> /// The idle interval after which the topic is automatically deleted as an [ISO 8601 duration](https://en.wikipedia.org/wiki/ISO_8601#Durations). The minimum duration is `5` minutes or `P5M`. /// </summary> [Input("autoDeleteOnIdle")] public Input<string>? AutoDeleteOnIdle { get; set; } /// <summary> /// Boolean flag which controls whether the Subscription has dead letter support on filter evaluation exceptions. Defaults to `true`. /// </summary> [Input("deadLetteringOnFilterEvaluationError")] public Input<bool>? DeadLetteringOnFilterEvaluationError { get; set; } /// <summary> /// Boolean flag which controls whether the Subscription has dead letter support when a message expires. Defaults to `false`. /// </summary> [Input("deadLetteringOnMessageExpiration")] public Input<bool>? DeadLetteringOnMessageExpiration { get; set; } /// <summary> /// The Default message timespan to live as an [ISO 8601 duration](https://en.wikipedia.org/wiki/ISO_8601#Durations). This is the duration after which the message expires, starting from when the message is sent to Service Bus. This is the default value used when TimeToLive is not set on a message itself. /// </summary> [Input("defaultMessageTtl")] public Input<string>? DefaultMessageTtl { get; set; } /// <summary> /// Boolean flag which controls whether the Subscription supports batched operations. Defaults to `false`. /// </summary> [Input("enableBatchedOperations")] public Input<bool>? EnableBatchedOperations { get; set; } /// <summary> /// The name of a Queue or Topic to automatically forward Dead Letter messages to. /// </summary> [Input("forwardDeadLetteredMessagesTo")] public Input<string>? ForwardDeadLetteredMessagesTo { get; set; } /// <summary> /// The name of a Queue or Topic to automatically forward messages to. /// </summary> [Input("forwardTo")] public Input<string>? ForwardTo { get; set; } /// <summary> /// The lock duration for the subscription as an [ISO 8601 duration](https://en.wikipedia.org/wiki/ISO_8601#Durations). The default value is `1` minute or `P1M`. /// </summary> [Input("lockDuration")] public Input<string>? LockDuration { get; set; } /// <summary> /// The maximum number of deliveries. /// </summary> [Input("maxDeliveryCount")] public Input<int>? MaxDeliveryCount { get; set; } /// <summary> /// Specifies the name of the ServiceBus Subscription resource. Changing this forces a new resource to be created. /// </summary> [Input("name")] public Input<string>? Name { get; set; } /// <summary> /// The name of the ServiceBus Namespace to create this Subscription in. Changing this forces a new resource to be created. /// </summary> [Input("namespaceName")] public Input<string>? NamespaceName { get; set; } /// <summary> /// Boolean flag which controls whether this Subscription supports the concept of a session. Defaults to `false`. Changing this forces a new resource to be created. /// </summary> [Input("requiresSession")] public Input<bool>? RequiresSession { get; set; } /// <summary> /// The name of the resource group in which to create the namespace. Changing this forces a new resource to be created. /// </summary> [Input("resourceGroupName")] public Input<string>? ResourceGroupName { get; set; } /// <summary> /// The status of the Subscription. Possible values are `Active`,`ReceiveDisabled`, or `Disabled`. Defaults to `Active`. /// </summary> [Input("status")] public Input<string>? Status { get; set; } /// <summary> /// The name of the ServiceBus Topic to create this Subscription in. Changing this forces a new resource to be created. /// </summary> [Input("topicName")] public Input<string>? TopicName { get; set; } public SubscriptionState() { } } }
46.065
313
0.617606
[ "ECL-2.0", "Apache-2.0" ]
aangelisc/pulumi-azure
sdk/dotnet/ServiceBus/Subscription.cs
18,426
C#
๏ปฟusing System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Cobweb Testing Extensions for MVC5.1, Unit Tests")] [assembly: AssemblyDescription("Unit tests for Cobweb's MVC5.1 testing utilities and classes. Cobweb is a base-class utility library for .NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Arana Software")] [assembly: AssemblyProduct("Aranasoft's Cobweb")] [assembly: AssemblyCopyright("Copyright ยฉ 2013-2018")] [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("2a3afd6f-105f-4de4-afbc-00f96bee08fa")] // 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.51.0.0")] [assembly: AssemblyFileVersion("1.51.0.0")]
42.472222
144
0.749509
[ "BSD-3-Clause" ]
aranasoft/cobweb-testing-mvc
test/Testing.Mvc5-1.Tests/Properties/AssemblyInfo.cs
1,532
C#
using System; using System.Collections.Generic; namespace json2record.tests.sample2.DTOs { public record PrepaymentSubaccount { public string subaccountNumber { get; init; } public int subaccountId { get; init; } public string description { get; init; } public DateTime lastModifiedDateTime { get; init; } public bool active { get; init; } public List<Segments> segments { get; init; } } }
35.153846
60
0.652079
[ "MIT" ]
mikalst/dtolab
json2record.tests/DTOs/sample2/PrepaymentSubaccount.cs
457
C#
๏ปฟusing System.Collections.Generic; using Plugin.Models.Cards; using Plugin.Models.Charts; using Plugin.Models.Stat; namespace Plugin.Models.Movie { public class MovieStatistics { public List<Card<string>> Cards { get; set; } public List<TopCard> TopCards { get; set; } public List<Chart> Charts { get; set; } public PersonStats People { get; set; } public IEnumerable<ShortMovie> Shorts { get; set; } public IEnumerable<SuspiciousMovie> NoImdb { get; set; } public IEnumerable<SuspiciousMovie> NoPrimary { get; set; } } }
31.105263
67
0.668359
[ "MIT" ]
mregni/EmbyStat-Plugin
Plugin/Models/Movie/MovieStatistics.cs
593
C#
๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Security.Policy; using System.Text; using System.Threading.Tasks; namespace Services.Contracts.Binding { [AttributeUsage(AttributeTargets.Class)] public class BindingSource : Attribute { public BindingSource() { } public string Url { get; set; } } }
19.05
44
0.685039
[ "Apache-2.0" ]
CodeFiction/CodeEksi
Core/Services.Contracts/Binding/BindingSource.cs
383
C#
using System; using System.Collections.Generic; using NHapi.Base.Log; using NHapi.Model.V23.Group; using NHapi.Model.V23.Segment; using NHapi.Model.V23.Datatype; using NHapi.Base; using NHapi.Base.Parser; using NHapi.Base.Model; namespace NHapi.Model.V23.Message { ///<summary> /// Represents a RRD_O02 message structure (see chapter [AAA]). This structure contains the /// following elements: ///<ol> ///<li>0: MSH (Message header segment) </li> ///<li>1: MSA (Message acknowledgement segment) </li> ///<li>2: ERR (Error segment) optional </li> ///<li>3: NTE (Notes and comments segment) optional repeating</li> ///<li>4: RRD_O02_PATIENT (a Group object) optional </li> ///</ol> ///</summary> [Serializable] public class RRD_O02 : AbstractMessage { ///<summary> /// Creates a new RRD_O02 Group with custom IModelClassFactory. ///</summary> public RRD_O02(IModelClassFactory factory) : base(factory){ init(factory); } ///<summary> /// Creates a new RRD_O02 Group with DefaultModelClassFactory. ///</summary> public RRD_O02() : base(new DefaultModelClassFactory()) { init(new DefaultModelClassFactory()); } ///<summary> /// initalize method for RRD_O02. This does the segment setup for the message. ///</summary> private void init(IModelClassFactory factory) { try { this.add(typeof(MSH), true, false); this.add(typeof(MSA), true, false); this.add(typeof(ERR), false, false); this.add(typeof(NTE), false, true); this.add(typeof(RRD_O02_PATIENT), false, false); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating RRD_O02 - this is probably a bug in the source code generator.", e); } } public override string Version { get{ return Constants.VERSION; } } ///<summary> /// Returns MSH (Message header segment) - creates it if necessary ///</summary> public MSH MSH { get{ MSH ret = null; try { ret = (MSH)this.GetStructure("MSH"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns MSA (Message acknowledgement segment) - creates it if necessary ///</summary> public MSA MSA { get{ MSA ret = null; try { ret = (MSA)this.GetStructure("MSA"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns ERR (Error segment) - creates it if necessary ///</summary> public ERR ERR { get{ ERR ret = null; try { ret = (ERR)this.GetStructure("ERR"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns first repetition of NTE (Notes and comments segment) - creates it if necessary ///</summary> public NTE GetNTE() { NTE ret = null; try { ret = (NTE)this.GetStructure("NTE"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of NTE /// * (Notes and comments segment) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public NTE GetNTE(int rep) { return (NTE)this.GetStructure("NTE", rep); } /** * Returns the number of existing repetitions of NTE */ public int NTERepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("NTE").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the NTE results */ public IEnumerable<NTE> NTEs { get { for (int rep = 0; rep < NTERepetitionsUsed; rep++) { yield return (NTE)this.GetStructure("NTE", rep); } } } ///<summary> ///Adds a new NTE ///</summary> public NTE AddNTE() { return this.AddStructure("NTE") as NTE; } ///<summary> ///Removes the given NTE ///</summary> public void RemoveNTE(NTE toRemove) { this.RemoveStructure("NTE", toRemove); } ///<summary> ///Removes the NTE at the given index ///</summary> public void RemoveNTEAt(int index) { this.RemoveRepetition("NTE", index); } ///<summary> /// Returns RRD_O02_PATIENT (a Group object) - creates it if necessary ///</summary> public RRD_O02_PATIENT PATIENT { get{ RRD_O02_PATIENT ret = null; try { ret = (RRD_O02_PATIENT)this.GetStructure("PATIENT"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } } }
28.057416
146
0.63455
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
afaonline/nHapi
src/NHapi.Model.V23/Message/RRD_O02.cs
5,864
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.VirtualMachineImages.V20200214.Outputs { [OutputType] public sealed class ImageTemplateIdentityResponse { /// <summary> /// The type of identity used for the image template. The type 'None' will remove any identities from the image template. /// </summary> public readonly string? Type; /// <summary> /// The list of user identities associated with the image template. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. /// </summary> public readonly ImmutableDictionary<string, Outputs.ImageTemplateIdentityResponseUserAssignedIdentities>? UserAssignedIdentities; [OutputConstructor] private ImageTemplateIdentityResponse( string? type, ImmutableDictionary<string, Outputs.ImageTemplateIdentityResponseUserAssignedIdentities>? userAssignedIdentities) { Type = type; UserAssignedIdentities = userAssignedIdentities; } } }
41.333333
301
0.721102
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/VirtualMachineImages/V20200214/Outputs/ImageTemplateIdentityResponse.cs
1,488
C#
๏ปฟnamespace MyTested.HttpServer.Tests.UtilitiesTests { using System; using Setups; using Utilities; using Xunit; public class VersionValidatorTests { [Fact] public void TryParseShouldReturnCorrectVersion() { var version = VersionValidator.TryParse("1.1", TestObjectFactory.GetFailingValidationAction()); Assert.Equal(1, version.Major); Assert.Equal(1, version.Minor); } [Fact] public void TryParseShouldInvokeFailedActionIfStringIsNotInCorrectFormat() { var exception = Assert.Throws<NullReferenceException>(() => { VersionValidator.TryParse("test", TestObjectFactory.GetFailingValidationAction()); }); Assert.Equal("version valid version string invalid one", exception.Message); } } }
28.419355
107
0.626561
[ "MIT" ]
Magicianred/MyTested.HttpServer
test/MyTested.HttpServer.Tests/UtilitiesTests/VersionValidatorTests.cs
883
C#
๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Unity { public class UnityObject { } } namespace Unity.Collections { public class UnityCollection { } } namespace UnityEngine { using Color32Proxy = System.Drawing.Color; using ColorProxy = System.Windows.Media.Color; using ColorsProxy = System.Windows.Media.Colors; using Vector3Proxy = System.Windows.Media.Media3D.Vector3D; using Point3DProxy = System.Windows.Media.Media3D.Point3D; using Vector4Proxy = System.Windows.Media.Media3D.Point4D; using Vector2Proxy = System.Windows.Vector; using Point2DProxy = System.Windows.Point; using QuaternionProxy = System.Windows.Media.Media3D.Quaternion; using Matrix4x4Proxy = System.Windows.Media.Media3D.Matrix3D; using System.Windows.Media; public struct Color32 { public byte a; public byte r; public byte g; public byte b; public Color32(byte r = 0, byte g = 0, byte b = 0, byte a = 255) { this.a = a; this.r = r; this.g = g; this.b = b; } public static implicit operator Color32(Color32Proxy c) => new Color32(c.R, c.G, c.B, c.A); public static implicit operator Color32(ColorProxy c) => new Color32(c.R, c.G, c.B, c.A); public static implicit operator Color32(Color c) => new Color32(c.proxy.R, c.proxy.G, c.proxy.B, c.proxy.A); public static implicit operator Color32Proxy(Color32 c) => Color32Proxy.FromArgb(c.a, c.r, c.g, c.b); public static implicit operator Color(Color32 c) => ColorProxy.FromArgb(c.a, c.r, c.g, c.b); public static Color32 Lerp(Color neutralColor, Color32 color32, float scale) { throw new NotImplementedException(); } } public struct Color { internal ColorProxy proxy; public float a { get => proxy.ScA; set => proxy.ScA = value; } public float r { get => proxy.ScR; set => proxy.ScR = value; } public float g { get => proxy.ScG; set => proxy.ScG = value; } public float b { get => proxy.ScB; set => proxy.ScB = value; } private Color(ColorProxy c) { proxy = c; } public Color(float r, float g, float b, float a = 1) { proxy = ColorProxy.FromScRgb(a, r, g, b); } public static implicit operator Color(ColorProxy c) => new Color(c); public static implicit operator ColorProxy(Color c) => c.proxy; public static Color operator *(Color c, float s) => new Color(c.proxy * s); public static readonly Color black = ColorsProxy.Black; public static readonly Color white = ColorsProxy.White; public static readonly Color red = ColorsProxy.Red; public static readonly Color green = ColorsProxy.Green; public static readonly Color blue = ColorsProxy.Blue; public static readonly Color grey = ColorsProxy.Gray; public static readonly Color clear = ColorsProxy.Transparent; public static bool operator ==(Color c1, Color c2) => c1.proxy == c2.proxy; public static bool operator !=(Color c1, Color c2) => c1.proxy != c2.proxy; public static Color32 Lerp(Color white, Color grey, float value) { throw new NotImplementedException(); } public static void RGBToHSV(Color32 color32, out float h, out float s, out float v) { throw new NotImplementedException(); } } public struct Vector2Int { public int x; public int y; public Vector2Int(int x, int y) : this() { this.x = x; this.y = y; } public override bool Equals(object obj) { if (obj is Vector2Int other) { return x == other.x && y == other.y; } return false; } public override int GetHashCode() { var hashCode = 1502939027; hashCode = hashCode * -1521134295 + x.GetHashCode(); hashCode = hashCode * -1521134295 + y.GetHashCode(); return hashCode; } public static bool operator ==(Vector2Int v1, Vector2Int v2) => (v1.x == v2.x && v1.y == v2.y); public static bool operator !=(Vector2Int v1, Vector2Int v2) => (v1.x != v2.x || v1.y != v2.y); } public struct Vector2 { public float x; public float y; internal Vector2Proxy Proxy { get => new Vector2(x, y); set { x = (float)value.X; y = (float)value.Y; } } public float magnitude { get { return (float)Proxy.Length; } } internal Vector2(Vector2Proxy p) { x = (float)p.X; y = (float)p.Y; } public Vector2(float x, float y) { this.x = x; this.y = y; } public static float Distance(Vector2 a, Vector2 b) { var v = b.Proxy - a.Proxy; return (float)v.Length; } public override bool Equals(object obj) { if (obj is Vector2 other) { return x == other.x && y == other.y; } return false; } public override int GetHashCode() { return Proxy.GetHashCode(); } public static implicit operator Vector2(Vector2Proxy p) => new Vector2(p); public static implicit operator Vector2Proxy(Vector2 v) => v.Proxy; public static implicit operator Point2DProxy(Vector2 v) => new Point2DProxy(v.x, v.y); public static implicit operator Vector2(Vector3 v) => new Vector2(v.x, v.y); public static Vector2 operator *(Vector2 v, float s) => (v.Proxy * s); public static Vector2 operator +(Vector2 v1, Vector2 v2) => (v1.Proxy + v2.Proxy); public static Vector2 operator -(Vector2 v1, Vector2 v2) => (v1.Proxy - v2.Proxy); public static Vector2 operator *(Vector2 v1, Vector2 v2) => new Vector2(v1.x * v2.x, v1.y * v2.y); public static bool operator ==(Vector2 v1, Vector2 v2) => (v1.x == v2.x && v1.y == v2.y); public static bool operator !=(Vector2 v1, Vector2 v2) => (v1.x != v2.x || v1.y != v2.y); public static readonly Vector2 zero = new Vector2Proxy(0.0, 0.0); public static readonly Vector2 one = new Vector2Proxy(1.0, 1.0); } public struct Vector3 { internal Vector3Proxy proxy; public float x { get => (float)proxy.X; set => proxy.X = value; } public float y { get => (float)proxy.Y; set => proxy.Y = value; } public float z { get => (float)proxy.Z; set => proxy.Z = value; } internal Vector3(Vector3Proxy v) { proxy = v; } public Vector3(float x, float y, float z) { proxy = new Vector3Proxy(x, y, z); } public Vector3 normalized { get => throw new NotImplementedException(); } public float magnitude { get => throw new NotImplementedException(); } public static float Distance(Vector3 a, Vector3 b) { var v = b.proxy - a.proxy; return (float)v.Length; } public static float Dot(Vector3 a, Vector3 b) { return (float)Vector3Proxy.DotProduct(a, b); } public static Vector3 Cross(Vector3 a, Vector3 b) { return Vector3Proxy.CrossProduct(a.proxy, b.proxy); } public static void OrthoNormalize(ref Vector3 n, ref Vector3 t) { throw new NotImplementedException(); } public static Vector3 Normalize(Vector3 v) { Vector3 result = new Vector3(v); result.proxy.Normalize(); return result; } public void Normalize() { proxy.Normalize(); } public static Vector3 Lerp(Vector3 smoothFollowerPrevWorldPos, Vector3 position, float v) { throw new NotImplementedException(); } public void Scale(Vector3 amount) { throw new NotImplementedException(); } public override bool Equals(object obj) { if (obj is Vector3 other) { return proxy == other.proxy; } return false; } public override int GetHashCode() { return proxy.GetHashCode(); } public static implicit operator Vector3(Vector3Proxy v) => new Vector3(v); public static implicit operator Vector3Proxy(Vector3 v) => v.proxy; public static implicit operator Point3DProxy(Vector3 v) => new Point3DProxy(v.proxy.X, v.proxy.Y, v.proxy.Z); public static Vector3 operator +(Vector3 v1, Vector3 v2) => new Vector3(v1.proxy + v2.proxy); public static Vector3 operator -(Vector3 v1, Vector3 v2) => new Vector3(v1.proxy - v2.proxy); public static Vector3 operator *(Vector3 v, float d) => new Vector3(v.proxy * d); public static Vector3 operator /(Vector3 v, float d) => new Vector3(v.proxy / d); public static bool operator ==(Vector3 v1, Vector3 v2) => (v1.proxy == v2.proxy); public static bool operator !=(Vector3 v1, Vector3 v2) => (v1.proxy != v2.proxy); public static implicit operator Vector3(Vector2 v) { throw new NotImplementedException(); } public static readonly Vector3 one = new Vector3Proxy(1.0, 1.0, 1.0); public static readonly Vector3 zero = new Vector3Proxy(0.0, 0.0, 0.0); public static readonly Vector3 up = new Vector3Proxy(0.0, 1.0, 0.0); public static readonly Vector3 down = new Vector3Proxy(0.0, -1.0, 0.0); public static readonly Vector3 forward = new Vector3Proxy(1.0, 0.0, 0.0); public static readonly Vector3 back = new Vector3Proxy(-1.0, 0.0, 0.0); public static readonly Vector3 right = new Vector3Proxy(0.0, 0.0, 1.0); public static readonly Vector3 left = new Vector3Proxy(0.0, 0.0, -1.0); } public struct Bounds { public Vector3 min; public Vector3 max; public Vector3 extents { get => throw new NotImplementedException(); } public Vector3 center { get => throw new NotImplementedException(); } public bool Contains(Vector3 point) { throw new NotImplementedException(); } } public struct Vector4 { internal Vector4Proxy vector; public float x { get => (float)vector.X; set => vector.X = value; } public float y { get => (float)vector.Y; set => vector.Y = value; } public float z { get => (float)vector.Z; set => vector.Z = value; } public float w { get => (float)vector.W; set => vector.W = value; } internal Vector4(Vector4Proxy v) { vector = v; } public Vector4(float x, float y, float z, float w) { vector = new Vector4Proxy(x, y, z, w); } } public class Quaternion { internal QuaternionProxy quaternion; public static readonly object identity; public float x, y, z, w; public Quaternion() { } internal Quaternion(QuaternionProxy q) { quaternion = q; } public static implicit operator Quaternion(QuaternionProxy q) => new Quaternion(q); public static implicit operator QuaternionProxy(Quaternion q) => q.quaternion; public static Quaternion LookRotation(Vector3 vector3) { throw new NotImplementedException(); } public static Quaternion Euler(float xrot, float angle, float v) { throw new NotImplementedException(); } } public class Matrix4x4 { internal readonly Matrix4x4Proxy matrix; public static readonly Matrix4x4 identity; public Matrix4x4(Matrix4x4Proxy q) { matrix = q; } public Vector3 GetColumn(int col) { throw new NotImplementedException(); } public Vector3 MultiplyPoint3x4(Vector3 vector3) { throw new NotImplementedException(); } public Vector3 MultiplyVector(Vector3 vector3) { throw new NotImplementedException(); } public float this[int r, int c] { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public Quaternion rotation; public Vector3 lossyScale; public static implicit operator Matrix4x4(Matrix4x4Proxy m) => new Matrix4x4(m); public static implicit operator Matrix4x4Proxy(Matrix4x4 m) => m.matrix; } public struct Rect { public Vector2 position; public Vector2 size; public Rect(float x = 0, float y = 0, float width = 0, float height = 0) { position = new Vector2(x, y); size = new Vector2(width, height); } public Rect(Vector2 position, Vector2 size) { this.position = position; this.size = size; } public float x { get => position.x; set => position.x = value; } public float y { get => position.y; set => position.y = value; } public float width { get => size.x; set => size.x = value; } public float height { get => size.y; set => size.y = value; } public float xMin { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public float xMax { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public float yMin { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public float yMax { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } } public static class Mathf { public static readonly int Rad2Deg; public static float Abs(float a) { return Math.Abs(a); } public static float Pow(float a, float e) { return (float)Math.Pow(a, e); } public static float Lerp(float a, float b, float t) { return a + t * (b - a); } public static float Clamp01(float a) { return Math.Max(Math.Min(1.0f, a), 0.0f); } public static float Clamp(float a, float min, float max) { return Math.Max(Math.Min(max, a), min); } public static int Clamp(int a, int min, int max) { return Math.Max(Math.Min(max, a), min); } public static float PerlinNoise(float v1, float v2) { throw new NotImplementedException(); } public static int Atan2(float v, float delta) { throw new NotImplementedException(); } public static bool Approximately(float delta, int v) { throw new NotImplementedException(); } public static float Exp(float v) { throw new NotImplementedException(); } public static float Sqrt(float p) { throw new NotImplementedException(); } public static float Sign(float p) { throw new NotImplementedException(); } public static float Max(float a, float b) { throw new NotImplementedException(); } public static float Min(float a, float b) { throw new NotImplementedException(); } } }
25.845238
97
0.527982
[ "MIT" ]
jonnybasic/tesNet
UnityProxy/Unity.cs
17,370
C#
๏ปฟusing UnityEngine; public interface IUiElementSelector { void Select(RectTransform parent); void Deselect(); }
16.285714
35
0.789474
[ "MIT" ]
azsdaja/Osnowa
Assets/Scripts/IUiElementSelector.cs
116
C#
๏ปฟnamespace Herc.Pwa.Server.Entities { /// <summary> /// This is base interface for all Entities. /// </summary> /// <remarks> /// I normally use a GUID on everything even if it is not the primary key. /// it helps by being able to migrate data. If I copy records from one db to another the /// auto incrementing id could and likely would be different where the GUID would be the same. /// Leaving out the GUID to start with /// TODO: consider adding GUID. /// </remarks> public interface IEntity { /// <summary> /// /// </summary> /// <remarks> /// It is nice to ability to have a generic collection Entities /// Also nice to have clarity when dealing with many Ids with <Entity>Id /// To allow for both means you can (see Code below) /// </remarks> /// <code> /// Example: /// public int ApplicationId { get; set; } /// public int Id => ApplicationId; /// </code> int Id { get; } } }
32.3
96
0.621259
[ "Unlicense" ]
iamonuwa/herc-in-blazorstate
Source/Herc.Pwa.Server/Entities/IEntity.cs
971
C#
using System; using System.IO; using System.Text; using UnityEngine; using System.ComponentModel; namespace Ginkgo { public enum LogLevel { [Description("None")] None, [Description("Debug")] Debug, [Description("Info")] Info, [Description("Warning")] Warning, [Description("Error")] Error } public class LogInfo { public string m_name; public bool m_consolePrinting = true; public bool m_screenPrinting; public bool m_filePrinting; public LogLevel m_minLevel = LogLevel.Debug; public LogLevel m_defaultLevel = LogLevel.Debug; public bool m_verbose; } public enum LogTarget { INVALID, CONSOLE, SCREEN, FILE } public class Logger { private const string OUTPUT_DIRECTORY_NAME = "Logs"; private const string OUTPUT_FILE_EXTENSION = "log"; private string m_name; private StreamWriter m_fileWriter; private bool m_fileWriterInitialized; public Logger(string name) { this.m_name = name; } public bool CanPrint(LogTarget target, LogLevel level, bool verbose) { LogInfo logInfo = Log.Get().GetLogInfo(this.m_name); if (logInfo == null) { return false; } if (level < logInfo.m_minLevel) { return false; } if (verbose && !logInfo.m_verbose) { return false; } switch (target) { case LogTarget.CONSOLE: return logInfo.m_consolePrinting; case LogTarget.SCREEN: return logInfo.m_screenPrinting; case LogTarget.FILE: return logInfo.m_filePrinting; default: return false; } } public bool CanPrint() { LogInfo logInfo = Log.Get().GetLogInfo(this.m_name); return logInfo != null && (logInfo.m_consolePrinting || logInfo.m_screenPrinting || logInfo.m_filePrinting); } public LogLevel GetDefaultLevel() { LogInfo logInfo = Log.Get().GetLogInfo(this.m_name); if (logInfo == null) { return LogLevel.Debug; } return logInfo.m_defaultLevel; } public bool IsVerbose() { LogInfo logInfo = Log.Get().GetLogInfo(this.m_name); return logInfo != null && logInfo.m_verbose; } public void Print(string format, params object[] args) { LogLevel defaultLevel = this.GetDefaultLevel(); this.Print(defaultLevel, false, format, args); } public void Print(LogLevel level, string format, params object[] args) { this.Print(level, false, format, args); } public void Print(bool verbose, string format, params object[] args) { LogLevel defaultLevel = this.GetDefaultLevel(); this.Print(defaultLevel, verbose, format, args); } public void Print(LogLevel level, bool verbose, string format, params object[] args) { string message = GeneralUtils.SafeFormat(format, args); this.Print(level, verbose, message); } public void Print(LogLevel level, bool verbose, string message) { this.FilePrint(level, verbose, message); this.ConsolePrint(level, verbose, message); this.ScreenPrint(level, verbose, message); } public void PrintDebug(string format, params object[] args) { this.PrintDebug(false, format, args); } public void PrintDebug(bool verbose, string format, params object[] args) { this.Print(LogLevel.Debug, verbose, format, args); } public void PrintInfo(string format, params object[] args) { this.PrintInfo(false, format, args); } public void PrintInfo(bool verbose, string format, params object[] args) { this.Print(LogLevel.Info, verbose, format, args); } public void PrintWarning(string format, params object[] args) { this.PrintWarning(false, format, args); } public void PrintWarning(bool verbose, string format, params object[] args) { this.Print(LogLevel.Warning, verbose, format, args); } public void PrintError(string format, params object[] args) { this.PrintError(false, format, args); } public void PrintError(bool verbose, string format, params object[] args) { this.Print(LogLevel.Error, verbose, format, args); } public void FilePrint(string format, params object[] args) { LogLevel defaultLevel = this.GetDefaultLevel(); this.FilePrint(defaultLevel, false, format, args); } public void FilePrint(LogLevel level, string format, params object[] args) { this.FilePrint(level, false, format, args); } public void FilePrint(bool verbose, string format, params object[] args) { LogLevel defaultLevel = this.GetDefaultLevel(); this.FilePrint(defaultLevel, verbose, format, args); } public void FilePrint(LogLevel level, bool verbose, string format, params object[] args) { string message = GeneralUtils.SafeFormat(format, args); this.FilePrint(level, verbose, message); } public void FilePrint(LogLevel level, bool verbose, string message) { if (!this.CanPrint(LogTarget.FILE, level, verbose)) { return; } this.InitFileWriter(); if (this.m_fileWriter == null) { return; } StringBuilder stringBuilder = new StringBuilder(); switch (level) { case LogLevel.Debug: stringBuilder.Append("D "); break; case LogLevel.Info: stringBuilder.Append("I "); break; case LogLevel.Warning: stringBuilder.Append("W "); break; case LogLevel.Error: stringBuilder.Append("E "); break; } stringBuilder.Append(DateTime.Now.TimeOfDay.ToString()); stringBuilder.Append(" "); stringBuilder.Append(message); this.m_fileWriter.WriteLine(stringBuilder.ToString()); this.m_fileWriter.Flush(); } public void ConsolePrint(string format, params object[] args) { LogLevel defaultLevel = this.GetDefaultLevel(); this.ConsolePrint(defaultLevel, false, format, args); } public void ConsolePrint(LogLevel level, string format, params object[] args) { this.ConsolePrint(level, false, format, args); } public void ConsolePrint(bool verbose, string format, params object[] args) { LogLevel defaultLevel = this.GetDefaultLevel(); this.ConsolePrint(defaultLevel, verbose, format, args); } public void ConsolePrint(LogLevel level, bool verbose, string format, params object[] args) { string message = GeneralUtils.SafeFormat(format, args); this.ConsolePrint(level, verbose, message); } public void ConsolePrint(LogLevel level, bool verbose, string message) { if (!this.CanPrint(LogTarget.CONSOLE, level, verbose)) { return; } string message2 = string.Format("[{0}] {1}", this.m_name, message); switch (level) { case LogLevel.Debug: case LogLevel.Info: Debug.Log(message2); break; case LogLevel.Warning: Debug.LogWarning(message2); break; case LogLevel.Error: Debug.LogError(message2); break; } } public void ScreenPrint(string format, params object[] args) { LogLevel defaultLevel = this.GetDefaultLevel(); this.ScreenPrint(defaultLevel, false, format, args); } public void ScreenPrint(LogLevel level, string format, params object[] args) { this.ScreenPrint(level, false, format, args); } public void ScreenPrint(bool verbose, string format, params object[] args) { LogLevel defaultLevel = this.GetDefaultLevel(); this.ScreenPrint(defaultLevel, verbose, format, args); } public void ScreenPrint(LogLevel level, bool verbose, string format, params object[] args) { string message = GeneralUtils.SafeFormat(format, args); this.ScreenPrint(level, verbose, message); } public void ScreenPrint(LogLevel level, bool verbose, string message) { if (!this.CanPrint(LogTarget.SCREEN, level, verbose)) { return; } if (ScreenDebugger.Get() == null) { return; } string message2 = string.Format("[{0}] {1}", this.m_name, message); ScreenDebugger.Get().AddMessage(message2); } private void InitFileWriter() { if (this.m_fileWriterInitialized) { return; } this.m_fileWriter = null; string text = Path.Combine(FileUtils.PersistentDataPath, OUTPUT_DIRECTORY_NAME); if (!Directory.Exists(text)) { try { Directory.CreateDirectory(text); } catch (Exception) { } } string path = string.Format("{0}/{1}.{2}", text, this.m_name, OUTPUT_FILE_EXTENSION); try { this.m_fileWriter = new StreamWriter(new FileStream(path, FileMode.Create, FileAccess.ReadWrite)); } catch (Exception) { } this.m_fileWriterInitialized = true; } } }
30.508475
120
0.533889
[ "MIT" ]
boostmerlin/UnityPolymer
HostUnityProj/Assets/Ginkgo/Gadget/Log/Logger.cs
10,800
C#
๏ปฟusing System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace task2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } int[,] m = new int[,] { { 4, 9, 12 }, { 56, 45, 23 }, { 3, 67, 89 } }; // ะพะฑัŠัะฒะปะตะฝะธะต ะธ ะธะฝะธั†ะธะฐะปะธะทะฐั†ะธั ะดะฒัƒะผะตั€ะฝะพะณะพ ะผะฐััะธะฒะฐ m private void button1_Click(object sender, EventArgs e) { for (int i = 0; i <= m.GetUpperBound(0); ++i) { for (int j = 0; j <= m.GetUpperBound(1); ++j) { richTextBox1.Text += String.Format("{0}{1} ัะปะตะผะตะฝั‚ = {2};", i, j, m[i, j]); // ะดะพะฑะฐะฒะปะตะฝะธะต ัะปะตะผะตะฝั‚ะฐ ะผะฐััะธะฒะฐ(ัั‚ั€ะพะบะฐ i, ัั‚ะพะปะฑะตั† j, ัะปะตะผะตะฝั‚ m[i, j]) ะฒ richtextbox1 } richTextBox1.Text += "\n"; // ะฟะตั€ะตั…ะพะด ะฝะฐ ะฝะพะฒัƒัŽ ัั‚ั€ะพั‡ะบัƒ ะฟะพัะปะต ะดะพะฑะฐะฒะปะตะฝะธั ะฒัะตั… ัะปะตะผะตะฝั‚ะพะฒ ั‚ะตะบัƒั‰ะตะน(i-ะพะน) ัั‚ั€ะพะบะธ ะผะฐััะธะฒะฐ m } } } }
31.735294
179
0.561631
[ "Apache-2.0" ]
dkhramchenko/cpp
laba6/task2/task2/Form1.cs
1,246
C#
๏ปฟusing Abp.Configuration.Startup; using Abp.Localization.Dictionaries; using Abp.Localization.Dictionaries.Xml; using Abp.Reflection.Extensions; namespace Workflow.Localization { public static class WorkflowLocalizationConfigurer { public static void Configure(ILocalizationConfiguration localizationConfiguration) { localizationConfiguration.Sources.Add( new DictionaryBasedLocalizationSource(WorkflowConsts.LocalizationSourceName, new XmlEmbeddedFileLocalizationDictionaryProvider( typeof(WorkflowLocalizationConfigurer).GetAssembly(), "Workflow.Localization.SourceFiles" ) ) ); } } }
33.391304
92
0.661458
[ "MIT" ]
rafim25/AngularBoiler
aspnet-core/src/Workflow.Core/Localization/WorkflowLocalizationConfigurer.cs
770
C#
๏ปฟusing System; using System.Security.Cryptography; using System.Text; using TreeGecko.Library.Common.Objects; namespace TreeGecko.Library.Net.Objects { public class TGUserPassword : AbstractTGObject { public Guid UserGuid { get; set; } public string Salt { get; set; } public String HashedPassword { get; set; } public override TGSerializedObject GetTGSerializedObject() { TGSerializedObject tgs = base.GetTGSerializedObject(); tgs.Add("UserGuid", UserGuid); tgs.Add("HashedPassword", HashedPassword); tgs.Add("Salt", Salt); return tgs; } public override void LoadFromTGSerializedObject(TGSerializedObject _tgs) { base.LoadFromTGSerializedObject(_tgs); UserGuid = _tgs.GetGuid("UserGuid"); HashedPassword = _tgs.GetString("HashedPassword"); Salt = _tgs.GetString("Salt"); } public static string GenerateSalt(string _username, int _size = 25) { byte[] saltSalt = Guid.NewGuid().ToByteArray(); Rfc2898DeriveBytes hasher = new Rfc2898DeriveBytes(_username, saltSalt, 10000); return Convert.ToBase64String(hasher.GetBytes(_size)); } public static string HashPassword(string _salt, string _plainTextPassword, int _size = 25) { byte[] saltBytes = Encoding.UTF8.GetBytes(_salt); Rfc2898DeriveBytes hasher = new Rfc2898DeriveBytes(_plainTextPassword, saltBytes, 10000); return Convert.ToBase64String(hasher.GetBytes(_size)); } public static TGUserPassword GetNew(Guid _userGuid, string _userName, string _password) { TGUserPassword userPassword = new TGUserPassword { Guid = _userGuid, UserGuid = _userGuid, Salt = GenerateSalt(_userName) }; userPassword.HashedPassword = HashPassword(userPassword.Salt, _password); return userPassword; } } }
32.703125
101
0.623029
[ "MIT" ]
TreeGecko/Libraries
src/tgNet/Objects/TGUserPassword.cs
2,095
C#
๏ปฟnamespace tomenglertde.ResXManager.VSIX.Visuals { using System.ComponentModel.Composition; using JetBrains.Annotations; using tomenglertde.ResXManager.Infrastructure; using TomsToolbox.Wpf.Composition; [LocalizedDisplayName(StringResourceKey.ShowErrorsConfiguration_Header)] [VisualCompositionExport(RegionId.Configuration)] internal class ShowErrorsConfigurationViewModel { [ImportingConstructor] public ShowErrorsConfigurationViewModel([NotNull] DteConfiguration configuration) { Configuration = configuration; } [NotNull] public DteConfiguration Configuration { get; } } }
28.08
90
0.707977
[ "MIT" ]
DJmRek/ResXResourceManager
ResXManager.VSIX/Visuals/ShowErrorsConfigurationViewModel.cs
704
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("Latex4CorelDraw")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Latex4CorelDraw")] [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("7325577f-8891-476d-aa82-a9c82d5c708c")] // 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.7")] [assembly: AssemblyFileVersion("1.0.7")]
36.842105
84
0.746429
[ "MIT" ]
mfschumann/Latex4CorelDraw
Properties/AssemblyInfo.cs
1,403
C#
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.ResponseCompression; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.IdentityModel.Tokens; using pruebatecnicapeaku.Server.Models; using System; using System.Linq; using System.Text; namespace pruebatecnicapeaku.Server { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity<IdentityUser, IdentityRole>(). AddEntityFrameworkStores<ApplicationDbContext>(). AddDefaultTokenProviders(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme). AddJwtBearer(options => options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = false, ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey( Encoding.UTF8.GetBytes(Configuration["jwt:key"])), ClockSkew = TimeSpan.Zero }); services.AddControllersWithViews(); services.AddRazorPages(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseWebAssemblyDebugging(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseBlazorFrameworkFiles(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); endpoints.MapControllers(); endpoints.MapFallbackToFile("index.html"); }); } } }
36.670455
143
0.626278
[ "MIT" ]
edgaralvarezrengifo/prueatecnica_peaku
pruebatecnicapeaku/Server/Startup.cs
3,227
C#
๏ปฟusing System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 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("SkipYoutubeAdSysTray")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SkipYoutubeAdSysTray")] [assembly: AssemblyCopyright("Copyright ยฉ 2020")] [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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // 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")]
42.642857
98
0.711474
[ "MIT" ]
aivarasatk/YoutubeAdSkipper
SkipYoutubeAdSysTray/Properties/AssemblyInfo.cs
2,391
C#
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using RestSharp; namespace Atlassian.Jira.Remote { /// <summary> /// Contract for a client that interacts with JIRA via rest. /// </summary> public interface IJiraRestClient { /// <summary> /// Base url of the Jira server. /// </summary> string Url { get; } /// <summary> /// RestSharp client used to issue requests. /// </summary> RestClient RestSharpClient { get; } /// <summary> /// Settings to configure the rest client. /// </summary> JiraRestClientSettings Settings { get; } /// <summary> /// Executes a request. /// </summary> /// <param name="request">Request object.</param> /// <param name="token">Cancellation token for the operation.</param> Task<IRestResponse> ExecuteRequestAsync(IRestRequest request, CancellationToken token = default(CancellationToken)); /// <summary> /// Executes an async request and returns the response as JSON. /// </summary> /// <param name="method">Request method.</param> /// <param name="resource">Request resource url.</param> /// <param name="requestBody">Request body to be serialized.</param> /// <param name="token">Cancellation token for the operation.</param> Task<JToken> ExecuteRequestAsync(Method method, string resource, object requestBody = null, CancellationToken token = default(CancellationToken)); /// <summary> /// Executes an async request and serializes the response to an object. /// </summary> /// <typeparam name="T">Type to serialize the response.</typeparam> /// <param name="method">Request method.</param> /// <param name="resource">Request resource url.</param> /// <param name="requestBody">Request body to be serialized.</param> /// <param name="token">Cancellation token for this operation.</param> Task<T> ExecuteRequestAsync<T>(Method method, string resource, object requestBody = null, CancellationToken token = default(CancellationToken)); /// <summary> /// Executes an async request and serializes the response to an object. /// </summary> /// <typeparam name="T">Type to serialize the response.</typeparam> /// <param name="method">Request method.</param> /// <param name="resource">Request resource url.</param> /// <param name="requestBody">Request body to be serialized.</param> /// <param name="token">Cancellation token for this operation.</param> /// <param name="queryParameters">Parameters to add to OAuth queries.</param> Task<JToken> ExecuteRequestAsync(Method method, string resource, Dictionary<string, string> queryParameters, object requestBody = null, CancellationToken token = default(CancellationToken)); /// <summary> /// Executes an async request and serializes the response to an object. /// </summary> /// <typeparam name="T">Type to serialize the response.</typeparam> /// <param name="method">Request method.</param> /// <param name="resource">Request resource url.</param> /// <param name="requestBody">Request body to be serialized.</param> /// <param name="token">Cancellation token for this operation.</param> /// <param name="queryParameters">Parameters to add to OAuth queries.</param> Task<T> ExecuteRequestAsync<T>(Method method, string resource, Dictionary<string, string> queryParameters, object requestBody = null, CancellationToken token = default(CancellationToken)); } }
47.949367
198
0.646251
[ "BSD-2-Clause" ]
tkosanke/atlassian.net-sdk
Atlassian.Jira/Remote/IJiraRestClient.cs
3,788
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Threading; using System.Threading.Tasks; namespace Microsoft.PowerShell.EditorServices.Services.PowerShell.Console { /// <summary> /// Provides platform specific console utilities. /// </summary> internal interface IConsoleOperations { /// <summary> /// Obtains the next character or function key pressed by the user asynchronously. /// Does not block when other console API's are called. /// </summary> /// <param name="intercept"> /// Determines whether to display the pressed key in the console window. <see langword="true" /> /// to not display the pressed key; otherwise, <see langword="false" />. /// </param> /// <param name="cancellationToken">The CancellationToken to observe.</param> /// <returns> /// An object that describes the <see cref="ConsoleKey" /> constant and Unicode character, if any, /// that correspond to the pressed console key. The <see cref="ConsoleKeyInfo" /> object also /// describes, in a bitwise combination of <see cref="ConsoleModifiers" /> values, whether /// one or more Shift, Alt, or Ctrl modifier keys was pressed simultaneously with the console key. /// </returns> ConsoleKeyInfo ReadKey(bool intercept, CancellationToken cancellationToken); /// <summary> /// Obtains the next character or function key pressed by the user asynchronously. /// Does not block when other console API's are called. /// </summary> /// <param name="intercept"> /// Determines whether to display the pressed key in the console window. <see langword="true" /> /// to not display the pressed key; otherwise, <see langword="false" />. /// </param> /// <param name="cancellationToken">The CancellationToken to observe.</param> /// <returns> /// A task that will complete with a result of the key pressed by the user. /// </returns> Task<ConsoleKeyInfo> ReadKeyAsync(bool intercept, CancellationToken cancellationToken); /// <summary> /// Obtains the horizontal position of the console cursor. Use this method /// instead of <see cref="System.Console.CursorLeft" /> to avoid triggering /// pending calls to <see cref="IConsoleOperations.ReadKeyAsync(bool, CancellationToken)" /> /// on Unix platforms. /// </summary> /// <returns>The horizontal position of the console cursor.</returns> int GetCursorLeft(); /// <summary> /// Obtains the horizontal position of the console cursor. Use this method /// instead of <see cref="System.Console.CursorLeft" /> to avoid triggering /// pending calls to <see cref="IConsoleOperations.ReadKeyAsync(bool, CancellationToken)" /> /// on Unix platforms. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken" /> to observe.</param> /// <returns>The horizontal position of the console cursor.</returns> int GetCursorLeft(CancellationToken cancellationToken); /// <summary> /// Obtains the horizontal position of the console cursor. Use this method /// instead of <see cref="System.Console.CursorLeft" /> to avoid triggering /// pending calls to <see cref="IConsoleOperations.ReadKeyAsync(bool, CancellationToken)" /> /// on Unix platforms. /// </summary> /// <returns> /// A <see cref="Task{T}" /> representing the asynchronous operation. The /// <see cref="Task{T}.Result" /> property will return the horizontal position /// of the console cursor. /// </returns> Task<int> GetCursorLeftAsync(); /// <summary> /// Obtains the horizontal position of the console cursor. Use this method /// instead of <see cref="System.Console.CursorLeft" /> to avoid triggering /// pending calls to <see cref="IConsoleOperations.ReadKeyAsync(bool, CancellationToken)" /> /// on Unix platforms. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken" /> to observe.</param> /// <returns> /// A <see cref="Task{T}" /> representing the asynchronous operation. The /// <see cref="Task{T}.Result" /> property will return the horizontal position /// of the console cursor. /// </returns> Task<int> GetCursorLeftAsync(CancellationToken cancellationToken); /// <summary> /// Obtains the vertical position of the console cursor. Use this method /// instead of <see cref="System.Console.CursorTop" /> to avoid triggering /// pending calls to <see cref="IConsoleOperations.ReadKeyAsync(bool, CancellationToken)" /> /// on Unix platforms. /// </summary> /// <returns>The vertical position of the console cursor.</returns> int GetCursorTop(); /// <summary> /// Obtains the vertical position of the console cursor. Use this method /// instead of <see cref="System.Console.CursorTop" /> to avoid triggering /// pending calls to <see cref="IConsoleOperations.ReadKeyAsync(bool, CancellationToken)" /> /// on Unix platforms. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken" /> to observe.</param> /// <returns>The vertical position of the console cursor.</returns> int GetCursorTop(CancellationToken cancellationToken); /// <summary> /// Obtains the vertical position of the console cursor. Use this method /// instead of <see cref="System.Console.CursorTop" /> to avoid triggering /// pending calls to <see cref="IConsoleOperations.ReadKeyAsync(bool, CancellationToken)" /> /// on Unix platforms. /// </summary> /// <returns> /// A <see cref="Task{T}" /> representing the asynchronous operation. The /// <see cref="Task{T}.Result" /> property will return the vertical position /// of the console cursor. /// </returns> Task<int> GetCursorTopAsync(); /// <summary> /// Obtains the vertical position of the console cursor. Use this method /// instead of <see cref="System.Console.CursorTop" /> to avoid triggering /// pending calls to <see cref="IConsoleOperations.ReadKeyAsync(bool, CancellationToken)" /> /// on Unix platforms. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken" /> to observe.</param> /// <returns> /// A <see cref="Task{T}" /> representing the asynchronous operation. The /// <see cref="Task{T}.Result" /> property will return the vertical position /// of the console cursor. /// </returns> Task<int> GetCursorTopAsync(CancellationToken cancellationToken); } }
51.359712
106
0.636644
[ "MIT" ]
CALISOULB/PowerShellEditorServices
src/PowerShellEditorServices/Services/PowerShell/Console/IConsoleOperations.cs
7,139
C#
๏ปฟusing System; using GVFS.Common; using GVFS.Common.Git; using GVFS.Virtualization.FileSystem; namespace GVFS.UnitTests.Mock.Virtualization.FileSystem { public class MockFileSystemVirtualizer : FileSystemVirtualizer { public MockFileSystemVirtualizer(GVFSContext context, GVFSGitObjects gvfsGitObjects) : base(context, gvfsGitObjects) { } public override FileSystemResult ClearNegativePathCache(out uint totalEntryCount) { totalEntryCount = 0; return new FileSystemResult(FSResult.Ok, rawResult: 0); } public override FileSystemResult DeleteFile(string relativePath, UpdatePlaceholderType updateFlags, out UpdateFailureReason failureReason) { throw new NotImplementedException(); } public override void Stop() { } public override FileSystemResult UpdatePlaceholderIfNeeded(string relativePath, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime, DateTime changeTime, uint fileAttributes, long endOfFile, string shaContentId, UpdatePlaceholderType updateFlags, out UpdateFailureReason failureReason) { throw new NotImplementedException(); } protected override bool TryStart(out string error) { error = null; return true; } } }
34.119048
313
0.671319
[ "MIT" ]
abhijeet-gautam/VFSForGit
GVFS/GVFS.UnitTests/Mock/Virtualization/FileSystem/MockFileSystemVirtualizer.cs
1,435
C#
๏ปฟusing System.Collections.Generic; namespace Melanchall.DryWetMidi.Core { // TODO: test /// <summary> /// Comparer to compare <see cref="MidiFile"/> objects for equality. /// </summary> public sealed class MidiFileEqualityComparer : IEqualityComparer<MidiFile> { #region Fields private readonly MidiFileEqualityCheckSettings _settings; #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="MidiFileEqualityComparer"/>. /// </summary> public MidiFileEqualityComparer() : this(null) { } /// <summary> /// Initializes a new instance of the <see cref="MidiFileEqualityComparer"/> with the /// specified settings according to which <see cref="MidiFile"/> objects should /// be compared for equality. /// </summary> /// <param name="settings">Settings according to which <see cref="MidiFile"/> objects should /// be compared for equality.</param> public MidiFileEqualityComparer(MidiFileEqualityCheckSettings settings) { _settings = settings ?? new MidiFileEqualityCheckSettings(); } #endregion #region IEqualityComparer<MidiFile> /// <summary> /// Determines whether the specified objects are equal. /// </summary> /// <param name="x">The first file to compare.</param> /// <param name="y">The second file to compare.</param> /// <returns><c>true</c> if the specified objects are equal; otherwise, <c>false</c>.</returns> public bool Equals(MidiFile x, MidiFile y) { string message; return MidiFile.Equals(x, y, _settings, out message); } /// <summary> /// Returns a hash code for the specified object. /// </summary> /// <param name="obj">The <see cref="MidiFile"/> for which a hash code is to be returned.</param> /// <returns>A hash code for the specified object.</returns> public int GetHashCode(MidiFile obj) { return obj.Chunks.Count.GetHashCode(); } #endregion } }
32.735294
105
0.597934
[ "MIT" ]
EnableIrelandAT/Coimbra
ProjectCoimbra.UWP/Melanchall.DryWetMidi.UWP/Core/Equality/File/MidiFileEqualityComparer.cs
2,228
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. namespace System.Windows.Forms { using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System; using System.ComponentModel; using System.Windows.Forms; using System.Drawing; using Microsoft.Win32; internal class Command : WeakReference { private static Command[] cmds; private static int icmdTry; private static readonly object internalSyncObject = new object(); private const int idMin = 0x00100; private const int idLim = 0x10000; internal int id; public Command(ICommandExecutor target) : base(target, false) { AssignID(this); } public virtual int ID { get { return id; } } [SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")] protected static void AssignID(Command cmd) { lock (internalSyncObject) { int icmd; if (null == cmds) { cmds = new Command[20]; icmd = 0; } else { Debug.Assert(cmds.Length > 0, "why is cmds.Length zero?"); Debug.Assert(icmdTry >= 0, "why is icmdTry negative?"); int icmdLim = cmds.Length; if (icmdTry >= icmdLim) { icmdTry = 0; } // First look for an empty slot (starting at icmdTry). for (icmd = icmdTry; icmd < icmdLim; icmd++) { if (null == cmds[icmd]) { goto FindSlotComplete; } } for (icmd = 0; icmd < icmdTry; icmd++) { if (null == cmds[icmd]) { goto FindSlotComplete; } } // All slots have Command objects in them. Look for a command // with a null referent. for (icmd = 0; icmd < icmdLim; icmd++) { if (null == cmds[icmd].Target) { goto FindSlotComplete; } } // Grow the array. icmd = cmds.Length; icmdLim = Math.Min(idLim - idMin, 2 * icmd); if (icmdLim <= icmd) { // Already at maximal size. Do a garbage collect and look again. GC.Collect(); for (icmd = 0; icmd < icmdLim; icmd++) { if (null == cmds[icmd] || null == cmds[icmd].Target) { goto FindSlotComplete; } } throw new ArgumentException(SR.CommandIdNotAllocated); } else { Command[] newCmds = new Command[icmdLim]; Array.Copy(cmds, 0, newCmds, 0, icmd); cmds = newCmds; } } FindSlotComplete: cmd.id = icmd + idMin; Debug.Assert(cmd.id >= idMin && cmd.id < idLim, "generated command id out of range"); cmds[icmd] = cmd; icmdTry = icmd + 1; } } public static bool DispatchID(int id) { Command cmd = GetCommandFromID(id); if (null == cmd) { return false; } return cmd.Invoke(); } protected static void Dispose(Command cmd) { lock (internalSyncObject) { if (cmd.id >= idMin) { cmd.Target = null; if (cmds[cmd.id - idMin] == cmd) { cmds[cmd.id - idMin] = null; } cmd.id = 0; } } } public virtual void Dispose() { if (id >= idMin) { Dispose(this); } } public static Command GetCommandFromID(int id) { lock (internalSyncObject) { if (null == cmds) { return null; } int i = id - idMin; if (i < 0 || i >= cmds.Length) { return null; } return cmds[i]; } } public virtual bool Invoke() { object target = Target; if (!(target is ICommandExecutor)) { return false; } ((ICommandExecutor)target).Execute(); return true; } } }
28.219388
101
0.389261
[ "MIT" ]
Bhaskers-Blu-Org2/winforms
src/System.Windows.Forms/src/System/Windows/Forms/Command.cs
5,533
C#
using ModelsLayer.Models; using System; using System.Collections.Generic; #nullable disable namespace ModelsLayer.ViewModels { public class ViewProduct { public ViewProduct() { } public ViewProduct(int productId, int? seasonalId, string productName, decimal productPrice, string productDescription, decimal? productDiscount) { ProductId = productId; SeasonalId = seasonalId; ProductName = productName; ProductPrice = productPrice; ProductDescription = productDescription; ProductDiscount = productDiscount; } public int ProductId { get; set; } public int? SeasonalId { get; set; } public string ProductName { get; set; } public decimal ProductPrice { get; set; } public string ProductDescription { get; set; } public decimal? ProductDiscount { get; set; } public int? CategoryId { get; set; } public string? Category { get; set; } //public virtual Category Category { get; set; } public virtual Seasonal Seasonal { get; set; } public virtual ICollection<UserProduct> UserProducts { get; set; } } }
27.292683
149
0.690795
[ "MIT" ]
Not-Fight-Club/not-fight-club-shop
ShopService/ModelsLayer/ViewModels/ViewProduct.cs
1,119
C#
๏ปฟ๏ปฟusing System; using System.Xml.Serialization; using System.Collections; using System.Collections.Generic; using Newtonsoft.Json; namespace JdSdk.Response.Price { ๏ปฟ [Serializable] public class PriceChange : JdObject { [JsonProperty("sku_id")] public String SkuId { get; set; } [JsonProperty("price")] public String Price { get; set; } [JsonProperty("market_price")] public String MarketPrice { get; set; } } }
16.638889
39
0.519199
[ "Apache-2.0" ]
starpeng/JdSdk2
Source/JdSdk/response/price/PriceChange.cs
605
C#
๏ปฟ//------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.18034 // // ร„nderungen an dieser Datei kรถnnen falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ namespace OnTimePad_WPF.Properties { using System; /// <summary> /// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw. /// </summary> // Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert // -Klasse รผber ein Tool wie ResGen oder Visual Studio automatisch generiert. // Um einen Member hinzuzufรผgen oder zu entfernen, bearbeiten Sie die .ResX-Datei und fรผhren dann ResGen // mit der /str-Option erneut aus, oder Sie erstellen Ihr VS-Projekt neu. [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> /// Gibt die zwischengespeicherte ResourceManager-Instanz zurรผck, die von dieser Klasse verwendet wird. /// </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("OnTimePad_WPF.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// รœberschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads fรผr alle /// Ressourcenzuordnungen, die diese stark typisierte Ressourcenklasse verwenden. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
46.9375
179
0.637816
[ "MIT" ]
pixi1/One-Time-Pad-V2.0.0
Properties/Resources.Designer.cs
3,014
C#
๏ปฟusing System.Collections.Generic; using System.Runtime.Serialization; using CCSWE.FiveHundredPx.Models; namespace CCSWE.FiveHundredPx.Contracts { [DataContract] public class GetPhotoFavoritesResponse: PagedResponse { [DataMember(Name = "users")] public List<User> Users { get; set; } } }
23.071429
57
0.712074
[ "Apache-2.0" ]
CoryCharlton/CCSWE-500px-API
Source/Api/Contracts/GetPhotoFavoritesResponse.cs
325
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 PinWin { 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 EmbeddedResource { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal EmbeddedResource() { } /// <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("PinWin.EmbeddedResource", typeof(EmbeddedResource).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; } } /// <summary> /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). /// </summary> internal static System.Drawing.Icon TargetWindowIcon { get { object obj = ResourceManager.GetObject("TargetWindowIcon", resourceCulture); return ((System.Drawing.Icon)(obj)); } } } }
42.932432
175
0.604658
[ "MIT" ]
Mario-Kart-Felix/pinwin
PinWin/EmbeddedResource.Designer.cs
3,179
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: Templates\CSharp\Requests\IEntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The interface IEducationSchoolRequest. /// </summary> public partial interface IEducationSchoolRequest : IBaseRequest { /// <summary> /// Creates the specified EducationSchool using POST. /// </summary> /// <param name="educationSchoolToCreate">The EducationSchool to create.</param> /// <returns>The created EducationSchool.</returns> System.Threading.Tasks.Task<EducationSchool> CreateAsync(EducationSchool educationSchoolToCreate); /// <summary> /// Creates the specified EducationSchool using POST. /// </summary> /// <param name="educationSchoolToCreate">The EducationSchool to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created EducationSchool.</returns> System.Threading.Tasks.Task<EducationSchool> CreateAsync(EducationSchool educationSchoolToCreate, CancellationToken cancellationToken); /// <summary> /// Deletes the specified EducationSchool. /// </summary> /// <returns>The task to await.</returns> System.Threading.Tasks.Task DeleteAsync(); /// <summary> /// Deletes the specified EducationSchool. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken); /// <summary> /// Gets the specified EducationSchool. /// </summary> /// <returns>The EducationSchool.</returns> System.Threading.Tasks.Task<EducationSchool> GetAsync(); /// <summary> /// Gets the specified EducationSchool. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The EducationSchool.</returns> System.Threading.Tasks.Task<EducationSchool> GetAsync(CancellationToken cancellationToken); /// <summary> /// Updates the specified EducationSchool using PATCH. /// </summary> /// <param name="educationSchoolToUpdate">The EducationSchool to update.</param> /// <returns>The updated EducationSchool.</returns> System.Threading.Tasks.Task<EducationSchool> UpdateAsync(EducationSchool educationSchoolToUpdate); /// <summary> /// Updates the specified EducationSchool using PATCH. /// </summary> /// <param name="educationSchoolToUpdate">The EducationSchool to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception> /// <returns>The updated EducationSchool.</returns> System.Threading.Tasks.Task<EducationSchool> UpdateAsync(EducationSchool educationSchoolToUpdate, CancellationToken cancellationToken); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> IEducationSchoolRequest Expand(string value); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> IEducationSchoolRequest Expand(Expression<Func<EducationSchool, object>> expandExpression); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> IEducationSchoolRequest Select(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> IEducationSchoolRequest Select(Expression<Func<EducationSchool, object>> selectExpression); } }
47.296296
153
0.641543
[ "MIT" ]
OfficeGlobal/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/IEducationSchoolRequest.cs
5,108
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Batch.V20200301.Inputs { public sealed class TaskContainerSettingsArgs : Pulumi.ResourceArgs { /// <summary> /// These additional options are supplied as arguments to the "docker create" command, in addition to those controlled by the Batch Service. /// </summary> [Input("containerRunOptions")] public Input<string>? ContainerRunOptions { get; set; } /// <summary> /// This is the full image reference, as would be specified to "docker pull". If no tag is provided as part of the image name, the tag ":latest" is used as a default. /// </summary> [Input("imageName", required: true)] public Input<string> ImageName { get; set; } = null!; /// <summary> /// This setting can be omitted if was already provided at pool creation. /// </summary> [Input("registry")] public Input<Inputs.ContainerRegistryArgs>? Registry { get; set; } [Input("workingDirectory")] public Input<string>? WorkingDirectory { get; set; } public TaskContainerSettingsArgs() { } } }
35.585366
174
0.650446
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/Batch/V20200301/Inputs/TaskContainerSettingsArgs.cs
1,459
C#
// This file is part of Silk.NET. // // You may modify and distribute Silk.NET under the terms // of the MIT license. See the LICENSE file for details. using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Text; using Silk.NET.Core; using Silk.NET.Core.Native; using Silk.NET.Core.Attributes; using Silk.NET.Core.Contexts; using Silk.NET.Core.Loader; #pragma warning disable 1591 namespace Silk.NET.Direct3D9 { [NativeName("Name", "_D3DOVERLAYCAPS")] public unsafe partial struct Overlaycaps { public Overlaycaps ( uint? caps = null, uint? maxOverlayDisplayWidth = null, uint? maxOverlayDisplayHeight = null ) : this() { if (caps is not null) { Caps = caps.Value; } if (maxOverlayDisplayWidth is not null) { MaxOverlayDisplayWidth = maxOverlayDisplayWidth.Value; } if (maxOverlayDisplayHeight is not null) { MaxOverlayDisplayHeight = maxOverlayDisplayHeight.Value; } } [NativeName("Type", "UINT")] [NativeName("Type.Name", "UINT")] [NativeName("Name", "Caps")] public uint Caps; [NativeName("Type", "UINT")] [NativeName("Type.Name", "UINT")] [NativeName("Name", "MaxOverlayDisplayWidth")] public uint MaxOverlayDisplayWidth; [NativeName("Type", "UINT")] [NativeName("Type.Name", "UINT")] [NativeName("Name", "MaxOverlayDisplayHeight")] public uint MaxOverlayDisplayHeight; } }
26.28125
72
0.598098
[ "MIT" ]
ThomasMiz/Silk.NET
src/Microsoft/Silk.NET.Direct3D9/Structs/Overlaycaps.gen.cs
1,682
C#
๏ปฟusing System; using System.Collections.Generic; using System.Windows.Forms; using Grasshopper.Kernel; using Grasshopper.Kernel.Data; using Grasshopper.Kernel.Types; using GH_IO.Serialization; using Rhino.Geometry; namespace Heron { public class MultiMeshPatch : HeronComponent { /// <summary> /// Initializes a new instance of the MultiMeshPatch class. /// </summary> public MultiMeshPatch() : base("Multi Mesh Patch", "MMPatch", "Multithreaded creation of mesh patches from planar polylines. The first polyine in a branch will be considered the outer boundary, " + "any others will be considered holes and should be completely within the outer boundary.", "Utilities") { } public override Grasshopper.Kernel.GH_Exposure Exposure { get { return GH_Exposure.tertiary; } } /// <summary> /// Registers all the input parameters for this component. /// </summary> protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager) { pManager.AddCurveParameter("Polylines", "polylines", "Polylines from which to generate mesh patches. The first polyine in a branch will be considered the outer boundary, " + "any others will be considered holes and should be completely within the outer boundary.", GH_ParamAccess.tree); pManager.AddNumberParameter("Extrude Height", "extrude", "Height to extrude mesh patches.", GH_ParamAccess.tree); pManager[1].Optional = true; } /// <summary> /// Registers all the output parameters for this component. /// </summary> protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager) { pManager.AddMeshParameter("Mesh Patches", "meshes", "Meshes resulting from mesh patches.", GH_ParamAccess.tree); } /// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param> protected override void SolveInstance(IGH_DataAccess DA) { GH_Structure<GH_Curve> crvs = new GH_Structure<GH_Curve>(); DA.GetDataTree<GH_Curve>(0, out crvs); GH_Structure<GH_Number> height = new GH_Structure<GH_Number>(); DA.GetDataTree<GH_Number>(1, out height); double tol = DocumentTolerance(); //reserve one processor for GUI totalMaxConcurrancy = System.Environment.ProcessorCount - 1; //tells us how many threads were using //Message = totalMaxConcurrancy + " threads"; //create a dictionary that works in parallel var mPatchTree = new System.Collections.Concurrent.ConcurrentDictionary<GH_Path, GH_Mesh>(); //Multi-threading the loop System.Threading.Tasks.Parallel.ForEach(crvs.Paths, new System.Threading.Tasks.ParallelOptions { MaxDegreeOfParallelism = totalMaxConcurrancy }, pth => { List<Curve> branchCrvs = new List<Curve>(); double offset = 0; if (crvs.get_Branch(pth).Count > 0) { foreach (var ghCrv in crvs.get_Branch(pth)) { Curve c = null; GH_Convert.ToCurve(ghCrv, ref c, 0); if (extrudeDir == "Extrude Z") { ///Ensure boundary winds clockwise if (c.ClosedCurveOrientation(Vector3d.ZAxis) < 0) { c.Reverse(); } } branchCrvs.Add(c); } ///Convert first curve in branch to polyline ///Don't know why the boundary parameter can't be a Curve if the holes are allowed to be Curves Polyline pL = null; branchCrvs[0].TryGetPolyline(out pL); branchCrvs.RemoveAt(0); ///Check validity of pL if (!pL.IsValid) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Curve could not be converted to polyline or is invalid"); } ///The magic found here: ///https://discourse.mcneel.com/t/mesh-with-holes-from-polylines-in-rhinowip-to-c/45589 Mesh mPatch = Mesh.CreatePatch(pL, tol, null, branchCrvs, null, null, true, 1); mPatch.Ngons.AddPlanarNgons(tol); mPatch.FaceNormals.ComputeFaceNormals(); mPatch.Normals.ComputeNormals(); mPatch.Compact(); //mPatch.UnifyNormals(); if (height.PathExists(pth)) { if (height.get_Branch(pth).Count > 0) { GH_Convert.ToDouble(height.get_Branch(pth)[0], out offset, 0); if (extrudeDir == "Extrude Z") { mPatch = mPatch.Offset(offset, true, Vector3d.ZAxis); } else { mPatch = mPatch.Offset(offset, true); } } } else if (height.get_FirstItem(true) != null) { GH_Convert.ToDouble(height.get_FirstItem(true), out offset, 0); if (extrudeDir == "Extrude Z") { mPatch = mPatch.Offset(offset, true, Vector3d.ZAxis); } else { mPatch = mPatch.Offset(offset, true); } } else { } mPatchTree[pth] = new GH_Mesh(mPatch); } }); ///End of multi-threaded loop ///Convert dictionary to regular old data tree GH_Structure<GH_Mesh> mTree = new GH_Structure<GH_Mesh>(); foreach (KeyValuePair<GH_Path, GH_Mesh> m in mPatchTree) { mTree.Append(m.Value, m.Key); } DA.SetDataTree(0, mTree); } public static int totalMaxConcurrancy = 1; /// Add menu items for extrusion selection protected override void AppendAdditionalComponentMenuItems(ToolStripDropDown menu) { ToolStripMenuItem exZ = new ToolStripMenuItem("Extrude Z"); exZ.Tag = "Extrude Z"; exZ.ToolTipText = "Extrude in the positive World Z axis."; exZ.Checked = IsItemSelected("Extrude Z"); exZ.Click += Menu_DoClick; ToolStripMenuItem exN = new ToolStripMenuItem("Extrude Normal"); exN.Tag = "Extrude Normal"; exN.ToolTipText = "Extrude normal to the mesh faces in the patch."; exN.Checked = IsItemSelected("Extrude Normal"); exN.Click += Menu_DoClick; //base.AppendAdditionalComponentMenuItems(menu); menu.Items.Add(exZ); menu.Items.Add(exN); } private void Menu_DoClick(object sender, EventArgs e) { ToolStripMenuItem item = sender as ToolStripMenuItem; if (item == null) return; string code = (string)item.Tag; if (IsItemSelected(code)) return; RecordUndoEvent("ExtrudeDir"); extrudeDir = code; Message = totalMaxConcurrancy + " threads | " + extrudeDir; ExpireSolution(true); } private string extrudeDir = "Extrude Z"; private bool IsItemSelected(string eZ) { return eZ.Equals(extrudeDir); } public string ExtrudeDir { get { return extrudeDir; } set { extrudeDir = value; } } /// Sticky items public override bool Write(GH_IO.Serialization.GH_IWriter writer) { writer.SetString("ExtrudeDir", ExtrudeDir); return base.Write(writer); } public override bool Read(GH_IReader reader) { ExtrudeDir = reader.GetString("ExtrudeDir"); return base.Read(reader); } /// <summary> /// Provides an Icon for the component. /// </summary> protected override System.Drawing.Bitmap Icon { get { //You can add image files to your project resources and access them like this: // return Resources.IconForThisComponent; return Properties.Resources.shp; } } /// <summary> /// Gets the unique ID for this component. Do not change this ID after release. /// </summary> public override Guid ComponentGuid { get { return new Guid("7bc480af-4f21-4b55-8ba7-36e3f2082d7f"); } } } }
37.316206
186
0.530135
[ "MIT" ]
blueherongis/Heron
Heron/Components/Utilities/MultiMeshPatch.cs
9,443
C#
๏ปฟusing UnityEngine; using System.Collections; using UnityEngine.UI; namespace RVP { [DisallowMultipleComponent] [AddComponentMenu("RVP/Demo Scripts/Vehicle HUD", 1)] //Class for the HUD in the demo public class VehicleHud : MonoBehaviour { public GameObject targetVehicle; public Text speedText; public Text gearText; public Slider rpmMeter; public Slider boostMeter; public Text propertySetterText; public Text stuntText; public Text scoreText; VehicleParent vp; Motor engine; Transmission trans; GearboxTransmission gearbox; ContinuousTransmission varTrans; StuntDetect stunter; public bool stuntMode; float stuntEndTime = -1; PropertyToggleSetter propertySetter; private void Start() { Initialize(targetVehicle); } public void Initialize(GameObject newVehicle) { if (!newVehicle) { return; } targetVehicle = newVehicle; vp = targetVehicle.GetComponent<VehicleParent>(); trans = targetVehicle.GetComponentInChildren<Transmission>(); if (trans) { if (trans is GearboxTransmission) { gearbox = trans as GearboxTransmission; } else if (trans is ContinuousTransmission) { varTrans = trans as ContinuousTransmission; } } if (stuntMode) { stunter = targetVehicle.GetComponent<StuntDetect>(); } engine = targetVehicle.GetComponentInChildren<Motor>(); propertySetter = targetVehicle.GetComponent<PropertyToggleSetter>(); stuntText.gameObject.SetActive(stuntMode); scoreText.gameObject.SetActive(stuntMode); } void Update() { if (vp) { speedText.text = (vp.velMag * 2.23694f).ToString("0") + " MPH"; if (trans) { if (gearbox) { gearText.text = "Gear: " + (gearbox.currentGear == 0 ? "R" : (gearbox.currentGear == 1 ? "N" : (gearbox.currentGear - 1).ToString())); } else if (varTrans) { gearText.text = "Ratio: " + varTrans.currentRatio.ToString("0.00"); } } if (engine) { rpmMeter.value = engine.targetPitch; if (engine.maxBoost > 0) { boostMeter.value = engine.boost / engine.maxBoost; } } if (stuntMode && stunter) { stuntEndTime = string.IsNullOrEmpty(stunter.stuntString) ? Mathf.Max(0, stuntEndTime - Time.deltaTime) : 2; if (stuntEndTime == 0) { stuntText.text = ""; } else if (!string.IsNullOrEmpty(stunter.stuntString)) { stuntText.text = stunter.stuntString; } scoreText.text = "Score: " + stunter.score.ToString("n0"); } if (propertySetter) { propertySetterText.text = propertySetter.currentPreset == 0 ? "Normal Steering" : (propertySetter.currentPreset == 1 ? "Skid Steering" : "Crab Steering"); } } } } }
31.644068
174
0.488484
[ "MIT" ]
cobby1212/Randomation-Vehicle-Physics
Assets/Scripts/Demo/VehicleHud.cs
3,736
C#
๏ปฟusing System; using System.Collections.Generic; using System.Web; using System.Linq; public class Example { // Initializing Lib internal DBContext dBContext = new DBContext("Example\\SQLEXPRESS", "DataBase"); public Example() { //Some Possible Variables to Change dBContext.timeOut = 50; // In seconds dBContext.bufferSize = 65000; // Amout of bytes send per package (used for streaming only) } //Executing a Command public void ExecuteCommand(int id, string newName) { string sqlCommand = @" UPDATE Example SET Name = @p1 WHERE ID = @p0"; dbContext.ExecuteSqlCommand(sqlCommand, id, newName); } //Getting From Server public List<Example> GetList() { string sqlCommand = @" SELECT ID, Name FROM Example "; return dBContext.SqlQuery<Example>(sqlCommand); } public Example GetItem(int id) { string sqlCommand = @" SELECT ID, Name FROM Example WHERE ID = @p0 "; return dBContext.SqlQuery<Example>(sqlCommand, id).FirstOrDefault(); } //File Stream public void FileStream(System.Web.HttpContext httpContext, long offset, int id) { string sqlCommand = @" SELECT B.File.PathName() AS PathName, B.Size AS Size FROM Example WHERE ID = @p0 "; dBContext.FileStream(httpContext, offset, sqlCommand, id); } public class Example { public int ID { get; set; } public string Name { get; set; } } } // Using FileStream //Example example = GetItem(Convert.ToInt32(context.Request["id"])); //string fileName = (example.Name == "" ? "noName.jpg" : archive.Name); //context.Response.ContentType = archive.Type; //context.Response.AddHeader("Content-Disposition", "inline; filename=" + fileName); //archiveBLL.FileStream(context, example.ID);
27.935065
99
0.562064
[ "MIT" ]
RealSvildr/SQLMinimal
Example.cs
2,153
C#
๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MYCGenerator4OurDailyBread.GlobalVariables { public static class GlobalVariables { public const string MainFolderTokenKey = "MainFolderToken"; public const int MaxPlusNum = 10; } }
21.125
67
0.748521
[ "MIT" ]
ychsue/MYCGenerator4OurDailyBread
MYCGenerator4OurDailyBread/GlobalVariables/GlobalVariables.cs
340
C#
๏ปฟ/* <file> Description: Azure Storage Blob Quickstart: Demonstrate how to upload, list, download, and delete blobs Authors: Vadim Osovitny Anatoly Osovitny Created: 22 Jun 2018 Copyright (c) 2018 Osovitny Inc. All rights reserved. </file> */ using Microsoft.WindowsAzure.Storage; using System; namespace Osovitny.Azure.Storage.Blob.QuickStart { class Program { private static string STORAGE_CONNECTIONSTRING = "PUT-YOUR-STORAGE-CONNECTIONSTRING-HERE"; static void Main(string[] args) { /* All Samples for fictional company: Alex Corporation */ CloudStorageAccount storageAccount = null; if (!CloudStorageAccount.TryParse(STORAGE_CONNECTIONSTRING, out storageAccount)) { Console.WriteLine("A connection string is not correct"); Console.WriteLine("Press any key to exit application."); Console.ReadLine(); return; } Basics.ProcessSamplesAsync(storageAccount).Wait(); Advanced.ProcessSamplesAsync(storageAccount).Wait(); Console.WriteLine("Press any key to exit the sample application."); Console.ReadLine(); } } }
23.52
94
0.682823
[ "MIT" ]
osovitny/azure-storage-quickstart
.NETCore/BlobQuickStart/Program.cs
1,178
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.OnsMqtt.Model.V20200420; namespace Aliyun.Acs.OnsMqtt.Transform.V20200420 { public class ListGroupIdResponseUnmarshaller { public static ListGroupIdResponse Unmarshall(UnmarshallerContext context) { ListGroupIdResponse listGroupIdResponse = new ListGroupIdResponse(); listGroupIdResponse.HttpResponse = context.HttpResponse; listGroupIdResponse.RequestId = context.StringValue("ListGroupId.RequestId"); List<ListGroupIdResponse.ListGroupId_MqttGroupIdDo> listGroupIdResponse_data = new List<ListGroupIdResponse.ListGroupId_MqttGroupIdDo>(); for (int i = 0; i < context.Length("ListGroupId.Data.Length"); i++) { ListGroupIdResponse.ListGroupId_MqttGroupIdDo mqttGroupIdDo = new ListGroupIdResponse.ListGroupId_MqttGroupIdDo(); mqttGroupIdDo.CreateTime = context.LongValue("ListGroupId.Data["+ i +"].CreateTime"); mqttGroupIdDo.GroupId = context.StringValue("ListGroupId.Data["+ i +"].GroupId"); mqttGroupIdDo.IndependentNaming = context.BooleanValue("ListGroupId.Data["+ i +"].IndependentNaming"); mqttGroupIdDo.InstanceId = context.StringValue("ListGroupId.Data["+ i +"].InstanceId"); mqttGroupIdDo.UpdateTime = context.LongValue("ListGroupId.Data["+ i +"].UpdateTime"); listGroupIdResponse_data.Add(mqttGroupIdDo); } listGroupIdResponse.Data = listGroupIdResponse_data; return listGroupIdResponse; } } }
44
141
0.754717
[ "Apache-2.0" ]
awei1688/aliyun-openapi-net-sdk
aliyun-net-sdk-onsmqtt/OnsMqtt/Transform/V20200420/ListGroupIdResponseUnmarshaller.cs
2,332
C#
๏ปฟusing Android.App; using Android.Widget; using Android.OS; namespace TelemetryQs { [Activity(Label = "TelemetryQs", MainLauncher = true, Icon = "@mipmap/icon")] public class MainActivity : Activity { int count = 1; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); // Get our button from the layout resource, // and attach an event to it Button button = FindViewById<Button>(Resource.Id.myButton); button.Click += delegate { button.Text = $"{count++} clicks!"; }; } } }
26.5
81
0.609164
[ "MIT" ]
NAXAM/mapbox-android-telemetry-android-binding
demo/TelemetryQs/MainActivity.cs
744
C#
๏ปฟusing System; using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// Player's unique data /// </summary> /// <remarks> /// Not used in any of implementations. /// </remarks> public struct PlayerUData { public string playerName; public Guid guid; public PlayerUData(string name,Guid id) { playerName = name; guid=id; } } /// <summary> /// Player Controller /// </summary> public class PlayerController : BasicController { /// <summary> /// Input manager of this controller. /// <para>Each player controller has one input manager</para> /// </summary> private InputManager inputMngr; public InputManager GetInputManager { get { return inputMngr; } } public string playerName; /// <summary> /// Unique ID of this player controller or player /// </summary> private Guid guid; public Guid GetID { get { return guid; } } public PlayerUData GetPlayerUniqueData { get { return new PlayerUData(playerName, guid); } } private void Awake() { guid = Guid.NewGuid(); } // Use this for initialization public override void Start () { base.Start(); } // Update is called once per frame public override void Update () { } public override void OnDestroy() { base.OnDestroy(); inputMngr.onInputProcessed -= processMovement; } public override void controlPawn(BasicPawn pawn) { base.controlPawn(pawn); } public override void releasePawn() { if (inputMngr) { string guidStr = guid.ToString(); inputMngr.stopListenerSet(guidStr); inputMngr.stopTouchSet(guidStr); } base.releasePawn(); } /// <summary> /// Method that need to be called after taking control of pawn to start listening to controls of that pawn from input manager /// <para>will be useful in later stage of project</para> /// </summary> /// <param name="inputManager">Input manager to pass in</param> public void setupInputs(InputManager inputManager) { if (inputMngr == null) inputMngr = inputManager; inputMngr.onInputProcessed += processMovement; Dictionary<string, Action<float>> inputMap = new Dictionary<string, Action<float>>(); ((Player)controlledPawn).setupInputs(ref inputMap); foreach (KeyValuePair<string, Action<float>> entry in inputMap) { inputMngr.addToListenerSet(guid.ToString(), entry.Key, entry.Value); } inputMap.Clear(); ((Player)controlledPawn).setupTouches(ref inputMap); foreach (KeyValuePair<string, Action<float>> entry in inputMap) { inputMngr.addToTouchSet(guid.ToString(), entry.Key, entry.Value); } } public void setInputActive(bool isActive) { string guidStr = guid.ToString(); if (isActive) { inputMngr.resumeListenerSet(guidStr); inputMngr.resumeTouchSet(guidStr); } else { inputMngr.pauseListenerSet(guidStr); inputMngr.pauseTouchSet(guidStr); } } }
24.139706
129
0.610113
[ "MIT" ]
jeslaspravin/FlappyBird
Assets/Scripts/Controller/PlayerController.cs
3,285
C#
๏ปฟusing OpenTK.Graphics.OpenGL; using System; namespace Render.Core.GraphicsInterface { public class VertexArrayObject : IManagedAssetHandle { public readonly float[] Data; internal VertexArrayObject(ManagedGraphicsService graphics) { this.graphics = graphics; handle = graphics.gl.GenVertexArray(); } private readonly ManagedGraphicsService graphics; public ManagedGraphicsService GraphicsService => throw new NotImplementedException(); private readonly int handle; public int Handle => handle; public AssetBinding Binding() { graphics.gl.BindVertexArray(handle); return new AssetBinding(() => graphics.gl.BindVertexArray(0)); } public void Dispose() { graphics.gl.DeleteVertexArray(handle); graphics.VertexArrayHandles.Remove(handle); } } }
26.971429
93
0.637712
[ "MIT" ]
KelsonBall/RaymarchingSim
src/Render.Core.GraphicsInterfaces/VertexArrayObject.cs
946
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq.Expressions; using UnityEditor; using UnityEngine; public static class SerializableObjHelper { public static SerializedProperty FindProperty(this SerializedObject obj, Expression<Func<object>> exp) { var body = exp.Body as MemberExpression; if (body == null) { var ubody = (UnaryExpression)exp.Body; body = ubody.Operand as MemberExpression; } var name = body.Member.Name; return obj.FindProperty(name); } public static SerializedProperty FindPropertyRelative(this SerializedProperty obj, Expression<Func<object>> exp) { var body = exp.Body as MemberExpression; if (body == null) { var ubody = (UnaryExpression)exp.Body; body = ubody.Operand as MemberExpression; } var name = body.Member.Name; return obj.FindPropertyRelative(name); } }
22.512821
113
0.747153
[ "MIT" ]
LaudateCorpus1/Physical-Camera
Project/Assets/Vfx-Camera/Scripts/Editor/SerializableObjHelper.cs
878
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable namespace Azure.ResourceManager.Compute.Models { /// <summary> Describes the properties of the Virtual Machine for which the restore point was created. The properties provided are a subset and the snapshot of the overall Virtual Machine properties captured at the time of the restore point creation. </summary> public partial class RestorePointSourceMetadata { /// <summary> Initializes a new instance of RestorePointSourceMetadata. </summary> internal RestorePointSourceMetadata() { } /// <summary> Initializes a new instance of RestorePointSourceMetadata. </summary> /// <param name="hardwareProfile"> Gets the hardware profile. </param> /// <param name="storageProfile"> Gets the storage profile. </param> /// <param name="osProfile"> Gets the OS profile. </param> /// <param name="diagnosticsProfile"> Gets the diagnostics profile. </param> /// <param name="licenseType"> Gets the license type, which is for bring your own license scenario. </param> /// <param name="vmId"> Gets the virtual machine unique id. </param> /// <param name="securityProfile"> Gets the security profile. </param> /// <param name="location"> Location of the VM from which the restore point was created. </param> internal RestorePointSourceMetadata(HardwareProfile hardwareProfile, RestorePointSourceVmStorageProfile storageProfile, OSProfile osProfile, DiagnosticsProfile diagnosticsProfile, string licenseType, string vmId, SecurityProfile securityProfile, string location) { HardwareProfile = hardwareProfile; StorageProfile = storageProfile; OSProfile = osProfile; DiagnosticsProfile = diagnosticsProfile; LicenseType = licenseType; VmId = vmId; SecurityProfile = securityProfile; Location = location; } /// <summary> Gets the hardware profile. </summary> public HardwareProfile HardwareProfile { get; } /// <summary> Gets the storage profile. </summary> public RestorePointSourceVmStorageProfile StorageProfile { get; } /// <summary> Gets the OS profile. </summary> public OSProfile OSProfile { get; } /// <summary> Gets the diagnostics profile. </summary> internal DiagnosticsProfile DiagnosticsProfile { get; } /// <summary> Boot Diagnostics is a debugging feature which allows you to view Console Output and Screenshot to diagnose VM status. &lt;br&gt;**NOTE**: If storageUri is being specified then ensure that the storage account is in the same region and subscription as the VM. &lt;br&gt;&lt;br&gt; You can easily view the output of your console log. &lt;br&gt;&lt;br&gt; Azure also enables you to see a screenshot of the VM from the hypervisor. </summary> public BootDiagnostics BootDiagnostics { get => DiagnosticsProfile?.BootDiagnostics; } /// <summary> Gets the license type, which is for bring your own license scenario. </summary> public string LicenseType { get; } /// <summary> Gets the virtual machine unique id. </summary> public string VmId { get; } /// <summary> Gets the security profile. </summary> public SecurityProfile SecurityProfile { get; } /// <summary> Location of the VM from which the restore point was created. </summary> public string Location { get; } } }
57.587302
458
0.68247
[ "MIT" ]
jasonsandlin/azure-sdk-for-net
sdk/compute/Azure.ResourceManager.Compute/src/Generated/Models/RestorePointSourceMetadata.cs
3,628
C#
/** * Copyright 2013 Canada Health Infoway, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: $LastChangedBy: gng $ * Last modified: $LastChangedDate: 2015-11-19 18:20:12 -0500 (Fri, 30 Jan 2015) $ * Revision: $LastChangedRevision: 9755 $ */ /* This class was auto-generated by the message builder generator tools. */ using Ca.Infoway.Messagebuilder; namespace Ca.Infoway.Messagebuilder.Model.Ab_r02_04_03_shr.Domainvalue { public interface RoleLinkStatusActive : Code { } }
36.413793
83
0.710227
[ "ECL-2.0", "Apache-2.0" ]
CanadaHealthInfoway/message-builder-dotnet
message-builder-release-ab_r02_04_03_shr/Main/Ca/Infoway/Messagebuilder/Model/Ab_r02_04_03_shr/Domainvalue/RoleLinkStatusActive.cs
1,056
C#
// *** WARNING: this file was generated by crd2pulumi. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Kubernetes.Types.Outputs.Apicur.V1Alpha1 { [OutputType] public sealed class ApicurioRegistrySpecConfigurationStreamsSecurity { public readonly Pulumi.Kubernetes.Types.Outputs.Apicur.V1Alpha1.ApicurioRegistrySpecConfigurationStreamsSecurityScram Scram; public readonly Pulumi.Kubernetes.Types.Outputs.Apicur.V1Alpha1.ApicurioRegistrySpecConfigurationStreamsSecurityTls Tls; [OutputConstructor] private ApicurioRegistrySpecConfigurationStreamsSecurity( Pulumi.Kubernetes.Types.Outputs.Apicur.V1Alpha1.ApicurioRegistrySpecConfigurationStreamsSecurityScram scram, Pulumi.Kubernetes.Types.Outputs.Apicur.V1Alpha1.ApicurioRegistrySpecConfigurationStreamsSecurityTls tls) { Scram = scram; Tls = tls; } } }
37.2
132
0.759857
[ "Apache-2.0" ]
pulumi/pulumi-kubernetes-crds
operators/apicurio-registry/dotnet/Kubernetes/Crds/Operators/ApicurioRegistry/Apicur/V1Alpha1/Outputs/ApicurioRegistrySpecConfigurationStreamsSecurity.cs
1,116
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace App.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class JosbListView : ContentPage { public JosbListView() { InitializeComponent(); } } }
19.238095
53
0.673267
[ "MIT" ]
AdrianaMota/MobileApp-Xamarin
src/App/Views/JosbListView.xaml.cs
404
C#
๏ปฟusing UnityEngine; [CreateAssetMenu( fileName = "UnsignedLongVariable.asset", menuName = SOArchitecture_Utility.ADVANCED_VARIABLE_SUBMENU + "ulong", order = SOArchitecture_Utility.ASSET_MENU_ORDER_COLLECTIONS + 17)] public class ULongVariable : BaseVariable<ulong> { }
31.333333
74
0.787234
[ "Unlicense" ]
Stevo0225/PuzzleGame
Assets/SO Architecture/Variables/ULongVariable.cs
284
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.DataCollection { using System; using System.Collections.ObjectModel; using Microsoft.VisualStudio.TestPlatform.Common.DataCollection; using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities; using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.DataCollection.Interfaces; using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Interfaces; using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging; /// <summary> /// Utility class that facilitates the IPC communication. Acts as server. /// </summary> public sealed class DataCollectionRequestSender : IDataCollectionRequestSender, IDisposable { private ICommunicationManager communicationManager; private IDataSerializer dataSerializer; /// <summary> /// Initializes a new instance of the <see cref="DataCollectionRequestSender"/> class. /// </summary> public DataCollectionRequestSender() : this(new SocketCommunicationManager(), JsonDataSerializer.Instance) { } /// <summary> /// Initializes a new instance of the <see cref="DataCollectionRequestSender"/> class. /// </summary> /// <param name="communicationManager"> /// The communication manager. /// </param> /// <param name="dataSerializer"> /// The data serializer. /// </param> internal DataCollectionRequestSender(ICommunicationManager communicationManager, IDataSerializer dataSerializer) { this.communicationManager = communicationManager; this.dataSerializer = dataSerializer; } /// <summary> /// Creates an endpoint and listens for client connection asynchronously /// </summary> /// <returns>Port number</returns> public int InitializeCommunication() { var port = this.communicationManager.HostServer(); this.communicationManager.AcceptClientAsync(); return port; } /// <summary> /// Waits for Request Handler to be connected /// </summary> /// <param name="clientConnectionTimeout">Time to wait for connection</param> /// <returns>True, if Handler is connected</returns> public bool WaitForRequestHandlerConnection(int clientConnectionTimeout) { return this.communicationManager.WaitForClientConnection(clientConnectionTimeout); } /// <summary> /// The dispose. /// </summary> public void Dispose() { this.communicationManager?.StopServer(); } /// <summary> /// Closes the connection /// </summary> public void Close() { this.Dispose(); if (EqtTrace.IsInfoEnabled) { EqtTrace.Info("Closing the connection"); } } /// <inheritdoc/> public BeforeTestRunStartResult SendBeforeTestRunStartAndGetResult(string settingsXml, ITestMessageEventHandler runEventsHandler) { var isDataCollectionStarted = false; BeforeTestRunStartResult result = null; this.communicationManager.SendMessage(MessageType.BeforeTestRunStart, settingsXml); while (!isDataCollectionStarted) { var message = this.communicationManager.ReceiveMessage(); if (message.MessageType == MessageType.DataCollectionMessage) { var msg = this.dataSerializer.DeserializePayload<DataCollectionMessageEventArgs>(message); runEventsHandler.HandleLogMessage(msg.Level, msg.Message); } else if (message.MessageType == MessageType.BeforeTestRunStartResult) { isDataCollectionStarted = true; result = this.dataSerializer.DeserializePayload<BeforeTestRunStartResult>(message); } } return result; } /// <inheritdoc/> public Collection<AttachmentSet> SendAfterTestRunStartAndGetResult(ITestMessageEventHandler runEventsHandler, bool isCancelled) { var isDataCollectionComplete = false; Collection<AttachmentSet> attachmentSets = null; this.communicationManager.SendMessage(MessageType.AfterTestRunEnd, isCancelled); // Cycle through the messages that the datacollector sends. // Currently each of the operations are not separate tasks since they should not each take much time. This is just a notification. while (!isDataCollectionComplete) { var message = this.communicationManager.ReceiveMessage(); if (message.MessageType == MessageType.DataCollectionMessage) { var msg = this.dataSerializer.DeserializePayload<DataCollectionMessageEventArgs>(message); runEventsHandler.HandleLogMessage(msg.Level, msg.Message); } else if (message.MessageType == MessageType.AfterTestRunEndResult) { attachmentSets = this.dataSerializer.DeserializePayload<Collection<AttachmentSet>>(message); isDataCollectionComplete = true; } } return attachmentSets; } } }
40.765517
142
0.642023
[ "MIT" ]
wjk/dotnet-vstest
src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionRequestSender.cs
5,911
C#
๏ปฟ// Copyright 2017, Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Ads.AdWords.Lib; using Google.Api.Ads.AdWords.v201710; using Google.Api.Ads.Common.Util; using System; namespace Google.Api.Ads.AdWords.Examples.CSharp.v201710 { /// <summary> /// This code example creates a click-to-download ad, also known as an /// app promotion ad to a given ad group. To list ad groups, run /// GetAdGroups.cs. /// </summary> public class AddClickToDownloadAd : ExampleBase { /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> /// <param name="args">The command line arguments.</param> public static void Main(string[] args) { AddClickToDownloadAd codeExample = new AddClickToDownloadAd(); Console.WriteLine(codeExample.Description); try { long adGroupId = long.Parse("INSERT_ADGROUP_ID_HERE"); codeExample.Run(new AdWordsUser(), adGroupId); } catch (Exception e) { Console.WriteLine("An exception occurred while running this code example. {0}", ExampleUtilities.FormatException(e)); } } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description { get { return "This code example creates a click-to-download ad, also known as an app " + "promotion ad to a given ad group. To list ad groups, run GetAdGroups.cs."; } } /// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="adGroupId">Id of the ad group to which ads are added. /// </param> public void Run(AdWordsUser user, long adGroupId) { using (AdGroupAdService adGroupAdService = (AdGroupAdService) user.GetService(AdWordsService.v201710.AdGroupAdService)) { // Create the template ad. TemplateAd clickToDownloadAppAd = new TemplateAd(); clickToDownloadAppAd.name = "Ad for demo game"; clickToDownloadAppAd.templateId = 353; clickToDownloadAppAd.finalUrls = new string[] { "http://play.google.com/store/apps/details?id=com.example.demogame" }; clickToDownloadAppAd.displayUrl = "play.google.com"; // Create the template elements for the ad. You can refer to // https://developers.google.com/adwords/api/docs/appendix/templateads // for the list of avaliable template fields. TemplateElementField headline = new TemplateElementField(); headline.name = "headline"; headline.fieldText = "Enjoy your drive in Mars"; headline.type = TemplateElementFieldType.TEXT; TemplateElementField description1 = new TemplateElementField(); description1.name = "description1"; description1.fieldText = "Realistic physics simulation"; description1.type = TemplateElementFieldType.TEXT; TemplateElementField description2 = new TemplateElementField(); description2.name = "description2"; description2.fieldText = "Race against players online"; description2.type = TemplateElementFieldType.TEXT; TemplateElementField appId = new TemplateElementField(); appId.name = "appId"; appId.fieldText = "com.example.demogame"; appId.type = TemplateElementFieldType.TEXT; TemplateElementField appStore = new TemplateElementField(); appStore.name = "appStore"; appStore.fieldText = "2"; appStore.type = TemplateElementFieldType.ENUM; // Optionally specify a landscape image. The image needs to be in a BASE64 // encoded form. Here we download a demo image and encode it for this ad. byte[] imageData = MediaUtilities.GetAssetDataFromUrl("https://goo.gl/9JmyKk", user.Config); Image image = new Image(); image.data = imageData; TemplateElementField landscapeImage = new TemplateElementField(); landscapeImage.name = "landscapeImage"; landscapeImage.fieldMedia = image; landscapeImage.type = TemplateElementFieldType.IMAGE; TemplateElement adData = new TemplateElement(); adData.uniqueName = "adData"; adData.fields = new TemplateElementField[] {headline, description1, description2, appId, appStore, landscapeImage}; clickToDownloadAppAd.templateElements = new TemplateElement[] { adData }; // Create the adgroupad. AdGroupAd clickToDownloadAppAdGroupAd = new AdGroupAd(); clickToDownloadAppAdGroupAd.adGroupId = adGroupId; clickToDownloadAppAdGroupAd.ad = clickToDownloadAppAd; // Optional: Set the status. clickToDownloadAppAdGroupAd.status = AdGroupAdStatus.PAUSED; // Create the operation. AdGroupAdOperation operation = new AdGroupAdOperation(); operation.@operator = Operator.ADD; operation.operand = clickToDownloadAppAdGroupAd; try { // Create the ads. AdGroupAdReturnValue retval = adGroupAdService.mutate( new AdGroupAdOperation[] { operation }); // Display the results. if (retval != null && retval.value != null) { foreach (AdGroupAd adGroupAd in retval.value) { Console.WriteLine("New click-to-download ad with id = \"{0}\" and url = \"{1}\" " + "was created.", adGroupAd.ad.id, adGroupAd.ad.finalUrls[0]); } } else { Console.WriteLine("No click-to-download ads were created."); } } catch (Exception e) { throw new System.ApplicationException("Failed to create click-to-download ad.", e); } } } } }
40.474359
97
0.663921
[ "Apache-2.0" ]
MajaGrubbe/googleads-dotnet-lib
examples/AdWords/CSharp/v201710/AdvancedOperations/AddClickToDownloadAd.cs
6,316
C#
using Amazon.JSII.Runtime.Deputy; #pragma warning disable CS0672,CS0809,CS1591 namespace AlibabaCloud.SDK.ROS.CDK.Vpc { #pragma warning disable CS8618 /// <summary>Properties for defining a `ALIYUN::VPC::IpsecServer`.</summary> [JsiiByValue(fqn: "@alicloud/ros-cdk-vpc.IpsecServerProps")] public class IpsecServerProps : AlibabaCloud.SDK.ROS.CDK.Vpc.IIpsecServerProps { /// <summary>Property clientIpPool: Client network segment refers to the address segment that assigns access addresses to the virtual network card of the client.</summary> /// <remarks> /// Note: The client network segment cannot conflict with the VPC side network segment. /// </remarks> [JsiiProperty(name: "clientIpPool", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOverride: true)] public object ClientIpPool { get; set; } /// <summary>Property localSubnet: The local network segment refers to the network segment on the VPC side that needs to be interconnected with the client network segment.</summary> /// <remarks> /// Use half-width commas (,) to separate multiple network segments, for example: 192.168.1.0/24,192.168.2.0/24. /// </remarks> [JsiiProperty(name: "localSubnet", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOverride: true)] public object LocalSubnet { get; set; } /// <summary>Property vpnGatewayId: VPN gateway instance ID.</summary> [JsiiProperty(name: "vpnGatewayId", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOverride: true)] public object VpnGatewayId { get; set; } /// <summary>Property effectImmediately: true: Apply the new configuration and trigger a reconnection immediately.</summary> /// <remarks> /// false: Trigger a reconnection only when network traffic occurs. (The reconnection may cause the network to be unavailable for a brief moment) /// </remarks> [JsiiOptional] [JsiiProperty(name: "effectImmediately", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"boolean\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true, isOverride: true)] public object? EffectImmediately { get; set; } /// <summary>Property ikeConfig: Negotiation parameter configuration in the first phase.</summary> [JsiiOptional] [JsiiProperty(name: "ikeConfig", typeJson: "{\"union\":{\"types\":[{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"},{\"fqn\":\"@alicloud/ros-cdk-vpc.RosIpsecServer.IkeConfigProperty\"}]}}", isOptional: true, isOverride: true)] public object? IkeConfig { get; set; } /// <summary>Property ipsecConfig: Negotiation parameter configuration in the second phase.</summary> [JsiiOptional] [JsiiProperty(name: "ipsecConfig", typeJson: "{\"union\":{\"types\":[{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"},{\"fqn\":\"@alicloud/ros-cdk-vpc.RosIpsecServer.IpsecConfigProperty\"}]}}", isOptional: true, isOverride: true)] public object? IpsecConfig { get; set; } /// <summary>Property ipsecServerName: The value must be 2 to 128 characters in length and start with a letter or Chinese character.</summary> /// <remarks> /// It can contain digits, underscores (_), and hyphens (-). /// </remarks> [JsiiOptional] [JsiiProperty(name: "ipsecServerName", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true, isOverride: true)] public object? IpsecServerName { get; set; } /// <summary>Property psk: Pre-Shared key.</summary> /// <remarks> /// Used for identity authentication between the VPN gateway and the client. A 16-bit random string is randomly generated by default, or you can manually specify the key. The length is limited to 100 characters. /// </remarks> [JsiiOptional] [JsiiProperty(name: "psk", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true, isOverride: true)] public object? Psk { get; set; } /// <summary>Property pskEnabled: Whether to enable the pre-shared key authentication method.</summary> /// <remarks> /// Only the value is true, which means that the pre-shared key authentication mode is enabled. /// </remarks> [JsiiOptional] [JsiiProperty(name: "pskEnabled", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"boolean\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true, isOverride: true)] public object? PskEnabled { get; set; } } }
48.118182
238
0.606461
[ "Apache-2.0" ]
aliyun/Resource-Orchestration-Service-Cloud-Development-K
multiple-languages/dotnet/AlibabaCloud.SDK.ROS.CDK.Vpc/AlibabaCloud/SDK/ROS/CDK/Vpc/IpsecServerProps.cs
5,293
C#
๏ปฟusing System; using System.Collections.Generic; #nullable disable namespace Start_App.Domain.Entities { public partial class JobCandidate { public int JobCandidateId { get; set; } public int? BusinessEntityId { get; set; } public string Resume { get; set; } public DateTime ModifiedDate { get; set; } public virtual Employee BusinessEntity { get; set; } } }
23
60
0.661836
[ "MIT" ]
JohnZhaoXiaoHu/Start-App
Start-App.Domain/Entities/AdventureWork2017/HumanResources/JobCandidate.cs
416
C#
๏ปฟusing Gwen.Net.Control; using static Gwen.Net.Platform.GwenPlatform; namespace Gwen.Net.CommonDialog { /// <summary> /// Dialog for selecting an existing directory. /// </summary> public class FolderBrowserDialog : FileDialog { public FolderBrowserDialog(ControlBase parent) : base(parent) {} protected override void OnCreated() { base.OnCreated(); FoldersOnly = true; Title = "Select Folder"; OkButtonText = "Select"; } protected override void OnItemSelected(string path) { if (DirectoryExists(path)) { SetCurrentItem(GetFileName(path)); } } protected override bool IsSubmittedNameOk(string path) { if (DirectoryExists(path)) { SetPath(path); return true; } return false; } protected override bool ValidateFileName(string path) { return DirectoryExists(path); } } }
23.145833
62
0.530153
[ "MIT" ]
pershingthesecond/Gwen.Net
Gwen.Net/CommonDialog/FolderBrowserDialog.cs
1,113
C#
๏ปฟusing CommunityToolkit.Maui.Behaviors; using Xunit; namespace CommunityToolkit.Maui.UnitTests.Behaviors; public class ImpliedOrderGridBehavior_Tests : BaseTest { [Fact] public void CorrectRowColumnAssignment() { var grid = new Grid(); grid.Behaviors.Add(new ImpliedOrderGridBehavior()); grid.RowDefinitions.Add(new RowDefinition()); grid.RowDefinitions.Add(new RowDefinition()); grid.RowDefinitions.Add(new RowDefinition()); grid.RowDefinitions.Add(new RowDefinition()); grid.RowDefinitions.Add(new RowDefinition()); grid.ColumnDefinitions.Add(new ColumnDefinition()); grid.ColumnDefinitions.Add(new ColumnDefinition()); grid.ColumnDefinitions.Add(new ColumnDefinition()); // R0C0 AssertExpectedCoordinates(grid, new Label(), 0, 0); // R0C1 AssertExpectedCoordinates(grid, new Label(), 0, 1); // R0C2 AssertExpectedCoordinates(grid, new Label(), 0, 2); // R1C0 var columnSpanLabel = new Label(); Grid.SetColumnSpan(columnSpanLabel, 2); AssertExpectedCoordinates(grid, columnSpanLabel, 1, 0); // R1C2 AssertExpectedCoordinates(grid, new Label(), 1, 2); // R2C0 var rowSpanLabel = new Label(); Grid.SetRowSpan(rowSpanLabel, 2); AssertExpectedCoordinates(grid, rowSpanLabel, 2, 0); // R2C1 AssertExpectedCoordinates(grid, new Label(), 2, 1); // R2C2 AssertExpectedCoordinates(grid, new Label(), 2, 2); // R3C1 AssertExpectedCoordinates(grid, new Label(), 3, 1); // R0C0 Manual Assignment var manualSetToUsedCellLabel = new Label(); Grid.SetRow(manualSetToUsedCellLabel, 0); Grid.SetColumn(manualSetToUsedCellLabel, 0); AssertExpectedCoordinates(grid, manualSetToUsedCellLabel, 0, 0); // R3C2 AssertExpectedCoordinates(grid, new Label(), 3, 2); // R4C1 var manualSetToCellLabel = new Label(); Grid.SetRow(manualSetToCellLabel, 4); Grid.SetColumn(manualSetToCellLabel, 1); AssertExpectedCoordinates(grid, manualSetToCellLabel, 4, 1); // R4C0 AssertExpectedCoordinates(grid, new Label(), 4, 0); } [Fact] public void ThrowsOnManualAssignmentToUsedCell() { var grid = CreateExceptionTestGrid(); // R0C0 grid.Children.Add(new Label()); // Manual R0C) var throwLabel = new Label(); Grid.SetColumn(throwLabel, 0); Grid.SetRow(throwLabel, 0); Assert.Throws<Exception>(() => grid.Children.Add(throwLabel)); } [Fact] public void ThrowsOnCellsExceeded() { var grid = CreateExceptionTestGrid(); // R0C0 grid.Children.Add(new Label()); // R0C1 grid.Children.Add(new Label()); // R1C0 grid.Children.Add(new Label()); // R1C1 grid.Children.Add(new Label()); // Throws Assert.Throws<Exception>(() => grid.Children.Add(new Label())); } [Fact] public void ThrowsOnSpanExceedsColumns() { var grid = CreateExceptionTestGrid(); var throwLabel = new Label(); Grid.SetColumnSpan(throwLabel, 10); Assert.Throws<Exception>(() => grid.Children.Add(throwLabel)); } [Fact] public void ThrowsOnSpanExceedsRows() { var grid = CreateExceptionTestGrid(); var throwLabel = new Label(); Grid.SetRowSpan(throwLabel, 10); Assert.Throws<Exception>(() => grid.Children.Add(throwLabel)); } Grid CreateExceptionTestGrid() { var grid = new Grid(); grid.Behaviors.Add(new ImpliedOrderGridBehavior { ThrowOnLayoutWarning = true }); grid.RowDefinitions.Add(new RowDefinition()); grid.RowDefinitions.Add(new RowDefinition()); grid.ColumnDefinitions.Add(new ColumnDefinition()); grid.ColumnDefinitions.Add(new ColumnDefinition()); return grid; } void AssertExpectedCoordinates(Grid grid, View view, int row, int column) { grid.Children.Add(view); Assert.Equal(row, Grid.GetRow(view)); Assert.Equal(column, Grid.GetColumn(view)); } }
24.267974
83
0.719634
[ "MIT" ]
ChaplinMarchais/Maui
src/CommunityToolkit.Maui.UnitTests/Behaviors/ImpliedOrderGridBehavior_Tests.cs
3,715
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using Sentry.Extensibility; using Sentry.Internal.ScopeStack; namespace Sentry.Internal { internal sealed class SentryScopeManager : IInternalScopeManager, IDisposable { // Internal for testing internal IScopeStackContainer ScopeStackContainer { get; } private readonly SentryOptions _options; internal KeyValuePair<Scope, ISentryClient>[] ScopeAndClientStack { get => ScopeStackContainer.Stack ??= NewStack(); set => ScopeStackContainer.Stack = value; } private Func<KeyValuePair<Scope, ISentryClient>[]> NewStack { get; } private bool IsGlobalMode => ScopeStackContainer is GlobalScopeStackContainer; public SentryScopeManager( IScopeStackContainer scopeStackContainer, SentryOptions options, ISentryClient rootClient) { ScopeStackContainer = scopeStackContainer; _options = options; NewStack = () => new [] { new KeyValuePair<Scope, ISentryClient>(new Scope(options), rootClient) }; } public KeyValuePair<Scope, ISentryClient> GetCurrent() { var current = ScopeAndClientStack; return current[current.Length - 1]; } public void ConfigureScope(Action<Scope>? configureScope) { _options.DiagnosticLogger?.LogDebug("Configuring the scope."); var scope = GetCurrent(); configureScope?.Invoke(scope.Key); } public Task ConfigureScopeAsync(Func<Scope, Task>? configureScope) { _options.DiagnosticLogger?.LogDebug("Configuring the scope asynchronously."); var scope = GetCurrent(); return configureScope?.Invoke(scope.Key) ?? Task.CompletedTask; } public IDisposable PushScope() => PushScope<object>(null); public IDisposable PushScope<TState>(TState? state) { if (IsGlobalMode) { _options.DiagnosticLogger?.LogWarning("Push scope called in global mode, returning."); return DisabledHub.Instance; } var currentScopeAndClientStack = ScopeAndClientStack; var scope = currentScopeAndClientStack[currentScopeAndClientStack.Length - 1]; if (scope.Key.Locked) { _options.DiagnosticLogger?.LogDebug("Locked scope. No new scope pushed."); // Apply to current scope if (state != null) { scope.Key.Apply(state); } return DisabledHub.Instance; } var clonedScope = scope.Key.Clone(); if (state != null) { clonedScope.Apply(state); } var scopeSnapshot = new ScopeSnapshot(_options, currentScopeAndClientStack, this); _options.DiagnosticLogger?.LogDebug("New scope pushed."); var newScopeAndClientStack = new KeyValuePair<Scope, ISentryClient>[currentScopeAndClientStack.Length + 1]; Array.Copy(currentScopeAndClientStack, newScopeAndClientStack, currentScopeAndClientStack.Length); newScopeAndClientStack[newScopeAndClientStack.Length - 1] = new KeyValuePair<Scope, ISentryClient>(clonedScope, scope.Value); ScopeAndClientStack = newScopeAndClientStack; return scopeSnapshot; } public void WithScope(Action<Scope> scopeCallback) { using (PushScope()) { var scope = GetCurrent(); scopeCallback.Invoke(scope.Key); } } public void BindClient(ISentryClient? client) { _options.DiagnosticLogger?.LogDebug("Binding a new client to the current scope."); var currentScopeAndClientStack = ScopeAndClientStack; var top = currentScopeAndClientStack[currentScopeAndClientStack.Length - 1]; var newScopeAndClientStack = new KeyValuePair<Scope, ISentryClient>[currentScopeAndClientStack.Length]; Array.Copy(currentScopeAndClientStack, newScopeAndClientStack, currentScopeAndClientStack.Length); newScopeAndClientStack[newScopeAndClientStack.Length - 1] = new KeyValuePair<Scope, ISentryClient>(top.Key, client ?? DisabledHub.Instance); ScopeAndClientStack = newScopeAndClientStack; } private sealed class ScopeSnapshot : IDisposable { private readonly SentryOptions _options; private readonly KeyValuePair<Scope, ISentryClient>[] _snapshot; private readonly SentryScopeManager _scopeManager; public ScopeSnapshot( SentryOptions options, KeyValuePair<Scope, ISentryClient>[] snapshot, SentryScopeManager scopeManager) { _options = options; _snapshot = snapshot; _scopeManager = scopeManager; } public void Dispose() { _options.DiagnosticLogger?.LogDebug("Disposing scope."); var previousScopeKey = _snapshot[_snapshot.Length - 1].Key; var currentScope = _scopeManager.ScopeAndClientStack; // Only reset the parent if this is still the current scope for (var i = currentScope.Length - 1; i >= 0; --i) { if (ReferenceEquals(currentScope[i].Key, previousScopeKey)) { _scopeManager.ScopeAndClientStack = _snapshot; break; } } } } public void Dispose() { _options.DiagnosticLogger?.LogDebug($"Disposing {nameof(SentryScopeManager)}."); ScopeStackContainer.Stack = null; } } }
36.768293
152
0.603483
[ "MIT" ]
paperview/sentry-dotnet
src/Sentry/Internal/SentryScopeManager.cs
6,030
C#
๏ปฟusing System; namespace yocto.tests.yetevenmorebad { public class AssemblyRegistration { public void Initialize(IContainer container) { } } }
15
52
0.633333
[ "Apache-2.0" ]
MILL5/yocto
src/yocto.tests.common/AssemblyRegistration/YetEvenMoreBadAssemblyRegistration.cs
182
C#
๏ปฟusing System.Collections; using System.Collections.Generic; using UnityEngine; using System; using UnityEngine.SceneManagement; public class StartGameController : MonoBehaviour { public void StartGame(int sceneIndex) { Time.timeScale = 1; DataCollector.Instance.SetLoadData(false); SceneManager.LoadScene(sceneIndex); } public void ContinueGame(int sceneIndex) { Time.timeScale = 1; if(DataCollector.Instance.SetLoadData(true)) SceneManager.LoadScene(sceneIndex); } public void QuitGame() { Application.Quit(); } }
21.964286
52
0.678049
[ "MIT" ]
kamitul/Breakout
Assets/Scripts/MainMenu/StartGameController.cs
617
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 elasticache-2015-02-02.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.ElastiCache.Model { /// <summary> /// Represents the output from the <i>AddTagsToResource</i>, <i>ListTagsOnResource</i>, /// and <i>RemoveTagsFromResource</i> actions. /// </summary> public partial class RemoveTagsFromResourceResponse : AmazonWebServiceResponse { private List<Tag> _tagList = new List<Tag>(); /// <summary> /// Gets and sets the property TagList. /// <para> /// A list of cost allocation tags as key-value pairs. /// </para> /// </summary> public List<Tag> TagList { get { return this._tagList; } set { this._tagList = value; } } // Check to see if TagList property is set internal bool IsSetTagList() { return this._tagList != null && this._tagList.Count > 0; } } }
30.877193
109
0.653409
[ "Apache-2.0" ]
jasoncwik/aws-sdk-net
sdk/src/Services/ElastiCache/Generated/Model/RemoveTagsFromResourceResponse.cs
1,760
C#
๏ปฟusing Blazorise.Modules; using Microsoft.JSInterop; namespace Blazorise.AntDesign.Modules { internal class AntDesignJSTooltipModule : JSTooltipModule { public AntDesignJSTooltipModule( IJSRuntime jsRuntime, IVersionProvider versionProvider ) : base( jsRuntime, versionProvider ) { } public override string ModuleFileName => $"./_content/Blazorise.AntDesign/tooltip.js?v={VersionProvider.Version}"; } }
28.8125
122
0.715835
[ "MIT" ]
OuticNZ/Blazorise
Source/Blazorise.AntDesign/Modules/AntDesignJSTooltipModule.cs
463
C#
๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Tasks { class Dirs { // Normal Directories: public static string firefoxDir; public static string chromeDir; public static string edgeDir; public static string discordDir; // Directories that point to the extension folder public static string firefoxExtDir; public static string chromeExtDir; public static string edgeExtDir; } }
23.608696
57
0.685083
[ "Apache-2.0" ]
hackinggames/Tasks
Tasks/Classes/Dirs.cs
545
C#
๏ปฟusing System; namespace YourBrand.Invoices.Application.Common.Models; public record ItemsResult<T>(IEnumerable<T> Items, int TotalItems);
28.8
67
0.791667
[ "MIT" ]
marinasundstrom/YourCompany
Finance/Invoices/Invoices/Application/Common/Models/ItemsResult.cs
146
C#
๏ปฟusing MediatR; namespace Scheduler.Application.Resources.Commands.EditResource { public class EditResourceCommand : IRequest { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public bool IsActive { get; set; } } }
24.076923
63
0.638978
[ "MIT" ]
knightpedro/scheduler
Scheduler.Application/Resources/Commands/EditResource/EditResourceCommand.cs
315
C#
using System; using System.Collections.Generic; using System.Linq; namespace LeetCode.Naive.Problems { /// <summary> /// Problem: https://leetcode.com/problems/strobogrammatic-number-ii/ /// Submission: https://leetcode.com/submissions/detail/450769856/ /// Facebook, Google /// </summary> internal class P0247 { public class Solution { public IList<string> FindStrobogrammatic(int n) { var arr = new char[n]; var mid = (n - 1) / 2; var ans = new List<string>(); Rec(ans, arr, 0, n, mid); return ans; } private void Rec(List<string> ans, char[] arr, int index, int len, int mid) { var ch = new char[] { '0', '1', '6', '8', '9' }; var st = new char[] { '0', '1', '9', '8', '6' }; for (var i = 0; i < ch.Length; i++) { arr[index] = ch[i]; arr[len - 1 - index] = st[i]; if (index != mid) { Rec(ans, arr, index + 1, len, mid); } else { if (arr[0] == '0' && len > 1) continue; if (index * 2 + 1 == len && (ch[i] == '6' || ch[i] == '9')) continue; ans.Add(new string(arr)); } } } } } }
23.754386
82
0.437962
[ "MIT" ]
viacheslave/algo
leetcode-subscription/c#/Problems/P0247.cs
1,354
C#
/* * Copyright 2008-2013 Mohawk College of Applied Arts and Technology * * 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. * * User: $user$ * Date: 01-09-2009 **/ using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization; using System.Xml; namespace MohawkCollege.EHR.HL7v3.MIF.MIF20.Vocabulary { /// <summary> /// A type of concept relationship supported by containing code system /// </summary> [XmlType(TypeName = "SupportedConceptRelationship", Namespace = "urn:hl7-org:v3/mif2")] public class SupportedConceptRelationship { /// <summary> /// Identifies the stereotypical behavior associated with the /// relationship /// </summary> [XmlAttribute("relationshipKind")] public ConceptRelationshipKind RelationshipKind { get; set; } /// <summary> /// The label for the specific type of concept relationship supported by the code /// system /// </summary> [XmlAttribute("name")] public string Name { get; set; } /// <summary> /// Identifies the name of the relationship. Allows linking a relationship and its derived inverse /// </summary> [XmlAttribute("inverseName")] public string InverseName { get; set; } /// <summary> /// A unique identifier within the code system for this particular relationship type /// </summary> [XmlAttribute("id")] public string Id { get; set; } /// <summary> /// Indicates whether the relationship is intended to be navigated /// when selecting a code /// </summary> [XmlAttribute("isNavigable")] public bool IsNavigable { get; set; } /// <summary> /// Indicates whether codes are limited to only one out going relationship, /// only one incoming relationship or both /// </summary> [XmlAttribute("functionalism")] public bool Functionalism { get; set; } /// <summary> /// Indicates if the associate always holds for a concept within itself /// </summary> [XmlAttribute("reflexivity")] public string Reflexivity { get; set; } /// <summary> /// Inidcates if the relationship always holds in the reverse direction as well. /// </summary> [XmlAttribute("symmetry")] public string Symmetry { get; set; } /// <summary> /// Indicates whether the relationship always propagates or never propagates. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Transivity"), XmlAttribute("transivity")] public string Transivity { get; set; } /// <summary> /// Describes how the relationship is intended to be used and what its for /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays"), XmlElement("description")] public XmlNode[] Description { get; set; } /// <summary> /// If present, indicates that only codes within the defined value set are allowed /// to be the source of this type of relationship /// </summary> [XmlElement("allowedForSources")] public ContentDefinition AllowedForSources { get; set; } /// <summary> /// If present, indicates that only codes within the defined value set are allowed /// to be the target of this type of relationship /// </summary> [XmlElement("allowedForTargets")] public ContentDefinition AllowedForTargets { get; set; } /// <summary> /// If present, indicates that only codes within the defined value set are allowed /// to be the target of this type of relationship /// </summary> [XmlElement("requiredForSources")] public ContentDefinition RequiredForSources { get; set; } /// <summary> /// If present, indicates that only codes within the defined value set are allowed /// to be the target of this type of relationship /// </summary> [XmlElement("requiredForTargets")] public ContentDefinition RequiredForTargets { get; set; } /// <summary> /// No documentation available /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists"), XmlElement("supportedProperty")] public List<SupportedProperty> SupportedProperty { get; set; } /// <summary> /// Identifies the concept within the vocabulary that is considered to define this particular relationship /// </summary> [XmlElement("definingConcept")] public ConceptRef DefiningConcept { get; set; } } }
45.418033
259
0.649341
[ "Apache-2.0" ]
avjabalpur/ccd-generator
gpmr/MohawkCollege.EHR.HL7v3.MIF.MIF20/Vocabulary/SupportedConceptRelationship.cs
5,541
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("6.2.4.zbirka.znamenke")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("6.2.4.zbirka.znamenke")] [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("62e843a4-d233-4ae1-9546-244e8f1adf9f")] // 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.108108
84
0.74539
[ "MIT" ]
robertlucic66/AlgebraCSharp2019-1
ConsoleApp1/6.2.4.zbirka.znamenke/Properties/AssemblyInfo.cs
1,413
C#
๏ปฟusing System.Collections.Generic; namespace SFA.DAS.RoatpOversight.Domain { public static class OversightReviewStatuses { public static IReadOnlyList<OversightReviewStatus> SuccessfulStatuses { get; } = new List<OversightReviewStatus> { OversightReviewStatus.SuccessfulAlreadyActive, OversightReviewStatus.Successful, OversightReviewStatus.SuccessfulFitnessForFunding }; } }
29.933333
120
0.717149
[ "MIT" ]
SkillsFundingAgency/das-roatp-oversight
src/SFA.DAS.RoatpOversight.Domain/OversightReviewStatuses.cs
451
C#
๏ปฟ/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * Sweep-line, Constrained Delauney Triangulation (CDT) See: Domiter, V. and * Zalik, B.(2008)'Sweep-line algorithm for constrained Delaunay triangulation', * International Journal of Geographical Information Science * * "FlipScan" Constrained Edge Algorithm invented by author of this code. * * Author: Thomas ร…hlรฉn, thahlen@gmail.com */ // Changes from the Java version // Turned DTSweep into a static class // Lots of deindentation via early bailout // Future possibilities // Comments! using System; using System.Collections.Generic; using System.Diagnostics; namespace FarseerPhysics.Common.Decomposition.CDT.Delaunay.Sweep { internal static class DTSweep { private const double PI_div2 = Math.PI / 2; private const double PI_3div4 = 3 * Math.PI / 4; /// <summary> /// Triangulate simple polygon with holes /// </summary> public static void Triangulate(DTSweepContext tcx) { tcx.CreateAdvancingFront(); Sweep(tcx); // Finalize triangulation if (tcx.TriangulationMode == TriangulationMode.Polygon) { FinalizationPolygon(tcx); } else { FinalizationConvexHull(tcx); } tcx.Done(); } /// <summary> /// Start sweeping the Y-sorted point set from bottom to top /// </summary> private static void Sweep(DTSweepContext tcx) { List<TriangulationPoint> points = tcx.Points; for (int i = 1; i < points.Count; i++) { TriangulationPoint point = points[i]; AdvancingFrontNode node = PointEvent(tcx, point); if (point.HasEdges) { foreach (DTSweepConstraint e in point.Edges) { EdgeEvent(tcx, e, node); } } tcx.Update(null); } } /// <summary> /// If this is a Delaunay Triangulation of a pointset we need to fill so the triangle mesh gets a ConvexHull /// </summary> private static void FinalizationConvexHull(DTSweepContext tcx) { DelaunayTriangle t1, t2; AdvancingFrontNode n1 = tcx.aFront.Head.Next; AdvancingFrontNode n2 = n1.Next; TurnAdvancingFrontConvex(tcx, n1, n2); // TODO: implement ConvexHull for lower right and left boundary // Lets remove triangles connected to the two "algorithm" points // XXX: When the first the nodes are points in a triangle we need to do a flip before // removing triangles or we will lose a valid triangle. // Same for last three nodes! // !!! If I implement ConvexHull for lower right and left boundary this fix should not be // needed and the removed triangles will be added again by default n1 = tcx.aFront.Tail.Prev; if (n1.Triangle.Contains(n1.Next.Point) && n1.Triangle.Contains(n1.Prev.Point)) { t1 = n1.Triangle.NeighborAcross(n1.Point); RotateTrianglePair(n1.Triangle, n1.Point, t1, t1.OppositePoint(n1.Triangle, n1.Point)); tcx.MapTriangleToNodes(n1.Triangle); tcx.MapTriangleToNodes(t1); } n1 = tcx.aFront.Head.Next; if (n1.Triangle.Contains(n1.Prev.Point) && n1.Triangle.Contains(n1.Next.Point)) { t1 = n1.Triangle.NeighborAcross(n1.Point); RotateTrianglePair(n1.Triangle, n1.Point, t1, t1.OppositePoint(n1.Triangle, n1.Point)); tcx.MapTriangleToNodes(n1.Triangle); tcx.MapTriangleToNodes(t1); } // Lower right boundary TriangulationPoint first = tcx.aFront.Head.Point; n2 = tcx.aFront.Tail.Prev; t1 = n2.Triangle; TriangulationPoint p1 = n2.Point; n2.Triangle = null; do { tcx.RemoveFromList(t1); p1 = t1.PointCCW(p1); if (p1 == first) break; t2 = t1.NeighborCCW(p1); t1.Clear(); t1 = t2; } while (true); // Lower left boundary first = tcx.aFront.Head.Next.Point; p1 = t1.PointCW(tcx.aFront.Head.Point); t2 = t1.NeighborCW(tcx.aFront.Head.Point); t1.Clear(); t1 = t2; while (p1 != first) //TODO: Port note. This was do while before. { tcx.RemoveFromList(t1); p1 = t1.PointCCW(p1); t2 = t1.NeighborCCW(p1); t1.Clear(); t1 = t2; } // Remove current head and tail node now that we have removed all triangles attached // to them. Then set new head and tail node points tcx.aFront.Head = tcx.aFront.Head.Next; tcx.aFront.Head.Prev = null; tcx.aFront.Tail = tcx.aFront.Tail.Prev; tcx.aFront.Tail.Next = null; tcx.FinalizeTriangulation(); } /// <summary> /// We will traverse the entire advancing front and fill it to form a convex hull. /// </summary> private static void TurnAdvancingFrontConvex(DTSweepContext tcx, AdvancingFrontNode b, AdvancingFrontNode c) { AdvancingFrontNode first = b; while (c != tcx.aFront.Tail) { if (TriangulationUtil.Orient2d(b.Point, c.Point, c.Next.Point) == Orientation.CCW) { // [b,c,d] Concave - fill around c Fill(tcx, c); c = c.Next; } else { // [b,c,d] Convex if (b != first && TriangulationUtil.Orient2d(b.Prev.Point, b.Point, c.Point) == Orientation.CCW) { // [a,b,c] Concave - fill around b Fill(tcx, b); b = b.Prev; } else { // [a,b,c] Convex - nothing to fill b = c; c = c.Next; } } } } private static void FinalizationPolygon(DTSweepContext tcx) { // Get an Internal triangle to start with DelaunayTriangle t = tcx.aFront.Head.Next.Triangle; TriangulationPoint p = tcx.aFront.Head.Next.Point; while (!t.GetConstrainedEdgeCW(p)) { t = t.NeighborCCW(p); } // Collect interior triangles constrained by edges tcx.MeshClean(t); } /// <summary> /// Find closes node to the left of the new point and /// create a new triangle. If needed new holes and basins /// will be filled to. /// </summary> private static AdvancingFrontNode PointEvent(DTSweepContext tcx, TriangulationPoint point) { AdvancingFrontNode node = tcx.LocateNode(point); AdvancingFrontNode newNode = NewFrontTriangle(tcx, point, node); // Only need to check +epsilon since point never have smaller // x value than node due to how we fetch nodes from the front if (point.X <= node.Point.X + TriangulationUtil.EPSILON) { Fill(tcx, node); } tcx.AddNode(newNode); FillAdvancingFront(tcx, newNode); return newNode; } /// <summary> /// Creates a new front triangle and legalize it /// </summary> private static AdvancingFrontNode NewFrontTriangle(DTSweepContext tcx, TriangulationPoint point, AdvancingFrontNode node) { DelaunayTriangle triangle = new DelaunayTriangle(point, node.Point, node.Next.Point); triangle.MarkNeighbor(node.Triangle); tcx.Triangles.Add(triangle); AdvancingFrontNode newNode = new AdvancingFrontNode(point); newNode.Next = node.Next; newNode.Prev = node; node.Next.Prev = newNode; node.Next = newNode; tcx.AddNode(newNode); // XXX: BST if (!Legalize(tcx, triangle)) { tcx.MapTriangleToNodes(triangle); } return newNode; } private static void EdgeEvent(DTSweepContext tcx, DTSweepConstraint edge, AdvancingFrontNode node) { try { tcx.EdgeEvent.ConstrainedEdge = edge; tcx.EdgeEvent.Right = edge.P.X > edge.Q.X; if (IsEdgeSideOfTriangle(node.Triangle, edge.P, edge.Q)) { return; } // For now we will do all needed filling // TODO: integrate with flip process might give some better performance // but for now this avoid the issue with cases that needs both flips and fills FillEdgeEvent(tcx, edge, node); EdgeEvent(tcx, edge.P, edge.Q, node.Triangle, edge.Q); } catch (PointOnEdgeException e) { Debug.WriteLine("Skipping Edge: {0}", e.Message); } } private static void FillEdgeEvent(DTSweepContext tcx, DTSweepConstraint edge, AdvancingFrontNode node) { if (tcx.EdgeEvent.Right) { FillRightAboveEdgeEvent(tcx, edge, node); } else { FillLeftAboveEdgeEvent(tcx, edge, node); } } private static void FillRightConcaveEdgeEvent(DTSweepContext tcx, DTSweepConstraint edge, AdvancingFrontNode node) { Fill(tcx, node.Next); if (node.Next.Point != edge.P) { // Next above or below edge? if (TriangulationUtil.Orient2d(edge.Q, node.Next.Point, edge.P) == Orientation.CCW) { // Below if (TriangulationUtil.Orient2d(node.Point, node.Next.Point, node.Next.Next.Point) == Orientation.CCW) { // Next is concave FillRightConcaveEdgeEvent(tcx, edge, node); } else { // Next is convex } } } } private static void FillRightConvexEdgeEvent(DTSweepContext tcx, DTSweepConstraint edge, AdvancingFrontNode node) { // Next concave or convex? if (TriangulationUtil.Orient2d(node.Next.Point, node.Next.Next.Point, node.Next.Next.Next.Point) == Orientation.CCW) { // Concave FillRightConcaveEdgeEvent(tcx, edge, node.Next); } else { // Convex // Next above or below edge? if (TriangulationUtil.Orient2d(edge.Q, node.Next.Next.Point, edge.P) == Orientation.CCW) { // Below FillRightConvexEdgeEvent(tcx, edge, node.Next); } else { // Above } } } private static void FillRightBelowEdgeEvent(DTSweepContext tcx, DTSweepConstraint edge, AdvancingFrontNode node) { if (node.Point.X < edge.P.X) // needed? { if (TriangulationUtil.Orient2d(node.Point, node.Next.Point, node.Next.Next.Point) == Orientation.CCW) { // Concave FillRightConcaveEdgeEvent(tcx, edge, node); } else { // Convex FillRightConvexEdgeEvent(tcx, edge, node); // Retry this one FillRightBelowEdgeEvent(tcx, edge, node); } } } private static void FillRightAboveEdgeEvent(DTSweepContext tcx, DTSweepConstraint edge, AdvancingFrontNode node) { while (node.Next.Point.X < edge.P.X) { // Check if next node is below the edge Orientation o1 = TriangulationUtil.Orient2d(edge.Q, node.Next.Point, edge.P); if (o1 == Orientation.CCW) { FillRightBelowEdgeEvent(tcx, edge, node); } else { node = node.Next; } } } private static void FillLeftConvexEdgeEvent(DTSweepContext tcx, DTSweepConstraint edge, AdvancingFrontNode node) { // Next concave or convex? if (TriangulationUtil.Orient2d(node.Prev.Point, node.Prev.Prev.Point, node.Prev.Prev.Prev.Point) == Orientation.CW) { // Concave FillLeftConcaveEdgeEvent(tcx, edge, node.Prev); } else { // Convex // Next above or below edge? if (TriangulationUtil.Orient2d(edge.Q, node.Prev.Prev.Point, edge.P) == Orientation.CW) { // Below FillLeftConvexEdgeEvent(tcx, edge, node.Prev); } else { // Above } } } private static void FillLeftConcaveEdgeEvent(DTSweepContext tcx, DTSweepConstraint edge, AdvancingFrontNode node) { Fill(tcx, node.Prev); if (node.Prev.Point != edge.P) { // Next above or below edge? if (TriangulationUtil.Orient2d(edge.Q, node.Prev.Point, edge.P) == Orientation.CW) { // Below if (TriangulationUtil.Orient2d(node.Point, node.Prev.Point, node.Prev.Prev.Point) == Orientation.CW) { // Next is concave FillLeftConcaveEdgeEvent(tcx, edge, node); } else { // Next is convex } } } } private static void FillLeftBelowEdgeEvent(DTSweepContext tcx, DTSweepConstraint edge, AdvancingFrontNode node) { if (node.Point.X > edge.P.X) { if (TriangulationUtil.Orient2d(node.Point, node.Prev.Point, node.Prev.Prev.Point) == Orientation.CW) { // Concave FillLeftConcaveEdgeEvent(tcx, edge, node); } else { // Convex FillLeftConvexEdgeEvent(tcx, edge, node); // Retry this one FillLeftBelowEdgeEvent(tcx, edge, node); } } } private static void FillLeftAboveEdgeEvent(DTSweepContext tcx, DTSweepConstraint edge, AdvancingFrontNode node) { while (node.Prev.Point.X > edge.P.X) { // Check if next node is below the edge Orientation o1 = TriangulationUtil.Orient2d(edge.Q, node.Prev.Point, edge.P); if (o1 == Orientation.CW) { FillLeftBelowEdgeEvent(tcx, edge, node); } else { node = node.Prev; } } } private static bool IsEdgeSideOfTriangle(DelaunayTriangle triangle, TriangulationPoint ep, TriangulationPoint eq) { int index = triangle.EdgeIndex(ep, eq); if (index != -1) { triangle.MarkConstrainedEdge(index); triangle = triangle.Neighbors[index]; if (triangle != null) { triangle.MarkConstrainedEdge(ep, eq); } return true; } return false; } private static void EdgeEvent(DTSweepContext tcx, TriangulationPoint ep, TriangulationPoint eq, DelaunayTriangle triangle, TriangulationPoint point) { if (IsEdgeSideOfTriangle(triangle, ep, eq)) return; TriangulationPoint p1 = triangle.PointCCW(point); Orientation o1 = TriangulationUtil.Orient2d(eq, p1, ep); if (o1 == Orientation.Collinear) { if (triangle.Contains(eq, p1)) { triangle.MarkConstrainedEdge(eq, p1); // We are modifying the constraint maybe it would be better to // not change the given constraint and just keep a variable for the new constraint tcx.EdgeEvent.ConstrainedEdge.Q = p1; triangle = triangle.NeighborAcross(point); EdgeEvent(tcx, ep, p1, triangle, p1); } else { throw new PointOnEdgeException("EdgeEvent - Point on constrained edge not supported yet"); } if (tcx.IsDebugEnabled) { Debug.WriteLine("EdgeEvent - Point on constrained edge"); } return; } TriangulationPoint p2 = triangle.PointCW(point); Orientation o2 = TriangulationUtil.Orient2d(eq, p2, ep); if (o2 == Orientation.Collinear) { if (triangle.Contains(eq, p2)) { triangle.MarkConstrainedEdge(eq, p2); // We are modifying the constraint maybe it would be better to // not change the given constraint and just keep a variable for the new constraint tcx.EdgeEvent.ConstrainedEdge.Q = p2; triangle = triangle.NeighborAcross(point); EdgeEvent(tcx, ep, p2, triangle, p2); } else { throw new PointOnEdgeException("EdgeEvent - Point on constrained edge not supported yet"); } if (tcx.IsDebugEnabled) { Debug.WriteLine("EdgeEvent - Point on constrained edge"); } return; } if (o1 == o2) { // Need to decide if we are rotating CW or CCW to get to a triangle // that will cross edge if (o1 == Orientation.CW) { triangle = triangle.NeighborCCW(point); } else { triangle = triangle.NeighborCW(point); } EdgeEvent(tcx, ep, eq, triangle, point); } else { // This triangle crosses constraint so lets flippin start! FlipEdgeEvent(tcx, ep, eq, triangle, point); } } private static void FlipEdgeEvent(DTSweepContext tcx, TriangulationPoint ep, TriangulationPoint eq, DelaunayTriangle t, TriangulationPoint p) { DelaunayTriangle ot = t.NeighborAcross(p); TriangulationPoint op = ot.OppositePoint(t, p); if (ot == null) { // If we want to integrate the fillEdgeEvent do it here // With current implementation we should never get here throw new InvalidOperationException("[BUG:FIXME] FLIP failed due to missing triangle"); } if (t.GetConstrainedEdgeAcross(p)) { throw new Exception("Intersecting Constraints"); } bool inScanArea = TriangulationUtil.InScanArea(p, t.PointCCW(p), t.PointCW(p), op); if (inScanArea) { // Lets rotate shared edge one vertex CW RotateTrianglePair(t, p, ot, op); tcx.MapTriangleToNodes(t); tcx.MapTriangleToNodes(ot); if (p == eq && op == ep) { if (eq == tcx.EdgeEvent.ConstrainedEdge.Q && ep == tcx.EdgeEvent.ConstrainedEdge.P) { //if (tcx.IsDebugEnabled) Console.WriteLine("[FLIP] - constrained edge done"); // TODO: remove t.MarkConstrainedEdge(ep, eq); ot.MarkConstrainedEdge(ep, eq); Legalize(tcx, t); Legalize(tcx, ot); } else { //if (tcx.IsDebugEnabled) Console.WriteLine("[FLIP] - subedge done"); // TODO: remove // XXX: I think one of the triangles should be legalized here? } } else { //if (tcx.IsDebugEnabled) // Console.WriteLine("[FLIP] - flipping and continuing with triangle still crossing edge"); // TODO: remove Orientation o = TriangulationUtil.Orient2d(eq, op, ep); t = NextFlipTriangle(tcx, o, t, ot, p, op); FlipEdgeEvent(tcx, ep, eq, t, p); } } else { TriangulationPoint newP = NextFlipPoint(ep, eq, ot, op); FlipScanEdgeEvent(tcx, ep, eq, t, ot, newP); EdgeEvent(tcx, ep, eq, t, p); } } /// <summary> /// When we need to traverse from one triangle to the next we need /// the point in current triangle that is the opposite point to the next /// triangle. /// </summary> private static TriangulationPoint NextFlipPoint(TriangulationPoint ep, TriangulationPoint eq, DelaunayTriangle ot, TriangulationPoint op) { Orientation o2d = TriangulationUtil.Orient2d(eq, op, ep); if (o2d == Orientation.CW) { // Right return ot.PointCCW(op); } else if (o2d == Orientation.CCW) { // Left return ot.PointCW(op); } else { // TODO: implement support for point on constraint edge throw new PointOnEdgeException("Point on constrained edge not supported yet"); } } /// <summary> /// After a flip we have two triangles and know that only one will still be /// intersecting the edge. So decide which to contiune with and legalize the other /// </summary> /// <param name="tcx"></param> /// <param name="o">should be the result of an TriangulationUtil.orient2d( eq, op, ep )</param> /// <param name="t">triangle 1</param> /// <param name="ot">triangle 2</param> /// <param name="p">a point shared by both triangles</param> /// <param name="op">another point shared by both triangles</param> /// <returns>returns the triangle still intersecting the edge</returns> private static DelaunayTriangle NextFlipTriangle(DTSweepContext tcx, Orientation o, DelaunayTriangle t, DelaunayTriangle ot, TriangulationPoint p, TriangulationPoint op) { int edgeIndex; if (o == Orientation.CCW) { // ot is not crossing edge after flip edgeIndex = ot.EdgeIndex(p, op); ot.EdgeIsDelaunay[edgeIndex] = true; Legalize(tcx, ot); ot.EdgeIsDelaunay.Clear(); return t; } // t is not crossing edge after flip edgeIndex = t.EdgeIndex(p, op); t.EdgeIsDelaunay[edgeIndex] = true; Legalize(tcx, t); t.EdgeIsDelaunay.Clear(); return ot; } /// <summary> /// Scan part of the FlipScan algorithm<br> /// When a triangle pair isn't flippable we will scan for the next /// point that is inside the flip triangle scan area. When found /// we generate a new flipEdgeEvent /// </summary> /// <param name="tcx"></param> /// <param name="ep">last point on the edge we are traversing</param> /// <param name="eq">first point on the edge we are traversing</param> /// <param name="flipTriangle">the current triangle sharing the point eq with edge</param> /// <param name="t"></param> /// <param name="p"></param> private static void FlipScanEdgeEvent(DTSweepContext tcx, TriangulationPoint ep, TriangulationPoint eq, DelaunayTriangle flipTriangle, DelaunayTriangle t, TriangulationPoint p) { DelaunayTriangle ot = t.NeighborAcross(p); TriangulationPoint op = ot.OppositePoint(t, p); if (ot == null) { // If we want to integrate the fillEdgeEvent do it here // With current implementation we should never get here throw new Exception("[BUG:FIXME] FLIP failed due to missing triangle"); } bool inScanArea = TriangulationUtil.InScanArea(eq, flipTriangle.PointCCW(eq), flipTriangle.PointCW(eq), op); if (inScanArea) { // flip with new edge op->eq FlipEdgeEvent(tcx, eq, op, ot, op); // TODO: Actually I just figured out that it should be possible to // improve this by getting the next ot and op before the the above // flip and continue the flipScanEdgeEvent here // set new ot and op here and loop back to inScanArea test // also need to set a new flipTriangle first // Turns out at first glance that this is somewhat complicated // so it will have to wait. } else { TriangulationPoint newP = NextFlipPoint(ep, eq, ot, op); FlipScanEdgeEvent(tcx, ep, eq, flipTriangle, ot, newP); } } /// <summary> /// Fills holes in the Advancing Front /// </summary> private static void FillAdvancingFront(DTSweepContext tcx, AdvancingFrontNode n) { double angle; // Fill right holes AdvancingFrontNode node = n.Next; while (node.HasNext) { // if HoleAngle exceeds 90 degrees then break. if (LargeHole_DontFill(node)) break; Fill(tcx, node); node = node.Next; } // Fill left holes node = n.Prev; while (node.HasPrev) { // if HoleAngle exceeds 90 degrees then break. if (LargeHole_DontFill(node)) break; angle = HoleAngle(node); if (angle > PI_div2 || angle < -PI_div2) { break; } Fill(tcx, node); node = node.Prev; } // Fill right basins if (n.HasNext && n.Next.HasNext) { angle = BasinAngle(n); if (angle < PI_3div4) { FillBasin(tcx, n); } } } // True if HoleAngle exceeds 90 degrees. private static bool LargeHole_DontFill(AdvancingFrontNode node) { AdvancingFrontNode nextNode = node.Next; AdvancingFrontNode prevNode = node.Prev; if (!AngleExceeds90Degrees(node.Point, nextNode.Point, prevNode.Point)) return false; // Check additional points on front. AdvancingFrontNode next2Node = nextNode.Next; // "..Plus.." because only want angles on same side as point being added. if ((next2Node != null) && !AngleExceedsPlus90DegreesOrIsNegative(node.Point, next2Node.Point, prevNode.Point)) return false; AdvancingFrontNode prev2Node = prevNode.Prev; // "..Plus.." because only want angles on same side as point being added. if ((prev2Node != null) && !AngleExceedsPlus90DegreesOrIsNegative(node.Point, nextNode.Point, prev2Node.Point)) return false; return true; } private static bool AngleExceeds90Degrees(TriangulationPoint origin, TriangulationPoint pa, TriangulationPoint pb) { double angle = Angle(origin, pa, pb); bool exceeds90Degrees = ((angle > PI_div2) || (angle < -PI_div2)); return exceeds90Degrees; } private static bool AngleExceedsPlus90DegreesOrIsNegative(TriangulationPoint origin, TriangulationPoint pa, TriangulationPoint pb) { double angle = Angle(origin, pa, pb); bool exceedsPlus90DegreesOrIsNegative = (angle > PI_div2) || (angle < 0); return exceedsPlus90DegreesOrIsNegative; } private static double Angle(TriangulationPoint origin, TriangulationPoint pa, TriangulationPoint pb) { /* Complex plane * ab = cosA +i*sinA * ab = (ax + ay*i)(bx + by*i) = (ax*bx + ay*by) + i(ax*by-ay*bx) * atan2(y,x) computes the principal value of the argument function * applied to the complex number x+iy * Where x = ax*bx + ay*by * y = ax*by - ay*bx */ double px = origin.X; double py = origin.Y; double ax = pa.X - px; double ay = pa.Y - py; double bx = pb.X - px; double by = pb.Y - py; double x = ax * by - ay * bx; double y = ax * bx + ay * by; double angle = Math.Atan2(x, y); return angle; } /// <summary> /// Fills a basin that has formed on the Advancing Front to the right /// of given node. /// First we decide a left,bottom and right node that forms the /// boundaries of the basin. Then we do a reqursive fill. /// </summary> /// <param name="tcx"></param> /// <param name="node">starting node, this or next node will be left node</param> private static void FillBasin(DTSweepContext tcx, AdvancingFrontNode node) { if (TriangulationUtil.Orient2d(node.Point, node.Next.Point, node.Next.Next.Point) == Orientation.CCW) { // tcx.basin.leftNode = node.next.next; tcx.Basin.leftNode = node; } else { tcx.Basin.leftNode = node.Next; } // Find the bottom and right node tcx.Basin.bottomNode = tcx.Basin.leftNode; while (tcx.Basin.bottomNode.HasNext && tcx.Basin.bottomNode.Point.Y >= tcx.Basin.bottomNode.Next.Point.Y) { tcx.Basin.bottomNode = tcx.Basin.bottomNode.Next; } if (tcx.Basin.bottomNode == tcx.Basin.leftNode) { // No valid basins return; } tcx.Basin.rightNode = tcx.Basin.bottomNode; while (tcx.Basin.rightNode.HasNext && tcx.Basin.rightNode.Point.Y < tcx.Basin.rightNode.Next.Point.Y) { tcx.Basin.rightNode = tcx.Basin.rightNode.Next; } if (tcx.Basin.rightNode == tcx.Basin.bottomNode) { // No valid basins return; } tcx.Basin.width = tcx.Basin.rightNode.Point.X - tcx.Basin.leftNode.Point.X; tcx.Basin.leftHighest = tcx.Basin.leftNode.Point.Y > tcx.Basin.rightNode.Point.Y; FillBasinReq(tcx, tcx.Basin.bottomNode); } /// <summary> /// Recursive algorithm to fill a Basin with triangles /// </summary> private static void FillBasinReq(DTSweepContext tcx, AdvancingFrontNode node) { // if shallow stop filling if (IsShallow(tcx, node)) { return; } Fill(tcx, node); if (node.Prev == tcx.Basin.leftNode && node.Next == tcx.Basin.rightNode) { return; } else if (node.Prev == tcx.Basin.leftNode) { Orientation o = TriangulationUtil.Orient2d(node.Point, node.Next.Point, node.Next.Next.Point); if (o == Orientation.CW) { return; } node = node.Next; } else if (node.Next == tcx.Basin.rightNode) { Orientation o = TriangulationUtil.Orient2d(node.Point, node.Prev.Point, node.Prev.Prev.Point); if (o == Orientation.CCW) { return; } node = node.Prev; } else { // Continue with the neighbor node with lowest Y value if (node.Prev.Point.Y < node.Next.Point.Y) { node = node.Prev; } else { node = node.Next; } } FillBasinReq(tcx, node); } private static bool IsShallow(DTSweepContext tcx, AdvancingFrontNode node) { double height; if (tcx.Basin.leftHighest) { height = tcx.Basin.leftNode.Point.Y - node.Point.Y; } else { height = tcx.Basin.rightNode.Point.Y - node.Point.Y; } if (tcx.Basin.width > height) { return true; } return false; } /// <summary> /// ??? /// </summary> /// <param name="node">middle node</param> /// <returns>the angle between 3 front nodes</returns> private static double HoleAngle(AdvancingFrontNode node) { // XXX: do we really need a signed angle for holeAngle? // could possible save some cycles here /* Complex plane * ab = cosA +i*sinA * ab = (ax + ay*i)(bx + by*i) = (ax*bx + ay*by) + i(ax*by-ay*bx) * atan2(y,x) computes the principal value of the argument function * applied to the complex number x+iy * Where x = ax*bx + ay*by * y = ax*by - ay*bx */ double px = node.Point.X; double py = node.Point.Y; double ax = node.Next.Point.X - px; double ay = node.Next.Point.Y - py; double bx = node.Prev.Point.X - px; double by = node.Prev.Point.Y - py; return Math.Atan2(ax * by - ay * bx, ax * bx + ay * by); } /// <summary> /// The basin angle is decided against the horizontal line [1,0] /// </summary> private static double BasinAngle(AdvancingFrontNode node) { double ax = node.Point.X - node.Next.Next.Point.X; double ay = node.Point.Y - node.Next.Next.Point.Y; return Math.Atan2(ay, ax); } /// <summary> /// Adds a triangle to the advancing front to fill a hole. /// </summary> /// <param name="tcx"></param> /// <param name="node">middle node, that is the bottom of the hole</param> private static void Fill(DTSweepContext tcx, AdvancingFrontNode node) { DelaunayTriangle triangle = new DelaunayTriangle(node.Prev.Point, node.Point, node.Next.Point); // TODO: should copy the cEdge value from neighbor triangles // for now cEdge values are copied during the legalize triangle.MarkNeighbor(node.Prev.Triangle); triangle.MarkNeighbor(node.Triangle); tcx.Triangles.Add(triangle); // Update the advancing front node.Prev.Next = node.Next; node.Next.Prev = node.Prev; tcx.RemoveNode(node); // If it was legalized the triangle has already been mapped if (!Legalize(tcx, triangle)) { tcx.MapTriangleToNodes(triangle); } } /// <summary> /// Returns true if triangle was legalized /// </summary> private static bool Legalize(DTSweepContext tcx, DelaunayTriangle t) { // To legalize a triangle we start by finding if any of the three edges // violate the Delaunay condition for (int i = 0; i < 3; i++) { // TODO: fix so that cEdge is always valid when creating new triangles then we can check it here // instead of below with ot if (t.EdgeIsDelaunay[i]) { continue; } DelaunayTriangle ot = t.Neighbors[i]; if (ot != null) { TriangulationPoint p = t.Points[i]; TriangulationPoint op = ot.OppositePoint(t, p); int oi = ot.IndexOf(op); // If this is a Constrained Edge or a Delaunay Edge(only during recursive legalization) // then we should not try to legalize if (ot.EdgeIsConstrained[oi] || ot.EdgeIsDelaunay[oi]) { t.EdgeIsConstrained[i] = ot.EdgeIsConstrained[oi]; // XXX: have no good way of setting this property when creating new triangles so lets set it here continue; } bool inside = TriangulationUtil.SmartIncircle(p, t.PointCCW(p), t.PointCW(p), op); if (inside) { // Lets mark this shared edge as Delaunay t.EdgeIsDelaunay[i] = true; ot.EdgeIsDelaunay[oi] = true; // Lets rotate shared edge one vertex CW to legalize it RotateTrianglePair(t, p, ot, op); // We now got one valid Delaunay Edge shared by two triangles // This gives us 4 new edges to check for Delaunay // Make sure that triangle to node mapping is done only one time for a specific triangle bool notLegalized = !Legalize(tcx, t); if (notLegalized) { tcx.MapTriangleToNodes(t); } notLegalized = !Legalize(tcx, ot); if (notLegalized) { tcx.MapTriangleToNodes(ot); } // Reset the Delaunay edges, since they only are valid Delaunay edges // until we add a new triangle or point. // XXX: need to think about this. Can these edges be tried after we // return to previous recursive level? t.EdgeIsDelaunay[i] = false; ot.EdgeIsDelaunay[oi] = false; // If triangle have been legalized no need to check the other edges since // the recursive legalization will handles those so we can end here. return true; } } } return false; } /// <summary> /// Rotates a triangle pair one vertex CW /// n2 n2 /// P +-----+ P +-----+ /// | t /| |\ t | /// | / | | \ | /// n1| / |n3 n1| \ |n3 /// | / | after CW | \ | /// |/ oT | | oT \| /// +-----+ oP +-----+ /// n4 n4 /// </summary> private static void RotateTrianglePair(DelaunayTriangle t, TriangulationPoint p, DelaunayTriangle ot, TriangulationPoint op) { DelaunayTriangle n1 = t.NeighborCCW(p); DelaunayTriangle n2 = t.NeighborCW(p); DelaunayTriangle n3 = ot.NeighborCCW(op); DelaunayTriangle n4 = ot.NeighborCW(op); bool ce1 = t.GetConstrainedEdgeCCW(p); bool ce2 = t.GetConstrainedEdgeCW(p); bool ce3 = ot.GetConstrainedEdgeCCW(op); bool ce4 = ot.GetConstrainedEdgeCW(op); bool de1 = t.GetDelaunayEdgeCCW(p); bool de2 = t.GetDelaunayEdgeCW(p); bool de3 = ot.GetDelaunayEdgeCCW(op); bool de4 = ot.GetDelaunayEdgeCW(op); t.Legalize(p, op); ot.Legalize(op, p); // Remap dEdge ot.SetDelaunayEdgeCCW(p, de1); t.SetDelaunayEdgeCW(p, de2); t.SetDelaunayEdgeCCW(op, de3); ot.SetDelaunayEdgeCW(op, de4); // Remap cEdge ot.SetConstrainedEdgeCCW(p, ce1); t.SetConstrainedEdgeCW(p, ce2); t.SetConstrainedEdgeCCW(op, ce3); ot.SetConstrainedEdgeCW(op, ce4); // Remap neighbors // XXX: might optimize the markNeighbor by keeping track of // what side should be assigned to what neighbor after the // rotation. Now mark neighbor does lots of testing to find // the right side. t.Neighbors.Clear(); ot.Neighbors.Clear(); if (n1 != null) ot.MarkNeighbor(n1); if (n2 != null) t.MarkNeighbor(n2); if (n3 != null) t.MarkNeighbor(n3); if (n4 != null) ot.MarkNeighbor(n4); t.MarkNeighbor(ot); } } }
38.836664
184
0.508892
[ "MIT" ]
PsichiX/mindvolving
FarseerPhysics.Portable/Common/Decomposition/CDT/Delaunay/Sweep/DTSweep.cs
44,705
C#
๏ปฟ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.WindowsAzure.Storage.Table; using Orleans; using Orleans.AzureUtils; using Orleans.Providers.Streams.Generator; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.ServiceBus.Providers; using Orleans.Streams; using Orleans.TestingHost; using Tester; using Tester.StreamingTests; using TestExtensions; using TestGrains; using UnitTests.Grains; using Xunit; namespace ServiceBus.Tests.StreamingTests { [TestCategory("EventHub"), TestCategory("Streaming")] public class EHImplicitSubscriptionStreamRecoveryTests : OrleansTestingBase, IClassFixture<EHImplicitSubscriptionStreamRecoveryTests.Fixture> { private readonly Fixture fixture; private const string StreamProviderName = GeneratedStreamTestConstants.StreamProviderName; private const string EHPath = "ehorleanstest"; private const string EHConsumerGroup = "orleansnightly"; private const string EHCheckpointTable = "ehcheckpoint"; private static readonly string CheckpointNamespace = Guid.NewGuid().ToString(); private static readonly Lazy<EventHubSettings> EventHubConfig = new Lazy<EventHubSettings>(() => new EventHubSettings( TestDefaultConfiguration.EventHubConnectionString, EHConsumerGroup, EHPath)); private static readonly EventHubCheckpointerSettings CheckpointerSettings = new EventHubCheckpointerSettings(TestDefaultConfiguration.DataConnectionString, EHCheckpointTable, CheckpointNamespace, TimeSpan.FromSeconds(1)); private static readonly EventHubStreamProviderSettings ProviderSettings = new EventHubStreamProviderSettings(StreamProviderName); private readonly ImplicitSubscritionRecoverableStreamTestRunner runner; public class Fixture : BaseTestClusterFixture { protected override TestCluster CreateTestCluster() { // poor fault injection requires grain instances stay on same host, so only single host for this test var options = new TestClusterOptions(1); // register stream provider options.ClusterConfiguration.AddMemoryStorageProvider("Default"); options.ClusterConfiguration.Globals.RegisterStreamProvider<EventHubStreamProvider>(StreamProviderName, BuildProviderSettings()); options.ClientConfiguration.RegisterStreamProvider<EventHubStreamProvider>(StreamProviderName, BuildProviderSettings()); return new TestCluster(options); } public override void Dispose() { base.Dispose(); var dataManager = new AzureTableDataManager<TableEntity>(CheckpointerSettings.TableName, CheckpointerSettings.DataConnectionString, NullLoggerFactory.Instance); dataManager.InitTableAsync().Wait(); dataManager.ClearTableAsync().Wait(); } private static Dictionary<string, string> BuildProviderSettings() { var settings = new Dictionary<string, string>(); // get initial settings from configs ProviderSettings.WriteProperties(settings); EventHubConfig.Value.WriteProperties(settings); CheckpointerSettings.WriteProperties(settings); // add queue balancer setting settings.Add(PersistentStreamProviderConfig.QUEUE_BALANCER_TYPE, StreamQueueBalancerType.DynamicClusterConfigDeploymentBalancer.AssemblyQualifiedName); // add pub/sub settting settings.Add(PersistentStreamProviderConfig.STREAM_PUBSUB_TYPE, StreamPubSubType.ImplicitOnly.ToString()); return settings; } } public EHImplicitSubscriptionStreamRecoveryTests(Fixture fixture) { this.fixture = fixture; this.runner = new ImplicitSubscritionRecoverableStreamTestRunner(this.fixture.GrainFactory, StreamProviderName); } [Fact] public async Task Recoverable100EventStreamsWithTransientErrorsTest() { this.fixture.Logger.Info("************************ EHRecoverable100EventStreamsWithTransientErrorsTest *********************************"); await runner.Recoverable100EventStreamsWithTransientErrors(GenerateEvents, ImplicitSubscription_TransientError_RecoverableStream_CollectorGrain.StreamNamespace, 4, 100); } [Fact] public async Task Recoverable100EventStreamsWith1NonTransientErrorTest() { this.fixture.Logger.Info("************************ EHRecoverable100EventStreamsWith1NonTransientErrorTest *********************************"); await runner.Recoverable100EventStreamsWith1NonTransientError(GenerateEvents, ImplicitSubscription_NonTransientError_RecoverableStream_CollectorGrain.StreamNamespace, 4, 100); } private async Task GenerateEvents(string streamNamespace, int streamCount, int eventsInStream) { IStreamProvider streamProvider = (IStreamProvider)this.fixture.HostedCluster.StreamProviderManager.GetProvider(StreamProviderName); IAsyncStream<GeneratedEvent>[] producers = Enumerable.Range(0, streamCount) .Select(i => streamProvider.GetStream<GeneratedEvent>(Guid.NewGuid(), streamNamespace)) .ToArray(); for (int i = 0; i < eventsInStream - 1; i++) { // send event on each stream for (int j = 0; j < streamCount; j++) { await producers[j].OnNextAsync(new GeneratedEvent { EventType = GeneratedEvent.GeneratedEventType.Fill }); } } // send end events for (int j = 0; j < streamCount; j++) { await producers[j].OnNextAsync(new GeneratedEvent { EventType = GeneratedEvent.GeneratedEventType.Report }); } } } }
47.204545
187
0.679185
[ "MIT" ]
seralexeev/orleans
test/ServiceBus.Tests/Streaming/EHImplicitSubscriptionStreamRecoveryTests.cs
6,233
C#
๏ปฟusing System.Collections.Generic; using Abp.Application.Services.Dto; using Abp.Authorization; using Abp.AutoMapper; using Abp.Localization; namespace BodeAbp.Zero.Permissions.Dtos { /// <summary> /// ๆƒ้™ๅŸบๆœฌไฟกๆฏ /// </summary> [AutoMapFrom(typeof(Permission))] public class PermissionBriefOutPut { /// <summary> /// ๆƒ้™ๅ /// </summary> public string Name { get; set; } /// <summary> /// ๆ˜พ็คบๅ /// </summary> public ILocalizableString DisplayName { get; set; } /// <summary> /// ๅญๆƒ้™้›†ๅˆ /// </summary> public IReadOnlyList<PermissionBriefOutPut> Children { get; set; } } }
22.290323
74
0.581766
[ "MIT" ]
liuxx-u/BodeAbp
src/modules/BodeAbp.Zero/Permissions/Dtos/PermissionBriefOutPut.cs
727
C#
๏ปฟusing System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Torch.Utils; namespace Torch.Collections { /// <summary> /// Multithread safe, observable collection /// </summary> /// <typeparam name="TC">Collection type</typeparam> /// <typeparam name="TV">Value type</typeparam> public abstract class MtObservableCollection<TC, TV> : MtObservableCollectionBase<TV> where TC : class, ICollection<TV> { protected readonly TC Backing; protected override ReaderWriterLockSlim Lock { get; } protected MtObservableCollection(TC backing) { // recursion so the events can read snapshots. Lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion); Backing = backing; } #region ICollection /// <inheritdoc/> public override void Add(TV item) { using (Lock.WriteUsing()) { Backing.Add(item); MarkSnapshotsDirty(); OnPropertyChanged(nameof(Count)); OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, Backing.Count - 1)); } } /// <inheritdoc/> public override void Clear() { using (Lock.WriteUsing()) { Backing.Clear(); MarkSnapshotsDirty(); OnPropertyChanged(nameof(Count)); OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } /// <inheritdoc/> public override bool Contains(TV item) { using (Lock.ReadUsing()) return Backing.Contains(item); } /// <inheritdoc/> public override void CopyTo(TV[] array, int arrayIndex) { using (Lock.ReadUsing()) Backing.CopyTo(array, arrayIndex); } /// <inheritdoc/> public override bool Remove(TV item) { using (Lock.UpgradableReadUsing()) { int? oldIndex = (Backing as IList<TV>)?.IndexOf(item); if (oldIndex == -1) return false; using (Lock.WriteUsing()) { if (!Backing.Remove(item)) return false; MarkSnapshotsDirty(); OnPropertyChanged(nameof(Count)); OnCollectionChanged(oldIndex.HasValue ? new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, oldIndex.Value) : new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); return true; } } } /// <inheritdoc/> public override int Count { get { using (Lock.ReadUsing()) return Backing.Count; } } /// <inheritdoc/> public override bool IsReadOnly => Backing.IsReadOnly; /// <inheritdoc/> public override void CopyTo(Array array, int index) { using (Lock.ReadUsing()) { foreach (TV k in Backing) { array.SetValue(k, index); index++; } } } #endregion } }
30.699187
123
0.529396
[ "Apache-2.0" ]
Andargor/Torch
Torch/Collections/MTObservableCollection.cs
3,778
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 glue-2017-03-31.normal.json service model. */ using System; using System.Net; using Amazon.Runtime; namespace Amazon.Glue.Model { ///<summary> /// Glue exception /// </summary> #if !PCL && !CORECLR [Serializable] #endif public class OperationTimeoutException : AmazonGlueException { /// <summary> /// Constructs a new OperationTimeoutException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public OperationTimeoutException(string message) : base(message) {} /// <summary> /// Construct instance of OperationTimeoutException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public OperationTimeoutException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of OperationTimeoutException /// </summary> /// <param name="innerException"></param> public OperationTimeoutException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of OperationTimeoutException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public OperationTimeoutException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of OperationTimeoutException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public OperationTimeoutException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !PCL && !CORECLR /// <summary> /// Constructs a new instance of the OperationTimeoutException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected OperationTimeoutException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } #endif } }
42.865979
178
0.647908
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/Glue/Generated/Model/OperationTimeoutException.cs
4,158
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Response to SystemRoutingGetRouteDeviceListRequest. The column headings are "Net Address", /// "Port", "Transport" and "Description". /// <see cref="SystemRoutingGetRouteDeviceListRequest"/> /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""7f663d5135470c33ca64b0eed3c3aa0c:14262""}]")] public class SystemRoutingGetRouteDeviceListResponse : BroadWorksConnector.Ocip.Models.C.OCIDataResponse { private BroadWorksConnector.Ocip.Models.C.OCITable _routeDeviceTable; [XmlElement(ElementName = "routeDeviceTable", IsNullable = false, Namespace = "")] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:14262")] public BroadWorksConnector.Ocip.Models.C.OCITable RouteDeviceTable { get => _routeDeviceTable; set { RouteDeviceTableSpecified = true; _routeDeviceTable = value; } } [XmlIgnore] protected bool RouteDeviceTableSpecified { get; set; } } }
33.675
131
0.678545
[ "MIT" ]
JTOne123/broadworks-connector-net
BroadworksConnector/Ocip/Models/SystemRoutingGetRouteDeviceListResponse.cs
1,347
C#
๏ปฟusing System; using Calamari.Util; using FluentAssertions; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Util { [TestFixture] public class StringExtensionsFixture { [TestCase("Hello World", "ello", true)] [TestCase("Hello World", "ELLO", true)] [TestCase("HELLO WORLD", "ello", true)] [TestCase("Hello, world", "lO, wOrL", true)] [TestCase("Hello, world", "abc", false)] [TestCase("Hello, world", "ABC", false)] [TestCase("Hello, world", "!@#", false)] [Test] public void ShouldContainString(string originalString, string value, bool expected) { originalString.ContainsIgnoreCase(value); } [Test] public void NullValueShouldThrowException() { Action action = () => "foo".ContainsIgnoreCase(null); action.ShouldThrow<ArgumentNullException>(); } } }
30.096774
91
0.599143
[ "Apache-2.0" ]
bonefisher/Calamari
source/Calamari.Tests/Fixtures/Util/StringExtensionsFixture.cs
935
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.FSx")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon FSx. Amazon FSx provides fully-managed third-party file systems optimized for a variety of enterprise and compute-intensive workloads.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.5.0.28")]
46.1875
221
0.751015
[ "Apache-2.0" ]
augustoproiete-forks/aws--aws-sdk-net
sdk/code-analysis/ServiceAnalysis/FSx/Properties/AssemblyInfo.cs
1,478
C#
๏ปฟusing Discord; using Discord.Commands; using NadekoBot.Services; using System; using System.Threading.Tasks; using NadekoBot.Common.Attributes; using NadekoBot.Modules.Administration.Services; using System.Linq; namespace NadekoBot.Modules.Administration { public partial class Administration { [Group] public class MuteCommands : NadekoSubmodule<MuteService> { private readonly DbService _db; public MuteCommands(DbService db) { _db = db; } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.ManageRoles)] [Priority(0)] public async Task SetMuteRole([Remainder] string name) { name = name.Trim(); if (string.IsNullOrWhiteSpace(name)) return; using (var uow = _db.UnitOfWork) { var config = uow.GuildConfigs.For(Context.Guild.Id, set => set); config.MuteRoleName = name; _service.GuildMuteRoles.AddOrUpdate(Context.Guild.Id, name, (id, old) => name); await uow.CompleteAsync().ConfigureAwait(false); } await ReplyConfirmLocalized("mute_role_set").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.ManageRoles)] [Priority(1)] public Task SetMuteRole([Remainder] IRole role) => SetMuteRole(role.Name); [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.KickMembers)] [RequireUserPermission(GuildPermission.MuteMembers)] [Priority(0)] public async Task Mute(IGuildUser user) { try { await _service.MuteUser(user).ConfigureAwait(false); await ReplyConfirmLocalized("user_muted", Format.Bold(user.ToString())).ConfigureAwait(false); } catch { await ReplyErrorLocalized("mute_error").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.KickMembers)] [RequireUserPermission(GuildPermission.MuteMembers)] [Priority(1)] public async Task Mute(string time, IGuildUser user) { string argTime = time; int days = 0, hours = 0, minutes = 0; string sdays = "0", shours = "0", sminutes = "0"; if (argTime.Contains('d')) { sdays = argTime.Split('d')[0]; argTime = argTime.Split('d')[1]; } if (argTime.Contains('h')) { shours = argTime.Split('h')[0]; argTime = argTime.Split('h')[1]; } if (argTime.Contains('m')) { sminutes = argTime.Split('m')[0]; argTime = argTime.Split('m')[1]; } days = Convert.ToInt32(sdays); hours = Convert.ToInt32(shours); minutes = Convert.ToInt32(sminutes); int muteTime = (days * 24 * 60) + (hours * 60) + minutes; try { await _service.TimedMute(user, TimeSpan.FromMinutes(muteTime)).ConfigureAwait(false); await ReplyConfirmLocalized("user_muted_time", Format.Bold(user.ToString()), muteTime).ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); await ReplyErrorLocalized("mute_error").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.KickMembers)] [RequireUserPermission(GuildPermission.MuteMembers)] public async Task Unmute(IGuildUser user) { try { await _service.UnmuteUser(user).ConfigureAwait(false); await ReplyConfirmLocalized("user_unmuted", Format.Bold(user.ToString())).ConfigureAwait(false); } catch { await ReplyErrorLocalized("mute_error").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.KickMembers)] public async Task ChatMute(IGuildUser user) { try { await _service.MuteUser(user, MuteType.Chat).ConfigureAwait(false); await ReplyConfirmLocalized("user_chat_mute", Format.Bold(user.ToString())).ConfigureAwait(false); } catch { await ReplyErrorLocalized("mute_error").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.KickMembers)] public async Task ChatUnmute(IGuildUser user) { try { await _service.UnmuteUser(user, MuteType.Chat).ConfigureAwait(false); await ReplyConfirmLocalized("user_chat_unmute", Format.Bold(user.ToString())).ConfigureAwait(false); } catch { await ReplyErrorLocalized("mute_error").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.MuteMembers)] public async Task VoiceMute([Remainder] IGuildUser user) { try { await _service.MuteUser(user, MuteType.Voice).ConfigureAwait(false); await ReplyConfirmLocalized("user_voice_mute", Format.Bold(user.ToString())).ConfigureAwait(false); } catch { await ReplyErrorLocalized("mute_error").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.MuteMembers)] public async Task VoiceUnmute([Remainder] IGuildUser user) { try { await _service.UnmuteUser(user, MuteType.Voice).ConfigureAwait(false); await ReplyConfirmLocalized("user_voice_unmute", Format.Bold(user.ToString())).ConfigureAwait(false); } catch { await ReplyErrorLocalized("mute_error").ConfigureAwait(false); } } } } }
38.535354
129
0.526081
[ "MIT" ]
maltesermailo/Mitternacht-NEW
src/NadekoBot/Modules/Administration/MuteCommands.cs
7,632
C#
๏ปฟ/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Globalization; using System.Net; using System.Reflection; using System.Threading; using CookComputing.XmlRpc; using XenAdmin.Actions; using XenAdmin.Core; using XenAPI; using XenCenterLib; using System.Diagnostics; using System.Xml.Serialization; using XenAdmin.ServerDBs; namespace XenAdmin.Network { [DebuggerDisplay("IXenConnection :{HostnameWithPort}")] public class XenConnection : IXenConnection,IXmlSerializable { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public string Hostname { get; set; } public int Port { get; set; } public string Username { get; set; } public string Password { get; set; } public string FriendlyName { get; set; } /// <summary> /// The last known name for the pool, in the form "'Pool friendly name' (hostname or IP)". /// </summary> public string LastConnectionFullName = ""; /// <summary> /// Whether this connection is saved in a disconnected state (i.e. don't reconnect on session restore). /// </summary> public bool SaveDisconnected { get; set; } /// <summary> /// Indicates whether this connection was created in the Add Server dialog. /// </summary> public bool fromDialog = false; /// <summary> /// Whether we're expecting network disruption, say because we're reconfiguring the network at this time. In that case, we ignore /// keepalive failures, and expect task polling to be disrupted. /// </summary> private volatile bool _expectedDisruption = false; public bool ExpectDisruption { get { return _expectedDisruption; } set { _expectedDisruption = value; } } /// <summary> /// If we are 'expecting' this connection's Password property to contain the correct password /// (i.e. false if the user has just entered the password, true if it was restored from the saved session). /// </summary> public bool ExpectPasswordIsCorrect { get; set; } /// <summary> /// Used by the patch wizard, supress any errors coming from reconnect attempts /// </summary> private volatile bool _supressErrors = false; public bool SupressErrors { get { return _supressErrors; } set { _supressErrors = value; } } /// <summary> /// Indicates whether we are expecting the pool master to change soon (e.g. when explicitly designating a new master). /// </summary> private volatile bool _masterMayChange = false; public bool MasterMayChange { get { return _masterMayChange; } set { _masterMayChange = value; } } /// <summary> /// Set when we detect that Event.next() has become blocked and we need to reset the connection. See CA-33145. /// </summary> private bool EventNextBlocked = false; /// <summary> /// A cache of the pool's opaque_ref, last time this connection was connected. This will be /// Helper.NullOpaqueRef if it's never been connected. /// </summary> private string PoolOpaqueRef = Helper.NullOpaqueRef; /// <summary> /// Set after a successful connection attempt, before the cache is populated. /// </summary> private string MasterIPAddress = ""; /// <summary> /// The lock that must be taken around connectTask and monitor. /// </summary> private readonly object connectTaskLock = new object(); private ConnectTask connectTask = null; private Heartbeat heartbeat = null; /// <summary> /// Whether we are trying to automatically connect to the new master. Set in HandleConnectionLost. /// Note: I think we are not using this correctly -- see CA-37864 for details -- but I'm not going /// to fix it unless it gives rise to a reported bug, because I can't test the fix. /// </summary> private volatile bool FindingNewMaster = false; /// <summary> /// The time at which we started looking for the new master. /// </summary> private DateTime FindingNewMasterStartedAt = DateTime.MinValue; /// <summary> /// Timeout before we consider that Event.next() has got blocked: see CA-33145 /// </summary> private const int EVENT_NEXT_TIMEOUT = 120 * 1000; // 2 minutes private string LastMasterHostname = ""; public readonly object PoolMembersLock = new object(); private List<string> _poolMembers = new List<string>(); public List<string> PoolMembers { get { return _poolMembers; } set { _poolMembers = value; } } private int PoolMemberIndex = 0; private System.Threading.Timer ReconnectionTimer = null; private ActionBase ConnectAction; private DateTime m_startTime = DateTime.MinValue; private int m_lastDebug; private TimeSpan ServerTimeOffset_ = TimeSpan.Zero; private object ServerTimeOffsetLock = new object(); /// <summary> /// The offset between the clock at the client and the clock at the server. server time + ServerTimeOffset = client time. /// This does not take the local timezone into account -- all calculations should be in UTC. /// For Orlando and greater, this value is set by XenMetricsMonitor, calling Host.get_servertime on a heartbeat. /// </summary> public TimeSpan ServerTimeOffset { get { lock (ServerTimeOffsetLock) { return ServerTimeOffset_; } } set { lock (ServerTimeOffsetLock) { TimeSpan diff = ServerTimeOffset_ - value; if (diff.TotalSeconds < -1 || 1 < diff.TotalSeconds) { var now = DateTime.UtcNow; var debugMsg = string.Format("Time offset for {0} is now {1}. It's now {2} UTC here, and {3} UTC on the server.", Hostname, value, now.ToString("o", CultureInfo.InvariantCulture), (now.Subtract(value)).ToString("o", CultureInfo.InvariantCulture)); if (m_startTime.Ticks == 0)//log it the first time it is detected { m_startTime = now; log.Info(debugMsg); } //then log every 5mins int currDebug = (int)((now - m_startTime).TotalSeconds) / 300; if (currDebug > m_lastDebug) { m_lastDebug = currDebug; log.InfoFormat(debugMsg); } } ServerTimeOffset_ = value; } if (TimeSkewUpdated != null) TimeSkewUpdated(this, EventArgs.Empty); } } public string HostnameWithPort { get { return Port == ConnectionsManager.DEFAULT_XEN_PORT ? Hostname : Hostname + ':' + Port.ToString(); } } public string UriScheme { get { return Port == 8080 || Port == 80 ? Uri.UriSchemeHttp : Uri.UriSchemeHttps; } } public string Version { get; set; } public string Name { get { string result = Helpers.GetName(Helpers.GetPoolOfOne(this)); return !string.IsNullOrEmpty(result) ? result : !string.IsNullOrEmpty(FriendlyName) ? FriendlyName : Hostname; } } /// <summary> /// The cache of XenAPI objects for this connection. /// </summary> private readonly ICache _cache = new Cache(); public ICache Cache { get { return _cache; } } private readonly LockFreeQueue<ObjectChange> eventQueue = new LockFreeQueue<ObjectChange>(); private readonly System.Threading.Timer cacheUpdateTimer; /// <summary> /// Whether the cache for this connection has been populated. /// </summary> private bool cacheIsPopulated = false; public bool CacheIsPopulated { get { return cacheIsPopulated; } } private bool cacheUpdaterRunning = false; private bool updatesWaiting = false; /// <summary> /// Initializes a new instance of the <see cref="XenConnection"/> class. /// </summary> public XenConnection() { Port = ConnectionsManager.DEFAULT_XEN_PORT; Username = "root"; SaveDisconnected = false; ExpectPasswordIsCorrect = true; cacheUpdateTimer = new System.Threading.Timer(cacheUpdater); } /// <summary> /// For use by unit tests only. /// </summary> /// <param name="user"></param> /// <param name="password"></param> /// <returns></returns> public Session Connect(string user, string password) { heartbeat = new Heartbeat(this, XenAdminConfigManager.Provider.ConnectionTimeout); Session session = SessionFactory.CreateSession(this, Hostname, Port); try { session.login_with_password(user, password, Helper.APIVersionString(API_Version.LATEST), Session.UserAgent); // this is required so connection.IsConnected returns true in the unit tests. connectTask = new ConnectTask("test", 0); connectTask.Connected = true; connectTask.Session = session; return session; } catch (Exception) { return null; } } /// <summary> /// Used by unit tests only. /// </summary> /// <param name="session">The session.</param> public void LoadCache(Session session) { this.Cache.Clear(); cacheIsPopulated = false; string token = ""; XenObjectDownloader.GetAllObjects(session, eventQueue, () => false, ref token); List<ObjectChange> events = new List<ObjectChange>(); while (eventQueue.NotEmpty) events.Add(eventQueue.Dequeue()); this.Cache.UpdateFrom(this, events); cacheIsPopulated = true; } /// <summary> /// Fired just before the cache is cleared (i.e. the cache is still populated). /// </summary> public event EventHandler<EventArgs> ClearingCache; public event EventHandler<EventArgs> CachePopulated; public event EventHandler<ConnectionResultEventArgs> ConnectionResult; public event EventHandler<EventArgs> ConnectionStateChanged; public event EventHandler<EventArgs> ConnectionLost; public event EventHandler<EventArgs> ConnectionClosed; public event EventHandler<EventArgs> ConnectionReconnecting; public event EventHandler<EventArgs> BeforeConnectionEnd; public event EventHandler<ConnectionMessageChangedEventArgs> ConnectionMessageChanged; public event EventHandler<ConnectionMajorChangeEventArgs> BeforeMajorChange; public event EventHandler<ConnectionMajorChangeEventArgs> AfterMajorChange; /// <summary> /// Fired on the UI thread, once per batch of events in CacheUpdater. /// </summary> public event EventHandler<EventArgs> XenObjectsUpdated; public NetworkCredential NetworkCredential { get; set; } public event EventHandler<EventArgs> TimeSkewUpdated; public bool IsConnected { get { // sneaky, but avoids a lock ConnectTask t = connectTask; return t != null && t.Connected; } } public bool InProgress { get { return connectTask != null; } } /// <summary> /// Gets the Session passed to ConnectWorkerThread and used to update the cache in XenObjectDownloader. /// May return null. /// </summary> public Session Session { get { ConnectTask t = connectTask; return t == null ? null : t.Session; } } /// <summary> /// Create a duplicate of the Session that this connection is currently using. /// This will use a separate TCP stream, but the same authentication credentials. /// </summary> /// <returns></returns> public Session DuplicateSession() { return DuplicateSession(Session.STANDARD_TIMEOUT); } public Session DuplicateSession(int timeout) { Session s = Session; if (s == null) throw new DisconnectionException(); return SessionFactory.DuplicateSession(s, this, timeout); } /// <summary> /// For retrieving an extra session using different credentials to those stored in the connection. Used for the sudo /// function in actions. Does not prompt for new credentials if the authentication fails. /// Does not change connection's Username and Password. /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> public Session ElevatedSession(string username, string password) { return GetNewSession(Hostname, Port, username, password, true); } /// <summary> /// For retrieving a new session. /// </summary> /// <param name="hostname"></param> /// <param name="port"></param> /// <param name="username"></param> /// <param name="password"></param> /// <param name="isElevated"></param> /// <returns>null if the server password has changed, the user has been prompted for the new password, /// but the user has clicked cancel on the dialog.</returns> private Session GetNewSession(string hostname, int port, string username, string password, bool isElevated) { const int DELAY = 250; // unit = ms int attempt = 0; while (true) { attempt++; string uname = isElevated ? username : Username; string pwd = isElevated ? password : Password; // Keep the password that we're using for this iteration, as it may // be changed by another thread handling an authentication failure. // For elevated session we use the elevated username and password passed into this function, // as the connection's Username and Password are not updated. Session session = SessionFactory.CreateSession(this, hostname, port); if (isElevated) session.IsElevatedSession = true; try { session.login_with_password(uname, pwd, !string.IsNullOrEmpty(Version) ? Version : Helper.APIVersionString(API_Version.LATEST), Session.UserAgent); NetworkCredential = new NetworkCredential(uname, pwd); return session; } catch (Failure f) { if (connectTask == null || connectTask.Cancelled) // the user has clicked cancel on the connection to server dialog { attempt = DEFAULT_MAX_SESSION_LOGIN_ATTEMPTS; // make sure we throw rather than try again throw new CancelledException(); // make the dialog pop up again } else if (f.ErrorDescription.Count > 0) { switch (f.ErrorDescription[0]) { case Failure.SESSION_AUTHENTICATION_FAILED: if (isElevated) throw; if (PromptForNewPassword(pwd)) attempt = 0; else { //user cannot provide correct credentials, we d/c now to save the confusion of having the server available //but unusable. EndConnect(); throw new CancelledException(); } break; case Failure.HOST_IS_SLAVE: // we know it is a slave so there there is no need to try and connect again, we need to connect to the master case Failure.RBAC_PERMISSION_DENIED: // No point retrying this, the user needs the read only role at least to log in case Failure.HOST_UNKNOWN_TO_MASTER: // Will never succeed, CA-74718 throw; default: if (isElevated) { if (attempt >= DEFAULT_MAX_SESSION_LOGIN_ATTEMPTS) throw; else break; } else break; } } else { if (attempt >= DEFAULT_MAX_SESSION_LOGIN_ATTEMPTS) throw; } } catch (WebException e) { if (e.Status == WebExceptionStatus.TrustFailure) throw new CancelledException(); if (e.Status == WebExceptionStatus.NameResolutionFailure || e.Status == WebExceptionStatus.ProtocolError || attempt >= DEFAULT_MAX_SESSION_LOGIN_ATTEMPTS) throw; } catch (UriFormatException) { // No point trying to connect more than once to a duff URI throw; } catch (Exception) { if (attempt >= DEFAULT_MAX_SESSION_LOGIN_ATTEMPTS) throw; } Thread.Sleep(DELAY); } } // This CompareTo() mimics the sort order we get from XenSearch, with // pools first, then hosts, then disconnected connections. It is used // in some dialogs where we don't do a proper search: see CA-57131 & // CA-60517 for examples. public int CompareTo(IXenConnection other) { if (this == other) return 0; if (other == null) return -1; Pool thisPool = Helpers.GetPool(this); Pool otherPool = Helpers.GetPool(other); int thisClass = (this.IsConnected ? (thisPool == null ? 2 : 1) : 3); int otherClass = (other.IsConnected ? (otherPool == null ? 2 : 1) : 3); if (thisClass != otherClass) return thisClass - otherClass; int result = StringUtility.NaturalCompare(Name, other.Name); if (result != 0) return result; Pool p1 = Helpers.GetPoolOfOne(this); Pool p2 = Helpers.GetPoolOfOne(other); if (p1 == null || p2 == null) return 0; // shouldn't happen once connected, but let's be safe return p1.opaque_ref.CompareTo(p2.opaque_ref); } /// <summary> /// Set the pool and master details in the Action to allow proper filtering in HistoryPanel. /// </summary> private void SetPoolAndHostInAction(ActionBase action) { Pool pool = Helpers.GetPoolOfOne(this); if (pool != null) SetPoolAndHostInAction(action, pool, PoolOpaqueRef); } private void SetPoolAndHostInAction(ActionBase action, Pool pool, string poolopaqueref) { if (pool != null && !string.IsNullOrEmpty(poolopaqueref)) { Pool p = new Pool(); p.Connection = this; p.opaque_ref = poolopaqueref; p.UpdateFrom(pool); Host h = new Host(); h.Connection = this; h.opaque_ref = pool.master.opaque_ref; h.name_label = Hostname; action.Pool = p; action.Host = h; } else { // Match the hack in XenSearch/GroupAlg.cs. We are creating fake Host objects to // represent the disconnected server, with the opaque_ref set to the connection's HostnameWithPort. // We need to do the same here, so that Actions for disconnected hosts (like failed connections) // are attached to the disconnected server correctly. Host host = new Host(); host.Connection = this; host.opaque_ref = HostnameWithPort; action.Host = host; } } private Func<IXenConnection, string, bool> _promptForNewPassword; /// <summary> /// /// </summary> /// <param name="initiateMasterSearch">If true, if connection to the master fails we will start trying to connect to /// each remembered slave in turn.</param> /// <param name="promptForNewPassword">A function that prompts the user for the changed password for a server.</param> public void BeginConnect(bool initiateMasterSearch, Func<IXenConnection, string, bool> promptForNewPassword) { _promptForNewPassword = promptForNewPassword; //InvokeHelper.Synchronizer is used for synchronizing the cache update. Must not be null at this point. It can be initialized through InvokeHelper.Initialize() Trace.Assert(InvokeHelper.Synchronizer != null); InvokeHelper.AssertOnEventThread(); if (initiateMasterSearch) { FindingNewMaster = true; FindingNewMasterStartedAt = DateTime.Now; } MasterMayChange = false; if (!HandlePromptForNewPassword()) return; lock (connectTaskLock) { if (connectTask == null) { ClearEventQueue(); OnBeforeMajorChange(false); Cache.Clear(); OnAfterMajorChange(false); connectTask = new ConnectTask(Hostname, Port); StopMonitor(); heartbeat = new Heartbeat(this, XenAdminConfigManager.Provider.ConnectionTimeout); Thread t = new Thread(ConnectWorkerThread); t.Name = "Connection to " + Hostname; t.IsBackground = true; t.Start(connectTask); } else { // a connection is already in progress } } } private static object WaitForMonitor = new object(); private static int WaitForEventRegistered = 0; private static object WaitForEventRegisteredLock = new object(); public void WaitFor(Func<bool> predicate, Func<bool> cancelling) { lock (WaitForEventRegisteredLock) { if (WaitForEventRegistered == 0) XenObjectsUpdated += WakeWaitFor; WaitForEventRegistered++; } try { while (true) { lock (WaitForMonitor) { if (predicate() || (cancelling != null && cancelling())) return; System.Threading.Monitor.Wait(WaitForMonitor, 500); } } } finally { lock (WaitForEventRegisteredLock) { WaitForEventRegistered--; if (WaitForEventRegistered == 0) XenObjectsUpdated -= WakeWaitFor; } } } private void WakeWaitFor(object sender, EventArgs e) { lock (WaitForMonitor) { System.Threading.Monitor.PulseAll(WaitForMonitor); } } /// <summary> /// Equivalent to WaitForCache(xenref, null). /// </summary> /// <typeparam name="T"></typeparam> /// <param name="xenref"></param> /// <returns></returns> public T WaitForCache<T>(XenRef<T> xenref) where T : XenObject<T> { return WaitForCache(xenref, null); } /// <summary> /// Wait for the given object to arrive in our cache. Returns the XenObject, or null if it does /// not appear within the timeout (1 minute). /// /// This blocks, so must only be used on a background thread. /// </summary> /// <param name="xenref"></param> /// <param name="cancelling">A delegate to check whether to cancel. May be null, in which case it's ignored</param> public T WaitForCache<T>(XenRef<T> xenref, Func<bool> cancelling) where T : XenObject<T> { lock (WaitForEventRegisteredLock) { if (WaitForEventRegistered == 0) XenObjectsUpdated += WakeWaitFor; WaitForEventRegistered++; } try { for (int i = 0; i < 120; i++) { lock (WaitForMonitor) { T result = Resolve<T>(xenref); if (result != null || (cancelling != null && cancelling())) return result; System.Threading.Monitor.Wait(WaitForMonitor, 500); } } return null; } finally { lock (WaitForEventRegisteredLock) { WaitForEventRegistered--; if (WaitForEventRegistered == 0) XenObjectsUpdated -= WakeWaitFor; } } } /// <param name="clearCache">Whether the cache should be cleared (requires invoking onto the GUI thread)</param> /// <param name="exiting"></param> public void EndConnect(bool clearCache = true, bool exiting = false) { ConnectTask t = connectTask; connectTask = null; EndConnect(clearCache, t, exiting); } /// <summary> /// Closes the connecting dialog, stops the XenMetricsMonitor thread, marks this.task as Cancelled and /// logs out of the task's Session on a background thread. /// </summary> /// <param name="clearCache">Whether the cache should be cleared (requires invoking onto the GUI thread)</param> /// <param name="task"></param> /// <param name="exiting"></param> private void EndConnect(bool clearCache, ConnectTask task, bool exiting) { OnBeforeConnectionEnd(); lock (connectTaskLock) { StopMonitor(); if (task != null) { task.Cancelled = true; Session session = task.Session; task.Session = null; if (session != null) { Logout(session, exiting); } } } MarkConnectActionComplete(); // Save list of addresses of current hosts in pool List<string> members = new List<string>(); foreach (Host host in Cache.Hosts) { members.Add(host.address); } lock (PoolMembersLock) { PoolMembers = members; } // Clear the XenAPI object cache if (clearCache) { ClearCache(); } _promptForNewPassword = null; OnConnectionClosed(); } /// <summary> /// Try to logout the given session. This will cause any threads blocking on Event.next() to get /// a XenAPI.Failure (which is better than them hanging around forever). /// Do on a background thread - otherwise, if the master has died, then this will block /// until the timeout is reached (default 20s). /// However, in the case of exiting, the thread need to be set as foreground. /// Otherwise the logging out operation can be terminated when other foreground threads finish. /// </summary> /// <param name="session">May be null, in which case nothing happens.</param> /// <param name="exiting"></param> public void Logout(Session session, bool exiting = false) { if (session == null || session.opaque_ref == null) return; Thread t = new Thread(Logout_); t.Name = string.Format("Logging out session {0}", session.opaque_ref); if (exiting) { t.IsBackground = false; t.Priority = ThreadPriority.AboveNormal; } else { t.IsBackground = true; t.Priority = ThreadPriority.Lowest; } t.Start(session); } public void Logout() { Logout(Session); } private static void Logout_(object o) { Session session = (Session)o; try { log.Debug("Trying Session.logout() on background thread"); session.logout(); log.Debug("Session.logout() succeeded"); } catch (Exception e) { log.Debug("Session.logout() failed", e); } } public void Interrupt() { ConnectTask t = connectTask; ICache coll = Cache; connectTask = null; if (t != null && t.Connected) { string poolopaqueref = null; Pool pool = coll == null ? null : getAPool(coll, out poolopaqueref); t.Cancelled = true; HandleConnectionLost(t, pool, poolopaqueref); } } private void ClearCache() { OnClearingCache(); ClearEventQueue(); // This call to Clear needs to occur on the background thread, otherwise the event firing in response to all the changes // block in one big lump rather than the smaller pieces that you get when invoking onto the event thread on a finer // granularity. If you do all this on the event thread, then the app tends to go (Not Responding) when you lose a connection. // It doesn't actually occur on the background thread all the time. There's a path from AddServerDialog.ConnectToServer. Cache.Clear(); } private void OnCachePopulated() { lock (connectTaskLock) { if (heartbeat != null) heartbeat.Start(); } if (CachePopulated != null) CachePopulated(this, EventArgs.Empty); MarkConnectActionComplete(); } private string GetReason(Exception error) { if (error is CookComputing.XmlRpc.XmlRpcServerException) { return string.Format(Messages.SERVER_FAILURE, error.Message); } else if (error is ArgumentException) { // This happens if the server API is incompatible with our bindings. This should // never happen in production, but will happen during development if a field // changes type, for example. return Messages.SERVER_API_INCOMPATIBLE; } else if (error is WebException) { WebException w = error as WebException; if (w.Status == WebExceptionStatus.NameResolutionFailure) { return string.Format(Messages.CONNECT_RESOLUTION_FAILURE, this.Hostname); } else if (w.Status == WebExceptionStatus.ConnectFailure) { return string.Format(Messages.CONNCET_CONNECTION_FAILURE, this.Hostname); } else if (w.Status == WebExceptionStatus.ReceiveFailure) { return string.Format(Messages.ERROR_NO_XENSERVER, this.Hostname); } else if (w.Status == WebExceptionStatus.SecureChannelFailure) { return string.Format(Messages.ERROR_SECURE_CHANNEL_FAILURE, this.Hostname); } else { return w.Message; } } else if (error is Failure && error != null && !string.IsNullOrEmpty(error.Message)) { Failure f = error as Failure; if (f.ErrorDescription[0] == Failure.RBAC_PERMISSION_DENIED) { // we use a different error message here from the standard one in friendly names return Messages.ERROR_NO_PERMISSION; } return error.Message; } else if (error is NullReferenceException && error.Source.StartsWith("CookComputing")) { return string.Format(Messages.CONNCET_CONNECTION_FAILURE, this.Hostname); } else if (error != null && !string.IsNullOrEmpty(error.Message)) { return error.Message; } else { return null; } } private void HandleSuccessfulConnection(string taskHostname, int task_port) { // add server name to history (if it's not already there) XenAdminConfigManager.Provider.UpdateServerHistory(HostnameWithPort); if (!ConnectionsManager.XenConnectionsContains(this)) { lock (ConnectionsManager.ConnectionsLock) { ConnectionsManager.XenConnections.Add(this); } InvokeHelper.Invoke(XenAdminConfigManager.Provider.SaveSettingsIfRequired); } log.InfoFormat("Connected to {0} ({1}:{2})", FriendlyName, taskHostname, task_port); string name = string.IsNullOrEmpty(FriendlyName) || FriendlyName == taskHostname ? taskHostname : string.Format("{0} ({1})", FriendlyName, taskHostname); string title = string.Format(Messages.CONNECTING_NOTICE_TITLE, name); string msg = string.Format(Messages.CONNECTING_NOTICE_TEXT, name); log.Info($"Connecting to {name} in progress."); ConnectAction = new ActionBase(title, msg, false, false); ExpectPasswordIsCorrect = true; OnConnectionResult(true, null, null); } /// <summary> /// Check the password isn't null, which happens when the session is restored without remembering passwords. /// </summary> /// <returns>Whether to continue.</returns> private bool HandlePromptForNewPassword() { if (Password == null && !PromptForNewPassword(Password)) { // if false the user has cancelled, set the password back to null and return Password = null; return false; } return true; } private void HandleConnectionTermination() { // clean up action so we dont stay open forever if (ConnectAction != null) ConnectAction.IsCompleted = true; } private readonly object PromptLock = new object(); /// <summary> /// Prompts the user for the changed password for a server. /// </summary> /// <param name="old_password"></param> /// <returns></returns> private bool PromptForNewPassword(string old_password) { // Serialise prompting for new passwords, so that we don't get multiple dialogs pop up. lock (PromptLock) { if (Password != old_password) { // Some other thread has changed the password already. Retry using that one. return true; } bool result = (_promptForNewPassword != null) ? _promptForNewPassword(this, old_password) : false; return result; } } private void ClearEventQueue() { while (eventQueue.NotEmpty) { eventQueue.Dequeue(); } // Suspend the cache update timer cacheUpdateTimer.Change(Timeout.Infinite, Timeout.Infinite); } private void EventsPending() { lock (cacheUpdateTimer) { if (cacheUpdaterRunning) updatesWaiting = true; else cacheUpdateTimer.Change(50, -1); } } private void cacheUpdater(object state) { lock (cacheUpdateTimer) { if (cacheUpdaterRunning) { // there is a race-condition here which can be observed under high load: It is possible for the timer to fire even when // cacheUpdaterRunning = true. The check ensures we don't get multiple threads calling cacheUpdater // on the same connection. updatesWaiting = true; return; } cacheUpdaterRunning = true; updatesWaiting = false; } try { cacheUpdater_(); } finally { bool waiting; lock (cacheUpdateTimer) { waiting = updatesWaiting; cacheUpdaterRunning = false; } if (waiting) cacheUpdater(null); } } private void cacheUpdater_() { // Copy events off the event queue // as we don't want events delivered while we're // on the GUI thread to be included in this set of // updates, otherwise we might hose the gui thread // during an event storm (ie deleting 1000 vms) List<ObjectChange> events = new List<ObjectChange>(); while (eventQueue.NotEmpty) events.Add(eventQueue.Dequeue()); if (events.Count > 0) { InvokeHelper.Invoke(delegate() { try { OnBeforeMajorChange(false); bool fire = Cache.UpdateFrom(this, events); OnAfterMajorChange(false); if (fire) OnXenObjectsUpdated(); } catch (Exception e) { log.Error("Exception updating cache.", e); #if DEBUG if (System.Diagnostics.Debugger.IsAttached) throw; #endif } }); if (!cacheIsPopulated) { cacheIsPopulated = true; try { OnCachePopulated(); } catch (Exception e) { log.Error("Exception calling OnCachePopulated.", e); #if DEBUG if (System.Diagnostics.Debugger.IsAttached) throw; #endif } } } } /// <summary> /// if not called the action will never finish and the gui will never close /// </summary> private void MarkConnectActionComplete() { if (ConnectAction != null && !ConnectAction.IsCompleted) { string title = string.Format(Messages.CONNECTION_OK_NOTICE_TITLE, Hostname); string msg = string.Format(Messages.CONNECTION_OK_NOTICE_TEXT, Hostname); log.Info($"Connection to {Hostname} successful."); ConnectAction.Title = title; ConnectAction.Description = msg; SetPoolAndHostInAction(ConnectAction); // mark the connect action as completed ConnectAction.Finished = DateTime.Now; ConnectAction.PercentComplete = 100; ConnectAction.IsCompleted = true; } } /// <summary> /// Stops this connection's XenMetricsMonitor thread. /// Expects to be locked under connectTaskLock. /// </summary> private void StopMonitor() { if (heartbeat != null) { heartbeat.Stop(); heartbeat = null; } } private const int DEFAULT_MAX_SESSION_LOGIN_ATTEMPTS = 3; private bool IsSimulatorConnection { get { return DbProxy.IsSimulatorUrl(this.Hostname); } } private readonly string eventNextConnectionGroupName = Guid.NewGuid().ToString(); /// <summary> /// The main method for a connection to a XenServer. This method runs until the connection is lost, and /// contains a loop that after doing an initial cache fill processes events off the wire when they arrive. /// </summary> /// <param name="o"></param> private void ConnectWorkerThread(object o) { ConnectTask task = (ConnectTask)o; Exception error = null; Pool pool = null; try { log.DebugFormat("IXenConnection: trying to connect to {0}", HostnameWithPort); Session session = GetNewSession(task.Hostname, task.Port, Username, Password, false); // Save the session so we can log it out later task.Session = session; if (session.APIVersion < API_Version.API_2_5) throw new ServerNotSupported(); // Event.next uses a different session with a shorter timeout: see CA-33145. Session eventNextSession = DuplicateSession(EVENT_NEXT_TIMEOUT); eventNextSession.ConnectionGroupName = eventNextConnectionGroupName; // this will force the eventNextSession onto its own set of TCP streams (see CA-108676) cacheIsPopulated = false; session.CacheWarming = true; string token = ""; bool eventsExceptionLogged = false; while (true) { if (task.Cancelled) break; EventNextBlocked = false; if (session.CacheWarming) { if (!task.Connected) { // We've started cache sync: update the dialog text OnConnectionMessageChanged(string.Format(Messages.LABEL_SYNC, this.Hostname)); } XenObjectDownloader.GetAllObjects(session, eventQueue, task.GetCancelled, ref token); session.CacheWarming = false; } else { try { XenObjectDownloader.GetEvents(eventNextSession, eventQueue, task.GetCancelled, ref token); eventsExceptionLogged = false; } catch (Exception exn) { if (!ExpectDisruption) throw; log.DebugFormat("Exception (disruption is expected) in XenObjectDownloader.GetEvents: {0}", exn.GetType().Name); // ignoring some exceptions when disruption is expected if (exn is XmlRpcIllFormedXmlException || exn is System.IO.IOException || (exn is WebException && ((exn as WebException).Status == WebExceptionStatus.KeepAliveFailure || (exn as WebException).Status == WebExceptionStatus.ConnectFailure))) { if (!eventsExceptionLogged) { log.Debug("Ignoring keepalive/connect failure, because disruption is expected"); eventsExceptionLogged = true; } } else { throw; } } } // check if requested to cancel if (task.Cancelled) break; if (!task.Connected) { lock (ConnectionsManager.ConnectionsLock) { pool = ObjectChange.GetPool(eventQueue, out PoolOpaqueRef); Host master = ObjectChange.GetMaster(eventQueue); MasterIPAddress = master.address; foreach (IXenConnection iconn in ConnectionsManager.XenConnections) { XenConnection connection = iconn as XenConnection; Trace.Assert(connection != null); if (!connection.IsConnected) continue; bool sameRef = PoolOpaqueRef == connection.PoolOpaqueRef; if (!sameRef) continue; bool sameMaster = MasterIPAddress == connection.MasterIPAddress; if (sameRef && sameMaster) { throw new ConnectionExists(connection); } else { // CA-15633: XenCenter does not allow connection to host // on which backup is restored. throw new BadRestoreDetected(connection); } } task.Connected = true; string poolName = pool.Name(); FriendlyName = !string.IsNullOrEmpty(poolName) ? poolName : !string.IsNullOrEmpty(master.Name()) ? master.Name() : task.Hostname; } // ConnectionsLock // Remove any other (disconnected) entries for this server from the tree List<IXenConnection> existingConnections = new List<IXenConnection>(); foreach (IXenConnection connection in ConnectionsManager.XenConnections) { if (connection.Hostname.Equals(task.Hostname) && !connection.IsConnected) { existingConnections.Add(connection); } } foreach (IXenConnection connection in existingConnections) { ConnectionsManager.ClearCacheAndRemoveConnection(connection); } log.DebugFormat("Getting server time for pool {0} ({1})...", FriendlyName, PoolOpaqueRef); SetServerTimeOffset(session, pool.master.opaque_ref); // add server name to history (if it's not already there) XenAdminConfigManager.Provider.UpdateServerHistory(HostnameWithPort); HandleSuccessfulConnection(task.Hostname, task.Port); try { SetPoolAndHostInAction(ConnectAction, pool, PoolOpaqueRef); } catch (Exception e) { log.Error(e, e); } log.DebugFormat("Completed connection phase for pool {0} ({1}).", FriendlyName, PoolOpaqueRef); } EventsPending(); } } catch (Failure e) { if (task.Cancelled && e.ErrorDescription.Count > 0 && e.ErrorDescription[0] == Failure.SESSION_INVALID) { // Do nothing: this is probably a result of the user disconnecting, and us calling session.logout() } else { error = e; log.Warn(e); } } catch (WebException e) { error = e; log.Debug(e.Message); } catch (XmlRpcFaultException e) { error = e; log.Debug(e.Message); } catch (XmlRpcException e) { error = e; log.Debug(e.Message); } catch (TargetInvocationException e) { error = e.InnerException; log.Error("TargetInvocationException", e); } catch (UriFormatException e) { // This can happen when the user types gobbledy-gook into the host-name field // of the add server dialog... error = e; log.Debug(e.Message); } catch (CancelledException) { task.Cancelled = true; } catch (DisconnectionException e) { error = e; log.Debug(e.Message); } catch (EventFromBlockedException e) { EventNextBlocked = true; error = e; log.Error(e, e); } catch (Exception e) { error = e; log.Error(e, e); } finally { HandleConnectionResult(task, error, pool); } } private void HandleConnectionResult(ConnectTask task, Exception error, Pool pool) { if (task != connectTask) { // We've been superceded by a newer ConnectTask. Exit silently without firing events. // Can happen when user disconnects while sync is taking place, then reconnects // (creating a new _connectTask) before the sync is complete. } else { ClearEventQueue(); connectTask = null; HandleConnectionTermination(); if (error is ExpressRestriction) { EndConnect(true, task, false); ExpressRestriction e = (ExpressRestriction)error; // This can happen when the user attempts to connect to a second XE Express host from the UI string msg = string.Format(Messages.CONNECTION_RESTRICTED_MESSAGE, e.HostName, e.ExistingHostName); log.Info($"Connection to Server {e.HostName} restricted because a connection already exists to another XE Express Server ({e.ExistingHostName})"); string title = string.Format(Messages.CONNECTION_RESTRICTED_NOTICE_TITLE, e.HostName); ActionBase action = new ActionBase(title, msg, false, true, msg); SetPoolAndHostInAction(action, pool, PoolOpaqueRef); OnConnectionResult(false, Messages.CONNECTION_RESTRICTED_MESSAGE, error); } else if (error is ServerNotSupported) { EndConnect(true, task, false); log.Info(error.Message); OnConnectionResult(false, error.Message, error); } else if (task.Cancelled) { task.Connected = false; log.InfoFormat("IXenConnection: closing connection to {0}", this.HostnameWithPort); EndConnect(true, task, false); OnConnectionClosed(); } else if (task.Connected) { HandleConnectionLost(task, pool, PoolOpaqueRef); } else { // We never connected string reason = GetReason(error); log.WarnFormat("IXenConnection: failed to connect to {0}: {1}", HostnameWithPort, reason); Failure f = error as Failure; if (f != null && f.ErrorDescription[0] == Failure.HOST_IS_SLAVE) { //do not log an event in this case } else if (error is ConnectionExists) { //do not log an event in this case } else { // Create a new log message to say the connection attempt failed string title = string.Format(Messages.CONNECTION_FAILED_TITLE, HostnameWithPort); ActionBase n = new ActionBase(title, reason, false, true, reason); SetPoolAndHostInAction(n, pool, PoolOpaqueRef); } // We only want to continue the master search in certain circumstances if (FindingNewMaster && (error is WebException || (f != null && f.ErrorDescription[0] != Failure.RBAC_PERMISSION_DENIED))) { if (f != null) { if (f.ErrorDescription[0] == XenAPI.Failure.HOST_IS_SLAVE) { log.DebugFormat("Found a slave of {0} at {1}; redirecting to the master at {2}", LastMasterHostname, Hostname, f.ErrorDescription[1]); Hostname = f.ErrorDescription[1]; OnConnectionMessageChanged(string.Format(Messages.CONNECTION_REDIRECTING, LastMasterHostname, Hostname)); ReconnectMaster(); } else if (f.ErrorDescription[0] == XenAPI.Failure.HOST_STILL_BOOTING) { log.DebugFormat("Found a slave of {0} at {1}, but it's still booting; trying the next pool member", LastMasterHostname, Hostname); MaybeStartNextSlaveTimer(reason, error); } else { log.DebugFormat("Found a slave of {0} at {1}, but got a failure; trying the next pool member", LastMasterHostname, Hostname); MaybeStartNextSlaveTimer(reason, error); } } else if (PoolMemberRemaining()) { log.DebugFormat("Connection to {0} failed; trying the next pool member", Hostname); MaybeStartNextSlaveTimer(reason, error); } else { if (ExpectDisruption || DateTime.Now - FindingNewMasterStartedAt < SEARCH_NEW_MASTER_STOP_AFTER) { log.DebugFormat("While trying to find a connection for {0}, tried to connect to every remembered host. Will now loop back through pool members again.", this.HostnameWithPort); lock (PoolMembersLock) { PoolMemberIndex = 0; } MaybeStartNextSlaveTimer(reason, error); } else if (LastMasterHostname != "") { log.DebugFormat("Stopping search for new master for {0}: timeout reached without success. Trying the old master one last time", LastConnectionFullName); FindingNewMaster = false; Hostname = LastMasterHostname; ReconnectMaster(); } else { OnConnectionResult(false, reason, error); } } } else { OnConnectionResult(false, reason, error); } } } } private void SetServerTimeOffset(Session session, string master_opaqueref) { DateTime t = Host.get_servertime(session, master_opaqueref); ServerTimeOffset = DateTime.UtcNow - t; } /// <summary> /// Called when a connection that had been made successfully is then lost. /// </summary> /// <param name="task"></param> /// <param name="pool"></param> /// <param name="poolopaqueref"></param> private void HandleConnectionLost(ConnectTask task, Pool pool, string poolopaqueref) { task.Connected = false; log.WarnFormat("Lost connection to {0}", this.HostnameWithPort); // Cancel all current actions to do with this connection if (!ExpectDisruption) { InvokeHelper.Invoke(() => ConnectionsManager.CancelAllActions(this)); } // Save list of addresses of current hosts in pool List<string> members = new List<string>(); foreach (Host host in Cache.Hosts) { if (!string.IsNullOrEmpty(host.address)) members.Add(host.address); } // Save master's address so we don't try to reconnect to it first Host master = Helpers.GetMaster(this); // Save ha_enabled status before we clear the cache bool ha_enabled = IsHAEnabled(); // NB line below clears the cache EndConnect(true, task, false); string description; LastMasterHostname = Hostname; string poolName = pool.Name(); if (string.IsNullOrEmpty(poolName)) { LastConnectionFullName = HostnameWithPort; } else { LastConnectionFullName = string.Format("'{0}' ({1})", poolName, HostnameWithPort); } if (!EventNextBlocked && (MasterMayChange || ha_enabled) && members.Count > 1) { log.DebugFormat("Will now try to connect to another pool member"); lock (PoolMembersLock) { PoolMembers.Clear(); PoolMembers.AddRange(members); PoolMemberIndex = 0; // Don't reconnect to the master straight away, try a slave first if (master != null && PoolMembers[0] == master.address && PoolMembers.Count > 1) { PoolMemberIndex = 1; } } FindingNewMaster = true; // Record the time at which we started the new master search. FindingNewMasterStartedAt = DateTime.Now; StartReconnectMasterTimer(); description = string.Format(Messages.CONNECTION_LOST_NOTICE_MASTER_IN_X_SECONDS, LastConnectionFullName, XenConnection.SEARCH_NEW_MASTER_TIMEOUT_MS / 1000); log.DebugFormat("Beginning search for new master; will give up after {0} seconds", SEARCH_NEW_MASTER_STOP_AFTER.TotalSeconds); } else { log.DebugFormat("Will retry connection to {0} in {1} ms.", LastConnectionFullName, ReconnectHostTimeoutMs); StartReconnectSingleHostTimer(); description = string.Format(Messages.CONNECTION_LOST_RECONNECT_IN_X_SECONDS, LastConnectionFullName, ReconnectHostTimeoutMs / 1000); } string title = string.Format(Messages.CONNECTION_LOST_NOTICE_TITLE, LastConnectionFullName); ActionBase n = new ActionBase(title, description, false, true, description); SetPoolAndHostInAction(n, pool, poolopaqueref); OnConnectionLost(); } private bool PoolMemberRemaining() { lock (PoolMembersLock) { return PoolMemberIndex < PoolMembers.Count; } } private bool IsHAEnabled() { Pool pool = Helpers.GetPoolOfOne(this); return pool != null && pool.ha_enabled; } /// <summary> /// When we lose connection to a non-HA host, the timeout before we try reconnecting. /// </summary> private const int RECONNECT_HOST_TIMEOUT_MS = 120 * 1000; private const int RECONNECT_SHORT_TIMEOUT_MS = 5 * 1000; private int ReconnectHostTimeoutMs { get { if (EventNextBlocked || IsSimulatorConnection) return RECONNECT_SHORT_TIMEOUT_MS; else return RECONNECT_HOST_TIMEOUT_MS; } } /// <summary> /// When HA is enabled, the timeout after losing connection to the master before we start searching for a new master. /// i.e. This should be the time it takes master failover to be sorted out on the server, plus a margin. /// NB we already have an additional built-in delay - it takes time for us to decide that the host is not responding, /// and kill the connection to the dead host, before starting the search. /// </summary> private const int SEARCH_NEW_MASTER_TIMEOUT_MS = 60 * 1000; /// <summary> /// When HA is enabled, and going through each of the slaves to try and find the new master, the time between failing /// to connect to one slave and trying to connect to the next in the list. /// </summary> private const int SEARCH_NEXT_SLAVE_TIMEOUT_MS = 15 * 1000; /// <summary> /// When going through each of the remembered members of the pool looking for the new master, don't start another pass /// through connecting to each of the hosts if we've already been looking for this long. /// </summary> private static readonly TimeSpan SEARCH_NEW_MASTER_STOP_AFTER = TimeSpan.FromMinutes(6); private void StartReconnectSingleHostTimer() { ReconnectionTimer = new System.Threading.Timer((TimerCallback)ReconnectSingleHostTimer, null, ReconnectHostTimeoutMs, ReconnectHostTimeoutMs); } private void StartReconnectMasterTimer() { StartReconnectMasterTimer(SEARCH_NEW_MASTER_TIMEOUT_MS); } private void MaybeStartNextSlaveTimer(string reason, Exception error) { if (PoolMemberRemaining()) StartReconnectMasterTimer(SEARCH_NEXT_SLAVE_TIMEOUT_MS); else OnConnectionResult(false, reason, error); } private void StartReconnectMasterTimer(int timeout) { OnConnectionMessageChanged(string.Format(Messages.CONNECTION_WILL_RETRY_SLAVE, LastConnectionFullName.Ellipsise(25) , timeout / 1000)); ReconnectionTimer = new System.Threading.Timer((TimerCallback)ReconnectMasterTimer, null, timeout, Timeout.Infinite); } private void ReconnectSingleHostTimer(object state) { if (IsConnected || !ConnectionsManager.XenConnectionsContains(this)) { log.DebugFormat("Host {0} already reconnected", Hostname); if (ReconnectionTimer != null) { ReconnectionTimer.Dispose(); ReconnectionTimer = null; } return; } if (!ExpectDisruption) // only try once unless expect disruption { if (ReconnectionTimer != null) { ReconnectionTimer.Dispose(); ReconnectionTimer = null; } } log.DebugFormat("Reconnecting to server {0}...", Hostname); if (!XenAdminConfigManager.Provider.Exiting) { InvokeHelper.Invoke(delegate() { /*ConnectionResult += new EventHandler<ConnectionResultEventArgs>(XenConnection_ConnectionResult); CachePopulated += new EventHandler<EventArgs>(XenConnection_CachePopulated);*/ BeginConnect(false, _promptForNewPassword); }); OnConnectionReconnecting(); } } /*void XenConnection_CachePopulated(object sender, EventArgs e) { CachePopulated -= new EventHandler<EventArgs>(XenConnection_CachePopulated); Program.MainWindow.CommandInterface.TrySelectNewObjectInTree(this, false, true, false); } void XenConnection_ConnectionResult(object sender, ConnectionResultEventArgs e) { if (!e.Connected) CachePopulated -= new EventHandler<EventArgs>(XenConnection_CachePopulated); }*/ private void ReconnectMasterTimer(object state) { if (IsConnected || !ConnectionsManager.XenConnectionsContains(this)) { log.DebugFormat("Master has been found for {0} at {1}", LastMasterHostname, Hostname); return; } lock (PoolMembersLock) { if (PoolMemberIndex < PoolMembers.Count) { Hostname = PoolMembers[PoolMemberIndex]; PoolMemberIndex++; } } OnConnectionMessageChanged(string.Format(Messages.CONNECTION_RETRYING_SLAVE, LastConnectionFullName.Ellipsise(25), Hostname)); ReconnectMaster(); } private void ReconnectMaster() { // Add an informational entry to the log string title = string.Format(Messages.CONNECTION_FINDING_MASTER_TITLE, LastConnectionFullName); string descr = string.Format(Messages.CONNECTION_FINDING_MASTER_DESCRIPTION, LastConnectionFullName, Hostname); ActionBase action = new ActionBase(title, descr, false, true); SetPoolAndHostInAction(action, null, PoolOpaqueRef); log.DebugFormat("Looking for master for {0} on {1}...", LastConnectionFullName, Hostname); if (!XenAdminConfigManager.Provider.Exiting) { InvokeHelper.Invoke(delegate() { /*ConnectionResult += new EventHandler<ConnectionResultEventArgs>(XenConnection_ConnectionResult); CachePopulated += new EventHandler<EventArgs>(XenConnection_CachePopulated);*/ BeginConnect(false, _promptForNewPassword); }); OnConnectionReconnecting(); } } private Pool getAPool(ICache objects, out string opaqueref) { foreach (Pool pool in objects.Pools) { opaqueref = pool.opaque_ref; return pool; } System.Diagnostics.Trace.Assert(false); opaqueref = null; return null; } private void OnClearingCache() { if (ClearingCache != null) ClearingCache(this, new EventArgs()); } private void OnConnectionResult(bool connected, string reason, Exception error) { if (ConnectionResult != null) ConnectionResult(this, new ConnectionResultEventArgs(connected, reason, error)); OnConnectionStateChanged(); } private void OnConnectionClosed() { if (ConnectionClosed != null) ConnectionClosed(this, null); OnConnectionStateChanged(); } private void OnConnectionLost() { if (ConnectionLost != null) ConnectionLost(this, null); OnConnectionStateChanged(); } private void OnConnectionReconnecting() { if (ConnectionReconnecting != null) ConnectionReconnecting(this, null); OnConnectionStateChanged(); } private void OnBeforeConnectionEnd() { if (BeforeConnectionEnd != null) BeforeConnectionEnd(this, null); } private void OnConnectionStateChanged() { if (ConnectionStateChanged != null) ConnectionStateChanged(this, null); } private void OnConnectionMessageChanged(string message) { if (ConnectionMessageChanged != null) ConnectionMessageChanged(this, new ConnectionMessageChangedEventArgs(message)); } public void OnBeforeMajorChange(bool background) { if (BeforeMajorChange != null) BeforeMajorChange(this, new ConnectionMajorChangeEventArgs(background)); } public void OnAfterMajorChange(bool background) { if (AfterMajorChange != null) AfterMajorChange(this, new ConnectionMajorChangeEventArgs(background)); } private void OnXenObjectsUpdated() { // Using BeginInvoke here means that the XenObjectsUpdated event gets fired after any // CollectionChanged events fired by ChangeableDictionary during Cache.UpdateFrom. InvokeHelper.BeginInvoke(delegate() { if (XenObjectsUpdated != null) XenObjectsUpdated(this, null); }); } public T TryResolveWithTimeout<T>(XenRef<T> t) where T : XenObject<T> { log.DebugFormat("Resolving {0} {1}", t, t.opaque_ref); int timeout = 120; // two minutes; while (timeout > 0) { T obj = Resolve(t); if (obj != null) return obj; Thread.Sleep(1000); timeout--; } if (typeof(T) == typeof(Host)) throw new Failure(Failure.HOST_OFFLINE); throw new Failure(Failure.HANDLE_INVALID, typeof(T).Name, t.opaque_ref); } /// <summary> /// Stub to Cache.Resolve /// </summary> /// <typeparam name="T"></typeparam> /// <param name="xenRef">May be null, in which case null is returned.</param> /// <returns></returns> public virtual T Resolve<T>(XenRef<T> xenRef) where T : XenObject<T> { return Cache.Resolve(xenRef); } /// <summary> /// Resolve every object in the given list. Skip any references that don't resolve. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="xenRefs">May be null, in which case the empty list is returned.</param> /// <returns></returns> public List<T> ResolveAll<T>(IEnumerable<XenRef<T>> xenRefs) where T : XenObject<T> { List<T> result = new List<T>(); if (xenRefs != null) { foreach (XenRef<T> xenRef in xenRefs) { T o = Resolve(xenRef); if (o != null) result.Add(o); } } return result; } public List<VDI> ResolveAllShownXenModelObjects(List<XenRef<VDI>> xenRefs, bool showHiddenObjects) { List<VDI> result = ResolveAll(xenRefs); result.RemoveAll(vdi => !vdi.Show(showHiddenObjects)); return result; } public static T FindByUUIDXenObject<T>(string uuid) where T : XenObject<T> { foreach (IXenConnection c in ConnectionsManager.XenConnectionsCopy) { T o = c.Cache.Find_By_Uuid<T>(uuid); if (o != null) return o; } return null; } /// <summary> /// Find a XenObject corresponding to the given XenRef, or null if no such object is found. /// </summary> public static T FindByRef<T>(XenRef<T> needle) where T : XenObject<T> { foreach (IXenConnection c in ConnectionsManager.XenConnectionsCopy) { T o = c.Resolve<T>(needle); if (o != null) return o; } return null; } public static string ConnectedElsewhere(string hostname) { lock (ConnectionsManager.ConnectionsLock) { foreach (IXenConnection connection in ConnectionsManager.XenConnections) { Pool pool = Helpers.GetPoolOfOne(connection); if (pool == null) continue; Host master = connection.Resolve(pool.master); if (master == null) continue; if (master.address == hostname) { // we have tried to connect to a slave that is a member of a pool we are already connected to. return pool.Name(); } } } return null; } #region IXmlSerializable Members public System.Xml.Schema.XmlSchema GetSchema() { return null; } public void ReadXml(System.Xml.XmlReader reader) { Hostname = reader["Hostname"]; } public void WriteXml(System.Xml.XmlWriter writer) { writer.WriteElementString("Hostname",Hostname); } #endregion #region IDisposable Members /// <summary> /// Disposing this class will make it unusable - make sure you want to do this /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private bool disposed; protected virtual void Dispose(bool disposing) { if(!disposed) { if (disposing) { ClearingCache = null; CachePopulated = null; ConnectionResult = null; ConnectionStateChanged = null; ConnectionLost = null; ConnectionClosed = null; ConnectionReconnecting = null; BeforeConnectionEnd = null; ConnectionMessageChanged = null; BeforeMajorChange = null; AfterMajorChange = null; XenObjectsUpdated = null; TimeSkewUpdated = null; if (ReconnectionTimer != null) ReconnectionTimer.Dispose(); if (cacheUpdateTimer != null) cacheUpdateTimer.Dispose(); } disposed = true; } } #endregion } public class ExpressRestriction : DisconnectionException { public readonly string HostName; public readonly string ExistingHostName; public ExpressRestriction(string HostName, string ExistingHostName) { this.HostName = HostName; this.ExistingHostName = ExistingHostName; } public override string Message { get { return string.Format(Messages.LICENSE_RESTRICTION_MESSAGE, HostName, ExistingHostName); } } } public class ServerNotSupported : DisconnectionException { public override string Message { get { return Messages.SERVER_TOO_OLD; } } } public class ConnectionExists : DisconnectionException { public IXenConnection connection; public ConnectionExists(IXenConnection connection) { this.connection = connection; } public override string Message { get { if (connection != null) return string.Format(Messages.CONNECTION_EXISTS, connection.Hostname); else return Messages.CONNECTION_EXISTS_NULL; } } public virtual string GetDialogMessage(IXenConnection _this) { Pool p = Helpers.GetPool(connection); if (p == null) return String.Format(Messages.ALREADY_CONNECTED, _this.Hostname); return String.Format(Messages.SLAVE_ALREADY_CONNECTED, _this.Hostname, p.Name()); } } class BadRestoreDetected : ConnectionExists { public BadRestoreDetected(IXenConnection xc) : base(xc) { } public override string Message { get { return String.Format(Messages.BAD_RESTORE_DETECTED, connection.Name); } } public override string GetDialogMessage(IXenConnection _this) { return Message; } } }
40.021196
197
0.501971
[ "BSD-2-Clause" ]
MihaelaStoica/xenadmin
XenModel/Network/XenConnection.cs
84,967
C#
๏ปฟusing System; using System.IO; using System.Linq; using System.Reflection; using Microsoft.Build.Evaluation; using Moq; using NuGet.CommandLine.Test; using Xunit; namespace NuGet.CommandLine { public class ProjectFactoryTest { [Fact] public void ProjectFactoryInitializesPropertiesForPreprocessor() { // arrange const string inputSpec = @"<?xml version=""1.0""?> <package> <metadata> <id>$id$</id> <version>$version$</version> <description>$description$</description> <authors>$author$</authors> <copyright>$copyright$</copyright> <licenseUrl>http://nuget.codeplex.com/license</licenseUrl> <projectUrl>http://nuget.codeplex.com</projectUrl> <tags>nuget</tags> </metadata> </package>"; var metadata = new ManifestMetadata { Id = "ProjectFactoryTest", Version = "2.0.30619.9000", Title = "NuGet.Test", Description = "", Copyright = "\x00a9 Outercurve. All rights reserved.", Authors = "Outercurve Foundation", }; var projectMock = new Mock<Project>(); var msbuildDirectory = NuGet.CommandLine.MsBuildUtility.GetMsbuildDirectory("4.0", console: null); var factory = new ProjectFactory(msbuildDirectory, projectMock.Object); // act var author = factory.InitializeProperties(metadata); var actual = Preprocessor.Process(inputSpec.AsStream(), factory, false); // assert Assert.Equal("Outercurve Foundation", author); const string expected = @"<?xml version=""1.0""?> <package> <metadata> <id>ProjectFactoryTest</id> <version>2.0.30619.9000</version> <description></description> <authors>Outercurve Foundation</authors> <copyright>ยฉ Outercurve. All rights reserved.</copyright> <licenseUrl>http://nuget.codeplex.com/license</licenseUrl> <projectUrl>http://nuget.codeplex.com</projectUrl> <tags>nuget</tags> </metadata> </package>"; Assert.Equal(expected, actual); } [Fact] public void ProjectFactoryCanCompareContentsOfReadOnlyFile() { var us = Assembly.GetExecutingAssembly(); var sourcePath = us.Location; var targetFile = new PhysicalPackageFile { SourcePath = sourcePath }; var fullPath = sourcePath + "readOnly"; File.Copy(sourcePath, fullPath); File.SetAttributes(fullPath, FileAttributes.ReadOnly); try { var actual = ProjectFactory.ContentEquals(targetFile, fullPath); Assert.Equal(true, actual); } finally { File.SetAttributes(fullPath, FileAttributes.Normal); File.Delete(fullPath); } } /// <summary> /// This test ensures that when building a nuget package from a project file (e.g. .csproj) /// that if the case doesn't match between a file in the .nuspec file and the file on disk /// that NuGet won't attempt to add it again. /// </summary> /// <example> /// Given: The .nuspec file contains &quot;Assembly.xml&quot; and the file on disk is &quot;Assembly.XML.&quot; /// Command: nuget pack Assembly.csproj /// Output: Exception: An item with the key already exists /// </example> [Fact] public void EnsureProjectFactoryDoesNotAddFileThatIsAlreadyInPackage() { // Setup var nugetexe = Util.GetNuGetExePath(); var workingDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); try { // Arrange Directory.CreateDirectory(workingDirectory); File.WriteAllText(Path.Combine(workingDirectory, "Assembly.nuspec"), GetNuspecContent()); File.WriteAllText(Path.Combine(workingDirectory, "Assembly.csproj"), GetProjectContent()); File.WriteAllText(Path.Combine(workingDirectory, "Source.cs"), GetSourceFileContent()); var projPath = Path.Combine(workingDirectory, "Assembly.csproj"); // Act var r = CommandRunner.Run( nugetexe, workingDirectory, "pack Assembly.csproj -build", waitForExit: true); var package = new OptimizedZipPackage(Path.Combine(workingDirectory, "Assembly.1.0.0.nupkg")); var files = package.GetFiles().Select(f => f.Path).ToArray(); // Assert Assert.Equal(0, r.Item1); Array.Sort(files); Assert.Equal(files, new[] { @"lib\net45\Assembly.dll", @"lib\net45\Assembly.xml" }); } finally { // Teardown try { Directory.Delete(workingDirectory, true); } catch { } } } private static string GetNuspecContent() { return @"<?xml version=""1.0"" encoding=""utf-8""?> <package xmlns=""http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd""> <metadata> <id>Assembly</id> <version>1.0.0</version> <title /> <authors>Author</authors> <owners /> <requireLicenseAcceptance>false</requireLicenseAcceptance> <description>Description for Assembly.</description> </metadata> <files> <file src=""bin\Debug\Assembly.dll"" target=""lib\net45\Assembly.dll"" /> <file src=""bin\Debug\Assembly.xml"" target=""lib\net45\Assembly.xml"" /> </files> </package>"; } private static string GetProjectContent() { return @"<?xml version=""1.0"" encoding=""utf-8""?> <Project ToolsVersion=""4.0"" DefaultTargets=""Build"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Import Project=""$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"" Condition=""Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"" /> <PropertyGroup> <Configuration Condition="" '$(Configuration)' == '' "">Debug</Configuration> <Platform Condition="" '$(Platform)' == '' "">AnyCPU</Platform> <ProjectGuid>{CD08AD03-0CBF-47B1-8A95-D9E9C2330F50}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Assembly</RootNamespace> <AssemblyName>Assembly</AssemblyName> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ""> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DocumentationFile>bin\Debug\Assembly.XML</DocumentationFile> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> </PropertyGroup> <PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ""> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include=""System"" /> <Reference Include=""System.Core"" /> <Reference Include=""System.Xml.Linq"" /> <Reference Include=""System.Data.DataSetExtensions"" /> <Reference Include=""Microsoft.CSharp"" /> <Reference Include=""System.Data"" /> <Reference Include=""System.Xml"" /> </ItemGroup> <ItemGroup> <Compile Include=""Source.cs"" /> </ItemGroup> <Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" /> </Project>"; } private static string GetSourceFileContent() { return @"using System; namespace Assembly { /// <summary>Source</summary> public class Source { // Does nothing } }"; } } }
37.16087
190
0.595063
[ "Apache-2.0" ]
NuGetArchive/NuGet.PackageManagement
test/NuGet.CommandLine.Test/ProjectFactoryTest.cs
8,550
C#
๏ปฟusing Komodex.Common; using Komodex.DACP.Containers; using Komodex.DACP.Items; using Komodex.DACP.Queries; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Komodex.DACP.Groups { public class Album : DacpGroup { public Album(DacpContainer container, DacpNodeDictionary nodes) : base(container, nodes) { } public string ArtistName { get; private set; } protected override void ProcessNodes(DacpNodeDictionary nodes) { base.ProcessNodes(nodes); ArtistName = nodes.GetString("asaa"); } internal override DacpQueryElement GroupQuery { get { var query = base.GroupQuery; if (Client.ServerSupportsPlayQueue) return query; if (string.IsNullOrEmpty(ArtistName)) return query; return DacpQueryCollection.And(query, DacpQueryCollection.Or(DacpQueryPredicate.Is("daap.songartist", ArtistName), DacpQueryPredicate.Is("daap.songalbumartist", ArtistName))); } } #region Songs private List<Song> _songs; public async Task<List<Song>> GetSongsAsync() { if (_songs != null) return _songs; DacpRequest request = Container.GetItemsRequest(ItemQuery); _songs = await Client.GetListAsync(request, n => new Song(Container, n)).ConfigureAwait(false); return _songs; } #endregion #region Commands public async Task<bool> SendPlayCommandAsync(PlayQueueMode mode = PlayQueueMode.Replace) { DacpRequest request; if (Client.ServerSupportsPlayQueue) request = Database.GetPlayQueueEditRequest("add", GroupQuery, mode, "album"); else request = Database.GetCueSongRequest(ItemQuery, "album", 0); try { await Client.SendRequestAsync(request).ConfigureAwait(false); } catch { return false; } return true; } public async Task<bool> SendPlaySongCommandAsync(Song song, PlayQueueMode mode = PlayQueueMode.Replace) { DacpRequest request; if (Client.ServerSupportsPlayQueue) { request = Database.GetPlayQueueEditRequest("add", DacpQueryPredicate.Is("dmap.itemid", song.ID), mode, "album"); request.QueryParameters["queuefilter"] = string.Format("album:{0}", PersistentID); } else { var songs = await GetSongsAsync(); int index = songs.FindIndex(s => s.ID == song.ID); if (index < 0) return false; request = Database.GetCueSongRequest(ItemQuery, "album", index); } try { await Client.SendRequestAsync(request).ConfigureAwait(false); } catch { return false; } return true; } public async Task<bool> SendShuffleCommandAsync() { DacpRequest request; if (Client.ServerSupportsPlayQueue) request = Database.GetPlayQueueEditRequest("add", GroupQuery, PlayQueueMode.Shuffle, "album"); else request = Database.GetCueShuffleRequest(ItemQuery, "album"); try { await Client.SendRequestAsync(request).ConfigureAwait(false); } catch { return false; } return true; } #endregion } }
32.981818
191
0.585998
[ "MIT" ]
misenhower/WPRemote
CommonLibraries/Libraries/Komodex.DACP (Win8)/Groups/Album.cs
3,630
C#
using System; using UltimaOnline; namespace UltimaOnline.Items { public class PhillipsWoodenSteed : MonsterStatuette { [Constructable] public PhillipsWoodenSteed() : base(MonsterStatuetteType.PhillipsWoodenSteed) { LootType = LootType.Regular; } public override bool ForceShowProperties { get { return ObjectPropertyList.Enabled; } } public PhillipsWoodenSteed(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(); } } }
24.764706
96
0.586698
[ "MIT" ]
netcode-gamer/game.ultimaonline.io
UltimaOnline.Data/Items/Minor Artifacts/PhillipsWoodenSteed.cs
842
C#
๏ปฟusing Oxide.Core; using Oxide.Core.Libraries; using Oxide.Core.Plugins; using System.Collections.Generic; using System.Linq; using VRage.Game.ModAPI; namespace Oxide.Game.MedievalEngineers.Libraries { /// <summary> /// A library containing functions for adding console and chat commands /// </summary> public class Command : Library { public override bool IsGlobal => false; private struct PluginCallback { public readonly Plugin Plugin; public readonly string Name; public PluginCallback(Plugin plugin, string name) { Plugin = plugin; Name = name; } } private class ConsoleCommand { public readonly string Name; public readonly Plugin Plugin; public readonly string CallbackName; public ConsoleCommand(string name, Plugin plugin, string callback) { Name = name; Plugin = plugin; CallbackName = callback; } } private class ChatCommand { public readonly string Name; public readonly Plugin Plugin; public readonly string CallbackName; public ChatCommand(string name, Plugin plugin, string callback) { Name = name; Plugin = plugin; CallbackName = callback; } } // All chat commands that plugins have registered private readonly Dictionary<string, ChatCommand> chatCommands; // All console commands that plugins have registered private readonly Dictionary<string, ConsoleCommand> consoleCommands; // A reference to the plugin removed callback private readonly Dictionary<Plugin, Event.Callback<Plugin, PluginManager>> pluginRemovedFromManager; /// <summary> /// Initializes a new instance of the Command class /// </summary> public Command() { chatCommands = new Dictionary<string, ChatCommand>(); consoleCommands = new Dictionary<string, ConsoleCommand>(); pluginRemovedFromManager = new Dictionary<Plugin, Event.Callback<Plugin, PluginManager>>(); } /// <summary> /// Adds a chat command /// </summary> /// <param name="command"></param> /// <param name="plugin"></param> /// <param name="callbackName"></param> [LibraryFunction("AddChatCommand")] public void AddChatCommand(string command, Plugin plugin, string callbackName) { var commandName = command.ToLowerInvariant(); ChatCommand cmd; if (chatCommands.TryGetValue(commandName, out cmd)) { var previousPluginName = cmd.Plugin?.Name ?? "an unknown plugin"; var newPluginName = plugin?.Name ?? "An unknown plugin"; var msg = $"{newPluginName} has replaced the '{commandName}' chat command previously registered by {previousPluginName}"; Interface.Oxide.LogWarning(msg); } cmd = new ChatCommand(commandName, plugin, callbackName); // Add the new command to collections chatCommands[commandName] = cmd; // Hook the unload event if (plugin != null && !pluginRemovedFromManager.ContainsKey(plugin)) pluginRemovedFromManager[plugin] = plugin.OnRemovedFromManager.Add(plugin_OnRemovedFromManager); } /// <summary> /// Adds a console command /// </summary> /// <param name="command"></param> /// <param name="plugin"></param> /// <param name="callbackName"></param> [LibraryFunction("AddConsoleCommand")] public void AddConsoleCommand(string command, Plugin plugin, string callbackName) { var commandName = command.ToLowerInvariant(); ConsoleCommand cmd; if (consoleCommands.TryGetValue(commandName, out cmd)) { var previousPluginName = cmd.Plugin?.Name ?? "an unknown plugin"; var newPluginName = plugin?.Name ?? "An unknown plugin"; var msg = $"{newPluginName} has replaced the '{commandName}' console command previously registered by {previousPluginName}"; Interface.Oxide.LogWarning(msg); } cmd = new ConsoleCommand(commandName, plugin, callbackName); // Add the new command to collections consoleCommands[commandName] = cmd; // Hook the unload event if (plugin != null && !pluginRemovedFromManager.ContainsKey(plugin)) pluginRemovedFromManager[plugin] = plugin.OnRemovedFromManager.Add(plugin_OnRemovedFromManager); } /// <summary> /// Handles the specified chat command /// </summary> /// <param name="session"></param> /// <param name="command"></param> /// <param name="args"></param> internal bool HandleChatCommand(IMyPlayer session, string command, string[] args) { ChatCommand cmd; if (!chatCommands.TryGetValue(command.ToLowerInvariant(), out cmd)) return false; cmd.Plugin.CallHook(cmd.CallbackName, session, command, args); return true; } /// <summary> /// Handles the specified console command /// </summary> /// <param name="command"></param> /// <param name="args"></param> /// <returns></returns> internal object HandleConsoleCommand(string command, string[] args) { ConsoleCommand cmd; if (!consoleCommands.TryGetValue(command.ToLowerInvariant(), out cmd)) return null; cmd.Plugin.CallHook(cmd.CallbackName, command, args); return true; } /// <summary> /// Called when a plugin has been removed from manager /// </summary> /// <param name="sender"></param> /// <param name="manager"></param> private void plugin_OnRemovedFromManager(Plugin sender, PluginManager manager) { // Remove all console commands which were registered by the plugin foreach (var cmd in consoleCommands.Values.Where(c => c.Plugin == sender).ToArray()) consoleCommands.Remove(cmd.Name); // Remove all chat commands which were registered by the plugin foreach (var cmd in chatCommands.Values.Where(c => c.Plugin == sender).ToArray()) chatCommands.Remove(cmd.Name); // Unhook the event Event.Callback<Plugin, PluginManager> callback; if (pluginRemovedFromManager.TryGetValue(sender, out callback)) { callback.Remove(); pluginRemovedFromManager.Remove(sender); } } } }
37.843243
140
0.590201
[ "MIT" ]
CryptoJones/Oxide
Games/Oxide.MedievalEngineers/Libraries/Command.cs
7,003
C#
๏ปฟnamespace SentimentAnalysis.AzureMachineLearning.Tests.Settings { using System.Configuration; using System.Diagnostics; using DotNetTestHelper; using Microsoft.VisualStudio.TestTools.UnitTesting; using AzureMachineLearningSettings = AzureMachineLearning.AzureMachineLearningSettings; [TestClass] public abstract class SettingsTest { protected AzureMachineLearningSettings Sut { get; set; } [TestInitialize] public void Init() { Sut = new SutBuilder<AzureMachineLearningSettings>().Build(); } [TestCleanup] public void Cleanup() { ConfigurationManager.AppSettings[Constants.PositiveSentimentThresholdConfigKey] = Constants.DefaultPositiveSentimentThreshold.ToString(); ConfigurationManager.AppSettings[Constants.NegativeSentimentThresholdConfigKey] = Constants.DefaultNegativeSentimentThreshold.ToString(); ConfigurationManager.AppSettings[Constants.ServiceBaseUriConfigKey] = Constants.DefaultServiceBaseUri; ConfigurationManager.AppSettings[Constants.BatchItemLimitConfigKey] = Constants.DefaultBatchItemLimit.ToString(); } } }
41.37931
149
0.74
[ "Unlicense" ]
bfdill/SentimentAnalysis
SentimentAnalysis.AzureMachineLearning.Tests/Settings/SettingsTest.cs
1,202
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the config-2014-11-12.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ConfigService.Model { /// <summary> /// This is the response object from the BatchGetResourceConfig operation. /// </summary> public partial class BatchGetResourceConfigResponse : AmazonWebServiceResponse { private List<BaseConfigurationItem> _baseConfigurationItems = new List<BaseConfigurationItem>(); private List<ResourceKey> _unprocessedResourceKeys = new List<ResourceKey>(); /// <summary> /// Gets and sets the property BaseConfigurationItems. /// <para> /// A list that contains the current configuration of one or more resources. /// </para> /// </summary> public List<BaseConfigurationItem> BaseConfigurationItems { get { return this._baseConfigurationItems; } set { this._baseConfigurationItems = value; } } // Check to see if BaseConfigurationItems property is set internal bool IsSetBaseConfigurationItems() { return this._baseConfigurationItems != null && this._baseConfigurationItems.Count > 0; } /// <summary> /// Gets and sets the property UnprocessedResourceKeys. /// <para> /// A list of resource keys that were not processed with the current response. The unprocessesResourceKeys /// value is in the same form as ResourceKeys, so the value can be directly provided to /// a subsequent BatchGetResourceConfig operation. If there are no unprocessed resource /// keys, the response contains an empty unprocessedResourceKeys list. /// </para> /// </summary> [AWSProperty(Min=1, Max=100)] public List<ResourceKey> UnprocessedResourceKeys { get { return this._unprocessedResourceKeys; } set { this._unprocessedResourceKeys = value; } } // Check to see if UnprocessedResourceKeys property is set internal bool IsSetUnprocessedResourceKeys() { return this._unprocessedResourceKeys != null && this._unprocessedResourceKeys.Count > 0; } } }
38.6
115
0.65965
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/ConfigService/Generated/Model/BatchGetResourceConfigResponse.cs
3,088
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.Threading.Tasks; namespace NuGet.Services.Configuration { /// <summary> /// Injects a <see cref="Configuration"/> subclass with configuration. /// </summary> public interface IConfigurationFactory { /// <summary> /// Injects a <see cref="Configuration"/> subclass with configuration. /// Enumerates through all of the properties of <typeparam name="T">T</typeparam> and injects configuration using the name of each property. /// </summary> /// <typeparam name="T"> /// Subclass of configuration to inject with configuration. /// Configuration will only be injected into properties of the class. /// </typeparam> /// <returns>A <typeparam name="T">T</typeparam> with all of its properties injected with configuration.</returns> Task<T> Get<T>() where T : Configuration, new(); } }
42.76
148
0.665108
[ "Apache-2.0" ]
DalavanCloud/ServerCommon
src/NuGet.Services.Configuration/IConfigurationFactory.cs
1,071
C#
๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using XFDraw.Numerics; namespace XFDraw { public class LinearGradientBrush : GradientBrush { public LinearGradientBrush() { StartPoint = Vector2.Zero; EndPoint = Vector2.One; } public Vector2 StartPoint { get; set; } public Vector2 EndPoint { get; set; } } }
20.636364
52
0.643172
[ "MIT" ]
billreiss/XFDraw
XFDraw/LinearGradientBrush.cs
456
C#
๏ปฟusing System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Cache; using System.Text; /* * http://www.c-sharpcorner.com/UploadFile/0d5b44/ftp-using-C-Sharp-net/ */ /* static void Main(string[] args) { FTPOperations ops = new FTPOperations("user", "pass", "http://mysite.com/") string listing = ops.ListFtpDrive(); ops.PostFileToFTP(@"C:\TMP\file01.txt", @"fileo1.txt"); ops.GetFileFromFTP(@"fileo1.txt", (@"C:\TMP\file01-copy.txt"); } */ namespace GM.OnlineAccess { public class FTPOperations { string username { get; set; } string password { get; set; } string ftpAddress { get; set; } public FTPOperations(string _username, string _password, string _ftpAddress) { username = _username; password = _password; ftpAddress = _ftpAddress; } public string ListFtpDrive() { // show all the contents and directories of your FTP Drive try { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpAddress); request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.CacheIfAvailable); request.Method = WebRequestMethods.Ftp.ListDirectoryDetails; request.Credentials = new NetworkCredential(username, password); request.KeepAlive = false; request.UseBinary = true; request.UsePassive = true; FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); StreamReader reader = new StreamReader(responseStream); StringBuilder sb = new StringBuilder(); //Console.WriteLine(reader.ReadToEnd()); sb.Append(reader.ReadToEnd()); //Console.WriteLine("Directory List Complete, status {0}", response.StatusDescription); sb.Append($"Directory List Complete, status {response.StatusDescription}"); reader.Close(); response.Close(); return sb.ToString(); } catch (Exception ex) { //Console.WriteLine(ex.Message.ToString()); return(ex.Message.ToString()); } } public void ReadFileFromFtp(string remoteFilePath, string localFilePath) { // Get and open the following content only, try { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpAddress + "/" + remoteFilePath); request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.CacheIfAvailable); request.Method = WebRequestMethods.Ftp.DownloadFile; request.Credentials = new NetworkCredential(username, password); request.KeepAlive = false; request.UseBinary = true; request.UsePassive = true; FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); StreamReader reader = new StreamReader(responseStream); //Console.WriteLine(reader.ReadToEnd()); //Console.WriteLine("Download Complete", response.StatusDescription); StreamWriter writer = new StreamWriter(localFilePath, append: false); writer.Write(reader.ReadToEnd()); reader.Close(); writer.Close(); response.Close(); } catch (WebException e) { Console.WriteLine(e.Message.ToString()); String status = ((FtpWebResponse)e.Response).StatusDescription; Console.WriteLine(status); } catch (Exception ex) { Console.WriteLine(ex.Message.ToString()); } } // Post a file public void WriteFileToFtp(string localFilePath, string remoteFilePath) { try { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpAddress + "/" + remoteFilePath); request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.CacheIfAvailable); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(username, password); // Copy the contents of the file to the request stream. StreamReader sourceStream = new StreamReader(localFilePath); byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); sourceStream.Close(); request.ContentLength = fileContents.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(fileContents, 0, fileContents.Length); requestStream.Close(); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription); response.Close(); } catch (WebException e) { Console.WriteLine(e.Message.ToString()); String status = ((FtpWebResponse)e.Response).StatusDescription; Console.WriteLine(status); } catch (Exception ex) { Console.WriteLine(ex.Message.ToString()); } } /* * FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://Hostname.com/TestFile.txt"); * To read all file content. */ } }
38.270968
110
0.573837
[ "MIT" ]
johnpankowicz/govmeeting-before-bfg
BackEnd/Online/OnlineAccess_Lib/FTPOperations.cs
5,934
C#
using System; using UnityEngine; public class LookAtCamera : MonoBehaviour { private Camera mainCamera; private Transform tr; private void Start() { this.mainCamera = Camera.main; this.tr = base.transform; } private void Update() { if (this.mainCamera != null) { this.tr.LookAt(this.mainCamera.transform); } } }
14.041667
45
0.697329
[ "MIT" ]
moto2002/superWeapon
src/LookAtCamera.cs
337
C#
๏ปฟ// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Reflection; using System.Text; using System.Threading.Tasks; using Azure.Core.TestFramework; using Azure.Identity.Tests.Mock; using Azure.Security.KeyVault.Secrets; using NUnit.Framework; namespace Azure.Identity.Tests { // These tests are intended to be only run live on an azure VM with managed identity enabled. public class ManagedIdentityCredentialImdsLiveTests : RecordedTestBase<IdentityTestEnvironment> { public ManagedIdentityCredentialImdsLiveTests(bool isAsync) : base(isAsync) { Sanitizer = new IdentityRecordedTestSanitizer(); } [NonParallelizable] [Test] public async Task ValidateImdsSystemAssignedIdentity() { if (string.IsNullOrEmpty(TestEnvironment.IMDSEnable)) { Assert.Ignore(); } var vaultUri = new Uri(TestEnvironment.SystemAssignedVault); var cred = CreateManagedIdentityCredential(); // Hard code service version or recorded tests will fail: https://github.com/Azure/azure-sdk-for-net/issues/10432 var kvoptions = Recording.InstrumentClientOptions(new SecretClientOptions(SecretClientOptions.ServiceVersion.V7_0)); var kvclient = new SecretClient(vaultUri, cred, kvoptions); KeyVaultSecret secret = await kvclient.GetSecretAsync("identitytestsecret"); Assert.IsNotNull(secret); } [NonParallelizable] [Test] public async Task ValidateImdsUserAssignedIdentity() { if (string.IsNullOrEmpty(TestEnvironment.IMDSEnable)) { Assert.Ignore(); } var vaultUri = new Uri(TestEnvironment.SystemAssignedVault); var clientId = TestEnvironment.IMDSClientId; var cred = CreateManagedIdentityCredential(clientId); // Hard code service version or recorded tests will fail: https://github.com/Azure/azure-sdk-for-net/issues/10432 var kvoptions = Recording.InstrumentClientOptions(new SecretClientOptions(SecretClientOptions.ServiceVersion.V7_0)); var kvclient = new SecretClient(vaultUri, cred, kvoptions); KeyVaultSecret secret = await kvclient.GetSecretAsync("identitytestsecret"); Assert.IsNotNull(secret); } private ManagedIdentityCredential CreateManagedIdentityCredential(string clientId = null, TokenCredentialOptions options = null) { options = Recording.InstrumentClientOptions(options ?? new TokenCredentialOptions()); var pipeline = CredentialPipeline.GetInstance(options); // if we're in playback mode we need to mock the ImdsAvailable call since we won't be able to open a connection var client = (Mode == RecordedTestMode.Playback) ? new MockManagedIdentityClient(pipeline, clientId) { AuthRequestBuilderFactory = () => new ImdsManagedIdentitySource(pipeline.HttpPipeline, clientId) } : new ManagedIdentityClient(pipeline, clientId); var cred = new ManagedIdentityCredential(pipeline, client); return cred; } } }
37.3
168
0.679774
[ "MIT" ]
conhua/azure-sdk-for-net
sdk/identity/Azure.Identity/tests/ManagedIdentityCredentialImdsLiveTests.cs
3,359
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; namespace Microsoft.AspNetCore.Routing; internal sealed class DefaultEndpointConventionBuilder : IEndpointConventionBuilder { internal EndpointBuilder EndpointBuilder { get; } private List<Action<EndpointBuilder>>? _conventions; public DefaultEndpointConventionBuilder(EndpointBuilder endpointBuilder) { EndpointBuilder = endpointBuilder; _conventions = new(); } public void Add(Action<EndpointBuilder> convention) { var conventions = _conventions; if (conventions is null) { throw new InvalidOperationException("Conventions cannot be added after building the endpoint"); } conventions.Add(convention); } public Endpoint Build() { // Only apply the conventions once var conventions = Interlocked.Exchange(ref _conventions, null); if (conventions is not null) { foreach (var convention in conventions) { convention(EndpointBuilder); } } return EndpointBuilder.Build(); } }
26.55102
107
0.670254
[ "MIT" ]
Akarachudra/kontur-aspnetcore-fork
src/Http/Routing/src/DefaultEndpointConventionBuilder.cs
1,301
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("Funq.Abstract")] [assembly: AssemblyDescription( @"Library of abstract collection classes for Funq. ")] [assembly: AssemblyCompany("Gregory Rosenbaum")] [assembly: AssemblyProduct("Funq.Abstract")] [assembly: AssemblyCopyright("Copyright ยฉ 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: InternalsVisibleTo("Funq.Collections")] [assembly: InternalsVisibleTo("Funq.FSharp")] [assembly: InternalsVisibleTo("Funq.Tests.Performance")] [assembly: InternalsVisibleTo("Funq.Tests.Integrity")] [assembly: AssemblyVersion("0.2.*")] //[assembly: InternalsVisibleTo("Funq.Collections")] // 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("f02e5cfe-c06f-41cf-aac1-27ba0bb70f63")] // 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.*")]
34.4375
84
0.752571
[ "MIT" ]
buybackoff/Funq
Funq/Funq.Abstract/Properties/AssemblyInfo.cs
1,656
C#
๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using System.Data.Common; using NumberShop.Models.Tables; namespace NumberShop.Models.Contexts { public class UserDbContext : DbContext { public DbSet<User> Users { get; set; } public UserDbContext(DbContextOptions<UserDbContext> opt) : base(opt) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<User>().ToTable("user").HasKey(k => k.Account); } } }
24.52
79
0.683524
[ "MIT" ]
wtzqasdf/NumberShop
NumberShop/Models/Contexts/UserDbContext.cs
615
C#
using System.Collections.Generic; using System.Linq; namespace EmptyProject.Dialogs { public class DialogManager { public static DialogManager Instance { get; } = new DialogManager(); public List<Dialog> ActiveDialogs { get; } = new List<Dialog>(); public Dialog Top => ActiveDialogs.FirstOrDefault(); public void Open<T>() where T : Dialog, new() { Open(new T()); } public void Open<T>(T dialog) where T : Dialog { dialog.Attach(The.World); ActiveDialogs.Insert(0, dialog); } public void Remove<T>(T dialog) where T : Dialog { ActiveDialogs.Remove(dialog); } } }
20.266667
70
0.680921
[ "MIT" ]
game-forest/Citrus
Examples/EmptyProject/EmptyProject.Game/Dialogs/DialogManager.cs
608
C#
using System; using System.Diagnostics; using System.Net.Http; using System.Reflection; using System.Threading.Tasks; using Watchdog.Execution; using Watchdog.Http; using Watchdog.Metrics; namespace Watchdog { /// <summary> /// Represents the watchdog server /// (which is composed of many components, http server being one of them) /// </summary> public class WatchdogServer : IDisposable { private readonly Config config; private readonly HealthStateManager healthStateManager; private readonly Initializer initializer; private readonly MetricsManager metricsManager; private readonly RequestQueue requestQueue; private readonly RequestConsumer requestConsumer; private readonly ExecutionKernel executionKernel; private readonly HttpClient httpClient; private readonly HttpServer httpServer; public WatchdogServer(Config config) { this.config = config; healthStateManager = new HealthStateManager(); httpClient = new HttpClient(); initializer = new Initializer(httpClient); metricsManager = new MetricsManager(config); requestQueue = new RequestQueue( healthStateManager, config.MaxQueueLength ); executionKernel = new ExecutionKernel( healthStateManager, config.RequestTimeoutSeconds ); requestConsumer = new RequestConsumer( requestQueue, initializer, healthStateManager, executionKernel, metricsManager ); httpServer = new HttpServer( port: config.Port, verbose: config.VerboseHttpServer, router: new Router( healthStateManager, requestQueue, metricsManager ) ); } /// <summary> /// Start the server /// </summary> public void Start() { PrintStartupMessage(); healthStateManager.Initialize(); InitializeAsync().GetAwaiter().GetResult(); executionKernel.Initialize(); requestConsumer.Initialize(); httpServer.Start(); Log.Info("Unisave Watchdog running."); } private void PrintStartupMessage() { string version = typeof(WatchdogServer).Assembly .GetCustomAttribute<AssemblyInformationalVersionAttribute>() .InformationalVersion; Console.WriteLine($"Starting Unisave Watchdog {version} ..."); Console.WriteLine($"Listening on port {config.Port}"); Console.WriteLine($"Execution timeout: {config.RequestTimeoutSeconds} seconds"); Console.WriteLine("Process ID: " + Process.GetCurrentProcess().Id); } /// <summary> /// Downloads the game assemblies /// </summary> private async Task InitializeAsync() { // dummy init if (config.DummyInitialization) { initializer.DummyInitialization(); return; } // regular init if (config.InitializationRecipeUrl == null) Log.Info("Skipping startup worker initialization."); else await initializer.InitializeWorker(config.InitializationRecipeUrl); } /// <summary> /// Stop the server /// </summary> public void Stop() { Log.Info("Stopping Unisave Watchdog..."); httpServer?.Stop(); requestConsumer?.Dispose(); executionKernel?.Dispose(); requestQueue?.Dispose(); metricsManager?.Dispose(); httpClient?.Dispose(); healthStateManager?.Dispose(); Log.Info("Bye."); } public void Dispose() { Stop(); } } }
31.87218
92
0.547771
[ "Apache-2.0" ]
unisave-cloud/watchdog
Watchdog/WatchdogServer.cs
4,239
C#
๏ปฟusing Syadeu.Presentation.Entities; using System; namespace Syadeu.Presentation.Internal { /// <summary> /// Presentation Manager์— ์œ ์ € ์‹œ์Šคํ…œ์„ ๋“ฑ๋กํ•˜๊ธฐ ์œ„ํ•œ ์ธํ„ฐํŽ˜์ด์Šค์ž…๋‹ˆ๋‹ค.<br/> /// <see cref="PresentationGroupEntity.RegisterSystem(System.Type[])"/> ์„ <see cref="Register"/>์—์„œ ํ˜ธ์ถœํ•˜์—ฌ ๋“ฑ๋กํ•˜์„ธ์š”. /// </summary> /// <remarks> /// ํด๋ž˜์Šค์— ์ง์ ‘ ์ฐธ์กฐํ•˜์—ฌ ์‚ฌ์šฉํ•˜๊ฒŒ๋” ๋งŒ๋“ค์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.<br/> /// <seealso cref="PresentationGroupEntity"/>์„ ์ฐธ์กฐํ•˜์—ฌ ์‚ฌ์šฉํ•˜์„ธ์š”. /// </remarks> internal interface IPresentationRegister { bool StartOnInitialize { get; } /// <summary> /// <see langword="null"/> ์ด ์•„๋‹ ๊ฒฝ์šฐ, ํ•ด๋‹น ์”ฌ์ด ๋กœ๋“œ๋˜๊ฑฐ๋‚˜ ์–ธ๋กœ๋“œ ๋˜๋ฉด, ์ž๋™์œผ๋กœ ํ™œ์„ฑํ™”๋˜๊ณ  ๋น„ํ™œ์„ฑํ™” ๋ฉ๋‹ˆ๋‹ค. /// </summary> SceneReference DependenceScene { get; } /// <summary> /// <see langword="null"/> ์ด ์•„๋‹ ๊ฒฝ์šฐ, /// ํ•ด๋‹น ๊ทธ๋ฃน(<see cref="PresentationGroupEntity"/>)์ด ์‹œ์ž‘๋ ๋•Œ ๊ฐ™์ด ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค. /// </summary> Type DependenceGroup { get; } /// <summary> /// <see cref="PresentationManager"/>์—์„œ ํ˜ธ์ถœ๋˜๋Š” ๋ฉ”์†Œ๋“œ์ž…๋‹ˆ๋‹ค.<br/> /// <see cref="PresentationGroupEntity.RegisterSystem(System.Type[])"/> ์„ ์—ฌ๊ธฐ์„œ ํ˜ธ์ถœํ•˜์—ฌ ๋“ฑ๋กํ•˜์„ธ์š”. /// </summary> void Register(); } }
35.181818
114
0.594315
[ "Apache-2.0" ]
Syadeu/CoreSystem
Runtime/Presentation/Internal/IPresentationRegister.cs
1,457
C#
using System; namespace Buildron.Domain.Users { /// <summary> /// User authentication completed event arguments. /// </summary> public class UserAuthenticationCompletedEventArgs : EventArgs { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Buildron.Domain.Users.UserAuthenticationCompletedEventArgs"/> class. /// </summary> /// <param name="user">User.</param> /// <param name="success">If set to <c>true</c> success.</param> public UserAuthenticationCompletedEventArgs(IAuthUser user, bool success) { User = user; Success = success; } #endregion #region Properties /// <summary> /// Gets the user. /// </summary> public IAuthUser User { get; private set; } /// <summary> /// Gets a value indicating whether this <see cref="Buildron.Domain.Users.UserAuthenticationCompletedEventArgs"/> is success. /// </summary> /// <value><c>true</c> if success; otherwise, <c>false</c>.</value> public bool Success { get; private set; } #endregion } }
29.638889
127
0.661668
[ "MIT" ]
skahal/Buildron
src/Buildron/Buildron.ModSdk/Domain/Users/UserAuthenticationCompletedEventArgs.cs
1,067
C#
๏ปฟusing System; namespace SimplexTestApp { internal class Program { private static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }
16.5
47
0.560606
[ "MIT" ]
phinoox/simplex
Simplex/SimplexTestApp/Program.cs
200
C#
๏ปฟusing Android.App; using Android.Content.PM; using Android.OS; using Gcm.Client; namespace AZKitMobile.Droid { [Activity(Label = "AZKitMobile", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); //intialize the azure mobile platform //reguired on this platform to load all assemblies Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init(); global::Xamarin.Forms.Forms.Init(this, bundle); LoadApplication(new App()); //only register for notifications if we have a gcm project identifier in the settings if (!string.IsNullOrEmpty(AZKitMobile.Models.Settings.GoogleCCMProjectIdentifer)) { GcmClient.CheckDevice(this.ApplicationContext); GcmClient.CheckManifest(this.ApplicationContext); GcmClient.Register(this.ApplicationContext, AZKitMobile.Models.Settings.GoogleCCMProjectIdentifer); } } } }
36.823529
160
0.679712
[ "MIT" ]
Azure-Samples/azure-solutions-digital-marketing-reference-implementation
src/AzureKit/AZKitMobile/AZKitMobile.Droid/MainActivity.cs
1,254
C#
using System; using NUnit.Framework; namespace Codewars.sixKyu { [TestFixture] public class KataTests { [Test] [TestCase("Welcome", ExpectedResult = "emocleW")] [TestCase("Hey fellow warriors", ExpectedResult = "Hey wollef sroirraw")] [TestCase("This is a test", ExpectedResult = "This is a test")] [TestCase("This is another test", ExpectedResult = "This is rehtona test")] [TestCase("You are almost to the last test", ExpectedResult = "You are tsomla to the last test")] [TestCase("Just kidding there is still one more", ExpectedResult = "Just gniddik ereht is llits one more")] public string Test(string word) { return Kata.SpinWords(word); } } }
36.095238
115
0.637203
[ "MIT" ]
AsmusGerman/csharp-codewars-katas
6-kyu/stop-gninnips-my-sdrow/Kata.test.cs
758
C#
๏ปฟusing MediatR; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using System.Linq; using System.Threading; using System.Threading.Tasks; using CaseFile.Api.Business.Commands; using CaseFile.Entities; namespace CaseFile.Api.Business.Handlers { public class UserCountQueryHandler : IRequestHandler<UserCountCommand, int> { private readonly CaseFileContext _context; private readonly ILogger _logger; public UserCountQueryHandler(CaseFileContext context, ILogger<UserCountQueryHandler> logger) { _context = context; _logger = logger; } public async Task<int> Handle(UserCountCommand request, CancellationToken cancellationToken) { _logger.LogInformation($"Getting the total User count for the ngo with the id {request.NgoId}"); IQueryable<Entities.User> users = _context.Users; if (request.NgoId > 0) { users = users.Where(u => u.NgoId == request.NgoId); } return await users.CountAsync(cancellationToken); } } }
31.305556
108
0.671695
[ "MPL-2.0" ]
code4romania/case-file-api
api/CaseFile.Api.Business/Handlers/UserCountQueryHandler.cs
1,129
C#
๏ปฟusing System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; namespace MyShop.WebUI.Tests.Mocks { public class MockHttpContext : HttpContextBase { private MockRequest request; private MockResponse response; private HttpCookieCollection cookies; public MockHttpContext() { cookies = new HttpCookieCollection(); this.request = new MockRequest(cookies); this.response = new MockResponse(cookies); } public override HttpRequestBase Request { get { return request; } } public override HttpResponseBase Response { get { return response; } } } public class MockResponse : HttpResponseBase { private readonly HttpCookieCollection cookies; public MockResponse(HttpCookieCollection cookies) { this.cookies = cookies; } public override HttpCookieCollection Cookies { get { return cookies; } } } public class MockRequest : HttpRequestBase { private readonly HttpCookieCollection cookies; public MockRequest(HttpCookieCollection cookies) { this.cookies = cookies; } public override HttpCookieCollection Cookies { get { return cookies; } } } }
22.186667
58
0.554087
[ "MIT" ]
chisho21/MyShop
MyShop/MyShop.WebUI.Tests/Mocks/MockHttpContext.cs
1,666
C#
๏ปฟ//confirmed working with Hurtworld ItemV2, ROK, Rust, 7DaystoDie using System; using System.Collections.Generic; using System.Linq; namespace Oxide.Plugins { [Info("NightMessage", "Mordeus", "1.0.1")] [Description("Universal Day/Night Message")] public class NightMessage : CovalencePlugin { public bool NightMessageSent = false; public bool DayMessageSent = false; //config public string ChatTitle; public bool UseNightMessage; public bool UseDayMessage; public float DawnTime; public float DuskTime; #region Lang API private new void LoadDefaultMessages() { lang.RegisterMessages(new Dictionary<string, string>() { ["NightMessage"] = "{Title} [#add8e6]Night is upon us, beware![/#]", ["DayMessage"] = "{Title} [#add8e6]Dawn has arrived![/#]" }, this); } #endregion Lang API #region Config protected override void LoadDefaultConfig() { PrintWarning("Generating new configurationfile..."); } private new void LoadConfig() { ChatTitle = GetConfig<string>("Title", "[#00ffff]Server:[/#]"); UseNightMessage = GetConfig<bool>("Use Night Message", true); UseDayMessage = GetConfig<bool>("Use Day Message", true); DawnTime = GetConfig<float>("Dawn Time", 7f); DuskTime = GetConfig<float>("Dusk Time", 19f); SaveConfig(); } #endregion Config #region Oxide private void OnServerInitialized() { timer.Repeat(1, 0, CheckTime); } private void Init() { LoadConfig(); } #endregion Oxide #region Time Helpers private void CheckTime() { if (IsNight && !NightMessageSent) { SendMessage(true, false); NightMessageSent = true; DayMessageSent = false; } else if (!IsNight && !DayMessageSent) { SendMessage(false, true); DayMessageSent = true; NightMessageSent = false; } } bool IsNight => server.Time.TimeOfDay.Hours < DawnTime || server.Time.TimeOfDay.Hours >= DuskTime; private void SendMessage(bool night, bool day) { if (day && DayMessageSent == false && UseDayMessage) Broadcast("DayMessage"); if (night && NightMessageSent == false && UseNightMessage) Broadcast("NightMessage"); } #endregion Time Helpers #region Helpers private string Message(string key, string id = null, params object[] args) { return lang.GetMessage(key, this, id).Replace("{Title}", ChatTitle); } private T GetConfig<T>(params object[] pathAndValue) { List<string> pathL = pathAndValue.Select((v) => v.ToString()).ToList(); pathL.RemoveAt(pathAndValue.Length - 1); string[] path = pathL.ToArray(); if (Config.Get(path) == null) { Config.Set(pathAndValue); PrintWarning($"Added field to config: {string.Join("/", path)}"); } return (T)Convert.ChangeType(Config.Get(path), typeof(T)); } private void Broadcast(string key) { foreach (var player in players.Connected) player.Reply(Message(key, player.Id)); } #endregion Helpers } }
33.900901
112
0.528302
[ "MIT" ]
john-clark/rust-oxide-umod
oxide/plugins/universal/NightMessage.cs
3,765
C#