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
/* * 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.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.Ecs.Transform; using Aliyun.Acs.Ecs.Transform.V20140526; namespace Aliyun.Acs.Ecs.Model.V20140526 { public class ReInitDiskRequest : RpcAcsRequest<ReInitDiskResponse> { public ReInitDiskRequest() : base("Ecs", "2014-05-26", "ReInitDisk", "ecs", "openAPI") { } private long? resourceOwnerId; private string password; private string resourceOwnerAccount; private bool? autoStartInstance; private string ownerAccount; private string action; private string diskId; private string securityEnhancementStrategy; private string keyPairName; private long? ownerId; public long? ResourceOwnerId { get { return resourceOwnerId; } set { resourceOwnerId = value; DictionaryUtil.Add(QueryParameters, "ResourceOwnerId", value.ToString()); } } public string Password { get { return password; } set { password = value; DictionaryUtil.Add(QueryParameters, "Password", value); } } public string ResourceOwnerAccount { get { return resourceOwnerAccount; } set { resourceOwnerAccount = value; DictionaryUtil.Add(QueryParameters, "ResourceOwnerAccount", value); } } public bool? AutoStartInstance { get { return autoStartInstance; } set { autoStartInstance = value; DictionaryUtil.Add(QueryParameters, "AutoStartInstance", value.ToString()); } } public string OwnerAccount { get { return ownerAccount; } set { ownerAccount = value; DictionaryUtil.Add(QueryParameters, "OwnerAccount", value); } } public string Action { get { return action; } set { action = value; DictionaryUtil.Add(QueryParameters, "Action", value); } } public string DiskId { get { return diskId; } set { diskId = value; DictionaryUtil.Add(QueryParameters, "DiskId", value); } } public string SecurityEnhancementStrategy { get { return securityEnhancementStrategy; } set { securityEnhancementStrategy = value; DictionaryUtil.Add(QueryParameters, "SecurityEnhancementStrategy", value); } } public string KeyPairName { get { return keyPairName; } set { keyPairName = value; DictionaryUtil.Add(QueryParameters, "KeyPairName", value); } } public long? OwnerId { get { return ownerId; } set { ownerId = value; DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString()); } } public override ReInitDiskResponse GetResponse(UnmarshallerContext unmarshallerContext) { return ReInitDiskResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
20.259067
95
0.64757
[ "Apache-2.0" ]
pengesoft/aliyun-openapi-net-sdk
aliyun-net-sdk-ecs/Ecs/Model/V20140526/ReInitDiskRequest.cs
3,910
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.Text; using Silk.NET.Core.Native; using Ultz.SuperInvoke; namespace Silk.NET.Vulkan { public unsafe struct PhysicalDeviceShaderFloat16Int8Features { public PhysicalDeviceShaderFloat16Int8Features ( StructureType sType = StructureType.PhysicalDeviceShaderFloat16Int8Features, void* pNext = default, Bool32 shaderFloat16 = default, Bool32 shaderInt8 = default ) { SType = sType; PNext = pNext; ShaderFloat16 = shaderFloat16; ShaderInt8 = shaderInt8; } /// <summary></summary> public StructureType SType; /// <summary></summary> public void* PNext; /// <summary></summary> public Bool32 ShaderFloat16; /// <summary></summary> public Bool32 ShaderInt8; } }
25.634146
88
0.6451
[ "MIT" ]
mcavanagh/Silk.NET
src/Vulkan/Silk.NET.Vulkan/Structs/PhysicalDeviceShaderFloat16Int8Features.gen.cs
1,051
C#
using System.Collections.Generic; using Newtonsoft.Json; namespace DigitalOcean.API.Models.Requests { public class DatabaseBackup { /// <summary> /// A unique, human-readable name for the database cluster. /// </summary> [JsonProperty("name")] public string Name { get; set; } /// <summary> /// A slug representing the database engine to be used for the cluster. The slug for PostgreSQL, the only engine current supported, is "pg". /// </summary> [JsonProperty("engine")] public string Engine { get; set; } /// <summary> /// A string representing the version of the database engine to use for the cluster. If excluded, the specified engine's default version is used. The available versions for PostgreSQL, the first supported engine, are "10" and "11" defaulting to the later. /// </summary> [JsonProperty("version")] public string Version { get; set; } /// <summary> /// A slug identifier representing the size of the nodes in the database cluster. /// </summary> [JsonProperty("size")] public string Size { get; set; } /// <summary> /// A slug identifier for the region where the database cluster will be created. /// </summary> [JsonProperty("region")] public string Region { get; set; } /// <summary> /// The number of nodes in the database cluster. Valid values are are 1-3. In addition to the primary node, up to two standby nodes may be added for highly available configurations. The value is inclusive of the primary node. For example, setting the value to 2 will provision a database cluster with a primary node and one standby node. /// </summary> [JsonProperty("num_nodes")] public int NumNodes { get; set; } /// <summary> /// A flat array of tag names as strings to apply to the database cluster after it is created. Tag names can either be existing or new tags. /// </summary> [JsonProperty("tags")] public List<string> Tags { get; set; } /// <summary> /// A string specifying the UUID of the VPC to which the database cluster will be assigned. /// If excluded, the cluster will be assigned to your account's default VPC for the region. /// </summary> [JsonProperty("private_network_uuid")] public string PrivateNetworkUuid { get; set; } /// <summary> /// An embedded object containing two attributes specifying the name of the original database cluster and the timestamp of the backup to restore (see below). /// </summary> [JsonProperty("backup_restore")] public DatabaseBackupRestore BackupRestore { get; set; } } }
45.435484
345
0.635783
[ "MIT" ]
JoshClose/DigitalOcean.API
DigitalOcean.API/Models/Requests/DatabaseBackup.cs
2,817
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Security.Claims; using System.Web; using System.Web.Mvc; using System.Threading.Tasks; using Microsoft.Azure.ActiveDirectory.GraphClient; using Microsoft.IdentityModel.Clients.ActiveDirectory; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.OpenIdConnect; using _2016MT45.Models; namespace _2016MT45.Controllers { [Authorize] public class UserProfileController : Controller { private ApplicationDbContext db = new ApplicationDbContext(); private string clientId = ConfigurationManager.AppSettings["ida:ClientId"]; private string appKey = ConfigurationManager.AppSettings["ida:ClientSecret"]; private string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"]; private string graphResourceID = "https://graph.windows.net"; // GET: UserProfile public async Task<ActionResult> Index() { string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; try { Uri servicePointUri = new Uri(graphResourceID); Uri serviceRoot = new Uri(servicePointUri, tenantID); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, async () => await GetTokenForApplication()); // use the token for querying the graph to get the user details var result = await activeDirectoryClient.Users .Where(u => u.ObjectId.Equals(userObjectID)) .ExecuteAsync(); IUser user = result.CurrentPage.ToList().First(); return View(user); } catch (AdalException) { // Return to error page. return View("Error"); } // if the above failed, the user needs to explicitly re-authenticate for the app to obtain the required token catch (Exception) { return View("Relogin"); } } public void RefreshSession() { HttpContext.GetOwinContext().Authentication.Challenge( new AuthenticationProperties { RedirectUri = "/UserProfile" }, OpenIdConnectAuthenticationDefaults.AuthenticationType); } public async Task<string> GetTokenForApplication() { string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; // get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc) ClientCredential clientcred = new ClientCredential(clientId, appKey); // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's database AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID, new ADALTokenCache(signedInUserID)); AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync(graphResourceID, clientcred, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)); return authenticationResult.AccessToken; } } }
47.060976
200
0.678673
[ "MIT" ]
tkopacz/2016NetCoreWebApiOneDriveBusiness
2016MT45/2016MT45/Controllers/UserProfileController.cs
3,861
C#
using System; using UnityEngine; using UnityEngine.Video; using System.Collections.Generic; namespace Adrenak.UniVRMedia { public class VRMediaPlayer { [Serializable] public class Configuration { /// <summary> /// The position of the sphere video player and the camera in world space /// </summary> public Vector3 position; /// <summary> /// The color of the video player surface while the stream initializes /// </summary> public Color bgColor; /// <summary> /// The layers that the player camera should render /// </summary> public LayerMask cameraCullilngMask; /// <summary> /// The layer to which the video player surface belongs /// </summary> [SerializeField, Layer] public int playerLayer; } /// <summary> /// The <see cref="VideoPlayer"/> component that is playing the video /// </summary> public VideoPlayer Video { get; private set; } /// <summary> /// The <see cref="AudioSource"/> component that is playing the audio /// </summary> public AudioSource Audio { get; private set; } /// <summary> /// The <see cref="GameObject"/> that is the parent of all the player setup /// </summary> public GameObject Host { get; private set; } /// <summary> /// The <see cref="Camera"/> that is used for rendering the video sphere /// </summary> public GameObject Cam { get; private set; } /// <summary> /// The <see cref="Configuration"/> object that is used to appl the settings /// </summary> public Configuration Config { get; private set; } Dictionary<Camera, bool> m_CameraStatus = new Dictionary<Camera, bool>(); float m_TimeScaleMemento; // ================================================ // PUBLIC METHODS // ================================================ /// <summary> /// Creates an instance using the configuration given /// </summary> /// <param name="config"></param> public VRMediaPlayer(Configuration config) { Config = config; CreateHostObject(); ManageComponents(); InvertNormals(); SetColor(Config.bgColor); SetupCamera(); } /// <summary> /// Use this instead of VideoPlayer.Play /// </summary> public void Play() { SaveCameras(); StopCameras(); Cam.GetComponent<Camera>().enabled = true; m_TimeScaleMemento = Time.timeScale; Time.timeScale = 0; Video.Play(); } /// <summary> /// Use this instead of VideoPlayer.Pause /// </summary> public void Pause() { Video.Pause(); } /// <summary> /// Use this instead of VideoPlayer.Stop /// </summary> public void Stop() { ResetCameras(); Video.Stop(); MonoBehaviour.Destroy(Host); Time.timeScale = m_TimeScaleMemento; } // ================================================ // PRIVATE METHODS // ================================================ void CreateHostObject() { Host = GameObject.CreatePrimitive(PrimitiveType.Sphere); Host.layer = Config.playerLayer; Host.name = "UniVRMediaObject"; Host.transform.localScale = new Vector3(-100F, 100F, 100F); Host.transform.position = Config.position; } void ManageComponents() { var collider = Host.GetComponent<Collider>(); if (collider != null) UnityEngine.Object.Destroy(collider); Video = Host.AddComponent<VideoPlayer>(); Audio = Host.AddComponent<AudioSource>(); Video.audioOutputMode = VideoAudioOutputMode.AudioSource; Video.SetTargetAudioSource(0, Audio); } void InvertNormals() { var filter = Host.GetComponent<MeshFilter>(); filter.mesh.InvertNormals(); } void SetColor(Color color) { Texture2D tex = new Texture2D(1, 1); tex.SetPixel(0, 0, color); tex.Apply(); var renderer = Host.GetComponent<Renderer>(); renderer.material.shader = Shader.Find("Unlit/Texture"); renderer.material.mainTexture = tex; } void SetupCamera() { var cameraRoot = new GameObject("UniVRMediaCameraRoot"); cameraRoot.transform.position = Config.position; // Create a new camera at the center of the player Cam = new GameObject("UniVRMediaCamera"); Cam.AddComponent<CameraControls>(); Cam.transform.SetParent(cameraRoot.transform); Cam.transform.localPosition = Vector3.zero; // Initialize the camera component. Ignore the layers and set the clipping planes var cam = Cam.AddComponent<Camera>(); cam.cullingMask = Config.cameraCullilngMask; cam.nearClipPlane = 1F; cam.farClipPlane = 1000F; } void SaveCameras() { // We store the current state of all the cameras and disable them var cameras = GameObject.FindObjectsOfType<Camera>(); foreach (var c in cameras) m_CameraStatus.Add(c, c.enabled); } void ResetCameras() { // We reset all the old cameras to their origial states and clear the dictionary foreach (var p in m_CameraStatus) p.Key.enabled = p.Value; m_CameraStatus.Clear(); } void StopCameras() { foreach (var pair in m_CameraStatus) pair.Key.enabled = false; } } }
34.511236
94
0.525476
[ "MIT" ]
adrenak/Uni360Media
Assets/Adrenak/UniVRMedia/Scripts/VRMediaPlayer.cs
6,145
C#
using System; namespace IptablesCtl.Native { public enum LogLevels { EMERGENCY =0, ALERT=1, CRITICAL=2,ERROR=3,WARNING=4,NOTICE=5,INFORMATIONAL=6,DEBUG=7 } };
22.25
92
0.685393
[ "Apache-2.0" ]
skywarer/IptablesCtl
IptablesCtl/Native/LogLevels.cs
178
C#
using System; using System.ComponentModel; using System.Diagnostics; using System.Windows; namespace WhileTrue.Classes.DragNDrop { internal class DragDropSourceAdapter : IDragDropSourceAdapter { private readonly IDragDropUiSourceHandlerInstance dragSourceHandler; private readonly DependencyObject source; private readonly IDragDropSource sourceHandler; private DragDropSourceAdapter(IDragDropSource sourceHandler, DependencyObject source) { this.sourceHandler = sourceHandler; this.source = source; dragSourceHandler = DragDrop.GetDragDropUISourceHandler(source.GetType()).Create(source, this); System.Windows.DragDrop.AddGiveFeedbackHandler(this.source, GiveFeedback); System.Windows.DragDrop.AddQueryContinueDragHandler(this.source, QueryContinueDrag); } public void DoDragDrop() { var DragData = sourceHandler.DragData; var TypeConverter = TypeDescriptor.GetConverter(DragData.GetType()); IDataObject DataObject = null; if (TypeConverter != null) if (TypeConverter.CanConvertTo(typeof(IDataObject))) DataObject = (IDataObject) TypeConverter.ConvertTo(DragData, typeof(IDataObject)); if (DataObject == null) { if (DragData.GetType().GetCustomAttributes(typeof(SerializableAttribute), true).Length > 0) DataObject = new DataObject(DragData); else DataObject = new DataObject(new DragDropObjectWrapper(new DataObject(DragData))); } var DropEffect = System.Windows.DragDrop.DoDragDrop(source, DataObject, sourceHandler.DragEffects); sourceHandler.NotifyDropped(ToDragDropEffect(DropEffect)); } public void Dispose() { System.Windows.DragDrop.RemoveGiveFeedbackHandler(source, GiveFeedback); System.Windows.DragDrop.RemoveQueryContinueDragHandler(source, QueryContinueDrag); dragSourceHandler.Dispose(); } private static void GiveFeedback(object sender, GiveFeedbackEventArgs e) { } private static void QueryContinueDrag(object sender, QueryContinueDragEventArgs e) { if (e.EscapePressed) { e.Action = DragAction.Cancel; e.Handled = true; } } private static DragDropEffect ToDragDropEffect(DragDropEffects dropEffect) { if (dropEffect == DragDropEffects.None || dropEffect == DragDropEffects.Scroll) return DragDropEffect.None; if ((dropEffect & DragDropEffects.Copy) != 0) { Trace.Assert((dropEffect ^ DragDropEffects.Copy) == 0, "dropEffect has multiple bits set"); return DragDropEffect.Copy; } if ((dropEffect & DragDropEffects.Move) != 0) { Trace.Assert((dropEffect ^ DragDropEffects.Move) == 0, "dropEffect has multiple bits set"); return DragDropEffect.Move; } if ((dropEffect & DragDropEffects.Link) != 0) { Trace.Assert((dropEffect ^ DragDropEffects.Link) == 0, "dropEffect has multiple bits set"); return DragDropEffect.Link; } if ((dropEffect & DragDropEffects.Link) != 0) { Trace.Assert((dropEffect ^ DragDropEffects.Link) == 0, "dropEffect has multiple bits set"); return DragDropEffect.Link; } Trace.Fail("dropEffect is neither Copy, Move nor Link"); return DragDropEffect.None; } public static DragDropSourceAdapter Create(IDragDropSource dragDropSource, DependencyObject dependencyObject) { return new DragDropSourceAdapter(dragDropSource, dependencyObject); } } }
38.84466
119
0.623594
[ "Unlicense", "MIT" ]
GMS-online/wt-libraries
wt.core.win/Classes/DragNDrop/DragDropSourceAdapter.cs
4,003
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Text.Json.Reflection; namespace System.Text.Json.Serialization.Metadata { /// <summary> /// Provides JSON serialization-related metadata about a type. /// </summary> /// <remarks>This API is for use by the output of the System.Text.Json source generator and should not be called directly.</remarks> [DebuggerDisplay("{DebuggerDisplay,nq}")] [EditorBrowsable(EditorBrowsableState.Never)] public partial class JsonTypeInfo { internal const string JsonObjectTypeName = "System.Text.Json.Nodes.JsonObject"; internal delegate object? ConstructorDelegate(); internal delegate T ParameterizedConstructorDelegate<T, TArg0, TArg1, TArg2, TArg3>(TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3); internal ConstructorDelegate? CreateObject { get; set; } internal object? CreateObjectWithArgs { get; set; } // Add method delegate for non-generic Stack and Queue; and types that derive from them. internal object? AddMethodDelegate { get; set; } internal JsonPropertyInfo? DataExtensionProperty { get; private set; } // If enumerable or dictionary, the JsonTypeInfo for the element type. private JsonTypeInfo? _elementTypeInfo; // Avoids having to perform an expensive cast to JsonTypeInfo<T> to check if there is a Serialize method. internal bool HasSerialize { get; set; } /// <summary> /// Return the JsonTypeInfo for the element type, or null if the type is not an enumerable or dictionary. /// </summary> /// <remarks> /// This should not be called during warm-up (initial creation of JsonTypeInfos) to avoid recursive behavior /// which could result in a StackOverflowException. /// </remarks> internal JsonTypeInfo? ElementTypeInfo { get { if (_elementTypeInfo == null && ElementType != null) { _elementTypeInfo = Options.GetOrAddJsonTypeInfo(ElementType); } return _elementTypeInfo; } set { // Set by JsonMetadataServices. Debug.Assert(_elementTypeInfo == null); _elementTypeInfo = value; } } internal Type? ElementType { get; set; } // If dictionary, the JsonTypeInfo for the key type. private JsonTypeInfo? _keyTypeInfo; /// <summary> /// Return the JsonTypeInfo for the key type, or null if the type is not a dictionary. /// </summary> /// <remarks> /// This should not be called during warm-up (initial creation of JsonTypeInfos) to avoid recursive behavior /// which could result in a StackOverflowException. /// </remarks> internal JsonTypeInfo? KeyTypeInfo { get { if (_keyTypeInfo == null && KeyType != null) { Debug.Assert(PropertyInfoForTypeInfo.ConverterStrategy == ConverterStrategy.Dictionary); _keyTypeInfo = Options.GetOrAddJsonTypeInfo(KeyType); } return _keyTypeInfo; } set { // Set by JsonMetadataServices. Debug.Assert(_keyTypeInfo == null); _keyTypeInfo = value; } } internal Type? KeyType { get; set; } internal JsonSerializerOptions Options { get; set; } internal Type Type { get; private set; } /// <summary> /// The JsonPropertyInfo for this JsonTypeInfo. It is used to obtain the converter for the TypeInfo. /// </summary> /// <remarks> /// The returned JsonPropertyInfo does not represent a real property; instead it represents either: /// a collection element type, /// a generic type parameter, /// a property type (if pushed to a new stack frame), /// or the root type passed into the root serialization APIs. /// For example, for a property returning <see cref="Collections.Generic.List{T}"/> where T is a string, /// a JsonTypeInfo will be created with .Type=typeof(string) and .PropertyInfoForTypeInfo=JsonPropertyInfo{string}. /// Without this property, a "Converter" property would need to be added to JsonTypeInfo and there would be several more /// `if` statements to obtain the converter from either the actual JsonPropertyInfo (for a real property) or from the /// TypeInfo (for the cases mentioned above). In addition, methods that have a JsonPropertyInfo argument would also likely /// need to add an argument for JsonTypeInfo. /// </remarks> internal JsonPropertyInfo PropertyInfoForTypeInfo { get; set; } internal bool IsObjectWithParameterizedCtor => PropertyInfoForTypeInfo.ConverterBase.ConstructorIsParameterized; /// <summary> /// Returns a helper class used for computing the default value. /// </summary> internal DefaultValueHolder DefaultValueHolder => _defaultValueHolder ??= DefaultValueHolder.CreateHolder(Type); private DefaultValueHolder? _defaultValueHolder; internal JsonNumberHandling? NumberHandling { get; set; } internal JsonTypeInfo() { Debug.Assert(false, "This constructor should not be called."); } internal JsonTypeInfo(Type type, JsonSerializerOptions options!!, bool dummy) { Type = type; Options = options; // Setting this option is deferred to the initialization methods of the various metadada info types. PropertyInfoForTypeInfo = null!; } [RequiresUnreferencedCode(JsonSerializer.SerializationUnreferencedCodeMessage)] internal JsonTypeInfo(Type type, JsonSerializerOptions options) : this( type, GetConverter( type, parentClassType: null, // A TypeInfo never has a "parent" class. memberInfo: null, // A TypeInfo never has a "parent" property. options), options) { } [RequiresUnreferencedCode(JsonSerializer.SerializationUnreferencedCodeMessage)] internal JsonTypeInfo(Type type, JsonConverter converter, JsonSerializerOptions options) { Type = type; Options = options; JsonNumberHandling? typeNumberHandling = GetNumberHandlingForType(Type); PropertyInfoForTypeInfo = CreatePropertyInfoForTypeInfo(Type, converter, typeNumberHandling, Options); ElementType = converter.ElementType; switch (PropertyInfoForTypeInfo.ConverterStrategy) { case ConverterStrategy.Object: { const BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; CreateObject = Options.MemberAccessorStrategy.CreateConstructor(type); Dictionary<string, JsonPropertyInfo>? ignoredMembers = null; PropertyInfo[] properties = type.GetProperties(bindingFlags); bool propertyOrderSpecified = false; // PropertyCache is not accessed by other threads until the current JsonTypeInfo instance // is finished initializing and added to the cache on JsonSerializerOptions. // Default 'capacity' to the common non-polymorphic + property case. PropertyCache = new JsonPropertyDictionary<JsonPropertyInfo>(Options.PropertyNameCaseInsensitive, capacity: properties.Length); // We start from the most derived type. Type? currentType = type; while (true) { foreach (PropertyInfo propertyInfo in properties) { bool isVirtual = propertyInfo.IsVirtual(); string propertyName = propertyInfo.Name; // Ignore indexers and virtual properties that have overrides that were [JsonIgnore]d. if (propertyInfo.GetIndexParameters().Length > 0 || PropertyIsOverridenAndIgnored(propertyName, propertyInfo.PropertyType, isVirtual, ignoredMembers)) { continue; } // For now we only support public properties (i.e. setter and/or getter is public). if (propertyInfo.GetMethod?.IsPublic == true || propertyInfo.SetMethod?.IsPublic == true) { CacheMember( currentType, propertyInfo.PropertyType, propertyInfo, isVirtual, typeNumberHandling, ref propertyOrderSpecified, ref ignoredMembers); } else { if (JsonPropertyInfo.GetAttribute<JsonIncludeAttribute>(propertyInfo) != null) { ThrowHelper.ThrowInvalidOperationException_JsonIncludeOnNonPublicInvalid(propertyName, currentType); } // Non-public properties should not be included for (de)serialization. } } foreach (FieldInfo fieldInfo in currentType.GetFields(bindingFlags)) { string fieldName = fieldInfo.Name; if (PropertyIsOverridenAndIgnored(fieldName, fieldInfo.FieldType, currentMemberIsVirtual: false, ignoredMembers)) { continue; } bool hasJsonInclude = JsonPropertyInfo.GetAttribute<JsonIncludeAttribute>(fieldInfo) != null; if (fieldInfo.IsPublic) { if (hasJsonInclude || Options.IncludeFields) { CacheMember( currentType, fieldInfo.FieldType, fieldInfo, isVirtual: false, typeNumberHandling, ref propertyOrderSpecified, ref ignoredMembers); } } else { if (hasJsonInclude) { ThrowHelper.ThrowInvalidOperationException_JsonIncludeOnNonPublicInvalid(fieldName, currentType); } // Non-public fields should not be included for (de)serialization. } } currentType = currentType.BaseType; if (currentType == null) { break; } properties = currentType.GetProperties(bindingFlags); }; if (propertyOrderSpecified) { PropertyCache.List.Sort((p1, p2) => p1.Value!.Order.CompareTo(p2.Value!.Order)); } if (converter.ConstructorIsParameterized) { ParameterInfo[] parameters = converter.ConstructorInfo!.GetParameters(); int parameterCount = parameters.Length; JsonParameterInfoValues[] jsonParameters = GetParameterInfoArray(parameters); InitializeConstructorParameters(jsonParameters); } } break; case ConverterStrategy.Enumerable: { CreateObject = Options.MemberAccessorStrategy.CreateConstructor(type); } break; case ConverterStrategy.Dictionary: { KeyType = converter.KeyType; CreateObject = Options.MemberAccessorStrategy.CreateConstructor(type); } break; case ConverterStrategy.Value: { CreateObject = Options.MemberAccessorStrategy.CreateConstructor(type); } break; case ConverterStrategy.None: { ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(type); } break; default: Debug.Fail($"Unexpected class type: {PropertyInfoForTypeInfo.ConverterStrategy}"); throw new InvalidOperationException(); } // These two method overrides are expected to perform // orthogonal changes, so we can invoke them both safely. converter.ConfigureJsonTypeInfo(this, options); converter.ConfigureJsonTypeInfoUsingReflection(this, options); } private void CacheMember( Type declaringType, Type memberType, MemberInfo memberInfo, bool isVirtual, JsonNumberHandling? typeNumberHandling, ref bool propertyOrderSpecified, ref Dictionary<string, JsonPropertyInfo>? ignoredMembers) { bool hasExtensionAttribute = memberInfo.GetCustomAttribute(typeof(JsonExtensionDataAttribute)) != null; if (hasExtensionAttribute && DataExtensionProperty != null) { ThrowHelper.ThrowInvalidOperationException_SerializationDuplicateTypeAttribute(Type, typeof(JsonExtensionDataAttribute)); } JsonPropertyInfo jsonPropertyInfo = AddProperty(memberInfo, memberType, declaringType, isVirtual, typeNumberHandling, Options); Debug.Assert(jsonPropertyInfo.NameAsString != null); if (hasExtensionAttribute) { Debug.Assert(DataExtensionProperty == null); ValidateAndAssignDataExtensionProperty(jsonPropertyInfo); Debug.Assert(DataExtensionProperty != null); } else { CacheMember(jsonPropertyInfo, PropertyCache, ref ignoredMembers); propertyOrderSpecified |= jsonPropertyInfo.Order != 0; } } private void CacheMember(JsonPropertyInfo jsonPropertyInfo, JsonPropertyDictionary<JsonPropertyInfo>? propertyCache, ref Dictionary<string, JsonPropertyInfo>? ignoredMembers) { string memberName = jsonPropertyInfo.ClrName!; // The JsonPropertyNameAttribute or naming policy resulted in a collision. if (!propertyCache!.TryAdd(jsonPropertyInfo.NameAsString, jsonPropertyInfo)) { JsonPropertyInfo other = propertyCache[jsonPropertyInfo.NameAsString]!; if (other.IsIgnored) { // Overwrite previously cached property since it has [JsonIgnore]. propertyCache[jsonPropertyInfo.NameAsString] = jsonPropertyInfo; } else if ( // Does the current property have `JsonIgnoreAttribute`? !jsonPropertyInfo.IsIgnored && // Is the current property hidden by the previously cached property // (with `new` keyword, or by overriding)? other.ClrName != memberName && // Was a property with the same CLR name was ignored? That property hid the current property, // thus, if it was ignored, the current property should be ignored too. ignoredMembers?.ContainsKey(memberName) != true) { // We throw if we have two public properties that have the same JSON property name, and neither have been ignored. ThrowHelper.ThrowInvalidOperationException_SerializerPropertyNameConflict(Type, jsonPropertyInfo); } // Ignore the current property. } if (jsonPropertyInfo.IsIgnored) { (ignoredMembers ??= new Dictionary<string, JsonPropertyInfo>()).Add(memberName, jsonPropertyInfo); } } private sealed class ParameterLookupKey { public ParameterLookupKey(string name, Type type) { Name = name; Type = type; } public string Name { get; } public Type Type { get; } public override int GetHashCode() { return StringComparer.OrdinalIgnoreCase.GetHashCode(Name); } public override bool Equals([NotNullWhen(true)] object? obj) { Debug.Assert(obj is ParameterLookupKey); ParameterLookupKey other = (ParameterLookupKey)obj; return Type == other.Type && string.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase); } } private sealed class ParameterLookupValue { public ParameterLookupValue(JsonPropertyInfo jsonPropertyInfo) { JsonPropertyInfo = jsonPropertyInfo; } public string? DuplicateName { get; set; } public JsonPropertyInfo JsonPropertyInfo { get; } } private void InitializeConstructorParameters(JsonParameterInfoValues[] jsonParameters, bool sourceGenMode = false) { var parameterCache = new JsonPropertyDictionary<JsonParameterInfo>(Options.PropertyNameCaseInsensitive, jsonParameters.Length); // Cache the lookup from object property name to JsonPropertyInfo using a case-insensitive comparer. // Case-insensitive is used to support both camel-cased parameter names and exact matches when C# // record types or anonymous types are used. // The property name key does not use [JsonPropertyName] or PropertyNamingPolicy since we only bind // the parameter name to the object property name and do not use the JSON version of the name here. var nameLookup = new Dictionary<ParameterLookupKey, ParameterLookupValue>(PropertyCache!.Count); foreach (KeyValuePair<string, JsonPropertyInfo?> kvp in PropertyCache.List) { JsonPropertyInfo jsonProperty = kvp.Value!; string propertyName = jsonProperty.ClrName!; ParameterLookupKey key = new(propertyName, jsonProperty.PropertyType); ParameterLookupValue value = new(jsonProperty); if (!JsonHelpers.TryAdd(nameLookup, key, value)) { // More than one property has the same case-insensitive name and Type. // Remember so we can throw a nice exception if this property is used as a parameter name. ParameterLookupValue existing = nameLookup[key]; existing.DuplicateName = propertyName; } } foreach (JsonParameterInfoValues parameterInfo in jsonParameters) { ParameterLookupKey paramToCheck = new(parameterInfo.Name, parameterInfo.ParameterType); if (nameLookup.TryGetValue(paramToCheck, out ParameterLookupValue? matchingEntry)) { if (matchingEntry.DuplicateName != null) { // Multiple object properties cannot bind to the same constructor parameter. ThrowHelper.ThrowInvalidOperationException_MultiplePropertiesBindToConstructorParameters( Type, parameterInfo.Name!, matchingEntry.JsonPropertyInfo.NameAsString, matchingEntry.DuplicateName); } Debug.Assert(matchingEntry.JsonPropertyInfo != null); JsonPropertyInfo jsonPropertyInfo = matchingEntry.JsonPropertyInfo; JsonParameterInfo jsonParameterInfo = CreateConstructorParameter(parameterInfo, jsonPropertyInfo, sourceGenMode, Options); parameterCache.Add(jsonPropertyInfo.NameAsString, jsonParameterInfo); } // It is invalid for the extension data property to bind with a constructor argument. else if (DataExtensionProperty != null && StringComparer.OrdinalIgnoreCase.Equals(paramToCheck.Name, DataExtensionProperty.NameAsString)) { ThrowHelper.ThrowInvalidOperationException_ExtensionDataCannotBindToCtorParam(DataExtensionProperty); } } ParameterCache = parameterCache; ParameterCount = jsonParameters.Length; } private static JsonParameterInfoValues[] GetParameterInfoArray(ParameterInfo[] parameters) { int parameterCount = parameters.Length; JsonParameterInfoValues[] jsonParameters = new JsonParameterInfoValues[parameterCount]; for (int i = 0; i < parameterCount; i++) { ParameterInfo reflectionInfo = parameters[i]; JsonParameterInfoValues jsonInfo = new() { Name = reflectionInfo.Name!, ParameterType = reflectionInfo.ParameterType, Position = reflectionInfo.Position, HasDefaultValue = reflectionInfo.HasDefaultValue, DefaultValue = reflectionInfo.GetDefaultValue() }; jsonParameters[i] = jsonInfo; } return jsonParameters; } private static bool PropertyIsOverridenAndIgnored( string currentMemberName, Type currentMemberType, bool currentMemberIsVirtual, Dictionary<string, JsonPropertyInfo>? ignoredMembers) { if (ignoredMembers == null || !ignoredMembers.TryGetValue(currentMemberName, out JsonPropertyInfo? ignoredMember)) { return false; } return currentMemberType == ignoredMember.PropertyType && currentMemberIsVirtual && ignoredMember.IsVirtual; } private void ValidateAndAssignDataExtensionProperty(JsonPropertyInfo jsonPropertyInfo) { if (!IsValidDataExtensionProperty(jsonPropertyInfo)) { ThrowHelper.ThrowInvalidOperationException_SerializationDataExtensionPropertyInvalid(Type, jsonPropertyInfo); } DataExtensionProperty = jsonPropertyInfo; } private bool IsValidDataExtensionProperty(JsonPropertyInfo jsonPropertyInfo) { Type memberType = jsonPropertyInfo.PropertyType; bool typeIsValid = typeof(IDictionary<string, object>).IsAssignableFrom(memberType) || typeof(IDictionary<string, JsonElement>).IsAssignableFrom(memberType) || // Avoid a reference to typeof(JsonNode) to support trimming. (memberType.FullName == JsonObjectTypeName && ReferenceEquals(memberType.Assembly, GetType().Assembly)); return typeIsValid && Options.GetConverterInternal(memberType) != null; } private static JsonParameterInfo CreateConstructorParameter( JsonParameterInfoValues parameterInfo, JsonPropertyInfo jsonPropertyInfo, bool sourceGenMode, JsonSerializerOptions options) { if (jsonPropertyInfo.IsIgnored) { return JsonParameterInfo.CreateIgnoredParameterPlaceholder(parameterInfo, jsonPropertyInfo, sourceGenMode); } JsonConverter converter = jsonPropertyInfo.ConverterBase; JsonParameterInfo jsonParameterInfo = converter.CreateJsonParameterInfo(); jsonParameterInfo.Initialize(parameterInfo, jsonPropertyInfo, options); return jsonParameterInfo; } // This method gets the runtime information for a given type or property. // The runtime information consists of the following: // - class type, // - element type (if the type is a collection), // - the converter (either native or custom), if one exists. private static JsonConverter GetConverter( Type type, Type? parentClassType, MemberInfo? memberInfo, JsonSerializerOptions options) { Debug.Assert(type != null); ValidateType(type, parentClassType, memberInfo, options); return options.GetConverterFromMember(parentClassType, type, memberInfo); } private static void ValidateType(Type type, Type? parentClassType, MemberInfo? memberInfo, JsonSerializerOptions options) { if (!options.IsJsonTypeInfoCached(type) && IsInvalidForSerialization(type)) { ThrowHelper.ThrowInvalidOperationException_CannotSerializeInvalidType(type, parentClassType, memberInfo); } } private static bool IsInvalidForSerialization(Type type) { return type.IsPointer || IsByRefLike(type) || type.ContainsGenericParameters; } private static bool IsByRefLike(Type type) { #if BUILDING_INBOX_LIBRARY return type.IsByRefLike; #else if (!type.IsValueType) { return false; } object[] attributes = type.GetCustomAttributes(inherit: false); for (int i = 0; i < attributes.Length; i++) { if (attributes[i].GetType().FullName == "System.Runtime.CompilerServices.IsByRefLikeAttribute") { return true; } } return false; #endif } private static JsonNumberHandling? GetNumberHandlingForType(Type type) { var numberHandlingAttribute = (JsonNumberHandlingAttribute?)JsonSerializerOptions.GetAttributeThatCanHaveMultiple(type, typeof(JsonNumberHandlingAttribute)); return numberHandlingAttribute?.Handling; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string DebuggerDisplay => $"ConverterStrategy.{PropertyInfoForTypeInfo.ConverterStrategy}, {Type.Name}"; } }
44.675
182
0.565543
[ "MIT" ]
AUTOMATE-2001/runtime
src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.cs
28,592
C#
namespace CoderPatros.AuthenticatedHttpClient { // implementation shamelessly ripped off from the Azure sample // https://github.com/Azure-Samples/active-directory-dotnet-daemon/blob/master/TodoListDaemon/Program.cs public class AzureAdAuthenticatedHttpClientOptions { /// <summary> /// The AAD Instance is the instance of Azure, for example public Azure or Azure China. /// </summary> /// <value></value> public string AadInstance { get; set; } = "https://login.microsoftonline.com/{0}"; /// <summary> /// The Tenant is the name of the Azure AD tenant in which this application is registered. /// </summary> /// <value></value> public string Tenant { get; set; } /// <summary> /// The Client ID is used by the application to uniquely identify itself to Azure AD. /// </summary> /// <value></value> public string ClientId { get; set; } /// <summary> /// The App Key is a credential used by the application to authenticate to Azure AD. /// </summary> /// <value></value> public string AppKey { get; set; } /// <summary> /// The Resource Id is the id of the service you are contacting/authenticating to. /// </summary> /// <value></value> public string ResourceId { get; set; } } }
38.888889
108
0.600714
[ "MIT" ]
coderpatros/dotnet-authenticated-httpclient
CoderPatros.AuthenticatedHttpClient.AzureAd/AzureAdAuthenticatedHttpClientOptions.cs
1,402
C#
using JwtRsaHmacSample.Api.Models; using Microsoft.IdentityModel.Tokens; namespace JwtRsaHmacSample.Api.Services { public interface IJwtHandler { JWT Create(string userId); TokenValidationParameters Parameters { get;} } }
23.090909
56
0.724409
[ "MIT" ]
spetz/jwt-hmac-rsa-aspnet-core-sample
src/JwtRsaHmacSample.Api/Services/IJwtHandler.cs
254
C#
using System; namespace Encapsula_Modelo { public class DomainExceptionValidation : Exception { public DomainExceptionValidation(string error) : base(error) { } public static void When(bool hasError, string error) { if (hasError) throw new DomainExceptionValidation(error); } } }
21.764706
68
0.602703
[ "MIT" ]
LucasCancio/poo-com-solid
Modulo01/11_Encapsula_Modelo/Encapsula_Modelo/DomainExceptionValidation.cs
372
C#
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using QuantConnect.Data; using QuantConnect.Orders.Fees; using QuantConnect.Orders.Fills; using QuantConnect.Orders.Slippage; namespace QuantConnect.Securities.Cfd { /// <summary> /// CFD Security Object Implementation for CFD Assets /// </summary> /// <seealso cref="Security"/> public class Cfd : Security { /// <summary> /// Constructor for the CFD security /// </summary> /// <param name="exchangeHours">Defines the hours this exchange is open</param> /// <param name="quoteCurrency">The cash object that represent the quote currency</param> /// <param name="config">The subscription configuration for this security</param> /// <param name="symbolProperties">The symbol properties for this security</param> public Cfd(SecurityExchangeHours exchangeHours, Cash quoteCurrency, SubscriptionDataConfig config, SymbolProperties symbolProperties) : base(config, quoteCurrency, symbolProperties, new CfdExchange(exchangeHours), new CfdCache(), new SecurityPortfolioModel(), new ImmediateFillModel(), new ConstantFeeModel(0), new SpreadSlippageModel(), new ImmediateSettlementModel(), new SecurityMarginModel(50m), new CfdDataFilter() ) { Holdings = new CfdHolding(this); } /// <summary> /// Gets the contract multiplier for this CFD security /// </summary> /// <remarks> /// PipValue := ContractMultiplier * PipSize /// </remarks> public decimal ContractMultiplier { get { return SymbolProperties.ContractMultiplier; } } /// <summary> /// Gets the pip size for this CFD security /// </summary> public decimal PipSize { get { return SymbolProperties.PipSize; } } } }
36.773333
141
0.631255
[ "Apache-2.0" ]
algemeen-ontwikkeling/Lean
Common/Securities/Cfd/Cfd.cs
2,760
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.Aws.ApiGateway { /// <summary> /// Connects a custom domain name registered via `aws.apigateway.DomainName` /// with a deployed API so that its methods can be called via the /// custom domain name. /// /// /// /// &gt; This content is derived from https://github.com/terraform-providers/terraform-provider-aws/blob/master/website/docs/r/api_gateway_base_path_mapping.html.markdown. /// </summary> public partial class BasePathMapping : Pulumi.CustomResource { /// <summary> /// The id of the API to connect. /// </summary> [Output("restApi")] public Output<string> RestApi { get; private set; } = null!; /// <summary> /// Path segment that must be prepended to the path when accessing the API via this mapping. If omitted, the API is exposed at the root of the given domain. /// </summary> [Output("basePath")] public Output<string?> BasePath { get; private set; } = null!; /// <summary> /// The already-registered domain name to connect the API to. /// </summary> [Output("domainName")] public Output<string> DomainName { get; private set; } = null!; /// <summary> /// The name of a specific deployment stage to expose at the given path. If omitted, callers may select any stage by including its name as a path element after the base path. /// </summary> [Output("stageName")] public Output<string?> StageName { get; private set; } = null!; /// <summary> /// Create a BasePathMapping 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 BasePathMapping(string name, BasePathMappingArgs args, CustomResourceOptions? options = null) : base("aws:apigateway/basePathMapping:BasePathMapping", name, args ?? ResourceArgs.Empty, MakeResourceOptions(options, "")) { } private BasePathMapping(string name, Input<string> id, BasePathMappingState? state = null, CustomResourceOptions? options = null) : base("aws:apigateway/basePathMapping:BasePathMapping", name, state, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; 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 BasePathMapping 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 BasePathMapping Get(string name, Input<string> id, BasePathMappingState? state = null, CustomResourceOptions? options = null) { return new BasePathMapping(name, id, state, options); } } public sealed class BasePathMappingArgs : Pulumi.ResourceArgs { /// <summary> /// The id of the API to connect. /// </summary> [Input("restApi", required: true)] public Input<string> RestApi { get; set; } = null!; /// <summary> /// Path segment that must be prepended to the path when accessing the API via this mapping. If omitted, the API is exposed at the root of the given domain. /// </summary> [Input("basePath")] public Input<string>? BasePath { get; set; } /// <summary> /// The already-registered domain name to connect the API to. /// </summary> [Input("domainName", required: true)] public Input<string> DomainName { get; set; } = null!; /// <summary> /// The name of a specific deployment stage to expose at the given path. If omitted, callers may select any stage by including its name as a path element after the base path. /// </summary> [Input("stageName")] public Input<string>? StageName { get; set; } public BasePathMappingArgs() { } } public sealed class BasePathMappingState : Pulumi.ResourceArgs { /// <summary> /// The id of the API to connect. /// </summary> [Input("restApi")] public Input<string>? RestApi { get; set; } /// <summary> /// Path segment that must be prepended to the path when accessing the API via this mapping. If omitted, the API is exposed at the root of the given domain. /// </summary> [Input("basePath")] public Input<string>? BasePath { get; set; } /// <summary> /// The already-registered domain name to connect the API to. /// </summary> [Input("domainName")] public Input<string>? DomainName { get; set; } /// <summary> /// The name of a specific deployment stage to expose at the given path. If omitted, callers may select any stage by including its name as a path element after the base path. /// </summary> [Input("stageName")] public Input<string>? StageName { get; set; } public BasePathMappingState() { } } }
42.019608
182
0.619381
[ "ECL-2.0", "Apache-2.0" ]
Dominik-K/pulumi-aws
sdk/dotnet/Apigateway/BasePathMapping.cs
6,429
C#
/* * Copyright 2019 Mikhail Shiryaev * * 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. * * * Product : Rapid SCADA * Module : KpOpcUa * Summary : Device configuration form * * Author : Mikhail Shiryaev * Created : 2019 * Modified : 2019 */ using Opc.Ua; using Opc.Ua.Client; using Scada.Comm.Devices.OpcUa.Config; using Scada.UI; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace Scada.Comm.Devices.OpcUa.UI { /// <summary> /// Device configuration form. /// <para>Форма настройки конфигурации КП.</para> /// </summary> public partial class FrmConfig : Form { /// <summary> /// Represents an object associated with a node of the server tree. /// </summary> private class ServerNodeTag { public ServerNodeTag(ReferenceDescription rd, NamespaceTable namespaceTable) { DisplayName = rd.DisplayName.Text; OpcNodeId = ExpandedNodeId.ToNodeId(rd.NodeId, namespaceTable); NodeClass = rd.NodeClass; DataType = null; IsFilled = false; } public string DisplayName { get; private set; } public NodeId OpcNodeId { get; private set; } public NodeClass NodeClass { get; private set; } public Type DataType { get; private set; } public bool IsFilled { get; set; } } /// <summary> /// Represents an object associated with a monitored item configuration. /// </summary> internal class ItemConfigTag { public ItemConfigTag(int signal, bool isArray, int arrayLen) { Signal = signal; SetLength(isArray, arrayLen); } public int Signal { get; set; } public int Length { get; set; } public void SetLength(bool isArray, int arrayLen) { Length = arrayLen > 1 ? arrayLen : 1; } public string GetSignalStr() { return Length > 1 ? Signal + " - " + (Signal + Length - 1) : Signal.ToString(); } } private const string FolderOpenImageKey = "folder_open.png"; private const string FolderClosedImageKey = "folder_closed.png"; private static readonly Dictionary<string, Type> KnownTypes = new Dictionary<string, Type> { { "byte", typeof(byte) }, { "double", typeof(double) }, { "Int16", typeof(Int16) }, { "int32", typeof(Int32) }, { "int64", typeof(Int64) }, { "sbyte", typeof(SByte) }, { "float", typeof(Single) }, { "uint16", typeof(UInt16) }, { "uint32", typeof(UInt32) }, { "uint64", typeof(UInt64) }, }; private readonly AppDirs appDirs; // the application directories private readonly int kpNum; // the device number private readonly DeviceConfig deviceConfig; // the device configuration private string configFileName; // the configuration file name private bool modified; // the configuration was modified private bool changing; // controls are being changed programmatically private int? maxCmdNum; // the maximum command number private Session opcSession; // the OPC session private TreeNode subscriptionsNode; // the tree node of the subscriptions private TreeNode commandsNode; // the tree node of the commands /// <summary> /// Initializes a new instance of the class. /// </summary> private FrmConfig() { InitializeComponent(); ctrlSubscription.Visible = false; ctrlItem.Visible = false; ctrlCommand.Visible = false; } /// <summary> /// Initializes a new instance of the class. /// </summary> public FrmConfig(AppDirs appDirs, int kpNum) : this() { this.appDirs = appDirs ?? throw new ArgumentNullException("appDirs"); this.kpNum = kpNum; deviceConfig = new DeviceConfig(); configFileName = ""; modified = false; changing = false; maxCmdNum = null; opcSession = null; subscriptionsNode = null; commandsNode = null; } /// <summary> /// Gets or sets a value indicating whether the configuration was modified. /// </summary> private bool Modified { get { return modified; } set { modified = value; btnSave.Enabled = modified; } } /// <summary> /// Sets the controls according to the configuration. /// </summary> private void ConfigToControls() { changing = true; txtServerUrl.Text = deviceConfig.ConnectionOptions.ServerUrl; FillDeviceTree(); changing = false; } /// <summary> /// Fills the device tree. /// </summary> private void FillDeviceTree() { try { tvDevice.BeginUpdate(); tvDevice.Nodes.Clear(); subscriptionsNode = TreeViewUtils.CreateNode(KpPhrases.SubscriptionsNode, FolderClosedImageKey); commandsNode = TreeViewUtils.CreateNode(KpPhrases.CommandsNode, FolderClosedImageKey); int signal = 1; foreach (SubscriptionConfig subscriptionConfig in deviceConfig.Subscriptions) { TreeNode subscriptionNode = CreateSubscriptionNode(subscriptionConfig); subscriptionsNode.Nodes.Add(subscriptionNode); foreach (ItemConfig itemConfig in subscriptionConfig.Items) { subscriptionNode.Nodes.Add(CreateItemNode(itemConfig)); ItemConfigTag tag = new ItemConfigTag(signal, itemConfig.IsArray, itemConfig.ArrayLen); signal += tag.Length; itemConfig.Tag = tag; } } foreach (CommandConfig commandConfig in deviceConfig.Commands) { commandsNode.Nodes.Add(CreateCommandNode(commandConfig)); } tvDevice.Nodes.Add(subscriptionsNode); tvDevice.Nodes.Add(commandsNode); subscriptionsNode.Expand(); commandsNode.Expand(); } finally { tvDevice.EndUpdate(); } } /// <summary> /// Creates a new subscription node according to the subscription configuration. /// </summary> private TreeNode CreateSubscriptionNode(SubscriptionConfig subscriptionConfig) { TreeNode subscriptionNode = TreeViewUtils.CreateNode( GetDisplayName(subscriptionConfig.DisplayName, KpPhrases.EmptySubscription), FolderClosedImageKey); subscriptionNode.Tag = subscriptionConfig; return subscriptionNode; } /// <summary> /// Creates a new monitored item node according to the item configuration. /// </summary> private TreeNode CreateItemNode(ItemConfig itemConfig) { TreeNode itemNode = TreeViewUtils.CreateNode( GetDisplayName(itemConfig.DisplayName, KpPhrases.EmptyItem), "variable.png"); itemNode.Tag = itemConfig; return itemNode; } /// <summary> /// Creates a new command node according to the command configuration. /// </summary> private TreeNode CreateCommandNode(CommandConfig commandConfig) { TreeNode commandNode = TreeViewUtils.CreateNode( GetDisplayName(commandConfig.DisplayName, KpPhrases.EmptyCommand), "command.png"); commandNode.Tag = commandConfig; return commandNode; } /// <summary> /// Returns the specified display name or the default name. /// </summary> private string GetDisplayName(string displayName, string defaultName) { return string.IsNullOrEmpty(displayName) ? defaultName : displayName; } /// <summary> /// Connects to the OPC server. /// </summary> private async Task<bool> ConnectToOpcServer() { try { OpcUaHelper helper = new OpcUaHelper(appDirs, kpNum, OpcUaHelper.RuntimeKind.View) { CertificateValidation = CertificateValidator_CertificateValidation }; if (await helper.ConnectAsync(deviceConfig.ConnectionOptions)) { opcSession = helper.OpcSession; return true; } else { opcSession = null; return false; } } catch (Exception ex) { ScadaUiUtils.ShowError(KpPhrases.ConnectServerError + ":" + Environment.NewLine + ex.Message); return false; } finally { SetConnButtonsEnabled(); } } /// <summary> /// Disconnects from the OPC server. /// </summary> private void DisconnectFromOpcServer() { try { tvServer.Nodes.Clear(); btnViewAttrs.Enabled = false; btnAddItem.Enabled = false; subscriptionsNode = null; commandsNode = null; if (opcSession != null) { opcSession.Close(); opcSession = null; } } catch (Exception ex) { ScadaUiUtils.ShowError(KpPhrases.DisconnectServerError + ":" + Environment.NewLine + ex.Message); } finally { SetConnButtonsEnabled(); } } /// <summary> /// Browses the server node. /// </summary> private void BrowseServerNode(TreeNode treeNode) { try { tvServer.BeginUpdate(); bool fillNode = false; TreeNodeCollection nodeCollection = null; NodeId nodeId = null; if (treeNode == null) { fillNode = true; nodeCollection = tvServer.Nodes; nodeId = ObjectIds.ObjectsFolder; } else if (treeNode.Tag is ServerNodeTag serverNodeTag) { fillNode = !serverNodeTag.IsFilled; nodeCollection = treeNode.Nodes; nodeId = serverNodeTag.OpcNodeId; } if (fillNode && nodeId != null && opcSession != null) { opcSession.Browse(null, null, nodeId, 0, BrowseDirection.Forward, ReferenceTypeIds.HierarchicalReferences, true, (uint)NodeClass.Variable | (uint)NodeClass.Object | (uint)NodeClass.Method, out byte[] continuationPoint, out ReferenceDescriptionCollection references); nodeCollection.Clear(); foreach (ReferenceDescription rd in references) { TreeNode childNode = TreeViewUtils.CreateNode(rd.DisplayName, SelectImageKey(rd.NodeClass)); childNode.Tag = new ServerNodeTag(rd, opcSession.NamespaceUris); if (rd.NodeClass.HasFlag(NodeClass.Object)) { TreeNode emptyNode = TreeViewUtils.CreateNode(KpPhrases.EmptyNode, "empty.png"); childNode.Nodes.Add(emptyNode); } nodeCollection.Add(childNode); } } } catch (Exception ex) { ScadaUiUtils.ShowError(KpPhrases.BrowseServerError + ":" + Environment.NewLine + ex.Message); } finally { tvServer.EndUpdate(); } } /// <summary> /// Selects an image key depending on the node class. /// </summary> private string SelectImageKey(NodeClass nodeClass) { if (nodeClass.HasFlag(NodeClass.Object)) return "object.png"; else if (nodeClass.HasFlag(NodeClass.Method)) return "method.png"; else return "variable.png"; } /// <summary> /// Adds a new item to the configuration. /// </summary> private bool AddItem(TreeNode serverNode) { if (serverNode?.Tag is ServerNodeTag serverNodeTag && serverNodeTag.NodeClass == NodeClass.Variable) { TreeNode deviceNode = tvDevice.SelectedNode; object deviceNodeTag = deviceNode?.Tag; if (GetTopParentNode(tvDevice.SelectedNode) == commandsNode) { // add a new command if (GetDataTypeName(serverNodeTag.OpcNodeId, out string dataTypeName)) { CommandConfig commandConfig = new CommandConfig { NodeID = serverNodeTag.OpcNodeId.ToString(), DisplayName = serverNodeTag.DisplayName, DataTypeName = dataTypeName, CmdNum = GetNextCmdNum() }; tvDevice.Insert(commandsNode, CreateCommandNode(commandConfig), deviceConfig.Commands, commandConfig); Modified = true; return true; } } else { // create a new monitored item ItemConfig itemConfig = new ItemConfig { NodeID = serverNodeTag.OpcNodeId.ToString(), DisplayName = serverNodeTag.DisplayName, }; itemConfig.Tag = new ItemConfigTag(0, itemConfig.IsArray, itemConfig.ArrayLen); // find a subscription TreeNode subscriptionNode = deviceNode?.FindClosest(typeof(SubscriptionConfig)) ?? subscriptionsNode.LastNode; SubscriptionConfig subscriptionConfig; // add a new subscription if (subscriptionNode == null) { subscriptionConfig = new SubscriptionConfig(); subscriptionNode = CreateSubscriptionNode(subscriptionConfig); tvDevice.Insert(subscriptionsNode, subscriptionNode, deviceConfig.Subscriptions, subscriptionConfig); } else { subscriptionConfig = (SubscriptionConfig)subscriptionNode.Tag; } // add the monitored item TreeNode itemNode = CreateItemNode(itemConfig); tvDevice.Insert(subscriptionNode, itemNode, subscriptionConfig.Items, itemConfig); UpdateSignals(itemNode); Modified = true; return true; } } return false; } /// <summary> /// Gets the data type name of the node. /// </summary> private bool GetDataTypeName(NodeId nodeId, out string dataTypeName) { if (nodeId == null) throw new ArgumentNullException("nodeId"); if (opcSession == null) throw new InvalidOperationException("OPC session must not be null."); try { ReadValueIdCollection nodesToRead = new ReadValueIdCollection { new ReadValueId { NodeId = nodeId, AttributeId = Attributes.DataType } }; opcSession.Read(null, 0, TimestampsToReturn.Neither, nodesToRead, out DataValueCollection results, out DiagnosticInfoCollection diagnosticInfos); ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); DataValue dataTypeValue = results[0]; INode dataType = opcSession.NodeCache.Find((NodeId)dataTypeValue.Value); if (dataType == null) { throw new ScadaException(Localization.UseRussian ? "Не удалось получить тип данных от OPC-сервера." : "Unable to get data type from OPC server."); } if (KnownTypes.TryGetValue(dataType.DisplayName.Text.ToLowerInvariant(), out Type type)) { dataTypeName = type.FullName; return true; } else { ScadaUiUtils.ShowError(string.Format(KpPhrases.UnknownDataType, dataType.DisplayName.Text)); dataTypeName = ""; return false; } } catch (Exception ex) { ScadaUiUtils.ShowError(KpPhrases.GetDataTypeError + ":" + Environment.NewLine + ex.Message); dataTypeName = ""; return false; } } /// <summary> /// Gets the next command number. /// </summary> private int GetNextCmdNum() { if (maxCmdNum == null) { maxCmdNum = deviceConfig.Commands.Any() ? deviceConfig.Commands.Max(x => x.CmdNum) : 0; } return (++maxCmdNum).Value; } /// <summary> /// Sets the enabled property of the connection buttons. /// </summary> private void SetConnButtonsEnabled() { if (opcSession == null) { btnConnect.Enabled = true; btnDisconnect.Enabled = false; } else { btnConnect.Enabled = false; btnDisconnect.Enabled = true; } } /// <summary> /// Sets the enabled property of the buttons that manipulate the server tree. /// </summary> private void SetServerButtonsEnabled() { btnViewAttrs.Enabled = opcSession != null && tvServer.SelectedNode != null; } /// <summary> /// Sets the enabled property of the buttons that manipulate the device tree. /// </summary> private void SetDeviceButtonsEnabled() { ServerNodeTag serverNodeTag = tvServer.SelectedNode?.Tag as ServerNodeTag; bool deviceNodeTagDefined = tvDevice.SelectedNode?.Tag != null; btnAddItem.Enabled = serverNodeTag != null && serverNodeTag.NodeClass == NodeClass.Variable; btnMoveUpItem.Enabled = deviceNodeTagDefined && tvDevice.SelectedNode.PrevNode != null; btnMoveDownItem.Enabled = deviceNodeTagDefined && tvDevice.SelectedNode.NextNode != null; btnDeleteItem.Enabled = deviceNodeTagDefined; } /// <summary> /// Sets the node image as open or closed folder. /// </summary> private void SetFolderImage(TreeNode treeNode) { if (treeNode.ImageKey.StartsWith("folder_")) treeNode.SetImageKey(treeNode.IsExpanded ? FolderOpenImageKey : FolderClosedImageKey); } /// <summary> /// Gets the top parent of the specified node. /// </summary> private TreeNode GetTopParentNode(TreeNode treeNode) { if (treeNode == null) { return null; } else { TreeNode parentNode = treeNode.Parent; while (parentNode != null) { treeNode = parentNode; parentNode = treeNode.Parent; } return treeNode; } } /// <summary> /// Update signals if 2 elements are reversed. /// </summary> private void SwapSignals(TreeNode treeNode1, TreeNode treeNode2) { if (treeNode1?.Tag is ItemConfig itemConfig1 && treeNode2?.Tag is ItemConfig itemConfig2 && itemConfig1.Tag is ItemConfigTag itemConfigTag1 && itemConfig2.Tag is ItemConfigTag itemConfigTag2) { int signal1 = itemConfigTag1.Signal; itemConfigTag1.Signal = itemConfigTag2.Signal; itemConfigTag2.Signal = signal1; ctrlItem.ShowSignal(); } } /// <summary> /// Update signals starting from the specified node. /// </summary> private void UpdateSignals(TreeNode startNode) { TreeNode startSubscrNode = startNode?.FindClosest(typeof(SubscriptionConfig)); if (startSubscrNode != null) { // define initial signal int signal = 1; TreeNode subscrNode = startSubscrNode.PrevNode; while (subscrNode != null) { if (subscrNode.LastNode?.Tag is ItemConfig itemConfig && itemConfig.Tag is ItemConfigTag tag) { signal = tag.Signal + tag.Length; break; } subscrNode = subscrNode.PrevNode; } // recalculate signals subscrNode = startSubscrNode; while (subscrNode != null) { foreach (TreeNode itemNode in subscrNode.Nodes) { if (itemNode.Tag is ItemConfig itemConfig && itemConfig.Tag is ItemConfigTag tag) { tag.Signal = signal; signal += tag.Length; } } subscrNode = subscrNode.NextNode; } ctrlItem.ShowSignal(); } } /// <summary> /// Validates the certificate. /// </summary> private void CertificateValidator_CertificateValidation(CertificateValidator validator, CertificateValidationEventArgs e) { if (e.Error.StatusCode == StatusCodes.BadCertificateUntrusted) e.Accept = true; } private void FrmConfig_Load(object sender, EventArgs e) { // translate the form if (Localization.LoadDictionaries(appDirs.LangDir, "KpOpcUa", out string errMsg)) Translator.TranslateForm(this, GetType().FullName, toolTip); else ScadaUiUtils.ShowError(errMsg); Text = string.Format(Text, kpNum); KpPhrases.Init(); // load a configuration configFileName = DeviceConfig.GetFileName(appDirs.ConfigDir, kpNum); if (File.Exists(configFileName) && !deviceConfig.Load(configFileName, out errMsg)) ScadaUiUtils.ShowError(errMsg); // display the configuration ConfigToControls(); SetConnButtonsEnabled(); SetServerButtonsEnabled(); SetDeviceButtonsEnabled(); Modified = false; } private void FrmConfig_FormClosing(object sender, FormClosingEventArgs e) { if (Modified) { DialogResult result = MessageBox.Show(CommPhrases.SaveKpSettingsConfirm, CommonPhrases.QuestionCaption, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); switch (result) { case DialogResult.Yes: if (!deviceConfig.Save(configFileName, out string errMsg)) { ScadaUiUtils.ShowError(errMsg); e.Cancel = true; } break; case DialogResult.No: break; default: e.Cancel = true; break; } } } private async void btnConnect_ClickAsync(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(deviceConfig.ConnectionOptions.ServerUrl)) ScadaUiUtils.ShowError(KpPhrases.ServerUrlRequired); else if (await ConnectToOpcServer()) BrowseServerNode(null); } private void txtServerUrl_TextChanged(object sender, EventArgs e) { if (!changing) { deviceConfig.ConnectionOptions.ServerUrl = txtServerUrl.Text; Modified = true; } } private void btnDisconnect_Click(object sender, EventArgs e) { DisconnectFromOpcServer(); } private void btnSecurityOptions_Click(object sender, EventArgs e) { if (new FrmSecurityOptions(deviceConfig.ConnectionOptions).ShowDialog() == DialogResult.OK) Modified = true; } private void btnViewAttrs_Click(object sender, EventArgs e) { if (opcSession != null && tvServer.SelectedNode?.Tag is ServerNodeTag serverNodeTag) { new FrmNodeAttr(opcSession, serverNodeTag.OpcNodeId).ShowDialog(); } } private void tvServer_AfterSelect(object sender, TreeViewEventArgs e) { SetServerButtonsEnabled(); SetDeviceButtonsEnabled(); } private void tvServer_BeforeExpand(object sender, TreeViewCancelEventArgs e) { BrowseServerNode(e.Node); } private void tvServer_KeyDown(object sender, KeyEventArgs e) { TreeNode selectedNode = tvServer.SelectedNode; if (e.KeyCode == Keys.Enter && AddItem(selectedNode)) { // go to the next node if (selectedNode.NextNode != null) tvServer.SelectedNode = selectedNode.NextNode; else if (selectedNode.Parent?.NextNode != null) tvServer.SelectedNode = selectedNode.Parent.NextNode; } } private void tvServer_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e) { if (e.Button == MouseButtons.Left) AddItem(tvServer.SelectedNode); } private void btnAddItem_Click(object sender, EventArgs e) { AddItem(tvServer.SelectedNode); } private void btnAddSubscription_Click(object sender, EventArgs e) { // add a new subscription SubscriptionConfig subscriptionConfig = new SubscriptionConfig(); TreeNode subscriptionNode = CreateSubscriptionNode(subscriptionConfig); tvDevice.Insert(subscriptionsNode, subscriptionNode, deviceConfig.Subscriptions, subscriptionConfig); ctrlSubscription.SetFocus(); Modified = true; } private void btnMoveUpItem_Click(object sender, EventArgs e) { // move up the selected item TreeNode selectedNode = tvDevice.SelectedNode; object deviceNodeTag = selectedNode?.Tag; if (deviceNodeTag is SubscriptionConfig) { tvDevice.MoveUpSelectedNode(deviceConfig.Subscriptions); UpdateSignals(selectedNode); } else if (deviceNodeTag is ItemConfig) { if (selectedNode.Parent.Tag is SubscriptionConfig subscriptionConfig) { tvDevice.MoveUpSelectedNode(subscriptionConfig.Items); SwapSignals(selectedNode, selectedNode.NextNode); } } else if (deviceNodeTag is CommandConfig) { tvDevice.MoveUpSelectedNode(deviceConfig.Commands); } Modified = true; } private void btnMoveDownItem_Click(object sender, EventArgs e) { // move down the selected item TreeNode selectedNode = tvDevice.SelectedNode; object deviceNodeTag = tvDevice.SelectedNode?.Tag; if (deviceNodeTag is SubscriptionConfig) { tvDevice.MoveDownSelectedNode(deviceConfig.Subscriptions); UpdateSignals(selectedNode); } else if (deviceNodeTag is ItemConfig) { if (selectedNode.Parent.Tag is SubscriptionConfig subscriptionConfig) { tvDevice.MoveDownSelectedNode(subscriptionConfig.Items); SwapSignals(selectedNode, selectedNode.PrevNode); } } else if (deviceNodeTag is CommandConfig) { tvDevice.MoveDownSelectedNode(deviceConfig.Commands); } Modified = true; } private void btnDeleteItem_Click(object sender, EventArgs e) { // delete the selected item TreeNode selectedNode = tvDevice.SelectedNode; object deviceNodeTag = selectedNode?.Tag; if (deviceNodeTag is SubscriptionConfig) { TreeNode nextSubscrNode = selectedNode.NextNode; tvDevice.RemoveNode(selectedNode, deviceConfig.Subscriptions); UpdateSignals(nextSubscrNode); } else if (deviceNodeTag is ItemConfig) { if (selectedNode.Parent.Tag is SubscriptionConfig subscriptionConfig) { TreeNode subscrNode = selectedNode.Parent; tvDevice.RemoveNode(selectedNode, subscriptionConfig.Items); UpdateSignals(subscrNode); } } else if (deviceNodeTag is CommandConfig) { tvDevice.RemoveNode(selectedNode, deviceConfig.Commands); maxCmdNum = null; // need to recalculate maximum command number } Modified = true; } private void tvDevice_AfterSelect(object sender, TreeViewEventArgs e) { SetDeviceButtonsEnabled(); // show parameters of the selected item gbEmptyItem.Visible = false; ctrlSubscription.Visible = false; ctrlItem.Visible = false; ctrlCommand.Visible = false; object deviceNodeTag = e.Node?.Tag; if (deviceNodeTag is SubscriptionConfig subscriptionConfig) { ctrlSubscription.SubscriptionConfig = subscriptionConfig; ctrlSubscription.Visible = true; } else if (deviceNodeTag is ItemConfig itemConfig) { ctrlItem.ItemConfig = itemConfig; ctrlItem.Visible = true; } else if (deviceNodeTag is CommandConfig commandConfig) { ctrlCommand.CommandConfig = commandConfig; ctrlCommand.Visible = true; } else { gbEmptyItem.Visible = true; } } private void tvDevice_AfterExpand(object sender, TreeViewEventArgs e) { SetFolderImage(e.Node); } private void tvDevice_AfterCollapse(object sender, TreeViewEventArgs e) { SetFolderImage(e.Node); } private void ctrlItem_ObjectChanged(object sender, ObjectChangedEventArgs e) { Modified = true; TreeNode selectedNode = tvDevice.SelectedNode; TreeUpdateTypes treeUpdateTypes = (TreeUpdateTypes)e.ChangeArgument; if (e.ChangedObject is SubscriptionConfig subscriptionConfig) { if (treeUpdateTypes.HasFlag(TreeUpdateTypes.CurrentNode)) selectedNode.Text = GetDisplayName(subscriptionConfig.DisplayName, KpPhrases.EmptySubscription); } else if (e.ChangedObject is ItemConfig itemConfig) { if (treeUpdateTypes.HasFlag(TreeUpdateTypes.CurrentNode)) selectedNode.Text = GetDisplayName(itemConfig.DisplayName, KpPhrases.EmptyItem); if (treeUpdateTypes.HasFlag(TreeUpdateTypes.UpdateSignals)) UpdateSignals(selectedNode); } else if (e.ChangedObject is CommandConfig commandConfig) { if (treeUpdateTypes.HasFlag(TreeUpdateTypes.CurrentNode)) selectedNode.Text = GetDisplayName(commandConfig.DisplayName, KpPhrases.EmptyCommand); } } private void btnSave_Click(object sender, EventArgs e) { if (deviceConfig.Save(configFileName, out string errMsg)) Modified = false; else ScadaUiUtils.ShowError(errMsg); } } }
35.887424
116
0.527625
[ "Apache-2.0" ]
kanadeiar/scada
ScadaComm/OpenKPs/KpOpcUa/OpcUa/UI/FrmConfig.cs
35,450
C#
using System.Data; using FluentMigrator; namespace Group3.Semester3.WebApp.Migrations { [Migration(20201209123550)] public class CreateShareFileLinksTable : Migration { public override void Up() { Create.Table("SharedFilesLinks") .WithColumn("FileId").AsGuid().NotNullable() .WithColumn("Hash").AsString().NotNullable(); Create.ForeignKey() .FromTable("SharedFilesLinks").ForeignColumn("FileId") .ToTable("Files").PrimaryColumn("Id") .OnDeleteOrUpdate(Rule.Cascade); ; } public override void Down() { Delete.Table("SharedFilesLinks"); } } }
27.259259
70
0.567935
[ "MIT" ]
dmai0919-group3/3rd-semester-project
Group3.Semester3.WebApp/Migrations/20201209123550_CreateShareFileLinksTable.cs
738
C#
using Maple.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Maple.Caching { public class DefaultAsyncTokenProvider : IAsyncTokenProvider { private readonly ILogger _logger; public DefaultAsyncTokenProvider(ILogger logger) { this._logger = logger; } public IVolatileToken GetToken(Action<Action<IVolatileToken>> task) { var token = new AsyncVolativeToken(task, _logger); token.QueueWorkItem(); return token; } public class AsyncVolativeToken : IVolatileToken { private readonly Action<Action<IVolatileToken>> _task; private readonly List<IVolatileToken> _taskTokens = new List<IVolatileToken>(); private volatile Exception _taskException; private volatile bool _isTaskFinished; public AsyncVolativeToken(Action<Action<IVolatileToken>> task, ILogger logger) { _task = task; Logger = logger; } public ILogger Logger { get; set; } public void QueueWorkItem() { // Start a work item to collect tokens in our internal array ThreadPool.QueueUserWorkItem(state => { try { _task(token => _taskTokens.Add(token)); } catch (Exception ex) { if (ex.IsFatal()) throw; Logger.Error(ex, "Error while monitoring extension files. Assuming extensions are not current."); _taskException = ex; } finally { _isTaskFinished = true; } }); } public bool IsCurrent { get { // We are current until the task has finished if (_taskException != null) { return false; } if (_isTaskFinished) { return _taskTokens.All(t => t.IsCurrent); } return true; } } } } }
30.731707
121
0.474603
[ "BSD-3-Clause" ]
fengqinhua/Maple-OLD
src/Maple/Caching/DefaultAsyncTokenProvider.cs
2,522
C#
using System.ComponentModel.DataAnnotations; namespace TaskManagerApp.Models.DTOs.Requests { public class UserLoginRequest { [Required] [EmailAddress] public string Email { get; set; } [Required] public string Password { get; set; } } }
22.230769
45
0.640138
[ "MIT" ]
bahkali/100DaysC-
13-TaskManager/TaskManagerApp/Models/DTOs/Requests/UserLoginRequest.cs
289
C#
// ----------------------------------------------------------------------- // <copyright file="Primitives.cs"> // Original Triangle code by Jonathan Richard Shewchuk, http://www.cs.cmu.edu/~quake/triangle.html // Triangle.NET code by Christian Woltering, http://triangle.codeplex.com/ // </copyright> // ----------------------------------------------------------------------- namespace TriangleNet { using System; using TriangleNet.Geometry; using TriangleNet.Tools; /// <summary> /// Provides some primitives regularly used in computational geometry. /// </summary> public static class Primitives { static double splitter; // Used to split double factors for exact multiplication. static double epsilon; // Floating-point machine epsilon. //static double resulterrbound; static double ccwerrboundA; // ccwerrboundB, ccwerrboundC; static double iccerrboundA; // iccerrboundB, iccerrboundC; /// <summary> /// Initialize the variables used for exact arithmetic. /// </summary> /// <remarks> /// 'epsilon' is the largest power of two such that 1.0 + epsilon = 1.0 in /// floating-point arithmetic. 'epsilon' bounds the relative roundoff /// error. It is used for floating-point error analysis. /// /// 'splitter' is used to split floating-point numbers into two half- /// length significands for exact multiplication. /// /// I imagine that a highly optimizing compiler might be too smart for its /// own good, and somehow cause this routine to fail, if it pretends that /// floating-point arithmetic is too much like real arithmetic. /// /// Don't change this routine unless you fully understand it. /// </remarks> public static void ExactInit() { double half; double check, lastcheck; bool every_other; every_other = true; half = 0.5; epsilon = 1.0; splitter = 1.0; check = 1.0; // Repeatedly divide 'epsilon' by two until it is too small to add to // one without causing roundoff. (Also check if the sum is equal to // the previous sum, for machines that round up instead of using exact // rounding. Not that these routines will work on such machines.) do { lastcheck = check; epsilon *= half; if (every_other) { splitter *= 2.0; } every_other = !every_other; check = 1.0 + epsilon; } while ((check != 1.0) && (check != lastcheck)); splitter += 1.0; // Error bounds for orientation and incircle tests. //resulterrbound = (3.0 + 8.0 * epsilon) * epsilon; ccwerrboundA = (3.0 + 16.0 * epsilon) * epsilon; //ccwerrboundB = (2.0 + 12.0 * epsilon) * epsilon; //ccwerrboundC = (9.0 + 64.0 * epsilon) * epsilon * epsilon; iccerrboundA = (10.0 + 96.0 * epsilon) * epsilon; //iccerrboundB = (4.0 + 48.0 * epsilon) * epsilon; //iccerrboundC = (44.0 + 576.0 * epsilon) * epsilon * epsilon; } /// <summary> /// Check, if the three points appear in counterclockwise order. The result is /// also a rough approximation of twice the signed area of the triangle defined /// by the three points. /// </summary> /// <param name="pa">Point a.</param> /// <param name="pb">Point b.</param> /// <param name="pc">Point c.</param> /// <returns>Return a positive value if the points pa, pb, and pc occur in /// counterclockwise order; a negative value if they occur in clockwise order; /// and zero if they are collinear.</returns> /// <remarks> /// Uses exact arithmetic if necessary to ensure a correct answer. The /// result returned is the determinant of a matrix. This determinant is /// computed adaptively, in the sense that exact arithmetic is used only to /// the degree it is needed to ensure that the returned value has the /// correct sign. Hence, this function is usually quite fast, but will run /// more slowly when the input points are collinear or nearly so. /// /// See Robust Predicates paper for details. /// </remarks> public static double CounterClockwise(Point pa, Point pb, Point pc) { double detleft, detright, det; double detsum, errbound; Statistic.CounterClockwiseCount++; detleft = (pa.x - pc.x) * (pb.y - pc.y); detright = (pa.y - pc.y) * (pb.x - pc.x); det = detleft - detright; if (Behavior.NoExact) { return det; } if (detleft > 0.0) { if (detright <= 0.0) { return det; } else { detsum = detleft + detright; } } else if (detleft < 0.0) { if (detright >= 0.0) { return det; } else { detsum = -detleft - detright; } } else { return det; } errbound = ccwerrboundA * detsum; if ((det >= errbound) || (-det >= errbound)) { return det; } return (double)CounterClockwiseDecimal(pa, pb, pc); } private static decimal CounterClockwiseDecimal(Point pa, Point pb, Point pc) { Statistic.CounterClockwiseCountDecimal++; decimal detleft, detright, det /*, detsum*/; detleft = ((decimal)pa.x - (decimal)pc.x) * ((decimal)pb.y - (decimal)pc.y); detright = ((decimal)pa.y - (decimal)pc.y) * ((decimal)pb.x - (decimal)pc.x); det = detleft - detright; if (detleft > 0.0m) { if (detright <= 0.0m) { return det; } else { //detsum = detleft + detright; } } else if (detleft < 0.0m) { if (detright >= 0.0m) { return det; } else { //detsum = -detleft - detright; } } return det; } /// <summary> /// Check if the point pd lies inside the circle passing through pa, pb, and pc. The /// points pa, pb, and pc must be in counterclockwise order, or the sign of the result /// will be reversed. /// </summary> /// <param name="pa">Point a.</param> /// <param name="pb">Point b.</param> /// <param name="pc">Point c.</param> /// <param name="pd">Point d.</param> /// <returns>Return a positive value if the point pd lies inside the circle passing through /// pa, pb, and pc; a negative value if it lies outside; and zero if the four points /// are cocircular.</returns> /// <remarks> /// Uses exact arithmetic if necessary to ensure a correct answer. The /// result returned is the determinant of a matrix. This determinant is /// computed adaptively, in the sense that exact arithmetic is used only to /// the degree it is needed to ensure that the returned value has the /// correct sign. Hence, this function is usually quite fast, but will run /// more slowly when the input points are cocircular or nearly so. /// /// See Robust Predicates paper for details. /// </remarks> public static double InCircle(Point pa, Point pb, Point pc, Point pd) { double adx, bdx, cdx, ady, bdy, cdy; double bdxcdy, cdxbdy, cdxady, adxcdy, adxbdy, bdxady; double alift, blift, clift; double det; double permanent, errbound; Statistic.InCircleCount++; adx = pa.x - pd.x; bdx = pb.x - pd.x; cdx = pc.x - pd.x; ady = pa.y - pd.y; bdy = pb.y - pd.y; cdy = pc.y - pd.y; bdxcdy = bdx * cdy; cdxbdy = cdx * bdy; alift = adx * adx + ady * ady; cdxady = cdx * ady; adxcdy = adx * cdy; blift = bdx * bdx + bdy * bdy; adxbdy = adx * bdy; bdxady = bdx * ady; clift = cdx * cdx + cdy * cdy; det = alift * (bdxcdy - cdxbdy) + blift * (cdxady - adxcdy) + clift * (adxbdy - bdxady); if (Behavior.NoExact) { return det; } permanent = (Math.Abs(bdxcdy) + Math.Abs(cdxbdy)) * alift + (Math.Abs(cdxady) + Math.Abs(adxcdy)) * blift + (Math.Abs(adxbdy) + Math.Abs(bdxady)) * clift; errbound = iccerrboundA * permanent; if ((det > errbound) || (-det > errbound)) { return det; } return (double)InCircleDecimal(pa, pb, pc, pd); } private static decimal InCircleDecimal(Point pa, Point pb, Point pc, Point pd) { Statistic.InCircleCountDecimal++; decimal adx, bdx, cdx, ady, bdy, cdy; decimal bdxcdy, cdxbdy, cdxady, adxcdy, adxbdy, bdxady; decimal alift, blift, clift; adx = (decimal)pa.x - (decimal)pd.x; bdx = (decimal)pb.x - (decimal)pd.x; cdx = (decimal)pc.x - (decimal)pd.x; ady = (decimal)pa.y - (decimal)pd.y; bdy = (decimal)pb.y - (decimal)pd.y; cdy = (decimal)pc.y - (decimal)pd.y; bdxcdy = bdx * cdy; cdxbdy = cdx * bdy; alift = adx * adx + ady * ady; cdxady = cdx * ady; adxcdy = adx * cdy; blift = bdx * bdx + bdy * bdy; adxbdy = adx * bdy; bdxady = bdx * ady; clift = cdx * cdx + cdy * cdy; return alift * (bdxcdy - cdxbdy) + blift * (cdxady - adxcdy) + clift * (adxbdy - bdxady); } /// <summary> /// Return a positive value if the point pd is incompatible with the circle /// or plane passing through pa, pb, and pc (meaning that pd is inside the /// circle or below the plane); a negative value if it is compatible; and /// zero if the four points are cocircular/coplanar. The points pa, pb, and /// pc must be in counterclockwise order, or the sign of the result will be /// reversed. /// </summary> /// <param name="pa">Point a.</param> /// <param name="pb">Point b.</param> /// <param name="pc">Point c.</param> /// <param name="pd">Point d.</param> /// <returns>Return a positive value if the point pd lies inside the circle passing through /// pa, pb, and pc; a negative value if it lies outside; and zero if the four points /// are cocircular.</returns> public static double NonRegular(Point pa, Point pb, Point pc, Point pd) { return InCircle(pa, pb, pc, pd); } /// <summary> /// Find the circumcenter of a triangle. /// </summary> /// <param name="torg">Triangle point.</param> /// <param name="tdest">Triangle point.</param> /// <param name="tapex">Triangle point.</param> /// <param name="xi">Relative coordinate of new location.</param> /// <param name="eta">Relative coordinate of new location.</param> /// <param name="offconstant">Off-center constant.</param> /// <returns>Coordinates of the circumcenter (or off-center)</returns> public static Point FindCircumcenter(Point torg, Point tdest, Point tapex, ref double xi, ref double eta, double offconstant) { double xdo, ydo, xao, yao; double dodist, aodist, dadist; double denominator; double dx, dy, dxoff, dyoff; Statistic.CircumcenterCount++; // Compute the circumcenter of the triangle. xdo = tdest.x - torg.x; ydo = tdest.y - torg.y; xao = tapex.x - torg.x; yao = tapex.y - torg.y; dodist = xdo * xdo + ydo * ydo; aodist = xao * xao + yao * yao; dadist = (tdest.x - tapex.x) * (tdest.x - tapex.x) + (tdest.y - tapex.y) * (tdest.y - tapex.y); if (Behavior.NoExact) { denominator = 0.5 / (xdo * yao - xao * ydo); } else { // Use the counterclockwise() routine to ensure a positive (and // reasonably accurate) result, avoiding any possibility of // division by zero. denominator = 0.5 / CounterClockwise(tdest, tapex, torg); // Don't count the above as an orientation test. Statistic.CounterClockwiseCount--; } dx = (yao * dodist - ydo * aodist) * denominator; dy = (xdo * aodist - xao * dodist) * denominator; // Find the (squared) length of the triangle's shortest edge. This // serves as a conservative estimate of the insertion radius of the // circumcenter's parent. The estimate is used to ensure that // the algorithm terminates even if very small angles appear in // the input PSLG. if ((dodist < aodist) && (dodist < dadist)) { if (offconstant > 0.0) { // Find the position of the off-center, as described by Alper Ungor. dxoff = 0.5 * xdo - offconstant * ydo; dyoff = 0.5 * ydo + offconstant * xdo; // If the off-center is closer to the origin than the // circumcenter, use the off-center instead. if (dxoff * dxoff + dyoff * dyoff < dx * dx + dy * dy) { dx = dxoff; dy = dyoff; } } } else if (aodist < dadist) { if (offconstant > 0.0) { dxoff = 0.5 * xao + offconstant * yao; dyoff = 0.5 * yao - offconstant * xao; // If the off-center is closer to the origin than the // circumcenter, use the off-center instead. if (dxoff * dxoff + dyoff * dyoff < dx * dx + dy * dy) { dx = dxoff; dy = dyoff; } } } else { if (offconstant > 0.0) { dxoff = 0.5 * (tapex.x - tdest.x) - offconstant * (tapex.y - tdest.y); dyoff = 0.5 * (tapex.y - tdest.y) + offconstant * (tapex.x - tdest.x); // If the off-center is closer to the destination than the // circumcenter, use the off-center instead. if (dxoff * dxoff + dyoff * dyoff < (dx - xdo) * (dx - xdo) + (dy - ydo) * (dy - ydo)) { dx = xdo + dxoff; dy = ydo + dyoff; } } } // To interpolate vertex attributes for the new vertex inserted at // the circumcenter, define a coordinate system with a xi-axis, // directed from the triangle's origin to its destination, and // an eta-axis, directed from its origin to its apex. // Calculate the xi and eta coordinates of the circumcenter. xi = (yao * dx - xao * dy) * (2.0 * denominator); eta = (xdo * dy - ydo * dx) * (2.0 * denominator); return new Point(torg.x + dx, torg.y + dy); } /// <summary> /// Find the circumcenter of a triangle. /// </summary> /// <param name="torg">Triangle point.</param> /// <param name="tdest">Triangle point.</param> /// <param name="tapex">Triangle point.</param> /// <param name="xi">Relative coordinate of new location.</param> /// <param name="eta">Relative coordinate of new location.</param> /// <returns>Coordinates of the circumcenter</returns> /// <remarks> /// The result is returned both in terms of x-y coordinates and xi-eta /// (barycentric) coordinates. The xi-eta coordinate system is defined in /// terms of the triangle: the origin of the triangle is the origin of the /// coordinate system; the destination of the triangle is one unit along the /// xi axis; and the apex of the triangle is one unit along the eta axis. /// This procedure also returns the square of the length of the triangle's /// shortest edge. /// </remarks> public static Point FindCircumcenter(Point torg, Point tdest, Point tapex, ref double xi, ref double eta) { double xdo, ydo, xao, yao; double dodist, aodist; double denominator; double dx, dy; Statistic.CircumcenterCount++; // Compute the circumcenter of the triangle. xdo = tdest.x - torg.x; ydo = tdest.y - torg.y; xao = tapex.x - torg.x; yao = tapex.y - torg.y; dodist = xdo * xdo + ydo * ydo; aodist = xao * xao + yao * yao; if (Behavior.NoExact) { denominator = 0.5 / (xdo * yao - xao * ydo); } else { // Use the counterclockwise() routine to ensure a positive (and // reasonably accurate) result, avoiding any possibility of // division by zero. denominator = 0.5 / CounterClockwise(tdest, tapex, torg); // Don't count the above as an orientation test. Statistic.CounterClockwiseCount--; } dx = (yao * dodist - ydo * aodist) * denominator; dy = (xdo * aodist - xao * dodist) * denominator; // To interpolate vertex attributes for the new vertex inserted at // the circumcenter, define a coordinate system with a xi-axis, // directed from the triangle's origin to its destination, and // an eta-axis, directed from its origin to its apex. // Calculate the xi and eta coordinates of the circumcenter. xi = (yao * dx - xao * dy) * (2.0 * denominator); eta = (xdo * dy - ydo * dx) * (2.0 * denominator); return new Point(torg.x + dx, torg.y + dy); } } }
40.229508
100
0.49893
[ "MIT" ]
nmatanski/Advanced-2D-Platformer-Unity
2D Platformer/Assets/Third-Party Assets/Anima2D/Scripts/Editor/Triangle/Primitives.cs
19,634
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Dms.Ambulance.V2100</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace Dms.Ambulance.V2100 { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.IO; using System.Text; [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:hl7-org:v3")] public partial class BXIT_IVL_PQ : IVL_PQ { private string qtyField; private static System.Xml.Serialization.XmlSerializer serializer; public BXIT_IVL_PQ() { this.qtyField = "1"; } [System.Xml.Serialization.XmlAttributeAttribute(DataType="integer")] public string qty { get { return this.qtyField; } set { this.qtyField = value; } } private static System.Xml.Serialization.XmlSerializer Serializer { get { if ((serializer == null)) { serializer = new System.Xml.Serialization.XmlSerializer(typeof(BXIT_IVL_PQ)); } return serializer; } } #region Serialize/Deserialize /// <summary> /// Serializes current BXIT_IVL_PQ object into an XML document /// </summary> /// <returns>string XML value</returns> public virtual string Serialize() { System.IO.StreamReader streamReader = null; System.IO.MemoryStream memoryStream = null; try { memoryStream = new System.IO.MemoryStream(); Serializer.Serialize(memoryStream, this); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); streamReader = new System.IO.StreamReader(memoryStream); return streamReader.ReadToEnd(); } finally { if ((streamReader != null)) { streamReader.Dispose(); } if ((memoryStream != null)) { memoryStream.Dispose(); } } } /// <summary> /// Deserializes workflow markup into an BXIT_IVL_PQ object /// </summary> /// <param name="xml">string workflow markup to deserialize</param> /// <param name="obj">Output BXIT_IVL_PQ object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool Deserialize(string xml, out BXIT_IVL_PQ obj, out System.Exception exception) { exception = null; obj = default(BXIT_IVL_PQ); try { obj = Deserialize(xml); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool Deserialize(string xml, out BXIT_IVL_PQ obj) { System.Exception exception = null; return Deserialize(xml, out obj, out exception); } public static BXIT_IVL_PQ Deserialize(string xml) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(xml); return ((BXIT_IVL_PQ)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } } /// <summary> /// Serializes current BXIT_IVL_PQ object into file /// </summary> /// <param name="fileName">full path of outupt xml file</param> /// <param name="exception">output Exception value if failed</param> /// <returns>true if can serialize and save into file; otherwise, false</returns> public virtual bool SaveToFile(string fileName, out System.Exception exception) { exception = null; try { SaveToFile(fileName); return true; } catch (System.Exception e) { exception = e; return false; } } public virtual void SaveToFile(string fileName) { System.IO.StreamWriter streamWriter = null; try { string xmlString = Serialize(); System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName); streamWriter = xmlFile.CreateText(); streamWriter.WriteLine(xmlString); streamWriter.Close(); } finally { if ((streamWriter != null)) { streamWriter.Dispose(); } } } /// <summary> /// Deserializes xml markup from file into an BXIT_IVL_PQ object /// </summary> /// <param name="fileName">string xml file to load and deserialize</param> /// <param name="obj">Output BXIT_IVL_PQ object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool LoadFromFile(string fileName, out BXIT_IVL_PQ obj, out System.Exception exception) { exception = null; obj = default(BXIT_IVL_PQ); try { obj = LoadFromFile(fileName); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool LoadFromFile(string fileName, out BXIT_IVL_PQ obj) { System.Exception exception = null; return LoadFromFile(fileName, out obj, out exception); } public static BXIT_IVL_PQ LoadFromFile(string fileName) { System.IO.FileStream file = null; System.IO.StreamReader sr = null; try { file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read); sr = new System.IO.StreamReader(file); string xmlString = sr.ReadToEnd(); sr.Close(); file.Close(); return Deserialize(xmlString); } finally { if ((file != null)) { file.Dispose(); } if ((sr != null)) { sr.Dispose(); } } } #endregion #region Clone method /// <summary> /// Create a clone of this BXIT_IVL_PQ object /// </summary> public virtual BXIT_IVL_PQ Clone() { return ((BXIT_IVL_PQ)(this.MemberwiseClone())); } #endregion } }
43.556098
1,368
0.57442
[ "MIT" ]
Kusnaditjung/MimDms
src/Dms.Ambulance.V2100/Generated/BXIT_IVL_PQ.cs
8,929
C#
using AutoMapper; using Autofac; using MassTransit; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.OpenApi.Models; using System; using Microsoft.Extensions.Logging; using Autofac.Extensions.DependencyInjection; using Microsoft.AspNetCore.Mvc; using ResilientIntegration.Api.Filters; using ResilientIntegration.Core; using ResilientIntegration.Api.Infrastructure; using ResilientIntegration.Core.Infrastructure; using Serilog; namespace WebApi { public class Startup { private readonly IHostingEnvironment _env; private readonly IConfiguration _config; private readonly ILoggerFactory _loggerFactory; public Startup(IHostingEnvironment env, IConfiguration config, ILoggerFactory loggerFactory) { _env = env; _config = config; _loggerFactory = loggerFactory; } public IConfiguration Configuration { get; } public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddMvc(options => { options.Filters.Add<ApiExceptionFilter>(); }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Resilient Integration API", Version = "v1" }); }); services.AddAutoMapper(typeof(Startup)); services.AddMassTransit(); var builder = new ContainerBuilder(); builder.Populate(services); builder.RegisterModule(new ApiModule()); builder.RegisterModule(new BusModule()); var container = builder.Build(); return new AutofacServiceProvider(container); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseSerilogRequestLogging(); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Resilient Integration V1"); c.RoutePrefix = string.Empty; }); app.UseMvcWithDefaultRoute(); } } }
30.886076
108
0.642623
[ "Apache-2.0" ]
ryanlangton/resilient-integration
src/web-api/Startup.cs
2,440
C#
namespace StyleCopAnalyzers.CLI; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Reflection; using System.Runtime.Loader; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; public class AnalyzerLoader { public IReadOnlyDictionary<string, ReportDiagnostic> RuleSets => rulesets; private const string StyleCopAnalyzersDll = "StyleCop.Analyzers"; private const string StyleCopAnalyzersCodeFixesDll = "StyleCop.Analyzers.CodeFixes"; private readonly Dictionary<string, ReportDiagnostic> rulesets = new Dictionary<string, ReportDiagnostic>(); public AnalyzerLoader(string ruleSetFilePath) { if (File.Exists(ruleSetFilePath)) { RuleSet.GetDiagnosticOptionsFromRulesetFile(ruleSetFilePath, out rulesets); } rulesets.Add("AD0001", ReportDiagnostic.Error); } public ImmutableArray<DiagnosticAnalyzer> GetAnalyzers() { var name = new AssemblyName(StyleCopAnalyzersDll); var stylecop = AssemblyLoadContext.Default.LoadFromAssemblyName(name); var assembly = stylecop.GetType("StyleCop.Analyzers.NoCodeFixAttribute")?.Assembly; if (assembly == null) { return default; } var diagnosticAnalyzerType = typeof(DiagnosticAnalyzer); var analyzers = ImmutableArray.CreateBuilder<DiagnosticAnalyzer>(); foreach (var type in assembly.GetTypes()) { if (!type.IsSubclassOf(diagnosticAnalyzerType) || type.IsAbstract) { continue; } if (!(Activator.CreateInstance(type) is DiagnosticAnalyzer analyzer)) { continue; } if (!IsValidAnalyzer(analyzer, rulesets)) { continue; } analyzers.Add(analyzer!); } return analyzers.ToImmutable(); } public ImmutableArray<CodeFixProvider> GetCodeFixProviders() { var name = new AssemblyName(StyleCopAnalyzersCodeFixesDll); var assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(name); var codeFixProviderType = typeof(CodeFixProvider); var providers = ImmutableArray.CreateBuilder<CodeFixProvider>(); foreach (var type in assembly.GetTypes()) { if (!type.IsSubclassOf(codeFixProviderType) || type.IsAbstract) { continue; } if (!(Activator.CreateInstance(type) is CodeFixProvider codeFixProvider)) { continue; } if (!IsValidCodeFixProvider(codeFixProvider, rulesets)) { continue; } providers.Add(codeFixProvider); } return providers.ToImmutableArray(); } private bool IsValidAnalyzer(DiagnosticAnalyzer analyzer, Dictionary<string, ReportDiagnostic> rulesets) { foreach (var diagnostic in analyzer.SupportedDiagnostics) { if (!IsValidRule(diagnostic.Id, rulesets)) { return false; } } return true; } private bool IsValidCodeFixProvider(CodeFixProvider codeFixProvider, Dictionary<string, ReportDiagnostic> rulesets) { foreach (var diagnosticId in codeFixProvider.FixableDiagnosticIds) { if (!IsValidRule(diagnosticId, rulesets)) { return false; } } return true; } private bool IsValidRule(string diagnosticId, Dictionary<string, ReportDiagnostic> rulesets) { if (rulesets.ContainsKey(diagnosticId)) { if (rulesets[diagnosticId] == ReportDiagnostic.Suppress || rulesets[diagnosticId] == ReportDiagnostic.Hidden) { return false; } } return true; } }
29.820896
119
0.627377
[ "Apache-2.0" ]
rookxx/StyleCopAnalyzersCmd
src/AnalyzerLoader.cs
3,996
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; [ExecuteInEditMode] [AddComponentMenu("Enviro/Standard/AddionalCamera")] public class EnviroAdditionalCamera : MonoBehaviour { #if ENVIRO_HD public bool addEnviroSkyRendering = true; public bool addEnviroSkyPostProcessing = true; public bool addWeatherEffects = true; private Camera myCam; private EnviroSkyRendering skyRender; private EnviroPostProcessing enviroPostProcessing; private GameObject EffectHolder; private GameObject VFX; private List<EnviroWeatherPrefab> zoneWeather = new List<EnviroWeatherPrefab>(); private EnviroWeatherPrefab currentWeather; private void OnEnable() { myCam = GetComponent<Camera>(); if (myCam != null) InitImageEffects(); } private void Start() { if (addWeatherEffects) { CreateEffectHolder(); StartCoroutine(SetupWeatherEffects()); } } void Update () { if (addWeatherEffects) UpdateWeatherEffects(); } private void CreateEffectHolder () { int childs = myCam.transform.childCount; for (int i = childs - 1; i >= 0; i--) { if(myCam.transform.GetChild(i).gameObject.name == "Effect Holder") DestroyImmediate(myCam.transform.GetChild(i).gameObject); } EffectHolder = new GameObject(); EffectHolder.name = "Effect Holder"; EffectHolder.transform.SetParent(myCam.transform,false); VFX = new GameObject(); VFX.name = "VFX"; VFX.transform.SetParent(EffectHolder.transform, false); } IEnumerator SetupWeatherEffects() { yield return new WaitForSeconds(1f); for (int i = 0; i < EnviroSky.instance.Weather.weatherPresets.Count; i++) { //Create Weather Prefab GameObject wPrefab = new GameObject(); EnviroWeatherPrefab wP = wPrefab.AddComponent<EnviroWeatherPrefab>(); wP.weatherPreset = EnviroSky.instance.Weather.weatherPresets[i]; wPrefab.name = wP.weatherPreset.Name; //Add Particle Effects for (int w = 0; w < wP.weatherPreset.effectSystems.Count; w++) { if (wP.weatherPreset.effectSystems[w] == null || wP.weatherPreset.effectSystems[w].prefab == null) { Debug.Log("Warning! Missing Particle System Entry: " + wP.weatherPreset.Name); Destroy(wPrefab); break; } GameObject eS = (GameObject)Instantiate(wP.weatherPreset.effectSystems[w].prefab, wPrefab.transform); eS.transform.localPosition = wP.weatherPreset.effectSystems[w].localPositionOffset; eS.transform.localEulerAngles = wP.weatherPreset.effectSystems[w].localRotationOffset; ParticleSystem pS = eS.GetComponent<ParticleSystem>(); if (pS != null) wP.effectSystems.Add(pS); else { pS = eS.GetComponentInChildren<ParticleSystem>(); if (pS != null) wP.effectSystems.Add(pS); else { Debug.Log("No Particle System found in prefab in weather preset: " + wP.weatherPreset.Name); Destroy(wPrefab); break; } } } wP.effectEmmisionRates.Clear(); wPrefab.transform.parent = VFX.transform; wPrefab.transform.localPosition = Vector3.zero; wPrefab.transform.localRotation = Quaternion.identity; zoneWeather.Add(wP); } // Setup Particle Systems Emission Rates for (int i = 0; i < zoneWeather.Count; i++) { for (int i2 = 0; i2 < zoneWeather[i].effectSystems.Count; i2++) { zoneWeather[i].effectEmmisionRates.Add(EnviroSkyMgr.instance.GetEmissionRate(zoneWeather[i].effectSystems[i2])); EnviroSkyMgr.instance.SetEmissionRate(zoneWeather[i].effectSystems[i2], 0f); } } //Set Current Weather if (EnviroSky.instance.Weather.currentActiveWeatherPrefab != null) { for (int i = 0; i < zoneWeather.Count; i++) { if (zoneWeather[i].weatherPreset == EnviroSky.instance.Weather.currentActiveWeatherPrefab.weatherPreset) currentWeather = zoneWeather[i]; } } } private void UpdateWeatherEffects() { if (EnviroSky.instance.Weather.currentActiveWeatherPrefab == null || currentWeather == null) return; if(EnviroSky.instance.Weather.currentActiveWeatherPrefab.weatherPreset != currentWeather.weatherPreset) { for(int i = 0; i < zoneWeather.Count; i++) { if (zoneWeather[i].weatherPreset == EnviroSky.instance.Weather.currentActiveWeatherPrefab.weatherPreset) currentWeather = zoneWeather[i]; } } UpdateEffectSystems(currentWeather, true); } private void UpdateEffectSystems(EnviroWeatherPrefab id, bool withTransition) { if (id != null) { float speed = 500f * Time.deltaTime; if (withTransition) speed = EnviroSkyMgr.instance.WeatherSettings.effectTransitionSpeed * Time.deltaTime; for (int i = 0; i < id.effectSystems.Count; i++) { if (id.effectSystems[i].isStopped) id.effectSystems[i].Play(); // Set EmissionRate float val = Mathf.Lerp(EnviroSkyMgr.instance.GetEmissionRate(id.effectSystems[i]), id.effectEmmisionRates[i] * EnviroSky.instance.qualitySettings.GlobalParticleEmissionRates, speed) * EnviroSkyMgr.instance.InteriorZoneSettings.currentInteriorWeatherEffectMod; EnviroSkyMgr.instance.SetEmissionRate(id.effectSystems[i], val); } for (int i = 0; i < zoneWeather.Count; i++) { if (zoneWeather[i].gameObject != id.gameObject) { for (int i2 = 0; i2 < zoneWeather[i].effectSystems.Count; i2++) { float val2 = Mathf.Lerp(EnviroSkyMgr.instance.GetEmissionRate(zoneWeather[i].effectSystems[i2]), 0f, speed); if (val2 < 1f) val2 = 0f; EnviroSkyMgr.instance.SetEmissionRate(zoneWeather[i].effectSystems[i2], val2); if (val2 == 0f && !zoneWeather[i].effectSystems[i2].isStopped) { zoneWeather[i].effectSystems[i2].Stop(); } } } } } } private void InitImageEffects() { if (addEnviroSkyRendering) { skyRender = myCam.gameObject.GetComponent<EnviroSkyRendering>(); if (skyRender == null) skyRender = myCam.gameObject.AddComponent<EnviroSkyRendering>(); skyRender.isAddionalCamera = true; #if UNITY_EDITOR string[] assets = UnityEditor.AssetDatabase.FindAssets("enviro_spot_cookie", null); for (int idx = 0; idx < assets.Length; idx++) { string path = UnityEditor.AssetDatabase.GUIDToAssetPath(assets[idx]); if (path.Length > 0) { skyRender.DefaultSpotCookie = UnityEditor.AssetDatabase.LoadAssetAtPath<Texture>(path); } } #endif } if (addEnviroSkyPostProcessing) { enviroPostProcessing = myCam.gameObject.GetComponent<EnviroPostProcessing>(); if (enviroPostProcessing == null) enviroPostProcessing = myCam.gameObject.AddComponent<EnviroPostProcessing>(); } } #endif }
35.064378
275
0.573195
[ "Unlicense" ]
adityawahyu04/Tugas-Pertemuan-1-Lab-Pemgame
Assets/Enviro - Sky and Weather/Enviro Standard/Scripts/Utilities/EnviroAdditionalCamera.cs
8,172
C#
using System; namespace CheckExcellent { class CheckExcellent { private static double grade; static void Main(string[] args) { var garde = Double.Parse(Console.ReadLine()); if (grade >= 5.5) { } } } }
15.631579
57
0.484848
[ "MIT" ]
ztimofeev/Programming_Basics_CSharp-repo
Lecture-3-ConditionStatments/CheckExcellent/CheckExcellent.cs
299
C#
// Copyright (c) 2021 Salim Mayaleh. All Rights Reserved // Licensed under the BSD-3-Clause License // Generated at 28.11.2021 16:31:27 by RaynetApiDocToDotnet.ApiDocParser, created by Salim Mayaleh. using System; using Newtonsoft.Json; using System.Collections.Generic; using System.Threading.Tasks; using Maya.Raynet.Crm.Attribute; namespace Maya.Raynet.Crm.Request.Put { public class Credit : PutRequest { protected override List<string> Actions {get; set;} = new List<string>(); public Credit() { Actions.Add("invoice"); Actions.Add("creditNote"); } public Credit SetRequestData(Model.Request.Put.Credit body) { this.requestBody = body; return this; } public async Task<Ext.Unit> ExecuteAsync(ApiClient apiClient) => await base.ExecuteNoResultAsync<Model.Request.Put.Credit>(apiClient, this.requestBody); private Model.Request.Put.Credit requestBody; } }
29.314286
106
0.655945
[ "BSD-3-Clause" ]
mayaleh/Maya.Raynet.Crm
src/Maya.Raynet.Crm/Request/Put/Credit.cs
1,026
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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.ContractsLight; using System.IO; using System.Text; using System.Threading.Tasks; using BuildXL.Native.IO; using BuildXL.Utilities; using BuildXL.Utilities.VmCommandProxy; namespace BuildXL.Processes { /// <summary> /// Sandboxed process that will be executed in VM. /// </summary> public class ExternalVmSandboxedProcess : ExternalSandboxedProcess { /// <inheritdoc /> public override int ProcessId => Process?.Id ?? -1; /// <summary> /// Underlying managed <see cref="Process"/> object. /// </summary> public Process Process => m_processExecutor?.Process; /// <inheritdoc /> public override string StdOut => m_processExecutor?.StdOutCompleted ?? false ? m_output.ToString() : string.Empty; /// <inheritdoc /> public override string StdErr => m_processExecutor?.StdErrCompleted ?? false ? m_error.ToString() : string.Empty; /// <inheritdoc /> public override int? ExitCode => m_processExecutor.ExitCompleted ? Process?.ExitCode : default; private readonly StringBuilder m_output = new StringBuilder(); private readonly StringBuilder m_error = new StringBuilder(); private AsyncProcessExecutor m_processExecutor; private readonly ExternalToolSandboxedProcessExecutor m_tool; private readonly VmInitializer m_vmInitializer; /// <summary> /// Creates an instance of <see cref="ExternalVmSandboxedProcess"/>. /// </summary> public ExternalVmSandboxedProcess( SandboxedProcessInfo sandboxedProcessInfo, VmInitializer vmInitializer, ExternalToolSandboxedProcessExecutor tool) : base(sandboxedProcessInfo) { Contract.Requires(vmInitializer != null); Contract.Requires(tool != null); m_vmInitializer = vmInitializer; m_tool = tool; } /// <inheritdoc /> public override void Dispose() { m_processExecutor?.Dispose(); } /// <inheritdoc /> public override ulong? GetActivePeakMemoryUsage() => m_processExecutor?.GetActivePeakMemoryUsage(); /// <inheritdoc /> [SuppressMessage("AsyncUsage", "AsyncFixer02:MissingAsyncOpportunity")] public override async Task<SandboxedProcessResult> GetResultAsync() { Contract.Requires(m_processExecutor != null); // (1) Wait for VmCommandProxy. await m_processExecutor.WaitForExitAsync(); await m_processExecutor.WaitForStdOutAndStdErrAsync(); // (2) Validate result of VmCommandProxy. if (m_processExecutor.TimedOut || m_processExecutor.Killed) { // If timed out/killed, then sandboxed process result may have not been deserialized yet. return CreateResultForVmCommandProxyFailure(); } if (Process.ExitCode != 0) { return CreateResultForVmCommandProxyFailure(); } if (!FileUtilities.FileExistsNoFollow(RunOutputPath)) { m_error.AppendLine($"Could not find VM output file '{RunOutputPath}"); return CreateResultForVmCommandProxyFailure(); } // (3) Validate the result of sandboxed process executor run by VmCommandProxy. RunResult runVmResult = ExceptionUtilities.HandleRecoverableIOException( () => VmSerializer.DeserializeFromFile<RunResult>(RunOutputPath), e => m_error.AppendLine(e.Message)); if (runVmResult == null) { return CreateResultForVmCommandProxyFailure(); } if (runVmResult.ProcessStateInfo.ExitCode != 0) { return CreateResultForSandboxExecutorFailure(runVmResult); } return DeserializeSandboxedProcessResultFromFile(); } /// <inheritdoc /> public override Task KillAsync() => KillProcessExecutorAsync(m_processExecutor); /// <inheritdoc /> public override void Start() { RunInVm(); } private void RunInVm() { // (1) Serialize sandboxed prosess info. SerializeSandboxedProcessInfoToFile(); // (2) Create and serialize run request. var runRequest = new RunRequest { AbsolutePath = m_tool.ExecutablePath, Arguments = m_tool.CreateArguments(GetSandboxedProcessInfoFile(), GetSandboxedProcessResultsFile()), WorkingDirectory = GetOutputDirectory() }; VmSerializer.SerializeToFile(RunRequestPath, runRequest); // (2) Create a process to execute VmCommandProxy. string arguments = $"{VmCommands.Run} /{VmCommands.Params.InputJsonFile}:\"{RunRequestPath}\" /{VmCommands.Params.OutputJsonFile}:\"{RunOutputPath}\""; var process = CreateVmCommandProxyProcess(arguments); LogExternalExecution($"call (wd: {process.StartInfo.WorkingDirectory}) {m_vmInitializer.VmCommandProxy} {arguments}"); m_processExecutor = new AsyncProcessExecutor( process, TimeSpan.FromMilliseconds(-1), // Timeout should only be applied to the process that the external tool executes. line => AppendLineIfNotNull(m_output, line), line => AppendLineIfNotNull(m_error, line), SandboxedProcessInfo.Provenance, message => LogExternalExecution(message)); m_processExecutor.Start(); } private string RunRequestPath => GetVmCommandProxyPath("VmRunInput"); private string RunOutputPath => GetVmCommandProxyPath("VmRunOutput"); private string GetVmCommandProxyPath(string command) => Path.Combine(GetOutputDirectory(), $"{command}-Pip{SandboxedProcessInfo.PipSemiStableHash:X16}.json"); private Process CreateVmCommandProxyProcess(string arguments) { return new Process { StartInfo = new ProcessStartInfo { FileName = m_vmInitializer.VmCommandProxy, Arguments = arguments, WorkingDirectory = GetOutputDirectory(), RedirectStandardError = true, RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true }, EnableRaisingEvents = true }; } private SandboxedProcessResult CreateResultForVmCommandProxyFailure() { string output = m_output.ToString(); string error = m_error.ToString(); string hint = Path.GetFileNameWithoutExtension(m_tool.ExecutablePath); return CreateResultForFailure( exitCode: m_processExecutor.TimedOut ? ExitCodes.Timeout : Process.ExitCode, killed: m_processExecutor.Killed, timedOut: m_processExecutor.TimedOut, output: output, error: error, hint: hint); } private SandboxedProcessResult CreateResultForSandboxExecutorFailure(RunResult runVmResult) { Contract.Requires(runVmResult != null); return CreateResultForFailure( exitCode: runVmResult.ProcessStateInfo.ExitCode, killed: false, timedOut: false, output: runVmResult.StdOut ?? string.Empty, error: runVmResult.StdErr ?? string.Empty, hint: Path.GetFileNameWithoutExtension(m_tool.ExecutablePath)); } } }
39.028169
167
0.602069
[ "MIT" ]
erickulcyk/BuildXL
Public/Src/Engine/Processes/ExternalVMSandboxedProcess.cs
8,315
C#
using CognitiveRelay.Models; using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using Newtonsoft.Json; using System; namespace CognitiveRelay { public class Comment { [BsonId] [JsonIgnore] public ObjectId _id { get; set; } public string Language { get; set; } public string Text { get; set; } public double? Score { get; set; } public SentimentRequest ToSentimentRequest() { return new SentimentRequest() { Documents = new[] { new RequestDocument() { Id = 1, Language = Language, Text = Text} } }; } public DateTime? CreatedOn { get; set; } [JsonIgnore] public string Hash { get; set; } } }
24.029412
59
0.543452
[ "MIT" ]
ikemtz/CIS373
cognitive-relay/src/Comment.cs
819
C#
namespace Negum.Core.Managers.Entries { /// <summary> /// Represents Sprite with Sound entry in section. /// </summary> /// /// <author> /// https://github.com/TheNegumProject/Negum.Core /// </author> public interface ISpriteSoundEntry : IManagerSectionEntry<ISpriteSoundEntry> { IVectorEntry Sprite { get; } IVectorEntry Sound { get; } } /// <summary> /// </summary> /// /// <author> /// https://github.com/TheNegumProject/Negum.Core /// </author> public class SpriteSoundEntry : ManagerSectionEntry<ISpriteSoundEntry>, ISpriteSoundEntry { public IVectorEntry Sprite { get; private set; } public IVectorEntry Sound { get; private set; } public override ISpriteSoundEntry Get() { this.Sprite = this.Section.GetValue<IVectorEntry>(this.FieldKey + ".spr"); this.Sound = this.Section.GetValue<IVectorEntry>(this.FieldKey + ".snd"); return this; } } }
29.142857
93
0.605882
[ "MIT" ]
TheNegumProject/Negum.Core
Negum.Core/Managers/Entries/ISpriteSoundEntry.cs
1,020
C#
///////////////////////////////////////////////////////////////////////////////// // Paint.NET // // Copyright (C) dotPDN LLC, Rick Brewster, Tom Jackson, and contributors. // // Portions Copyright (C) Microsoft Corporation. All Rights Reserved. // // See src/Resources/Files/License.txt for full licensing and attribution // // details. // // . // ///////////////////////////////////////////////////////////////////////////////// using PixelDotNet.IndirectUI; using PixelDotNet.PropertySystem; using PixelDotNet.SystemLayer; using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Runtime.Serialization; using System.Text; namespace PixelDotNet { public sealed class PngFileType : InternalFileType { protected override bool IsReflexive(PropertyBasedSaveConfigToken token) { PngBitDepthUIChoices bitDepth = (PngBitDepthUIChoices)token.GetProperty<StaticListChoiceProperty>(PropertyNames.BitDepth).Value; // Only 32-bit is reflexive return (bitDepth == PngBitDepthUIChoices.Bpp32); } public PngFileType() : base("PNG", FileTypeFlags.SupportsLoading | FileTypeFlags.SupportsSaving, new string[] { ".png" }) { } public enum PropertyNames { BitDepth = 0, DitherLevel = 1, Threshold = 2 } public enum PngBitDepthUIChoices { AutoDetect = 0, Bpp32 = 1, Bpp24 = 2, Bpp8 = 3 } public override ControlInfo OnCreateSaveConfigUI(PropertyCollection props) { ControlInfo configUI = CreateDefaultSaveConfigUI(props); configUI.SetPropertyControlValue( PropertyNames.BitDepth, ControlInfoPropertyNames.DisplayName, PdnResources.GetString("PngFileType.ConfigUI.BitDepth.DisplayName")); PropertyControlInfo bitDepthPCI = configUI.FindControlForPropertyName(PropertyNames.BitDepth); bitDepthPCI.SetValueDisplayName(PngBitDepthUIChoices.AutoDetect, PdnResources.GetString("PngFileType.ConfigUI.BitDepth.AutoDetect.DisplayName")); bitDepthPCI.SetValueDisplayName(PngBitDepthUIChoices.Bpp32, PdnResources.GetString("PngFileType.ConfigUI.BitDepth.Bpp32.DisplayName")); bitDepthPCI.SetValueDisplayName(PngBitDepthUIChoices.Bpp24, PdnResources.GetString("PngFileType.ConfigUI.BitDepth.Bpp24.DisplayName")); bitDepthPCI.SetValueDisplayName(PngBitDepthUIChoices.Bpp8, PdnResources.GetString("PngFileType.ConfigUI.BitDepth.Bpp8.DisplayName")); configUI.SetPropertyControlType(PropertyNames.BitDepth, PropertyControlType.RadioButton); configUI.SetPropertyControlValue( PropertyNames.DitherLevel, ControlInfoPropertyNames.DisplayName, PdnResources.GetString("PngFileType.ConfigUI.DitherLevel.DisplayName")); configUI.SetPropertyControlValue( PropertyNames.Threshold, ControlInfoPropertyNames.DisplayName, PdnResources.GetString("PngFileType.ConfigUI.Threshold.DisplayName")); configUI.SetPropertyControlValue( PropertyNames.Threshold, ControlInfoPropertyNames.Description, PdnResources.GetString("PngFileType.ConfigUI.Threshold.Description")); return configUI; } public override PropertyCollection OnCreateSavePropertyCollection() { List<Property> props = new List<Property>(); props.Add(StaticListChoiceProperty.CreateForEnum<PngBitDepthUIChoices>(PropertyNames.BitDepth, PngBitDepthUIChoices.AutoDetect, false)); props.Add(new Int32Property(PropertyNames.DitherLevel, 7, 0, 8)); props.Add(new Int32Property(PropertyNames.Threshold, 128, 0, 255)); List<PropertyCollectionRule> rules = new List<PropertyCollectionRule>(); rules.Add(new ReadOnlyBoundToValueRule<object, StaticListChoiceProperty>( PropertyNames.Threshold, PropertyNames.BitDepth, PngBitDepthUIChoices.Bpp8, true)); rules.Add(new ReadOnlyBoundToValueRule<object, StaticListChoiceProperty>( PropertyNames.DitherLevel, PropertyNames.BitDepth, PngBitDepthUIChoices.Bpp8, true)); PropertyCollection pc = new PropertyCollection(props, rules); return pc; } protected override Document OnLoad(Stream input) { using (Image image = PdnResources.LoadImage(input)) { Document document = Document.FromImage(image); return document; } } internal override Set<SavableBitDepths> CreateAllowedBitDepthListFromToken(PropertyBasedSaveConfigToken token) { PngBitDepthUIChoices bitDepthFromToken = (PngBitDepthUIChoices)token.GetProperty<StaticListChoiceProperty>(PropertyNames.BitDepth).Value; Set<SavableBitDepths> bitDepths = new Set<SavableBitDepths>(); switch (bitDepthFromToken) { case PngBitDepthUIChoices.AutoDetect: bitDepths.AddRange(SavableBitDepths.Rgb24, SavableBitDepths.Rgb8, SavableBitDepths.Rgba32, SavableBitDepths.Rgba8); break; case PngBitDepthUIChoices.Bpp24: bitDepths.AddRange(SavableBitDepths.Rgb24); break; case PngBitDepthUIChoices.Bpp32: bitDepths.AddRange(SavableBitDepths.Rgba32); break; case PngBitDepthUIChoices.Bpp8: bitDepths.AddRange(SavableBitDepths.Rgb8, SavableBitDepths.Rgba8); break; default: throw new InvalidEnumArgumentException("bitDepthFromToken", (int)bitDepthFromToken, typeof(PngBitDepthUIChoices)); } return bitDepths; } internal override int GetThresholdFromToken(PropertyBasedSaveConfigToken token) { int threshold = token.GetProperty<Int32Property>(PropertyNames.Threshold).Value; return threshold; } internal override int GetDitherLevelFromToken(PropertyBasedSaveConfigToken token) { int ditherLevel = token.GetProperty<Int32Property>(PropertyNames.DitherLevel).Value; return ditherLevel; } internal override unsafe void FinalSave( Document input, Stream output, Surface scratchSurface, int ditherLevel, SavableBitDepths bitDepth, PropertyBasedSaveConfigToken token, ProgressEventHandler progressCallback) { if (bitDepth == SavableBitDepths.Rgba32) { ImageCodecInfo icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Png); EncoderParameters parms = new EncoderParameters(1); EncoderParameter parm = new EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 32); parms.Param[0] = parm; using (Bitmap bitmap = scratchSurface.CreateAliasedBitmap()) { GdiPlusFileType.LoadProperties(bitmap, input); bitmap.Save(output, icf, parms); } } else if (bitDepth == SavableBitDepths.Rgb24) { // In order to save memory, we 'squish' the 32-bit bitmap down to 24-bit in-place // instead of allocating a new bitmap and copying it over. SquishSurfaceTo24Bpp(scratchSurface); ImageCodecInfo icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Png); EncoderParameters parms = new EncoderParameters(1); EncoderParameter parm = new EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 24); parms.Param[0] = parm; using (Bitmap bitmap = CreateAliased24BppBitmap(scratchSurface)) { GdiPlusFileType.LoadProperties(bitmap, input); bitmap.Save(output, icf, parms); } } else if (bitDepth == SavableBitDepths.Rgb8) { using (Bitmap quantized = Quantize(scratchSurface, ditherLevel, 256, false, progressCallback)) { ImageCodecInfo icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Png); EncoderParameters parms = new EncoderParameters(1); EncoderParameter parm = new EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 8); parms.Param[0] = parm; GdiPlusFileType.LoadProperties(quantized, input); quantized.Save(output, icf, parms); } } else if (bitDepth == SavableBitDepths.Rgba8) { using (Bitmap quantized = Quantize(scratchSurface, ditherLevel, 256, true, progressCallback)) { ImageCodecInfo icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Png); EncoderParameters parms = new EncoderParameters(1); EncoderParameter parm = new EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 8); parms.Param[0] = parm; GdiPlusFileType.LoadProperties(quantized, input); quantized.Save(output, icf, parms); } } else { throw new InvalidEnumArgumentException("bitDepth", (int)bitDepth, typeof(SavableBitDepths)); } } } }
42.59751
157
0.598188
[ "MIT" ]
Relfos/PixelDotNet
PixelDotNet/Data/PngFileType.cs
10,266
C#
using System; using System.Diagnostics.CodeAnalysis; using WMD.Game.State.Data; namespace WMD.Game.State.Utility { /// <summary> /// Provides methods for performing land area-related calculations. /// </summary> public static class LandAreaCalculator { /// <summary> /// Calculates the maximum amount of land area the current player could purchase with their funds. /// </summary> /// <param name="gameState">The current <see cref="GameState"/>.</param> /// <returns>The maximum amount of land area the current player could purchase with their funds, in square kilometers.</returns> /// <remarks>This method does not take into account the actual amount of remaining land area available for purchase.</remarks> public static int CalculateMaximumLandAreaCurrentPlayerCouldPurchase([DisallowNull] GameState gameState) { decimal availableFunds = gameState.CurrentPlayer.State.Money; decimal pricePerSquareKilometer = gameState.UnclaimedLandPurchasePrice; return (int)Math.Floor(availableFunds / pricePerSquareKilometer); } /// <summary> /// Calculates the total purchase price for the given area of unclaimed land. /// </summary> /// <param name="gameState">The current <see cref="GameState"/>.</param> /// <param name="areaToPurchase">The unclaimed land area to purchase, in square kilometers.</param> /// <returns>The total purchase price for the given area of unclaimed land.</returns> /// <remarks>This method does not take into account the actual amount of remaining land area available for purchase.</remarks> public static decimal CalculateTotalPurchasePrice([DisallowNull] GameState gameState, int areaToPurchase) => gameState.UnclaimedLandPurchasePrice * areaToPurchase; /// <summary> /// Takes a potential change in land area owned by a player and returns an amount which would stay within the allowed bounds. /// </summary> /// <param name="gameState">The current <see cref="GameState"/>.</param> /// <param name="playerIndex">The index of the player for which the change is taking place.</param> /// <param name="potentialAreaChange">The amount by which the player's owned land area could change if there was no limitation.</param> /// <returns> /// <paramref name="potentialAreaChange"/> if the resulting land area change for the player would result in a value between 0 and their /// remaining land area if the change is negative, or between <paramref name="potentialAreaChange"/> and the total remaining unclaimed /// land area if the change is positive; otherwise, 0. /// </returns> public static int ClampLandAreaChangeAmount([DisallowNull] GameState gameState, int playerIndex, int potentialAreaChange) => potentialAreaChange switch { _ when potentialAreaChange < 0 => ClampNegativeLandAreaChangeAmount(gameState, playerIndex, potentialAreaChange), _ when potentialAreaChange > 0 => ClampPositiveLandAreaChangeAmount(gameState, playerIndex, potentialAreaChange), _ => 0, }; private static int ClampNegativeLandAreaChangeAmount(GameState gameState, int playerIndex, int potentialAreaChange) => Math.Max(potentialAreaChange, -1 * Math.Max(gameState.Players[playerIndex].State.Land, 0)); private static int ClampPositiveLandAreaChangeAmount(GameState gameState, int playerIndex, int potentialAreaChange) => Math.Min(potentialAreaChange, gameState.Planet.UnclaimedLandArea); } }
60.52459
159
0.700163
[ "MIT" ]
Xyaneon/Weapons-of-Mass-Domination
src/wmd-core/State/Utility/LandAreaCalculator.cs
3,694
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Security.Cryptography; namespace TeachersAssessment { public partial class FormMain : Form { int t; tGlobal p_global = tGlobal.GetInstance(-1); TablerDBDataSet.TeachersDataTable p_Teachers = new TablerDBDataSet.TeachersDataTable(); TablerDBDataSet.AllocationTableDataTable p_AllocationTable = new TablerDBDataSet.AllocationTableDataTable(); DataSet1.PasswordsDataTable passwords = new DataSet1.PasswordsDataTable(); System.Data.MPrSQL.MPrSQLDataAdapter passwordsDA = MyTableAdapters.PasswordsAdapter(); DataSet1.ClassTeachersDataTable classTechrTable = new DataSet1.ClassTeachersDataTable(); System.Data.MPrSQL.MPrSQLDataAdapter classTchrDA = MyTableAdapters.ClassTeachersAdapter(); public FormMain() { InitializeComponent(); System.Data.MPrSQL.MPrSQLDataAdapter l_TeachersDA = MyTableAdapters.TeachersTableAdapter(); System.Data.MPrSQL.MPrSQLDataAdapter l_allocDA = MyTableAdapters.AllocationTableTableAdapter(); l_TeachersDA.Fill(p_Teachers); l_allocDA.Fill(p_AllocationTable); TablerDBDataSet.TeachersDataTable l_Teachers = new TablerDBDataSet.TeachersDataTable(); foreach (TablerDBDataSet.TeachersRow l_trw in p_Teachers) { TablerDBDataSet.AllocationTableRow[] l_allocrows = (TablerDBDataSet.AllocationTableRow[])p_AllocationTable.Select( p_AllocationTable.TeacherIDColumn.ColumnName + " = " + l_trw.TeachersID + " OR " + p_AllocationTable.TeachersStrColumn.ColumnName + " LIKE '%" + l_trw.TeachersID.ToString() + ",%'" ); foreach (TablerDBDataSet.AllocationTableRow l_alrw in l_allocrows) { if (l_alrw.IsTeachersStrNull() || l_alrw.TeachersStr.Trim().Length == 0 || (l_alrw.TeachersStr.StartsWith(l_trw.TeachersID.ToString() + ",") || l_alrw.TeachersStr.Contains("," + l_trw.TeachersID.ToString() + ","))) { l_Teachers.ImportRow(l_trw); break; } } } TablerDBDataSet.TeachersRow l_trw1 = p_Teachers.FindByTeachersID(1); l_Teachers.ImportRow(l_trw1); DataView l_dv = new DataView(l_Teachers); l_dv.Sort = l_Teachers.TeachersNameColumn.ColumnName; TeacherComboBox.DataSource = l_dv; TeacherComboBox.DisplayMember = p_Teachers.TeachersNameColumn.ColumnName; TeacherComboBox.ValueMember = p_Teachers.TeachersIDColumn.ColumnName; TeacherComboBox.AutoCompleteMode = AutoCompleteMode.Suggest; TeacherComboBox.AutoCompleteSource = AutoCompleteSource.ListItems; TeacherComboBox.SelectedIndex = -1; TeacherComboBox.Text = "Teacher Name"; label3.Visible = false; p_global.TeacherIDSelected = 0; passwordsDA.Fill(passwords); classTchrDA.Fill(classTechrTable); textBox1.TextChanged +=new EventHandler(textBox1_TextChanged); TeacherComboBox.Select(); } private void label1_Click(object sender, EventArgs e) { } private void btnDailyReport_Click(object sender, EventArgs e) { if (TeacherComboBox.SelectedIndex == -1) { label5.Visible = true; } else { p_global.TeacherIDSelected = 0; bool access = Login(Convert.ToInt32(TeacherComboBox.SelectedValue)); if (access) { textBox1.Text = ""; DataSet1.ClassTeachersRow[] l_clrws = (DataSet1.ClassTeachersRow[]) classTechrTable.Select(classTechrTable.TeacherIDColumn.ColumnName + " = " + TeacherComboBox.SelectedValue.ToString()); if (l_clrws.Length > 0) { Form1 d_entry = new Form1(l_clrws[0].GradeID, TeacherComboBox.Text,Convert.ToInt32(TeacherComboBox.SelectedValue)); d_entry.ShowDialog(); this.Close(); } else { MessageBox.Show("You need to be a class teacher to access this area."); } } } } private bool Login(int tID) { t = tID; DataSet1.PasswordsRow[] passwordsRows = (DataSet1.PasswordsRow[])passwords.Select(passwords.TeacherIDColumn.ColumnName + " = " + tID); if (passwordsRows.Length == 1) { if (passwordsRows[0].Password == EncryptPassword(textBox1.Text).Replace(" ", "")) { return true; } else { label3.Visible = true; return false; } } else if (passwordsRows.Length == 0) { if (textBox1.Text.Equals("123")) { return true; } else { label3.Visible = true; return false; } } return false; } private void textBox1_TextChanged(object sender, EventArgs e) { label3.Hide(); } public string EncryptPassword(string stringToEncrypt) { MD5 md5 = new MD5CryptoServiceProvider(); //compute hash from the bytes of text md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(stringToEncrypt)); //get hash result after compute it byte[] result = md5.Hash; StringBuilder strBuilder = new StringBuilder(); for (int i = 0; i < result.Length; i++) { //change it into 2 hexadecimal digits //for each byte strBuilder.Append(result[i].ToString("x2")); } return strBuilder.ToString(); } private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { if (TeacherComboBox.SelectedIndex >= 0) { t = Convert.ToInt32(TeacherComboBox.SelectedValue); Register d_entryR = new Register(t); d_entryR.ShowDialog(); passwords.Clear(); passwordsDA.Fill(passwords); } else { label3.Show(); } } private void btnTeacherAssess_Click(object sender, EventArgs e) { if (TeacherComboBox.SelectedIndex == -1) { label5.Visible = true; } else { bool access = Login(Convert.ToInt32(TeacherComboBox.SelectedValue)); if (access) { textBox1.Text = ""; p_global.TeacherIDSelected = Convert.ToInt32(TeacherComboBox.SelectedValue.ToString()); Form1 d_entry = new Form1(p_global.TeacherIDSelected, TeacherComboBox.Text,Convert.ToInt32(TeacherComboBox.SelectedValue.ToString())); d_entry.ShowDialog(); this.Close(); } } } private void TeacherComboBox_SelectedIndexChanged(object sender, EventArgs e) { label5.Visible = false; } } }
36.946429
207
0.527791
[ "Apache-2.0" ]
Adibhatt95/Time-tableExtensionTOOL
FormMain.cs
8,278
C#
using System; using System.Threading.Tasks; using FingerSensorsApp.Services; using Windows.ApplicationModel.Activation; namespace FingerSensorsApp.Activation { internal class DefaultActivationHandler : ActivationHandler<IActivatedEventArgs> { private readonly Type _navElement; public DefaultActivationHandler(Type navElement) { _navElement = navElement; } protected override async Task HandleInternalAsync(IActivatedEventArgs args) { // When the navigation stack isn't restored, navigate to the first page and configure // the new page by passing required information in the navigation parameter object arguments = null; if (args is LaunchActivatedEventArgs launchArgs) { arguments = launchArgs.Arguments; } NavigationService.Navigate(_navElement, arguments); await Task.CompletedTask; } protected override bool CanHandleInternal(IActivatedEventArgs args) { // None of the ActivationHandlers has handled the app activation return NavigationService.Frame.Content == null && _navElement != null; } } }
31.225
97
0.66293
[ "Apache-2.0" ]
srw2ho/FingerPrintSensor_SEN0188
FingerSensorsApp/Activation/DefaultActivationHandler.cs
1,251
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Modify a criteria for the user's call forwarding selective service. /// The following elements are only used in AS data mode: /// callToNumber /// /// For the callToNumbers in the callToNumberList, the extension element is not used and the number element is only used when the type is BroadWorks Mobility. /// The response is either a SuccessResponse or an ErrorResponse. /// <see cref="SuccessResponse"/> /// <see cref="ErrorResponse"/> /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""543304bb75006bfa60814c897fa03ec0:181""}]")] public class UserCallForwardingSelectiveModifyCriteriaRequest : BroadWorksConnector.Ocip.Models.C.OCIRequest { private string _userId; [XmlElement(ElementName = "userId", IsNullable = false, Namespace = "")] [Group(@"543304bb75006bfa60814c897fa03ec0:181")] [MinLength(1)] [MaxLength(161)] public string UserId { get => _userId; set { UserIdSpecified = true; _userId = value; } } [XmlIgnore] protected bool UserIdSpecified { get; set; } private string _criteriaName; [XmlElement(ElementName = "criteriaName", IsNullable = false, Namespace = "")] [Group(@"543304bb75006bfa60814c897fa03ec0:181")] [MinLength(1)] [MaxLength(50)] public string CriteriaName { get => _criteriaName; set { CriteriaNameSpecified = true; _criteriaName = value; } } [XmlIgnore] protected bool CriteriaNameSpecified { get; set; } private string _newCriteriaName; [XmlElement(ElementName = "newCriteriaName", IsNullable = false, Namespace = "")] [Optional] [Group(@"543304bb75006bfa60814c897fa03ec0:181")] [MinLength(1)] [MaxLength(50)] public string NewCriteriaName { get => _newCriteriaName; set { NewCriteriaNameSpecified = true; _newCriteriaName = value; } } [XmlIgnore] protected bool NewCriteriaNameSpecified { get; set; } private BroadWorksConnector.Ocip.Models.TimeSchedule _timeSchedule; [XmlElement(ElementName = "timeSchedule", IsNullable = true, Namespace = "")] [Optional] [Group(@"543304bb75006bfa60814c897fa03ec0:181")] public BroadWorksConnector.Ocip.Models.TimeSchedule TimeSchedule { get => _timeSchedule; set { TimeScheduleSpecified = true; _timeSchedule = value; } } [XmlIgnore] protected bool TimeScheduleSpecified { get; set; } private BroadWorksConnector.Ocip.Models.HolidaySchedule _holidaySchedule; [XmlElement(ElementName = "holidaySchedule", IsNullable = true, Namespace = "")] [Optional] [Group(@"543304bb75006bfa60814c897fa03ec0:181")] public BroadWorksConnector.Ocip.Models.HolidaySchedule HolidaySchedule { get => _holidaySchedule; set { HolidayScheduleSpecified = true; _holidaySchedule = value; } } [XmlIgnore] protected bool HolidayScheduleSpecified { get; set; } private BroadWorksConnector.Ocip.Models.CallForwardingSelectiveNumberSelection16 _forwardToNumberSelection; [XmlElement(ElementName = "forwardToNumberSelection", IsNullable = false, Namespace = "")] [Optional] [Group(@"543304bb75006bfa60814c897fa03ec0:181")] public BroadWorksConnector.Ocip.Models.CallForwardingSelectiveNumberSelection16 ForwardToNumberSelection { get => _forwardToNumberSelection; set { ForwardToNumberSelectionSpecified = true; _forwardToNumberSelection = value; } } [XmlIgnore] protected bool ForwardToNumberSelectionSpecified { get; set; } private string _forwardToPhoneNumber; [XmlElement(ElementName = "forwardToPhoneNumber", IsNullable = true, Namespace = "")] [Optional] [Group(@"543304bb75006bfa60814c897fa03ec0:181")] [MinLength(1)] [MaxLength(161)] public string ForwardToPhoneNumber { get => _forwardToPhoneNumber; set { ForwardToPhoneNumberSpecified = true; _forwardToPhoneNumber = value; } } [XmlIgnore] protected bool ForwardToPhoneNumberSpecified { get; set; } private BroadWorksConnector.Ocip.Models.CriteriaFromDnModify _fromDnCriteria; [XmlElement(ElementName = "fromDnCriteria", IsNullable = false, Namespace = "")] [Optional] [Group(@"543304bb75006bfa60814c897fa03ec0:181")] public BroadWorksConnector.Ocip.Models.CriteriaFromDnModify FromDnCriteria { get => _fromDnCriteria; set { FromDnCriteriaSpecified = true; _fromDnCriteria = value; } } [XmlIgnore] protected bool FromDnCriteriaSpecified { get; set; } private BroadWorksConnector.Ocip.Models.ReplacementCallToNumberList _callToNumberList; [XmlElement(ElementName = "callToNumberList", IsNullable = true, Namespace = "")] [Optional] [Group(@"543304bb75006bfa60814c897fa03ec0:181")] public BroadWorksConnector.Ocip.Models.ReplacementCallToNumberList CallToNumberList { get => _callToNumberList; set { CallToNumberListSpecified = true; _callToNumberList = value; } } [XmlIgnore] protected bool CallToNumberListSpecified { get; set; } } }
32.44898
162
0.604874
[ "MIT" ]
JTOne123/broadworks-connector-net
BroadworksConnector/Ocip/Models/UserCallForwardingSelectiveModifyCriteriaRequest.cs
6,360
C#
#if !NETSTANDARD1_0 using System; using System.Data; using System.Diagnostics; namespace Adenson.Data { /// <summary> /// Represents simple a key/value pair that can be automagically turned into a IDbDataParameter /// </summary> public sealed class Parameter : IEquatable<Parameter> { #region Constructor /// <summary> /// Initializes a new instance of the <see cref="Parameter"/> class. /// </summary> /// <param name="name">The name.</param> /// <param name="value">The value.</param> public Parameter(string name, object value) { this.Name = Arg.IsNotEmpty(name); this.Value = value == null ? DBNull.Value : value; } /// <summary> /// Initializes a new instance of the <see cref="Parameter"/> class. /// </summary> /// <param name="name">The name.</param> /// <param name="value">The value.</param> /// <param name="type">The value type.</param> public Parameter(string name, object value, DbType type) : this(name, value) { this.DbType = type; } #endregion #region Properties /// <summary> /// Gets the name of the parameter. /// </summary> public string Name { get; private set; } /// <summary> /// Gets the value of the parameter. /// </summary> public object Value { get; private set; } /// <summary> /// Gets or sets the db type. /// </summary> public DbType? DbType { get; set; } #endregion #region Methods /// <summary> /// Checks equality of name and value of the other. /// </summary> /// <param name="other">The other.</param> /// <returns>true, or false, i dont know</returns> public bool Equals(Parameter other) { if (other == null) { return false; } if (Object.ReferenceEquals(this, other)) { return true; } return other.Name == this.Name && other.Value == this.Value; } /// <summary> /// Checks equality of name and value of the other. /// </summary> /// <param name="obj">The other.</param> /// <returns>Returns true if they are the same reference, false otherwise.</returns> public override bool Equals(object obj) { var other = obj as Parameter; if (other != null) { return this.Equals(other); } return base.Equals(obj); } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>A 32-bit signed integer that is the hash code for this instance.</returns> public override int GetHashCode() { return base.GetHashCode(); } #endregion } } #endif
22.338983
98
0.599014
[ "MIT" ]
ayo10/adenson.core
Core/Data/Parameter.cs
2,636
C#
#pragma checksum "F:\Extras\app\2 Player Reactor\2 Player Reactor\2 Player Reactor\White.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "50BF5187AFA9B7DED4B95954E39AB926" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.17929 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using Microsoft.Phone.Controls; using System; using System.Windows; using System.Windows.Automation; using System.Windows.Automation.Peers; using System.Windows.Automation.Provider; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Interop; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Imaging; using System.Windows.Resources; using System.Windows.Shapes; using System.Windows.Threading; namespace _2_Player_Reactor { public partial class Page5 : Microsoft.Phone.Controls.PhoneApplicationPage { internal System.Windows.Media.Animation.Storyboard Storyboard1; internal System.Windows.Controls.Grid LayoutRoot; internal System.Windows.Controls.Button PlayButton1; internal System.Windows.Controls.Button PlayButton2; internal System.Windows.Controls.TextBlock l1; internal System.Windows.Controls.TextBlock l2; internal System.Windows.Controls.Button startline2_1; internal System.Windows.Controls.Button startline2_2; internal System.Windows.Controls.Button startline1_1; internal System.Windows.Controls.Button startline1_2; internal System.Windows.Controls.Image p1green; internal System.Windows.Controls.Image p2green; internal System.Windows.Controls.Image p2red; internal System.Windows.Controls.Image p1red; internal System.Windows.Shapes.Rectangle r1; internal System.Windows.Controls.TextBlock fcheck; internal System.Windows.Controls.TextBlock score2; internal System.Windows.Controls.TextBlock score1; private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Windows.Application.LoadComponent(this, new System.Uri("/2%20Player%20Reactor;component/White.xaml", System.UriKind.Relative)); this.Storyboard1 = ((System.Windows.Media.Animation.Storyboard)(this.FindName("Storyboard1"))); this.LayoutRoot = ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot"))); this.PlayButton1 = ((System.Windows.Controls.Button)(this.FindName("PlayButton1"))); this.PlayButton2 = ((System.Windows.Controls.Button)(this.FindName("PlayButton2"))); this.l1 = ((System.Windows.Controls.TextBlock)(this.FindName("l1"))); this.l2 = ((System.Windows.Controls.TextBlock)(this.FindName("l2"))); this.startline2_1 = ((System.Windows.Controls.Button)(this.FindName("startline2_1"))); this.startline2_2 = ((System.Windows.Controls.Button)(this.FindName("startline2_2"))); this.startline1_1 = ((System.Windows.Controls.Button)(this.FindName("startline1_1"))); this.startline1_2 = ((System.Windows.Controls.Button)(this.FindName("startline1_2"))); this.p1green = ((System.Windows.Controls.Image)(this.FindName("p1green"))); this.p2green = ((System.Windows.Controls.Image)(this.FindName("p2green"))); this.p2red = ((System.Windows.Controls.Image)(this.FindName("p2red"))); this.p1red = ((System.Windows.Controls.Image)(this.FindName("p1red"))); this.r1 = ((System.Windows.Shapes.Rectangle)(this.FindName("r1"))); this.fcheck = ((System.Windows.Controls.TextBlock)(this.FindName("fcheck"))); this.score2 = ((System.Windows.Controls.TextBlock)(this.FindName("score2"))); this.score1 = ((System.Windows.Controls.TextBlock)(this.FindName("score1"))); } } }
44.055046
172
0.634944
[ "Apache-2.0" ]
mandyjohar23/twin-player-reactor
2 Player Reactor/obj/Debug/White.g.cs
4,804
C#
namespace BetSystem.Data.Models { using System; using System.ComponentModel.DataAnnotations.Schema; using System.Security.Claims; using System.Threading.Tasks; using Common.Models; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more. public class User : IdentityUser, IAuditInfo, IDeletableEntity { public DateTime CreatedOn { get; set; } public DateTime? ModifiedOn { get; set; } [Index] public bool IsDeleted { get; set; } public DateTime? DeletedOn { get; set; } public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager, string authenticationType) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, authenticationType); // Add custom user claims here return userIdentity; } } }
36.121212
175
0.698826
[ "MIT" ]
NikitoG/BetSystem
Source/Data/BetSystem.Data.Models/User.cs
1,194
C#
/*---------------------------------------------------------------- Copyright (C) 2022 Senparc 文件名:AsynchronousPostData.cs 文件功能描述:异步任务接口提交数据Json 创建标识:Senparc - 20150408 ----------------------------------------------------------------*/ namespace Senparc.Weixin.Work.AdvancedAPIs.Asynchronous { public class Asynchronous_CallBack { public string url { get; set; } public string token { get; set; } public string encodingaeskey { get; set; } } }
25.6
67
0.474609
[ "Apache-2.0" ]
AaronWu666/WeiXinMPSDK
src/Senparc.Weixin.Work/Senparc.Weixin.Work/AdvancedAPIs/Asynchronous/AsynchronousJson/AsynchronousPostData.cs
566
C#
#region Copyright //////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Dynastream Innovations Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2017 Dynastream Innovations Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 20.54Release // Tag = production/akw/20.54.00-0-ga49a69a //////////////////////////////////////////////////////////////////////////////// #endregion namespace Dynastream.Fit { /// <summary> /// Implements the profile CourseCapabilities type as a class /// </summary> public static class CourseCapabilities { public const uint Processed = 0x00000001; public const uint Valid = 0x00000002; public const uint Time = 0x00000004; public const uint Distance = 0x00000008; public const uint Position = 0x00000010; public const uint HeartRate = 0x00000020; public const uint Power = 0x00000040; public const uint Cadence = 0x00000080; public const uint Training = 0x00000100; public const uint Navigation = 0x00000200; public const uint Bikeway = 0x00000400; public const uint Invalid = (uint)0x00000000; } }
40.045455
83
0.614642
[ "MIT" ]
JaniceBPC/FitFiles
Dynastream/Fit/Profile/Types/CourseCapabilities.cs
1,762
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. #nullable disable extern alias DSR; using System; using System.Collections.Immutable; using System.Diagnostics; using System.Runtime.InteropServices.ComTypes; using DSR::Microsoft.DiaSymReader; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using Xunit; namespace Roslyn.Test.Utilities { internal sealed class MockSymUnmanagedReader : ISymUnmanagedReader, ISymUnmanagedReader2, ISymUnmanagedReader3 { private readonly ImmutableDictionary<int, MethodDebugInfoBytes> _methodDebugInfoMap; public MockSymUnmanagedReader(ImmutableDictionary<int, MethodDebugInfoBytes> methodDebugInfoMap) { _methodDebugInfoMap = methodDebugInfoMap; } public int GetMethod(int methodToken, out ISymUnmanagedMethod method) { return GetMethodByVersion(methodToken, 1, out method); } public int GetMethodByVersion(int methodToken, int version, out ISymUnmanagedMethod retVal) { Assert.Equal(1, version); MethodDebugInfoBytes info; if (!_methodDebugInfoMap.TryGetValue(methodToken, out info)) { retVal = null; return HResult.E_FAIL; } Assert.NotNull(info); retVal = info.Method; return HResult.S_OK; } public int GetSymAttribute(int methodToken, string name, int bufferLength, out int count, byte[] customDebugInformation) { // The EE should never be calling ISymUnmanagedReader.GetSymAttribute. // In order to account for EnC updates, it should always be calling // ISymUnmanagedReader3.GetSymAttributeByVersion instead. throw ExceptionUtilities.Unreachable; } public int GetSymAttributeByVersion(int methodToken, int version, string name, int bufferLength, out int count, byte[] customDebugInformation) { Assert.Equal(1, version); Assert.Equal("MD2", name); MethodDebugInfoBytes info; if (!_methodDebugInfoMap.TryGetValue(methodToken, out info)) { count = 0; return HResult.S_FALSE; // This is a guess. We're not consuming it, so it doesn't really matter. } Assert.NotNull(info); info.Bytes.TwoPhaseCopy(bufferLength, out count, customDebugInformation); return HResult.S_OK; } public int GetDocument(string url, Guid language, Guid languageVendor, Guid documentType, out ISymUnmanagedDocument document) { throw new NotImplementedException(); } public int GetDocuments(int bufferLength, out int count, ISymUnmanagedDocument[] documents) { throw new NotImplementedException(); } public int GetUserEntryPoint(out int methodToken) { throw new NotImplementedException(); } public int GetVariables(int methodToken, int bufferLength, out int count, ISymUnmanagedVariable[] variables) { throw new NotImplementedException(); } public int GetGlobalVariables(int bufferLength, out int count, ISymUnmanagedVariable[] variables) { throw new NotImplementedException(); } public int GetMethodFromDocumentPosition(ISymUnmanagedDocument document, int line, int column, out ISymUnmanagedMethod method) { throw new NotImplementedException(); } public int GetNamespaces(int bufferLength, out int count, ISymUnmanagedNamespace[] namespaces) { throw new NotImplementedException(); } public int Initialize(object metadataImporter, string fileName, string searchPath, IStream stream) { throw new NotImplementedException(); } public int UpdateSymbolStore(string fileName, IStream stream) { throw new NotImplementedException(); } public int ReplaceSymbolStore(string fileName, IStream stream) { throw new NotImplementedException(); } public int GetSymbolStoreFileName(int bufferLength, out int count, char[] name) { throw new NotImplementedException(); } public int GetMethodsFromDocumentPosition(ISymUnmanagedDocument document, int line, int column, int bufferLength, out int count, ISymUnmanagedMethod[] methods) { throw new NotImplementedException(); } public int GetDocumentVersion(ISymUnmanagedDocument document, out int version, out bool isCurrent) { throw new NotImplementedException(); } public int GetMethodVersion(ISymUnmanagedMethod method, out int version) { throw new NotImplementedException(); } public int GetMethodByVersionPreRemap(int methodToken, int version, out ISymUnmanagedMethod method) { throw new NotImplementedException(); } public int GetSymAttributePreRemap(int methodToken, string name, int bufferLength, out int count, byte[] customDebugInformation) { throw new NotImplementedException(); } public int GetMethodsInDocument(ISymUnmanagedDocument document, int bufferLength, out int count, ISymUnmanagedMethod[] methods) { throw new NotImplementedException(); } public int GetSymAttributeByVersionPreRemap(int methodToken, int version, string name, int bufferLength, out int count, byte[] customDebugInformation) { throw new NotImplementedException(); } } internal sealed class MockSymUnmanagedMethod : ISymUnmanagedMethod { private readonly ISymUnmanagedScope _rootScope; public MockSymUnmanagedMethod(ISymUnmanagedScope rootScope) { _rootScope = rootScope; } int ISymUnmanagedMethod.GetRootScope(out ISymUnmanagedScope retVal) { retVal = _rootScope; return HResult.S_OK; } int ISymUnmanagedMethod.GetSequencePointCount(out int retVal) { retVal = 1; return HResult.S_OK; } int ISymUnmanagedMethod.GetSequencePoints(int cPoints, out int pcPoints, int[] offsets, ISymUnmanagedDocument[] documents, int[] lines, int[] columns, int[] endLines, int[] endColumns) { pcPoints = 1; offsets[0] = 0; documents[0] = null; lines[0] = 0; columns[0] = 0; endLines[0] = 0; endColumns[0] = 0; return HResult.S_OK; } int ISymUnmanagedMethod.GetNamespace(out ISymUnmanagedNamespace retVal) { throw new NotImplementedException(); } int ISymUnmanagedMethod.GetOffset(ISymUnmanagedDocument document, int line, int column, out int retVal) { throw new NotImplementedException(); } int ISymUnmanagedMethod.GetParameters(int cParams, out int pcParams, ISymUnmanagedVariable[] parms) { throw new NotImplementedException(); } int ISymUnmanagedMethod.GetRanges(ISymUnmanagedDocument document, int line, int column, int cRanges, out int pcRanges, int[] ranges) { throw new NotImplementedException(); } int ISymUnmanagedMethod.GetScopeFromOffset(int offset, out ISymUnmanagedScope retVal) { throw new NotImplementedException(); } int ISymUnmanagedMethod.GetSourceStartEnd(ISymUnmanagedDocument[] docs, int[] lines, int[] columns, out bool retVal) { throw new NotImplementedException(); } int ISymUnmanagedMethod.GetToken(out int pToken) { throw new NotImplementedException(); } } internal sealed class MockSymUnmanagedScope : ISymUnmanagedScope, ISymUnmanagedScope2 { private readonly ImmutableArray<ISymUnmanagedScope> _children; private readonly ImmutableArray<ISymUnmanagedNamespace> _namespaces; private readonly ISymUnmanagedConstant[] _constants; private readonly int _startOffset; private readonly int _endOffset; public MockSymUnmanagedScope(ImmutableArray<ISymUnmanagedScope> children, ImmutableArray<ISymUnmanagedNamespace> namespaces, ISymUnmanagedConstant[] constants = null, int startOffset = 0, int endOffset = 1) { _children = children; _namespaces = namespaces; _constants = constants ?? new ISymUnmanagedConstant[0]; _startOffset = startOffset; _endOffset = endOffset; } public int GetChildren(int numDesired, out int numRead, ISymUnmanagedScope[] buffer) { _children.TwoPhaseCopy(numDesired, out numRead, buffer); return HResult.S_OK; } public int GetNamespaces(int numDesired, out int numRead, ISymUnmanagedNamespace[] buffer) { _namespaces.TwoPhaseCopy(numDesired, out numRead, buffer); return HResult.S_OK; } public int GetStartOffset(out int pRetVal) { pRetVal = _startOffset; return HResult.S_OK; } public int GetEndOffset(out int pRetVal) { pRetVal = _endOffset; return HResult.S_OK; } public int GetLocalCount(out int pRetVal) { pRetVal = 0; return HResult.S_OK; } public int GetLocals(int cLocals, out int pcLocals, ISymUnmanagedVariable[] locals) { pcLocals = 0; return HResult.S_OK; } public int GetMethod(out ISymUnmanagedMethod pRetVal) { throw new NotImplementedException(); } public int GetParent(out ISymUnmanagedScope pRetVal) { throw new NotImplementedException(); } public int GetConstantCount(out int pRetVal) { pRetVal = _constants.Length; return HResult.S_OK; } public int GetConstants(int cConstants, out int pcConstants, ISymUnmanagedConstant[] constants) { pcConstants = _constants.Length; if (constants != null) { Array.Copy(_constants, constants, constants.Length); } return HResult.S_OK; } } internal sealed class MockSymUnmanagedNamespace : ISymUnmanagedNamespace { private readonly ImmutableArray<char> _nameChars; public MockSymUnmanagedNamespace(string name) { if (name != null) { var builder = ArrayBuilder<char>.GetInstance(); builder.AddRange(name); builder.AddRange('\0'); _nameChars = builder.ToImmutableAndFree(); } } int ISymUnmanagedNamespace.GetName(int numDesired, out int numRead, char[] buffer) { _nameChars.TwoPhaseCopy(numDesired, out numRead, buffer); return 0; } int ISymUnmanagedNamespace.GetNamespaces(int cNameSpaces, out int pcNameSpaces, ISymUnmanagedNamespace[] namespaces) { throw new NotImplementedException(); } int ISymUnmanagedNamespace.GetVariables(int cVars, out int pcVars, ISymUnmanagedVariable[] pVars) { throw new NotImplementedException(); } } internal delegate int GetSignatureDelegate(int bufferLength, out int count, byte[] signature); internal sealed class MockSymUnmanagedConstant : ISymUnmanagedConstant { private readonly string _name; private readonly object _value; private readonly GetSignatureDelegate _getSignature; public MockSymUnmanagedConstant(string name, object value, GetSignatureDelegate getSignature) { _name = name; _value = value; _getSignature = getSignature; } int ISymUnmanagedConstant.GetName(int bufferLength, out int count, char[] name) { count = _name.Length + 1; // + 1 for null terminator Debug.Assert((bufferLength == 0) || (bufferLength == count)); for (int i = 0; i < bufferLength - 1; i++) { name[i] = _name[i]; } return HResult.S_OK; } int ISymUnmanagedConstant.GetSignature(int bufferLength, out int count, byte[] signature) { return _getSignature(bufferLength, out count, signature); } int ISymUnmanagedConstant.GetValue(out object value) { value = _value; return HResult.S_OK; } } internal static class MockSymUnmanagedHelpers { public static void TwoPhaseCopy<T>(this ImmutableArray<T> source, int numDesired, out int numRead, T[] destination) { if (destination == null) { Assert.Equal(0, numDesired); numRead = source.IsDefault ? 0 : source.Length; } else { Assert.False(source.IsDefault); Assert.Equal(source.Length, numDesired); source.CopyTo(0, destination, 0, numDesired); numRead = numDesired; } } public static void Add2(this ArrayBuilder<byte> bytes, short s) { var shortBytes = BitConverter.GetBytes(s); Assert.Equal(2, shortBytes.Length); bytes.AddRange(shortBytes); } public static void Add4(this ArrayBuilder<byte> bytes, int i) { var intBytes = BitConverter.GetBytes(i); Assert.Equal(4, intBytes.Length); bytes.AddRange(intBytes); } } }
33.971292
214
0.621408
[ "MIT" ]
333fred/roslyn
src/Test/PdbUtilities/Reader/MockSymUnmanagedReader.cs
14,202
C#
using System; using System.Windows; using System.Windows.Media; using GammaJul.ReSharper.EnhancedTooltip.Settings; using JetBrains.Annotations; using JetBrains.Application; using JetBrains.Application.Components; using JetBrains.Application.UI.Components.Theming; using JetBrains.Util; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Formatting; namespace GammaJul.ReSharper.EnhancedTooltip.VisualStudio { [ShellComponent] public class TooltipFormattingProvider { [NotNull] [ItemCanBeNull] private readonly Lazy<IClassificationFormatMap> _lazyTooltipFormatMap; [NotNull] [ItemCanBeNull] private readonly Lazy<IClassificationFormatMap> _lazyTextFormatMap; [NotNull] [ItemCanBeNull] private readonly Lazy<ResourceDictionary> _lazyTextViewBackgroundResources; [NotNull] public TextFormattingRunProperties GetTooltipFormatting() => _lazyTooltipFormatMap.Value?.DefaultTextProperties ?? TextFormattingRunProperties.CreateTextFormattingRunProperties(); [CanBeNull] public Brush TryGetBackground(TooltipColorSource colorSource) { if (colorSource == TooltipColorSource.EnvironmentSettings) return GetAppBrush(ThemeColor.TooltipBackground.BrushKey); return _lazyTextViewBackgroundResources.Value?["Background"] as Brush; } [CanBeNull] public Brush TryGetForeground(TooltipColorSource colorSource) { if (colorSource == TooltipColorSource.EnvironmentSettings) return GetAppBrush(ThemeColor.TooltipForeground.BrushKey); TextFormattingRunProperties textProperties = _lazyTextFormatMap.Value?.DefaultTextProperties; return textProperties == null || textProperties.ForegroundBrushEmpty ? null : textProperties.ForegroundBrush; } [CanBeNull] public Brush TryGetBorderBrush() => GetAppBrush(ThemeColor.TooltipBorder.BrushKey); [CanBeNull] [Pure] private static Brush GetAppBrush([NotNull] Object brushKey) => Application.Current.Resources[brushKey] as Brush; public TooltipFormattingProvider( [NotNull] Lazy<Optional<IClassificationFormatMapService>> lazyFormatMapService, [NotNull] Lazy<Optional<IEditorFormatMapService>> lazyEditorFormatMapService) { _lazyTooltipFormatMap = Lazy.Of( () => lazyFormatMapService.Value.CanBeNull?.GetClassificationFormatMap("tooltip"), true); _lazyTextFormatMap = Lazy.Of( () => lazyFormatMapService.Value.CanBeNull?.GetClassificationFormatMap("text"), true); _lazyTextViewBackgroundResources = Lazy.Of( () => lazyEditorFormatMapService.Value.CanBeNull?.GetEditorFormatMap("text").GetProperties("TextView Background"), true); } } }
38.323529
124
0.805833
[ "Apache-2.0" ]
DimitarCC/ReSharper.EnhancedTooltip
source/GammaJul.ReSharper.EnhancedTooltip/VisualStudio/TooltipFormattingProvider.cs
2,606
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace WebApi.Migrations { public partial class ShiftCreatedAt : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<DateTime>( name: "CreatedAt", table: "Shifts", nullable: false, defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "CreatedAt", table: "Shifts"); } } }
27.84
91
0.581897
[ "MIT" ]
asagynbaev/CEA_Api
Migrations/20200115234752_ShiftCreatedAt.cs
698
C#
// DocSection: managing_navigation_articles_slugs // Tip: Find more about .NET SDKs at https://docs.kontent.ai/net using Kentico.Kontent.Delivery; // Creates an instance of the delivery client // ProTip: Use DI for this in your apps https://docs.kontent.ai/net-register-client IDeliveryClient client = DeliveryClientBuilder .WithProjectId("975bf280-fd91-488c-994c-2f04416e5ee3") .Build(); // Gets specific elements of all articles // Create strongly typed models according to https://docs.kontent.ai/net-strong-types DeliveryItemListingResponse<Article> response = await client.GetItemsAsync<Article>( new EqualsFilter("system.type", "article"), new ElementsParameter("title", "url_pattern") ); var items = response.Items; // EndDocSection
40.315789
85
0.762402
[ "MIT" ]
Simply007/kontent-docs-samples
net/managing-navigation/GetArticlesSlug.cs
766
C#
using System; using System.Buffers.Text; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Runtime.InteropServices; using System.Reflection; using System.Security.Authentication; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace MySqlConnector.Utilities { internal static class Utility { public static void Dispose<T>(ref T disposable) where T : class, IDisposable { if (disposable != null) { disposable.Dispose(); disposable = null; } } public static string FormatInvariant(this string format, params object[] args) => string.Format(CultureInfo.InvariantCulture, format, args); #if NET45 || NET461 || NET471 || NETSTANDARD1_3 || NETSTANDARD2_0 public static string GetString(this Encoding encoding, ReadOnlySpan<byte> span) { if (span.Length == 0) return ""; #if NET45 return encoding.GetString(span.ToArray()); #else unsafe { fixed (byte* ptr = span) return encoding.GetString(ptr, span.Length); } #endif } public static unsafe void GetBytes(this Encoding encoding, ReadOnlySpan<char> chars, Span<byte> bytes) { fixed (char* charsPtr = chars) fixed (byte* bytesPtr = bytes) { encoding.GetBytes(charsPtr, chars.Length, bytesPtr, bytes.Length); } } #endif #if NET461 || NET471 || NETSTANDARD2_0 public static unsafe void Convert(this Encoder encoder, ReadOnlySpan<char> chars, Span<byte> bytes, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { fixed (char* charsPtr = chars) fixed (byte* bytesPtr = bytes) { // MemoryMarshal.GetNonNullPinnableReference is internal, so fake it by using an invalid but non-null pointer; this // prevents Convert from throwing an exception when the output buffer is empty encoder.Convert(charsPtr, chars.Length, bytesPtr == null ? (byte*) 1 : bytesPtr, bytes.Length, flush, out charsUsed, out bytesUsed, out completed); } } #endif /// <summary> /// Loads a RSA public key from a PEM string. Taken from <a href="https://stackoverflow.com/a/32243171/23633">Stack Overflow</a>. /// </summary> /// <param name="publicKey">The public key, in PEM format.</param> /// <returns>An RSA public key, or <c>null</c> on failure.</returns> public static RSA DecodeX509PublicKey(string publicKey) { var x509Key = System.Convert.FromBase64String(publicKey.Replace("-----BEGIN PUBLIC KEY-----", "").Replace("-----END PUBLIC KEY-----", "")); // encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1" byte[] seqOid = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 }; // --------- Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob ------ using (var stream = new MemoryStream(x509Key)) using (var reader = new BinaryReader(stream)) //wrap Memory Stream with BinaryReader for easy reading { var temp = reader.ReadUInt16(); switch (temp) { case 0x8130: reader.ReadByte(); //advance 1 byte break; case 0x8230: reader.ReadInt16(); //advance 2 bytes break; default: throw new FormatException("Expected 0x8130 or 0x8230 but read {0:X4}".FormatInvariant(temp)); } var seq = reader.ReadBytes(15); if (!seq.SequenceEqual(seqOid)) //make sure Sequence for OID is correct throw new FormatException("Expected RSA OID but read {0}".FormatInvariant(BitConverter.ToString(seq))); temp = reader.ReadUInt16(); if (temp == 0x8103) //data read as little endian order (actual data order for Bit String is 03 81) reader.ReadByte(); //advance 1 byte else if (temp == 0x8203) reader.ReadInt16(); //advance 2 bytes else throw new FormatException("Expected 0x8130 or 0x8230 but read {0:X4}".FormatInvariant(temp)); var bt = reader.ReadByte(); if (bt != 0x00) //expect null byte next throw new FormatException("Expected 0x00 but read {0:X2}".FormatInvariant(bt)); temp = reader.ReadUInt16(); if (temp == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) reader.ReadByte(); //advance 1 byte else if (temp == 0x8230) reader.ReadInt16(); //advance 2 bytes else throw new FormatException("Expected 0x8130 or 0x8230 but read {0:X4}".FormatInvariant(temp)); temp = reader.ReadUInt16(); byte lowbyte; byte highbyte = 0x00; if (temp == 0x8102) { //data read as little endian order (actual data order for Integer is 02 81) lowbyte = reader.ReadByte(); // read next bytes which is bytes in modulus } else if (temp == 0x8202) { highbyte = reader.ReadByte(); //advance 2 bytes lowbyte = reader.ReadByte(); } else { throw new FormatException("Expected 0x8102 or 0x8202 but read {0:X4}".FormatInvariant(temp)); } var modulusSize = highbyte * 256 + lowbyte; var firstbyte = reader.ReadByte(); reader.BaseStream.Seek(-1, SeekOrigin.Current); if (firstbyte == 0x00) { //if first byte (highest order) of modulus is zero, don't include it reader.ReadByte(); //skip this null byte modulusSize -= 1; //reduce modulus buffer size by 1 } var modulus = reader.ReadBytes(modulusSize); //read the modulus bytes if (reader.ReadByte() != 0x02) //expect an Integer for the exponent data throw new FormatException("Expected 0x02"); int exponentSize = reader.ReadByte(); // should only need one byte for actual exponent data (for all useful values) var exponent = reader.ReadBytes(exponentSize); // ------- create RSACryptoServiceProvider instance and initialize with public key ----- var rsa = RSA.Create(); var rsaKeyInfo = new RSAParameters { Modulus = modulus, Exponent = exponent }; rsa.ImportParameters(rsaKeyInfo); return rsa; } } /// <summary> /// Returns a new <see cref="ArraySegment{T}"/> that starts at index <paramref name="index"/> into <paramref name="arraySegment"/>. /// </summary> /// <param name="arraySegment">The <see cref="ArraySegment{T}"/> from which to create a slice.</param> /// <param name="index">The non-negative, zero-based starting index of the new slice (relative to <see cref="ArraySegment{T}.Offset"/> of <paramref name="arraySegment"/>.</param> /// <returns>A new <see cref="ArraySegment{T}"/> starting at the <paramref name="index"/>th element of <paramref name="arraySegment"/> and continuing to the end of <paramref name="arraySegment"/>.</returns> public static ArraySegment<T> Slice<T>(this ArraySegment<T> arraySegment, int index) => new ArraySegment<T>(arraySegment.Array, arraySegment.Offset + index, arraySegment.Count - index); /// <summary> /// Returns a new <see cref="ArraySegment{T}"/> that starts at index <paramref name="index"/> into <paramref name="arraySegment"/> and has a length of <paramref name="length"/>. /// </summary> /// <param name="arraySegment">The <see cref="ArraySegment{T}"/> from which to create a slice.</param> /// <param name="index">The non-negative, zero-based starting index of the new slice (relative to <see cref="ArraySegment{T}.Offset"/> of <paramref name="arraySegment"/>.</param> /// <param name="length">The non-negative length of the new slice.</param> /// <returns>A new <see cref="ArraySegment{T}"/> of length <paramref name="length"/>, starting at the <paramref name="index"/>th element of <paramref name="arraySegment"/>.</returns> public static ArraySegment<T> Slice<T>(this ArraySegment<T> arraySegment, int index, int length) => new ArraySegment<T>(arraySegment.Array, arraySegment.Offset + index, length); /// <summary> /// Returns a new <see cref="byte[]"/> that is a slice of <paramref name="input"/> starting at <paramref name="offset"/>. /// </summary> /// <param name="input">The array to slice.</param> /// <param name="offset">The offset at which to slice.</param> /// <returns>A new <see cref="byte[]"/> that is a slice of <paramref name="input"/> from <paramref name="offset"/> to the end.</returns> public static byte[] ArraySlice(byte[] input, int offset, int length) { if (offset == 0 && length == input.Length) return input; var slice = new byte[length]; Array.Copy(input, offset, slice, 0, slice.Length); return slice; } /// <summary> /// Finds the next index of <paramref name="pattern"/> in <paramref name="data"/>, starting at index <paramref name="offset"/>. /// </summary> /// <param name="data">The array to search.</param> /// <param name="offset">The offset at which to start searching.</param> /// <param name="pattern">The pattern to find in <paramref name="data"/>.</param> /// <returns>The offset of <paramref name="pattern"/> within <paramref name="data"/>, or <c>-1</c> if <paramref name="pattern"/> was not found.</returns> public static int FindNextIndex(ReadOnlySpan<byte> data, int offset, ReadOnlySpan<byte> pattern) { var limit = data.Length - pattern.Length; for (var start = offset; start <= limit; start++) { var i = 0; for (; i < pattern.Length; i++) { if (data[start + i] != pattern[i]) break; } if (i == pattern.Length) return start; } return -1; } /// <summary> /// Resizes <paramref name="resizableArray"/> to hold at least <paramref name="newLength"/> items. /// </summary> /// <remarks><paramref name="resizableArray"/> may be <c>null</c>, in which case a new <see cref="ResizableArray{T}"/> will be allocated.</remarks> public static void Resize<T>(ref ResizableArray<T> resizableArray, int newLength) { if (resizableArray is null) resizableArray = new ResizableArray<T>(); resizableArray.DoResize(newLength); } public static TimeSpan ParseTimeSpan(ReadOnlySpan<byte> value) { var originalValue = value; // parse (optional) leading minus sign var isNegative = false; if (value.Length > 0 && value[0] == 0x2D) { isNegative = true; value = value.Slice(1); } // parse hours (0-838) if (!Utf8Parser.TryParse(value, out int hours, out var bytesConsumed) || hours < 0 || hours > 838) goto InvalidTimeSpan; if (value.Length == bytesConsumed || value[bytesConsumed] != 58) goto InvalidTimeSpan; value = value.Slice(bytesConsumed + 1); // parse minutes (0-59) if (!Utf8Parser.TryParse(value, out int minutes, out bytesConsumed) || bytesConsumed != 2 || minutes < 0 || minutes > 59) goto InvalidTimeSpan; if (value.Length < 3 || value[2] != 58) goto InvalidTimeSpan; value = value.Slice(3); // parse seconds (0-59) if (!Utf8Parser.TryParse(value, out int seconds, out bytesConsumed) || bytesConsumed != 2 || seconds < 0 || seconds > 59) goto InvalidTimeSpan; int microseconds; if (value.Length == 2) { microseconds = 0; } else { if (value[2] != 46) goto InvalidTimeSpan; value = value.Slice(3); if (!Utf8Parser.TryParse(value, out microseconds, out bytesConsumed) || bytesConsumed != value.Length || microseconds < 0 || microseconds > 999_999) goto InvalidTimeSpan; for (; bytesConsumed < 6; bytesConsumed++) microseconds *= 10; } if (isNegative) { hours = -hours; minutes = -minutes; seconds = -seconds; microseconds = -microseconds; } return new TimeSpan(0, hours, minutes, seconds, microseconds / 1000) + TimeSpan.FromTicks(microseconds % 1000 * 10); InvalidTimeSpan: throw new FormatException("Couldn't interpret '{0}' as a valid TimeSpan".FormatInvariant(Encoding.UTF8.GetString(originalValue))); } #if NET45 public static Task CompletedTask { get { if (s_completedTask is null) { var tcs = new TaskCompletionSource<object>(); tcs.SetResult(null); s_completedTask = tcs.Task; } return s_completedTask; } } static Task s_completedTask; public static Task TaskFromException(Exception exception) => TaskFromException<object>(exception); public static Task<T> TaskFromException<T>(Exception exception) { var tcs = new TaskCompletionSource<T>(); tcs.SetException(exception); return tcs.Task; } #else public static Task CompletedTask => Task.CompletedTask; public static Task TaskFromException(Exception exception) => Task.FromException(exception); public static Task<T> TaskFromException<T>(Exception exception) => Task.FromException<T>(exception); #endif public static byte[] TrimZeroByte(byte[] value) { if (value[value.Length - 1] == 0) Array.Resize(ref value, value.Length - 1); return value; } #if NET45 public static bool TryGetBuffer(this MemoryStream memoryStream, out ArraySegment<byte> buffer) { try { var rawBuffer = memoryStream.GetBuffer(); buffer = new ArraySegment<byte>(rawBuffer, 0, checked((int) memoryStream.Length)); return true; } catch (UnauthorizedAccessException) { buffer = default(ArraySegment<byte>); return false; } } #endif public static void SwapBytes(byte[] bytes, int offset1, int offset2) { byte swap = bytes[offset1]; bytes[offset1] = bytes[offset2]; bytes[offset2] = swap; } #if NET45 || NET461 public static bool IsWindows() => Environment.OSVersion.Platform == PlatformID.Win32NT; public static void GetOSDetails(out string os, out string osDescription, out string architecture) { os = Environment.OSVersion.Platform == PlatformID.Win32NT ? "Windows" : Environment.OSVersion.Platform == PlatformID.Unix ? "Linux" : Environment.OSVersion.Platform == PlatformID.MacOSX ? "macOS" : null; osDescription = Environment.OSVersion.VersionString; architecture = IntPtr.Size == 8 ? "X64" : "X86"; } #else public static bool IsWindows() { try { // OSPlatform.Windows is not supported on AWS Lambda return RuntimeInformation.IsOSPlatform(OSPlatform.Windows); } catch (PlatformNotSupportedException) { return false; } } public static void GetOSDetails(out string os, out string osDescription, out string architecture) { os = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "Windows" : RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? "Linux" : RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? "macOS" : null; osDescription = RuntimeInformation.OSDescription; architecture = RuntimeInformation.ProcessArchitecture.ToString(); } #endif #if NET45 || NET461 public static SslProtocols GetDefaultSslProtocols() { if (!s_defaultSslProtocols.HasValue) { // Prior to .NET Framework 4.7, SslProtocols.None is not a valid argument to SslStream.AuthenticateAsClientAsync. // If the NET461 build is loaded by an application that targets. NET 4.7 (or later), or if app.config has set // Switch.System.Net.DontEnableSystemDefaultTlsVersions to false, then SslProtocols.None will work; otherwise, // if the application targets .NET 4.6.2 or earlier and hasn't changed the AppContext switch, then it will // fail at runtime. We attempt to determine if it will fail by accessing the internal static // ServicePointManager.DisableSystemDefaultTlsVersions property, which controls whether SslProtocols.None is // an acceptable value. bool disableSystemDefaultTlsVersions; try { var property = typeof(ServicePointManager).GetProperty("DisableSystemDefaultTlsVersions", BindingFlags.NonPublic | BindingFlags.Static); disableSystemDefaultTlsVersions = property is null || (property.GetValue(null) is bool b && b); } catch (Exception) { // couldn't access the property; assume the safer default of 'true' disableSystemDefaultTlsVersions = true; } s_defaultSslProtocols = disableSystemDefaultTlsVersions ? (SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12) : SslProtocols.None; } return s_defaultSslProtocols.Value; } static SslProtocols? s_defaultSslProtocols; #elif NETSTANDARD1_3 public static SslProtocols GetDefaultSslProtocols() => SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12; #else public static SslProtocols GetDefaultSslProtocols() => SslProtocols.None; #endif } }
37.373272
208
0.688656
[ "MIT" ]
datatechnology/MySqlConnector
src/MySqlConnector/Utilities/Utility.cs
16,220
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.EntityFrameworkCore.TestUtilities.QueryTestGeneration; public class AppendCorrelatedCollectionExpressionMutator : ExpressionMutator { public AppendCorrelatedCollectionExpressionMutator(DbContext context) : base(context) { } private bool ContainsCollectionNavigation(Type type) => Context.Model.FindEntityType(type)?.GetNavigations().Any(n => n.IsCollection) ?? false; public override bool IsValid(Expression expression) => IsQueryableResult(expression) && IsEntityType(expression.Type.GetGenericArguments()[0]) && ContainsCollectionNavigation(expression.Type.GetGenericArguments()[0]); public override Expression Apply(Expression expression, Random random) { var typeArgument = expression.Type.GetGenericArguments()[0]; var navigations = Context.Model.FindEntityType(typeArgument).GetNavigations().Where(n => n.IsCollection).ToList(); var i = random.Next(navigations.Count); var navigation = navigations[i]; var collectionElementType = navigation.ForeignKey.DeclaringEntityType.ClrType; var listType = typeof(List<>).MakeGenericType(collectionElementType); var select = QueryableMethods.Select.MakeGenericMethod(typeArgument, listType); var where = EnumerableMethods.Where.MakeGenericMethod(collectionElementType); var toList = EnumerableMethods.ToList.MakeGenericMethod(collectionElementType); var outerPrm = Expression.Parameter(typeArgument, "outerPrm"); var innerPrm = Expression.Parameter(collectionElementType, "innerPrm"); var outerLambdaBody = Expression.Call( toList, Expression.Call( where, Expression.Property(outerPrm, navigation.PropertyInfo), Expression.Lambda(Expression.Constant(true), innerPrm))); var resultExpression = Expression.Call( select, expression, Expression.Lambda(outerLambdaBody, outerPrm)); return resultExpression; } }
41.12963
122
0.70824
[ "MIT" ]
Applesauce314/efcore
test/EFCore.Specification.Tests/TestUtilities/QueryTestGeneration/AppendCorrelatedCollectionExpressionMutator.cs
2,223
C#
namespace MassTransit.AmazonSqsTransport.Configuration.Configuration { using System; using System.Collections.Generic; using Builders; using GreenPipes; using GreenPipes.Agents; using GreenPipes.Builders; using GreenPipes.Configurators; using MassTransit.Configuration; using MassTransit.Pipeline.Filters; using Pipeline; using Topology; using Topology.Settings; using Transport; public class AmazonSqsReceiveEndpointConfiguration : ReceiveEndpointConfiguration, IAmazonSqsReceiveEndpointConfiguration, IAmazonSqsReceiveEndpointConfigurator { readonly IBuildPipeConfigurator<ConnectionContext> _connectionConfigurator; readonly IAmazonSqsEndpointConfiguration _endpointConfiguration; readonly IAmazonSqsHostConfiguration _hostConfiguration; readonly Lazy<Uri> _inputAddress; readonly IBuildPipeConfigurator<ClientContext> _clientConfigurator; readonly QueueReceiveSettings _settings; public AmazonSqsReceiveEndpointConfiguration(IAmazonSqsHostConfiguration hostConfiguration, string queueName, IAmazonSqsEndpointConfiguration endpointConfiguration) : this(hostConfiguration, endpointConfiguration) { SubscribeMessageTopics = true; _settings = new QueueReceiveSettings(queueName, true, false); } public AmazonSqsReceiveEndpointConfiguration(IAmazonSqsHostConfiguration hostConfiguration, QueueReceiveSettings settings, IAmazonSqsEndpointConfiguration endpointConfiguration) : this(hostConfiguration, endpointConfiguration) { _settings = settings; } AmazonSqsReceiveEndpointConfiguration(IAmazonSqsHostConfiguration hostConfiguration, IAmazonSqsEndpointConfiguration endpointConfiguration) : base(hostConfiguration, endpointConfiguration) { _hostConfiguration = hostConfiguration; _endpointConfiguration = endpointConfiguration; _connectionConfigurator = new PipeConfigurator<ConnectionContext>(); _clientConfigurator = new PipeConfigurator<ClientContext>(); HostAddress = hostConfiguration.Host.Address; _inputAddress = new Lazy<Uri>(FormatInputAddress); } public IAmazonSqsReceiveEndpointConfigurator Configurator => this; public IAmazonSqsBusConfiguration BusConfiguration => _hostConfiguration.BusConfiguration; public IAmazonSqsHostConfiguration HostConfiguration => _hostConfiguration; public IAmazonSqsHostControl Host => _hostConfiguration.Host; public bool SubscribeMessageTopics { get; set; } public ReceiveSettings Settings => _settings; public override Uri HostAddress { get; } public override Uri InputAddress => _inputAddress.Value; IAmazonSqsTopologyConfiguration IAmazonSqsEndpointConfiguration.Topology => _endpointConfiguration.Topology; public override IReceiveEndpoint Build() { var builder = new AmazonSqsReceiveEndpointBuilder(this); ApplySpecifications(builder); var receiveEndpointContext = builder.CreateReceiveEndpointContext(); _clientConfigurator.UseFilter(new ConfigureTopologyFilter<ReceiveSettings>(_settings, receiveEndpointContext.BrokerTopology)); IAgent consumerAgent; if (_hostConfiguration.BusConfiguration.DeployTopologyOnly) { var transportReadyFilter = new TransportReadyFilter<ClientContext>(receiveEndpointContext); _clientConfigurator.UseFilter(transportReadyFilter); consumerAgent = transportReadyFilter; } else { if (_settings.PurgeOnStartup) _clientConfigurator.UseFilter(new PurgeOnStartupFilter(_settings.EntityName)); var consumerFilter = new AmazonSqsConsumerFilter(receiveEndpointContext); _clientConfigurator.UseFilter(consumerFilter); consumerAgent = consumerFilter; } IFilter<ConnectionContext> clientFilter = new ReceiveClientFilter(_clientConfigurator.Build()); _connectionConfigurator.UseFilter(clientFilter); var transport = new SqsReceiveTransport(_hostConfiguration.Host, _settings, _connectionConfigurator.Build(), receiveEndpointContext); transport.Add(consumerAgent); return CreateReceiveEndpoint(_settings.EntityName ?? NewId.Next().ToString(), transport, receiveEndpointContext); } IAmazonSqsHost IAmazonSqsReceiveEndpointConfigurator.Host => Host; public bool Durable { set { _settings.Durable = value; Changed("Durable"); } } public bool AutoDelete { set { _settings.AutoDelete = value; Changed("AutoDelete"); } } public ushort PrefetchCount { set => _settings.PrefetchCount = value; } public ushort WaitTimeSeconds { set => _settings.WaitTimeSeconds = value; } public bool PurgeOnStartup { set => _settings.PurgeOnStartup = value; } public IDictionary<string, object> QueueAttributes => _settings.QueueAttributes; public IDictionary<string, object> QueueSubscriptionAttributes => _settings.QueueSubscriptionAttributes; public void Subscribe(string topicName, Action<ITopicSubscriptionConfigurator> configure = null) { if (topicName == null) throw new ArgumentNullException(nameof(topicName)); _endpointConfiguration.Topology.Consume.Bind(topicName, configure); } public void Subscribe<T>(Action<ITopicSubscriptionConfigurator> configure = null) where T : class { _endpointConfiguration.Topology.Consume.GetMessageTopology<T>().Subscribe(configure); } public void ConfigureClient(Action<IPipeConfigurator<ClientContext>> configure) { configure?.Invoke(_clientConfigurator); } public void ConfigureConnection(Action<IPipeConfigurator<ConnectionContext>> configure) { configure?.Invoke(_connectionConfigurator); } Uri FormatInputAddress() { return _settings.GetInputAddress(_hostConfiguration.Host.Settings.HostAddress); } protected override bool IsAlreadyConfigured() { return _inputAddress.IsValueCreated || base.IsAlreadyConfigured(); } public override IEnumerable<ValidationResult> Validate() { var queueName = $"{_settings.EntityName}"; if (!AmazonSqsEntityNameValidator.Validator.IsValidEntityName(_settings.EntityName)) yield return this.Failure(queueName, "must be a valid queue name"); if (_settings.PurgeOnStartup) yield return this.Warning(queueName, "Existing messages in the queue will be purged on service start"); foreach (var result in base.Validate()) yield return result.WithParentKey(queueName); } } }
35.864734
147
0.674704
[ "ECL-2.0", "Apache-2.0" ]
AOrlov/MassTransit
src/MassTransit.AmazonSqsTransport/Configuration/Configuration/AmazonSqsReceiveEndpointConfiguration.cs
7,426
C#
using Autofac; using System; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Pomelo.EntityFrameworkCore.MySql.Infrastructure; using Pomelo.EntityFrameworkCore.MySql.Storage; using Adnc.Infr.EfCore; using Adnc.Infr.Common; using Adnc.Cus.Core.Entities; using Adnc.Core.Shared.Entities; using Adnc.Infr.EfCore.Interceptors; using Microsoft.EntityFrameworkCore.Query; using Pomelo.EntityFrameworkCore.MySql.Query.ExpressionVisitors.Internal; namespace Adnc.UnitTest.Fixtures { public class MaxscaleDbcontextFixture : IDisposable { public IContainer Container { get; private set; } public MaxscaleDbcontextFixture() { var containerBuilder = new ContainerBuilder(); //maxscale连接地址 //var dbstring = "Server=59.110.49.142;Port=14006;database=adnc_cus;uid=adnc;pwd=123abc;"; var dbstring = "server=59.110.49.142;port=14006;user=adnc;password=123abc;database=adnc_cus"; //注册操作用户 containerBuilder.RegisterType<UserContext>() .InstancePerLifetimeScope(); //注册DbContext Options containerBuilder.Register<DbContextOptions>(c => { var options = new DbContextOptionsBuilder<AdncDbContext>() .UseLoggerFactory(LoggerFactory.Create(builder => builder.AddDebug())) .UseMySql(dbstring, mySqlOptions => { mySqlOptions.ServerVersion(new ServerVersion(new Version(10, 5, 8), ServerType.MariaDb)); mySqlOptions.CharSet(CharSet.Utf8Mb4); }) .AddInterceptors(new CustomCommandInterceptor()) .Options; return options; }).InstancePerLifetimeScope(); //注册EntityInfo containerBuilder.RegisterType<EntityInfo>() .As<IEntityInfo>() .InstancePerLifetimeScope(); //注册DbContext containerBuilder.RegisterType<AdncDbContext>() .InstancePerLifetimeScope(); //注册Adnc.Infr.EfCore AdncInfrEfCoreModule.Register(containerBuilder); var services = Container = containerBuilder.Build(); } public void Dispose() { this.Container?.Dispose(); } } }
35.323529
109
0.620733
[ "MIT" ]
cqwebwang/Adnc
test/Adnc.UnitTest/Fixtures/MaxscaleDbcontextFixture.cs
2,440
C#
/// <summary> /// Copyright 2021 HGTP Capstone Team at the University of Utah: /// Emma Pinegar, Harrison Quick, Misha Griego, Jacob B. Norgaard /// /// Licensed under the MIT license. Read the project readme for details. /// </summary> namespace RevisedGestrApp.Models { /// <summary> /// Represents a contact person. /// </summary> public class Contact { public string Name { get; set; } public string PhoneNumber { get; set; } } }
25.157895
72
0.640167
[ "Unlicense" ]
HGTP/hgtp-capstone
mobile-app/RevisedGestrApp/RevisedGestrApp/RevisedGestrApp/Models/Contact.cs
480
C#
using LNF.DataAccess; using System; namespace LNF.Impl.Repository.Data { public class GlobalCost : IDataItem { public virtual int GlobalID { get; set; } public virtual int BusinessDay { get; set; } public virtual Account LabAccount { get; set; } public virtual Account LabCreditAccount { get; set; } public virtual Account SubsidyCreditAccount { get; set; } public virtual Client Admin { get; set; } public virtual int AccessToOld { get; set; } public virtual DateTime EffDate { get; set; } } }
31.833333
65
0.65096
[ "MIT" ]
lurienanofab/lnf
LNF.Impl/Repository/Data/GlobalCost.cs
575
C#
namespace Console_CSharp { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Xml.Linq; internal class XmlDocReader { private IEnumerable<XElement> MemberElements { get; } public XmlDocReader(string aPath) { XDocument xDocument; using (TextReader reader = File.OpenText(aPath)) { xDocument = XDocument.Load(reader); } MemberElements = xDocument.Root.Descendants("member"); } public string GetDescriptionForName(string aName) { XElement memberElement = MemberElements.First(aElement => aElement.Attribute("name").Value == aName); XElement summary = memberElement.Descendants("summary").FirstOrDefault(); return summary.Value; } public string GetDescriptionForPropertyInfo(PropertyInfo aPropertyInfo) => GetDescriptionForName($"P:{aPropertyInfo.DeclaringType.FullName}.{aPropertyInfo.Name}"); public string GetDescriptionForType(Type aType) => GetDescriptionForName($"T:{aType.FullName}"); } }
29.432432
107
0.708907
[ "Unlicense" ]
TimeWarpEngineering/timewarp-architecture
Source/TimeWarp.Console.Template/content/TimeWarp.Console-CSharp/Source/XmlDocReader.cs
1,091
C#
using Cofoundry.Core; using Cofoundry.Domain; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Cofoundry.Samples.PageBlockTypes { public class CarouselDisplayModelMapper : IPageBlockTypeDisplayModelMapper<CarouselDataModel> { private readonly IContentRepository _contentRepository; public CarouselDisplayModelMapper( IContentRepository contentRepository ) { _contentRepository = contentRepository; } public async Task MapAsync( PageBlockTypeDisplayModelMapperContext<CarouselDataModel> context, PageBlockTypeDisplayModelMapperResult<CarouselDataModel> result ) { // Find all the image ids to load var allImageAssetIds = context .Items .SelectMany(m => m.DataModel.Slides) .Select(m => m.ImageId) .Where(i => i > 0) .Distinct(); // Load image data var allImages = await _contentRepository .WithExecutionContext(context.ExecutionContext) .ImageAssets() .GetByIdRange(allImageAssetIds) .AsRenderDetails() .ExecuteAsync(); // Map display model foreach (var items in context.Items) { var output = new CarouselDisplayModel(); output.Slides = EnumerableHelper .Enumerate(items.DataModel.Slides) .Select(m => new CarouselSlideDisplayModel() { Image = allImages.GetOrDefault(m.ImageId), Text = m.Text, Title = m.Title }) .ToList(); result.Add(items, output); } } } }
31.290323
97
0.545876
[ "MIT" ]
cofoundry-cms/Cofoundry.Samples.PageBlockTypes
src/Cofoundry.Samples.PageBlockTypes/Cofoundry/PageBlockTypes/Carousel/CarouselDisplayModelMapper.cs
1,942
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 polly-2016-06-10.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.Polly.Model { /// <summary> /// SSML speech marks are not supported for plain text-type input. /// </summary> #if !NETSTANDARD [Serializable] #endif public partial class SsmlMarksNotSupportedForTextTypeException : AmazonPollyException { /// <summary> /// Constructs a new SsmlMarksNotSupportedForTextTypeException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public SsmlMarksNotSupportedForTextTypeException(string message) : base(message) {} /// <summary> /// Construct instance of SsmlMarksNotSupportedForTextTypeException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public SsmlMarksNotSupportedForTextTypeException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of SsmlMarksNotSupportedForTextTypeException /// </summary> /// <param name="innerException"></param> public SsmlMarksNotSupportedForTextTypeException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of SsmlMarksNotSupportedForTextTypeException /// </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 SsmlMarksNotSupportedForTextTypeException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of SsmlMarksNotSupportedForTextTypeException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public SsmlMarksNotSupportedForTextTypeException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !NETSTANDARD /// <summary> /// Constructs a new instance of the SsmlMarksNotSupportedForTextTypeException 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 SsmlMarksNotSupportedForTextTypeException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception. /// </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 a null reference (Nothing in Visual Basic). </exception> #if BCL35 [System.Security.Permissions.SecurityPermission( System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] #endif [System.Security.SecurityCritical] // These FxCop rules are giving false-positives for this method [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); } #endif } }
48.879032
183
0.691305
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/Polly/Generated/Model/SsmlMarksNotSupportedForTextTypeException.cs
6,061
C#
/******************************************/ /* */ /* Copyright (c) 2018 monitor1394 */ /* https://github.com/monitor1394 */ /* */ /******************************************/ using UnityEngine; namespace XCharts { /// <summary> /// 高亮的图形样式和文本标签样式。 /// </summary> [System.Serializable] public class Emphasis : SubComponent { [SerializeField] private bool m_Show; [SerializeField] private SerieLabel m_Label = new SerieLabel(); [SerializeField] private ItemStyle m_ItemStyle = new ItemStyle(); /// <summary> /// 是否启用高亮样式。 /// </summary> public bool show { get { return m_Show; } set { m_Show = value; } } /// <summary> /// 图形文本标签。 /// </summary> public SerieLabel label { get { return m_Label; } set { if (PropertyUtility.SetClass(ref m_Label, value, true)) SetAllDirty(); } } /// <summary> /// 图形样式。 /// </summary> public ItemStyle itemStyle { get { return m_ItemStyle; } set { if (PropertyUtility.SetClass(ref m_ItemStyle, value, true)) SetVerticesDirty(); } } public override bool vertsDirty { get { return m_VertsDirty || label.vertsDirty || itemStyle.vertsDirty; } } public override bool componentDirty { get { return m_ComponentDirty || label.componentDirty; } } internal override void ClearVerticesDirty() { base.ClearVerticesDirty(); label.ClearVerticesDirty(); itemStyle.ClearVerticesDirty(); } internal override void ClearComponentDirty() { base.ClearComponentDirty(); label.ClearComponentDirty(); } } }
29.765625
116
0.502887
[ "MIT" ]
moonforce/unity-ugui-XCharts
Assets/XCharts/Runtime/Component/Sub/Emphasis.cs
1,977
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace System.ComponentModel.Design { public sealed class DesignerActionUIService : IDisposable { private DesignerActionUIStateChangeEventHandler _designerActionUIStateChangedEventHandler; private readonly IServiceProvider _serviceProvider; //standard service provider private readonly DesignerActionService _designerActionService; internal DesignerActionUIService(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; if (serviceProvider != null) { _serviceProvider = serviceProvider; IDesignerHost host = (IDesignerHost)serviceProvider.GetService(typeof(IDesignerHost)); host.AddService(typeof(DesignerActionUIService), this); _designerActionService = serviceProvider.GetService(typeof(DesignerActionService)) as DesignerActionService; Debug.Assert(_designerActionService != null, "we should have created and registered the DAService first"); } } /// <summary> /// Disposes all resources and unhooks all events. /// </summary> public void Dispose() { if (_serviceProvider != null) { IDesignerHost host = (IDesignerHost)_serviceProvider.GetService(typeof(IDesignerHost)); if (host != null) { host.RemoveService(typeof(DesignerActionUIService)); } } } /// <summary> /// This event is thrown whenever a request is made to show/hide the ui /// </summary> public event DesignerActionUIStateChangeEventHandler DesignerActionUIStateChange { add => _designerActionUIStateChangedEventHandler += value; remove => _designerActionUIStateChangedEventHandler -= value; } public void HideUI(IComponent component) { OnDesignerActionUIStateChange(new DesignerActionUIStateChangeEventArgs(component, DesignerActionUIStateChangeType.Hide)); } public void ShowUI(IComponent component) { OnDesignerActionUIStateChange(new DesignerActionUIStateChangeEventArgs(component, DesignerActionUIStateChangeType.Show)); } /// <summary> /// This is a new Helper Method that the service provides to refresh the DesignerActionGlyph as well as DesignerActionPanels. /// </summary> public void Refresh(IComponent component) { OnDesignerActionUIStateChange(new DesignerActionUIStateChangeEventArgs(component, DesignerActionUIStateChangeType.Refresh)); } /// <summary> /// This fires our DesignerActionsChanged event. /// </summary> private void OnDesignerActionUIStateChange(DesignerActionUIStateChangeEventArgs e) { _designerActionUIStateChangedEventHandler?.Invoke(this, e); } public bool ShouldAutoShow(IComponent component) { // Check the designer options... if (_serviceProvider != null) { if (_serviceProvider.GetService(typeof(DesignerOptionService)) is DesignerOptionService opts) { PropertyDescriptor p = opts.Options.Properties["ObjectBoundSmartTagAutoShow"]; if (p != null && p.PropertyType == typeof(bool) && !(bool)p.GetValue(null)) { return false; } } } if (_designerActionService != null) { DesignerActionListCollection coll = _designerActionService.GetComponentActions(component); if (coll != null && coll.Count > 0) { for (int i = 0; i < coll.Count; i++) { if (coll[i].AutoShow) { return true; } } } } return false; } } }
39.827273
136
0.598265
[ "MIT" ]
SeppPenner/winforms
src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerActionUIService.cs
4,383
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // La información general sobre un ensamblado se controla mediante el siguiente // conjunto de atributos. Cambie estos atributos para modificar la información // asociada con un ensamblado. [assembly: AssemblyTitle("SOFTTEK.SF.CodeGeneration")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SOFTTEK.SF.CodeGeneration")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Si establece ComVisible como false, los tipos de este ensamblado no estarán visibles // para los componentes COM. Si necesita obtener acceso a un tipo de este ensamblado desde // COM, establezca el atributo ComVisible como true en este tipo. [assembly: ComVisible(false)] // El siguiente GUID sirve como identificador de typelib si este proyecto se expone a COM [assembly: Guid("1dd151ff-7c6c-4211-8275-9440b149fd8c")] // La información de versión de un ensamblado consta de los cuatro valores siguientes: // // Versión principal // Versión secundaria // Número de compilación // Revisión // // Puede especificar todos los valores o establecer como predeterminados los números de compilación y de revisión // mediante el carácter '*', como se muestra a continuación: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
41.864865
114
0.763073
[ "MIT" ]
ingscarrero/dotNet
SOFTTEK/softtek.scms.net/SOFTTEK.SF.CodeGeneration/Properties/AssemblyInfo.cs
1,567
C#
using System; using System.Timers; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.IO; namespace AsyncServer { #region TimeoutTimer /// <summary> /// Timeout Timer /// </summary> public class TimeoutTimer : Timer { private object tag; public object Tag { get { return tag; } } public TimeoutTimer(object tag) : base() { this.tag = tag; } public void Restart() { Stop(); Start(); } } #endregion public enum ConnectStatu{ Uncheck =0, Success, Fail } /// <summary> /// Represents an Asterion client connection. /// </summary> public class Connection<T> : AClient { public ConnectStatu Statu { get; internal set; } internal byte[] Bytes; internal byte[] ResetCache() { Bytes = new byte[1024]; return Bytes; } /// <summary> /// Gets the timeout timer. /// </summary> /// <value>The timeout timer.</value> public TimeoutTimer Timer { get; internal set; } public T Tag { get; set; } /// <summary> /// Initializes a new instance of the Connection class. /// </summary> public Connection(TcpClient client):base(client) { Timer = new TimeoutTimer(this); Statu = ConnectStatu.Uncheck; } } }
21.109375
63
0.589193
[ "MIT" ]
Yugioh-Sims-International/Launcher-Server-System
lib/AsyncServer/Connection.cs
1,353
C#
using Retyped; namespace BabylonJsDemo.SceneProviders { public abstract class AbstractSceneProvider { public abstract babylon_js.BABYLON.Scene CreateScene(dom.HTMLCanvasElement canvas, babylon_js.BABYLON.Engine engine); } }
27.222222
125
0.77551
[ "Apache-2.0" ]
Chelton17/idk
BabylonJsDemo/BabylonJsDemo/SceneProviders/AbstractSceneProvider.cs
247
C#
/* * Copyright(c) 2020 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.ComponentModel; using Tizen.NUI.BaseComponents; namespace Tizen.NUI.Components { /// <summary> /// The default CheckBox style /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public class DefaultCheckBoxStyle : StyleBase { /// <summary> /// Return default CheckBox style /// </summary> internal protected override ViewStyle GetAttributes() { ButtonStyle style = new ButtonStyle { Size = new Size(30, 30), Icon = new ImageViewStyle { WidthResizePolicy = ResizePolicyType.DimensionDependency, HeightResizePolicy = ResizePolicyType.SizeRelativeToParent, SizeModeFactor = new Vector3(1, 1, 1), Opacity = new Selector<float?> { Normal = 1.0f, Selected = 1.0f, Disabled = 0.4f, DisabledSelected = 0.4f }, BackgroundImage = new Selector<string> { Normal = DefaultStyle.GetResourcePath("nui_component_default_checkbox_bg_n.png"), Pressed = DefaultStyle.GetResourcePath("nui_component_default_checkbox_bg_p.png"), Selected = DefaultStyle.GetResourcePath("nui_component_default_checkbox_bg_p.png"), Disabled = DefaultStyle.GetResourcePath("nui_component_default_checkbox_bg_n.png"), DisabledSelected = DefaultStyle.GetResourcePath("nui_component_default_checkbox_bg_p.png"), }, ResourceUrl = new Selector<string> { Normal = "", Pressed = "", Selected = DefaultStyle.GetResourcePath("nui_component_default_checkbox_s.png"), Disabled = "", DisabledSelected = DefaultStyle.GetResourcePath("nui_component_default_checkbox_s.png"), } }, Text = new TextLabelStyle { PointSize = new Selector<float?> { All = DefaultStyle.PointSizeNormal }, WidthResizePolicy = ResizePolicyType.FillToParent, HeightResizePolicy = ResizePolicyType.FillToParent, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, TextColor = new Selector<Color> { Normal = new Color(0.22f, 0.22f, 0.22f, 1), Pressed = new Color(0.11f, 0.11f, 0.11f, 1), Disabled = new Color(0.66f, 0.66f, 0.66f, 1) } } }; return style; } } }
42.880952
115
0.549139
[ "Apache-2.0", "MIT" ]
JoogabYun/TizenFX
src/Tizen.NUI.Components/PreloadStyle/DefaultCheckBoxStyle.cs
3,602
C#
// Copyright (c) Christof Senn. All rights reserved. See license.txt in the project root for license information. namespace Remote.Linq { using Aqua.Dynamic; using System; using SystemLinq = System.Linq.Expressions; /// <summary> /// Denotes a provider for mapping values on translating expressions from <i>System.Linq</i> to <i>Remote.Linq</i> and vice versa. /// </summary> public interface IExpressionValueMapperProvider { /// <summary> /// Gets a <see cref="IDynamicObjectMapper"/> to map values from and to <see cref="DynamicObject"/>. /// </summary> IDynamicObjectMapper ValueMapper { get; } /// <summary> /// Gets a function to check whether expressions or parts thereof are eligibly for local evaluation. /// </summary> Func<SystemLinq.Expression, bool>? CanBeEvaluatedLocally { get; } } }
37.541667
134
0.660377
[ "MIT" ]
6bee/Remote.Linq
src/Remote.Linq/IExpressionValueMapperProvider.cs
903
C#
using System.Collections.Generic; using Product.Data.Context; using Product.Data.Entities; namespace Product.Data.Migrations { using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<ProductDataContext> { public Configuration() { AutomaticMigrationsEnabled = false; } private Material UpsertMaterial(ProductDataContext context, Material entity) { var existing = context.Materials.FirstOrDefault(x => x.Name == entity.Name); if (existing != null) { return existing; } entity = context.Materials.Add(entity); context.SaveChanges(); return entity; } private void UpsertProduct(ProductDataContext context, Entities.Product entity) { var existing = context.Products.FirstOrDefault(x => x.Name == entity.Name); if (existing != null) { return; } entity = context.Products.Add(entity); foreach (var productMaterial in entity.ProductMaterials) { var existingProductMaterial = context.ProductMaterials.FirstOrDefault(x => x.Quantity == productMaterial.Quantity && x.ProductId == productMaterial.ProductId && x.MaterialId == productMaterial.MaterialId); if (existingProductMaterial == null) { context.ProductMaterials.Add(productMaterial); } } context.SaveChanges(); } protected override void Seed(ProductDataContext context) { var box1 = UpsertMaterial(context, new Material { Name = "Box 1", Cost = 0.25m }); var box2 = UpsertMaterial(context, new Material { Name = "Box 2", Cost = 0.25m }); var label1 = UpsertMaterial(context, new Material { Name = "Toy Car Label", Cost = 0.01m }); var label2 = UpsertMaterial(context, new Material { Name = "Train Set Label", Cost = 0.01m }); var products = new[] { new Entities.Product { Name = "Toy Car", Price = 10.00m, ProductMaterials = new List<ProductMaterial>() { new ProductMaterial() { MaterialId = label1.MaterialId, Quantity = 2 }, new ProductMaterial() { MaterialId = box1.MaterialId, Quantity = 1 } } }, new Entities.Product { Name = "Train Set", Price = 100.00m, ProductMaterials = new List<ProductMaterial>() { new ProductMaterial() { MaterialId = label2.MaterialId, Quantity = 2 }, new ProductMaterial() { MaterialId = box2.MaterialId, Quantity = 1 } } }, }; foreach (var p in products) { UpsertProduct(context, p); } } } }
31.108108
221
0.486244
[ "MIT" ]
SGParikh/product-dotnet-test
Product.Data/Migrations/Configuration.cs
3,453
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.Media.V20180601Preview { public static class ListAssetContainerSas { public static Task<ListAssetContainerSasResult> InvokeAsync(ListAssetContainerSasArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<ListAssetContainerSasResult>("azure-nextgen:media/v20180601preview:listAssetContainerSas", args ?? new ListAssetContainerSasArgs(), options.WithVersion()); } public sealed class ListAssetContainerSasArgs : Pulumi.InvokeArgs { /// <summary> /// The Media Services account name. /// </summary> [Input("accountName", required: true)] public string AccountName { get; set; } = null!; /// <summary> /// The Asset name. /// </summary> [Input("assetName", required: true)] public string AssetName { get; set; } = null!; /// <summary> /// The SAS URL expiration time. This must be less than 24 hours from the current time. /// </summary> [Input("expiryTime")] public string? ExpiryTime { get; set; } /// <summary> /// The permissions to set on the SAS URL. /// </summary> [Input("permissions")] public string? Permissions { get; set; } /// <summary> /// The name of the resource group within the Azure subscription. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; public ListAssetContainerSasArgs() { } } [OutputType] public sealed class ListAssetContainerSasResult { /// <summary> /// The list of Asset container SAS URLs. /// </summary> public readonly ImmutableArray<string> AssetContainerSasUrls; [OutputConstructor] private ListAssetContainerSasResult(ImmutableArray<string> assetContainerSasUrls) { AssetContainerSasUrls = assetContainerSasUrls; } } }
32.652778
209
0.6359
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/Media/V20180601Preview/ListAssetContainerSas.cs
2,351
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using Newtonsoft.Json; namespace FormatterWebSite; public class InfinitelyRecursiveModel { [JsonConverter(typeof(StringIdentifierConverter))] public RecursiveIdentifier Id { get; set; } private class StringIdentifierConverter : JsonConverter { public override bool CanConvert(Type objectType) => objectType == typeof(RecursiveIdentifier); public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return new RecursiveIdentifier(reader.Value.ToString()); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } } }
31.413793
124
0.720088
[ "MIT" ]
AndrewTriesToCode/aspnetcore
src/Mvc/test/WebSites/FormatterWebSite/Models/InfinitelyRecursiveModel.cs
913
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18408 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // // This source code was auto-generated by xsd, Version=4.0.30319.1. // namespace Microsoft.WindowsAzure.Commands.ServiceManagement.Extensions.ADDomain { using System.Xml.Serialization; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)] [System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)] public partial class PublicConfig { private string nameField; private string userField; private uint optionsField; private string oUPathField; private string unjoinDomainUserField; private bool restartField; public PublicConfig() { this.optionsField = ((uint)(0)); this.restartField = false; } /// <remarks/> public string Name { get { return this.nameField; } set { this.nameField = value; } } /// <remarks/> public string User { get { return this.userField; } set { this.userField = value; } } /// <remarks/> [System.ComponentModel.DefaultValueAttribute(typeof(uint), "0")] public uint Options { get { return this.optionsField; } set { this.optionsField = value; } } /// <remarks/> public string OUPath { get { return this.oUPathField; } set { this.oUPathField = value; } } /// <remarks/> public string UnjoinDomainUser { get { return this.unjoinDomainUserField; } set { this.unjoinDomainUserField = value; } } /// <remarks/> [System.ComponentModel.DefaultValueAttribute(false)] public bool Restart { get { return this.restartField; } set { this.restartField = value; } } } }
28.373832
82
0.458827
[ "MIT" ]
Milstein/azure-sdk-tools
WindowsAzurePowershell/src/Commands.ServiceManagement/Extensions/ADDomain/ADPublicSchema.cs
2,932
C#
// OsmSharp - OpenStreetMap (OSM) SDK // Copyright (C) 2013 Abelshausen Ben // // This file is part of OsmSharp. // // OsmSharp is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // OsmSharp is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with OsmSharp. If not, see <http://www.gnu.org/licenses/>. using System.Collections.Generic; using System.Linq; namespace OsmSharp.Collections.Tags { /// <summary> /// A dictionary that uses a string table behind. /// </summary> public class StringTableTagsCollection : TagsCollectionBase { /// <summary> /// Holds the list of encoded tags. /// </summary> private readonly List<TagEncoded> _tagsList; /// <summary> /// Holds the stringtable. /// </summary> private readonly ObjectTable<string> _stringTable; /// <summary> /// Creates a new dictionary. /// </summary> /// <param name="stringTable"></param> public StringTableTagsCollection(ObjectTable<string> stringTable) { _stringTable = stringTable; _tagsList = new List<TagEncoded>(); } /// <summary> /// Adds key-value pair of strings. /// </summary> /// <param name="key"></param> /// <param name="value"></param> public override void Add(string key, string value) { _tagsList.Add(new TagEncoded() { Key = _stringTable.Add(key), Value = _stringTable.Add(value) }); } /// <summary> /// Returns the number of tags in this collection. /// </summary> public override int Count { get { return _tagsList.Count; } } /// <summary> /// Returns true if this collection is readonly. /// </summary> public override bool IsReadonly { get { return false; } } /// <summary> /// Adds a tag. /// </summary> /// <param name="tag"></param> public override void Add(Tag tag) { this.Add(tag.Key, tag.Value); } /// <summary> /// Adds a new tag (key-value pair) to this tags collection. /// </summary> /// <param name="key"></param> /// <param name="value"></param> public override void AddOrReplace(string key, string value) { uint keyInt = _stringTable.Add(key); // TODO: this could be problematic, testing contains adds objects to string table. uint valueInt = _stringTable.Add(value); for (int idx = 0; idx < _tagsList.Count; idx++) { TagEncoded tag = _tagsList[idx]; if (tag.Key == keyInt) { tag.Value = valueInt; _tagsList[idx] = tag; return; } } _tagsList.Add(new TagEncoded() { Key = keyInt, Value = valueInt }); } /// <summary> /// Adds a new tag to this collection. /// </summary> /// <param name="tag"></param> public override void AddOrReplace(Tag tag) { this.AddOrReplace(tag.Key, tag.Value); } /// <summary> /// Returns true if the given key is present. /// </summary> /// <param name="key"></param> /// <returns></returns> public override bool ContainsKey(string key) { uint keyInt = _stringTable.Add(key); // TODO: this could be problematic, testing contains adds objects to string table. return _tagsList.Any(tag => tag.Key == keyInt); } /// <summary> /// Returns true when the given key is found and sets the value. /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> public override bool TryGetValue(string key, out string value) { uint keyInt = _stringTable.Add(key); // TODO: this could be problematic, testing contains adds objects to string table. foreach (var tagEncoded in _tagsList.Where(tagEncoded => tagEncoded.Key == keyInt)) { value = _stringTable.Get(tagEncoded.Value); return true; } value = null; return false; } /// <summary> /// Returns true when key-value are contained. /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> public override bool ContainsKeyValue(string key, string value) { uint keyInt = _stringTable.Add(key); // TODO: this could be problematic, testing contains adds objects to string table. uint valueInt = _stringTable.Add(value); return _tagsList.Any(tagEncoded => tagEncoded.Key == keyInt && tagEncoded.Value == valueInt); } /// <summary> /// Returns an enumerator for the tags. /// </summary> /// <returns></returns> public override IEnumerator<Tag> GetEnumerator() { foreach (var tagEncoded in _tagsList) { var tag = new Tag() { Key = _stringTable.Get(tagEncoded.Key), Value = _stringTable.Get(tagEncoded.Value) }; yield return tag; } } /// <summary> /// An encoded tag. /// </summary> private struct TagEncoded { /// <summary> /// The encoded key. /// </summary> public uint Key { get; set; } /// <summary> /// The encode value. /// </summary> public uint Value { get; set; } } /// <summary> /// Clears all tags. /// </summary> public override void Clear() { _tagsList.Clear(); } /// <summary> /// Removes all tags with the given key. /// </summary> /// <param name="key"></param> /// <returns></returns> public override bool RemoveKey(string key) { uint keyInt = _stringTable.Add(key); return _tagsList.RemoveAll(tagEncoded => tagEncoded.Key == keyInt) > 0; } /// <summary> /// Removes the given key-value pair. /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> public override bool RemoveKeyValue(string key, string value) { uint keyInt = _stringTable.Add(key); uint valueInt = _stringTable.Add(value); return _tagsList.RemoveAll(tagEncoded => tagEncoded.Key == keyInt && tagEncoded.Value == valueInt) > 0; } /// <summary> /// Removes all tags that match the given predicate. /// </summary> /// <param name="predicate"></param> public override void RemoveAll(System.Predicate<Tag> predicate) { _tagsList.RemoveAll(x => predicate.Invoke(new Tag(_stringTable.Get(x.Key), _stringTable.Get(x.Value)))); } } }
32.710204
132
0.518717
[ "Apache-2.0" ]
fakit/OSM-AutoCAD
Mustern/core-releases-v1.3/OsmSharp/Collections/Tags/StringTableTagsCollection.cs
8,016
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.Sql.V20171001Preview { /// <summary> /// A managed instance key. /// </summary> [AzureNextGenResourceType("azure-nextgen:sql/v20171001preview:ManagedInstanceKey")] public partial class ManagedInstanceKey : Pulumi.CustomResource { /// <summary> /// The key creation date. /// </summary> [Output("creationDate")] public Output<string> CreationDate { get; private set; } = null!; /// <summary> /// Kind of encryption protector. This is metadata used for the Azure portal experience. /// </summary> [Output("kind")] public Output<string> Kind { get; private set; } = null!; /// <summary> /// Resource name. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The key type like 'ServiceManaged', 'AzureKeyVault'. /// </summary> [Output("serverKeyType")] public Output<string> ServerKeyType { get; private set; } = null!; /// <summary> /// Thumbprint of the key. /// </summary> [Output("thumbprint")] public Output<string> Thumbprint { get; private set; } = null!; /// <summary> /// Resource type. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// The URI of the key. If the ServerKeyType is AzureKeyVault, then the URI is required. /// </summary> [Output("uri")] public Output<string?> Uri { get; private set; } = null!; /// <summary> /// Create a ManagedInstanceKey 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 ManagedInstanceKey(string name, ManagedInstanceKeyArgs args, CustomResourceOptions? options = null) : base("azure-nextgen:sql/v20171001preview:ManagedInstanceKey", name, args ?? new ManagedInstanceKeyArgs(), MakeResourceOptions(options, "")) { } private ManagedInstanceKey(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-nextgen:sql/v20171001preview:ManagedInstanceKey", name, null, 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-nextgen:sql:ManagedInstanceKey"}, new Pulumi.Alias { Type = "azure-nextgen:sql/v20200202preview:ManagedInstanceKey"}, new Pulumi.Alias { Type = "azure-nextgen:sql/v20200801preview:ManagedInstanceKey"}, }, }; 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 ManagedInstanceKey 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="options">A bag of options that control this resource's behavior</param> public static ManagedInstanceKey Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new ManagedInstanceKey(name, id, options); } } public sealed class ManagedInstanceKeyArgs : Pulumi.ResourceArgs { /// <summary> /// The name of the managed instance key to be operated on (updated or created). /// </summary> [Input("keyName")] public Input<string>? KeyName { get; set; } /// <summary> /// The name of the managed instance. /// </summary> [Input("managedInstanceName", required: true)] public Input<string> ManagedInstanceName { get; set; } = null!; /// <summary> /// The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// The key type like 'ServiceManaged', 'AzureKeyVault'. /// </summary> [Input("serverKeyType", required: true)] public InputUnion<string, Pulumi.AzureNextGen.Sql.V20171001Preview.ServerKeyType> ServerKeyType { get; set; } = null!; /// <summary> /// The URI of the key. If the ServerKeyType is AzureKeyVault, then the URI is required. /// </summary> [Input("uri")] public Input<string>? Uri { get; set; } public ManagedInstanceKeyArgs() { } } }
40.273973
153
0.602721
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Sql/V20171001Preview/ManagedInstanceKey.cs
5,880
C#
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if DIRECTX11_1 using System; using System.Collections.Generic; using System.Text; namespace SharpDX.Direct2D1 { /// <summary> /// Represents the base interface for all of the transforms implemented by the transform author. /// </summary> /// <unmanaged>ID2D1Transform</unmanaged> [ShadowAttribute(typeof(TransformShadow))] public partial interface Transform { /// <summary> /// <p>[This documentation is preliminary and is subject to change.]</p><p><strong>Applies to: </strong>desktop apps | Metro style apps</p><p>Allows a transform to state how it would map a rectangle requested on its output to a set of sample rectangles on its input.</p> /// </summary> /// <param name="outputRect"><dd> <p>The output rectangle to which the inputs must be mapped.</p> </dd></param> /// <param name="inputRects"><dd> <p>The corresponding set of inputs. The inputs will directly correspond to the transform inputs.</p> </dd></param> /// <remarks> /// <p>The transform implementation must ensure that any pixel shader or software callback implementation it provides honors this calculation.</p><p>The transform implementation must regard this method as purely functional. It can base the mapped input and output rectangles on its current state as specified by the encapsulating effect properties. However, it must not change its own state in response to this method being invoked. The DirectImage renderer implementation reserves the right to call this method at any time and in any sequence.</p> /// </remarks> /// <msdn-id>hh446945</msdn-id> /// <unmanaged>HRESULT ID2D1Transform::MapOutputRectToInputRects([In] const RECT* outputRect,[Out, Buffer] RECT* inputRects,[In] unsigned int inputRectsCount)</unmanaged> /// <unmanaged-short>ID2D1Transform::MapOutputRectToInputRects</unmanaged-short> void MapOutputRectangleToInputRectangles(SharpDX.Rectangle outputRect, SharpDX.Rectangle[] inputRects); /// <summary> /// <p>[This documentation is preliminary and is subject to change.]</p><p><strong>Applies to: </strong>desktop apps | Metro style apps</p><p>Performs the inverse mapping to <strong>MapOutputRectToInputRects</strong>.</p> /// </summary> /// <param name="inputRects">No documentation.</param> /// <param name="inputOpaqueSubRects">No documentation.</param> /// <param name="outputOpaqueSubRect">No documentation.</param> /// <returns>No outputOpaqueSubRect.</returns> /// <remarks> /// <p>The transform implementation must ensure that any pixel shader or software callback implementation it provides honors this calculation.</p><p>The transform implementation must regard this method as purely functional. It can base the mapped input and output rectangles on its current state as specified by the encapsulating effect properties. However, it must not change its own state in response to this method being invoked. The Direct2D renderer implementation reserves the right to call this method at any time and in any sequence.</p> /// </remarks> /// <msdn-id>hh446943</msdn-id> /// <unmanaged>HRESULT ID2D1Transform::MapInputRectsToOutputRect([In, Buffer] const RECT* inputRects,[In, Buffer] const RECT* inputOpaqueSubRects,[In] unsigned int inputRectCount,[Out] RECT* outputRect,[Out] RECT* outputOpaqueSubRect)</unmanaged> /// <unmanaged-short>ID2D1Transform::MapInputRectsToOutputRect</unmanaged-short> SharpDX.Rectangle MapInputRectanglesToOutputRectangle(SharpDX.Rectangle[] inputRects, SharpDX.Rectangle[] inputOpaqueSubRects, out SharpDX.Rectangle outputOpaqueSubRect); /// <summary> /// No documentation. /// </summary> /// <param name="inputIndex">No documentation.</param> /// <param name="invalidInputRect">No documentation.</param> /// <returns>The rectangle invalidated.</returns> /// <unmanaged>HRESULT ID2D1Transform::MapInvalidRect([In] unsigned int inputIndex,[In] RECT invalidInputRect,[Out] RECT* invalidOutputRect)</unmanaged> /// <unmanaged-short>ID2D1Transform::MapInvalidRect</unmanaged-short> SharpDX.Rectangle MapInvalidRect(int inputIndex, SharpDX.Rectangle invalidInputRect); } } #endif
75.232877
560
0.724326
[ "MIT" ]
VirusFree/SharpDX
Source/SharpDX.Direct2D1/Transform.cs
5,494
C#
using OpenTibiaUnity.Core.Trade; using UnityEngine; using UnityUI = UnityEngine.UI; namespace OpenTibiaUnity.Modules.Trade { [RequireComponent(typeof(UnityUI.Toggle))] public class NPCTradeItem : UI.Legacy.ToggleListItem { [SerializeField] private TMPro.TextMeshProUGUI _label = null; // properties public string text { get => _label.text; set => _label.text = value; } public TradeObjectRef tradeObject { get; set; } = null; } }
22.73913
63
0.636711
[ "MIT" ]
nekiro/OpenTibia-Unity
OpenTibia/Assets/Scripts/Modules/Trade/NPCTradeItem.cs
525
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using WorkflowDatabase.EF.Models; namespace Portal.ViewModels { public class TaskViewModel { public int WorkflowInstanceId { get; set; } public int ProcessId { get; set; } [DisplayFormat(NullDisplayText = "N/A", DataFormatString = "{0:d}")] public DateTime? DmEndDate { get; set; } public short? DaysToDmEndDate { get; set; } public bool DaysToDmEndDateGreenAlert { get; set; } public bool DaysToDmEndDateAmberAlert { get; set; } public bool DaysToDmEndDateRedAlert { get; set; } public bool IsOnHold { get; set; } public bool OnHoldDaysAmber { get; set; } public bool OnHoldDaysGreen { get; set; } public bool OnHoldDaysRed { get; set; } public int OnHoldDays { get; set; } [DisplayFormat(NullDisplayText = "N/A")] public string AssessmentDataParsedRsdraNumber { get; set; } [DisplayFormat(NullDisplayText = "N/A")] public string AssessmentDataSourceDocumentName { get; set; } public string Workspace { get; set; } public string TaskStage { get; set; } public AdUser Reviewer { get; set; } public AdUser Assessor { get; set; } public AdUser Verifier { get; set; } public string Team { get; set; } public string Complexity { get; set; } public string TaskNoteText { get; set; } public List<Comment> Comment { get; set; } } }
40.526316
76
0.64026
[ "MIT" ]
UKHO/taskmanager
src/Portal/Portal/ViewModels/TaskViewModel.cs
1,542
C#
using Microsoft.AspNetCore.Builder; using Netcool.HttpProxy; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); // Inject proxy builder.Services.AddProxy(options => { }); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.MapControllers(); app.UseRouting(); app.MapProxy("/baiduIp", "https://www.baidu.com/s?wd=ip"); app.Map("/baidu", appBuilder => { appBuilder.RunProxy("https://www.baidu.com/"); }); // map proxy with endpoint app.MapProxy("/baidu2/s/{wd:alpha}", dictionary => $"https://www.baidu.com/s?wd={dictionary["wd"]}"); app.MapProxy("/baidu3", _ => "https://www.baidu.com/s"); app.Run();
25.72973
101
0.717437
[ "Apache-2.0" ]
NeilQ/Netcool.Api
src/samples/Netcool.HttpProxy.Net6.Sample/Program.cs
952
C#
#if VOUCHERIFYSERVER || VOUCHERIFYCLIENT using System; using Newtonsoft.Json; using Voucherify.Core.DataModel; namespace Voucherify.DataModel { [JsonObject] public class VoucherRedemption : ApiObjectWithId { [JsonProperty(PropertyName = "date")] public DateTime? Date { get; private set; } [JsonProperty(PropertyName = "customer_id")] public string CustomerId { get; private set; } [JsonProperty(PropertyName = "tracking_id")] public string TrackingId { get; private set; } [JsonProperty(PropertyName = "result")] public RedemptionResult Result { get; private set; } [JsonProperty(PropertyName = "metadata")] public Metadata Metadata { get; private set; } [JsonProperty(PropertyName = "order")] public Order Order { get; private set; } public VoucherRedemption() { this.Metadata = new Metadata(); } public override string ToString() { return string.Format("VoucherRedemption(Id={0},Cusotmer={1},Tracking={2},Result={3})", this.Id, this.CustomerId, this.TrackingId, this.Result); } } } #endif
29.8
155
0.63255
[ "MIT" ]
Mncool/voucherify-dotNET-sdk
src/Voucherify/DataModel/VoucherRedemption.cs
1,194
C#
using System; using JetBrains.Annotations; namespace MirrorSharp.Advanced { /// <summary>Provides a way to log unhandled exceptions.</summary> public interface IExceptionLogger { /// <summary>Logs a given exception.</summary> /// <param name="exception">Exception to log.</param> /// <param name="session">Current <see cref="IWorkSession" /></param> /// <remarks>Implementations should avoid throwing exceptions from this method.</remarks> void LogException([NotNull] Exception exception, [NotNull] IWorkSession session); } }
41.428571
97
0.691379
[ "MIT" ]
edcoss/Sitecore-Script
Common/Advanced/IExceptionLogger.cs
582
C#
using System; namespace Cogito.MassTransit.Autofac.Sample1 { public class TestSagaMessage { public Guid Id { get; set; } public string Value { get; set; } } }
12.125
44
0.608247
[ "MIT" ]
alethic/Cogito.MassTransit
Cogito.MassTransit.Autofac.Sample1/TestSagaMessage.cs
196
C#
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Npgsql; namespace Discount.Grpc.Extensions { public static class HostExtensions { public static IHost MigrateDatabase<TContext>(this IHost host, int? retry = 0) { int retryForAvailability = retry.Value; using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var configuration = services.GetRequiredService<IConfiguration>(); var logger = services.GetRequiredService<ILogger<TContext>>(); try { logger.LogInformation("Migrating postresql database."); using var connection = new NpgsqlConnection(configuration.GetValue<string>("DatabaseSettings:ConnectionString")); connection.Open(); using var command = new NpgsqlCommand { Connection = connection, }; command.CommandText = "DROP TABLE IF EXISTS Coupon"; command.ExecuteNonQuery(); command.CommandText = @"CREATE TABLE Coupon(Id SERIAL PRIMARY KEY, ProductName VARCHAR(24) NOT NULL, Description TEXT, Amount INT)"; command.ExecuteNonQuery(); command.CommandText = "INSERT INTO Coupon(ProductName, Description, Amount) VALUES('IPhone X', 'IPhone Discount', 150);"; command.ExecuteNonQuery(); command.CommandText = "INSERT INTO Coupon(ProductName, Description, Amount) VALUES('Samsung 10', 'Samsung Discount', 100);"; command.ExecuteNonQuery(); logger.LogInformation("Migrated postresql database."); } catch (NpgsqlException ex) { logger.LogError(ex, "An error occured while migrating the pastresql database"); if(retryForAvailability < 50) { retryForAvailability++; System.Threading.Thread.Sleep(2000); MigrateDatabase<TContext>(host, retryForAvailability); } } return host; } } } }
41.349206
144
0.527831
[ "MIT" ]
ramious76/AspnetMicroservices
src/Services/Discount/Discount.Grpc/Extensions/HostExtensions.cs
2,607
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; namespace AI { public enum AbortType { None, LowerPriority } [NodeTint(0.2f, 0.2f, 0.5f)] public abstract class Composite : Node { public AbortType m_abortType = AbortType.None; [Output(ShowBackingValue.Never, ConnectionType.Multiple)] public Node children; protected List<Node> m_nodes; protected int m_nodeIndex; // override XNode.Init() protected override void Init() { base.Init(); m_nodes = new List<Node>(); m_nodeIndex = -1; } protected override void OnReady() { m_nodeIndex = 0; } protected override void OnAbort() { if (m_nodeStatus == NodeStatus.RUNNING) { m_nodes[m_nodeIndex].Abort(); } } public override void CollectConditionals(ref List<Conditional> conditionalNodes) { foreach (var node in m_nodes) { node.CollectConditionals(ref conditionalNodes); } } protected void ReevaluateConditionals(GameObject go) { if (m_abortType == AbortType.None) { return; } if (m_nodeStatus != NodeStatus.RUNNING) { return; } // 現在実行中のノードよりも優先度の高いノードを再評価する // 状態が変化していたら現在実行中のノードを中断して、変化したノードから評価を再開する。 List<Node> higherPriorityNodes = m_nodes.Where((node, i) => (i < m_nodeIndex)).ToList(); bool flag = false; foreach (var node in higherPriorityNodes) { List<Conditional> conditionals = new List<Conditional>(); node.CollectConditionals(ref conditionals); foreach (var cond in conditionals) { NodeStatus prevStatus = cond.PrevStatus; if (prevStatus != cond.Evaluate(go)) { m_nodes[m_nodeIndex].Abort(); m_nodeIndex = m_nodes.FindIndex(nd => nd == node); flag = true; break; } } if (flag) break; } } protected void SetupNodesOrderByPriority() { m_nodes.Clear(); XNode.NodePort outPort = GetOutputPort("children"); if (!outPort.IsConnected) { return; } m_nodes = outPort.GetConnections().Select(port => port.node as Node).ToList(); // Node.Priority の値で降順にソート m_nodes.Sort((lhs, rhs) => rhs.Priority - lhs.Priority); // 子ノードの EvaluationOrder プロパティを更新 foreach (Node node in m_nodes) { node.EvaluationOrder = m_nodes.IndexOf(node) + 1; } } } }
27.45045
100
0.505415
[ "MIT" ]
world29/FlappyAzarashi
Assets/Scripts/BehaviourTree/Nodes/Composite.cs
3,231
C#
using System.Collections.Generic; using GovernCMS.Models; namespace GovernCMS.ViewModels { public class ManageWebsiteViewModel { public string SiteName { get; set; } public string SiteUrl { get; set; } public int OwnerId { get; set; } public IList<Website> Websites { get; set; } } }
23.571429
52
0.651515
[ "MIT" ]
ptenn/govern-cms
GovernCMSWeb/ViewModels/ManageWebsiteViewModel.cs
332
C#
using System.Linq; using System.Threading.Tasks; using Baseline; using Marten; using Marten.Services; using Marten.Storage; using Marten.Testing.Documents; using Marten.Testing.Harness; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Npgsql; using Shouldly; using Weasel.Postgresql; using Weasel.Postgresql.Migrations; using Xunit; namespace CoreTests.DatabaseMultiTenancy { [Collection("multi-tenancy")] public class using_static_database_multitenancy: IAsyncLifetime { private IHost _host; private IDocumentStore theStore; private async Task<string> CreateDatabaseIfNotExists(NpgsqlConnection conn, string databaseName) { var builder = new NpgsqlConnectionStringBuilder(ConnectionSource.ConnectionString); var exists = await conn.DatabaseExists(databaseName); if (!exists) { await new DatabaseSpecification().BuildDatabase(conn, databaseName); } builder.Database = databaseName; return builder.ConnectionString; } public async Task InitializeAsync() { using var conn = new NpgsqlConnection(ConnectionSource.ConnectionString); await conn.OpenAsync(); var db1ConnectionString = await CreateDatabaseIfNotExists(conn, "database1"); var tenant3ConnectionString = await CreateDatabaseIfNotExists(conn, "tenant3"); var tenant4ConnectionString = await CreateDatabaseIfNotExists(conn, "tenant4"); #region sample_using_multi_tenanted_databases _host = await Host.CreateDefaultBuilder() .ConfigureServices(services => { services.AddMarten(opts => { // Explicitly map tenant ids to database connection strings opts.MultiTenantedDatabases(x => { // Map multiple tenant ids to a single named database x.AddMultipleTenantDatabase(db1ConnectionString,"database1").ForTenants("tenant1", "tenant2"); // Map a single tenant id to a database, which uses the tenant id as well for the database identifier x.AddSingleTenantDatabase(tenant3ConnectionString, "tenant3"); x.AddSingleTenantDatabase(tenant4ConnectionString,"tenant4"); }); opts.RegisterDocumentType<User>(); opts.RegisterDocumentType<Target>(); }) // All detected changes will be applied to all // the configured tenant databases on startup .ApplyAllDatabaseChangesOnStartup(); }).StartAsync(); #endregion theStore = _host.Services.GetRequiredService<IDocumentStore>(); } public Task DisposeAsync() { return _host.StopAsync(); } [Fact] public void default_tenant_usage_is_disabled() { theStore.Options.Advanced .DefaultTenantUsageEnabled.ShouldBeFalse(); } [Fact] public async Task creates_databases_from_apply() { using var conn = new NpgsqlConnection(ConnectionSource.ConnectionString); await conn.OpenAsync(); (await conn.DatabaseExists("database1")).ShouldBeTrue(); (await conn.DatabaseExists("tenant3")).ShouldBeTrue(); (await conn.DatabaseExists("tenant4")).ShouldBeTrue(); } [Fact] public async Task changes_are_applied_to_each_database() { var store = _host.Services.GetRequiredService<IDocumentStore>().As<DocumentStore>(); var databases = await store.Tenancy.BuildDatabases(); foreach (IMartenDatabase database in databases) { using var conn = database.CreateConnection(); await conn.OpenAsync(); var tables = await conn.ExistingTables(); tables.Any(x => x.QualifiedName == "public.mt_doc_user").ShouldBeTrue(); tables.Any(x => x.QualifiedName == "public.mt_doc_target").ShouldBeTrue(); } } [Fact] public async Task can_open_a_session_to_a_different_database() { var session = await theStore.OpenSessionAsync(new SessionOptions { TenantId = "tenant1", Tracking = DocumentTracking.None }); session.Connection.Database.ShouldBe("database1"); } [Fact] public async Task can_use_bulk_inserts() { var targets3 = Target.GenerateRandomData(100).ToArray(); var targets4 = Target.GenerateRandomData(50).ToArray(); await theStore.Advanced.Clean.DeleteAllDocumentsAsync(); await theStore.BulkInsertDocumentsAsync("tenant3", targets3); await theStore.BulkInsertDocumentsAsync("tenant4", targets4); using (var query3 = theStore.QuerySession("tenant3")) { var ids = await query3.Query<Target>().Select(x => x.Id).ToListAsync(); ids.OrderBy(x => x).ShouldHaveTheSameElementsAs(targets3.OrderBy(x => x.Id).Select(x => x.Id).ToList()); } using (var query4 = theStore.QuerySession("tenant4")) { var ids = await query4.Query<Target>().Select(x => x.Id).ToListAsync(); ids.OrderBy(x => x).ShouldHaveTheSameElementsAs(targets4.OrderBy(x => x.Id).Select(x => x.Id).ToList()); } } [Fact] public async Task clean_crosses_the_tenanted_databases() { var targets3 = Target.GenerateRandomData(100).ToArray(); var targets4 = Target.GenerateRandomData(50).ToArray(); await theStore.BulkInsertDocumentsAsync("tenant3", targets3); await theStore.BulkInsertDocumentsAsync("tenant4", targets4); await theStore.Advanced.Clean.DeleteAllDocumentsAsync(); using (var query3 = theStore.QuerySession("tenant3")) { (await query3.Query<Target>().AnyAsync()).ShouldBeFalse(); } using (var query4 = theStore.QuerySession("tenant4")) { (await query4.Query<Target>().AnyAsync()).ShouldBeFalse(); } } public static async Task administering_multiple_databases(IDocumentStore store) { #region sample_administering_multiple_databases // Apply all detected changes in every known database await store.Storage.ApplyAllConfiguredChangesToDatabaseAsync(); // Only apply to the default database if not using multi-tenancy per // database await store.Storage.Database.ApplyAllConfiguredChangesToDatabaseAsync(); // Find a specific database var database = await store.Storage.FindOrCreateDatabase("tenant1"); // Tear down everything await database.CompletelyRemoveAllAsync(); // Check out the projection state in just this database var state = await database.FetchEventStoreStatistics(); // Apply all outstanding database changes in just this database await database.ApplyAllConfiguredChangesToDatabaseAsync(); #endregion } } }
36.305164
133
0.596793
[ "MIT" ]
Rob89/marten
src/CoreTests/DatabaseMultiTenancy/using_static_database_multitenancy.cs
7,733
C#
using System; using System.Collections.Generic; using System.Text; using Tizen.NUI.BaseComponents; using Tizen.NUI; using Tizen.UIExtensions.NUI; using Tizen.UIExtensions.Common; using TColor = Tizen.UIExtensions.Common.Color; using Tizen.Applications; namespace NUIExGallery.TC { public class NavigationTest : TestCaseBase { public override string TestName => "Navigation Animation Test"; public override string TestDescription => "Navigation Animation test"; public override View Run() { var navi = new NavigationStack { WidthSpecification = LayoutParamPolicies.MatchParent, HeightSpecification = LayoutParamPolicies.MatchParent, }; navi.PushAnimation = (view, progress) => { view.Opacity = 0.5f + 0.5f * (float)progress; }; navi.PopAnimation = (view, progress) => { view.Opacity = 0.5f + 0.5f * (float)(1 - progress); }; _ = navi.Push(new PushPopPage(navi, 1), true); return navi; } class PushPopPage : View { NavigationStack _stack; public PushPopPage(NavigationStack stack, int depth) { _stack = stack; WidthSpecification = LayoutParamPolicies.MatchParent; HeightSpecification = LayoutParamPolicies.MatchParent; var rnd = new Random(); BackgroundColor = TColor.FromRgba(rnd.Next(100, 200), rnd.Next(100, 200), rnd.Next(100, 200), 255).ToNative(); Layout = new LinearLayout { LinearOrientation = LinearLayout.Orientation.Vertical }; Add(new Label { Text = $"Text {depth}" }); var push = new Button { Text = "Push (fade)" }; Add(push); push.Clicked += (s, e) => { stack.PushAnimation = (view, progress) => { view.Opacity = 0.5f + 0.5f * (float)progress; }; _ = _stack.Push(new PushPopPage(_stack, depth+1), true); }; var push2 = new Button { Text = "Push (fade + Left)" }; Add(push2); push2.Clicked += (s, e) => { float? originalX = null; stack.PushAnimation = (view, progress) => { if (originalX == null) { originalX = view.PositionX; } view.PositionX = originalX.Value + (float)(view.SizeWidth / 4.0f * (1 - progress)); view.Opacity = 0.5f + 0.5f * (float)progress; }; _ = _stack.Push(new PushPopPage(_stack, depth + 1), true); }; var push3 = new Button { Text = "Push (fade + Up)" }; Add(push3); push3.Clicked += (s, e) => { float? originY = null; stack.PushAnimation = (view, progress) => { if (originY == null) { originY = view.PositionY; } view.PositionY = originY.Value + (float)(view.SizeHeight / 4.0f * (1 - progress)); view.Opacity = 0.5f + 0.5f * (float)progress; }; _ = _stack.Push(new PushPopPage(_stack, depth + 1), true); }; var pop = new Button { Text = "Pop (fade)" }; Add(pop); pop.Clicked += (s, e) => { stack.PopAnimation = (view, progress) => { view.Opacity = 0.5f + 0.5f * (float)(1 - progress); }; _ = _stack.Pop(true); }; var pop2 = new Button { Text = "Pop (fade + Right)" }; Add(pop2); pop2.Clicked += (s, e) => { float? originX = null; stack.PopAnimation = (view, progress) => { if (originX == null) { originX = view.PositionX; } view.PositionX = originX.Value + (float)(view.SizeWidth / 4.0f * progress); view.Opacity = 0.5f + 0.5f * (float)(1 - progress); }; _ = _stack.Pop(true); }; var pop3 = new Button { Text = "Pop (fade + down)" }; Add(pop3); pop3.Clicked += (s, e) => { float? originY = null; stack.PopAnimation = (view, progress) => { if (originY == null) { originY = view.PositionY; } view.PositionY = originY.Value + (float)(view.SizeHeight / 4.0f * progress); view.Opacity = 0.5f + 0.5f * (float)(1 - progress); }; _ = _stack.Pop(true); }; Add(new Image { ResourceUrl = Application.Current.DirectoryInfo.Resource + (depth % 2 == 0 ? "image.png" : "image2.jpg") }); } } } }
32.823529
126
0.390844
[ "Apache-2.0" ]
Samsung/Tizen.UIExtensions
test/NUIExGallery/TC/NavigationTest.cs
6,140
C#
namespace Win32 { /// <summary> /// Print quality. /// </summary> public enum DMRES : short { /// <summary> /// Draft quality. /// </summary> DRAFT=-1, /// <summary> /// Low quality. /// </summary> LOW=-2, /// <summary> /// Medium quality. /// </summary> MEDIUM=-3, /// <summary> /// High quality. /// </summary> HIGH=-4, } }
12.689655
26
0.5
[ "MIT" ]
RomanMayer7/Win32
GDI/Defines/DMRES.cs
370
C#
//namespace System.Windows //{ // public enum Visibility : byte // { // /// <summary>Display the element.</summary> // Visible, // /// <summary>Do not display the element, but reserve space for the element in layout.</summary> // Hidden, // /// <summary>Do not display the element, and do not reserve space for it in layout.</summary> // Collapsed, // } //}
34
105
0.588235
[ "MIT" ]
zerotwooneone/GameScreen
GameScreenTests2/System/Windows/Visibility.cs
408
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/d3d12sdklayers.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace TerraFX.Interop { [Guid("09E0BF36-54AC-484F-8847-4BAEEAB6053F")] public unsafe partial struct ID3D12DebugCommandList { public void** lpVtbl; [return: NativeTypeName("HRESULT")] public int QueryInterface([NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("void **")] void** ppvObject) { return ((delegate* stdcall<ID3D12DebugCommandList*, Guid*, void**, int>)(lpVtbl[0]))((ID3D12DebugCommandList*)Unsafe.AsPointer(ref this), riid, ppvObject); } [return: NativeTypeName("ULONG")] public uint AddRef() { return ((delegate* stdcall<ID3D12DebugCommandList*, uint>)(lpVtbl[1]))((ID3D12DebugCommandList*)Unsafe.AsPointer(ref this)); } [return: NativeTypeName("ULONG")] public uint Release() { return ((delegate* stdcall<ID3D12DebugCommandList*, uint>)(lpVtbl[2]))((ID3D12DebugCommandList*)Unsafe.AsPointer(ref this)); } [return: NativeTypeName("BOOL")] public int AssertResourceState([NativeTypeName("ID3D12Resource *")] ID3D12Resource* pResource, [NativeTypeName("UINT")] uint Subresource, [NativeTypeName("UINT")] uint State) { return ((delegate* stdcall<ID3D12DebugCommandList*, ID3D12Resource*, uint, uint, int>)(lpVtbl[3]))((ID3D12DebugCommandList*)Unsafe.AsPointer(ref this), pResource, Subresource, State); } [return: NativeTypeName("HRESULT")] public int SetFeatureMask(D3D12_DEBUG_FEATURE Mask) { return ((delegate* stdcall<ID3D12DebugCommandList*, D3D12_DEBUG_FEATURE, int>)(lpVtbl[4]))((ID3D12DebugCommandList*)Unsafe.AsPointer(ref this), Mask); } public D3D12_DEBUG_FEATURE GetFeatureMask() { return ((delegate* stdcall<ID3D12DebugCommandList*, D3D12_DEBUG_FEATURE>)(lpVtbl[5]))((ID3D12DebugCommandList*)Unsafe.AsPointer(ref this)); } } }
44.037736
195
0.679949
[ "MIT" ]
john-h-k/terrafx.interop.windows
sources/Interop/Windows/um/d3d12sdklayers/ID3D12DebugCommandList.cs
2,336
C#
// File generated from our OpenAPI spec namespace Stripe { using Newtonsoft.Json; public class InvoiceCustomerDetailsTaxIdOptions : INestedOptions { /// <summary> /// Type of the tax ID, one of <c>ae_trn</c>, <c>au_abn</c>, <c>br_cnpj</c>, <c>br_cpf</c>, /// <c>ca_bn</c>, <c>ca_qst</c>, <c>ch_vat</c>, <c>cl_tin</c>, <c>es_cif</c>, <c>eu_vat</c>, /// <c>gb_vat</c>, <c>hk_br</c>, <c>id_npwp</c>, <c>in_gst</c>, <c>jp_cn</c>, <c>jp_rn</c>, /// <c>kr_brn</c>, <c>li_uid</c>, <c>mx_rfc</c>, <c>my_frp</c>, <c>my_itn</c>, /// <c>my_sst</c>, <c>no_vat</c>, <c>nz_gst</c>, <c>ru_inn</c>, <c>ru_kpp</c>, /// <c>sa_vat</c>, <c>sg_gst</c>, <c>sg_uen</c>, <c>th_vat</c>, <c>tw_vat</c>, /// <c>us_ein</c>, or <c>za_vat</c>. /// One of: <c>ae_trn</c>, <c>au_abn</c>, <c>br_cnpj</c>, <c>br_cpf</c>, <c>ca_bn</c>, /// <c>ca_qst</c>, <c>ch_vat</c>, <c>cl_tin</c>, <c>es_cif</c>, <c>eu_vat</c>, /// <c>gb_vat</c>, <c>hk_br</c>, <c>id_npwp</c>, <c>in_gst</c>, <c>jp_cn</c>, <c>jp_rn</c>, /// <c>kr_brn</c>, <c>li_uid</c>, <c>mx_rfc</c>, <c>my_frp</c>, <c>my_itn</c>, /// <c>my_sst</c>, <c>no_vat</c>, <c>nz_gst</c>, <c>ru_inn</c>, <c>ru_kpp</c>, /// <c>sa_vat</c>, <c>sg_gst</c>, <c>sg_uen</c>, <c>th_vat</c>, <c>tw_vat</c>, /// <c>us_ein</c>, or <c>za_vat</c>. /// </summary> [JsonProperty("type")] public string Type { get; set; } /// <summary> /// Value of the tax ID. /// </summary> [JsonProperty("value")] public string Value { get; set; } } }
48.088235
100
0.487462
[ "Apache-2.0" ]
GigiAkamala/stripe-dotnet
src/Stripe.net/Services/Invoices/InvoiceCustomerDetailsTaxIdOptions.cs
1,635
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using MessageManager.Key; using Microsoft.Azure.ServiceBus; using Microsoft.Azure.ServiceBus.Core; namespace MessageManager { public class DeleterArguments : CommandArguments { public bool Dead { get; set; } public string Id { get; set; } } public class Deleter : SbsCommand { public Deleter(string connectionString, DeleterArguments a) : base(connectionString, GetEntityPath(a.Type, a.TopicQueueName, a.Name, a.Dead)) { } public async Task Execute(string id, bool force) { if (string.IsNullOrEmpty(id) && !force) { Console.WriteLine($"No id specified. Use --force if you intend to delete all messages"); } var tokens = await ReceiveMessages(id); var tasks = tokens .Select(t => Receiver.AbandonAsync(t)); await Task.WhenAll(tasks); } private async Task<IEnumerable<string>> ReceiveMessages(string id) { var lockTokens = new List<string>(); Message message; do { message = await Receiver.ReceiveAsync(TimeSpan.FromSeconds(5)); if (message == null) { Console.WriteLine($"Message with id {id} was not found"); break; } if (string.IsNullOrEmpty(id) || message.MessageId == id) { await Receiver.CompleteAsync(message.SystemProperties.LockToken); Console.WriteLine($"Message with id {message.MessageId} was removed"); } lockTokens.Add(message.SystemProperties.LockToken); } while (message != null); return lockTokens; } } }
33.316667
104
0.541271
[ "MIT" ]
thonhotels/message-manager
src/Deleter.cs
1,999
C#
//------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion: 4.0.30319.42000 // // Änderungen an dieser Datei können fehlerhaftes Verhalten verursachen und gehen verloren, wenn // der Code neu generiert wird. // </auto-generated> //------------------------------------------------------------------------------ namespace Wows_Ballistic_Tool_GUI.Properties { /// <summary> /// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw. /// </summary> // Diese Klasse wurde von der StronglyTypedResourceBuilder-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 Option /str erneut aus, oder erstellen Sie 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 ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Wows_Ballistic_Tool_GUI.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle /// Ressourcenlookups, 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; } } } }
41.569444
189
0.628466
[ "MIT" ]
wyx227/Wows_Ballistic_Tool
Wows_Ballistic_Tool_GUI/Properties/Resources.Designer.cs
3,003
C#
// Copyright (c) Giovanni Lafratta. All rights reserved. // Licensed under the MIT license. // See the LICENSE file in the project root for more information. using Novacta.Analytics.Tests.TestableItems.Matrices; using Novacta.Analytics.Tests.Tools; namespace Novacta.Analytics.Tests.TestableItems.Kurtosis { /// <summary> /// Represents a testable kurtosis which summarizes /// all row items in the matrix represented by <see cref="TestableDoubleMatrix42"/>. /// </summary> class OnRowsNotAdjustedKurtosis02 : AlongDimensionKurtosis<DoubleMatrixState> { protected OnRowsNotAdjustedKurtosis02() : base( expected: new DoubleMatrixState( asColumnMajorDenseArray: new double[4] { double.NaN, double.NaN, double.NaN, double.NaN }, numberOfRows: 4, numberOfColumns: 1 ), data: TestableDoubleMatrix42.Get(), adjustForBias: false, dataOperation: DataOperation.OnRows ) { } /// <summary> /// Gets an instance of the <see cref="OnRowsNotAdjustedKurtosis02"/> class. /// </summary> /// <returns>An instance of the /// <see cref="OnRowsNotAdjustedKurtosis02"/> class.</returns> public static OnRowsNotAdjustedKurtosis02 Get() { return new OnRowsNotAdjustedKurtosis02(); } } }
36.595238
93
0.587508
[ "MIT" ]
Novacta/analytics
tests/Novacta.Analytics.Tests/TestableItems/Kurtosis/OnRowsNotAdjustedKurtosis02.cs
1,539
C#
using System; namespace NewLife.Caching.Models { /// <summary>Redis队列状态</summary> public class RedisQueueStatus { /// <summary>标识消费者的唯一Key</summary> public String Key { get; set; } /// <summary>机器名</summary> public String MachineName { get; set; } /// <summary>用户名</summary> public String UserName { get; set; } /// <summary>进程</summary> public Int32 ProcessId { get; set; } /// <summary>IP地址</summary> public String Ip { get; set; } /// <summary>开始时间</summary> public DateTime CreateTime { get; set; } /// <summary>最后活跃时间</summary> public DateTime LastActive { get; set; } /// <summary>消费消息数</summary> public Int64 Consumes { get; set; } /// <summary>确认消息数</summary> public Int64 Acks { get; set; } } }
24.942857
48
0.557847
[ "MIT" ]
BillSon68/NewLife.Redis
NewLife.Redis/Models/RedisQueueStatus.cs
959
C#
namespace Cloudtoid.UrlPattern { internal abstract class PatternValidatorBase : PatternNodeVisitor { internal void Validate(PatternNode pattern) => Visit(pattern); } }
23.625
70
0.724868
[ "MIT" ]
cloudtoid/url-pattern
src/Cloudtoid.UrlPattern/Validators/PatternValidatorBase.cs
191
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Automation; using System.Windows.Automation.Peers; using System.Windows.Controls.Primitives; using System.Windows.Media; using Xwt.Accessibility; using Xwt.Backends; namespace Xwt.WPFBackend { class AccessibleBackend : IAccessibleBackend { UIElement element; IAccessibleEventSink eventSink; ApplicationContext context; public bool IsAccessible { get; set; } private string identifier; public string Identifier { get { return AutomationProperties.GetAutomationId (element); } set { identifier = value; AutomationProperties.SetAutomationId (element, value); } } private string label; public string Label { get { return AutomationProperties.GetName (element); } set { label = value; AutomationProperties.SetName (element, value); } } private string description; public string Description { get { return AutomationProperties.GetHelpText (element); } set { description = value; AutomationProperties.SetHelpText (element, value); } } private Widget labelWidget; public Widget LabelWidget { set { labelWidget = value; AutomationProperties.SetLabeledBy (element, (Toolkit.GetBackend (value) as WidgetBackend)?.Widget); } } /// <summary> /// In some cases (just Popovers currently) we need to wait to set the automation properties until the element /// that needs them comes into existence (a PopoverRoot in the case of a Popover, when it's shown). This is /// used for that delayed initialization. /// </summary> /// <param name="element">UIElement on which to set the properties</param> public void InitAutomationProperties (UIElement element) { if (identifier != null) AutomationProperties.SetAutomationId (element, identifier); if (label != null) AutomationProperties.SetName (element, label); if (description != null) AutomationProperties.SetHelpText (element, description); if (labelWidget != null) AutomationProperties.SetLabeledBy (element, (Toolkit.GetBackend (labelWidget) as WidgetBackend)?.Widget); } public string Title { get; set; } public string Value { get; set; } public Role Role { get; set; } = Role.Custom; public Uri Uri { get; set; } public Rectangle Bounds { get; set; } public string RoleDescription { get; set; } public void DisableEvent (object eventId) { } public void EnableEvent (object eventId) { } public void Initialize (IWidgetBackend parentWidget, IAccessibleEventSink eventSink) { Initialize (parentWidget.NativeWidget, eventSink); var wpfBackend = parentWidget as WidgetBackend; if (wpfBackend != null) wpfBackend.HasAccessibleObject = true; } public void Initialize (IPopoverBackend parentPopover, IAccessibleEventSink eventSink) { var popoverBackend = (PopoverBackend) parentPopover; Popup popup = popoverBackend.NativeWidget; Initialize (popup, eventSink); } public void Initialize (object parentWidget, IAccessibleEventSink eventSink) { this.element = parentWidget as UIElement; if (element == null) throw new ArgumentException ("Widget is not a UIElement"); this.eventSink = eventSink; } public void InitializeBackend (object frontend, ApplicationContext context) { this.context = context; } internal void PerformInvoke () { context.InvokeUserCode (() => eventSink.OnPress ()); } // The following child methods are only supported for Canvas based widgets public void AddChild (object nativeChild) { var peer = nativeChild as AutomationPeer; var canvas = element as CustomCanvas; if (peer != null && canvas != null) canvas.AutomationPeer?.AddChild (peer); } public void RemoveAllChildren () { var canvas = element as CustomCanvas; if (canvas != null) canvas.AutomationPeer?.RemoveAllChildren (); } public void RemoveChild (object nativeChild) { var peer = nativeChild as AutomationPeer; var canvas = element as CustomCanvas; if (peer != null && canvas != null) canvas.AutomationPeer?.RemoveChild (peer); } public static AutomationControlType RoleToControlType (Role role) { switch (role) { case Role.Button: case Role.MenuButton: case Role.ToggleButton: return AutomationControlType.Button; case Role.CheckBox: return AutomationControlType.CheckBox; case Role.RadioButton: return AutomationControlType.RadioButton; case Role.RadioGroup: return AutomationControlType.Group; case Role.ComboBox: return AutomationControlType.ComboBox; case Role.List: return AutomationControlType.List; case Role.Popup: case Role.ToolTip: return AutomationControlType.ToolTip; case Role.ToolBar: return AutomationControlType.ToolBar; case Role.Label: return AutomationControlType.Text; case Role.Link: return AutomationControlType.Hyperlink; case Role.Image: return AutomationControlType.Image; case Role.Cell: return AutomationControlType.DataItem; case Role.Table: return AutomationControlType.DataGrid; case Role.Paned: return AutomationControlType.Pane; default: return AutomationControlType.Custom; } } } }
28.164894
112
0.727668
[ "MIT" ]
hamekoz/xwt
Xwt.WPF/Xwt.WPFBackend/AccessibleBackend.cs
5,295
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("Microsoft.OfficeProPlus.MSIGen")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Microsoft.OfficeProPlus.MSIGen")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("693423bb-aac9-4156-963c-642f76072e1c")] // 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.5.0.0")] [assembly: AssemblyFileVersion("1.5.0.0")]
38.72973
84
0.748779
[ "MIT" ]
Draeniky/Office-IT-Pro-Deployment-Scripts
Office-ProPlus-Deployment/Microsoft.ProPlus.InstallGenerator/Microsoft.OfficeProPlus.MSIGenerator/Properties/AssemblyInfo.cs
1,436
C#
// Decompiled with JetBrains decompiler // Type: VirusTotalNET.Objects.DetectedUrl // Assembly: VirusTotal.NET, Version=1.3.1.0, Culture=neutral, PublicKeyToken=null // MVID: 2B160AD8-F9AD-46F3-A2B1-F9B9E38BD041 // Assembly location: D:\repository\repo\vs2015\Security\FIDO.Threatfeeds\FIDO.Threatfeeds\packages\VirusTotal.NET.1.3.1.0\lib\VirusTotal.NET.dll using System; namespace FIDO.Threatfeeds.FIDO.Support.VirusTotal.NET { public class DetectedUrl { public string Url { get; set; } public int Positives { get; set; } public int Total { get; set; } public DateTime ScanDate { get; set; } } }
28.409091
145
0.7376
[ "Apache-2.0" ]
robfry/crucyble-csharp-micro-threatfeeds
FIDO.Threatfeeds/FIDO.Threatfeeds/FIDO.Support/VirusTotal.NET/DetectedUrl.cs
627
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.CSharp; namespace Microsoft.VisualStudio.ProjectSystem.LanguageServices.CSharp { [Export(typeof(ICommandLineParserService))] [AppliesTo(ProjectCapability.CSharp)] internal class CSharpCommandLineParserService : ICommandLineParserService { public BuildOptions Parse(IEnumerable<string> arguments, string baseDirectory) { Requires.NotNull(arguments, nameof(arguments)); Requires.NotNullOrEmpty(baseDirectory, nameof(baseDirectory)); return BuildOptions.FromCommandLineArguments( CSharpCommandLineParser.Default.Parse(arguments, baseDirectory, sdkDirectory: null, additionalReferenceDirectories: null)); } } }
43.217391
162
0.737425
[ "Apache-2.0" ]
MSLukeWest/project-system
src/Microsoft.VisualStudio.ProjectSystem.Managed/ProjectSystem/LanguageServices/CSharp/CSharpCommandLineParserService.cs
974
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; public class StartUp { private static void Main(string[] args) { Type boxType = typeof(Box); FieldInfo[] fields = boxType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance); Console.WriteLine(fields.Count()); var param = new List<double>(); for (int i = 0; i < 3; i++) { var input = double.Parse(Console.ReadLine()); param.Add(input); } var box = new Box(param[0], param[1], param[2]); Console.WriteLine($"Surface Area - {box.SurfaceArea():F2}"); Console.WriteLine($"Lateral Surface Area - {box.LateralSurfaceArea():F2}"); Console.WriteLine($"Volume - {box.Volume():F2}"); } }
27.793103
95
0.602978
[ "MIT" ]
Hellsflash/Databases-Advanced
OOP Introduction/Encapsulation and Validation Exercises/Class Box/StartUp.cs
808
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Composition; using System.Threading.Tasks; using StarkPlatform.CodeAnalysis.Host; using StarkPlatform.CodeAnalysis.Host.Mef; using Roslyn.Utilities; namespace StarkPlatform.CodeAnalysis.SymbolSearch { internal interface ISymbolSearchProgressService : IWorkspaceService { Task OnDownloadFullDatabaseStartedAsync(string title); Task OnDownloadFullDatabaseSucceededAsync(); Task OnDownloadFullDatabaseCanceledAsync(); Task OnDownloadFullDatabaseFailedAsync(string message); } [ExportWorkspaceService(typeof(ISymbolSearchProgressService)), Shared] internal class DefaultSymbolSearchProgressService : ISymbolSearchProgressService { public Task OnDownloadFullDatabaseStartedAsync(string title) => Task.CompletedTask; public Task OnDownloadFullDatabaseSucceededAsync() => Task.CompletedTask; public Task OnDownloadFullDatabaseCanceledAsync() => Task.CompletedTask; public Task OnDownloadFullDatabaseFailedAsync(string message) => Task.CompletedTask; } }
41.066667
161
0.784091
[ "Apache-2.0" ]
stark-lang/stark-roslyn
src/Workspaces/Core/Portable/SymbolSearch/ISymbolSearchProgressService.cs
1,234
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WhileIteration { class Program { static void Main(string[] args) { bool displayMenu = true; while (displayMenu) { displayMenu = MainMenu(); } } private static bool MainMenu() { Console.Clear(); Console.WriteLine("Choose a valid option:"); Console.WriteLine("1) Print Numbers"); Console.WriteLine("2) Guessing random numbers game"); Console.WriteLine("3) Exit"); Console.WriteLine(""); string result = Console.ReadLine(); if (result == "1") { PrintNumbers(); return true; } else if (result == "2") { GuessingGame(); return true; } else if (result == "3") { Console.WriteLine("Bye bye."); return false; } else { OtherKeyPressed(); return true; } } private static void GuessingGame() { Console.Clear(); Console.WriteLine("Guessing numbers from a \"dozen\" game! \"Hope you enjoy!\""); Random myRandom = new Random(); int randomNumber = myRandom.Next(1, 13); int guesses = 0; bool incorrect = true; do { Console.WriteLine("Guess a number between 1 and 12: "); string result = Console.ReadLine(); guesses++; if (result == randomNumber.ToString()) incorrect = false; else Console.WriteLine("You have chosen POORLY....."); } while (incorrect); Console.WriteLine("You have choosen WISELY! It took you {0} guesses.", guesses); Console.WriteLine("Press 'return' or 'enter' key to continue."); Console.ReadLine(); } private static void PrintNumbers() { Console.Clear(); Console.WriteLine("Print numbers!"); Console.Write("Type a number. Any number: "); int result = int.Parse(Console.ReadLine()); int counter = 0; while (counter < result + 1) { Console.Write(counter); Console.Write("-"); counter++; } Console.ReadLine(); } private static void OtherKeyPressed() { Console.Clear(); Console.WriteLine("Oh no.....Looks like you didn't type 1, 2, or 3."); Console.ReadLine(); } } }
29.466667
97
0.436005
[ "MIT" ]
castillocarlosr/test-cSharp-project
WhileIteration/WhileIteration/Program.cs
3,096
C#
namespace OnlyT.Services.Monitors { using System.Collections.Generic; using Models; public interface IMonitorsService { IEnumerable<MonitorItem> GetSystemMonitors(); MonitorItem GetMonitorItem(string monitorId); } }
19.615385
53
0.705882
[ "MIT" ]
Vikingo80/OnlyT
OnlyT/Services/Monitors/IMonitorsService.cs
257
C#
using Example.Shared.Core.Models; namespace Example.App.Shared.Models.View.Contact { public class AddressModel : IId { public int Id { get; set; } public string AddressInfo { get; set; } public decimal Latitude { get; set; } public decimal Longitude { get; set; } public int ContactId { get; set; } public ContactModel Contact { get; set; } } }
27.133333
49
0.619165
[ "MIT" ]
TinusHeystek/aspnet-core-web-app
Projects/Example.App.Shared/Models/View/Contact/AddressModel.cs
409
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; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.Test.Common; using Moq; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using Xunit; namespace Microsoft.AspNetCore.Razor.LanguageServer { public class DefaultRazorConfigurationServiceTest : LanguageServerTestBase { [Fact] public async Task GetLatestOptionsAsync_ReturnsExpectedOptions() { // Arrange var expectedOptions = new RazorLSPOptions(Trace.Messages, enableFormatting: false, autoClosingTags: false); var razorJsonString = @" { ""trace"": ""Messages"", ""format"": { ""enable"": ""false"" } } ".Trim(); var htmlJsonString = @" { ""format"": ""true"", ""autoClosingTags"": ""false"" } ".Trim(); var result = new JObject[] { JObject.Parse(razorJsonString), JObject.Parse(htmlJsonString) }; var languageServer = GetLanguageServer(new ResponseRouterReturns(result)); var configurationService = new DefaultRazorConfigurationService(languageServer, LoggerFactory); // Act var options = await configurationService.GetLatestOptionsAsync(CancellationToken.None); // Assert Assert.Equal(expectedOptions, options); } [Fact] public async Task GetLatestOptionsAsync_EmptyResponse_ReturnsNull() { // Arrange var languageServer = GetLanguageServer(result: null); var configurationService = new DefaultRazorConfigurationService(languageServer, LoggerFactory); // Act var options = await configurationService.GetLatestOptionsAsync(CancellationToken.None); // Assert Assert.Null(options); } [Fact] public async Task GetLatestOptionsAsync_ClientRequestThrows_ReturnsNull() { // Arrange var languageServer = GetLanguageServer(result: null, shouldThrow: true); var configurationService = new DefaultRazorConfigurationService(languageServer, LoggerFactory); // Act var options = await configurationService.GetLatestOptionsAsync(CancellationToken.None); // Assert Assert.Null(options); } private ClientNotifierServiceBase GetLanguageServer(IResponseRouterReturns result, bool shouldThrow = false) { var languageServer = new Mock<ClientNotifierServiceBase>(MockBehavior.Strict); if (shouldThrow) { } else { languageServer .Setup(l => l.SendRequestAsync("workspace/configuration", It.IsAny<ConfigurationParams>())) .Returns(Task.FromResult(result)); } return languageServer.Object; } private class ResponseRouterReturns : IResponseRouterReturns { private object _result; public ResponseRouterReturns(object result) { _result = result; } public Task<Response> Returning<Response>(CancellationToken cancellationToken) { return Task.FromResult((Response)_result); } public Task ReturningVoid(CancellationToken cancellationToken) { return Task.CompletedTask; } } } }
32.875
119
0.629006
[ "Apache-2.0" ]
Chatina73/AspNetCore-Tooling
src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DefaultRazorConfigurationServiceTest.cs
3,684
C#
using System; using Temporal.Util; using Temporal.Api.Common.V1; namespace Temporal.Serialization { public class VoidPayloadConverter : IPayloadConverter { public bool TryDeserialize<T>(Payloads serializedData, out T item) { // Check: `serializedData` is not null // AND `serializedData` has ZERO payload entries // AND `T` represents the `IPayload.Void` type: if (serializedData != null && SerializationUtil.GetPayloadCount(serializedData) == 0 && typeof(T) == typeof(Temporal.Common.IPayload.Void)) { item = Temporal.Common.Payload.Void.Cast<Temporal.Common.IPayload.Void, T>(); return true; } item = default(T); return false; } public bool TrySerialize<T>(T item, Payloads serializedDataAccumulator) { // If the specified `item` is `IPayload.Void`, then perform the serialization, // but the serialization does not actually generate a payload entry. if (item != null && item is Temporal.Common.IPayload.Void) { return true; } return false; } public override bool Equals(object obj) { return Object.ReferenceEquals(this, obj) || ((obj != null) && this.GetType().Equals(obj.GetType())); } public override int GetHashCode() { return base.GetHashCode(); } } }
30.705882
112
0.556194
[ "Apache-2.0" ]
macrogreg/sdk-dotnet
Src/SDK/Common/Temporal.Serialization/public/VoidPayloadConverter.cs
1,568
C#
using Newtonsoft.Json; using System.Collections.Generic; namespace HealthChecks.UI.Core.Discovery.K8S { internal class ServiceList { [JsonProperty("items")] public Service[] Items { get; set; } = new Service[] { }; } internal class Service { public Metadata Metadata { get; set; } public Status Status { get; set; } public Spec Spec { get; set; } } internal class Metadata { public string Name { get; set; } public string Namespace { get; set; } public string Uid { get; set; } } internal class LoadBalancer { public Ingress[] Ingress { get; set; } } internal class Status { public LoadBalancer LoadBalancer { get; set; } } internal class Ingress { public string Ip { get; set; } public string HostName { get; set; } } internal class Spec { public List<Port> Ports { get; set; } [JsonProperty("type")] public PortType PortType { get; set; } public string ClusterIP { get; set; } } internal class Port { public string Protocol { get; set; } [JsonProperty("Port")] public int PortNumber { get; set; } public int NodePort { get; set; } public int TargetPort { get; set; } } }
26.192308
65
0.559471
[ "Apache-2.0" ]
FurstLevy/AspNetCore.Diagnostics.HealthChecks
src/HealthChecks.UI/Core/Discovery/K8S/KubernetesResponses.cs
1,364
C#
// MonoGame - Copyright (C) The MonoGame Team // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. using System; using Microsoft.Xna.Framework.Graphics; using Windows.UI.Xaml.Controls; namespace Microsoft.Xna.Framework { partial class GraphicsDeviceManager { [CLSCompliant(false)] public SwapChainPanel SwapChainPanel { get; set; } partial void PlatformPreparePresentationParameters(PresentationParameters presentationParameters) { // The graphics device can use a XAML panel or a window // to created the default swapchain target. if (SwapChainPanel != null) { presentationParameters.DeviceWindowHandle = IntPtr.Zero; presentationParameters.SwapChainPanel = this.SwapChainPanel; } else { presentationParameters.DeviceWindowHandle = _game.Window.Handle; presentationParameters.SwapChainPanel = null; } } partial void PlatformApplyChanges() { ((UAPGameWindow)_game.Window).SetClientSize(_preferredBackBufferWidth, _preferredBackBufferHeight); } } }
32.74359
111
0.65231
[ "MIT" ]
06needhamt/MonoGame
MonoGame.Framework/Platform/GraphicsDeviceManager.WinRT.cs
1,277
C#
// Copyright 2022 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Billing.V1.Snippets { // [START cloudbilling_v1_generated_CloudBilling_SetIamPolicy_async_flattened] using Google.Cloud.Billing.V1; using Google.Cloud.Iam.V1; using System.Threading.Tasks; public sealed partial class GeneratedCloudBillingClientSnippets { /// <summary>Snippet for SetIamPolicyAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task SetIamPolicyAsync() { // Create client CloudBillingClient cloudBillingClient = await CloudBillingClient.CreateAsync(); // Initialize request argument(s) string resource = "a/wildcard/resource"; Policy policy = new Policy(); // Make the request Policy response = await cloudBillingClient.SetIamPolicyAsync(resource, policy); } } // [END cloudbilling_v1_generated_CloudBilling_SetIamPolicy_async_flattened] }
39.363636
91
0.700924
[ "Apache-2.0" ]
AlexandrTrf/google-cloud-dotnet
apis/Google.Cloud.Billing.V1/Google.Cloud.Billing.V1.GeneratedSnippets/CloudBillingClient.SetIamPolicyAsyncSnippet.g.cs
1,732
C#
using J2N; using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using JCG = J2N.Collections.Generic; /* * dk.brics.automaton * * Copyright (c) 2001-2009 Anders Moeller * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * this SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */ namespace Lucene.Net.Util.Automaton { /// <summary> /// Finite-state automaton with regular expression operations. /// <para/> /// Class invariants: /// <list type="bullet"> /// <item><description>An automaton is either represented explicitly (with <see cref="State"/> and /// <see cref="Transition"/> objects) or with a singleton string (see /// <see cref="Singleton"/> and <see cref="ExpandSingleton()"/>) in case the automaton /// is known to accept exactly one string. (Implicitly, all states and /// transitions of an automaton are reachable from its initial state.)</description></item> /// <item><description>Automata are always reduced (see <see cref="Reduce()"/>) and have no /// transitions to dead states (see <see cref="RemoveDeadTransitions()"/>).</description></item> /// <item><description>If an automaton is nondeterministic, then <see cref="IsDeterministic"/> /// returns <c>false</c> (but the converse is not required).</description></item> /// <item><description>Automata provided as input to operations are generally assumed to be /// disjoint.</description></item> /// </list> /// <para/> /// If the states or transitions are manipulated manually, the /// <see cref="RestoreInvariant()"/> method and <see cref="IsDeterministic"/> setter /// should be used afterwards to restore representation invariants that are /// assumed by the built-in automata operations. /// /// <para/> /// <para> /// Note: this class has internal mutable state and is not thread safe. It is /// the caller's responsibility to ensure any necessary synchronization if you /// wish to use the same Automaton from multiple threads. In general it is instead /// recommended to use a <see cref="RunAutomaton"/> for multithreaded matching: it is immutable, /// thread safe, and much faster. /// </para> /// @lucene.experimental /// </summary> public class Automaton #if FEATURE_CLONEABLE : System.ICloneable #endif { /// <summary> /// Minimize using Hopcroft's O(n log n) algorithm. this is regarded as one of /// the most generally efficient algorithms that exist. /// </summary> /// <seealso cref="SetMinimization(int)"/> public const int MINIMIZE_HOPCROFT = 2; /// <summary> /// Selects minimization algorithm (default: <c>MINIMIZE_HOPCROFT</c>). </summary> internal static int minimization = MINIMIZE_HOPCROFT; /// <summary> /// Initial state of this automaton. </summary> internal State initial; /// <summary> /// If <c>true</c>, then this automaton is definitely deterministic (i.e., there are /// no choices for any run, but a run may crash). /// </summary> internal bool deterministic; /// <summary> /// Extra data associated with this automaton. </summary> internal object info; ///// <summary> ///// Hash code. Recomputed by <see cref="MinimizationOperations#minimize(Automaton)"/> ///// </summary> //int hash_code; /// <summary> /// Singleton string. Null if not applicable. </summary> internal string singleton; /// <summary> /// Minimize always flag. </summary> internal static bool minimize_always = false; /// <summary> /// Selects whether operations may modify the input automata (default: /// <c>false</c>). /// </summary> internal static bool allow_mutation = false; /// <summary> /// Constructs a new automaton that accepts the empty language. Using this /// constructor, automata can be constructed manually from <see cref="State"/> and /// <see cref="Transition"/> objects. /// </summary> /// <seealso cref="State"/> /// <seealso cref="Transition"/> public Automaton(State initial) { this.initial = initial; deterministic = true; singleton = null; } public Automaton() : this(new State()) { } /// <summary> /// Selects minimization algorithm (default: <c>MINIMIZE_HOPCROFT</c>). /// </summary> /// <param name="algorithm"> minimization algorithm </param> public static void SetMinimization(int algorithm) { minimization = algorithm; } /// <summary> /// Sets or resets minimize always flag. If this flag is set, then /// <see cref="MinimizationOperations.Minimize(Automaton)"/> will automatically be /// invoked after all operations that otherwise may produce non-minimal /// automata. By default, the flag is not set. /// </summary> /// <param name="flag"> if <c>true</c>, the flag is set </param> public static void SetMinimizeAlways(bool flag) { minimize_always = flag; } /// <summary> /// Sets or resets allow mutate flag. If this flag is set, then all automata /// operations may modify automata given as input; otherwise, operations will /// always leave input automata languages unmodified. By default, the flag is /// not set. /// </summary> /// <param name="flag"> if <c>true</c>, the flag is set </param> /// <returns> previous value of the flag </returns> public static bool SetAllowMutate(bool flag) { bool b = allow_mutation; allow_mutation = flag; return b; } /// <summary> /// Returns the state of the allow mutate flag. If this flag is set, then all /// automata operations may modify automata given as input; otherwise, /// operations will always leave input automata languages unmodified. By /// default, the flag is not set. /// </summary> /// <returns> current value of the flag </returns> internal static bool AllowMutate { get { return allow_mutation; } } internal virtual void CheckMinimizeAlways() { if (minimize_always) { MinimizationOperations.Minimize(this); } } internal bool IsSingleton => singleton != null; /// <summary> /// Returns the singleton string for this automaton. An automaton that accepts /// exactly one string <i>may</i> be represented in singleton mode. In that /// case, this method may be used to obtain the string. /// </summary> /// <returns> String, <c>null</c> if this automaton is not in singleton mode. </returns> public virtual string Singleton => singleton; ///// <summary> ///// Sets initial state. ///// </summary> ///// <param name="s"> state </param> /* public void setInitialState(State s) { initial = s; singleton = null; } */ /// <summary> /// Gets initial state. /// </summary> /// <returns> state </returns> public virtual State GetInitialState() { ExpandSingleton(); return initial; } /// <summary> /// Returns deterministic flag for this automaton. /// </summary> /// <returns> <c>true</c> if the automaton is definitely deterministic, <c>false</c> if the /// automaton may be nondeterministic </returns> public virtual bool IsDeterministic { get => deterministic; set => deterministic = value; } /// <summary> /// Associates extra information with this automaton. /// </summary> /// <param name="value"> extra information </param> public virtual object Info { get => info; set => info = value; } // cached private State[] numberedStates; public virtual State[] GetNumberedStates() { if (numberedStates == null) { ExpandSingleton(); JCG.HashSet<State> visited = new JCG.HashSet<State>(); LinkedList<State> worklist = new LinkedList<State>(); State[] states = new State[4]; int upto = 0; worklist.AddLast(initial); visited.Add(initial); initial.number = upto; states[upto] = initial; upto++; while (worklist.Count > 0) { State s = worklist.First.Value; worklist.Remove(s); for (int i = 0; i < s.numTransitions; i++) { Transition t = s.TransitionsArray[i]; if (!visited.Contains(t.to)) { visited.Add(t.to); worklist.AddLast(t.to); t.to.number = upto; if (upto == states.Length) { State[] newArray = new State[ArrayUtil.Oversize(1 + upto, RamUsageEstimator.NUM_BYTES_OBJECT_REF)]; Array.Copy(states, 0, newArray, 0, upto); states = newArray; } states[upto] = t.to; upto++; } } } if (states.Length != upto) { State[] newArray = new State[upto]; Array.Copy(states, 0, newArray, 0, upto); states = newArray; } numberedStates = states; } return numberedStates; } public virtual void SetNumberedStates(State[] states) { SetNumberedStates(states, states.Length); } public virtual void SetNumberedStates(State[] states, int count) { Debug.Assert(count <= states.Length); // TODO: maybe we can eventually allow for oversizing here... if (count < states.Length) { State[] newArray = new State[count]; Array.Copy(states, 0, newArray, 0, count); numberedStates = newArray; } else { numberedStates = states; } } public virtual void ClearNumberedStates() { numberedStates = null; } /// <summary> /// Returns the set of reachable accept states. /// </summary> /// <returns> Set of <see cref="State"/> objects. </returns> public virtual ISet<State> GetAcceptStates() { ExpandSingleton(); JCG.HashSet<State> accepts = new JCG.HashSet<State>(); JCG.HashSet<State> visited = new JCG.HashSet<State>(); LinkedList<State> worklist = new LinkedList<State>(); worklist.AddLast(initial); visited.Add(initial); while (worklist.Count > 0) { State s = worklist.First.Value; worklist.Remove(s); if (s.accept) { accepts.Add(s); } foreach (Transition t in s.GetTransitions()) { if (!visited.Contains(t.to)) { visited.Add(t.to); worklist.AddLast(t.to); } } } return accepts; } /// <summary> /// Adds transitions to explicit crash state to ensure that transition function /// is total. /// </summary> internal virtual void Totalize() { State s = new State(); s.AddTransition(new Transition(Character.MinCodePoint, Character.MaxCodePoint, s)); foreach (State p in GetNumberedStates()) { int maxi = Character.MinCodePoint; p.SortTransitions(Transition.COMPARE_BY_MIN_MAX_THEN_DEST); foreach (Transition t in p.GetTransitions()) { if (t.min > maxi) { p.AddTransition(new Transition(maxi, (t.min - 1), s)); } if (t.max + 1 > maxi) { maxi = t.max + 1; } } if (maxi <= Character.MaxCodePoint) { p.AddTransition(new Transition(maxi, Character.MaxCodePoint, s)); } } ClearNumberedStates(); } /// <summary> /// Restores representation invariant. This method must be invoked before any /// built-in automata operation is performed if automaton states or transitions /// are manipulated manually. /// </summary> /// <seealso cref="IsDeterministic"/> public virtual void RestoreInvariant() { RemoveDeadTransitions(); } /// <summary> /// Reduces this automaton. An automaton is "reduced" by combining overlapping /// and adjacent edge intervals with same destination. /// </summary> public virtual void Reduce() { State[] states = GetNumberedStates(); if (IsSingleton) { return; } foreach (State s in states) { s.Reduce(); } } /// <summary> /// Returns sorted array of all interval start points. /// </summary> public virtual int[] GetStartPoints() { State[] states = GetNumberedStates(); JCG.HashSet<int> pointset = new JCG.HashSet<int>(); pointset.Add(Character.MinCodePoint); foreach (State s in states) { foreach (Transition t in s.GetTransitions()) { pointset.Add(t.min); if (t.max < Character.MaxCodePoint) { pointset.Add((t.max + 1)); } } } int[] points = new int[pointset.Count]; int n = 0; foreach (int m in pointset) { points[n++] = m; } Array.Sort(points); return points; } /// <summary> /// Returns the set of live states. A state is "live" if an accept state is /// reachable from it. /// </summary> /// <returns> Set of <see cref="State"/> objects. </returns> private State[] GetLiveStates() { State[] states = GetNumberedStates(); JCG.HashSet<State> live = new JCG.HashSet<State>(); foreach (State q in states) { if (q.Accept) { live.Add(q); } } // map<state, set<state>> ISet<State>[] map = new JCG.HashSet<State>[states.Length]; for (int i = 0; i < map.Length; i++) { map[i] = new JCG.HashSet<State>(); } foreach (State s in states) { for (int i = 0; i < s.numTransitions; i++) { map[s.TransitionsArray[i].to.Number].Add(s); } } LinkedList<State> worklist = new LinkedList<State>(live); while (worklist.Count > 0) { State s = worklist.First.Value; worklist.Remove(s); foreach (State p in map[s.number]) { if (!live.Contains(p)) { live.Add(p); worklist.AddLast(p); } } } return live.ToArray(/*new State[live.Count]*/); } /// <summary> /// Removes transitions to dead states and calls <see cref="Reduce()"/>. /// (A state is "dead" if no accept state is /// reachable from it.) /// </summary> public virtual void RemoveDeadTransitions() { State[] states = GetNumberedStates(); //clearHashCode(); if (IsSingleton) { return; } State[] live = GetLiveStates(); OpenBitSet liveSet = new OpenBitSet(states.Length); foreach (State s in live) { liveSet.Set(s.number); } foreach (State s in states) { // filter out transitions to dead states: int upto = 0; for (int i = 0; i < s.numTransitions; i++) { Transition t = s.TransitionsArray[i]; if (liveSet.Get(t.to.number)) { s.TransitionsArray[upto++] = s.TransitionsArray[i]; } } s.numTransitions = upto; } for (int i = 0; i < live.Length; i++) { live[i].number = i; } if (live.Length > 0) { SetNumberedStates(live); } else { // sneaky corner case -- if machine accepts no strings ClearNumberedStates(); } Reduce(); } /// <summary> /// Returns a sorted array of transitions for each state (and sets state /// numbers). /// </summary> public virtual Transition[][] GetSortedTransitions() { State[] states = GetNumberedStates(); Transition[][] transitions = new Transition[states.Length][]; foreach (State s in states) { s.SortTransitions(Transition.COMPARE_BY_MIN_MAX_THEN_DEST); s.TrimTransitionsArray(); transitions[s.number] = s.TransitionsArray; Debug.Assert(s.TransitionsArray != null); } return transitions; } /// <summary> /// Expands singleton representation to normal representation. Does nothing if /// not in singleton representation. /// </summary> public virtual void ExpandSingleton() { if (IsSingleton) { State p = new State(); initial = p; for (int i = 0, cp = 0; i < singleton.Length; i += Character.CharCount(cp)) { State q = new State(); p.AddTransition(new Transition(cp = Character.CodePointAt(singleton, i), q)); p = q; } p.accept = true; deterministic = true; singleton = null; } } /// <summary> /// Returns the number of states in this automaton. /// </summary> public virtual int GetNumberOfStates() { if (IsSingleton) { return singleton.CodePointCount(0, singleton.Length) + 1; } return GetNumberedStates().Length; } /// <summary> /// Returns the number of transitions in this automaton. This number is counted /// as the total number of edges, where one edge may be a character interval. /// </summary> public virtual int GetNumberOfTransitions() { if (IsSingleton) { return singleton.CodePointCount(0, singleton.Length); } int c = 0; foreach (State s in GetNumberedStates()) { c += s.NumTransitions; } return c; } public override bool Equals(object obj) { var other = obj as Automaton; return BasicOperations.SameLanguage(this, other); //throw new System.NotSupportedException("use BasicOperations.sameLanguage instead"); } // LUCENENET specific - in .NET, we can't simply throw an exception here because // collections use this to determine equality. Most of this code was pieced together from // BasicOperations.SubSetOf (which, when done both ways determines equality). public override int GetHashCode() { if (IsSingleton) { return singleton.GetHashCode(); } int hash = 31; // arbitrary prime this.Determinize(); // LUCENENET: should we do this ? Transition[][] transitions = this.GetSortedTransitions(); LinkedList<State> worklist = new LinkedList<State>(); JCG.HashSet<State> visited = new JCG.HashSet<State>(); State current = this.initial; worklist.AddLast(this.initial); visited.Add(this.initial); while (worklist.Count > 0) { current = worklist.First.Value; worklist.Remove(current); hash = 31 * hash + current.accept.GetHashCode(); Transition[] t1 = transitions[current.number]; for (int n1 = 0; n1 < t1.Length; n1++) { int min1 = t1[n1].min, max1 = t1[n1].max; hash = 31 * hash + min1.GetHashCode(); hash = 31 * hash + max1.GetHashCode(); State next = t1[n1].to; if (!visited.Contains(next)) { worklist.AddLast(next); visited.Add(next); } } } return hash; //throw new System.NotSupportedException(); } ///// <summary> ///// Must be invoked when the stored hash code may no longer be valid. ///// </summary> /* void clearHashCode() { hash_code = 0; } */ /// <summary> /// Returns a string representation of this automaton. /// </summary> public override string ToString() { StringBuilder b = new StringBuilder(); if (IsSingleton) { b.Append("singleton: "); int length = singleton.CodePointCount(0, singleton.Length); int[] codepoints = new int[length]; for (int i = 0, j = 0, cp = 0; i < singleton.Length; i += Character.CharCount(cp)) { codepoints[j++] = cp = singleton.CodePointAt(i); } foreach (int c in codepoints) { Transition.AppendCharString(c, b); } b.Append("\n"); } else { State[] states = GetNumberedStates(); b.Append("initial state: ").Append(initial.number).Append("\n"); foreach (State s in states) { b.Append(s.ToString()); } } return b.ToString(); } /// <summary> /// Returns <a href="http://www.research.att.com/sw/tools/graphviz/" /// target="_top">Graphviz Dot</a> representation of this automaton. /// </summary> public virtual string ToDot() { StringBuilder b = new StringBuilder("digraph Automaton {\n"); b.Append(" rankdir = LR;\n"); State[] states = GetNumberedStates(); foreach (State s in states) { b.Append(" ").Append(s.number); if (s.accept) { b.Append(" [shape=doublecircle,label=\"\"];\n"); } else { b.Append(" [shape=circle,label=\"\"];\n"); } if (s == initial) { b.Append(" initial [shape=plaintext,label=\"\"];\n"); b.Append(" initial -> ").Append(s.number).Append("\n"); } foreach (Transition t in s.GetTransitions()) { b.Append(" ").Append(s.number); t.AppendDot(b); } } return b.Append("}\n").ToString(); } /// <summary> /// Returns a clone of this automaton, expands if singleton. /// </summary> internal virtual Automaton CloneExpanded() { Automaton a = (Automaton)Clone(); a.ExpandSingleton(); return a; } /// <summary> /// Returns a clone of this automaton unless <see cref="allow_mutation"/> is /// set, expands if singleton. /// </summary> internal virtual Automaton CloneExpandedIfRequired() { if (allow_mutation) { ExpandSingleton(); return this; } else { return CloneExpanded(); } } /// <summary> /// Returns a clone of this automaton. /// </summary> public virtual object Clone() { Automaton a = (Automaton)base.MemberwiseClone(); if (!IsSingleton) { Dictionary<State, State> m = new Dictionary<State, State>(); State[] states = GetNumberedStates(); foreach (State s in states) { m[s] = new State(); } foreach (State s in states) { State p = m[s]; p.accept = s.accept; if (s == initial) { a.initial = p; } foreach (Transition t in s.GetTransitions()) { p.AddTransition(new Transition(t.min, t.max, m[t.to])); } } } a.ClearNumberedStates(); return a; } /// <summary> /// Returns a clone of this automaton, or this automaton itself if /// <see cref="allow_mutation"/> flag is set. /// </summary> internal virtual Automaton CloneIfRequired() { if (allow_mutation) { return this; } else { return (Automaton)Clone(); } } /// <summary> /// See <see cref="BasicOperations.Concatenate(Automaton, Automaton)"/>. /// </summary> public virtual Automaton Concatenate(Automaton a) { return BasicOperations.Concatenate(this, a); } /// <summary> /// See <see cref="BasicOperations.Concatenate(IList{Automaton})"/>. /// </summary> public static Automaton Concatenate(IList<Automaton> l) { return BasicOperations.Concatenate(l); } /// <summary> /// See <see cref="BasicOperations.Optional(Automaton)"/>. /// </summary> public virtual Automaton Optional() { return BasicOperations.Optional(this); } /// <summary> /// See <see cref="BasicOperations.Repeat(Automaton)"/>. /// </summary> public virtual Automaton Repeat() { return BasicOperations.Repeat(this); } /// <summary> /// See <see cref="BasicOperations.Repeat(Automaton, int)"/>. /// </summary> public virtual Automaton Repeat(int min) { return BasicOperations.Repeat(this, min); } /// <summary> /// See <see cref="BasicOperations.Repeat(Automaton, int, int)"/>. /// </summary> public virtual Automaton Repeat(int min, int max) { return BasicOperations.Repeat(this, min, max); } /// <summary> /// See <see cref="BasicOperations.Complement(Automaton)"/>. /// </summary> public virtual Automaton Complement() { return BasicOperations.Complement(this); } /// <summary> /// See <see cref="BasicOperations.Minus(Automaton, Automaton)"/>. /// </summary> public virtual Automaton Minus(Automaton a) { return BasicOperations.Minus(this, a); } /// <summary> /// See <see cref="BasicOperations.Intersection(Automaton, Automaton)"/>. /// </summary> public virtual Automaton Intersection(Automaton a) { return BasicOperations.Intersection(this, a); } /// <summary> /// See <see cref="BasicOperations.SubsetOf(Automaton, Automaton)"/>. /// </summary> public virtual bool SubsetOf(Automaton a) { return BasicOperations.SubsetOf(this, a); } /// <summary> /// See <see cref="BasicOperations.Union(Automaton, Automaton)"/>. /// </summary> public virtual Automaton Union(Automaton a) { return BasicOperations.Union(this, a); } /// <summary> /// See <see cref="BasicOperations.Union(ICollection{Automaton})"/>. /// </summary> public static Automaton Union(ICollection<Automaton> l) { return BasicOperations.Union(l); } /// <summary> /// See <see cref="BasicOperations.Determinize(Automaton)"/>. /// </summary> public virtual void Determinize() { BasicOperations.Determinize(this); } /// <summary> /// See <see cref="BasicOperations.IsEmptyString(Automaton)"/>. /// </summary> public virtual bool IsEmptyString { get { return BasicOperations.IsEmptyString(this); } } /// <summary> /// See <see cref="MinimizationOperations.Minimize(Automaton)"/>. Returns the /// automaton being given as argument. /// </summary> public static Automaton Minimize(Automaton a) { MinimizationOperations.Minimize(a); return a; } } }
34.582545
131
0.49997
[ "Apache-2.0" ]
bongohrtech/lucenenet
src/Lucene.Net/Util/Automaton/Automaton.cs
32,888
C#
using System; using System.Collections; using System.Collections.Generic; using Xunit; namespace Guidelines.RestApi.Collections.Filtering { public sealed class FilterCompilerTests { [Theory] [ClassData(typeof(CorrectInputTestData))] public void ShouldCompileWhenInputIsCorrect(string input, Item _, bool __) { // arrange // act var actual = FilterCompiler.Compile<Item>(input); // assert Assert.NotNull(actual); } [Theory] [ClassData(typeof(CorrectInputTestData))] public void ShouldTryCompileWhenInputIsCorrect(string input, Item _, bool __) { // arrange // act var actual = FilterCompiler.TryCompile<Item>(input, out var acutalFilter, out var actualError); // assert Assert.True(actual); Assert.NotNull(acutalFilter); Assert.Null(actualError); } [Theory] [ClassData(typeof(InvalidInputTestData))] public void TryCompileShouldReturnErrorWhenInputIsInvalid(string input, Item _, bool __) { // arrange // act var actual = FilterCompiler.TryCompile<Item>(input, out var acutalFilter, out var actualError); // assert Assert.False(actual); Assert.Null(acutalFilter); Assert.NotNull(actualError); } [Theory] [ClassData(typeof(CorrectInputTestData))] public void ShouldFilterWhenInputIsCorrectStatement(string input, Item item, bool expected) { // arrange var filterExpression = FilterParser.Parse<Item>(input); var filter = filterExpression.Compile(); // act var actual = filter(item); // assert Assert.Equal(expected, actual); } private sealed class CorrectInputTestData : IEnumerable<object[]> { public IEnumerator<object[]> GetEnumerator() { yield return new object[] { "Id eq 5", new Item { Id = 5 }, true }; yield return new object[] { "not Id eq 5", new Item { Id = 5 }, false }; yield return new object[] { "Value eq 5.0", new Item { Value = 5 }, true }; yield return new object[] { "Value eq 5", new Item { Value = 5 }, true }; yield return new object[] { "Value eq null", new Item { Value = 5 }, false }; yield return new object[] { "Value eq null", new Item { }, true }; yield return new object[] { "IsEnabled eq true", new Item { IsEnabled = true }, true }; yield return new object[] { "not IsEnabled eq false", new Item { IsEnabled = true }, true }; yield return new object[] { "Timestamp eq 2019-01-29", new Item { Timestamp = new DateTime(2019, 1, 29) }, true }; yield return new object[] { "Timestamp gt 2019-01-29T01:00:00", new Item { Timestamp = new DateTime(2019, 1, 29, 1, 30, 40) }, true }; yield return new object[] { "Title eq 'Some Title'", new Item { Title = "Some Title" }, true }; yield return new object[] { "contains(Title, 'Title')", new Item { Title = "Some Title" }, true }; yield return new object[] { "endswith(Title, 'Title')", new Item { Title = "Some Title" }, true }; yield return new object[] { "startswith(Title, 'Some')", new Item { Title = "Some Title" }, true }; yield return new object[] { "length(Title) eq 10", new Item { Title = "Some Title" }, true }; yield return new object[] { "Title in ('Some', 'Title')", new Item { Title = "Title" }, true }; yield return new object[] { "not indexof(Title, 'Tit') eq -1", new Item { Title = "Some Title" }, true }; yield return new object[] { "not indexof(Title, 'Tit') eq -1 and Value gt 4", new Item { Title = "Some Title", Value = 5 }, true }; yield return new object[] { "(length(Title) gt 5 and contains(Title, 'tle')) or Value in (3.0,5.0)", new Item { Title = "Some Title", Value = 3 }, true }; yield return new object[] { "not indexof(Title, 'Tit') eq -1 or Value le 4", new Item { Title = "Some Title", Value = 5 }, true }; } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } public sealed class InvalidInputTestData : IEnumerable<object[]> { public IEnumerator<object[]> GetEnumerator() { yield return new object[] { "Id eqo 5", new Item { Id = 5 }, true }; yield return new object[] { "not Id eq 2019-01-29", new Item { Id = 5 }, false }; yield return new object[] { "NotExistingProperty eq 5.0", new Item { Value = 5 }, true }; } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } } }
47.933333
170
0.556527
[ "MIT" ]
sleemer/Guidelines.RestApi.Collections.Filtering
Filtering.Tests/FilterCompilerTests.cs
5,033
C#