content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections; using System.Collections.Concurrent; using MongoDB.Driver; using NUnit.Framework; using Tababular; namespace MongolianBarbecue.Tests { public abstract class FixtureBase { static readonly MongoUrl MongoUrl; static FixtureBase() { var connectionString = $"mongodb://localhost/mongobbq-{DateTime.Now.GetHashCode()%10000}"; MongoUrl = new MongoUrl(connectionString); } static readonly TableFormatter Formatter = new TableFormatter(new Hints { CollapseVerticallyWhenSingleLine = true }); protected void PrintTable(IEnumerable objects) { Console.WriteLine(Formatter.FormatObjects(objects)); } protected IMongoDatabase GetCleanTestDatabase() { Console.WriteLine($"Getting clean test database at '{MongoUrl}'"); var mongoClient = new MongoClient(MongoUrl); mongoClient.DropDatabase(MongoUrl.DatabaseName); var database = mongoClient.GetDatabase(MongoUrl.DatabaseName); return database; } readonly ConcurrentStack<IDisposable> _disposables = new ConcurrentStack<IDisposable>(); protected void CleanUpDisposables() { while (_disposables.TryPop(out var disposable)) { disposable.Dispose(); } } protected TDisposable Using<TDisposable>(TDisposable disposable) where TDisposable : IDisposable { _disposables.Push(disposable); return disposable; } [SetUp] public void InternalSetUp() { SetUp(); } protected virtual void SetUp() { } [TearDown] public void InternalTearDown() { CleanUpDisposables(); } } }
26
125
0.605901
[ "MIT" ]
mookid8000/MongolianBarbecue
MongolianBarbecue.Tests/FixtureBase.cs
1,900
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; public static class ModelExtensionMethods { public static bool isShowInGrid(this PropertyInfo obj) { if (obj == null) return false; var showingrid = obj.GetCustomAttribute<ShowInGridAttribute>(); if(showingrid != null) { return showingrid.Show; } return true; } }
19.8
71
0.646465
[ "Apache-2.0" ]
halilkocaerkek/Asp.Net-Mvc-Templates
Data.Attributes/Extentions.cs
497
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.V20180701.Inputs { /// <summary> /// Represents a ContentKeyPolicyConfiguration that is unavailable in the current API version. /// </summary> public sealed class ContentKeyPolicyUnknownConfigurationArgs : Pulumi.ResourceArgs { /// <summary> /// The discriminator for derived types. /// </summary> [Input("odataType", required: true)] public Input<string> OdataType { get; set; } = null!; public ContentKeyPolicyUnknownConfigurationArgs() { } } }
30.068966
98
0.680046
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/Media/V20180701/Inputs/ContentKeyPolicyUnknownConfigurationArgs.cs
872
C#
using System; using System.Collections.Generic; using System.Text; namespace Demo.Core.Entities { public interface IEntity { } }
13
33
0.713287
[ "MIT" ]
wannvmi/MyLearning-Ocelot
MyLearning.Ocelot/Demo.Core/Entities/IEntity.cs
145
C#
// Copyright (C) 2012 Winterleaf Entertainment L,L,C. // // THE SOFTW ARE IS PROVIDED ON AN “ AS IS” BASIS, WITHOUT W ARRANTY OF ANY KIND, // INCLUDING WITHOUT LIMIT ATION THE W ARRANTIES OF MERCHANT ABILITY, FITNESS // FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT . THE ENTIRE RISK AS TO THE // QUALITY AND PERFORMANCE OF THE SOFTW ARE IS THE RESPONSIBILITY OF LICENSEE. // SHOULD THE SOFTW ARE PROVE DEFECTIVE IN ANY RESPECT , LICENSEE AND NOT LICEN - // SOR OR ITS SUPPLIERS OR RESELLERS ASSUMES THE ENTIRE COST OF AN Y SERVICE AND // REPAIR. THIS DISCLAIMER OF W ARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS // AGREEMENT. NO USE OF THE SOFTW ARE IS AUTHORIZED HEREUNDER EXCEPT UNDER // THIS DISCLAIMER. // // The use of the WinterLeaf Entertainment LLC DotNetT orque (“DNT ”) and DotNetT orque // Customizer (“DNTC”)is governed by this license agreement (“ Agreement”). // // R E S T R I C T I O N S // // (a) Licensee may not: (i) create any derivative works of DNTC, including but not // limited to translations, localizations, technology add-ons, or game making software // other than Games; (ii) reverse engineer , or otherwise attempt to derive the algorithms // for DNT or DNTC (iii) redistribute, encumber , sell, rent, lease, sublicense, or otherwise // transfer rights to DNTC; or (iv) remove or alter any tra demark, logo, copyright // or other proprietary notices, legends, symbols or labels in DNT or DNTC; or (iiv) use // the Software to develop or distribute any software that compete s with the Software // without WinterLeaf Entertainment’s prior written consent; or (i iiv) use the Software for // any illegal purpose. // (b) Licensee may not distribute the DNTC in any manner. // // LI C E N S E G R A N T . // This license allows companies of any size, government entities or individuals to cre - // ate, sell, rent, lease, or otherwise profit commercially from, games using executables // created from the source code of DNT // // ********************************************************************************** // ********************************************************************************** // ********************************************************************************** // THE SOURCE CODE GENERATED BY DNTC CAN BE DISTRIBUTED PUBLICLY PROVIDED THAT THE // DISTRIBUTOR PROVIDES THE GENERATE SOURCE CODE FREE OF CHARGE. // // THIS SOURCE CODE (DNT) CAN BE DISTRIBUTED PUBLICLY PROVIDED THAT THE DISTRIBUTOR // PROVIDES THE SOURCE CODE (DNT) FREE OF CHARGE. // ********************************************************************************** // ********************************************************************************** // ********************************************************************************** // // Please visit http://www.winterleafentertainment.com for more information about the project and latest updates. // // // #region using WinterLeaf.Classes; #endregion namespace DNT_FPS_Demo_Game_Dll.Scripts.Client { public partial class Main : TorqueScriptTemplate { //----------------------------------------------------------------------------- // Water //----------------------------------------------------------------------------- [Torque_Decorations.TorqueCallBack("", "", "water_Init", "", 0, 44000, true)] public void water_init() { TorqueSingleton ts = new TorqueSingleton("ShaderData", "WaterShader"); ts.PropsAddString("DXVertexShaderFile", "shaders/common/water/waterV.hlsl"); ts.PropsAddString("DXPixelShaderFile", "shaders/common/water/waterP.hlsl"); ts.PropsAddString("OGLVertexShaderFile", "shaders/common/water/gl/waterV.glsl"); ts.PropsAddString("OGLPixelShaderFile", "shaders/common/water/gl/waterP.glsl"); ts.Props.Add("pixVersion", "3.0"); ts.Create(); Torque_Class_Helper tch = new Torque_Class_Helper("GFXSamplerStateData", "WaterSampler"); tch.Props.Add("textureColorOp", "GFXTOPModulate"); tch.Props.Add("addressModeU", "GFXAddressWrap"); tch.Props.Add("addressModeV", "GFXAddressWrap"); tch.Props.Add("addressModeW", "GFXAddressWrap"); tch.Props.Add("magFilter", "GFXTextureFilterLinear"); tch.Props.Add("minFilter", "GFXTextureFilterAnisotropic"); tch.Props.Add("mipFilter", "GFXTextureFilterLinear"); tch.Props.Add("maxAnisotropy", "4"); tch.Create(); ts = new TorqueSingleton("GFXStateBlockData", "WaterStateBlock"); ts.Props.Add("samplersDefined", "true"); ts.Props.Add("samplerStates[0]", "WaterSampler"); // noise ts.Props.Add("samplerStates[1]", "SamplerClampPoint"); // #prepass ts.Props.Add("samplerStates[2]", "SamplerClampLinear"); // $reflectbuff ts.Props.Add("samplerStates[3]", "SamplerClampPoint"); // $backbuff ts.Props.Add("samplerStates[4]", "SamplerWrapLinear"); // $cubemap ts.Props.Add("samplerStates[5]", "SamplerWrapLinear"); // foam ts.Props.Add("samplerStates[6]", "SamplerClampLinear"); // depthMap ( color gradient ) ts.Props.Add("cullDefined", "true"); ts.PropsAddString("cullMode", "GFXCullCCW"); ts.Create(); ts = new TorqueSingleton("GFXStateBlockData", "UnderWaterStateBlock : WaterStateBlock"); ts.PropsAddString("cullMode", "GFXCullCW"); ts.Create(); ts = new TorqueSingleton("CustomMaterial", "WaterMat"); ts.PropsAddString(@"sampler[""prepassTex""]", "#prepass"); ts.PropsAddString(@"sampler[""reflectMap""]", "$reflectbuff"); ts.PropsAddString(@"sampler[""refractBuff""]", "$backbuff"); ts.Props.Add("shader", "WaterShader"); ts.Props.Add("stateBlock", "WaterStateBlock"); ts.Props.Add("version", "3.0"); ts.Props.Add("useAnisotropic[0]", "true"); ts.Create(); //----------------------------------------------------------------------------- // Underwater //----------------------------------------------------------------------------- ts = new TorqueSingleton("ShaderData", "UnderWaterShader"); ts.PropsAddString(@"DXVertexShaderFile", "shaders/common/water/waterV.hlsl"); ts.PropsAddString(@"DXPixelShaderFile", "shaders/common/water/waterP.hlsl"); ts.PropsAddString(@"OGLVertexShaderFile", "shaders/common/water/gl/waterV.glsl"); ts.PropsAddString(@"OGLPixelShaderFile", "shaders/common/water/gl/waterP.glsl"); ts.PropsAddString(@"defines", "UNDERWATER"); ts.Props.Add("pixVersion", "3.0"); ts.Create(); ts = new TorqueSingleton("CustomMaterial", "UnderwaterMat"); // These samplers are set in code not here. // This is to allow different WaterObject instances // to use this same material but override these textures // per instance. //sampler["bumpMap"] = "core/art/water/noise02"; //sampler["foamMap"] = "core/art/water/foam"; ts.PropsAddString(@"sampler[""prepassTex""]", "#prepass"); ts.PropsAddString(@"sampler[""refractBuff""]", "$backbuff"); ts.PropsAddString(@"shader", "UnderWaterShader"); ts.PropsAddString(@"stateBlock", "UnderWaterStateBlock"); ts.PropsAddString(@"specular", "0.75 0.75 0.75 1.0"); ts.Props.Add(@"specularPower", "48.0"); ts.Props.Add(@"version", "3.0"); ts.Create(); //----------------------------------------------------------------------------- // Basic Water //----------------------------------------------------------------------------- ts = new TorqueSingleton("ShaderData", "WaterBasicShader"); ts.PropsAddString("DXVertexShaderFile", "shaders/common/water/waterBasicV.hlsl"); ts.PropsAddString("DXPixelShaderFile", "shaders/common/water/waterBasicP.hlsl"); ts.PropsAddString("OGLVertexShaderFile", "shaders/common/water/gl/waterBasicV.glsl"); ts.PropsAddString("OGLPixelShaderFile", "shaders/common/water/gl/waterBasicP.glsl"); ts.Props.Add("pixVersion", "2.0"); ts.Create(); ts = new TorqueSingleton("GFXStateBlockData", "WaterBasicStateBlock"); ts.Props.Add("samplersDefined", "true"); ts.Props.Add("samplerStates[0]", "WaterSampler"); // noise ts.Props.Add("samplerStates[2]", "SamplerClampLinear"); // $reflectbuff ts.Props.Add("samplerStates[3]", "SamplerClampPoint"); // $backbuff ts.Props.Add("samplerStates[4]", "SamplerWrapLinear"); // $cubemap ts.Props.Add("cullDefined", "true"); ts.PropsAddString("cullMode", "GFXCullCCW"); ts.Create(); ts = new TorqueSingleton("GFXStateBlockData", "UnderWaterBasicStateBlock : WaterBasicStateBlock"); ts.PropsAddString("cullMode", "GFXCullCW"); ts.Create(); ts = new TorqueSingleton("CustomMaterial", "WaterBasicMat"); // These samplers are set in code not here. // This is to allow different WaterObject instances // to use this same material but override these textures // per instance. //sampler["bumpMap"] = "core/art/water/noise02"; //sampler["skyMap"] = "$cubemap"; //sampler["prepassTex"] = "#prepass"; ts.PropsAddString(@"sampler[""reflectMap""]", "$reflectbuff"); ts.PropsAddString(@"sampler[""refractBuff""]", "$backbuff"); ts.Props.Add("cubemap", "NewLevelSkyCubemap"); ts.Props.Add("shader", "WaterBasicShader"); ts.Props.Add("stateBlockZ", "WaterBasicStateBlock"); ts.Props.Add("version", "2.0"); ts.Create(); //----------------------------------------------------------------------------- // Basic UnderWater //----------------------------------------------------------------------------- ts = new TorqueSingleton("ShaderData", "UnderWaterBasicShader"); ts.PropsAddString(@"DXVertexShaderFile", "shaders/common/water/waterBasicV.hlsl"); ts.PropsAddString(@"DXPixelShaderFile", "shaders/common/water/waterBasicP.hlsl"); ts.PropsAddString(@"OGLVertexShaderFile", "shaders/common/water/gl/waterBasicV.glsl"); ts.PropsAddString(@"OGLPixelShaderFile", "shaders/common/water/gl/waterBasicP.glsl"); ts.PropsAddString(@"defines", "UNDERWATER"); ts.Props.Add("pixVersion", "2.0"); ts.Create(); ts = new TorqueSingleton("CustomMaterial", "UnderwaterBasicMat"); // These samplers are set in code not here. // This is to allow different WaterObject instances // to use this same material but override these textures // per instance. //sampler["bumpMap"] = "core/art/water/noise02"; //samplers["skyMap"] = "$cubemap"; //sampler["prepassTex"] = "#prepass"; ts.PropsAddString(@"sampler[""refractBuff""]", "$backbuff"); ts.Props.Add("shader", "UnderWaterBasicShader"); ts.Props.Add("stateBlock", "UnderWaterBasicStateBlock"); ts.Props.Add("version", "2.0"); ts.Create(); } } }
51.821739
114
0.551389
[ "Unlicense" ]
Winterleaf/DNT-Torque3D-V1.1-MIT-3.0
Templates/Full/DNT FPS Demo Dll No Core/Scripts/Client/Enviroment/water.cs
11,710
C#
// HO=False using System; // using System; using System.Collections.Generic; // using System.Collections.Generic; using System.Linq; // using System.Linq; using System.Text; // using System.Text; // // // namespace Charlotte // namespace Charlotte { // { public class IndicateCompleteEireneRepresentation // public class Scenario { // { // HO=False public int EmitPublicAdrasteaDamage() { return CollapseAnonymousHydrogenAccount() != 1 ? 0 : DetectNextIapetusTermination; } // public int ADM_a_12804627364052987216_15518737851131541028_z_GetInt_2() { return ADM_a_12804627364052987216_15518737851131541028_z_GetInt_1() != 1 ? 0 : ADM_a_12804627364052987216_15518737851131541028_z_Count_2; } // HO=False public void RequireRedundantGadoliniumMemory(int EscapeRawSaoPost, int CloseLocalAtlasChoice, int RespondUnableGelatoBranch) // public void ADM_a_06687837266033469094_13191855735157532304_z_Overload_03(int ADM_a_06687837266033469094_13191855735157532304_z_a, int ADM_a_06687837266033469094_13191855735157532304_z_b, int ADM_a_06687837266033469094_13191855735157532304_z_c) { // { this.BundleConditionalLawrenciumRepresentation(EscapeRawSaoPost, CloseLocalAtlasChoice, RespondUnableGelatoBranch, this.ExpandStandaloneGoldLocale().ReceiveUnauthorizedRubidiumDescription, this.ExpandStandaloneGoldLocale().FindDuplicateCressidaService, this.ExpandStandaloneGoldLocale().ImproveUnresolvedNeonEditor); // this.ADM_a_06687837266033469094_13191855735157532304_z_Overload_04(ADM_a_06687837266033469094_13191855735157532304_z_a, ADM_a_06687837266033469094_13191855735157532304_z_b, ADM_a_06687837266033469094_13191855735157532304_z_c, this.ADM_a_06687837266033469094_13191855735157532304_z_GetValue().ADM_a_06687837266033469094_13191855735157532304_z_ValueInfo_A, this.ADM_a_06687837266033469094_13191855735157532304_z_GetValue().ADM_a_06687837266033469094_13191855735157532304_z_ValueInfo_B, this.ADM_a_06687837266033469094_13191855735157532304_z_GetValue().ADM_a_06687837266033469094_13191855735157532304_z_ValueInfo_C); } // } // HO=False public void ProtectCurrentCustardMedia(ImproveRedundantPortiaSize CopySecureNesoTodo) // public void ADM_a_06687837266033469094_13191855735157532304_z_SetValue(ADM_a_06687837266033469094_13191855735157532304_z_ValueInfo ADM_a_06687837266033469094_13191855735157532304_z_SetValue_Prm) { // { ModifyApplicableNitrogenCursor = CopySecureNesoTodo; // ADM_a_06687837266033469094_13191855735157532304_z_Value = ADM_a_06687837266033469094_13191855735157532304_z_SetValue_Prm; } // } // HO=False public static int CompileMaximumSilverProfile; // public static int ADM_a_12804627364052987216_15518737851131541028_z_Count_5; // HO=False public int DeployExtraTarvosInitialization() // public int ADM_a_06687837266033469094_13191855735157532304_z_NextCount() { // { return SignCustomMetisFailure++; // return ADM_a_06687837266033469094_13191855735157532304_z_Count++; } // } // HO=False public int DownloadDynamicAluminiumConflict() { return AuthorizeUnusedProsperoProfile() == 0 ? 0 : ConflictDedicatedValetudoFramework; } // public int ADM_a_12804627364052987216_15518737851131541028_z_GetInt_6() { return ADM_a_12804627364052987216_15518737851131541028_z_GetInt_5() == 0 ? 0 : ADM_a_12804627364052987216_15518737851131541028_z_Count_6; } // HO=False public void BundleConditionalLawrenciumRepresentation(int EscapeRawSaoPost, int CloseLocalAtlasChoice, int RespondUnableGelatoBranch, int RequestGlobalSurturExecution, int RefactorCurrentRougeHighlight, int TypeAdditionalPerditaPackage) // public void ADM_a_06687837266033469094_13191855735157532304_z_Overload_04(int ADM_a_06687837266033469094_13191855735157532304_z_a, int ADM_a_06687837266033469094_13191855735157532304_z_b, int ADM_a_06687837266033469094_13191855735157532304_z_c, int ADM_a_06687837266033469094_13191855735157532304_z_a2, int ADM_a_06687837266033469094_13191855735157532304_z_b2, int ADM_a_06687837266033469094_13191855735157532304_z_c2) { // { var FollowCompleteHerseSource = new[] // var ADM_a_06687837266033469094_13191855735157532304_z_infos = new[] { // { new { LabelNestedTarqeqType = EscapeRawSaoPost, PullSecureBerylliumAction = RequestGlobalSurturExecution }, // new { ADM_a_06687837266033469094_13191855735157532304_z_Info_P1 = ADM_a_06687837266033469094_13191855735157532304_z_a, ADM_a_06687837266033469094_13191855735157532304_z_Info_P2 = ADM_a_06687837266033469094_13191855735157532304_z_a2 }, new { LabelNestedTarqeqType = CloseLocalAtlasChoice, PullSecureBerylliumAction = RequestGlobalSurturExecution }, // new { ADM_a_06687837266033469094_13191855735157532304_z_Info_P1 = ADM_a_06687837266033469094_13191855735157532304_z_b, ADM_a_06687837266033469094_13191855735157532304_z_Info_P2 = ADM_a_06687837266033469094_13191855735157532304_z_a2 }, new { LabelNestedTarqeqType = RespondUnableGelatoBranch, PullSecureBerylliumAction = RequestGlobalSurturExecution }, // new { ADM_a_06687837266033469094_13191855735157532304_z_Info_P1 = ADM_a_06687837266033469094_13191855735157532304_z_c, ADM_a_06687837266033469094_13191855735157532304_z_Info_P2 = ADM_a_06687837266033469094_13191855735157532304_z_a2 }, }; // }; this.ProtectCurrentCustardMedia(new ImproveRedundantPortiaSize() // this.ADM_a_06687837266033469094_13191855735157532304_z_SetValue(new ADM_a_06687837266033469094_13191855735157532304_z_ValueInfo() { // { ReceiveUnauthorizedRubidiumDescription = EscapeRawSaoPost, // ADM_a_06687837266033469094_13191855735157532304_z_ValueInfo_A = ADM_a_06687837266033469094_13191855735157532304_z_a, FindDuplicateCressidaService = CloseLocalAtlasChoice, // ADM_a_06687837266033469094_13191855735157532304_z_ValueInfo_B = ADM_a_06687837266033469094_13191855735157532304_z_b, ImproveUnresolvedNeonEditor = RespondUnableGelatoBranch, // ADM_a_06687837266033469094_13191855735157532304_z_ValueInfo_C = ADM_a_06687837266033469094_13191855735157532304_z_c, }); // }); if (FollowCompleteHerseSource[0].LabelNestedTarqeqType == RequestGlobalSurturExecution) this.SwitchDecimalCaesiumFile(FollowCompleteHerseSource[0].PullSecureBerylliumAction); // if (ADM_a_06687837266033469094_13191855735157532304_z_infos[0].ADM_a_06687837266033469094_13191855735157532304_z_Info_P1 == ADM_a_06687837266033469094_13191855735157532304_z_a2) this.ADM_a_06687837266033469094_13191855735157532304_z_Overload_05(ADM_a_06687837266033469094_13191855735157532304_z_infos[0].ADM_a_06687837266033469094_13191855735157532304_z_Info_P2); if (FollowCompleteHerseSource[1].LabelNestedTarqeqType == RefactorCurrentRougeHighlight) this.SwitchDecimalCaesiumFile(FollowCompleteHerseSource[1].PullSecureBerylliumAction); // if (ADM_a_06687837266033469094_13191855735157532304_z_infos[1].ADM_a_06687837266033469094_13191855735157532304_z_Info_P1 == ADM_a_06687837266033469094_13191855735157532304_z_b2) this.ADM_a_06687837266033469094_13191855735157532304_z_Overload_05(ADM_a_06687837266033469094_13191855735157532304_z_infos[1].ADM_a_06687837266033469094_13191855735157532304_z_Info_P2); if (FollowCompleteHerseSource[2].LabelNestedTarqeqType == TypeAdditionalPerditaPackage) this.SwitchDecimalCaesiumFile(FollowCompleteHerseSource[2].PullSecureBerylliumAction); // if (ADM_a_06687837266033469094_13191855735157532304_z_infos[2].ADM_a_06687837266033469094_13191855735157532304_z_Info_P1 == ADM_a_06687837266033469094_13191855735157532304_z_c2) this.ADM_a_06687837266033469094_13191855735157532304_z_Overload_05(ADM_a_06687837266033469094_13191855735157532304_z_infos[2].ADM_a_06687837266033469094_13191855735157532304_z_Info_P2); } // } // HO=False public int ResetTruePapayaAccount() { return UsePreviousZirconiumUnit; } // public int ADM_a_12804627364052987216_15518737851131541028_z_GetInt_0() { return ADM_a_12804627364052987216_15518737851131541028_z_Count_0; } // HO=False public static int ConflictDedicatedValetudoFramework; // public static int ADM_a_12804627364052987216_15518737851131541028_z_Count_6; // HO=False public static string CompleteCompleteDeimosFunctionality() { if(ArchiveCompleteEuphemeFilter == null) { ArchiveCompleteEuphemeFilter = InstallCorrectRoseName(); } return ArchiveCompleteEuphemeFilter; } // public static string SLS2_a_17482759180178759095_11927882640427598600_z() { if(SLS2_a_17482759180178759095_11927882640427598600_z_String == null) { SLS2_a_17482759180178759095_11927882640427598600_z_String = SLS2_a_17482759180178759095_11927882640427598600_z_GetString(); } return SLS2_a_17482759180178759095_11927882640427598600_z_String; } // HO=False public void SwitchDecimalCaesiumFile(int PrintBinaryBeautySession) // public void ADM_a_06687837266033469094_13191855735157532304_z_Overload_05(int ADM_a_06687837266033469094_13191855735157532304_z_v) { // { if (PrintBinaryBeautySession != this.CastBooleanProsperoCopyright()) // if (ADM_a_06687837266033469094_13191855735157532304_z_v != this.ADM_a_06687837266033469094_13191855735157532304_z_GetCount()) this.FailUnresolvedRheaButton(PrintBinaryBeautySession); // this.ADM_a_06687837266033469094_13191855735157532304_z_SetCount(ADM_a_06687837266033469094_13191855735157532304_z_v); else // else this.MatchLocalSunDocument(PrintBinaryBeautySession); // this.ADM_a_06687837266033469094_13191855735157532304_z_Overload_01(ADM_a_06687837266033469094_13191855735157532304_z_v); } // } // HO=False public ImproveRedundantPortiaSize ExpandStandaloneGoldLocale() // public ADM_a_06687837266033469094_13191855735157532304_z_ValueInfo ADM_a_06687837266033469094_13191855735157532304_z_GetValue() { // { return ModifyApplicableNitrogenCursor; // return ADM_a_06687837266033469094_13191855735157532304_z_Value; } // } // HO=False public static string ContinueSuccessfulMarsCase; // public static string SLS2_a_17638694284867815144_08039266912286611147_z_String; // HO=False public static int UsePreviousZirconiumUnit; // public static int ADM_a_12804627364052987216_15518737851131541028_z_Count_0; // HO=False public static string SanitizeUsefulPantaloniTab() { return new string(AggregateUnavailableHatiUnit().Where(ClearMatchingThyoneThread => ClearMatchingThyoneThread % 65537 != 0).Select(VisitUsefulHelikeCredential => (char)(VisitUsefulHelikeCredential % 65537 - 1)).ToArray()); } // public static string SLS2_a_17638694284867815144_08039266912286611147_z_GetString() { return new string(SLS2_a_17638694284867815144_08039266912286611147_z_E_GetString().Where(SLS2_a_17638694284867815144_08039266912286611147_z_Var => SLS2_a_17638694284867815144_08039266912286611147_z_Var % 65537 != 0).Select(SLS2_a_17638694284867815144_08039266912286611147_z_Var2 => (char)(SLS2_a_17638694284867815144_08039266912286611147_z_Var2 % 65537 - 1)).ToArray()); } // HO=False public void DeclareUnnecessaryErriapusScope(int EscapeRawSaoPost, int CloseLocalAtlasChoice) // public void ADM_a_06687837266033469094_13191855735157532304_z_Overload_02(int ADM_a_06687837266033469094_13191855735157532304_z_a, int ADM_a_06687837266033469094_13191855735157532304_z_b) { // { this.RequireRedundantGadoliniumMemory(EscapeRawSaoPost, CloseLocalAtlasChoice, this.DeployExtraTarvosInitialization()); // this.ADM_a_06687837266033469094_13191855735157532304_z_Overload_03(ADM_a_06687837266033469094_13191855735157532304_z_a, ADM_a_06687837266033469094_13191855735157532304_z_b, this.ADM_a_06687837266033469094_13191855735157532304_z_NextCount()); } // } // HO=False public static IEnumerable<int> FireOptionalPhilophrosyneApplication() { yield return 1586716307; yield return 1768581482; yield return 1769695611; yield return 1490311380; yield return 1012743261; yield return 1676698608; yield return 1155679458; } // public static IEnumerable<int> SLS2_a_17482759180178759095_11927882640427598600_z_E_GetString() { yield return 1586716307; yield return 1768581482; yield return 1769695611; yield return 1490311380; yield return 1012743261; yield return 1676698608; yield return 1155679458; } // HO=False public static int ApplyNativeMercuryTree; // public static int ADM_a_12804627364052987216_15518737851131541028_z_Count_3; // HO=False public static int BreakUnsupportedHyperionDeclaration; // public static int ADM_a_12804627364052987216_15518737851131541028_z_Count_1; // HO=False public void SupportNormalAstatineDevice() // public void ADM_a_06687837266033469094_13191855735157532304_z_ResetCount() { // { this.FailUnresolvedRheaButton(0); // this.ADM_a_06687837266033469094_13191855735157532304_z_SetCount(0); } // } // HO=False public static ImproveRedundantPortiaSize ModifyApplicableNitrogenCursor; // public static ADM_a_06687837266033469094_13191855735157532304_z_ValueInfo ADM_a_06687837266033469094_13191855735157532304_z_Value; // HO=False public void FailUnresolvedRheaButton(int ArchiveExtraCarmeNotification) // public void ADM_a_06687837266033469094_13191855735157532304_z_SetCount(int ADM_a_06687837266033469094_13191855735157532304_z_SetCount_Prm) { // { SignCustomMetisFailure = ArchiveExtraCarmeNotification; // ADM_a_06687837266033469094_13191855735157532304_z_Count = ADM_a_06687837266033469094_13191855735157532304_z_SetCount_Prm; } // } // HO=False public static int DetectNextIapetusTermination; // public static int ADM_a_12804627364052987216_15518737851131541028_z_Count_2; // HO=False public int AuthorizeUnusedProsperoProfile() { return ToggleDynamicJulietCheckbox() != 0 ? 0 : CompileMaximumSilverProfile; } // public int ADM_a_12804627364052987216_15518737851131541028_z_GetInt_5() { return ADM_a_12804627364052987216_15518737851131541028_z_GetInt_4() != 0 ? 0 : ADM_a_12804627364052987216_15518737851131541028_z_Count_5; } // HO=False public static IEnumerable<int> AggregateUnavailableHatiUnit() { yield return 1864462113; yield return 1248414313; yield return 1516395106; yield return 1657234119; yield return 1031814528; yield return 2131918610; yield return 1900048737; } // public static IEnumerable<int> SLS2_a_17638694284867815144_08039266912286611147_z_E_GetString() { yield return 1864462113; yield return 1248414313; yield return 1516395106; yield return 1657234119; yield return 1031814528; yield return 2131918610; yield return 1900048737; } // HO=False public int CollapseAnonymousHydrogenAccount() { return ResetTruePapayaAccount() == 0 ? 1 : BreakUnsupportedHyperionDeclaration; } // public int ADM_a_12804627364052987216_15518737851131541028_z_GetInt_1() { return ADM_a_12804627364052987216_15518737851131541028_z_GetInt_0() == 0 ? 1 : ADM_a_12804627364052987216_15518737851131541028_z_Count_1; } // HO=False public static string InstallCorrectRoseName() { return new string(FireOptionalPhilophrosyneApplication().Where(EqualPrivateLuminousWrapper => EqualPrivateLuminousWrapper % 65537 != 0).Select(IteratePhysicalGreipRegistration => (char)(IteratePhysicalGreipRegistration % 65537 - 1)).ToArray()); } // public static string SLS2_a_17482759180178759095_11927882640427598600_z_GetString() { return new string(SLS2_a_17482759180178759095_11927882640427598600_z_E_GetString().Where(SLS2_a_17482759180178759095_11927882640427598600_z_Var => SLS2_a_17482759180178759095_11927882640427598600_z_Var % 65537 != 0).Select(SLS2_a_17482759180178759095_11927882640427598600_z_Var2 => (char)(SLS2_a_17482759180178759095_11927882640427598600_z_Var2 % 65537 - 1)).ToArray()); } // HO=False public static int SignCustomMetisFailure; // public static int ADM_a_06687837266033469094_13191855735157532304_z_Count; // HO=False public int PrepareTemporaryLovelySequence() { return EmitPublicAdrasteaDamage() == 0 ? 0 : ApplyNativeMercuryTree; } // public int ADM_a_12804627364052987216_15518737851131541028_z_GetInt_3() { return ADM_a_12804627364052987216_15518737851131541028_z_GetInt_2() == 0 ? 0 : ADM_a_12804627364052987216_15518737851131541028_z_Count_3; } // HO=False public static int ProvideTrueStephanoView; // public static int ADM_a_12804627364052987216_15518737851131541028_z_Count_4; // HO=False public void MatchLocalSunDocument(int EscapeRawSaoPost) // public void ADM_a_06687837266033469094_13191855735157532304_z_Overload_01(int ADM_a_06687837266033469094_13191855735157532304_z_a) { // { this.DeclareUnnecessaryErriapusScope(EscapeRawSaoPost, this.DeployExtraTarvosInitialization()); // this.ADM_a_06687837266033469094_13191855735157532304_z_Overload_02(ADM_a_06687837266033469094_13191855735157532304_z_a, this.ADM_a_06687837266033469094_13191855735157532304_z_NextCount()); } // } // HO=False public int CastBooleanProsperoCopyright() // public int ADM_a_06687837266033469094_13191855735157532304_z_GetCount() { // { return SignCustomMetisFailure; // return ADM_a_06687837266033469094_13191855735157532304_z_Count; } // } // HO=True public List<DefaultInitialSuttungrThread> MakeConditionalPalladiumSnapshot = new List<DefaultInitialSuttungrThread>(); // public List<ScenarioCommand> Commands = new List<ScenarioCommand>(); // // HO=False public static string ArchiveCompleteEuphemeFilter; // public static string SLS2_a_17482759180178759095_11927882640427598600_z_String; // HO=False public int ToggleDynamicJulietCheckbox() { return PrepareTemporaryLovelySequence() - ProvideTrueStephanoView; } // public int ADM_a_12804627364052987216_15518737851131541028_z_GetInt_4() { return ADM_a_12804627364052987216_15518737851131541028_z_GetInt_3() - ADM_a_12804627364052987216_15518737851131541028_z_Count_4; } // HO=False public class ImproveRedundantPortiaSize // public class ADM_a_06687837266033469094_13191855735157532304_z_ValueInfo { // { public int ReceiveUnauthorizedRubidiumDescription; // public int ADM_a_06687837266033469094_13191855735157532304_z_ValueInfo_A; public int FindDuplicateCressidaService; // public int ADM_a_06687837266033469094_13191855735157532304_z_ValueInfo_B; public int ImproveUnresolvedNeonEditor; // public int ADM_a_06687837266033469094_13191855735157532304_z_ValueInfo_C; } // } // HO=False public static string FixAdditionalSoleilDeployment() { if(ContinueSuccessfulMarsCase == null) { ContinueSuccessfulMarsCase = SanitizeUsefulPantaloniTab(); } return ContinueSuccessfulMarsCase; } // public static string SLS2_a_17638694284867815144_08039266912286611147_z() { if(SLS2_a_17638694284867815144_08039266912286611147_z_String == null) { SLS2_a_17638694284867815144_08039266912286611147_z_String = SLS2_a_17638694284867815144_08039266912286611147_z_GetString(); } return SLS2_a_17638694284867815144_08039266912286611147_z_String; } // HO=False public IndicateCompleteEireneRepresentation(string TerminateMockArcheFollowing) // public Scenario(string file) { // { byte[] TypeGenericSeleniumRuntime = CrashCompletePriestessNode.Load(TerminateMockArcheFollowing); // byte[] fileData = DDResource.Load(file); string FireExpressThyoneSecurity = ControlUnresolvedHeleneSource.LabelUnauthorizedFluorineInspection(TypeGenericSeleniumRuntime, true, true, true, true); // string text = SCommon.ToJString(fileData, true, true, true, true); string[] CloseCustomCobaltPriority = ControlUnresolvedHeleneSource.DetectInvalidThemistoPriority(FireExpressThyoneSecurity); // string[] lines = SCommon.TextToLines(text); // foreach (string AccessConstantEinsteiniumStatement in CloseCustomCobaltPriority) // foreach (string line in lines) { // { if (AccessConstantEinsteiniumStatement == CompleteCompleteDeimosFunctionality()) // if (line == SLS2_a_17482759180178759095_11927882640427598600_z()) continue; // continue; // if (AccessConstantEinsteiniumStatement[0] == ((char)59)) // if (line[0] == ((char)59)) continue; // continue; // string[] CommitAvailableBestlaCleanup = ControlUnresolvedHeleneSource.InputLatestTarqeqInstallation(AccessConstantEinsteiniumStatement, FixAdditionalSoleilDeployment(), false, true); // string[] tokens = SCommon.Tokenize(line, SLS2_a_17638694284867815144_08039266912286611147_z(), false, true); // this.MakeConditionalPalladiumSnapshot.Add(new DefaultInitialSuttungrThread() // this.Commands.Add(new ScenarioCommand() { // { OverrideMultiplePuckRule = CommitAvailableBestlaCleanup, // Tokens = tokens, }); // }); } // } } // } // HO=False public void UploadDeprecatedMegacliteFunctionality() // public void ADM_a_06687837266033469094_13191855735157532304_z_Overload_00() { // { this.MatchLocalSunDocument(this.DeployExtraTarvosInitialization()); // this.ADM_a_06687837266033469094_13191855735157532304_z_Overload_01(this.ADM_a_06687837266033469094_13191855735157532304_z_NextCount()); } // } // HO=False } // } } // }
68.094771
619
0.84374
[ "MIT" ]
soleil-taruto/Hatena
a20201226/Confused_01/tmpsol_mid/Elsa20200001/Games/Scenario.cs
20,839
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Network { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// NetworkProfilesOperations operations. /// </summary> internal partial class NetworkProfilesOperations : IServiceOperations<NetworkManagementClient>, INetworkProfilesOperations { /// <summary> /// Initializes a new instance of the NetworkProfilesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal NetworkProfilesOperations(NetworkManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// Deletes the specified network profile. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkProfileName'> /// The name of the NetworkProfile. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string networkProfileName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkProfileName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkProfileName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2018-11-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkProfileName", networkProfileName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles/{networkProfileName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkProfileName}", System.Uri.EscapeDataString(networkProfileName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the specified network profile in a specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkProfileName'> /// The name of the PublicIPPrefx. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<NetworkProfile>> GetWithHttpMessagesAsync(string resourceGroupName, string networkProfileName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkProfileName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkProfileName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2018-11-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkProfileName", networkProfileName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles/{networkProfileName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkProfileName}", System.Uri.EscapeDataString(networkProfileName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<NetworkProfile>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<NetworkProfile>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a network profile. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkProfileName'> /// The name of the network profile. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update network profile operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<NetworkProfile>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkProfileName, NetworkProfile parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkProfileName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkProfileName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2018-11-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkProfileName", networkProfileName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles/{networkProfileName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkProfileName}", System.Uri.EscapeDataString(networkProfileName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<NetworkProfile>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<NetworkProfile>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<NetworkProfile>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Updates network profile tags. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkProfileName'> /// The name of the network profile. /// </param> /// <param name='parameters'> /// Parameters supplied to update network profile tags. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<NetworkProfile>> UpdateTagsWithHttpMessagesAsync(string resourceGroupName, string networkProfileName, TagsObject parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkProfileName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkProfileName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2018-11-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkProfileName", networkProfileName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "UpdateTags", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles/{networkProfileName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkProfileName}", System.Uri.EscapeDataString(networkProfileName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<NetworkProfile>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<NetworkProfile>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the network profiles in a subscription. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<NetworkProfile>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2018-11-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAll", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/networkProfiles").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<NetworkProfile>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NetworkProfile>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all network profiles in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<NetworkProfile>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2018-11-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkProfiles").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<NetworkProfile>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NetworkProfile>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the network profiles in a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<NetworkProfile>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAllNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<NetworkProfile>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NetworkProfile>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all network profiles in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<NetworkProfile>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<NetworkProfile>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NetworkProfile>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
46.215786
302
0.560471
[ "MIT" ]
Chuansssss/azure-sdk-for-net
src/SDKs/Network/Management.Network/Generated/NetworkProfilesOperations.cs
72,605
C#
// Copyright (C) 2003-2010 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Ivan Galkin // Created: 2009.03.24 using System; using Xtensive.Modelling; namespace Xtensive.Orm.Tests.Core.Modelling.IndexingModel { /// <summary> /// References to value column. /// </summary> [Serializable] public sealed class ValueColumnRef : ColumnInfoRef<PrimaryIndexInfo> { /// <inheritdoc/> protected override Nesting CreateNesting() { return new Nesting<ValueColumnRef, PrimaryIndexInfo, ValueColumnRefCollection>( this, "ValueColumns"); } // Constructors public ValueColumnRef(PrimaryIndexInfo parent) : base(parent) { } public ValueColumnRef(PrimaryIndexInfo parent, ColumnInfo column) : base(parent, column) { } } }
23.526316
86
0.6566
[ "MIT" ]
SergeiPavlov/dataobjects-net
Orm/Xtensive.Orm.Tests.Core/Modelling/IndexingModel/ValueColumnRef.cs
894
C#
// <file> // <copyright see="prj:///doc/copyright.txt"/> // <license see="prj:///doc/license.txt"/> // <owner name="David Srbecký" email="dsrbecky@gmail.com"/> // <version>$Revision$</version> // </file> // This file is automatically generated - any changes will be lost #pragma warning disable 1591 namespace Debugger.Wrappers.CorDebug { using System; public partial class ICorDebugModule { private Debugger.Interop.CorDebug.ICorDebugModule wrappedObject; internal Debugger.Interop.CorDebug.ICorDebugModule WrappedObject { get { return this.wrappedObject; } } public ICorDebugModule(Debugger.Interop.CorDebug.ICorDebugModule wrappedObject) { this.wrappedObject = wrappedObject; ResourceManager.TrackCOMObject(wrappedObject, typeof(ICorDebugModule)); } public static ICorDebugModule Wrap(Debugger.Interop.CorDebug.ICorDebugModule objectToWrap) { if ((objectToWrap != null)) { return new ICorDebugModule(objectToWrap); } else { return null; } } ~ICorDebugModule() { object o = wrappedObject; wrappedObject = null; ResourceManager.ReleaseCOMObject(o, typeof(ICorDebugModule)); } public bool Is<T>() where T: class { System.Reflection.ConstructorInfo ctor = typeof(T).GetConstructors()[0]; System.Type paramType = ctor.GetParameters()[0].ParameterType; return paramType.IsInstanceOfType(this.WrappedObject); } public T As<T>() where T: class { try { return CastTo<T>(); } catch { return null; } } public T CastTo<T>() where T: class { return (T)Activator.CreateInstance(typeof(T), this.WrappedObject); } public static bool operator ==(ICorDebugModule o1, ICorDebugModule o2) { return ((object)o1 == null && (object)o2 == null) || ((object)o1 != null && (object)o2 != null && o1.WrappedObject == o2.WrappedObject); } public static bool operator !=(ICorDebugModule o1, ICorDebugModule o2) { return !(o1 == o2); } public override int GetHashCode() { return base.GetHashCode(); } public override bool Equals(object o) { ICorDebugModule casted = o as ICorDebugModule; return (casted != null) && (casted.WrappedObject == wrappedObject); } public ICorDebugProcess Process { get { ICorDebugProcess ppProcess; Debugger.Interop.CorDebug.ICorDebugProcess out_ppProcess; this.WrappedObject.GetProcess(out out_ppProcess); ppProcess = ICorDebugProcess.Wrap(out_ppProcess); return ppProcess; } } public ulong BaseAddress { get { ulong pAddress; this.WrappedObject.GetBaseAddress(out pAddress); return pAddress; } } public ICorDebugAssembly Assembly { get { ICorDebugAssembly ppAssembly; Debugger.Interop.CorDebug.ICorDebugAssembly out_ppAssembly; this.WrappedObject.GetAssembly(out out_ppAssembly); ppAssembly = ICorDebugAssembly.Wrap(out_ppAssembly); return ppAssembly; } } public void GetName(uint cchName, out uint pcchName, System.IntPtr szName) { this.WrappedObject.GetName(cchName, out pcchName, szName); } public void EnableJITDebugging(int bTrackJITInfo, int bAllowJitOpts) { this.WrappedObject.EnableJITDebugging(bTrackJITInfo, bAllowJitOpts); } public void EnableClassLoadCallbacks(int bClassLoadCallbacks) { this.WrappedObject.EnableClassLoadCallbacks(bClassLoadCallbacks); } public ICorDebugFunction GetFunctionFromToken(uint methodDef) { ICorDebugFunction ppFunction; Debugger.Interop.CorDebug.ICorDebugFunction out_ppFunction; this.WrappedObject.GetFunctionFromToken(methodDef, out out_ppFunction); ppFunction = ICorDebugFunction.Wrap(out_ppFunction); return ppFunction; } public ICorDebugFunction GetFunctionFromRVA(ulong rva) { ICorDebugFunction ppFunction; Debugger.Interop.CorDebug.ICorDebugFunction out_ppFunction; this.WrappedObject.GetFunctionFromRVA(rva, out out_ppFunction); ppFunction = ICorDebugFunction.Wrap(out_ppFunction); return ppFunction; } public ICorDebugClass GetClassFromToken(uint typeDef) { ICorDebugClass ppClass; Debugger.Interop.CorDebug.ICorDebugClass out_ppClass; this.WrappedObject.GetClassFromToken(typeDef, out out_ppClass); ppClass = ICorDebugClass.Wrap(out_ppClass); return ppClass; } public ICorDebugModuleBreakpoint CreateBreakpoint() { ICorDebugModuleBreakpoint ppBreakpoint; Debugger.Interop.CorDebug.ICorDebugModuleBreakpoint out_ppBreakpoint; this.WrappedObject.CreateBreakpoint(out out_ppBreakpoint); ppBreakpoint = ICorDebugModuleBreakpoint.Wrap(out_ppBreakpoint); return ppBreakpoint; } public ICorDebugEditAndContinueSnapshot EditAndContinueSnapshot { get { ICorDebugEditAndContinueSnapshot ppEditAndContinueSnapshot; Debugger.Interop.CorDebug.ICorDebugEditAndContinueSnapshot out_ppEditAndContinueSnapshot; this.WrappedObject.GetEditAndContinueSnapshot(out out_ppEditAndContinueSnapshot); ppEditAndContinueSnapshot = ICorDebugEditAndContinueSnapshot.Wrap(out_ppEditAndContinueSnapshot); return ppEditAndContinueSnapshot; } } public object GetMetaDataInterface(ref System.Guid riid) { object ppObj; this.WrappedObject.GetMetaDataInterface(ref riid, out ppObj); return ppObj; } public uint Token { get { uint pToken; this.WrappedObject.GetToken(out pToken); return pToken; } } public int IsDynamic { get { int pDynamic; this.WrappedObject.IsDynamic(out pDynamic); return pDynamic; } } public ICorDebugValue GetGlobalVariableValue(uint fieldDef) { ICorDebugValue ppValue; Debugger.Interop.CorDebug.ICorDebugValue out_ppValue; this.WrappedObject.GetGlobalVariableValue(fieldDef, out out_ppValue); ppValue = ICorDebugValue.Wrap(out_ppValue); return ppValue; } public uint Size { get { uint pcBytes; this.WrappedObject.GetSize(out pcBytes); return pcBytes; } } public int IsInMemory { get { int pInMemory; this.WrappedObject.IsInMemory(out pInMemory); return pInMemory; } } } } #pragma warning restore 1591
24.484252
101
0.724393
[ "CC0-1.0" ]
TeamSPoon/swicli_old
src/Debugger.Core.JDWP/Debugger.Core/Wrappers/CorDebug/Autogenerated/ICorDebugModule.cs
6,220
C#
using System; using System.Threading; using System.Threading.Tasks; using MediatR; using Microsoft.Extensions.Logging; using SFA.DAS.EmploymentCheck.Functions.Application.Clients.EmploymentCheck; namespace SFA.DAS.EmploymentCheck.Functions.Mediators.Commands.SaveApprenticeEmploymentCheckResult { public class SaveApprenticeEmploymentCheckResultCommandHandler : IRequestHandler<SaveApprenticeEmploymentCheckResultCommand> { private const string ThisClassName = "\n\nSaveApprenticeEmploymentCheckResultCommandHandler"; public const string ErrorMessagePrefix = "[*** ERROR ***]"; private IEmploymentCheckClient _employmentCheckClient; private readonly ILogger<SaveApprenticeEmploymentCheckResultCommandHandler> _logger; public SaveApprenticeEmploymentCheckResultCommandHandler( IEmploymentCheckClient employmentCheckClient, ILogger<SaveApprenticeEmploymentCheckResultCommandHandler> logger) { _employmentCheckClient = employmentCheckClient; _logger = logger; } public async Task<Unit> Handle( SaveApprenticeEmploymentCheckResultCommand request, CancellationToken cancellationToken) { var thisMethodName = $"{ThisClassName}.Handle()"; try { if (request != null && request.ApprenticeEmploymentCheckMessageModel != null) { // Call the application client to save the employment check result await _employmentCheckClient.SaveApprenticeEmploymentCheckResult_Client(request.ApprenticeEmploymentCheckMessageModel); } else { _logger.LogInformation($"{thisMethodName}: {ErrorMessagePrefix} The ApprenticeEmploymentCheckMessageModel input parameter is null."); } } catch (Exception ex) { _logger.LogInformation($"{ThisClassName}: {ErrorMessagePrefix} Exception caught - {ex.Message}. {ex.StackTrace}"); } return Unit.Value; } } }
39.709091
153
0.665293
[ "MIT" ]
SkillsFundingAgency/das-employmentcheck
src/SFA.DAS.EmploymentCheck.Functions/Mediators/Commands/SaveApprenticeEmploymentCheckResult/SaveApprenticeEmploymentCheckResultCommandHandler.cs
2,186
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschränkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System.Collections.Generic; using GraphQL.Types; using Squidex.Domain.Apps.Entities.Schemas; using Squidex.Infrastructure; namespace Squidex.Domain.Apps.Entities.Contents.GraphQL.Types { public sealed class AppQueriesGraphType : ObjectGraphType { public AppQueriesGraphType(IGraphModel model, int pageSizeContents, int pageSizeAssets, IEnumerable<ISchemaEntity> schemas) { var assetType = model.GetAssetType(); AddAssetFind(assetType); AddAssetsQueries(assetType, pageSizeAssets); foreach (var schema in schemas) { var schemaId = schema.Id; var schemaType = schema.TypeName(); var schemaName = schema.DisplayName(); var contentType = model.GetContentType(schema.Id); AddContentFind(schemaType, schemaName, contentType); AddContentQueries(schemaId, schemaType, schemaName, contentType, pageSizeContents); } Description = "The app queries."; } private void AddAssetFind(IGraphType assetType) { AddField(new FieldType { Name = "findAsset", Arguments = AssetActions.Find.Arguments, ResolvedType = assetType, Resolver = AssetActions.Find.Resolver, Description = "Find an asset by id." }); } private void AddContentFind(string schemaType, string schemaName, IGraphType contentType) { AddField(new FieldType { Name = $"find{schemaType}Content", Arguments = ContentActions.Find.Arguments, ResolvedType = contentType, Resolver = ContentActions.Find.Resolver, Description = $"Find an {schemaName} content by id." }); } private void AddAssetsQueries(IGraphType assetType, int pageSize) { var resolver = AssetActions.Query.Resolver; AddField(new FieldType { Name = "queryAssets", Arguments = AssetActions.Query.Arguments(pageSize), ResolvedType = new ListGraphType(new NonNullGraphType(assetType)), Resolver = resolver, Description = "Get assets." }); AddField(new FieldType { Name = "queryAssetsWithTotal", Arguments = AssetActions.Query.Arguments(pageSize), ResolvedType = new AssetsResultGraphType(assetType), Resolver = resolver, Description = "Get assets and total count." }); } private void AddContentQueries(DomainId schemaId, string schemaType, string schemaName, IGraphType contentType, int pageSize) { var resolver = ContentActions.QueryOrReferencing.Query(schemaId); AddField(new FieldType { Name = $"query{schemaType}Contents", Arguments = ContentActions.QueryOrReferencing.Arguments(pageSize), ResolvedType = new ListGraphType(new NonNullGraphType(contentType)), Resolver = resolver, Description = $"Query {schemaName} content items." }); AddField(new FieldType { Name = $"query{schemaType}ContentsWithTotal", Arguments = ContentActions.QueryOrReferencing.Arguments(pageSize), ResolvedType = new ContentsResultGraphType(schemaType, schemaName, contentType), Resolver = resolver, Description = $"Query {schemaName} content items with total count." }); } } }
37.981818
133
0.552896
[ "MIT" ]
Smilefounder/squidex
backend/src/Squidex.Domain.Apps.Entities/Contents/GraphQL/Types/AppQueriesGraphType.cs
4,181
C#
using Volo.Abp; namespace AbpBlazorCustomizeLoginPage.EntityFrameworkCore { public abstract class AbpBlazorCustomizeLoginPageEntityFrameworkCoreTestBase : AbpBlazorCustomizeLoginPageTestBase<AbpBlazorCustomizeLoginPageEntityFrameworkCoreTestModule> { } }
27.1
177
0.852399
[ "MIT" ]
bartvanhoey/AbpBlazorCustomizeLoginPage
test/AbpBlazorCustomizeLoginPage.EntityFrameworkCore.Tests/EntityFrameworkCore/AbpBlazorCustomizeLoginPageEntityFrameworkCoreTestBase.cs
273
C#
using System; using ParallelTasks; using Sandbox.ModAPI; using VRageMath; using WeaponCore.Support; using WeaponCore.Platform; using Sandbox.Game.Entities; using VRage.Game.Entity; using VRage.Game.ModAPI; using VRage.ModAPI; using VRage.Game; using Sandbox.Common.ObjectBuilders; using VRage.Utils; using System.Collections.Generic; using Sandbox.Definitions; using Sandbox.Game.Entities.Cube; namespace WeaponCore { public partial class Session { internal void Timings() { _paused = false; Tick = (uint)(Session.ElapsedPlayTime.TotalMilliseconds * TickTimeDiv); Tick10 = Tick % 10 == 0; Tick20 = Tick % 20 == 0; Tick60 = Tick % 60 == 0; Tick120 = Tick % 120 == 0; Tick180 = Tick % 180 == 0; Tick300 = Tick % 300 == 0; Tick600 = Tick % 600 == 0; Tick1800 = Tick % 1800 == 0; Tick3600 = Tick % 3600 == 0; if (Tick60) { if (Av.ExplosionCounter - 5 >= 0) Av.ExplosionCounter -= 5; else Av.ExplosionCounter = 0; } if (++SCount == 60) SCount = 0; if (Count++ == 119) { Count = 0; UiBkOpacity = MyAPIGateway.Session.Config.UIBkOpacity; UiOpacity = MyAPIGateway.Session.Config.UIOpacity; CheckAdminRights(); } LCount++; if (LCount == 129) LCount = 0; if (!GameLoaded) { if (FirstLoop) { if (!MiscLoaded) MiscLoaded = true; InitRayCast(); GameLoaded = true; } else if (!FirstLoop) { Spawn.SpawnCamera("SpyCam", out SpyCam); FirstLoop = true; foreach (var t in AllDefinitions) { var name = t.Id.SubtypeName; var contains = name.Contains("BlockArmor"); if (contains) { AllArmorBaseDefinitions.Add(t); if (name.Contains("HeavyBlockArmor")) HeavyArmorBaseDefinitions.Add(t); } } } } if (!PlayersLoaded && KeenFuckery()) PlayersLoaded = true; if (ShieldMod && !ShieldApiLoaded && SApi.Load()) ShieldApiLoaded = true; } internal void ProfilePerformance() { var netTime1 = DsUtil.GetValue("network1"); var netTime2 = DsUtil.GetValue("network2"); var projectileTime = DsUtil.GetValue("projectiles"); var updateTime = DsUtil.GetValue("shoot"); var damageTime = DsUtil.GetValue("damage"); var drawTime = DsUtil.GetValue("draw"); var av = DsUtil.GetValue("av"); var db = DsUtil.GetValue("db"); var ai = DsUtil.GetValue("ai"); var charge = DsUtil.GetValue("charge"); var acquire = DsUtil.GetValue("acquire"); Log.LineShortDate($"(CPU-T) --- <Acq>{acquire.Median:0.0000}/{acquire.Min:0.0000}/{acquire.Max:0.0000} <DM>{damageTime.Median:0.0000}/{damageTime.Min:0.0000}/{damageTime.Max:0.0000} <DR>{drawTime.Median:0.0000}/{drawTime.Min:0.0000}/{drawTime.Max:0.0000} <AV>{av.Median:0.0000}/{av.Min:0.0000}/{av.Max:0.0000} <AI>{ai.Median:0.0000}/{ai.Min:0.0000}/{ai.Max:0.0000} <SH>{updateTime.Median:0.0000}/{updateTime.Min:0.0000}/{updateTime.Max:0.0000} <CH>{charge.Median:0.0000}/{charge.Min:0.0000}/{charge.Max:0.0000} <PR>{projectileTime.Median:0.0000}/{projectileTime.Min:0.0000}/{projectileTime.Max:0.0000} <DB>{db.Median:0.0000}/{db.Min:0.0000}/{db.Max:0.0000}> <NET1>{netTime1.Median:0.0000}/{netTime1.Min:0.0000}/{netTime1.Max:0.0000}> <NET2>{netTime2.Median:0.0000}/{netTime2.Min:0.0000}/{netTime2.Max:0.0000}>"); Log.LineShortDate($"(STATS) -------- AiReq:[{TargetRequests}] Targ:[{TargetChecks}] Bloc:[{BlockChecks}] Aim:[{CanShoot}] CCast:[{ClosestRayCasts}] RndCast[{RandomRayCasts}] TopCast[{TopRayCasts}]"); TargetRequests = 0; TargetChecks = 0; BlockChecks = 0; CanShoot = 0; ClosestRayCasts = 0; RandomRayCasts = 0; TopRayCasts = 0; TargetTransfers = 0; TargetSets = 0; TargetResets = 0; AmmoMoveTriggered = 0; AmmoPulls = 0; Load = 0d; DsUtil.Clean(); } internal void NetReport() { Log.LineShortDate("(NINFO)"); foreach (var reports in Reporter.ReportData) { var typeStr = reports.Key.ToString(); var reportList = reports.Value; int clientReceivers = 0; int serverReceivers = 0; int noneReceivers = 0; int validPackets = 0; int invalidPackets = 0; ulong dataTransfer = 0; foreach (var report in reportList) { if (report.PacketValid) validPackets++; else invalidPackets++; if (report.Receiver == NetworkReporter.Report.Received.None) noneReceivers++; else if (report.Receiver == NetworkReporter.Report.Received.Server) serverReceivers++; else clientReceivers++; dataTransfer += (uint)report.PacketSize; Reporter.ReportPool.Return(report); } var packetCount = reports.Value.Count; if (packetCount > 0) Log.LineShortDate($"(NINFO) - <{typeStr}> packets:[{packetCount}] dataTransfer:[{dataTransfer}] validPackets:[{validPackets}] invalidPackets:[{invalidPackets}] serverReceive:[{serverReceivers}({IsServer})] clientReceive:[{clientReceivers} ({IsClient})] unknownReceive:[{noneReceivers} ({IsServer})]"); } Log.LineShortDate("(NINFO)"); foreach (var list in Reporter.ReportData.Values) list.Clear(); } internal int ShortLoadAssigner() { if (_shortLoadCounter + 1 > 59) _shortLoadCounter = 0; else ++_shortLoadCounter; return _shortLoadCounter; } internal int LoadAssigner() { if (_loadCounter + 1 > 119) _loadCounter = 0; else ++_loadCounter; return _loadCounter; } private bool FindPlayer(IMyPlayer player, long id) { if (player.IdentityId == id) { Players[id] = player; SteamToPlayer[player.SteamUserId] = id; PlayerMouseStates[id] = new MouseStateData(); PlayerEventId++; if (player.SteamUserId == AuthorSteamId) AuthorPlayerId = player.IdentityId; } return false; } private void CheckAdminRights() { foreach (var item in Players) { var pLevel = item.Value.PromoteLevel; var playerId = item.Key; var player = item.Value; var wasAdmin = Admins.ContainsKey(playerId); if (pLevel == MyPromoteLevel.Admin || pLevel == MyPromoteLevel.Owner || pLevel == MyPromoteLevel.SpaceMaster) { var character = player.Character; var isAdmin = false; if (character != null) { if (MySafeZone.CheckAdminIgnoreSafezones(player.SteamUserId)) isAdmin = true; else { foreach (var gridAi in GridTargetingAIs.Values) { if (gridAi.Targets.ContainsKey((MyEntity)character) && gridAi.Weapons.Count > 0 && ((IMyTerminalBlock)gridAi.Weapons[0].MyCube).HasPlayerAccess(playerId)) { if (MyIDModule.GetRelationPlayerBlock(playerId, gridAi.MyOwner) == MyRelationsBetweenPlayerAndBlock.Enemies) { isAdmin = true; break; } } } } if (isAdmin) { Admins[playerId] = character; AdminMap[character] = player; continue; } } } if (wasAdmin) { IMyCharacter removeCharacter; IMyPlayer removePlayer; Admins.TryRemove(playerId, out removeCharacter); AdminMap.TryRemove(removeCharacter, out removePlayer); } } } internal void InitRayCast() { List<IHitInfo> tmpList = new List<IHitInfo>(); MyAPIGateway.Physics.CastRay(new Vector3D { X = 10, Y = 10, Z = 10 }, new Vector3D { X = -10, Y = -10, Z = -10 }, tmpList); while (ChargingWeaponsToReload.Count > 0) { Log.Line("charge before load"); var w = ChargingWeaponsToReload.Dequeue(); ComputeStorage(w); } /* foreach (var myEntity in MyEntities.GetEntities()) { var grid = myEntity as MyCubeGrid; if (grid != null) RemoveCoreToolbarWeapons(grid); } */ } //Would use DSUnique but to many profiler hits internal bool RemoveChargeWeapon(Weapon weapon) { int oldPos; if (ChargingWeaponsCheck.TryGetValue(weapon, out oldPos)) { ChargingWeaponsCheck.Remove(weapon); ChargingWeapons.RemoveAtFast(oldPos); var count = ChargingWeapons.Count; if (count > 0) { count--; if (oldPos <= count) ChargingWeaponsCheck[ChargingWeapons[oldPos]] = oldPos; else ChargingWeaponsCheck[ChargingWeapons[count]] = count; } return true; } return false; } internal void RemoveCoreToolbarWeapons(MyCubeGrid grid) { foreach (var cube in grid.GetFatBlocks()) { if (cube is MyShipController) { var ob = (MyObjectBuilder_ShipController)cube.GetObjectBuilderCubeBlock(); var reinit = false; for (int i = 0; i < ob.Toolbar.Slots.Count; i++) { var toolbarItem = ob.Toolbar.Slots[i].Data as MyObjectBuilder_ToolbarItemWeapon; if (toolbarItem != null) { var defId = (MyDefinitionId)toolbarItem.defId; if ((ReplaceVanilla && VanillaIds.ContainsKey(defId)) || WeaponPlatforms.ContainsKey(defId.SubtypeId)) { var index = ob.Toolbar.Slots[i].Index; var item = ob.Toolbar.Slots[i].Item; ob.Toolbar.Slots[i] = new MyObjectBuilder_Toolbar.Slot { Index = index, Item = item }; reinit = true; } } } if (reinit) cube.Init(ob, grid); } } } internal bool KeenFuckery() { try { if (Session?.Player == null) return false; MultiplayerId = MyAPIGateway.Multiplayer.MyId; PlayerId = Session.Player.IdentityId; if (HandlesInput) { List<IMyPlayer> players = new List<IMyPlayer>(); MyAPIGateway.Multiplayer.Players.GetPlayers(players); for (int i = 0; i < players.Count; i++) PlayerConnected(players[i].IdentityId); PlayerMouseStates[PlayerId] = UiInput.ClientMouseState; } PlayerMouseStates[-1] = new MouseStateData(); if (IsClient) SendUpdateRequest(-1, PacketType.RequestMouseStates); return true; } catch (Exception ex) { Log.Line($"Exception in UpdatingStopped: {ex} - Session:{Session != null} - Player:{Session?.Player != null} - ClientMouseState:{UiInput.ClientMouseState != null}"); } return false; } internal void ReallyStupidKeenShit() //aka block group removal of individual blocks { var categories = MyDefinitionManager.Static.GetCategories(); var removeDefs = new HashSet<MyDefinitionId>(MyDefinitionId.Comparer); var keepDefs = new HashSet<string>(); foreach (var weaponDef in WeaponDefinitions) { foreach (var mount in weaponDef.Assignments.MountPoints) { var subTypeId = mount.SubtypeId; MyDefinitionId defId = new MyDefinitionId(); if ((ReplaceVanilla && VanillaCoreIds.TryGetValue(MyStringHash.GetOrCompute(subTypeId), out defId))) removeDefs.Add(defId); else { foreach (var def in AllDefinitions) { if (def.Id.SubtypeName == subTypeId) { removeDefs.Add(def.Id); break; } } } } } foreach (var def in AllDefinitions) if (!removeDefs.Contains(def.Id)) keepDefs.Add(def.Id.SubtypeName); foreach (var category in categories) { if (category.Value.IsShipCategory) { var removeList = new List<string>(); foreach (var item in category.Value.ItemIds) { foreach (var def in removeDefs) { var type = def.TypeId.ToString().Replace("MyObjectBuilder_", ""); var subType = string.IsNullOrEmpty(def.SubtypeName) ? "(null)" : def.SubtypeName; if ((item.Contains(type) || item.Contains(subType))) removeList.Add(item); } } foreach (var keep in keepDefs) { for (int i = 0; i < removeList.Count; i++) { var toRemove = removeList[i]; if (!string.IsNullOrEmpty(keep) && toRemove.EndsWith(keep)) removeList.RemoveAtFast(i); } } for (int i = 0; i < removeList.Count; i++) category.Value.ItemIds.Remove(removeList[i]); } } } internal static double ModRadius(double radius, bool largeBlock) { if (largeBlock && radius < 3) radius = 3; else if (largeBlock && radius > 25) radius = 25; else if (!largeBlock && radius > 5) radius = 5; radius = Math.Ceiling(radius); return radius; } public void WeaponDebug(Weapon w) { DsDebugDraw.DrawLine(w.MyPivotTestLine, Color.Red, 0.05f); DsDebugDraw.DrawLine(w.MyBarrelTestLine, Color.Blue, 0.05f); DsDebugDraw.DrawLine(w.MyCenterTestLine, Color.Green, 0.05f); DsDebugDraw.DrawLine(w.MyAimTestLine, Color.Black, 0.07f); //DsDebugDraw.DrawSingleVec(w.MyPivotPos, 1f, Color.White); //DsDebugDraw.DrawBox(w.targetBox, Color.Plum); DsDebugDraw.DrawLine(w.LimitLine.From, w.LimitLine.To, Color.Orange, 0.05f); if (w.Target.HasTarget) DsDebugDraw.DrawLine(w.MyShootAlignmentLine, Color.Yellow, 0.05f); } public string ModPath() { var modPath = ModContext.ModPath; return modPath; } private void Paused() { Pause = true; Log.Line($"Stopping all AV due to pause"); /* foreach (var aiPair in GridTargetingAIs) { var gridAi = aiPair.Value; foreach (var comp in gridAi.WeaponBase.Values) comp.StopAllAv(); } foreach (var p in Projectiles.ActiveProjetiles) { p.ParticleStopped = true; if (p.AmmoEffect != null) { p.AmmoEffect.Stop(); p.AmmoEffect = null; } if (p.Info.AvShot?.HitEffect != null) { p.Info.AvShot.HitEffect.Stop(); p.Info.AvShot.HitEffect = null; } } */ if (WheelUi.WheelActive && WheelUi.Ai != null) WheelUi.CloseWheel(); } public bool TaskHasErrors(ref Task task, string taskName) { if (task.Exceptions != null && task.Exceptions.Length > 0) { foreach (var e in task.Exceptions) { Log.Line($"{taskName} thread!\n{e}"); } return true; } return false; } internal MyEntity TriggerEntityActivator() { var ent = new MyEntity(); ent.Init(null, TriggerEntityModel, null, null, null); ent.Render.CastShadows = false; ent.IsPreview = true; ent.Save = false; ent.SyncFlag = false; ent.NeedsWorldMatrix = false; ent.Flags |= EntityFlags.IsNotGamePrunningStructureObject; MyEntities.Add(ent); ent.PositionComp.SetWorldMatrix(MatrixD.Identity, null, false, false, false); ent.InScene = false; ent.Render.RemoveRenderObjects(); return ent; } internal void TriggerEntityClear(MyEntity myEntity) { myEntity.PositionComp.SetWorldMatrix(MatrixD.Identity, null, false, false, false); myEntity.InScene = false; myEntity.Render.RemoveRenderObjects(); } internal void LoadVanillaData() { var smallMissileId = new MyDefinitionId(typeof(MyObjectBuilder_SmallMissileLauncher), null); var smallGatId = new MyDefinitionId(typeof(MyObjectBuilder_SmallGatlingGun), null); var largeGatId = new MyDefinitionId(typeof(MyObjectBuilder_LargeGatlingTurret), null); var largeMissileId = new MyDefinitionId(typeof(MyObjectBuilder_LargeMissileTurret), null); var smallMissileHash = MyStringHash.GetOrCompute("SmallMissileLauncher"); var smallGatHash = MyStringHash.GetOrCompute("SmallGatlingGun"); var largeGatHash = MyStringHash.GetOrCompute("LargeGatlingTurret"); var smallGatTurretHash = MyStringHash.GetOrCompute("SmallGatlingTurret"); var largeMissileHash = MyStringHash.GetOrCompute("LargeMissileTurret"); VanillaIds[smallMissileId] = smallMissileHash; VanillaIds[smallGatId] = smallGatHash; VanillaIds[largeGatId] = largeGatHash; VanillaIds[largeMissileId] = largeMissileHash; VanillaCoreIds[smallMissileHash] = smallMissileId; VanillaCoreIds[smallGatHash] = smallGatId; VanillaCoreIds[largeGatHash] = largeGatId; VanillaCoreIds[largeMissileHash] = largeMissileId; VanillaSubpartNames.Add("InteriorTurretBase1"); VanillaSubpartNames.Add("InteriorTurretBase2"); VanillaSubpartNames.Add("MissileTurretBase1"); VanillaSubpartNames.Add("MissileTurretBarrels"); VanillaSubpartNames.Add("GatlingTurretBase1"); VanillaSubpartNames.Add("GatlingTurretBase2"); VanillaSubpartNames.Add("GatlingBarrel"); } private MyCameraBlock CameraEntityActivator() { var ent = new MyEntity(); ent.Init(null, null, null, null, null); ent.Render.CastShadows = false; ent.IsPreview = true; ent.Save = false; ent.SyncFlag = false; ent.NeedsWorldMatrix = false; ent.Flags |= EntityFlags.IsNotGamePrunningStructureObject; MyEntities.Add(ent, false); return ent as MyCameraBlock; } } }
38.55814
824
0.503804
[ "MIT" ]
B4Rme/WeaponCore
Data/Scripts/WeaponCore/Session/SessionSupport.cs
21,556
C#
using IdentityModel; using IdentityServer4.Models; using IdentityServer4.Services; using MagusAppGateway.Models; using MagusAppGateway.Services.IServices; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; namespace MagusAppGateway.Auth { public class ProfileService : IProfileService { private readonly IUserService _userService; private readonly IRoleService _roleService; public ProfileService(IUserService userService, IRoleService roleService) { _userService = userService; _roleService = roleService; } public async Task GetProfileDataAsync(ProfileDataRequestContext context) { #region 旧版本,没有用户验证 await Task.Run(() => { try { //depending on the scope accessing the user data. var claims = context.Subject.Claims.ToList(); //set issued claims to return context.IssuedClaims = claims.ToList(); } catch (Exception) { } }); #endregion } public async Task IsActiveAsync(IsActiveContext context) { await Task.Run(() => { context.IsActive = true; }); } } }
27.036364
81
0.555481
[ "MIT" ]
ShadowGB/MagusAppGateway
MagusAppGateway.Auth/ProfileService.cs
1,509
C#
namespace StripeTests { using Stripe; using Stripe.Infrastructure.FormEncoding; using Xunit; public class CouponCreateOptionsTest : BaseStripeTest { [Fact] public void Serialize() { var options = new CouponCreateOptions { PercentOff = 25, Duration = "forever", }; Assert.Equal("duration=forever&percent_off=25", FormEncoder.CreateQueryString(options)); } } }
22.590909
100
0.567404
[ "Apache-2.0" ]
GigiAkamala/stripe-dotnet
src/StripeTests/Services/Coupons/CouponCreateOptionsTest.cs
497
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WSIP.Model { class SaveInfo { private static string _saveFolder { get { return System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "WSIP"); } } public static string SaveFolder { get { return _saveFolder; } } public static string SettingsFile { get { return Path.Combine(_saveFolder, "settings.json"); } } } }
20.054054
129
0.525606
[ "MIT" ]
ChrisStayte/WSIP
WSIP/Model/SaveInfo.cs
744
C#
// <copyright file = "TriggerSchema.cs" company = "Terry D. Eppler"> // Copyright (c) Terry D. Eppler. All rights reserved. // </copyright> namespace BudgetExecution { public enum TriggerEvent { Delete, Update, Insert } public enum TriggerType { After, Before } public class TriggerSchema { public string body; public TriggerEvent @event; public string name; public string table; public TriggerType type; } }
20.695652
69
0.647059
[ "MIT" ]
KarmaScripter/Data
conversion/sdf/TriggerSchema.cs
478
C#
using System.Globalization; using BeUtl.Utilities; namespace BeUtl.Graphics; /// <summary> /// Defines a rectangle that may be defined relative to a containing element. /// </summary> public readonly struct RelativeRect : IEquatable<RelativeRect> { private static readonly char[] s_percentChar = { '%' }; /// <summary> /// A rectangle that represents 100% of an area. /// </summary> public static readonly RelativeRect Fill = new(0, 0, 1, 1, RelativeUnit.Relative); /// <summary> /// Initializes a new instance of the <see cref="RelativeRect"/> structure. /// </summary> /// <param name="x">The X position.</param> /// <param name="y">The Y position.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="unit">The unit of the rect.</param> public RelativeRect(float x, float y, float width, float height, RelativeUnit unit) { Rect = new Rect(x, y, width, height); Unit = unit; } /// <summary> /// Initializes a new instance of the <see cref="RelativeRect"/> structure. /// </summary> /// <param name="rect">The rectangle.</param> /// <param name="unit">The unit of the rect.</param> public RelativeRect(Rect rect, RelativeUnit unit) { Rect = rect; Unit = unit; } /// <summary> /// Initializes a new instance of the <see cref="RelativeRect"/> structure. /// </summary> /// <param name="size">The size of the rectangle.</param> /// <param name="unit">The unit of the rect.</param> public RelativeRect(Size size, RelativeUnit unit) { Rect = new Rect(size); Unit = unit; } /// <summary> /// Initializes a new instance of the <see cref="RelativeRect"/> structure. /// </summary> /// <param name="position">The position of the rectangle.</param> /// <param name="size">The size of the rectangle.</param> /// <param name="unit">The unit of the rect.</param> public RelativeRect(Point position, Size size, RelativeUnit unit) { Rect = new Rect(position, size); Unit = unit; } /// <summary> /// Initializes a new instance of the <see cref="RelativeRect"/> structure. /// </summary> /// <param name="topLeft">The top left position of the rectangle.</param> /// <param name="bottomRight">The bottom right position of the rectangle.</param> /// <param name="unit">The unit of the rect.</param> public RelativeRect(Point topLeft, Point bottomRight, RelativeUnit unit) { Rect = new Rect(topLeft, bottomRight); Unit = unit; } /// <summary> /// Gets the unit of the rectangle. /// </summary> public RelativeUnit Unit { get; } /// <summary> /// Gets the rectangle. /// </summary> public Rect Rect { get; } /// <summary> /// Checks for equality between two <see cref="RelativeRect"/>s. /// </summary> /// <param name="left">The first rectangle.</param> /// <param name="right">The second rectangle.</param> /// <returns>True if the rectangles are equal; otherwise false.</returns> public static bool operator ==(RelativeRect left, RelativeRect right) { return left.Equals(right); } /// <summary> /// Checks for inequality between two <see cref="RelativeRect"/>s. /// </summary> /// <param name="left">The first rectangle.</param> /// <param name="right">The second rectangle.</param> /// <returns>True if the rectangles are unequal; otherwise false.</returns> public static bool operator !=(RelativeRect left, RelativeRect right) { return !left.Equals(right); } /// <summary> /// Checks if the <see cref="RelativeRect"/> equals another object. /// </summary> /// <param name="obj">The other object.</param> /// <returns>True if the objects are equal, otherwise false.</returns> public override bool Equals(object? obj) => obj is RelativeRect other && Equals(other); /// <summary> /// Checks if the <see cref="RelativeRect"/> equals another rectangle. /// </summary> /// <param name="p">The other rectangle.</param> /// <returns>True if the objects are equal, otherwise false.</returns> public bool Equals(RelativeRect p) { return Unit == p.Unit && Rect == p.Rect; } /// <summary> /// Gets a hashcode for a <see cref="RelativeRect"/>. /// </summary> /// <returns>A hash code.</returns> public override int GetHashCode() { unchecked { return ((int)Unit * 397) ^ Rect.GetHashCode(); } } /// <summary> /// Converts a <see cref="RelativeRect"/> into pixels. /// </summary> /// <param name="size">The size of the visual.</param> /// <returns>The origin point in pixels.</returns> public Rect ToPixels(Size size) { return Unit == RelativeUnit.Absolute ? Rect : new Rect( Rect.X * size.Width, Rect.Y * size.Height, Rect.Width * size.Width, Rect.Height * size.Height); } /// <summary> /// Parses a <see cref="RelativeRect"/> string. /// </summary> /// <param name="s">The string.</param> /// <param name="rect">The <see cref="RelativeRect"/>.</param> /// <returns>The status of the operation.</returns> public static bool TryParse(string s, out RelativeRect rect) { return TryParse(s.AsSpan(), out rect); } /// <summary> /// Parses a <see cref="RelativeRect"/> string. /// </summary> /// <param name="s">The string.</param> /// <param name="rect">The <see cref="RelativeRect"/>.</param> /// <returns>The status of the operation.</returns> public static bool TryParse(ReadOnlySpan<char> s, out RelativeRect rect) { try { rect = Parse(s); return true; } catch { rect = default; return false; } } /// <summary> /// Parses a <see cref="RelativeRect"/> string. /// </summary> /// <param name="s">The string.</param> /// <returns>The parsed <see cref="RelativeRect"/>.</returns> public static RelativeRect Parse(string s) { return Parse(s.AsSpan()); } /// <summary> /// Parses a <see cref="RelativeRect"/> string. /// </summary> /// <param name="s">The string.</param> /// <returns>The parsed <see cref="RelativeRect"/>.</returns> public static RelativeRect Parse(ReadOnlySpan<char> s) { using (var tokenizer = new RefStringTokenizer(s, exceptionMessage: "Invalid RelativeRect.")) { ReadOnlySpan<char> x = tokenizer.ReadString(); ReadOnlySpan<char> y = tokenizer.ReadString(); ReadOnlySpan<char> width = tokenizer.ReadString(); ReadOnlySpan<char> height = tokenizer.ReadString(); RelativeUnit unit = RelativeUnit.Absolute; float scale = 1.0f; bool xRelative = x.EndsWith("%", StringComparison.Ordinal); bool yRelative = y.EndsWith("%", StringComparison.Ordinal); bool widthRelative = width.EndsWith("%", StringComparison.Ordinal); bool heightRelative = height.EndsWith("%", StringComparison.Ordinal); if (xRelative && yRelative && widthRelative && heightRelative) { x = x.TrimEnd(s_percentChar); y = y.TrimEnd(s_percentChar); width = width.TrimEnd(s_percentChar); height = height.TrimEnd(s_percentChar); unit = RelativeUnit.Relative; scale = 0.01f; } else if (xRelative || yRelative || widthRelative || heightRelative) { throw new FormatException("If one coordinate is relative, all must be."); } return new RelativeRect( float.Parse(x, provider: CultureInfo.InvariantCulture) * scale, float.Parse(y, provider: CultureInfo.InvariantCulture) * scale, float.Parse(width, provider: CultureInfo.InvariantCulture) * scale, float.Parse(height, provider: CultureInfo.InvariantCulture) * scale, unit); } } /// <summary> /// Returns a String representing this RelativeRect instance. /// </summary> /// <returns>The string representation.</returns> public override string ToString() { return Unit == RelativeUnit.Absolute ? Rect.ToString() : FormattableString.Invariant($"{Rect.X * 100}%, {Rect.Y * 100}%, {Rect.Width * 100}%, {Rect.Height * 100}%"); } }
34.57874
120
0.587612
[ "MIT" ]
YiB-PC/BeUtl
src/BeUtl.Graphics/Graphics/RelativeRect.cs
8,785
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cloudfront-2020-05-31.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.CloudFront.Model { /// <summary> /// A list of key groups whose public keys CloudFront can use to verify the signatures /// of signed URLs and signed cookies. /// </summary> public partial class TrustedKeyGroups { private bool? _enabled; private List<string> _items = new List<string>(); private int? _quantity; /// <summary> /// Gets and sets the property Enabled. /// <para> /// This field is <code>true</code> if any of the key groups in the list have public keys /// that CloudFront can use to verify the signatures of signed URLs and signed cookies. /// If not, this field is <code>false</code>. /// </para> /// </summary> [AWSProperty(Required=true)] public bool Enabled { get { return this._enabled.GetValueOrDefault(); } set { this._enabled = value; } } // Check to see if Enabled property is set internal bool IsSetEnabled() { return this._enabled.HasValue; } /// <summary> /// Gets and sets the property Items. /// <para> /// A list of key groups identifiers. /// </para> /// </summary> public List<string> Items { get { return this._items; } set { this._items = value; } } // Check to see if Items property is set internal bool IsSetItems() { return this._items != null && this._items.Count > 0; } /// <summary> /// Gets and sets the property Quantity. /// <para> /// The number of key groups in the list. /// </para> /// </summary> [AWSProperty(Required=true)] public int Quantity { get { return this._quantity.GetValueOrDefault(); } set { this._quantity = value; } } // Check to see if Quantity property is set internal bool IsSetQuantity() { return this._quantity.HasValue; } } }
31.1
109
0.575241
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/CloudFront/Generated/Model/TrustedKeyGroups.cs
3,110
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api20210201Preview { using Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.PowerShell; /// <summary>BackupPolicy base</summary> [System.ComponentModel.TypeConverter(typeof(BaseBackupPolicyTypeConverter))] public partial class BaseBackupPolicy { /// <summary> /// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the /// object before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); /// <summary> /// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); /// <summary> /// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); /// <summary> /// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api20210201Preview.BaseBackupPolicy" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> internal BaseBackupPolicy(global::System.Collections.IDictionary content) { bool returnNow = false; BeforeDeserializeDictionary(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api20210201Preview.IBaseBackupPolicyInternal)this).DatasourceType = (string[]) content.GetValueForProperty("DatasourceType",((Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api20210201Preview.IBaseBackupPolicyInternal)this).DatasourceType, __y => TypeConverterExtensions.SelectToArray<string>(__y, global::System.Convert.ToString)); ((Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api20210201Preview.IBaseBackupPolicyInternal)this).ObjectType = (string) content.GetValueForProperty("ObjectType",((Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api20210201Preview.IBaseBackupPolicyInternal)this).ObjectType, global::System.Convert.ToString); AfterDeserializeDictionary(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api20210201Preview.BaseBackupPolicy" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> internal BaseBackupPolicy(global::System.Management.Automation.PSObject content) { bool returnNow = false; BeforeDeserializePSObject(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api20210201Preview.IBaseBackupPolicyInternal)this).DatasourceType = (string[]) content.GetValueForProperty("DatasourceType",((Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api20210201Preview.IBaseBackupPolicyInternal)this).DatasourceType, __y => TypeConverterExtensions.SelectToArray<string>(__y, global::System.Convert.ToString)); ((Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api20210201Preview.IBaseBackupPolicyInternal)this).ObjectType = (string) content.GetValueForProperty("ObjectType",((Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api20210201Preview.IBaseBackupPolicyInternal)this).ObjectType, global::System.Convert.ToString); AfterDeserializePSObject(content); } /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api20210201Preview.BaseBackupPolicy" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api20210201Preview.IBaseBackupPolicy" /// />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api20210201Preview.IBaseBackupPolicy DeserializeFromDictionary(global::System.Collections.IDictionary content) { return new BaseBackupPolicy(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api20210201Preview.BaseBackupPolicy" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api20210201Preview.IBaseBackupPolicy" /// />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api20210201Preview.IBaseBackupPolicy DeserializeFromPSObject(global::System.Management.Automation.PSObject content) { return new BaseBackupPolicy(content); } /// <summary> /// Creates a new instance of <see cref="BaseBackupPolicy" />, deserializing the content from a json string. /// </summary> /// <param name="jsonText">a string containing a JSON serialized instance of this model.</param> /// <returns>an instance of the <see cref="className" /> model class.</returns> public static Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api20210201Preview.IBaseBackupPolicy FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.Json.JsonNode.Parse(jsonText)); /// <summary>Serializes this instance to a json string.</summary> /// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns> public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.SerializationMode.IncludeAll)?.ToString(); } /// BackupPolicy base [System.ComponentModel.TypeConverter(typeof(BaseBackupPolicyTypeConverter))] public partial interface IBaseBackupPolicy { } }
66.837037
414
0.700654
[ "MIT" ]
Khushboo-Baheti/azure-powershell
src/DataProtection/generated/api/Models/Api20210201Preview/BaseBackupPolicy.PowerShell.cs
8,889
C#
using System.Collections.Generic; namespace EnterpriseWebLibrary.EnterpriseWebFramework { /// <summary> /// A style that displays a hyperlink in a custom way. /// </summary> public class CustomHyperlinkStyle: HyperlinkStyle { private readonly ElementClassSet classes; private readonly IReadOnlyCollection<FlowComponent> children; /// <summary> /// Creates a custom style object. /// </summary> /// <param name="classes">The classes on the hyperlink.</param> /// <param name="children"></param> public CustomHyperlinkStyle( ElementClassSet classes = null, IReadOnlyCollection<FlowComponent> children = null ) { this.classes = classes; this.children = children; } ElementClassSet HyperlinkStyle.GetClasses() { return ActionComponentCssElementCreator.AllStylesClass.Add( classes ?? ElementClassSet.Empty ); } IReadOnlyCollection<FlowComponent> HyperlinkStyle.GetChildren( string destinationUrl ) { return children; } string HyperlinkStyle.GetJsInitStatements( string id ) { return ""; } } }
32.575758
118
0.72186
[ "MIT" ]
enduracode/enterprise-web-library
Core/EnterpriseWebFramework/Action Components/Hyperlink/Styles/CustomHyperlinkStyle.cs
1,077
C#
/* Copyright (c) Microsoft Corporation * * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ using System; using System.IO; namespace MiFare.PcSc { public class AtrInfo { public const int MaximumAtrCodes = 4; /// <summary> /// Helper class that holds information about the ICC Answer-To-Reset (ATR) information such /// as interface character and offset and length of the historical bytes. It also hold info /// about the validity of the TCK byte. /// </summary> public AtrInfo() { ProtocolInterfaceA = new byte[MaximumAtrCodes] {0, 0, 0, 0}; ProtocolInterfaceB = new byte[MaximumAtrCodes] {0, 0, 0, 0}; ProtocolInterfaceC = new byte[MaximumAtrCodes] {0, 0, 0, 0}; ProtocolInterfaceD = new byte[MaximumAtrCodes] {0, 0, 0, 0}; HistoricalBytes = null; } /// <summary> /// Protocol interface characters TAi /// </summary> public byte[] ProtocolInterfaceA { set; get; } /// <summary> /// Protocol interface characters TBi /// </summary> public byte[] ProtocolInterfaceB { set; get; } /// <summary> /// Protocol interface characters TCi /// </summary> public byte[] ProtocolInterfaceC { set; get; } /// <summary> /// Protocol interface characters TDi /// </summary> public byte[] ProtocolInterfaceD { set; get; } /// <summary> /// Historical bytes if present /// </summary> public byte[] HistoricalBytes { set; get; } /// <summary> /// Check Byte valid /// </summary> public bool? TckValid { set; get; } } /// <summary> /// Helper class that parses the ATR and populate the AtrInfo class /// </summary> internal static class AtrParser { /// <summary> /// Main parser method that extract information about the ATR byte array /// </summary> /// <returns> /// returns AtrInfo object if ATR is valid, null otherwise /// </returns> public static AtrInfo Parse(byte[] atrBytes) { if (atrBytes == null || atrBytes.Length < 1) return null; var atrInfo = new AtrInfo(); var supportedProtocols = 0; using (var reader = new BinaryReader(new MemoryStream(atrBytes))) { var initialChar = reader.ReadByte(); if (initialChar != (byte)AtrHeader.InitialHeader) { return null; } var formatByte = reader.ReadByte(); var interfacePresence = (byte)(formatByte.HiNibble() << 4); for (var i = 0; i < AtrInfo.MaximumAtrCodes; i++) { if ((interfacePresence & 0x10) != 0) atrInfo.ProtocolInterfaceA[i] = reader.ReadByte(); if ((interfacePresence & 0x20) != 0) atrInfo.ProtocolInterfaceB[i] = reader.ReadByte(); if ((interfacePresence & 0x40) != 0) atrInfo.ProtocolInterfaceC[i] = reader.ReadByte(); if ((interfacePresence & 0x80) != 0) atrInfo.ProtocolInterfaceD[i] = reader.ReadByte(); else break; interfacePresence = atrInfo.ProtocolInterfaceD[i]; supportedProtocols |= (1 << interfacePresence.LowNibble()); } var buffer = new byte[formatByte.LowNibble()]; reader.Read(buffer, 0, buffer.Length); atrInfo.HistoricalBytes = buffer; if ((supportedProtocols & ~1) != 0) { atrInfo.TckValid = ValidateTCK(atrBytes); } return atrInfo; } } /// <summary> /// Compute the ATR check byte (TCK) /// </summary> /// <returns> /// return the computed TCK /// </returns> private static bool ValidateTCK(byte[] atr) { byte ctk = 0; for (byte i = 1; i < atr.Length; i++) { ctk ^= atr[i]; } return (ctk == 0); } private enum AtrHeader : byte { InitialHeader = 0x3B } } /// <summary> /// Extensions to the Byte primitive data type /// </summary> public static class ByteExtension { public const byte NibbleSize = 4; /// <summary> /// Extracts the high nibble of a byte /// </summary> /// <returns> /// return byte represeting the high nibble of a byte /// </returns> public static byte HiNibble(this byte value) { return (byte)(value >> 4); } /// <summary> /// Extracts the low nibble of a byte /// </summary> /// <returns> /// return byte represeting the low nibble of a byte /// </returns> public static byte LowNibble(this byte value) { return (byte)(value & 0x0F); } } }
32.461957
258
0.523523
[ "MIT" ]
novotnyllc/MiFare
src/MiFare/PcSc/AtrParser.cs
5,975
C#
namespace Logger.Core { using Contracts; using System; public class Engine : IEngine { private ICommandInterpreter commandIterpreter; public Engine(ICommandInterpreter commandIterpreter) { this.commandIterpreter = commandIterpreter; } public void Run() { int n = int.Parse(Console.ReadLine()); for (int i = 0; i < n; i++) { string[] inputArgs = Console.ReadLine().Split(); this.commandIterpreter.AddAppender(inputArgs); } string input = Console.ReadLine(); while (input != "END") { string[] inputArgs = input.Split('|'); this.commandIterpreter.AddMessage(inputArgs); input = Console.ReadLine(); } this.commandIterpreter.PrintInfo(); } } }
23.125
64
0.516757
[ "MIT" ]
NikolayMirchev/CSharp-OOP
06. Solid/Solid/Problem 01.Logger/Core/Engine.cs
927
C#
using JetBrains.Application.Settings; using JetBrains.ReSharper.Daemon.Stages; using JetBrains.ReSharper.Daemon.Stages.Dispatcher; using JetBrains.ReSharper.Daemon.UsageChecking; using JetBrains.ReSharper.Feature.Services.Daemon; using JetBrains.ReSharper.Plugins.Yaml.Psi.Tree; using JetBrains.ReSharper.Psi.Tree; namespace JetBrains.ReSharper.Plugins.Yaml.Daemon.Stages { [DaemonStage(StagesBefore = new[] {typeof(CollectUsagesStage), typeof(GlobalFileStructureCollectorStage)}, StagesAfter = new[] {typeof(LanguageSpecificDaemonStage)})] public class YamlErrorStage : YamlDaemonStageBase { private readonly ElementProblemAnalyzerRegistrar myElementProblemAnalyzerRegistrar; public YamlErrorStage(ElementProblemAnalyzerRegistrar elementProblemAnalyzerRegistrar) { myElementProblemAnalyzerRegistrar = elementProblemAnalyzerRegistrar; } protected override IDaemonStageProcess CreateProcess(IDaemonProcess process, IContextBoundSettingsStore settings, DaemonProcessKind processKind, IYamlFile file) { return new YamlErrorStageProcess(process, processKind, myElementProblemAnalyzerRegistrar, settings, file); } private class YamlErrorStageProcess : YamlDaemonStageProcessBase { private readonly IElementAnalyzerDispatcher myElementAnalyzerDispatcher; public YamlErrorStageProcess(IDaemonProcess process, DaemonProcessKind processKind, ElementProblemAnalyzerRegistrar elementProblemAnalyzerRegistrar, IContextBoundSettingsStore settings, IYamlFile file) : base(process, file) { var elementProblemAnalyzerData = new ElementProblemAnalyzerData(file, settings, ElementProblemAnalyzerRunKind.FullDaemon); elementProblemAnalyzerData.SetDaemonProcess(process, processKind); myElementAnalyzerDispatcher = elementProblemAnalyzerRegistrar.CreateDispatcher(elementProblemAnalyzerData); } public override void VisitNode(ITreeNode node, IHighlightingConsumer consumer) { myElementAnalyzerDispatcher.Run(node, consumer); } } } }
44.085106
207
0.805985
[ "Apache-2.0" ]
citizenmatt/resharper-yaml
src/Daemon/Stages/YamlErrorStage.cs
2,074
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Cardville.Engine; using Cardville.Player; using Cardville.Cards; namespace Cardville.Dungeon.WFViewController { public static class PainterSelector { public static GameObjectPainter GetPainter(IInteractive gameObject) { switch (gameObject) { case PlayerObject playerObject: return new PlayerPainter(playerObject); case Card card: return new CardPainter(card); default: return new GameObjectPainter(gameObject); } } } }
25.821429
75
0.615491
[ "MIT" ]
coca-in-a-cola/Cardville
Cardville.Dungeon.WFViewController/PainterSelector.cs
725
C#
using RimWorld; using Verse; using ChildrenOfTheMachineGod; namespace Extension { public static class FactionExtention { public static Faction OfCotMG(this Faction f) => Find.FactionManager.FirstFactionOfDef(CotMG_FactionDefOf.ChildrenOfTheMachineGod); } }
22.461538
98
0.739726
[ "MIT" ]
SomethingCrunchy/HMC_ChildrenoftheMachineGod
Source/ChildrenOfTheMachineGod/ChildrenOfTheMachineGod/Faction_OfCotMG.cs
294
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text.Encodings.Web; using System.Threading.Tasks; using Core2ViewComponent.Services; namespace Core2ViewComponent.Services { public static class EmailSenderExtensions { public static Task SendEmailConfirmationAsync(this IEmailSender emailSender, string email, string link) { return emailSender.SendEmailAsync(email, "Confirm your email", $"Please confirm your account by clicking this link: <a href='{HtmlEncoder.Default.Encode(link)}'>link</a>"); } } }
31.526316
125
0.722871
[ "MIT" ]
kalimist123/loginViewComponent
Core2ViewComponent/Core2ViewComponent/Extensions/EmailSenderExtensions.cs
599
C#
//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.42000 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ namespace Shadowsocks.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.3.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("600")] public int LogViewerWidth { get { return ((int)(this["LogViewerWidth"])); } set { this["LogViewerWidth"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("400")] public int LogViewerHeight { get { return ((int)(this["LogViewerHeight"])); } set { this["LogViewerHeight"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("True")] public bool LogViewerMaximized { get { return ((bool)(this["LogViewerMaximized"])); } set { this["LogViewerMaximized"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("0")] public int LogViewerTop { get { return ((int)(this["LogViewerTop"])); } set { this["LogViewerTop"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("0")] public int LogViewerLeft { get { return ((int)(this["LogViewerLeft"])); } set { this["LogViewerLeft"] = value; } } } }
36.229885
151
0.552348
[ "Apache-2.0" ]
Snake-zzp/shadowsocks-windows
shadowsocks-csharp/Properties/Settings.Designer.cs
3,260
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace HashAndSalt { static class Utility { // utilty function to convert string to byte[] public static byte[] GetBytes(string str) { byte[] bytes = new byte[str.Length * sizeof(char)]; System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); return bytes; } // utilty function to convert byte[] to string public static string GetString(byte[] bytes) { char[] chars = new char[bytes.Length / sizeof(char)]; System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length); return new string(chars); } } }
28.481481
82
0.581274
[ "Unlicense" ]
anandgithub27/online-training
Ref/HashAndSaltSample/HashAndSaltSample/HashAndSalt/Utility.cs
771
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEngine; using UnityEngine.VR.WSA.Input; using HoloToolkit.Unity; /// <summary> /// GestureManager creates a gesture recognizer and signs up for a tap gesture. /// When a tap gesture is detected, GestureManager uses GazeManager to find the game object. /// GestureManager then sends a message to that game object. /// </summary> [RequireComponent(typeof(GazeManager))] public partial class RaySendingGestureManager : Singleton<RaySendingGestureManager> { /// <summary> /// To select even when a hologram is not being gazed at, /// set the override focused object. /// If its null, then the gazed at object will be selected. /// </summary> public GameObject OverrideFocusedObject { get; set; } /// <summary> /// Gets the currently focused object, or null if none. /// </summary> public GameObject FocusedObject { get { return focusedObject; } } private GestureRecognizer gestureRecognizer; private GameObject focusedObject; void Start() { // Create a new GestureRecognizer. Sign up for tapped events. gestureRecognizer = new GestureRecognizer(); gestureRecognizer.SetRecognizableGestures(GestureSettings.Tap); gestureRecognizer.TappedEvent += GestureRecognizer_TappedEvent; // Start looking for gestures. gestureRecognizer.StartCapturingGestures(); } private void GestureRecognizer_TappedEvent(InteractionSourceKind source, int tapCount, Ray headRay) { if (focusedObject != null) { focusedObject.SendMessage("OnSelect", headRay); } } void LateUpdate() { GameObject oldFocusedObject = focusedObject; if (GazeManager.Instance.Hit && OverrideFocusedObject == null && GazeManager.Instance.HitInfo.collider != null) { // If gaze hits a hologram, set the focused object to that game object. // Also if the caller has not decided to override the focused object. focusedObject = GazeManager.Instance.HitInfo.collider.gameObject; } else { // If our gaze doesn't hit a hologram, set the focused object to null or override focused object. focusedObject = OverrideFocusedObject; } if (focusedObject != oldFocusedObject) { // If the currently focused object doesn't match the old focused object, cancel the current gesture. // Start looking for new gestures. This is to prevent applying gestures from one hologram to another. gestureRecognizer.CancelGestures(); gestureRecognizer.StartCapturingGestures(); } } void OnDestroy() { gestureRecognizer.StopCapturingGestures(); gestureRecognizer.TappedEvent -= GestureRecognizer_TappedEvent; } }
33.811111
114
0.670062
[ "MIT" ]
LocalJoost/CubeBouncer
Assets/Custom/Scripts/RaySendingGestureManager.cs
3,045
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the health-2016-08-04.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.AWSHealth.Model { /// <summary> /// The values to use to filter results from the <a href="https://docs.aws.amazon.com/health/latest/APIReference/API_EntityFilter.html">EntityFilter</a> /// operation. /// </summary> public partial class EntityFilter { private List<string> _entityArns = new List<string>(); private List<string> _entityValues = new List<string>(); private List<string> _eventArns = new List<string>(); private List<DateTimeRange> _lastUpdatedTimes = new List<DateTimeRange>(); private List<string> _statusCodes = new List<string>(); private List<Dictionary<string, string>> _tags = new List<Dictionary<string, string>>(); /// <summary> /// Gets and sets the property EntityArns. /// <para> /// A list of entity ARNs (unique identifiers). /// </para> /// </summary> [AWSProperty(Min=1, Max=100)] public List<string> EntityArns { get { return this._entityArns; } set { this._entityArns = value; } } // Check to see if EntityArns property is set internal bool IsSetEntityArns() { return this._entityArns != null && this._entityArns.Count > 0; } /// <summary> /// Gets and sets the property EntityValues. /// <para> /// A list of IDs for affected entities. /// </para> /// </summary> [AWSProperty(Min=1, Max=100)] public List<string> EntityValues { get { return this._entityValues; } set { this._entityValues = value; } } // Check to see if EntityValues property is set internal bool IsSetEntityValues() { return this._entityValues != null && this._entityValues.Count > 0; } /// <summary> /// Gets and sets the property EventArns. /// <para> /// A list of event ARNs (unique identifiers). For example: <code>"arn:aws:health:us-east-1::event/EC2/EC2_INSTANCE_RETIREMENT_SCHEDULED/EC2_INSTANCE_RETIREMENT_SCHEDULED_ABC123-CDE456", /// "arn:aws:health:us-west-1::event/EBS/AWS_EBS_LOST_VOLUME/AWS_EBS_LOST_VOLUME_CHI789_JKL101"</code> /// /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=10)] public List<string> EventArns { get { return this._eventArns; } set { this._eventArns = value; } } // Check to see if EventArns property is set internal bool IsSetEventArns() { return this._eventArns != null && this._eventArns.Count > 0; } /// <summary> /// Gets and sets the property LastUpdatedTimes. /// <para> /// A list of the most recent dates and times that the entity was updated. /// </para> /// </summary> [AWSProperty(Min=1, Max=10)] public List<DateTimeRange> LastUpdatedTimes { get { return this._lastUpdatedTimes; } set { this._lastUpdatedTimes = value; } } // Check to see if LastUpdatedTimes property is set internal bool IsSetLastUpdatedTimes() { return this._lastUpdatedTimes != null && this._lastUpdatedTimes.Count > 0; } /// <summary> /// Gets and sets the property StatusCodes. /// <para> /// A list of entity status codes (<code>IMPAIRED</code>, <code>UNIMPAIRED</code>, or /// <code>UNKNOWN</code>). /// </para> /// </summary> [AWSProperty(Min=1, Max=3)] public List<string> StatusCodes { get { return this._statusCodes; } set { this._statusCodes = value; } } // Check to see if StatusCodes property is set internal bool IsSetStatusCodes() { return this._statusCodes != null && this._statusCodes.Count > 0; } /// <summary> /// Gets and sets the property Tags. /// <para> /// A map of entity tags attached to the affected entity. /// </para> /// <note> /// <para> /// Currently, the <code>tags</code> property isn't supported. /// </para> /// </note> /// </summary> [AWSProperty(Max=50)] public List<Dictionary<string, string>> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } } }
34.586826
195
0.564751
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/AWSHealth/Generated/Model/EntityFilter.cs
5,776
C#
using System; namespace KubeOps.Operator.Errors { internal class CrdPropertyTypeException : Exception { public CrdPropertyTypeException() : this("The given property has an invalid type.") { } public CrdPropertyTypeException(string message) : base(message) { } public CrdPropertyTypeException(string message, Exception innerException) : base(message, innerException) { } } }
21.652174
81
0.598394
[ "MIT" ]
Aivanovac/dotnet-operator-sdk
src/KubeOps/Operator/Errors/CrdPropertyTypeException.cs
500
C#
using System; using System.Collections.Generic; using IFoster.ViewModel.DashBoardViewModel.NoticeBoard; using Xamarin.Forms; namespace IFoster.View.DashBoardView.NoticeBoardTab { public partial class GlobalNoticeView : ContentView { public GlobalNoticeViewModel _globalNoticeViewModel; public GlobalNoticeView() { InitializeComponent(); _globalNoticeViewModel = new GlobalNoticeViewModel(); BindingContext = _globalNoticeViewModel; } } }
23.772727
65
0.709369
[ "MIT" ]
ZahirAhmad/XamarinForms4.0
IFoster/IFoster/View/DashBoardView/NoticeBoardTab/GlobalNoticeView.xaml.cs
525
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.Lex.Inputs { public sealed class BotAliasConversationLogsArgs : Pulumi.ResourceArgs { /// <summary> /// The Amazon Resource Name (ARN) of the IAM role used to write your logs to CloudWatch Logs or an S3 bucket. /// </summary> [Input("iamRoleArn", required: true)] public Input<string> IamRoleArn { get; set; } = null!; [Input("logSettings")] private InputList<Inputs.BotAliasConversationLogsLogSettingArgs>? _logSettings; /// <summary> /// The settings for your conversation logs. You can log text, audio, or both. Attributes are documented under log_settings. /// </summary> public InputList<Inputs.BotAliasConversationLogsLogSettingArgs> LogSettings { get => _logSettings ?? (_logSettings = new InputList<Inputs.BotAliasConversationLogsLogSettingArgs>()); set => _logSettings = value; } public BotAliasConversationLogsArgs() { } } }
35.236842
132
0.668409
[ "ECL-2.0", "Apache-2.0" ]
Otanikotani/pulumi-aws
sdk/dotnet/Lex/Inputs/BotAliasConversationLogsArgs.cs
1,339
C#
// Copyright (c) Leonardo Brugnara // Full copyright and license information in LICENSE file using Zenit.Ast; namespace Zenit.Semantics.Mutability { class FunctionMutabilityChecker : INodeVisitor<MutabilityCheckerVisitor, FunctionNode, MutabilityCheckResult> { public MutabilityCheckResult Visit(MutabilityCheckerVisitor checker, FunctionNode funcdecl) { checker.SymbolTable.EnterFunctionScope(funcdecl.Name); funcdecl.Body.ForEach(s => s.Visit(checker)); checker.SymbolTable.LeaveScope(); return new MutabilityCheckResult(checker.SymbolTable.GetVariableSymbol(funcdecl.Name)); } } }
30.636364
113
0.722552
[ "MIT" ]
lbrugnara/flsharp
FrontEnd/Semantics/Mutability/FunctionMutabilityChecker.cs
676
C#
using System; using System.Collections.Generic; using System.Configuration; using Abp.Dependency; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.Extensions; using Abp.MultiTenancy; using Abp.Runtime.Security; using MT.MultiTenancy; namespace MT.Migrator { public class MultiTenantMigrateExecuter : ITransientDependency { public Log Log { get; private set; } private readonly IAbpZeroDbMigrator _migrator; private readonly IRepository<Tenant> _tenantRepository; private readonly IDbPerTenantConnectionStringResolver _connectionStringResolver; public MultiTenantMigrateExecuter( IAbpZeroDbMigrator migrator, IRepository<Tenant> tenantRepository, Log log, IDbPerTenantConnectionStringResolver connectionStringResolver) { Log = log; _connectionStringResolver = connectionStringResolver; _migrator = migrator; _tenantRepository = tenantRepository; } public void Run(bool skipConnVerification) { var hostConnStr = _connectionStringResolver.GetNameOrConnectionString(new ConnectionStringResolveArgs(MultiTenancySides.Host)); if (hostConnStr.IsNullOrWhiteSpace()) { Log.Write("Configuration file should contain a connection string named 'Default'"); return; } Log.Write("Host database: " + hostConnStr); if (!skipConnVerification) { Log.Write("Continue to migration for this host database and all tenants..? (Y/N): "); var command = Console.ReadLine(); if (!command.IsIn("Y", "y")) { Log.Write("Migration canceled."); return; } } Log.Write("HOST database migration started..."); try { _migrator.CreateOrMigrateForHost(); } catch (Exception ex) { Log.Write("An error occured during migration of host database:"); Log.Write(ex.ToString()); Log.Write("Canceled migrations."); return; } Log.Write("HOST database migration completed."); Log.Write("--------------------------------------------------------"); var migratedDatabases = new HashSet<string>(); var tenants = _tenantRepository.GetAllList(t => t.ConnectionString != null && t.ConnectionString != ""); for (int i = 0; i < tenants.Count; i++) { var tenant = tenants[i]; Log.Write(string.Format("Tenant database migration started... ({0} / {1})", (i + 1), tenants.Count)); Log.Write("Name : " + tenant.Name); Log.Write("TenancyName : " + tenant.TenancyName); Log.Write("Tenant Id : " + tenant.Id); Log.Write("Connection string : " + SimpleStringCipher.Instance.Decrypt(tenant.ConnectionString)); if (!migratedDatabases.Contains(tenant.ConnectionString)) { try { _migrator.CreateOrMigrateForTenant(tenant); } catch (Exception ex) { Log.Write("An error occured during migration of tenant database:"); Log.Write(ex.ToString()); Log.Write("Skipped this tenant and will continue for others..."); } migratedDatabases.Add(tenant.ConnectionString); } else { Log.Write("This database has already migrated before (you have more than one tenant in same database). Skipping it...."); } Log.Write(string.Format("Tenant database migration completed. ({0} / {1})", (i + 1), tenants.Count)); Log.Write("--------------------------------------------------------"); } Log.Write("All databases have been migrated."); } } }
38.558559
141
0.528972
[ "MIT" ]
zhang-jun-yi/ABPZero
Tools/MT.Migrator/MultiTenantMigrateExecuter.cs
4,280
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.Azure.Commands.TrafficManager.Utilities { using ResourceManager.Common; using Microsoft.WindowsAzure.Commands.Utilities.Common; public abstract class TrafficManagerBaseCmdlet : AzureRMCmdlet { private TrafficManagerClient trafficManagerClient; public TrafficManagerClient TrafficManagerClient { get { if (this.trafficManagerClient == null) { this.trafficManagerClient = new TrafficManagerClient(DefaultProfile.Context) { VerboseLogger = WriteVerboseWithTimestamp, ErrorLogger = WriteErrorWithTimestamp }; } return this.trafficManagerClient; } set { this.trafficManagerClient = value; } } } }
38.363636
97
0.567536
[ "MIT" ]
DalavanCloud/azure-powershell
src/ResourceManager/TrafficManager/Commands.TrafficManager2/Utilities/TrafficManagerBaseCmdlet.cs
1,647
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Azure.Devices.Client; using Microsoft.Azure.Devices.Client.Exceptions; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Diagnostics.Tracing; using System.Threading.Tasks; namespace Microsoft.Azure.Devices.E2ETests { public partial class FaultInjectionPoolAmqpTests : IDisposable { private readonly string MessageSend_DevicePrefix = $"E2E_MessageSendFaultInjectionPoolAmqpTests"; // TODO: #943 - Honor different pool sizes for different connection pool settings. [Ignore] [TestMethod] public async Task Message_DeviceSak_TcpConnectionLossSendRecovery_SingleConnection_Amqp() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_Tcp_Only, PoolingOverAmqp.SingleConnection_PoolSize, PoolingOverAmqp.SingleConnection_DevicesCount, FaultInjection.FaultType_Tcp, FaultInjection.FaultCloseReason_Boom).ConfigureAwait(false); } // TODO: #943 - Honor different pool sizes for different connection pool settings. [Ignore] [TestMethod] public async Task Message_DeviceSak_TcpConnectionLossSendRecovery_SingleConnection_AmqpWs() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_WebSocket_Only, PoolingOverAmqp.SingleConnection_PoolSize, PoolingOverAmqp.SingleConnection_DevicesCount, FaultInjection.FaultType_Tcp, FaultInjection.FaultCloseReason_Boom).ConfigureAwait(false); } // TODO: #943 - Honor different pool sizes for different connection pool settings. [Ignore] [TestMethod] public async Task Message_IoTHubSak_TcpConnectionLossSendRecovery_SingleConnection_Amqp() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_Tcp_Only, PoolingOverAmqp.SingleConnection_PoolSize, PoolingOverAmqp.SingleConnection_DevicesCount, FaultInjection.FaultType_Tcp, FaultInjection.FaultCloseReason_Boom, authScope: ConnectionStringAuthScope.IoTHub).ConfigureAwait(false); } // TODO: #943 - Honor different pool sizes for different connection pool settings. [Ignore] [TestMethod] public async Task Message_IoTHubSak_TcpConnectionLossSendRecovery_SingleConnection_AmqpWs() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_WebSocket_Only, PoolingOverAmqp.SingleConnection_PoolSize, PoolingOverAmqp.SingleConnection_DevicesCount, FaultInjection.FaultType_Tcp, FaultInjection.FaultCloseReason_Boom, authScope: ConnectionStringAuthScope.IoTHub).ConfigureAwait(false); } // TODO: #943 - Honor different pool sizes for different connection pool settings. [Ignore] [TestMethod] public async Task Message_DeviceSak_AmqpConnectionLossSendRecovery_SingleConnection_Amqp() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_Tcp_Only, PoolingOverAmqp.SingleConnection_PoolSize, PoolingOverAmqp.SingleConnection_DevicesCount, FaultInjection.FaultType_AmqpConn, "").ConfigureAwait(false); } // TODO: #943 - Honor different pool sizes for different connection pool settings. [Ignore] [TestMethod] public async Task Message_DeviceSak_AmqpConnectionLossSendRecovery_SingleConnection_AmqpWs() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_WebSocket_Only, PoolingOverAmqp.SingleConnection_PoolSize, PoolingOverAmqp.SingleConnection_DevicesCount, FaultInjection.FaultType_AmqpConn, "").ConfigureAwait(false); } // TODO: #943 - Honor different pool sizes for different connection pool settings. [Ignore] [TestMethod] public async Task Message_IotHubSak_AmqpConnectionLossSendRecovery_SingleConnection_Amqp() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_Tcp_Only, PoolingOverAmqp.SingleConnection_PoolSize, PoolingOverAmqp.SingleConnection_DevicesCount, FaultInjection.FaultType_AmqpConn, "", authScope: ConnectionStringAuthScope.IoTHub).ConfigureAwait(false); } // TODO: #943 - Honor different pool sizes for different connection pool settings. [Ignore] [TestMethod] public async Task Message_IoTHubSak_AmqpConnectionLossSendRecovery_SingleConnection_AmqpWs() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_WebSocket_Only, PoolingOverAmqp.SingleConnection_PoolSize, PoolingOverAmqp.SingleConnection_DevicesCount, FaultInjection.FaultType_AmqpConn, "", authScope: ConnectionStringAuthScope.IoTHub).ConfigureAwait(false); } // TODO: #943 - Honor different pool sizes for different connection pool settings. // TODO: #950 - Link/session faults for message send/ method/ twin operations closes the connection. [Ignore] [TestMethod] public async Task Message_DeviceSak_AmqpSessionLossSendRecovery_SingleConnection_Amqp() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_Tcp_Only, PoolingOverAmqp.SingleConnection_PoolSize, PoolingOverAmqp.SingleConnection_DevicesCount, FaultInjection.FaultType_AmqpSess, "").ConfigureAwait(false); } // TODO: #943 - Honor different pool sizes for different connection pool settings. // TODO: #950 - Link/session faults for message send/ method/ twin operations closes the connection. [Ignore] [TestMethod] public async Task Message_DeviceSak_AmqpSessionLossSendRecovery_SingleConnection_AmqpWs() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_WebSocket_Only, PoolingOverAmqp.SingleConnection_PoolSize, PoolingOverAmqp.SingleConnection_DevicesCount, FaultInjection.FaultType_AmqpSess, "").ConfigureAwait(false); } // TODO: #943 - Honor different pool sizes for different connection pool settings. // TODO: #950 - Link/session faults for message send/ method/ twin operations closes the connection. [Ignore] [TestMethod] public async Task Message_IoTHubSak_AmqpSessionLossSendRecovery_SingleConnection_Amqp() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_Tcp_Only, PoolingOverAmqp.SingleConnection_PoolSize, PoolingOverAmqp.SingleConnection_DevicesCount, FaultInjection.FaultType_AmqpSess, "", authScope: ConnectionStringAuthScope.IoTHub).ConfigureAwait(false); } // TODO: #943 - Honor different pool sizes for different connection pool settings. // TODO: #950 - Link/session faults for message send/ method/ twin operations closes the connection. [Ignore] [TestMethod] public async Task Message_IoTHubSak_AmqpSessionLossSendRecovery_SingleConnection_AmqpWs() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_WebSocket_Only, PoolingOverAmqp.SingleConnection_PoolSize, PoolingOverAmqp.SingleConnection_DevicesCount, FaultInjection.FaultType_AmqpSess, "", authScope: ConnectionStringAuthScope.IoTHub).ConfigureAwait(false); } // TODO: #943 - Honor different pool sizes for different connection pool settings. // TODO: #950 - Link/session faults for message send/ method/ twin operations closes the connection. [Ignore] [TestMethod] public async Task Message_DeviceSak_AmqpD2CLinkDropSendRecovery_SingleConnection_Amqp() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_Tcp_Only, PoolingOverAmqp.SingleConnection_PoolSize, PoolingOverAmqp.SingleConnection_DevicesCount, FaultInjection.FaultType_AmqpD2C, FaultInjection.FaultCloseReason_Boom).ConfigureAwait(false); } // TODO: #943 - Honor different pool sizes for different connection pool settings. // TODO: #950 - Link/session faults for message send/ method/ twin operations closes the connection. [Ignore] [TestMethod] public async Task Message_DeviceSak_AmqpD2CLinkDropSendRecovery_SingleConnection_AmqpWs() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_WebSocket_Only, PoolingOverAmqp.SingleConnection_PoolSize, PoolingOverAmqp.SingleConnection_DevicesCount, FaultInjection.FaultType_AmqpD2C, FaultInjection.FaultCloseReason_Boom).ConfigureAwait(false); } // TODO: #943 - Honor different pool sizes for different connection pool settings. // TODO: #950 - Link/session faults for message send/ method/ twin operations closes the connection. [Ignore] [TestMethod] public async Task Message_IoTHubSak_AmqpD2CLinkDropSendRecovery_SingleConnection_Amqp() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_Tcp_Only, PoolingOverAmqp.SingleConnection_PoolSize, PoolingOverAmqp.SingleConnection_DevicesCount, FaultInjection.FaultType_AmqpD2C, FaultInjection.FaultCloseReason_Boom, authScope: ConnectionStringAuthScope.IoTHub).ConfigureAwait(false); } // TODO: #943 - Honor different pool sizes for different connection pool settings. // TODO: #950 - Link/session faults for message send/ method/ twin operations closes the connection. [Ignore] [TestMethod] public async Task Message_IoTHubSak_AmqpD2CLinkDropSendRecovery_SingleConnection_AmqpWs() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_WebSocket_Only, PoolingOverAmqp.SingleConnection_PoolSize, PoolingOverAmqp.SingleConnection_DevicesCount, FaultInjection.FaultType_AmqpD2C, FaultInjection.FaultCloseReason_Boom, authScope: ConnectionStringAuthScope.IoTHub).ConfigureAwait(false); } // TODO: #943 - Honor different pool sizes for different connection pool settings. [Ignore] [TestMethod] public async Task Message_DeviceSak_GracefulShutdownSendRecovery_SingleConnection_Amqp() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_Tcp_Only, PoolingOverAmqp.SingleConnection_PoolSize, PoolingOverAmqp.SingleConnection_DevicesCount, FaultInjection.FaultType_GracefulShutdownAmqp, FaultInjection.FaultCloseReason_Bye).ConfigureAwait(false); } // TODO: #943 - Honor different pool sizes for different connection pool settings. [Ignore] [TestMethod] public async Task Message_DeviceSak_GracefulShutdownSendRecovery_SingleConnection_AmqpWs() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_WebSocket_Only, PoolingOverAmqp.SingleConnection_PoolSize, PoolingOverAmqp.SingleConnection_DevicesCount, FaultInjection.FaultType_GracefulShutdownAmqp, FaultInjection.FaultCloseReason_Bye).ConfigureAwait(false); } // TODO: #943 - Honor different pool sizes for different connection pool settings. [Ignore] [TestMethod] public async Task Message_IoTHubSak_GracefulShutdownSendRecovery_SingleConnection_Amqp() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_Tcp_Only, PoolingOverAmqp.SingleConnection_PoolSize, PoolingOverAmqp.SingleConnection_DevicesCount, FaultInjection.FaultType_GracefulShutdownAmqp, FaultInjection.FaultCloseReason_Bye, authScope: ConnectionStringAuthScope.IoTHub).ConfigureAwait(false); } // TODO: #943 - Honor different pool sizes for different connection pool settings. [Ignore] [TestMethod] public async Task Message_IoTHubSak_GracefulShutdownSendRecovery_SingleConnection_AmqpWs() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_WebSocket_Only, PoolingOverAmqp.SingleConnection_PoolSize, PoolingOverAmqp.SingleConnection_DevicesCount, FaultInjection.FaultType_GracefulShutdownAmqp, FaultInjection.FaultCloseReason_Bye, authScope: ConnectionStringAuthScope.IoTHub).ConfigureAwait(false); } // TODO: #943 - Honor different pool sizes for different connection pool settings. [Ignore] [TestMethod] public async Task Message_DeviceSak_ThrottledConnectionRecovery_SingleConnection_Amqp() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_Tcp_Only, PoolingOverAmqp.SingleConnection_PoolSize, PoolingOverAmqp.SingleConnection_DevicesCount, FaultInjection.FaultType_Throttle, FaultInjection.FaultCloseReason_Boom).ConfigureAwait(false); } // TODO: #943 - Honor different pool sizes for different connection pool settings. [Ignore] [TestMethod] public async Task Message_DeviceSak_ThrottledConnectionRecovery_SingleConnection_AmqpWs() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_WebSocket_Only, PoolingOverAmqp.SingleConnection_PoolSize, PoolingOverAmqp.SingleConnection_DevicesCount, FaultInjection.FaultType_Throttle, FaultInjection.FaultCloseReason_Boom).ConfigureAwait(false); } // TODO: #943 - Honor different pool sizes for different connection pool settings. [Ignore] [TestMethod] public async Task Message_IoTHubSak_ThrottledConnectionRecovery_SingleConnection_Amqp() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_Tcp_Only, PoolingOverAmqp.SingleConnection_PoolSize, PoolingOverAmqp.SingleConnection_DevicesCount, FaultInjection.FaultType_Throttle, FaultInjection.FaultCloseReason_Boom, authScope: ConnectionStringAuthScope.IoTHub).ConfigureAwait(false); } // TODO: #943 - Honor different pool sizes for different connection pool settings. [Ignore] [TestMethod] public async Task Message_IoTHubSak_ThrottledConnectionRecovery_SingleConnection_AmqpWs() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_WebSocket_Only, PoolingOverAmqp.SingleConnection_PoolSize, PoolingOverAmqp.SingleConnection_DevicesCount, FaultInjection.FaultType_Throttle, FaultInjection.FaultCloseReason_Boom, authScope: ConnectionStringAuthScope.IoTHub).ConfigureAwait(false); } // TODO: #943 - Honor different pool sizes for different connection pool settings. [Ignore] [TestMethod] [ExpectedException(typeof(UnauthorizedException))] public async Task Message_DeviceSak_AuthenticationNoRecovery_SingleConnection_Amqp() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_Tcp_Only, PoolingOverAmqp.SingleConnection_PoolSize, PoolingOverAmqp.SingleConnection_DevicesCount, FaultInjection.FaultType_Auth, FaultInjection.FaultCloseReason_Boom).ConfigureAwait(false); } // TODO: #943 - Honor different pool sizes for different connection pool settings. [Ignore] [TestMethod] [ExpectedException(typeof(UnauthorizedException))] public async Task Message_DeviceSak_AuthenticationNoRecovery_SingleConnection_AmqpWs() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_WebSocket_Only, PoolingOverAmqp.SingleConnection_PoolSize, PoolingOverAmqp.SingleConnection_DevicesCount, FaultInjection.FaultType_Auth, FaultInjection.FaultCloseReason_Boom).ConfigureAwait(false); } // TODO: #943 - Honor different pool sizes for different connection pool settings. [Ignore] [TestMethod] [ExpectedException(typeof(UnauthorizedException))] public async Task Message_IoTHubSak_AuthenticationNoRecovery_SingleConnection_Amqp() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_Tcp_Only, PoolingOverAmqp.SingleConnection_PoolSize, PoolingOverAmqp.SingleConnection_DevicesCount, FaultInjection.FaultType_Auth, FaultInjection.FaultCloseReason_Boom, authScope: ConnectionStringAuthScope.IoTHub).ConfigureAwait(false); } // TODO: #943 - Honor different pool sizes for different connection pool settings. [Ignore] [TestMethod] [ExpectedException(typeof(UnauthorizedException))] public async Task Message_IoTHubSak_AuthenticationNoRecovery_SingleConnection_AmqpWs() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_WebSocket_Only, PoolingOverAmqp.SingleConnection_PoolSize, PoolingOverAmqp.SingleConnection_DevicesCount, FaultInjection.FaultType_Auth, FaultInjection.FaultCloseReason_Boom, authScope: ConnectionStringAuthScope.IoTHub).ConfigureAwait(false); } [TestMethod] public async Task Message_DeviceSak_TcpConnectionLossSendRecovery_MultipleConnections_Amqp() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_Tcp_Only, PoolingOverAmqp.MultipleConnections_PoolSize, PoolingOverAmqp.MultipleConnections_DevicesCount, FaultInjection.FaultType_Tcp, FaultInjection.FaultCloseReason_Boom).ConfigureAwait(false); } [TestMethod] public async Task Message_DeviceSak_TcpConnectionLossSendRecovery_MultipleConnections_AmqpWs() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_WebSocket_Only, PoolingOverAmqp.MultipleConnections_PoolSize, PoolingOverAmqp.MultipleConnections_DevicesCount, FaultInjection.FaultType_Tcp, FaultInjection.FaultCloseReason_Boom).ConfigureAwait(false); } [TestMethod] public async Task Message_IoTHubSak_TcpConnectionLossSendRecovery_MultipleConnections_Amqp() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_Tcp_Only, PoolingOverAmqp.MultipleConnections_PoolSize, PoolingOverAmqp.MultipleConnections_DevicesCount, FaultInjection.FaultType_Tcp, FaultInjection.FaultCloseReason_Boom, authScope: ConnectionStringAuthScope.IoTHub).ConfigureAwait(false); } [TestMethod] public async Task Message_IoTHubSak_TcpConnectionLossSendRecovery_MultipleConnections_AmqpWs() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_WebSocket_Only, PoolingOverAmqp.MultipleConnections_PoolSize, PoolingOverAmqp.MultipleConnections_DevicesCount, FaultInjection.FaultType_Tcp, FaultInjection.FaultCloseReason_Boom, authScope: ConnectionStringAuthScope.IoTHub).ConfigureAwait(false); } [TestMethod] public async Task Message_DeviceSak_AmqpConnectionLossSendRecovery_MultipleConnections_Amqp() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_Tcp_Only, PoolingOverAmqp.MultipleConnections_PoolSize, PoolingOverAmqp.MultipleConnections_DevicesCount, FaultInjection.FaultType_AmqpConn, "").ConfigureAwait(false); } [TestMethod] public async Task Message_DeviceSak_AmqpConnectionLossSendRecovery_MultipleConnections_AmqpWs() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_WebSocket_Only, PoolingOverAmqp.MultipleConnections_PoolSize, PoolingOverAmqp.MultipleConnections_DevicesCount, FaultInjection.FaultType_AmqpConn, "").ConfigureAwait(false); } [TestMethod] public async Task Message_IotHubSak_AmqpConnectionLossSendRecovery_MultipleConnections_Amqp() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_Tcp_Only, PoolingOverAmqp.MultipleConnections_PoolSize, PoolingOverAmqp.MultipleConnections_DevicesCount, FaultInjection.FaultType_AmqpConn, "", authScope: ConnectionStringAuthScope.IoTHub).ConfigureAwait(false); } [TestMethod] public async Task Message_IoTHubSak_AmqpConnectionLossSendRecovery_MultipleConnections_AmqpWs() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_WebSocket_Only, PoolingOverAmqp.MultipleConnections_PoolSize, PoolingOverAmqp.MultipleConnections_DevicesCount, FaultInjection.FaultType_AmqpConn, "", authScope: ConnectionStringAuthScope.IoTHub).ConfigureAwait(false); } // TODO: #950 - Link/session faults for message send/ method/ twin operations closes the connection. [TestMethod] public async Task Message_DeviceSak_AmqpSessionLossSendRecovery_MultipleConnections_Amqp() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_Tcp_Only, PoolingOverAmqp.MultipleConnections_PoolSize, PoolingOverAmqp.MultipleConnections_DevicesCount, FaultInjection.FaultType_AmqpSess, "").ConfigureAwait(false); } // TODO: #950 - Link/session faults for message send/ method/ twin operations closes the connection. [TestMethod] public async Task Message_DeviceSak_AmqpSessionLossSendRecovery_MultipleConnections_AmqpWs() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_WebSocket_Only, PoolingOverAmqp.MultipleConnections_PoolSize, PoolingOverAmqp.MultipleConnections_DevicesCount, FaultInjection.FaultType_AmqpSess, "").ConfigureAwait(false); } // TODO: #950 - Link/session faults for message send/ method/ twin operations closes the connection. [TestMethod] public async Task Message_IoTHubSak_AmqpSessionLossSendRecovery_MultipleConnections_Amqp() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_Tcp_Only, PoolingOverAmqp.MultipleConnections_PoolSize, PoolingOverAmqp.MultipleConnections_DevicesCount, FaultInjection.FaultType_AmqpSess, "", authScope: ConnectionStringAuthScope.IoTHub).ConfigureAwait(false); } // TODO: #950 - Link/session faults for message send/ method/ twin operations closes the connection. [TestMethod] public async Task Message_IoTHubSak_AmqpSessionLossSendRecovery_MultipleConnections_AmqpWs() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_WebSocket_Only, PoolingOverAmqp.MultipleConnections_PoolSize, PoolingOverAmqp.MultipleConnections_DevicesCount, FaultInjection.FaultType_AmqpSess, "", authScope: ConnectionStringAuthScope.IoTHub).ConfigureAwait(false); } // TODO: #950 - Link/session faults for message send/ method/ twin operations closes the connection. [TestMethod] public async Task Message_DeviceSak_AmqpD2CLinkDropSendRecovery_MultipleConnections_Amqp() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_Tcp_Only, PoolingOverAmqp.MultipleConnections_PoolSize, PoolingOverAmqp.MultipleConnections_DevicesCount, FaultInjection.FaultType_AmqpD2C, FaultInjection.FaultCloseReason_Boom).ConfigureAwait(false); } // TODO: #950 - Link/session faults for message send/ method/ twin operations closes the connection. [TestMethod] public async Task Message_DeviceSak_AmqpD2CLinkDropSendRecovery_MultipleConnections_AmqpWs() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_WebSocket_Only, PoolingOverAmqp.MultipleConnections_PoolSize, PoolingOverAmqp.MultipleConnections_DevicesCount, FaultInjection.FaultType_AmqpD2C, FaultInjection.FaultCloseReason_Boom).ConfigureAwait(false); } // TODO: #950 - Link/session faults for message send/ method/ twin operations closes the connection. [TestMethod] public async Task Message_IoTHubSak_AmqpD2CLinkDropSendRecovery_MultipleConnections_Amqp() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_Tcp_Only, PoolingOverAmqp.MultipleConnections_PoolSize, PoolingOverAmqp.MultipleConnections_DevicesCount, FaultInjection.FaultType_AmqpD2C, FaultInjection.FaultCloseReason_Boom, authScope: ConnectionStringAuthScope.IoTHub).ConfigureAwait(false); } // TODO: #950 - Link/session faults for message send/ method/ twin operations closes the connection. [TestMethod] public async Task Message_IoTHubSak_AmqpD2CLinkDropSendRecovery_MultipleConnections_AmqpWs() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_WebSocket_Only, PoolingOverAmqp.MultipleConnections_PoolSize, PoolingOverAmqp.MultipleConnections_DevicesCount, FaultInjection.FaultType_AmqpD2C, FaultInjection.FaultCloseReason_Boom, authScope: ConnectionStringAuthScope.IoTHub).ConfigureAwait(false); } [TestMethod] [TestCategory("LongRunning")] public async Task Message_DeviceSak_GracefulShutdownSendRecovery_MultipleConnections_Amqp() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_Tcp_Only, PoolingOverAmqp.MultipleConnections_PoolSize, PoolingOverAmqp.MultipleConnections_DevicesCount, FaultInjection.FaultType_GracefulShutdownAmqp, FaultInjection.FaultCloseReason_Bye).ConfigureAwait(false); } [TestMethod] public async Task Message_DeviceSak_GracefulShutdownSendRecovery_MultipleConnections_AmqpWs() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_WebSocket_Only, PoolingOverAmqp.MultipleConnections_PoolSize, PoolingOverAmqp.MultipleConnections_DevicesCount, FaultInjection.FaultType_GracefulShutdownAmqp, FaultInjection.FaultCloseReason_Bye).ConfigureAwait(false); } [TestMethod] public async Task Message_IoTHubSak_GracefulShutdownSendRecovery_MultipleConnections_Amqp() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_Tcp_Only, PoolingOverAmqp.MultipleConnections_PoolSize, PoolingOverAmqp.MultipleConnections_DevicesCount, FaultInjection.FaultType_GracefulShutdownAmqp, FaultInjection.FaultCloseReason_Bye, authScope: ConnectionStringAuthScope.IoTHub).ConfigureAwait(false); } [TestMethod] public async Task Message_IoTHubSak_GracefulShutdownSendRecovery_MultipleConnections_AmqpWs() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_WebSocket_Only, PoolingOverAmqp.MultipleConnections_PoolSize, PoolingOverAmqp.MultipleConnections_DevicesCount, FaultInjection.FaultType_GracefulShutdownAmqp, FaultInjection.FaultCloseReason_Bye, authScope: ConnectionStringAuthScope.IoTHub).ConfigureAwait(false); } [TestMethod] public async Task Message_DeviceSak_ThrottledConnectionRecovery_MultipleConnections_Amqp() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_Tcp_Only, PoolingOverAmqp.MultipleConnections_PoolSize, PoolingOverAmqp.MultipleConnections_DevicesCount, FaultInjection.FaultType_Throttle, FaultInjection.FaultCloseReason_Boom).ConfigureAwait(false); } [TestMethod] public async Task Message_DeviceSak_ThrottledConnectionRecovery_MultipleConnections_AmqpWs() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_WebSocket_Only, PoolingOverAmqp.MultipleConnections_PoolSize, PoolingOverAmqp.MultipleConnections_DevicesCount, FaultInjection.FaultType_Throttle, FaultInjection.FaultCloseReason_Boom).ConfigureAwait(false); } [TestMethod] public async Task Message_IoTHubSak_ThrottledConnectionRecovery_MultipleConnections_Amqp() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_Tcp_Only, PoolingOverAmqp.MultipleConnections_PoolSize, PoolingOverAmqp.MultipleConnections_DevicesCount, FaultInjection.FaultType_Throttle, FaultInjection.FaultCloseReason_Boom, authScope: ConnectionStringAuthScope.IoTHub).ConfigureAwait(false); } [TestMethod] public async Task Message_IoTHubSak_ThrottledConnectionRecovery_MultipleConnections_AmqpWs() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_WebSocket_Only, PoolingOverAmqp.MultipleConnections_PoolSize, PoolingOverAmqp.MultipleConnections_DevicesCount, FaultInjection.FaultType_Throttle, FaultInjection.FaultCloseReason_Boom, authScope: ConnectionStringAuthScope.IoTHub).ConfigureAwait(false); } [TestMethod] [ExpectedException(typeof(UnauthorizedException))] public async Task Message_DeviceSak_AuthenticationNoRecovery_MultipleConnections_Amqp() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_Tcp_Only, PoolingOverAmqp.MultipleConnections_PoolSize, PoolingOverAmqp.MultipleConnections_DevicesCount, FaultInjection.FaultType_Auth, FaultInjection.FaultCloseReason_Boom).ConfigureAwait(false); } [TestMethod] [ExpectedException(typeof(UnauthorizedException))] public async Task Message_DeviceSak_AuthenticationNoRecovery_MultipleConnections_AmqpWs() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_WebSocket_Only, PoolingOverAmqp.MultipleConnections_PoolSize, PoolingOverAmqp.MultipleConnections_DevicesCount, FaultInjection.FaultType_Auth, FaultInjection.FaultCloseReason_Boom).ConfigureAwait(false); } [TestMethod] [ExpectedException(typeof(UnauthorizedException))] public async Task Message_IoTHubSak_AuthenticationNoRecovery_MultipleConnections_Amqp() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_Tcp_Only, PoolingOverAmqp.MultipleConnections_PoolSize, PoolingOverAmqp.MultipleConnections_DevicesCount, FaultInjection.FaultType_Auth, FaultInjection.FaultCloseReason_Boom, authScope: ConnectionStringAuthScope.IoTHub).ConfigureAwait(false); } [TestMethod] [ExpectedException(typeof(UnauthorizedException))] public async Task Message_IoTHubSak_AuthenticationNoRecovery_MultipleConnections_AmqpWs() { await SendMessageRecoveryPoolOverAmqp( TestDeviceType.Sasl, Client.TransportType.Amqp_WebSocket_Only, PoolingOverAmqp.MultipleConnections_PoolSize, PoolingOverAmqp.MultipleConnections_DevicesCount, FaultInjection.FaultType_Auth, FaultInjection.FaultCloseReason_Boom, authScope: ConnectionStringAuthScope.IoTHub).ConfigureAwait(false); } private async Task SendMessageRecoveryPoolOverAmqp( TestDeviceType type, Client.TransportType transport, int poolSize, int devicesCount, string faultType, string reason, int delayInSec = FaultInjection.DefaultDelayInSec, int durationInSec = FaultInjection.DefaultDurationInSec, ConnectionStringAuthScope authScope = ConnectionStringAuthScope.Device) { Func<DeviceClient, TestDevice, Task> testOperation = async (deviceClient, testDevice) => { _log.WriteLine($"{nameof(FaultInjectionPoolAmqpTests)}: Preparing to send message for device {testDevice.Id}"); await deviceClient.OpenAsync().ConfigureAwait(false); (Client.Message testMessage, string messageId, string payload, string p1Value) = MessageSendE2ETests.ComposeD2CTestMessage(); _log.WriteLine($"{nameof(FaultInjectionPoolAmqpTests)}.{testDevice.Id}: payload='{payload}' p1Value='{p1Value}'"); await deviceClient.SendEventAsync(testMessage).ConfigureAwait(false); bool isReceived = EventHubTestListener.VerifyIfMessageIsReceived(testDevice.Id, payload, p1Value); Assert.IsTrue(isReceived, $"Message is not received for device {testDevice.Id}."); }; Func<IList<DeviceClient>, Task> cleanupOperation = async (deviceClients) => { foreach (DeviceClient deviceClient in deviceClients) { deviceClient.Dispose(); } }; await FaultInjectionPoolingOverAmqp.TestFaultInjectionPoolAmqpAsync( MessageSend_DevicePrefix, transport, poolSize, devicesCount, faultType, reason, delayInSec, durationInSec, (d, t) => { return Task.FromResult<bool>(false); }, testOperation, cleanupOperation, authScope).ConfigureAwait(false); } } }
46.35967
141
0.65912
[ "MIT" ]
bikamani/azure-iot-sdk-csharp
e2e/test/FaultInjectionPoolAmqpTests.MessageSendFaultInjectionPoolAmqpTests.cs
39,315
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 using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal abstract class SourceConstructorSymbolBase : SourceMemberMethodSymbol { protected ImmutableArray<ParameterSymbol> _lazyParameters; private TypeWithAnnotations _lazyReturnType; private bool _lazyIsVararg; protected SourceConstructorSymbolBase( SourceMemberContainerTypeSymbol containingType, Location location, CSharpSyntaxNode syntax, bool isIterator) : base(containingType, syntax.GetReference(), ImmutableArray.Create(location), isIterator) { Debug.Assert( syntax.IsKind(SyntaxKind.ConstructorDeclaration) || syntax.IsKind(SyntaxKind.RecordDeclaration)); } protected sealed override void MethodChecks(DiagnosticBag diagnostics) { var syntax = (CSharpSyntaxNode)syntaxReferenceOpt.GetSyntax(); var binderFactory = this.DeclaringCompilation.GetBinderFactory(syntax.SyntaxTree); ParameterListSyntax parameterList = GetParameterList(); // NOTE: if we asked for the binder for the body of the constructor, we'd risk a stack overflow because // we might still be constructing the member list of the containing type. However, getting the binder // for the parameters should be safe. var bodyBinder = binderFactory.GetBinder(parameterList, syntax, this).WithContainingMemberOrLambda(this); // Constraint checking for parameter and return types must be delayed until // the method has been added to the containing type member list since // evaluating the constraints may depend on accessing this method from // the container (comparing this method to others to find overrides for // instance). Constraints are checked in AfterAddingTypeMembersChecks. var signatureBinder = bodyBinder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this); SyntaxToken arglistToken; _lazyParameters = ParameterHelpers.MakeParameters( signatureBinder, this, parameterList, out arglistToken, allowRefOrOut: AllowRefOrOut, allowThis: false, addRefReadOnlyModifier: false, diagnostics: diagnostics); _lazyIsVararg = (arglistToken.Kind() == SyntaxKind.ArgListKeyword); _lazyReturnType = TypeWithAnnotations.Create(bodyBinder.GetSpecialType(SpecialType.System_Void, diagnostics, syntax)); var location = this.Locations[0]; if (MethodKind == MethodKind.StaticConstructor && (_lazyParameters.Length != 0)) { diagnostics.Add(ErrorCode.ERR_StaticConstParam, location, this); } this.CheckEffectiveAccessibility(_lazyReturnType, _lazyParameters, diagnostics); if (_lazyIsVararg && (IsGenericMethod || ContainingType.IsGenericType || _lazyParameters.Length > 0 && _lazyParameters[_lazyParameters.Length - 1].IsParams)) { diagnostics.Add(ErrorCode.ERR_BadVarargs, location); } } #nullable enable protected abstract ParameterListSyntax GetParameterList(); protected abstract bool AllowRefOrOut { get; } #nullable disable internal sealed override void AfterAddingTypeMembersChecks(ConversionsBase conversions, DiagnosticBag diagnostics) { base.AfterAddingTypeMembersChecks(conversions, diagnostics); var compilation = DeclaringCompilation; ParameterHelpers.EnsureIsReadOnlyAttributeExists(compilation, Parameters, diagnostics, modifyCompilation: true); ParameterHelpers.EnsureNativeIntegerAttributeExists(compilation, Parameters, diagnostics, modifyCompilation: true); ParameterHelpers.EnsureNullableAttributeExists(compilation, this, Parameters, diagnostics, modifyCompilation: true); foreach (var parameter in this.Parameters) { parameter.Type.CheckAllConstraints(compilation, conversions, parameter.Locations[0], diagnostics); } } public sealed override bool IsVararg { get { LazyMethodChecks(); return _lazyIsVararg; } } public sealed override bool IsImplicitlyDeclared { get { return base.IsImplicitlyDeclared; } } #if XSHARP internal override int ParameterCount #else internal sealed override int ParameterCount #endif { get { if (!_lazyParameters.IsDefault) { return _lazyParameters.Length; } return GetParameterList().ParameterCount; } } #if XSHARP public override ImmutableArray<ParameterSymbol> Parameters #else public sealed override ImmutableArray<ParameterSymbol> Parameters #endif { get { LazyMethodChecks(); return _lazyParameters; } } public sealed override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return ImmutableArray<TypeParameterSymbol>.Empty; } } public sealed override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes() => ImmutableArray<ImmutableArray<TypeWithAnnotations>>.Empty; public sealed override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds() => ImmutableArray<TypeParameterConstraintKind>.Empty; public override RefKind RefKind { get { return RefKind.None; } } public sealed override TypeWithAnnotations ReturnTypeWithAnnotations { get { LazyMethodChecks(); return _lazyReturnType; } } public sealed override string Name { get { return this.IsStatic ? WellKnownMemberNames.StaticConstructorName : WellKnownMemberNames.InstanceConstructorName; } } internal sealed override OneOrMany<SyntaxList<AttributeListSyntax>> GetReturnTypeAttributeDeclarations() { // constructors can't have return type attributes return OneOrMany.Create(default(SyntaxList<AttributeListSyntax>)); } protected sealed override IAttributeTargetSymbol AttributeOwner { get { return base.AttributeOwner; } } internal sealed override bool GenerateDebugInfo { get { return true; } } internal sealed override int CalculateLocalSyntaxOffset(int position, SyntaxTree tree) { Debug.Assert(position >= 0 && tree != null); TextSpan span; // local/lambda/closure defined within the body of the constructor: var ctorSyntax = (CSharpSyntaxNode)syntaxReferenceOpt.GetSyntax(); if (tree == ctorSyntax.SyntaxTree) { if (IsWithinExpressionOrBlockBody(position, out int offset)) { return offset; } // closure in ctor initializer lifting its parameter(s) spans the constructor declaration: if (position == ctorSyntax.SpanStart) { // Use a constant that is distinct from any other syntax offset. // -1 works since a field initializer and a constructor declaration header can't squeeze into a single character. return -1; } } // lambdas in ctor initializer: int ctorInitializerLength; var ctorInitializer = GetInitializer(); if (tree == ctorInitializer?.SyntaxTree) { span = ctorInitializer.Span; ctorInitializerLength = span.Length; if (span.Contains(position)) { return -ctorInitializerLength + (position - span.Start); } } else { ctorInitializerLength = 0; } // lambdas in field/property initializers: int syntaxOffset; var containingType = (SourceNamedTypeSymbol)this.ContainingType; if (containingType.TryCalculateSyntaxOffsetOfPositionInInitializer(position, tree, this.IsStatic, ctorInitializerLength, out syntaxOffset)) { return syntaxOffset; } // we haven't found the constructor part that declares the variable: throw ExceptionUtilities.Unreachable; } internal abstract override bool IsNullableAnalysisEnabled(); protected abstract CSharpSyntaxNode GetInitializer(); protected abstract bool IsWithinExpressionOrBlockBody(int position, out int offset); } }
38.285714
169
0.631012
[ "Apache-2.0" ]
SHirsch78/XSharpDev
Roslyn/src/Compilers/CSharp/Portable/Symbols/Source/SourceConstructorSymbolBase.cs
9,650
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Mod.ExampleApp.Application.Dtos; using Mod.ExampleApp.Application.Services; using Mod.ExampleApp.Domain.Entities; using Mod.Framework.WebApi.Controllers; namespace Mod.ExampleApp.API.Controllers { public class OrderController : CrudControllerBase<OrderDto, Order> { public OrderController(ILogger<OrderController> logger, IOrderAppService service) : base(logger, service) { } } }
28.941176
113
0.764228
[ "MIT" ]
EOP-OMB/mod-framework
Server/Mod.ExampleApp/Mod.ExampleApp.WebApi/Controllers/OrderController.cs
494
C#
using System; using System.Runtime.InteropServices; using UnityEngine.Experimental.Input.Utilities; ////REVIEW: move this inside InputActionTrace? namespace UnityEngine.Experimental.Input.LowLevel { /// <summary> /// A variable-size event that captures the triggering of an action. /// </summary> /// <remarks> /// Action events capture fully processed values only. /// /// This struct is internal as the data it stores requires having access to <see cref="InputActionState"/>. /// Public access is meant to go through <see cref="InputActionTrace"/> which provides a wrapper around /// action events in the form of <see cref="InputActionTrace.ActionEventPtr"/>. /// </remarks> [StructLayout(LayoutKind.Explicit, Size = InputEvent.kBaseEventSize + 16 + 1)] internal unsafe struct ActionEvent : IInputEventTypeInfo { public const int Type = 0x4143544E; // 'ACTN' ////REVIEW: should we decouple this from InputEvent? we get deviceId which we don't really have a use for [FieldOffset(0)] public InputEvent baseEvent; [FieldOffset(InputEvent.kBaseEventSize + 0)] private ushort m_ControlIndex; [FieldOffset(InputEvent.kBaseEventSize + 2)] private ushort m_BindingIndex; [FieldOffset(InputEvent.kBaseEventSize + 4)] private ushort m_InteractionIndex; [FieldOffset(InputEvent.kBaseEventSize + 6)] private byte m_StateIndex; [FieldOffset(InputEvent.kBaseEventSize + 7)] private byte m_Phase; [FieldOffset(InputEvent.kBaseEventSize + 8)] private double m_StartTime; [FieldOffset(InputEvent.kBaseEventSize + 16)] public fixed byte m_ValueData[1]; // Variable-sized. public double startTime { get { return m_StartTime; } set { m_StartTime = value; } } public InputActionPhase phase { get { return (InputActionPhase)m_Phase; } set { m_Phase = (byte)value; } } public byte* valueData { get { fixed(byte* data = m_ValueData) { return data; } } } public int valueSizeInBytes { get { return (int)baseEvent.sizeInBytes - InputEvent.kBaseEventSize - 16; } } public int stateIndex { get { return m_StateIndex; } set { Debug.Assert(value >= 0 && value <= byte.MaxValue); if (value < 0 || value > byte.MaxValue) throw new NotSupportedException("State count cannot exceed byte.MaxValue"); m_StateIndex = (byte)value; } } public int controlIndex { get { return m_ControlIndex; } set { Debug.Assert(value >= 0 && value <= ushort.MaxValue); if (value < 0 || value > ushort.MaxValue) throw new NotSupportedException("Control count cannot exceed ushort.MaxValue"); m_ControlIndex = (ushort)value; } } public int bindingIndex { get { return m_BindingIndex; } set { Debug.Assert(value >= 0 && value <= ushort.MaxValue); if (value < 0 || value > ushort.MaxValue) throw new NotSupportedException("Binding count cannot exceed ushort.MaxValue"); m_BindingIndex = (ushort)value; } } public int interactionIndex { get { if (m_InteractionIndex == ushort.MaxValue) return InputActionState.kInvalidIndex; return m_InteractionIndex; } set { Debug.Assert(value == InputActionState.kInvalidIndex || (value >= 0 && value < ushort.MaxValue)); if (value == InputActionState.kInvalidIndex) m_InteractionIndex = ushort.MaxValue; else { if (value < 0 || value >= ushort.MaxValue) throw new NotSupportedException("Interaction count cannot exceed ushort.MaxValue-1"); m_InteractionIndex = (ushort)value; } } } public InputEventPtr ToEventPtr() { fixed(ActionEvent* ptr = &this) { return new InputEventPtr((InputEvent*)ptr); } } public FourCC GetTypeStatic() { return Type; } public static int GetEventSizeWithValueSize(int valueSizeInBytes) { return InputEvent.kBaseEventSize + 16 + valueSizeInBytes; } public static ActionEvent* From(InputEventPtr ptr) { if (!ptr.valid) throw new ArgumentNullException("ptr"); if (!ptr.IsA<ActionEvent>()) throw new InvalidCastException(string.Format("Cannot cast event with type '{0}' into ActionEvent", ptr.type)); return (ActionEvent*)ptr.data; } } }
34.735099
114
0.556911
[ "MIT" ]
DrPaulRobertson/custom-controller-demos
DistanceDemo/Library/PackageCache/com.unity.inputsystem@0.2.0-preview/InputSystem/Events/ActionEvent.cs
5,245
C#
using System; using System.Collections.Generic; using g3; using f3; using UnityEngine; namespace f3 { public class UnityCurveRenderer : CurveRendererImplementation { protected LineRenderer r; public virtual void initialize(fGameObject go, Colorf color) { r = ((GameObject)go).AddComponent<LineRenderer>(); r.useWorldSpace = false; r.material = MaterialUtil.CreateTransparentMaterial(color); } public virtual void initialize(fGameObject go, fMaterial material, bool bSharedMat) { r = ((GameObject)go).AddComponent<LineRenderer>(); r.useWorldSpace = false; if (bSharedMat) r.sharedMaterial = material; else r.material = material; } public virtual void update_curve(Vector3f[] Vertices) { if ( Vertices == null ) { r.positionCount = 0; return; } if (r.positionCount != Vertices.Length) r.positionCount = Vertices.Length; for (int i = 0; i < Vertices.Length; ++i) r.SetPosition(i, Vertices[i]); } public virtual void update_num_points(int N) { if (r.positionCount != N) r.positionCount = N; } public virtual void update_position(int i, Vector3f v) { r.SetPosition(i, v); } public virtual void update_width(float width) { r.startWidth = r.endWidth = width; } public virtual void update_width(float startWidth, float endWidth) { r.startWidth = startWidth; r.endWidth = endWidth; } public virtual void update_color(Colorf color) { r.startColor = r.endColor = color; } public virtual void set_corner_quality(int n) { r.numCornerVertices = n; } public virtual bool is_pixel_width() { return false; } } public class UnityPixelCurveRenderer : UnityCurveRenderer { //fGameObject lineGO; Vector3f center; public override void initialize(fGameObject go, Colorf color) { //lineGO = go; base.initialize(go, color); } public override void update_curve(Vector3f[] Vertices) { base.update_curve(Vertices); if (Vertices == null) center = Vector3f.Zero; else center = BoundsUtil.Bounds(Vertices, (x) => { return x; }).Center; } public override void update_width(float width) { // how to convert this width to pixels? //float near_plane_w = Camera.main.nearClipPlane * (float)Math.Tan(Camera.main.fieldOfView); //float near_pixel_w = Camera.main.pixelWidth / near_plane_w; float near_plane_pixel_deg = Camera.main.fieldOfView / Camera.main.pixelWidth; float fWidth = VRUtil.GetVRRadiusForVisualAngle(center, Camera.main.transform.position, near_plane_pixel_deg); r.startWidth = r.endWidth = width * fWidth; } public override bool is_pixel_width() { return true; } } public class UnityCurveRendererFactory : CurveRendererFactory { public CurveRendererImplementation Build(LineWidthType widthType) { if (widthType == LineWidthType.World) return new UnityCurveRenderer(); else return new UnityPixelCurveRenderer(); } } }
28.015152
122
0.563548
[ "MIT" ]
Elevator89/frame3Sharp
unity/UnityCurveRenderer.cs
3,700
C#
using System; using System.ComponentModel.DataAnnotations.Schema; using LewisFam.Stocks.Models; namespace LewisFam.Stocks.Entity { [Table("StockQuotes", Schema = "trading")] public class StockQuote : Stock, IStockQuote { public StockQuote(string symbol) { Symbol = symbol; //Vendor = Models.Enums.Vendor.Cnbc; } //[Key] public virtual long QuoteId { get; protected set; } public virtual double Change { get; set; } public virtual double Close { get; set; } public virtual double High { get; set; } public virtual double Last { get; set; } public virtual double Low { get; set; } public virtual double Open { get; set; } public virtual long Volume { get; set; } public virtual double Price { get; set; } public virtual long TimeStamp { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); } }
33
101
0.621735
[ "MIT" ]
Lewis-Fam/Stocks
src/LewisFam.Stocks/Internal/Data/Entity/Move/StockQuote.cs
959
C#
using System; using Abp; using Abp.Authorization; using Abp.Dependency; using Abp.UI; namespace gatling.Authorization { public class AbpLoginResultTypeHelper : AbpServiceBase, ITransientDependency { public AbpLoginResultTypeHelper() { LocalizationSourceName = gatlingConsts.LocalizationSourceName; } public Exception CreateExceptionForFailedLoginAttempt(AbpLoginResultType result, string usernameOrEmailAddress, string tenancyName) { switch (result) { case AbpLoginResultType.Success: return new Exception("Don't call this method with a success result!"); case AbpLoginResultType.InvalidUserNameOrEmailAddress: case AbpLoginResultType.InvalidPassword: return new UserFriendlyException(L("LoginFailed"), L("InvalidUserNameOrPassword")); case AbpLoginResultType.InvalidTenancyName: return new UserFriendlyException(L("LoginFailed"), L("ThereIsNoTenantDefinedWithName{0}", tenancyName)); case AbpLoginResultType.TenantIsNotActive: return new UserFriendlyException(L("LoginFailed"), L("TenantIsNotActive", tenancyName)); case AbpLoginResultType.UserIsNotActive: return new UserFriendlyException(L("LoginFailed"), L("UserIsNotActiveAndCanNotLogin", usernameOrEmailAddress)); case AbpLoginResultType.UserEmailIsNotConfirmed: return new UserFriendlyException(L("LoginFailed"), L("UserEmailIsNotConfirmedAndCanNotLogin")); case AbpLoginResultType.LockedOut: return new UserFriendlyException(L("LoginFailed"), L("UserLockedOutMessage")); default: // Can not fall to default actually. But other result types can be added in the future and we may forget to handle it Logger.Warn("Unhandled login fail reason: " + result); return new UserFriendlyException(L("LoginFailed")); } } public string CreateLocalizedMessageForFailedLoginAttempt(AbpLoginResultType result, string usernameOrEmailAddress, string tenancyName) { switch (result) { case AbpLoginResultType.Success: throw new Exception("Don't call this method with a success result!"); case AbpLoginResultType.InvalidUserNameOrEmailAddress: case AbpLoginResultType.InvalidPassword: return L("InvalidUserNameOrPassword"); case AbpLoginResultType.InvalidTenancyName: return L("ThereIsNoTenantDefinedWithName{0}", tenancyName); case AbpLoginResultType.TenantIsNotActive: return L("TenantIsNotActive", tenancyName); case AbpLoginResultType.UserIsNotActive: return L("UserIsNotActiveAndCanNotLogin", usernameOrEmailAddress); case AbpLoginResultType.UserEmailIsNotConfirmed: return L("UserEmailIsNotConfirmedAndCanNotLogin"); default: // Can not fall to default actually. But other result types can be added in the future and we may forget to handle it Logger.Warn("Unhandled login fail reason: " + result); return L("LoginFailed"); } } } }
53.215385
143
0.644695
[ "MIT" ]
Dash-Nguyen/abp
aspnet-core/src/gatling.Application/Authorization/AbpLoginResultTypeHelper.cs
3,461
C#
/* * PERWAPI - An API for Reading and Writing PE Files * * Copyright (c) Diane Corney, Queensland University of Technology, 2004-2010. * * This program is free software; you can redistribute it and/or modify * it under the terms of the PERWAPI Copyright as included with this * distribution in the file PERWAPIcopyright.rtf. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY as is explained in the copyright notice. * * The author may be contacted at d.corney@qut.edu.au * * Version Date: 26/01/07 * * Contributions Made By: * * Douglas Stockwell - Developed support for PDB files. * Andrew Bacon - Integrated PDB file support and developed automatic * stack depth calculations. * */ // The conditional compilation on the CORAPI symbol has been // deleted from this version. Go back to version 1 in the QUT SVN // repository to get the conditional code if needed. using System; using System.IO; using System.Collections; using System.Text; using System.Diagnostics; using System.Reflection; // For the assembly attributes // // The assembly version is managed manually here. // 1.1.* are versions with the PDB handling built // Version 1.1.1+ uses System.Security.Crytography // to provide public key token methods // namespace QUT.PERWAPI { internal class MetaDataTables { private TableRow[][] tables; internal MetaDataTables(TableRow[][] tabs) { tables = tabs; } internal MetaDataElement GetTokenElement(uint token) { uint tabIx = (token & FileImage.TableMask) >> 24; uint elemIx = (token & FileImage.ElementMask) - 1; return (MetaDataElement)tables[tabIx][(int)elemIx]; } } /**************************************************************************/ // Streams for PE File Reader /**************************************************************************/ /// <summary> /// Stream in the Meta Data (#Strings, #US, #Blob and #GUID) /// </summary> /// internal class MetaDataInStream : BinaryReader { //protected bool largeIx = false; protected byte[] data; public MetaDataInStream(byte[] streamBytes) : base(new MemoryStream(streamBytes)) { data = streamBytes; } public uint ReadCompressedNum() { //int pos = (int)BaseStream.Position; //Console.WriteLine("Position = " + BaseStream.Position); byte b = ReadByte(); //pos++; uint num = 0; if (b <= 0x7F) { num = b; } else if (b >= 0xC0) { num = (uint)(((b - 0xC0) << 24) + (ReadByte() << 16) + (ReadByte() << 8) + ReadByte()); } else { // (b >= 0x80) && (b < 0xC0) num = (uint)((b - 0x80) << 8) + ReadByte(); } return num; } public int ReadCompressedInt() { // This code is based on a revised version of the // (incorrect) ECMA-335 spec which clarifies the // encoding of array lower bounds. (kjg 2008-Feb-22 ) // uint rawBits = ReadCompressedNum(); uint magnitude = (rawBits >> 1); if ((rawBits & 1) != 1) return (int)magnitude; else if (magnitude <= 0x3f) return (int)(magnitude | 0xffffffc0); else if (magnitude <= 0x1fff) return (int)(magnitude | 0xffffe000); else return (int)(magnitude | 0xf0000000); } internal bool AtEnd() { long pos = BaseStream.Position; long len = BaseStream.Length; //if (pos >= len-1) // Console.WriteLine("At end of stream"); return BaseStream.Position == BaseStream.Length - 1; } internal byte[] GetBlob(uint ix) { if (ix == 0) return new byte[0]; BaseStream.Seek(ix, SeekOrigin.Begin); //Console.WriteLine("Getting blob size at index " + buff.GetPos()); //if (Diag.CADiag) Console.WriteLine("Getting blob size at " + (BaseStream.Position+PEReader.blobStreamStartOffset)); uint bSiz = ReadCompressedNum(); //byte[] blobBytes = new byte[ReadCompressedNum()]; //if (Diag.CADiag) Console.WriteLine("Blob size = " + bSiz); byte[] blobBytes = new byte[bSiz]; for (int i = 0; i < blobBytes.Length; i++) { blobBytes[i] = ReadByte(); } return blobBytes; } internal byte[] GetBlob(uint ix, int len) { //Console.WriteLine("Getting blob size at index " + buffer.GetPos()); byte[] blobBytes = new byte[len]; for (int i = 0; i < len; i++) { blobBytes[i] = data[ix++]; } return blobBytes; } internal string GetString(uint ix) { uint end; for (end = ix; data[end] != '\0'; end++) ; char[] str = new char[end - ix]; for (int i = 0; i < str.Length; i++) { str[i] = (char)data[ix + i]; } return new string(str, 0, str.Length); } internal string GetBlobString(uint ix) { if (ix == 0) return ""; BaseStream.Seek(ix, SeekOrigin.Begin); return GetBlobString(); } internal string GetBlobString() { uint strLen = ReadCompressedNum(); char[] str = new char[strLen]; uint readpos = (uint)this.BaseStream.Position; for (int i = 0; i < strLen; i++) { str[i] = ReadChar(); uint newpos = (uint)this.BaseStream.Position; if (newpos > readpos + 1) strLen -= newpos - (readpos + 1); readpos = newpos; } return new string(str, 0, (int)strLen); } internal void GoToIndex(uint ix) { BaseStream.Seek(ix, SeekOrigin.Begin); } } /**************************************************************************/ internal class MetaDataStringStream : BinaryReader { //BinaryReader br; internal MetaDataStringStream(byte[] bytes) : base(new MemoryStream(bytes), Encoding.Unicode) { //br = new BinaryReader(new MemoryStream(bytes)/*,Encoding.Unicode*/); } private uint GetStringLength() { uint b = ReadByte(); uint num = 0; if (b <= 0x7F) { num = b; } else if (b >= 0xC0) { num = (uint)(((b - 0xC0) << 24) + (ReadByte() << 16) + (ReadByte() << 8) + ReadByte()); } else { // (b >= 0x80) && (b < 0xC0) num = (uint)((b - 0x80) << 8) + ReadByte(); } return num; } internal string GetUserString(uint ix) { BaseStream.Seek(ix, SeekOrigin.Begin); uint strLen = GetStringLength() / 2; char[] strArray = new char[strLen]; for (int i = 0; i < strLen; i++) { //strArray[i] = ReadChar(); // works for everett but not whidbey strArray[i] = (char)ReadUInt16(); } return new String(strArray); } } /**************************************************************************/ // Streams for generated MetaData /**************************************************************************/ /// <summary> /// Stream in the generated Meta Data (#Strings, #US, #Blob and #GUID) /// </summary> internal class MetaDataStream : BinaryWriter { private static readonly uint StreamHeaderSize = 8; private static uint maxSmlIxSize = 0xFFFF; private uint start = 0; uint size = 0, tide = 1; bool largeIx = false; uint sizeOfHeader; internal char[] name; Hashtable htable = new Hashtable(); internal MetaDataStream(char[] name, bool addInitByte) : base(new MemoryStream()) { if (addInitByte) { Write((byte)0); size = 1; } this.name = name; sizeOfHeader = StreamHeaderSize + (uint)name.Length; } internal MetaDataStream(char[] name, System.Text.Encoding enc, bool addInitByte) : base(new MemoryStream(), enc) { if (addInitByte) { Write((byte)0); size = 1; } this.name = name; sizeOfHeader = StreamHeaderSize + (uint)name.Length; } public uint Start { get { return start; } set { start = value; } } internal uint headerSize() { // Console.WriteLine(name + " stream has headersize of " + sizeOfHeader); return sizeOfHeader; } //internal void SetSize(uint siz) { // size = siz; //} internal uint Size() { return size; } internal bool LargeIx() { return largeIx; } internal void WriteDetails() { // Console.WriteLine(name + " - size = " + size); } internal uint Add(string str, bool prependSize) { Object val = htable[str]; uint index = 0; if (val == null) { index = size; htable[str] = index; char[] arr = str.ToCharArray(); if (prependSize) CompressNum((uint)arr.Length * 2 + 1); Write(arr); Write((byte)0); size = (uint)Seek(0, SeekOrigin.Current); } else { index = (uint)val; } return index; } internal uint Add(Guid guid) { Write(guid.ToByteArray()); size = (uint)Seek(0, SeekOrigin.Current); return tide++; } internal uint Add(byte[] blob) { uint ix = size; CompressNum((uint)blob.Length); Write(blob); size = (uint)Seek(0, SeekOrigin.Current); return ix; } internal uint Add(long val, uint numBytes) { uint ix = size; Write((byte)numBytes); switch (numBytes) { case 1: Write((byte)val); break; case 2: Write((short)val); break; case 4: Write((int)val); break; default: Write(val); break; } size = (uint)Seek(0, SeekOrigin.Current); return ix; } internal uint Add(ulong val, uint numBytes) { uint ix = size; Write((byte)numBytes); switch (numBytes) { case 1: Write((byte)val); break; case 2: Write((ushort)val); break; case 4: Write((uint)val); break; default: Write(val); break; } size = (uint)Seek(0, SeekOrigin.Current); return ix; } internal uint Add(char ch) { uint ix = size; Write((byte)2); // size of blob to follow Write(ch); size = (uint)Seek(0, SeekOrigin.Current); return ix; } internal uint Add(float val) { uint ix = size; Write((byte)4); // size of blob to follow Write(val); size = (uint)Seek(0, SeekOrigin.Current); return ix; } internal uint Add(double val) { uint ix = size; Write((byte)8); // size of blob to follow Write(val); size = (uint)Seek(0, SeekOrigin.Current); return ix; } private void CompressNum(uint val) { if (val <= 0x7F) { Write((byte)val); } else if (val <= 0x3FFF) { byte b1 = (byte)((val >> 8) | 0x80); byte b2 = (byte)(val & FileImage.iByteMask[0]); Write(b1); Write(b2); } else { byte b1 = (byte)((val >> 24) | 0xC0); byte b2 = (byte)((val & FileImage.iByteMask[2]) >> 16); byte b3 = (byte)((val & FileImage.iByteMask[1]) >> 8); ; byte b4 = (byte)(val & FileImage.iByteMask[0]); Write(b1); Write(b2); Write(b3); Write(b4); } } private void QuadAlign() { if ((size % 4) != 0) { uint pad = 4 - (size % 4); size += pad; for (int i = 0; i < pad; i++) { Write((byte)0); } } } internal void EndStream() { QuadAlign(); if (size > maxSmlIxSize) { largeIx = true; } } internal void WriteHeader(BinaryWriter output) { output.Write(start); output.Write(size); output.Write(name); } internal virtual void Write(BinaryWriter output) { // Console.WriteLine("Writing " + name + " stream at " + output.Seek(0,SeekOrigin.Current) + " = " + start); MemoryStream str = (MemoryStream)BaseStream; output.Write(str.ToArray()); } } }
29.27512
124
0.535098
[ "BSD-3-Clause" ]
k-john-gough/perwapi
PERWAPI/PERWAPI.cs
12,237
C#
using System; using System.Collections.Generic; using System.Reflection; using Elasticsearch.Net; using Newtonsoft.Json; namespace Nest { public class AggregationDescriptor<T> where T : class { internal readonly IDictionary<string, AggregationDescriptor<T>> _Aggregations = new Dictionary<string, AggregationDescriptor<T>>(); [JsonProperty("aggs", Order = 100)] [JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))] internal IDictionary<string, AggregationDescriptor<T>> _NestedAggregations; [JsonProperty("avg")] internal AverageAggregationDescriptor<T> _Average { get; set; } public AggregationDescriptor<T> Average(string name, Func<AverageAggregationDescriptor<T>, AverageAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a._Average = d); } [JsonProperty("date_histogram")] internal DateHistogramAggregationDescriptor<T> _DateHistogram { get; set; } public AggregationDescriptor<T> DateHistogram(string name, Func<DateHistogramAggregationDescriptor<T>, DateHistogramAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a._DateHistogram = d); } [JsonProperty("percentiles")] internal PercentilesAggregationDescriptor<T> _Percentiles { get; set; } public AggregationDescriptor<T> Percentiles(string name, Func<PercentilesAggregationDescriptor<T>, PercentilesAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a._Percentiles = d); } [JsonProperty("date_range")] internal DateRangeAggregationDescriptor<T> _DateRange { get; set; } public AggregationDescriptor<T> DateRange(string name, Func<DateRangeAggregationDescriptor<T>, DateRangeAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a._DateRange = d); } [JsonProperty("extended_stats")] internal ExtendedStatsAggregationDescriptor<T> _ExtendedStats { get; set; } public AggregationDescriptor<T> ExtendedStats(string name, Func<ExtendedStatsAggregationDescriptor<T>, ExtendedStatsAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a._ExtendedStats = d); } [JsonProperty("filter")] internal FilterAggregationDescriptor<T> _Filter { get; set; } public AggregationDescriptor<T> Filter(string name, Func<FilterAggregationDescriptor<T>, FilterAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a._Filter = d); } [JsonProperty("geo_distance")] internal GeoDistanceAggregationDescriptor<T> _GeoDistance { get; set; } public AggregationDescriptor<T> GeoDistance(string name, Func<GeoDistanceAggregationDescriptor<T>, GeoDistanceAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a._GeoDistance = d); } [JsonProperty("geohash_grid")] internal GeoHashAggregationDescriptor<T> _GeoHash { get; set; } public AggregationDescriptor<T> GeoHash(string name, Func<GeoHashAggregationDescriptor<T>, GeoHashAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a._GeoHash = d); } [JsonProperty("histogram")] internal HistogramAggregationDescriptor<T> _Histogram { get; set; } public AggregationDescriptor<T> Histogram(string name, Func<HistogramAggregationDescriptor<T>, HistogramAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a._Histogram = d); } [JsonProperty("global")] internal GlobalAggregationDescriptor<T> _Global { get; set; } public AggregationDescriptor<T> Global(string name, Func<GlobalAggregationDescriptor<T>, GlobalAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a._Global = d); } [JsonProperty("ip_range")] internal Ip4RangeAggregationDescriptor<T> _IpRange { get; set; } public AggregationDescriptor<T> IpRange(string name, Func<Ip4RangeAggregationDescriptor<T>, Ip4RangeAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a._IpRange = d); } [JsonProperty("max")] internal MaxAggregationDescriptor<T> _Max { get; set; } public AggregationDescriptor<T> Max(string name, Func<MaxAggregationDescriptor<T>, MaxAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a._Max = d); } [JsonProperty("min")] internal MinAggregationDescriptor<T> _Min { get; set; } public AggregationDescriptor<T> Min(string name, Func<MinAggregationDescriptor<T>, MinAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a._Min = d); } [JsonProperty("cardinality")] internal CardinalityAggregationDescriptor<T> _Cardinality { get; set; } public AggregationDescriptor<T> Cardinality(string name, Func<CardinalityAggregationDescriptor<T>, CardinalityAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a._Cardinality = d); } [JsonProperty("missing")] internal MissingAggregationDescriptor<T> _Missing { get; set; } public AggregationDescriptor<T> Missing(string name, Func<MissingAggregationDescriptor<T>, MissingAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a._Missing = d); } [JsonProperty("nested")] internal NestedAggregationDescriptor<T> _Nested { get; set; } public AggregationDescriptor<T> Nested(string name, Func<NestedAggregationDescriptor<T>, NestedAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a._Nested = d); } [JsonProperty("range")] internal RangeAggregationDescriptor<T> _Range { get; set; } public AggregationDescriptor<T> Range(string name, Func<RangeAggregationDescriptor<T>, RangeAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a._Range = d); } [JsonProperty("stats")] internal StatsAggregationDescriptor<T> _Stats { get; set; } public AggregationDescriptor<T> Stats(string name, Func<StatsAggregationDescriptor<T>, StatsAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a._Stats = d); } [JsonProperty("sum")] internal SumAggregationDescriptor<T> _Sum { get; set; } public AggregationDescriptor<T> Sum(string name, Func<SumAggregationDescriptor<T>, SumAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a._Sum = d); } [JsonProperty("terms")] internal TermsAggregationDescriptor<T> _Terms { get; set; } public AggregationDescriptor<T> Terms(string name, Func<TermsAggregationDescriptor<T>, TermsAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a._Terms = d); } [JsonProperty("significant_terms")] internal SignificantTermsAggregationDescriptor<T> _SignificantTerms { get; set; } public AggregationDescriptor<T> SignificantTerms(string name, Func<SignificantTermsAggregationDescriptor<T>, SignificantTermsAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a._SignificantTerms = d); } [JsonProperty("value_count")] internal ValueCountAggregationDescriptor<T> _ValueCount { get; set; } public AggregationDescriptor<T> ValueCount(string name, Func<ValueCountAggregationDescriptor<T>, ValueCountAggregationDescriptor<T>> selector) { return _SetInnerAggregation(name, selector, (a, d) => a._ValueCount = d); } private AggregationDescriptor<T> _SetInnerAggregation<TAggregation>( string key, Func<TAggregation, TAggregation> selector , Action<AggregationDescriptor<T>, TAggregation> setter ) where TAggregation : IAggregationDescriptor, new() { var innerDescriptor = selector(new TAggregation()); var descriptor = new AggregationDescriptor<T>(); setter(descriptor, innerDescriptor); var bucket = innerDescriptor as IBucketAggregationDescriptor<T>; if (bucket != null && bucket.NestedAggregations.HasAny()) { descriptor._NestedAggregations = bucket.NestedAggregations; } this._Aggregations[key] = descriptor; return this; } } }
39.793269
162
0.752688
[ "Apache-2.0" ]
NickCraver/NEST
src/Nest/DSL/Aggregations/AggregationDescriptor.cs
8,277
C#
using System; namespace Hammock.Streaming { #if !SILVERLIGHT [Serializable] #endif public class StreamOptions { public virtual TimeSpan? Duration { get; set; } public virtual int? ResultsPerCallback { get; set; } } }
18.857143
61
0.625
[ "MIT" ]
BigBadChicago/hammock
src/net35/Hammock/Streaming/StreamOptions.cs
266
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("MessageDialogs.Plugin.WindowsStore")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MessageDialogs.Plugin.WindowsStore")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: ComVisible(false)]
37.413793
84
0.748387
[ "MIT" ]
ammogcoder/Xamarin.Plugins
MessageDialogs/MessageDialogs/MessageDialogs.Plugin.WindowsStore/Properties/AssemblyInfo.cs
1,088
C#
using System; using Newtonsoft.Json; namespace Nest { [JsonObject(MemberSerialization = MemberSerialization.OptIn)] [JsonConverter(typeof (VariableFieldNameQueryJsonConverter<GeoDistanceQuery, IGeoDistanceQuery>))] public interface IGeoDistanceQuery : IFieldNameQuery { [VariableField] GeoLocation Location { get; set; } [JsonProperty("distance")] Distance Distance { get; set; } [JsonProperty("distance_type")] GeoDistanceType? DistanceType { get; set; } [JsonProperty("validation_method")] GeoValidationMethod? ValidationMethod { get; set; } } public class GeoDistanceQuery : FieldNameQueryBase, IGeoDistanceQuery { protected override bool Conditionless => IsConditionless(this); public GeoLocation Location { get; set; } public Distance Distance { get; set; } public GeoDistanceType? DistanceType { get; set; } public GeoValidationMethod? ValidationMethod { get; set; } internal override void InternalWrapInContainer(IQueryContainer c) => c.GeoDistance = this; internal static bool IsConditionless(IGeoDistanceQuery q) => q.Location == null || q.Distance == null || q.Field.IsConditionless(); } public class GeoDistanceQueryDescriptor<T> : FieldNameQueryDescriptorBase<GeoDistanceQueryDescriptor<T>, IGeoDistanceQuery, T> , IGeoDistanceQuery where T : class { protected override bool Conditionless => GeoDistanceQuery.IsConditionless(this); GeoLocation IGeoDistanceQuery.Location { get; set; } Distance IGeoDistanceQuery.Distance { get; set; } GeoDistanceType? IGeoDistanceQuery.DistanceType { get; set; } GeoValidationMethod? IGeoDistanceQuery.ValidationMethod { get; set; } public GeoDistanceQueryDescriptor<T> Location(GeoLocation location) => Assign(a => a.Location = location); public GeoDistanceQueryDescriptor<T> Location(double lat, double lon) => Assign(a => a.Location = new GeoLocation(lat, lon)); public GeoDistanceQueryDescriptor<T> Distance(Distance distance) => Assign(a => a.Distance = distance); public GeoDistanceQueryDescriptor<T> Distance(double distance, DistanceUnit unit) => Assign(a => a.Distance = new Distance(distance, unit)); public GeoDistanceQueryDescriptor<T> DistanceType(GeoDistanceType type) => Assign(a => a.DistanceType = type); public GeoDistanceQueryDescriptor<T> ValidationMethod(GeoValidationMethod? validation) => Assign(a => a.ValidationMethod = validation); } }
39.245902
142
0.767753
[ "Apache-2.0" ]
jslicer/elasticsearch-net
src/Nest/QueryDsl/Geo/Distance/GeoDistanceQuery.cs
2,396
C#
// Copyright (c) Microsoft Corporation // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Xbox.Services.DevTools.XblConfig { using System.Diagnostics.CodeAnalysis; /// <summary> /// Represents a configuration response of type T. /// </summary> /// <typeparam name="T">The strongly typed result of the response.</typeparam> [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleType", Justification = "Contains the same type with different type parameters.")] public class ConfigResponse<T> : ConfigResponseBase { /// <summary> /// Gets or sets result of the response. /// </summary> public T Result { get; set; } } /// <summary> /// Represents a configuration response. /// </summary> public class ConfigResponse : ConfigResponseBase { } }
33.678571
175
0.679745
[ "MIT" ]
Bhaskers-Blu-Org2/xbox-live-developer-tools
Microsoft.Xbox.Service.DevTools/XblConfig/ConfigResponse.cs
945
C#
using OdinPlugs.Wx.Models.MAEModel.EventModel; using OdinPlugs.Wx.Models.MAEModel.MessageModel; namespace OdinPlugs.Wx.Models.MAEModel { public abstract class BaseMessageModel { /// <summary> /// 开发者微信号 /// </summary> public string ToUserName { get; set; } /// <summary> /// 发送方帐号(一个OpenID) /// </summary> public string FromUserName { get; set; } /// <summary> /// 消息创建时间 (整型) /// </summary> public string CreateTime { get; set; } /// <summary> /// 消息类型 /// </summary> public MsgEnumType MsgType { get; set; } public EventEnumType Event { get; set; } public string OpenId { get; set; } public string MsgId { get; set; } } }
27.206897
48
0.546261
[ "MIT" ]
odinsam/OdinPlugs
Wx/Models/MAEModel/BaseMessageModel.cs
847
C#
using System.ComponentModel.DataAnnotations; using EPiServer.DataAbstraction; using EPiServer; namespace Alloy.Models.Blocks { /// <summary> /// Used to insert a link which is styled as a button /// </summary> [SiteContentType(GUID = "426CF12F-1F01-4EA0-922F-0778314DDAF0")] [SiteImageUrl] public class ButtonBlock : SiteBlockData { [Display(Order = 1, GroupName = SystemTabNames.Content)] [Required] public virtual string ButtonText { get; set; } [Display(Order = 2, GroupName = SystemTabNames.Content)] [Required] public virtual Url ButtonLink { get; set; } } }
28.086957
68
0.664087
[ "MIT" ]
Crasnam/episerver-testframework
samples/net48/Alloy/Alloy/Models/Blocks/ButtonBlock.cs
646
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("Senparc.Weixin.WxOpen.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Senparc.Weixin.WxOpen.Tests")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] //将 ComVisible 设置为 false 将使此程序集中的类型 //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("3580b469-c847-457f-8c44-65c26cbb1001")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
26.351351
58
0.716923
[ "Apache-2.0" ]
007008aabb/WeiXinMPSDK
src/Senparc.Weixin.WxOpen/src/Senparc.Weixin.WxOpen.Tests/Properties/AssemblyInfo.cs
1,326
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: EntityCollectionResponse.cs.tt namespace Microsoft.Graph { using System.Collections.Generic; using System.Text.Json.Serialization; /// <summary> /// The type DataClassificationServiceSensitivityLabelsCollectionResponse. /// </summary> public class DataClassificationServiceSensitivityLabelsCollectionResponse { /// <summary> /// Gets or sets the <see cref="IDataClassificationServiceSensitivityLabelsCollectionPage"/> value. /// </summary> [JsonPropertyName("value")] public IDataClassificationServiceSensitivityLabelsCollectionPage Value { get; set; } /// <summary> /// Gets or sets the nextLink string value. /// </summary> [JsonPropertyName("@odata.nextLink")] [JsonConverter(typeof(NextLinkConverter))] public string NextLink { get; set; } /// <summary> /// Gets or sets additional data. /// </summary> [JsonExtensionData] public IDictionary<string, object> AdditionalData { get; set; } } }
38.512821
153
0.601864
[ "MIT" ]
ScriptBox99/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/DataClassificationServiceSensitivityLabelsCollectionResponse.cs
1,502
C#
using System.Threading.Tasks; using CefSharp.Puppeteer; using PuppeteerSharp.Xunit; using Xunit; using Xunit.Abstractions; namespace PuppeteerSharp.Tests.EmulationTests { [Collection(TestConstants.TestFixtureCollectionName)] public class PageEmulateVisionDeficiencyTests : PuppeteerPageBaseTest { public PageEmulateVisionDeficiencyTests(ITestOutputHelper output) : base(output) { } [PuppeteerTest("emulation.spec.ts", "Page.emulateVisionDeficiency", "should work")] public async Task ShouldWork() { await DevToolsContext.SetViewportAsync(new ViewPortOptions { Width = 500, Height = 500 }); await DevToolsContext.GoToAsync(TestConstants.ServerUrl + "/grid.html"); await DevToolsContext.EmulateVisionDeficiencyAsync(VisionDeficiency.None); var screenshot = await DevToolsContext.ScreenshotDataAsync(); Assert.True(ScreenshotHelper.PixelMatch("screenshot-sanity.png", screenshot)); await DevToolsContext.EmulateVisionDeficiencyAsync(VisionDeficiency.Achromatopsia); screenshot = await DevToolsContext.ScreenshotDataAsync(); Assert.True(ScreenshotHelper.PixelMatch("vision-deficiency-achromatopsia.png", screenshot)); await DevToolsContext.EmulateVisionDeficiencyAsync(VisionDeficiency.BlurredVision); screenshot = await DevToolsContext.ScreenshotDataAsync(); Assert.True(ScreenshotHelper.PixelMatch("vision-deficiency-blurredVision.png", screenshot)); await DevToolsContext.EmulateVisionDeficiencyAsync(VisionDeficiency.Deuteranopia); screenshot = await DevToolsContext.ScreenshotDataAsync(); Assert.True(ScreenshotHelper.PixelMatch("vision-deficiency-deuteranopia.png", screenshot)); await DevToolsContext.EmulateVisionDeficiencyAsync(VisionDeficiency.Protanopia); screenshot = await DevToolsContext.ScreenshotDataAsync(); Assert.True(ScreenshotHelper.PixelMatch("vision-deficiency-protanopia.png", screenshot)); await DevToolsContext.EmulateVisionDeficiencyAsync(VisionDeficiency.Tritanopia); screenshot = await DevToolsContext.ScreenshotDataAsync(); Assert.True(ScreenshotHelper.PixelMatch("vision-deficiency-tritanopia.png", screenshot)); await DevToolsContext.EmulateVisionDeficiencyAsync(VisionDeficiency.None); screenshot = await DevToolsContext.ScreenshotDataAsync(); Assert.True(ScreenshotHelper.PixelMatch("screenshot-sanity.png", screenshot)); } } }
50.288462
104
0.734608
[ "MIT" ]
cefsharp/PuppeteerSharp.Embedded
lib/PuppeteerSharp.Tests/EmulationTests/PageEmulateVisionDeficiencyTests.cs
2,615
C#
// Copyright 2018 Esri. // // 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 Esri.ArcGISRuntime.Mapping; using System.Collections.Generic; using Xamarin.Forms; namespace ArcGISRuntime.Samples.LoadWebTiledLayer { [ArcGISRuntime.Samples.Shared.Attributes.Sample( "Web tiled layer", "Layers", "This sample demonstrates how to load a web tiled layer from a non-ArcGIS service, including how to include proper attribution.", "")] public partial class LoadWebTiledLayer : ContentPage { // Templated URL to the tile service private readonly string _templateUri = "https://stamen-tiles-{subdomain}.a.ssl.fastly.net/watercolor/{level}/{col}/{row}.jpg"; // List of subdomains for use when constructing the web tiled layer private readonly List<string> _tiledLayerSubdomains = new List<string> { "a", "b", "c", "d" }; // Attribution string for the Stamen service private readonly string _attribution = "Map tiles by <a href=\"http://stamen.com/\">Stamen Design</a>," + "under <a href=\"http://creativecommons.org/licenses/by/3.0\">CC BY 3.0</a>." + "Data by <a href=\"http://openstreetmap.org/\">OpenStreetMap</a>," + "under <a href=\"http://creativecommons.org/licenses/by-sa/3.0\">CC BY SA</a>."; public LoadWebTiledLayer() { InitializeComponent(); // Create the UI, setup the control references and execute initialization Initialize(); } private void Initialize() { // Create the layer from the URL and the subdomain list WebTiledLayer myBaseLayer = new WebTiledLayer(_templateUri, _tiledLayerSubdomains); // Create a basemap from the layer Basemap layerBasemap = new Basemap(myBaseLayer); // Apply the attribution for the layer myBaseLayer.Attribution = _attribution; // Create a map to hold the basemap Map myMap = new Map(layerBasemap); // Add the map to the map view MyMapView.Map = myMap; } } }
44.852459
137
0.633406
[ "Apache-2.0" ]
ChrisFrenchPDX/arcgis-runtime-samples-dotnet
src/Forms/Shared/Samples/Layers/LoadWebTiledLayer/LoadWebTiledLayer.xaml.cs
2,736
C#
using System; using System.Collections.Generic; using System.Linq; namespace BizHawk.Client.EmuHawk { public class RollColumns : List<RollColumn> { public RollColumn this[string name] => this.SingleOrDefault(column => column.Name == name); public IEnumerable<RollColumn> VisibleColumns => this.Where(c => c.Visible); public Action ChangedCallback { get; set; } // TODO: this shouldn't be exposed. But in order to not expose it, each RollColumn must have a change callback, and all property changes must call it, it is quicker and easier to just call this when needed public void ColumnsChanged() { int pos = 0; foreach (var col in VisibleColumns) { col.Left = pos; pos += col.Width; col.Right = pos; } ChangedCallback?.Invoke(); } public new void Add(RollColumn column) { if (this.Any(c => c.Name == column.Name)) { throw new InvalidOperationException("A column with this name already exists."); } base.Add(column); ColumnsChanged(); } public new void AddRange(IEnumerable<RollColumn> collection) { var items = collection.ToList(); foreach (var column in items) { if (this.Any(c => c.Name == column.Name)) { throw new InvalidOperationException("A column with this name already exists."); } } base.AddRange(items); ColumnsChanged(); } public new void Insert(int index, RollColumn column) { if (this.Any(c => c.Name == column.Name)) { throw new InvalidOperationException("A column with this name already exists."); } base.Insert(index, column); ColumnsChanged(); } public new void InsertRange(int index, IEnumerable<RollColumn> collection) { var items = collection.ToList(); foreach (var column in items) { if (this.Any(c => c.Name == column.Name)) { throw new InvalidOperationException("A column with this name already exists."); } } base.InsertRange(index, items); ColumnsChanged(); } public new bool Remove(RollColumn column) { var result = base.Remove(column); ColumnsChanged(); return result; } public new int RemoveAll(Predicate<RollColumn> match) { var result = base.RemoveAll(match); ColumnsChanged(); return result; } public new void RemoveAt(int index) { base.RemoveAt(index); ColumnsChanged(); } public new void RemoveRange(int index, int count) { base.RemoveRange(index, count); ColumnsChanged(); } public new void Clear() { base.Clear(); ColumnsChanged(); } public IEnumerable<string> Groups => this .Select(x => x.Group) .Distinct(); } }
22.033613
208
0.666667
[ "MIT" ]
RetroEdit/BizHawk
src/BizHawk.Client.EmuHawk/CustomControls/InputRoll/RollColumns.cs
2,624
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Microsoft.AspNetCore.Razor.Language { /// <summary> /// The mode in which an element should render. /// </summary> public enum TagMode { /// <summary> /// Include both start and end tags. /// </summary> StartTagAndEndTag, /// <summary> /// A self-closed tag. /// </summary> SelfClosing, /// <summary> /// Only a start tag. /// </summary> StartTagOnly } }
26.12
111
0.566616
[ "Apache-2.0" ]
belav/aspnetcore
src/Razor/Microsoft.AspNetCore.Razor.Language/src/TagMode.cs
653
C#
// Copyright (c) Microsoft Open Technologies, Inc. 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.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { partial struct MetadataTypeName { /// <summary> /// A digest of MetadataTypeName's fully qualified name which can be used as the key in a dictionary /// </summary> public struct Key : IEquatable<Key> { // PERF: We can work with either a fully qualified name (a single string) or // a 'split' name (namespace and type). If typeName is null, then a FQN is // stored in namespaceOrFullyQualifiedName private readonly string namespaceOrFullyQualifiedName; private readonly string typeName; private readonly byte useCLSCompliantNameArityEncoding; // Using byte instead of bool for denser packing and smaller structure size private readonly short forcedArity; internal Key(MetadataTypeName mdTypeName) { if (mdTypeName.IsNull) { this.namespaceOrFullyQualifiedName = null; this.typeName = null; this.useCLSCompliantNameArityEncoding = 0; this.forcedArity = 0; } else { if (mdTypeName.fullName != null) { this.namespaceOrFullyQualifiedName = mdTypeName.fullName; this.typeName = null; } else { Debug.Assert(mdTypeName.namespaceName != null); Debug.Assert(mdTypeName.typeName != null); this.namespaceOrFullyQualifiedName = mdTypeName.namespaceName; this.typeName = mdTypeName.typeName; } this.useCLSCompliantNameArityEncoding = mdTypeName.UseCLSCompliantNameArityEncoding ? (byte)1 : (byte)0; this.forcedArity = mdTypeName.forcedArity; } } private bool HasFullyQualifiedName { get { return this.typeName == null; } } public bool Equals(Key other) { return useCLSCompliantNameArityEncoding == other.useCLSCompliantNameArityEncoding && forcedArity == other.forcedArity && EqualNames(ref other); } private bool EqualNames(ref Key other) { if (this.typeName == other.typeName) { return this.namespaceOrFullyQualifiedName == other.namespaceOrFullyQualifiedName; } if (this.HasFullyQualifiedName) { return MetadataHelpers.SplitNameEqualsFullyQualifiedName(other.namespaceOrFullyQualifiedName, other.typeName, this.namespaceOrFullyQualifiedName); } if (other.HasFullyQualifiedName) { return MetadataHelpers.SplitNameEqualsFullyQualifiedName(this.namespaceOrFullyQualifiedName, this.typeName, other.namespaceOrFullyQualifiedName); } return false; } public override bool Equals(object obj) { return obj is Key && this.Equals((Key)obj); } public override int GetHashCode() { return Hash.Combine(GetHashCodeName(), Hash.Combine(useCLSCompliantNameArityEncoding != 0, forcedArity)); } private int GetHashCodeName() { int hashCode = Hash.GetFNVHashCode(this.namespaceOrFullyQualifiedName); if (!this.HasFullyQualifiedName) { hashCode = Hash.CombineFNVHash(hashCode, MetadataHelpers.DotDelimiter); hashCode = Hash.CombineFNVHash(hashCode, this.typeName); } return hashCode; } } public Key ToKey() { return new Key(this); } } }
37.15
184
0.537012
[ "ECL-2.0", "Apache-2.0" ]
binsys/roslyn_java
Src/Compilers/Core/Source/MetadataReader/MetadataTypeName.Key.cs
4,460
C#
// Copyright (c) Microsoft. All rights reserved. namespace Microsoft.VisualStudio.Composition { using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.Composition.Reflection; public class CachedComposition : ICompositionCacheManager, IRuntimeCompositionCacheManager { private static readonly Encoding TextEncoding = Encoding.UTF8; public Task SaveAsync(CompositionConfiguration configuration, Stream cacheStream, CancellationToken cancellationToken = default(CancellationToken)) { Requires.NotNull(configuration, nameof(configuration)); Requires.NotNull(cacheStream, nameof(cacheStream)); Requires.Argument(cacheStream.CanWrite, "cacheStream", Strings.WritableStreamRequired); return Task.Run(async delegate { var compositionRuntime = RuntimeComposition.CreateRuntimeComposition(configuration); await this.SaveAsync(compositionRuntime, cacheStream, cancellationToken).ConfigureAwait(false); }); } public Task SaveAsync(RuntimeComposition composition, Stream cacheStream, CancellationToken cancellationToken = default(CancellationToken)) { Requires.NotNull(composition, nameof(composition)); Requires.NotNull(cacheStream, nameof(cacheStream)); Requires.Argument(cacheStream.CanWrite, "cacheStream", Strings.WritableStreamRequired); return Task.Run(() => { using (var writer = new BinaryWriter(cacheStream, TextEncoding, leaveOpen: true)) { var context = new SerializationContext(writer, composition.Parts.Count * 5, composition.Resolver); context.Write(composition); context.FinalizeObjectTableCapacity(); } }); } public Task<RuntimeComposition> LoadRuntimeCompositionAsync(Stream cacheStream, Resolver resolver, CancellationToken cancellationToken = default(CancellationToken)) { Requires.NotNull(cacheStream, nameof(cacheStream)); Requires.Argument(cacheStream.CanRead, "cacheStream", Strings.ReadableStreamRequired); Requires.NotNull(resolver, nameof(resolver)); return Task.Run(() => { using (var reader = new BinaryReader(cacheStream, TextEncoding, leaveOpen: true)) { var context = new SerializationContext(reader, resolver); var runtimeComposition = context.ReadRuntimeComposition(); return runtimeComposition; } }); } public async Task<IExportProviderFactory> LoadExportProviderFactoryAsync(Stream cacheStream, Resolver resolver, CancellationToken cancellationToken = default(CancellationToken)) { var runtimeComposition = await this.LoadRuntimeCompositionAsync(cacheStream, resolver, cancellationToken).ConfigureAwait(false); return runtimeComposition.CreateExportProviderFactory(); } private class SerializationContext : SerializationContextBase { internal SerializationContext(BinaryReader reader, Resolver resolver) : base(reader, resolver) { } internal SerializationContext(BinaryWriter writer, int estimatedObjectCount, Resolver resolver) : base(writer, estimatedObjectCount, resolver) { } private enum RuntimeImportFlags : byte { None = 0x00, IsNonSharedInstanceRequired = 0x01, IsExportFactory = 0x02, CardinalityExactlyOne = 0x04, CardinalityOneOrZero = 0x08, IsParameter = 0x10, } internal void Write(RuntimeComposition compositionRuntime) { Requires.NotNull(this.writer, "writer"); Requires.NotNull(compositionRuntime, nameof(compositionRuntime)); using (this.Trace("RuntimeComposition")) { this.Write(compositionRuntime.Parts, this.Write); this.Write(compositionRuntime.MetadataViewsAndProviders); } this.TraceStats(); } internal RuntimeComposition ReadRuntimeComposition() { Requires.NotNull(this.reader, "reader"); RuntimeComposition result; using (this.Trace("RuntimeComposition")) { var parts = this.ReadList(this.reader, this.ReadRuntimePart); var metadataViewsAndProviders = this.ReadMetadataViewsAndProviders(); result = RuntimeComposition.CreateRuntimeComposition(parts, metadataViewsAndProviders, this.Resolver); } this.TraceStats(); return result; } private void Write(RuntimeComposition.RuntimeExport export) { using (this.Trace("RuntimeExport")) { if (this.TryPrepareSerializeReusableObject(export)) { this.Write(export.ContractName); this.Write(export.DeclaringTypeRef); this.Write(export.MemberRef); this.Write(export.ExportedValueTypeRef); this.Write(export.Metadata); } } } private RuntimeComposition.RuntimeExport ReadRuntimeExport() { using (this.Trace("RuntimeExport")) { uint id; RuntimeComposition.RuntimeExport value; if (this.TryPrepareDeserializeReusableObject(out id, out value)) { var contractName = this.ReadString(); var declaringType = this.ReadTypeRef(); var member = this.ReadMemberRef(); var exportedValueType = this.ReadTypeRef(); var metadata = this.ReadMetadata(); value = new RuntimeComposition.RuntimeExport( contractName, declaringType, member, exportedValueType, metadata); this.OnDeserializedReusableObject(id, value); } return value; } } private void Write(RuntimeComposition.RuntimePart part) { using (this.Trace("RuntimePart")) { this.Write(part.TypeRef); this.Write(part.Exports, this.Write); if (part.ImportingConstructorOrFactoryMethodRef == null) { this.writer.Write(false); } else { this.writer.Write(true); this.Write(part.ImportingConstructorOrFactoryMethodRef); this.Write(part.ImportingConstructorArguments, this.Write); } this.Write(part.ImportingMembers, this.Write); this.Write(part.OnImportsSatisfiedRef); this.Write(part.SharingBoundary); } } private RuntimeComposition.RuntimePart ReadRuntimePart() { using (this.Trace("RuntimePart")) { MethodRef importingCtor = default(MethodRef); IReadOnlyList<RuntimeComposition.RuntimeImport> importingCtorArguments = ImmutableList<RuntimeComposition.RuntimeImport>.Empty; var type = this.ReadTypeRef(); var exports = this.ReadList(this.reader, this.ReadRuntimeExport); bool hasCtor = this.reader.ReadBoolean(); if (hasCtor) { importingCtor = this.ReadMethodRef(); importingCtorArguments = this.ReadList(this.reader, this.ReadRuntimeImport); } var importingMembers = this.ReadList(this.reader, this.ReadRuntimeImport); var onImportsSatisfied = this.ReadMethodRef(); var sharingBoundary = this.ReadString(); return new RuntimeComposition.RuntimePart( type, importingCtor, importingCtorArguments, importingMembers, exports, onImportsSatisfied, sharingBoundary); } } private void Write(RuntimeComposition.RuntimeImport import) { using (this.Trace("RuntimeImport")) { RuntimeImportFlags flags = RuntimeImportFlags.None; flags |= import.ImportingMemberRef == null ? RuntimeImportFlags.IsParameter : 0; flags |= import.IsNonSharedInstanceRequired ? RuntimeImportFlags.IsNonSharedInstanceRequired : 0; flags |= import.IsExportFactory ? RuntimeImportFlags.IsExportFactory : 0; flags |= import.Cardinality == ImportCardinality.ExactlyOne ? RuntimeImportFlags.CardinalityExactlyOne : import.Cardinality == ImportCardinality.OneOrZero ? RuntimeImportFlags.CardinalityOneOrZero : 0; this.writer.Write((byte)flags); if (import.ImportingMemberRef == null) { this.Write(import.ImportingParameterRef); } else { this.Write(import.ImportingMemberRef); } this.Write(import.ImportingSiteTypeRef); if (import.Cardinality == ImportCardinality.ZeroOrMore) { this.Write(import.ImportingSiteTypeWithoutCollectionRef); } else { if (import.ImportingSiteTypeWithoutCollectionRef != import.ImportingSiteTypeRef) { throw new ArgumentException($"{nameof(import.ImportingSiteTypeWithoutCollectionRef)} and {nameof(import.ImportingSiteTypeRef)} must be equal when {nameof(import.Cardinality)} is not {nameof(ImportCardinality.ZeroOrMore)}.", nameof(import)); } } this.Write(import.SatisfyingExports, this.Write); this.Write(import.Metadata); if (import.IsExportFactory) { this.Write(import.ExportFactorySharingBoundaries, this.Write); } } } private RuntimeComposition.RuntimeImport ReadRuntimeImport() { using (this.Trace("RuntimeImport")) { var flags = (RuntimeImportFlags)this.reader.ReadByte(); var cardinality = flags.HasFlag(RuntimeImportFlags.CardinalityOneOrZero) ? ImportCardinality.OneOrZero : flags.HasFlag(RuntimeImportFlags.CardinalityExactlyOne) ? ImportCardinality.ExactlyOne : ImportCardinality.ZeroOrMore; bool isExportFactory = flags.HasFlag(RuntimeImportFlags.IsExportFactory); MemberRef importingMember = default(MemberRef); ParameterRef importingParameter = default(ParameterRef); if (flags.HasFlag(RuntimeImportFlags.IsParameter)) { importingParameter = this.ReadParameterRef(); } else { importingMember = this.ReadMemberRef(); } var importingSiteTypeRef = this.ReadTypeRef(); TypeRef importingSiteTypeWithoutCollectionRef = cardinality == ImportCardinality.ZeroOrMore ? this.ReadTypeRef() : importingSiteTypeRef; var satisfyingExports = this.ReadList(this.reader, this.ReadRuntimeExport); var metadata = this.ReadMetadata(); IReadOnlyList<string> exportFactorySharingBoundaries = isExportFactory ? this.ReadList(this.reader, this.ReadString) : ImmutableList<string>.Empty; return importingMember == null ? new RuntimeComposition.RuntimeImport( importingParameter, importingSiteTypeRef, importingSiteTypeWithoutCollectionRef, cardinality, satisfyingExports, flags.HasFlag(RuntimeImportFlags.IsNonSharedInstanceRequired), isExportFactory, metadata, exportFactorySharingBoundaries) : new RuntimeComposition.RuntimeImport( importingMember, importingSiteTypeRef, importingSiteTypeWithoutCollectionRef, cardinality, satisfyingExports, flags.HasFlag(RuntimeImportFlags.IsNonSharedInstanceRequired), isExportFactory, metadata, exportFactorySharingBoundaries); } } private void Write(IReadOnlyDictionary<TypeRef, RuntimeComposition.RuntimeExport> metadataTypesAndProviders) { using (this.Trace("MetadataTypesAndProviders")) { this.WriteCompressedUInt((uint)metadataTypesAndProviders.Count); foreach (var item in metadataTypesAndProviders) { this.Write(item.Key); this.Write(item.Value); } } } private IReadOnlyDictionary<TypeRef, RuntimeComposition.RuntimeExport> ReadMetadataViewsAndProviders() { using (this.Trace("MetadataTypesAndProviders")) { uint count = this.ReadCompressedUInt(); var builder = ImmutableDictionary.CreateBuilder<TypeRef, RuntimeComposition.RuntimeExport>(); for (uint i = 0; i < count; i++) { var key = this.ReadTypeRef(); var value = this.ReadRuntimeExport(); builder.Add(key, value); } return builder.ToImmutable(); } } } } }
44.397759
268
0.536467
[ "MIT" ]
Bhaskers-Blu-Org2/vs-mef
src/Microsoft.VisualStudio.Composition/Configuration/CachedComposition.cs
15,852
C#
using PoGo.ApiClient.Interfaces; using PoGo.GameServices.Player; using POGOProtos.Data; using POGOProtos.Data.Player; using POGOProtos.Inventory.Item; using POGOProtos.Networking.Responses; using System.Collections.Generic; namespace PoGo.GameServices { /// <summary> /// Manages the game logic for dealing with the player, including Achievements, Stats, and Level Rewards. /// </summary> public class PlayerService : GameServiceBase { #region Private Members private LevelUpRewards _levelUpRewards; private PlayerData _profile; private PlayerStats _stats; #endregion #region Properties /// <summary> /// /// </summary> public LevelUpRewards LevelUpRewards { get { return _levelUpRewards; } set { Set(ref _levelUpRewards, value); } } /// <summary> /// /// </summary> public PlayerData Profile { get { return _profile; } set { Set(ref _profile, value); } } /// <summary> /// /// </summary> public PlayerStats Stats { get { return _stats; } set { Set(ref _stats, value); } } #endregion #region Constructors /// <summary> /// Creates a new instance of the <see cref="PokedexService"/>. /// </summary> /// <param name="apiClient">The <see cref="IPokemonGoApiClient"/> instance to use for any Pokemon Go API requests.</param> public PlayerService(IPokemonGoApiClient apiClient) : base(apiClient) { LevelUpRewards = default(LevelUpRewards); Profile = default(PlayerData); Stats = default(PlayerStats); } #endregion #region Public Methods /// <summary> /// /// </summary> public override void ResetState() { LevelUpRewards = null; Profile = null; Stats = null; } /// <summary> /// /// </summary> public override void RegisterClientEvents() { ApiClient.CheckCodenameAvailableReceived += CheckCodenameAvailableReceived; ApiClient.ClaimCodenameReceived += ClaimCodenameReceived; ApiClient.CollectDailyBonusReceived += CollectDailyBonusReceived; ApiClient.CollectDailyDefenderBonusReceived += CollectDailyDefenderBonusReceived; ApiClient.EquipBadgeReceived += EquipBadgeReceived; ApiClient.PlayerReceived += PlayerReceived; ApiClient.PlayerProfileReceived += PlayerProfileReceived; ApiClient.CheckAwardedBadgesReceived += CheckAwardedBadgesReceived; ApiClient.LevelUpRewardsReceived += LevelUpRewardsReceived; ApiClient.SuggestedCodenamesReceived += SuggestedCodenamesReceived; ApiClient.MarkTutorialCompleteReceived += MarkTutorialCompleteReceived; ApiClient.AvatarReceived += AvatarReceived; ApiClient.ContactSettingsReceived += ContactSettingsReceived; ApiClient.PlayerTeamReceived += PlayerTeamReceived; ApiClient.PlayerUpdateReceived += PlayerUpdateReceived; } /// <summary> /// /// </summary> public override void UnregisterClientEvents() { ApiClient.CheckCodenameAvailableReceived -= CheckCodenameAvailableReceived; ApiClient.ClaimCodenameReceived -= ClaimCodenameReceived; ApiClient.CollectDailyBonusReceived -= CollectDailyBonusReceived; ApiClient.CollectDailyDefenderBonusReceived -= CollectDailyDefenderBonusReceived; ApiClient.EquipBadgeReceived -= EquipBadgeReceived; ApiClient.PlayerReceived -= PlayerReceived; ApiClient.PlayerProfileReceived -= PlayerProfileReceived; ApiClient.CheckAwardedBadgesReceived -= CheckAwardedBadgesReceived; ApiClient.LevelUpRewardsReceived -= LevelUpRewardsReceived; ApiClient.SuggestedCodenamesReceived -= SuggestedCodenamesReceived; ApiClient.MarkTutorialCompleteReceived -= MarkTutorialCompleteReceived; ApiClient.AvatarReceived -= AvatarReceived; ApiClient.ContactSettingsReceived -= ContactSettingsReceived; ApiClient.PlayerTeamReceived -= PlayerTeamReceived; ApiClient.PlayerUpdateReceived -= PlayerUpdateReceived; } #endregion #region Event Handlers private void CheckCodenameAvailableReceived(object sender, CheckCodenameAvailableResponse e) { throw new System.NotImplementedException(); } private void ClaimCodenameReceived(object sender, ClaimCodenameResponse e) { throw new System.NotImplementedException(); } private void CollectDailyBonusReceived(object sender, CollectDailyBonusResponse e) { throw new System.NotImplementedException(); } private void CollectDailyDefenderBonusReceived(object sender, CollectDailyDefenderBonusResponse e) { throw new System.NotImplementedException(); } private void EquipBadgeReceived(object sender, EquipBadgeResponse e) { throw new System.NotImplementedException(); } private void PlayerReceived(object sender, GetPlayerResponse e) { if (e.Success && e.PlayerData != null) { Profile = e.PlayerData; //ApiClient.Download.QueueDownloadRemoteConfigVersionRequest(); //ApiClient.Download.QueueGetAssetDigestRequest(); //ApiClient.Player.QueueGetLevelUpRewardsRequest(); } } private void PlayerProfileReceived(object sender, GetPlayerProfileResponse e) { if (e.Result == GetPlayerProfileResponse.Types.Result.Success) { throw new System.NotImplementedException(); } } private void CheckAwardedBadgesReceived(object sender, CheckAwardedBadgesResponse e) { throw new System.NotImplementedException(); } private void LevelUpRewardsReceived(object sender, LevelUpRewardsResponse e) { if (e.Result == LevelUpRewardsResponse.Types.Result.Success && e.CalculateSize() > 0) { LevelUpRewards = new LevelUpRewards(new List<ItemAward>(e.ItemsAwarded), new List<ItemId>(e.ItemsUnlocked)); } } private void SuggestedCodenamesReceived(object sender, GetSuggestedCodenamesResponse e) { throw new System.NotImplementedException(); } private void MarkTutorialCompleteReceived(object sender, MarkTutorialCompleteResponse e) { throw new System.NotImplementedException(); } private void AvatarReceived(object sender, SetAvatarResponse e) { throw new System.NotImplementedException(); } private void ContactSettingsReceived(object sender, SetContactSettingsResponse e) { throw new System.NotImplementedException(); } private void PlayerTeamReceived(object sender, SetPlayerTeamResponse e) { throw new System.NotImplementedException(); } private void PlayerUpdateReceived(object sender, PlayerUpdateResponse e) { throw new System.NotImplementedException(); } #endregion } }
34.183036
130
0.633407
[ "MIT" ]
PoGo-Devs/PoGo
src/PoGo.GameServices/PlayerService.cs
7,659
C#
/****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2018. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using Leap.Unity.Query; using System; using System.Collections.Generic; using System.Reflection; using UnityEditor; using UnityEngine; using UnityEngine.SceneManagement; namespace Leap.Unity { using UnityObject = UnityEngine.Object; public static class EditorUtils { private class SceneReference<T> where T : UnityObject { SerializedObject objectContainingReference; SerializedProperty reference; } /// <summary> /// Scans the currently-open scene for references of a and replaces them with b. /// These swaps are performed with Undo.RecordObject before an object's references /// are changed, so they can be undone. /// </summary> public static void ReplaceSceneReferences<T>(T a, T b) where T : UnityObject { var aId = a.GetInstanceID(); var refType = typeof(T); var curScene = SceneManager.GetActiveScene(); var rootObjs = curScene.GetRootGameObjects(); foreach (var rootObj in rootObjs) { var transforms = rootObj.GetComponentsInChildren<Transform>(); foreach (var transform in transforms) { var components = transform.GetComponents<Component>(); var objectChanges = new List<Action>(); foreach (var component in components) { var compType = typeof(Component); var fieldInfos = compType.GetFields(BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Public); foreach (var fieldInfo in fieldInfos.Query() .Where(fi => fi.FieldType.IsAssignableFrom(refType))) { var refValue = fieldInfo.GetValue(component) as T; if (refValue.GetInstanceID() == aId) { objectChanges.Add(() => { fieldInfo.SetValue(fieldInfo, b); }); } } } if (objectChanges.Count > 0) { Undo.RecordObject(transform.gameObject, "Swap " + transform.name + " references from " + a.name + " to " + b.name); foreach (var change in objectChanges) { change(); } } } } } } }
38.04
89
0.557308
[ "Apache-2.0" ]
6henrykim/UnityExamples
UnityExamples/Assets/LeapMotion/Core/Scripts/Utils/Editor/EditorUtils.cs
2,853
C#
namespace FastFood.DataProcessor.Dto.Export { using Models; public class TransientItemDto { public string Name { get; set; } public Item MostPopularItem { get; set; } } }
18.636364
49
0.634146
[ "MIT" ]
mayapeneva/DATABASE-Advanced-Entity-Framework
EXAMS/Exam_2017.12.10_FastFood/FastFood.DataProcessor/Dto/Export/TransientItemDto.cs
207
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using OAuthApp.Data; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace OAuthApp.Areas.Identity.Pages.Account.Manage { public partial class IndexModel : PageModel { private readonly UserManager<AppUser> _userManager; private readonly SignInManager<AppUser> _signInManager; public IndexModel( UserManager<AppUser> userManager, SignInManager<AppUser> signInManager) { _userManager = userManager; _signInManager = signInManager; } public string Username { get; set; } [TempData] public string StatusMessage { get; set; } [BindProperty] public InputModel Input { get; set; } public class InputModel { [Phone] [Display(Name = "Phone number")] public string PhoneNumber { get; set; } } private async Task LoadAsync(AppUser user) { var userName = await _userManager.GetUserNameAsync(user); var phoneNumber = await _userManager.GetPhoneNumberAsync(user); Username = userName; Input = new InputModel { PhoneNumber = phoneNumber }; } public async Task<IActionResult> OnGetAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } await LoadAsync(user); return Page(); } public async Task<IActionResult> OnPostAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } if (!ModelState.IsValid) { await LoadAsync(user); return Page(); } var phoneNumber = await _userManager.GetPhoneNumberAsync(user); if (Input.PhoneNumber != phoneNumber) { var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, Input.PhoneNumber); if (!setPhoneResult.Succeeded) { var userId = await _userManager.GetUserIdAsync(user); throw new InvalidOperationException($"Unexpected error occurred setting phone number for user with ID '{userId}'."); } } await _signInManager.RefreshSignInAsync(user); StatusMessage = "Your profile has been updated"; return RedirectToPage(); } } }
30.505155
136
0.576546
[ "Apache-2.0" ]
geffzhang/IdentityServer4.MicroService
OAuthApp/Areas/Identity/Pages/Account/Manage/Index.cshtml.cs
2,959
C#
using System; namespace Model { /// <summary> /// Contains information about college semester, such as when it starts, when it ends, what the name of semester is. /// </summary> public class Semester { //CONSTRUCTOR /// <param name="Id">ID of semester e.g 10</param> /// <param name="Name">Name of semester e.g Semester 2 2021</param> /// <param name="StartDate">The date when the semester starts e.g 2021-01-30 (YYYY-MM-DD)</param> /// <param name="FinishDate">The date when the semester ends e.g 2021-07-15 (YYYY-MM-DD)</param> public Semester(int Id, string Name, DateTime StartDate, DateTime FinishDate) { this.Id = Id; this.Name = Name; this.StartDate = StartDate; this.FinishDate = FinishDate; } //PROPERTIES public int Id { get; set; } public string Name { get; set; } public DateTime StartDate { get; set; } public DateTime FinishDate { get; set; } //METHODS public override string ToString() { return Name + ". " + StartDate.ToString("dd/MM/yyyy").Replace('-', '/') + " - " + FinishDate.ToString("dd/MM/yyyy").Replace('-', '/'); } } }
32.175
120
0.561772
[ "MIT" ]
A-Abdiukov/EnrolmentWPF
CollegeManager/BusinessLayer/Semester.cs
1,289
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the s3control-2018-08-20.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.S3Control.Model { /// <summary> /// Container for the parameters to the GetBucketTagging operation. /// <note> /// <para> /// This action gets an Amazon S3 on Outposts bucket's tags. To get an S3 bucket tags, /// see <a href="https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketTagging.html">GetBucketTagging</a> /// in the <i>Amazon S3 API Reference</i>. /// </para> /// </note> /// <para> /// Returns the tag set associated with the Outposts bucket. For more information, see /// <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/S3onOutposts.html">Using /// Amazon S3 on Outposts</a> in the <i>Amazon S3 User Guide</i>. /// </para> /// /// <para> /// To use this action, you must have permission to perform the <code>GetBucketTagging</code> /// action. By default, the bucket owner has this permission and can grant this permission /// to others. /// </para> /// /// <para> /// <code>GetBucketTagging</code> has the following special error: /// </para> /// <ul> <li> /// <para> /// Error code: <code>NoSuchTagSetError</code> /// </para> /// <ul> <li> /// <para> /// Description: There is no tag set associated with the bucket. /// </para> /// </li> </ul> </li> </ul> /// <para> /// All Amazon S3 on Outposts REST API requests for this action require an additional /// parameter of <code>x-amz-outpost-id</code> to be passed with the request and an S3 /// on Outposts endpoint hostname prefix instead of <code>s3-control</code>. For an example /// of the request syntax for Amazon S3 on Outposts that uses the S3 on Outposts endpoint /// hostname prefix and the <code>x-amz-outpost-id</code> derived using the access point /// ARN, see the <a href="https://docs.aws.amazon.com/AmazonS3/latest/API/API_control_GetBucketTagging.html#API_control_GetBucketTagging_Examples">Examples</a> /// section. /// </para> /// /// <para> /// The following actions are related to <code>GetBucketTagging</code>: /// </para> /// <ul> <li> /// <para> /// <a href="https://docs.aws.amazon.com/AmazonS3/latest/API/API_control_PutBucketTagging.html">PutBucketTagging</a> /// /// </para> /// </li> <li> /// <para> /// <a href="https://docs.aws.amazon.com/AmazonS3/latest/API/API_control_DeleteBucketTagging.html">DeleteBucketTagging</a> /// /// </para> /// </li> </ul> /// </summary> public partial class GetBucketTaggingRequest : AmazonS3ControlRequest { private string _accountId; private string _bucket; /// <summary> /// Gets and sets the property AccountId. /// <para> /// The account ID of the Outposts bucket. /// </para> /// </summary> [AWSProperty(Required=true, Max=64)] public string AccountId { get { return this._accountId; } set { this._accountId = value; } } // Check to see if AccountId property is set internal bool IsSetAccountId() { return this._accountId != null; } /// <summary> /// Gets and sets the property Bucket. /// <para> /// Specifies the bucket. /// </para> /// /// <para> /// For using this parameter with Amazon S3 on Outposts with the REST API, you must specify /// the name and the x-amz-outpost-id as well. /// </para> /// /// <para> /// For using this parameter with S3 on Outposts with the Amazon Web Services SDK and /// CLI, you must specify the ARN of the bucket accessed in the format <code>arn:aws:s3-outposts:&lt;Region&gt;:&lt;account-id&gt;:outpost/&lt;outpost-id&gt;/bucket/&lt;my-bucket-name&gt;</code>. /// For example, to access the bucket <code>reports</code> through outpost <code>my-outpost</code> /// owned by account <code>123456789012</code> in Region <code>us-west-2</code>, use the /// URL encoding of <code>arn:aws:s3-outposts:us-west-2:123456789012:outpost/my-outpost/bucket/reports</code>. /// The value must be URL encoded. /// </para> /// </summary> [AWSProperty(Required=true, Min=3, Max=255)] public string Bucket { get { return this._bucket; } set { this._bucket = value; } } // Check to see if Bucket property is set internal bool IsSetBucket() { return this._bucket != null; } } }
37.789116
203
0.613861
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/S3Control/Generated/Model/GetBucketTaggingRequest.cs
5,555
C#
using HarmonyLib; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace VSHUD { public static class HackMan { public static T GetField<T>(this object instance, string fieldname) => (T)AccessTools.Field(instance.GetType(), fieldname).GetValue(instance); public static T GetProperty<T>(this object instance, string fieldname) => (T)AccessTools.Property(instance.GetType(), fieldname).GetValue(instance); public static object CreateInstance(this Type type) => AccessTools.CreateInstance(type); public static T[] GetFields<T>(this object instance) { List<T> fields = new List<T>(); var declaredFields = AccessTools.GetDeclaredFields(instance.GetType())?.Where((t) => t.FieldType == typeof(T)); foreach (var val in declaredFields) { fields.Add(instance.GetField<T>(val.Name)); } return fields.ToArray(); } public static void SetField(this object instance, string fieldname, object setVal) => AccessTools.Field(instance.GetType(), fieldname).SetValue(instance, setVal); public static void CallMethod(this object instance, string method) => instance?.CallMethod(method, null); public static void CallMethod(this object instance, string method, params object[] args) => instance?.CallMethod<object>(method, args); public static T CallMethod<T>(this object instance, string method) => (T)instance.CallMethod<object>(method, null); public static T CallMethod<T>(this object instance, string method, params object[] args) { Type[] parameters = null; if (args != null) { parameters = args.Length > 0 ? new Type[args.Length] : null; for (int i = 0; i < args.Length; i++) { parameters[i] = args[i].GetType(); } } return (T)instance?.GetMethod(method, parameters).Invoke(instance, args); } public static MethodInfo GetMethod(this object instance, string method, params Type[] parameters) => instance.GetMethod(method, parameters, null); public static MethodInfo GetMethod(this object instance, string method, Type[] parameters = null, Type[] generics = null) => AccessTools.Method(instance.GetType(), method, parameters, generics); } }
49.77551
202
0.646166
[ "Unlicense" ]
Novocain1/MiscMods
VSHUD/Utility/HackMan.cs
2,441
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Cloudaudit.V20190319.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class Resources : AbstractModel { /// <summary> /// Resource type /// </summary> [JsonProperty("ResourceType")] public string ResourceType{ get; set; } /// <summary> /// Resource ID /// </summary> [JsonProperty("ResourceId")] public string ResourceId{ get; set; } /// <summary> /// Resource creation time /// </summary> [JsonProperty("CreateTime")] public string CreateTime{ get; set; } /// <summary> /// Resource region /// </summary> [JsonProperty("ResourceRegion")] public string ResourceRegion{ get; set; } /// <summary> /// Resource alias /// </summary> [JsonProperty("ResourceAlias")] public string ResourceAlias{ get; set; } /// <summary> /// Whether the resource is deleted /// </summary> [JsonProperty("IsDeleted")] public bool? IsDeleted{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "ResourceType", this.ResourceType); this.SetParamSimple(map, prefix + "ResourceId", this.ResourceId); this.SetParamSimple(map, prefix + "CreateTime", this.CreateTime); this.SetParamSimple(map, prefix + "ResourceRegion", this.ResourceRegion); this.SetParamSimple(map, prefix + "ResourceAlias", this.ResourceAlias); this.SetParamSimple(map, prefix + "IsDeleted", this.IsDeleted); } } }
31.936709
85
0.612366
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet-intl-en
TencentCloud/Cloudaudit/V20190319/Models/Resources.cs
2,523
C#
using System; using System.Reflection; using Eto.Forms; using MonoTouch.UIKit; namespace Eto.Platform.iOS.Forms.Controls { public class CheckBoxHandler : iosControl<UISwitch, CheckBox>, ICheckBox { public CheckBoxHandler() { Control = new UISwitch(); Control.ValueChanged += delegate { Widget.OnCheckedChanged(EventArgs.Empty); }; } public string Text { get { return null; } set { } } public bool ThreeState { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public bool? Checked { get { return Control.On; } set { Control.On = value ?? false; } } } }
15.659091
73
0.638607
[ "BSD-3-Clause" ]
carlokok/Eto
Source/Eto.Platform.iOS/Forms/Controls/CheckBoxHandler.cs
689
C#
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Numerics; using Schemavolution.Specification.Implementation; namespace Schemavolution.Specification.Genes { class CreateForeignKeyGene : TableDefinitionGene { private readonly IndexGene _parent; private readonly CreatePrimaryKeyGene _referencing; private readonly bool _cascadeDelete; private readonly bool _cascadeUpdate; public string DatabaseName => _parent.DatabaseName; public string SchemaName => _parent.SchemaName; public string TableName => _parent.TableName; public IEnumerable<CreateColumnGene> Columns => _parent.Columns; internal override CreateTableGene CreateTableGene => _parent.CreateTableGene; public CreateForeignKeyGene(IndexGene parent, CreatePrimaryKeyGene referencing, bool cascadeDelete, bool cascadeUpdate, ImmutableList<Gene> prerequsites) : base(prerequsites) { _parent = parent; _referencing = referencing; _cascadeDelete = cascadeDelete; _cascadeUpdate = cascadeUpdate; } public override IEnumerable<Gene> AllPrerequisites => Prerequisites .Concat(new[] { CreateTableGene }); public override string[] GenerateSql(EvolutionHistoryBuilder genesAffected, IGraphVisitor graph) { string indexTail = string.Join("_", Columns.Select(c => $"{c.ColumnName}").ToArray()); string columnList = string.Join(", ", Columns.Select(c => $"[{c.ColumnName}]").ToArray()); string referenceColumnList = string.Join(", ", _referencing.Columns.Select(c => $"[{c.ColumnName}]").ToArray()); string onDelete = _cascadeDelete ? " ON DELETE CASCADE" : ""; string onUpdate = _cascadeUpdate ? " ON UPDATE CASCADE" : ""; string[] sql = { $@"ALTER TABLE [{DatabaseName}].[{SchemaName}].[{TableName}] ADD CONSTRAINT [FK_{TableName}_{indexTail}] FOREIGN KEY ({columnList}) REFERENCES [{_referencing.DatabaseName}].[{_referencing.SchemaName}].[{_referencing.TableName}] ({referenceColumnList}){onDelete}{onUpdate}" }; return sql; } public override string[] GenerateRollbackSql(EvolutionHistoryBuilder genesAffected, IGraphVisitor graph) { string indexTail = string.Join("_", Columns.Select(c => $"{c.ColumnName}").ToArray()); string[] sql = { $"ALTER TABLE [{DatabaseName}].[{SchemaName}].[{TableName}]\r\n DROP CONSTRAINT [FK_{TableName}_{indexTail}]" }; return sql; } internal override string GenerateDefinitionSql() { string indexTail = string.Join("_", Columns.Select(c => $"{c.ColumnName}").ToArray()); string columnList = string.Join(", ", Columns.Select(c => $"[{c.ColumnName}]").ToArray()); string referenceColumnList = string.Join(", ", _referencing.Columns.Select(c => $"[{c.ColumnName}]").ToArray()); string onDelete = _cascadeDelete ? " ON DELETE CASCADE" : ""; string onUpdate = _cascadeUpdate ? " ON UPDATE CASCADE" : ""; return $@" CONSTRAINT [FK_{TableName}_{indexTail}] FOREIGN KEY ({columnList}) REFERENCES [{_referencing.DatabaseName}].[{_referencing.SchemaName}].[{_referencing.TableName}] ({referenceColumnList}){onDelete}{onUpdate}"; } protected override BigInteger ComputeSha256Hash() { return nameof(CreateForeignKeyGene).Sha256Hash().Concatenate( _parent.Sha256Hash, _referencing.Sha256Hash, new BigInteger((_cascadeDelete ? 2 : 0) + (_cascadeUpdate ? 1 : 0))); } internal override GeneMemento GetMemento() { return new GeneMemento( nameof(CreateForeignKeyGene), new Dictionary<string, string> { ["CascadeDelete"] = _cascadeDelete ? "true" : "false", ["CascaseUpdate"] = _cascadeUpdate ? "true" : "false" }, Sha256Hash, new Dictionary<string, IEnumerable<BigInteger>> { ["Prerequisites"] = Prerequisites.Select(x => x.Sha256Hash), ["Parent"] = new[] { _parent.Sha256Hash }, ["Referencing"] = new[] { _referencing.Sha256Hash } }); } public static CreateForeignKeyGene FromMemento(GeneMemento memento, IImmutableDictionary<BigInteger, Gene> genesByHashCode) { return new CreateForeignKeyGene( (CreateIndexGene)genesByHashCode[memento.Prerequisites["Parent"].Single()], (CreatePrimaryKeyGene)genesByHashCode[memento.Prerequisites["Referencing"].Single()], memento.Attributes["CascadeDelete"] == "true", memento.Attributes["CascaseUpdate"] == "true", memento.Prerequisites["Prerequisites"].Select(x => genesByHashCode[x]).ToImmutableList()); } } }
45.763158
163
0.614721
[ "MIT" ]
schemavolution/schemavolution
Schemavolution.Specification/Genes/CreateForeignKeyGene.cs
5,219
C#
using CefSharp; using CefSharp.WinForms; using System; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; using System.Security.Cryptography.X509Certificates; using System.Threading; namespace FPD.Sample.Desktop { public partial class Main : Form { public ChromiumWebBrowser browser; public void InitBrowser() { Cef.Initialize(new CefSettings()); browser = new ChromiumWebBrowser(Forge.EndPoints.OAuthRedirectURL); browser.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); browser.Location = new System.Drawing.Point(261, 12); browser.MinimumSize = new System.Drawing.Size(20, 20); browser.Name = "webBrowser1"; browser.Size = new System.Drawing.Size(455, 542); browser.TabIndex = 1; Controls.Add(browser); } public Main() { InitializeComponent(); InitBrowser(); } private void Main_Load(object sender, EventArgs e) { PrepareUserData(); browser.FrameLoadEnd += Browser_FrameLoadEnd; } private async void Browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e) { // if the browser redirect to this page, means the session ID is on the body if (e.Url.IndexOf("?code=") == -1) return; // remove this event... browser.FrameLoadEnd -= Browser_FrameLoadEnd; string htmlBody = await e.Browser.FocusedFrame.GetTextAsync(); // store the session SessionManager.SessionId = Regex.Replace(htmlBody, "<[^>]*(>|$)", string.Empty); // clear the browser browser.Load(Forge.EndPoints.BaseURL); PrepareUserData(); } private void Main_FormClosing(object sender, FormClosingEventArgs e) { Cef.Shutdown(); } private void btnSignout_Click(object sender, EventArgs e) { Cef.GetGlobalCookieManager().DeleteCookies(string.Empty, string.Empty); SessionManager.Signout(); treeDataManagement.Nodes.Clear(); lblUserName.Text = string.Empty; btnSignout.Visible = false; browser.Load(Forge.EndPoints.OAuthRedirectURL); } delegate void PrepareUserDataCallback(); private async void PrepareUserData() { // make sure this code is being executed on the UI thread if (btnSignout.InvokeRequired || browser.InvokeRequired) { PrepareUserDataCallback c = new PrepareUserDataCallback(PrepareUserData); this.Invoke(c, null); return; } if (!SessionManager.HasSession || !(await SessionManager.IsSessionValid())) return; // empty browser.Load(Forge.EndPoints.BaseURL); btnSignout.Visible = true; // show user name Forge.User user = await Forge.User.UserNameAsync(); lblUserName.Text = string.Format("{0} {1}", user.FirstName, user.LastName); // show hubs tree TreeNode[] hubs = await Forge.DataManagement.GetHubs(); treeDataManagement.Nodes.AddRange(hubs); } private async void treeDataManagement_AfterSelect(object sender, TreeViewEventArgs e) { string[] parameters = e.Node.Tag.ToString().Split('/'); string resourceType = parameters[parameters.Length - 2]; string resourceId = parameters[parameters.Length - 1]; switch (resourceType) { case "hubs": // load projects e.Node.Nodes.AddRange(await Forge.DataManagement.GetProjects(resourceId)); break; case "projects": string hubId = parameters[parameters.Length - 3]; e.Node.Nodes.AddRange(await Forge.DataManagement.GetTopFolder(hubId, resourceId /*projectId*/)); break; case "folders": string projectId = parameters[parameters.Length - 3]; e.Node.Nodes.AddRange(await Forge.DataManagement.GetFolderContents(projectId, resourceId/*folderId*/)); break; case "items": projectId = parameters[parameters.Length - 3]; e.Node.Nodes.AddRange(await Forge.DataManagement.GetItemVersions(projectId, resourceId/*itemId*/)); break; case "versions": browser.RequestHandler = new RequestHandler(); browser.Load(Forge.EndPoints.ViewerURL(resourceId)); //browser.ShowDevTools(); break; } e.Node.Expand(); } private class RequestHandler : IRequestHandler { public CefReturnValue OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback) { var headers = request.Headers; headers["FPDSampleSessionId"] = SessionManager.SessionId; headers["FPDSampleLocalId"] = SessionManager.MachineId; request.Headers = headers; return CefReturnValue.Continue; } public bool GetAuthCredentials(IWebBrowser browserControl, IBrowser browser, IFrame frame, bool isProxy, string host, int port, string realm, string scheme, IAuthCallback callback) { return false; } public IResponseFilter GetResourceResponseFilter(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response) { return null; } public bool OnBeforeBrowse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, bool isRedirect) { return false; } public bool OnCertificateError(IWebBrowser browserControl, IBrowser browser, CefErrorCode errorCode, string requestUrl, ISslInfo sslInfo, IRequestCallback callback) { return false; } public bool OnOpenUrlFromTab(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, WindowOpenDisposition targetDisposition, bool userGesture) { return false; } public void OnPluginCrashed(IWebBrowser browserControl, IBrowser browser, string pluginPath) { } public bool OnProtocolExecution(IWebBrowser browserControl, IBrowser browser, string url) { return false; } public bool OnQuotaRequest(IWebBrowser browserControl, IBrowser browser, string originUrl, long newSize, IRequestCallback callback) { return false; } public void OnRenderProcessTerminated(IWebBrowser browserControl, IBrowser browser, CefTerminationStatus status) { } public void OnRenderViewReady(IWebBrowser browserControl, IBrowser browser) { } public void OnResourceLoadComplete(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength) { } public void OnResourceRedirect(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response, ref string newUrl) { } public bool OnResourceResponse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response) { return false; } public bool OnSelectClientCertificate(IWebBrowser browserControl, IBrowser browser, bool isProxy, string host, int port, X509Certificate2Collection certificates, ISelectClientCertificateCallback callback) { return false; } } } }
47.146199
234
0.641032
[ "MIT" ]
Nainoor/Data-Management
data.management-csharp-desktop.sample/desktop/Main.cs
8,064
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Apache.NMS; using Apache.NMS.Util; using Apache.NMS.ActiveMQ; using Apache.NMS.ActiveMQ.Commands; using Newtonsoft.Json; namespace MarketRiskUI { public partial class ActiveMQ_TOPIC : Form { public ActiveMQ_TOPIC() { InitializeComponent(); } private void textBox_Monitor_TextChanged(object sender, EventArgs e) { } private Producer producer; private void button1_Click(object sender, EventArgs e) { if (producer != null) { producer.Init(); producer.SetTopic(); producer.CreateProducer(); } else { producer = new Producer(); producer.Init(); producer.SetTopic(); producer.CreateProducer(); } } private Consumer[] consumers=new Consumer[100]; private void button2_Click(object sender, EventArgs e) { int i = int.Parse(textBox3.Text); for (int index = 0; index < i; index++) { Consumer consumer = consumers[index]; if (consumer!= null) { if (textBox_selector.Text.ToString() != "") { consumer.Selector = textBox_selector.Text.ToString(); } consumer.Init(); consumer.SetTopic(); consumer.CreateConsumer(); } else { consumer = new Consumer(); if (textBox_selector.Text.ToString() != "") { consumer.Selector = textBox_selector.Text.ToString(); } consumers[index] = consumer; consumer.Init(); consumer.SetTopic(); consumer.CreateConsumer(); } } } private void button3_Click(object sender, EventArgs e) { AdvisoryExample ex = new AdvisoryExample(); ex.EnumerateQueues(); ex.EnumerateTopics(); ex.EnumerateDestinations(); ex.ShutDown(); } private void button4_Click(object sender, EventArgs e) { int i = int.Parse(textBox3.Text); for (int index = 0; index < i; index++) { Consumer consumer = consumers[index]; if (consumer != null) { consumer.Close(); } } } private void button5_Click(object sender, EventArgs e) { producer.Close(); } private void splitContainer1_Panel1_Paint(object sender, PaintEventArgs e) { } private void button6_Click(object sender, EventArgs e) { textBox1.Text = "发送耗时"+producer.SendMsg(textBox_send.Text.ToString(),int.Parse(textBox2.Text))+"秒"; } private void textBox2_TextChanged(object sender, EventArgs e) { } private void label5_Click(object sender, EventArgs e) { } private void button7_Click(object sender, EventArgs e) { int i = int.Parse(textBox3.Text); for (int index = 0; index < i; index++) { Consumer consumer = consumers[index]; if (consumer != null) { consumer.cleanStart(); } } } private void button8_Click(object sender, EventArgs e) { textBox1.Text = "发送耗时" + producer.SendSelectorMsg(textBox_send.Text.ToString(), int.Parse(textBox2.Text)) + "秒"; } private void button9_Click(object sender, EventArgs e) { timer1.Interval = 1000; timer1.Start(); sendCycle = 0; } private int sendCycle = 0; private void timer1_Tick(object sender, EventArgs e) { if (Convert.ToInt32(textBox_cycle.Text) > sendCycle) { producer.SendSelectorMsg(textBox_send.Text.ToString(), int.Parse(textBox2.Text)); } else { timer1.Enabled = false; } sendCycle++; } } public class topicCfg { public static string topicStr = "Test"; public static string url = "tcp://localhost:61616/"; public static string user = "admin"; public static string passwd = "admin"; }; public class CustomData { public int nameCode { get; set; } public string desc { get; set; } } class Producer { private IConnection connection; private ISession session; private IDestination dest; private IMessageProducer prod; public Producer() { } public void Init() { IConnectionFactory factory = new ConnectionFactory(topicCfg.url); if (connection == null) { connection = factory.CreateConnection(topicCfg.user, topicCfg.passwd); connection.Start(); session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge); } } public void SetTopic() { dest = session.GetTopic(topicCfg.topicStr); } public void CreateProducer() { prod = session.CreateProducer(dest); } /// <summary> /// 设置发送支持selector进行过滤的消息 /// </summary> /// <param name="content"></param> /// <param name="count"></param> /// <returns></returns> public double SendSelectorMsg(string content, int count) { //定义topic名 CustomData message = new CustomData(); message.desc = content; message.nameCode = 9527; string str = JsonConvert.SerializeObject(message); byte[] bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message)); // IMessage msg = prod.CreateBytesMessage(bytes); TimeSpan ts = new TimeSpan(); DateTime start = DateTime.Now; for (int i = 0; i < count; i++) { IMessage msg = prod.CreateTextMessage(str); msg.Properties.SetString("filter","demo"); //设置selector msg.Properties.SetDouble("double", 1.11); msg.Properties.SetInt("count", i); msg.Properties.SetInt("sendTime", DateTime.Now.Millisecond); prod.Send(msg, MsgDeliveryMode.NonPersistent, MsgPriority.Normal, TimeSpan.MinValue); } DateTime end = DateTime.Now; ts = end - start; return ts.TotalSeconds; } /// <summary> /// 发送普通消息 /// </summary> /// <param name="content"></param> /// <param name="count"></param> /// <returns></returns> public double SendMsg(string content,int count) { //定义topic名 CustomData message = new CustomData(); message.desc = content; message.nameCode = 9527; //字符串序列化 string str = JsonConvert.SerializeObject(message); //数组序列化 byte[] bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message)); // IMessage msg = prod.CreateBytesMessage(bytes); TimeSpan ts = new TimeSpan(); DateTime start = DateTime.Now; for (int i = 0; i < count; i++) { IMessage msg = prod.CreateTextMessage(str); prod.Send(msg, MsgDeliveryMode.NonPersistent, MsgPriority.Normal, TimeSpan.MinValue); } DateTime end = DateTime.Now; ts = end - start; return ts.TotalSeconds; } public void Close() { if (connection != null) { session.Close(); connection.Close(); connection = null; } } } class Consumer { private IConnection connection; private ISession session; private IDestination dest; private IMessageConsumer cons; private string selector=null; public Consumer() { } public void Init() { IConnectionFactory factory = new ConnectionFactory(topicCfg.url); if (connection == null) { connection = factory.CreateConnection(topicCfg.user, topicCfg.passwd); connection.Start(); session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge); } } public void SetTopic() { dest = session.GetTopic(topicCfg.topicStr); } public void CreateConsumer() { // cons = session.CreateConsumer(dest); //持久,如果断开了,生产者将不会删除消息,而是等待该消费者恢复上线后,继续为其服务。 cons = session.CreateDurableConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic(topicCfg.topicStr),"customer", selector, false); cons.Listener += new MessageListener(consumer_Listener); } private DateTime start; private DateTime end; private bool isStart=false; private TimeSpan ts; public string Selector { get => selector; set => selector = value; } public void cleanStart() { isStart = false; } private int send_receive = 0; void consumer_Listener(IMessage message) { if (isStart == false) { start = DateTime.Now; isStart = true; send_receive = 0; } try { ITextMessage msg = (ITextMessage)message; // Console.WriteLine(msg.Text+ " "+msg.NMSTimestamp); end = DateTime.Now; ts = end - start; send_receive += msg.NMSTimestamp.Millisecond - msg.Properties.GetInt("sendTime"); if (msg.Properties.GetInt("count")>=10000) Console.WriteLine("Receive: " + msg.Text + " span "+ ts.TotalSeconds + " "+(send_receive)); } catch (System.Exception e) { Console.WriteLine(e.Message); } } public void Close() { if (connection != null) { cons.Close(); session.Close(); connection.Close(); connection = null; } } } /// <summary> /// 官方的示例 /// </summary> class AdvisoryExample { private IConnection connection; private ISession session; public const String QUEUE_ADVISORY_DESTINATION = "ActiveMQ.Advisory.Queue"; public const String TOPIC_ADVISORY_DESTINATION = "ActiveMQ.Advisory.Topic"; public const String TEMPQUEUE_ADVISORY_DESTINATION = "ActiveMQ.Advisory.TempQueue"; public const String TEMPTOPIC_ADVISORY_DESTINATION = "ActiveMQ.Advisory.TempTopic"; public const String ALLDEST_ADVISORY_DESTINATION = QUEUE_ADVISORY_DESTINATION + "," + TOPIC_ADVISORY_DESTINATION + "," + TEMPQUEUE_ADVISORY_DESTINATION + "," + TEMPTOPIC_ADVISORY_DESTINATION; public AdvisoryExample() { IConnectionFactory factory = new ConnectionFactory(); connection = factory.CreateConnection(); connection.Start(); session = connection.CreateSession(); } public void EnumerateQueues() { Console.WriteLine("Listing all Queues on Broker:"); IDestination dest = session.GetTopic(QUEUE_ADVISORY_DESTINATION); using (IMessageConsumer consumer = session.CreateConsumer(dest)) { IMessage advisory; while ((advisory = consumer.Receive(TimeSpan.FromMilliseconds(2000))) != null) { ActiveMQMessage amqMsg = advisory as ActiveMQMessage; if (amqMsg.DataStructure != null) { DestinationInfo info = amqMsg.DataStructure as DestinationInfo; if (info != null) { Console.WriteLine(" Queue: " + info.Destination.ToString()); } } } } Console.WriteLine("Listing Complete."); } public void EnumerateTopics() { Console.WriteLine("Listing all Topics on Broker:"); IDestination dest = session.GetTopic(TOPIC_ADVISORY_DESTINATION); using (IMessageConsumer consumer = session.CreateConsumer(dest)) { IMessage advisory; while ((advisory = consumer.Receive(TimeSpan.FromMilliseconds(2000))) != null) { ActiveMQMessage amqMsg = advisory as ActiveMQMessage; if (amqMsg.DataStructure != null) { DestinationInfo info = amqMsg.DataStructure as DestinationInfo; if (info != null) { Console.WriteLine(" Topic: " + info.Destination.ToString()); } } } } Console.WriteLine("Listing Complete."); } public void EnumerateDestinations() { Console.WriteLine("Listing all Destinations on Broker:"); IDestination dest = session.GetTopic(ALLDEST_ADVISORY_DESTINATION); using (IMessageConsumer consumer = session.CreateConsumer(dest)) { IMessage advisory; while ((advisory = consumer.Receive(TimeSpan.FromMilliseconds(2000))) != null) { ActiveMQMessage amqMsg = advisory as ActiveMQMessage; if (amqMsg.DataStructure != null) { DestinationInfo info = amqMsg.DataStructure as DestinationInfo; if (info != null) { string destType = info.Destination.IsTopic ? "Topic" : "Qeue"; destType = info.Destination.IsTemporary ? "Temporary" + destType : destType; Console.WriteLine(" " + destType + ": " + info.Destination.ToString()); } } } } Console.WriteLine("Listing Complete."); } public void ShutDown() { session.Close(); connection.Close(); } public void SendMQ() { } }; }
30.79845
144
0.495784
[ "Apache-2.0" ]
ggwhsd/CSharpStudy
ActiveMQ_TOPIC.cs
16,082
C#
using System; using ZNCHANY.Api.Entities.Enums; using static ZNCHANY.Api.Entities.Enums.CommonEnum; namespace ZNCHANY.Api.ViewModels.Rbac.DncUserRoleMapping { public class DncUserRoleMappingJsonModel { /// <summary> /// /// </summary> public System.Guid UserGuid { get; set; } /// <summary> /// /// </summary> public System.String RoleCode { get; set; } /// <summary> /// /// </summary> public System.DateTime CreatedOn { get; set; } /// <summary> /// 是否可用(0:禁用,1:可用) /// </summary> public Status Status { get; set; } /// <summary> /// 是否已删 /// </summary> public IsDeleted IsDeleted { get; set; } } }
19.195122
56
0.517154
[ "Apache-2.0" ]
zazzlec/znchany
ZNCHANY.Api/ViewModels/Rbac/DncUserRoleMapping/DncUserRoleMappingJsonModel.cs
813
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.Storage; using Windows.Storage.Streams; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace FlightSimMonitor.Common { /// <summary> /// SuspensionManager は、グローバル セッション状態をキャプチャし、アプリケーションのプロセス継続時間管理を簡略化します。 /// セッション状態は、さまざまな条件下で自動的にクリアされます。 /// また、セッション間で伝達しやすく、アプリケーションのクラッシュや /// アップグレード時には破棄が必要な情報を格納する場合にのみ /// 使用する必要があります。 /// </summary> internal sealed class SuspensionManager { private static Dictionary<string, object> _sessionState = new Dictionary<string, object>(); private static List<Type> _knownTypes = new List<Type>(); private const string sessionStateFilename = "_sessionState.xml"; /// <summary> /// 現在のセッションのグローバル セッション状態へのアクセスを提供します。 /// この状態は、<see cref="SaveAsync"/> によってシリアル化され、<see cref="RestoreAsync"/> によって復元されます。 /// したがって、値は <see cref="DataContractSerializer"/> によってシリアル化可能で、 /// できるだけコンパクトになっている必要があります。 /// 文字列などの独立したデータ型を使用することを強くお勧めします。 /// </summary> public static Dictionary<string, object> SessionState { get { return _sessionState; } } /// <summary> /// セッション状態の読み取りおよび書き込み時に <see cref="DataContractSerializer"/> に提供されるカスタムの型の一覧です。 /// 最初は空になっています。 /// 型を追加して、シリアル化プロセスをカスタマイズできます。 /// </summary> public static List<Type> KnownTypes { get { return _knownTypes; } } /// <summary> /// 現在の <see cref="SessionState"/> を保存します。 /// <see cref="RegisterFrame"/> で登録された <see cref="Frame"/> インスタンスは、現在のナビゲーション スタックも保存します。 /// これは、アクティブな <see cref="Page"/> に状態を保存する機会を /// 順番に提供します。 /// </summary> /// <returns>セッション状態が保存されたときに反映される非同期タスクです。</returns> public static async Task SaveAsync() { try { // 登録されているすべてのフレームのナビゲーション状態を保存します foreach (var weakFrameReference in _registeredFrames) { Frame frame; if (weakFrameReference.TryGetTarget(out frame)) { SaveFrameNavigationState(frame); } } // セッション状態を同期的にシリアル化して、共有状態への非同期アクセスを // 状態 MemoryStream sessionData = new MemoryStream(); DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes); serializer.WriteObject(sessionData, _sessionState); // SessionState ファイルの出力ストリームを取得し、状態を非同期的に書き込みます StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(sessionStateFilename, CreationCollisionOption.ReplaceExisting); using (Stream fileStream = await file.OpenStreamForWriteAsync()) { sessionData.Seek(0, SeekOrigin.Begin); await sessionData.CopyToAsync(fileStream); } } catch (Exception e) { throw new SuspensionManagerException(e); } } /// <summary> /// 以前保存された <see cref="SessionState"/> を復元します。 /// <see cref="RegisterFrame"/> で登録された <see cref="Frame"/> インスタンスは、前のナビゲーション状態も復元します。 /// これは、アクティブな <see cref="Page"/> に状態を復元する機会を順番に提供します。 /// ます。 /// </summary> /// <param name="sessionBaseKey">セッションの種類を識別するオプションのキー。 /// これは複数のアプリケーションの起動シナリオを区別するために使用できます。</param> /// <returns>セッション状態が読み取られたときに反映される非同期タスクです。 /// このタスクが完了するまで、<see cref="SessionState"/> のコンテンツには /// 完了します。</returns> public static async Task RestoreAsync(String sessionBaseKey = null) { _sessionState = new Dictionary<String, Object>(); try { // SessionState ファイルの入力ストリームを取得します StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(sessionStateFilename); using (IInputStream inStream = await file.OpenSequentialReadAsync()) { // セッション状態を逆シリアル化します DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes); _sessionState = (Dictionary<string, object>)serializer.ReadObject(inStream.AsStreamForRead()); } // 登録されているフレームを保存された状態に復元します foreach (var weakFrameReference in _registeredFrames) { Frame frame; if (weakFrameReference.TryGetTarget(out frame) && (string)frame.GetValue(FrameSessionBaseKeyProperty) == sessionBaseKey) { frame.ClearValue(FrameSessionStateProperty); RestoreFrameNavigationState(frame); } } } catch (Exception e) { throw new SuspensionManagerException(e); } } private static DependencyProperty FrameSessionStateKeyProperty = DependencyProperty.RegisterAttached("_FrameSessionStateKey", typeof(String), typeof(SuspensionManager), null); private static DependencyProperty FrameSessionBaseKeyProperty = DependencyProperty.RegisterAttached("_FrameSessionBaseKeyParams", typeof(String), typeof(SuspensionManager), null); private static DependencyProperty FrameSessionStateProperty = DependencyProperty.RegisterAttached("_FrameSessionState", typeof(Dictionary<String, Object>), typeof(SuspensionManager), null); private static List<WeakReference<Frame>> _registeredFrames = new List<WeakReference<Frame>>(); /// <summary> /// <see cref="Frame"/> インスタンスを登録し、ナビゲーション履歴を <see cref="SessionState"/> に保存して、 /// ここから復元できるようにします。 /// フレームは、セッション状態管理に参加する場合、作成直後に 1 回登録する必要があります。 /// 登録されしだい、指定されたキーに対して状態が既に復元されていれば、 /// ナビゲーション履歴が直ちに復元されます。 /// <see cref="RestoreAsync"/> はナビゲーション履歴も復元します。 /// </summary> /// <param name="frame">ナビゲーション履歴を管理する必要があるインスタンスです /// <see cref="SuspensionManager"/></param> /// <param name="sessionStateKey">ナビゲーション関連情報を格納するのに /// 使用される <see cref="SessionState"/> への一意キーです。</param> /// <param name="sessionBaseKey">セッションの種類を識別するオプションのキー。 /// これは複数のアプリケーションの起動シナリオを区別するために使用できます。</param> public static void RegisterFrame(Frame frame, String sessionStateKey, String sessionBaseKey = null) { if (frame.GetValue(FrameSessionStateKeyProperty) != null) { throw new InvalidOperationException("Frames can only be registered to one session state key"); } if (frame.GetValue(FrameSessionStateProperty) != null) { throw new InvalidOperationException("Frames must be either be registered before accessing frame session state, or not registered at all"); } if (!string.IsNullOrEmpty(sessionBaseKey)) { frame.SetValue(FrameSessionBaseKeyProperty, sessionBaseKey); sessionStateKey = sessionBaseKey + "_" + sessionStateKey; } // 依存関係プロパティを使用してセッション キーをフレームに関連付け、 // ナビゲーション状態を管理する必要があるフレームの一覧を保持します frame.SetValue(FrameSessionStateKeyProperty, sessionStateKey); _registeredFrames.Add(new WeakReference<Frame>(frame)); // ナビゲーション状態が復元可能かどうか確認します RestoreFrameNavigationState(frame); } /// <summary> /// <see cref="SessionState"/> から <see cref="RegisterFrame"/> によって以前登録された <see cref="Frame"/> の関連付けを解除します。 /// 以前キャプチャされたナビゲーション状態は /// 削除されます。 /// </summary> /// <param name="frame">ナビゲーション履歴を管理する必要がなくなった /// 管理されます。</param> public static void UnregisterFrame(Frame frame) { // セッション状態を削除し、(到達不能になった弱い参照と共に) ナビゲーション状態が保存される // フレームの一覧からフレームを削除します SessionState.Remove((String)frame.GetValue(FrameSessionStateKeyProperty)); _registeredFrames.RemoveAll((weakFrameReference) => { Frame testFrame; return !weakFrameReference.TryGetTarget(out testFrame) || testFrame == frame; }); } /// <summary> /// 指定された <see cref="Frame"/> に関連付けられているセッション状態のストレージを提供します。 /// <see cref="RegisterFrame"/> で以前登録されたフレームには、 /// グローバルの <see cref="SessionState"/> の一部として自動的に保存および復元されるセッション状態があります。 /// 登録されていないフレームは遷移状態です。 /// 遷移状態は、ナビゲーション キャッシュから破棄されたページを復元する場合に /// ナビゲーション キャッシュ。 /// </summary> /// <remarks>アプリケーションは、フレームのセッション状態を直接処理するのではなく、<see cref="NavigationHelper"/> に依存して /// ページ固有の状態を管理するように選択できます。</remarks> /// <param name="frame">セッション状態が必要なインスタンスです。</param> /// <returns><see cref="SessionState"/> と同じシリアル化機構の影響を受ける状態の /// <see cref="SessionState"/>。</returns> public static Dictionary<String, Object> SessionStateForFrame(Frame frame) { var frameState = (Dictionary<String, Object>)frame.GetValue(FrameSessionStateProperty); if (frameState == null) { var frameSessionKey = (String)frame.GetValue(FrameSessionStateKeyProperty); if (frameSessionKey != null) { // 登録されているフレームは、対応するセッション状態を反映します if (!_sessionState.ContainsKey(frameSessionKey)) { _sessionState[frameSessionKey] = new Dictionary<String, Object>(); } frameState = (Dictionary<String, Object>)_sessionState[frameSessionKey]; } else { // 登録されていないフレームは遷移状態です frameState = new Dictionary<String, Object>(); } frame.SetValue(FrameSessionStateProperty, frameState); } return frameState; } private static void RestoreFrameNavigationState(Frame frame) { var frameState = SessionStateForFrame(frame); if (frameState.ContainsKey("Navigation")) { frame.SetNavigationState((String)frameState["Navigation"]); } } private static void SaveFrameNavigationState(Frame frame) { var frameState = SessionStateForFrame(frame); frameState["Navigation"] = frame.GetNavigationState(); } } public class SuspensionManagerException : Exception { public SuspensionManagerException() { } public SuspensionManagerException(Exception e) : base("SuspensionManager failed", e) { } } }
41.425926
156
0.600268
[ "Apache-2.0" ]
EsriJapan/flightsim-game-monitor-dotnet
FlightSimMonitor/Common/SuspensionManager.cs
14,463
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="App.xaml.cs" company="saramgsilva"> // Copyright (c) 2014 saramgsilva. All rights reserved. // </copyright> // <summary> // Interaction logic for App.xaml. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace ModernUIForWPFSample.DefaultModernUI { /// <summary> /// Interaction logic for App.xaml. /// </summary> public partial class App { } }
31.842105
120
0.390083
[ "MIT" ]
saramgsilva/ModernUISamples
src/ModernUIForWPFSample.DefaultModernUI/App.xaml.cs
607
C#
using Borlay.Arrays; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Diagnostics; using System.IO; using System.Threading.Tasks; using System.Linq; namespace Borlay.Repositories.RocksDb.Tests { [TestClass] public class PrimaryRepositoryTests { [TestMethod] public void SaveAndEntityOrderDescGet() { var dbOptions = new RocksDbSharp.DbOptions(); dbOptions.SetCreateIfMissing(); var rocksDb = RocksDbSharp.RocksDb.Open(dbOptions, @"C:\rocks\primaryrepositorytst\"); var repository = new RocksPrimaryRepository(rocksDb, "ent"); try { var id1 = ByteArray.New(32); var value1 = ByteArray.New(256); var id2 = ByteArray.New(32); var value2 = ByteArray.New(256); var id3 = ByteArray.New(32); var value3 = ByteArray.New(256); using (var transaction = repository.CreateTransaction()) { var key1 = transaction.AppendValue(id1, value1.Bytes, value1.Length); transaction.AppendScoreIndex(id1, key1, 12, IndexLevel.Entity, OrderType.Desc); var key2 = transaction.AppendValue(id2, value2.Bytes, value2.Length); transaction.AppendScoreIndex(id2, key2, 15, IndexLevel.Entity, OrderType.Desc); var key3 = transaction.AppendValue(id3, value3.Bytes, value3.Length); transaction.AppendScoreIndex(id3, key3, 14, IndexLevel.Entity, OrderType.Desc); transaction.Commit(); } var result = repository.GetValues(OrderType.Desc).ToArray(); Assert.IsNotNull(result); Assert.AreEqual(3, result.Length); Assert.IsTrue(result[0].Value.ContainsSequence32(value2.Bytes)); Assert.IsTrue(result[1].Value.ContainsSequence32(value3.Bytes)); Assert.IsTrue(result[2].Value.ContainsSequence32(value1.Bytes)); } finally { rocksDb.Dispose(); Directory.Delete(@"C:\rocks\primaryrepositorytst\", true); } } [TestMethod] public void SaveAndEntityOrderAscGet() { var dbOptions = new RocksDbSharp.DbOptions(); dbOptions.SetCreateIfMissing(); var rocksDb = RocksDbSharp.RocksDb.Open(dbOptions, @"C:\rocks\primaryrepositorytst\"); var repository = new RocksPrimaryRepository(rocksDb, "ent"); try { var id1 = ByteArray.New(32); var value1 = ByteArray.New(256); var id2 = ByteArray.New(32); var value2 = ByteArray.New(256); var id3 = ByteArray.New(32); var value3 = ByteArray.New(256); using (var transaction = repository.CreateTransaction()) { var key1 = transaction.AppendValue(id1, value1.Bytes, value1.Length); transaction.AppendScoreIndex(id1, key1, 12, IndexLevel.Entity, OrderType.Asc); var key2 = transaction.AppendValue(id2, value2.Bytes, value2.Length); transaction.AppendScoreIndex(id2, key2, 15, IndexLevel.Entity, OrderType.Asc); var key3 = transaction.AppendValue(id3, value3.Bytes, value3.Length); transaction.AppendScoreIndex(id3, key3, 14, IndexLevel.Entity, OrderType.Asc); transaction.Commit(); } var result = repository.GetValues(OrderType.Asc, false).ToArray(); Assert.IsNotNull(result); Assert.AreEqual(3, result.Length); Assert.IsTrue(result[0].Value.ContainsSequence32(value1.Bytes)); Assert.IsTrue(result[1].Value.ContainsSequence32(value3.Bytes)); Assert.IsTrue(result[2].Value.ContainsSequence32(value2.Bytes)); } finally { rocksDb.Dispose(); Directory.Delete(@"C:\rocks\primaryrepositorytst\", true); } } } }
37.893805
99
0.568893
[ "Apache-2.0" ]
Borlay/Borlay.Repositories.RocksDb
Borlay.Repositories.RocksDb/Borlay.Repositories.RocksDb.Tests/PrimaryRepositoryTests.cs
4,284
C#
using System; namespace _11_3rdBit { class Program { static void Main(string[] args) { Check3rdBit_Extended_Solution(); Check3rdBit_OneLiner_Solution(); } static void Check3rdBit_OneLiner_Solution() { Console.WriteLine((int.Parse(Console.ReadLine()) >> 3) & 1); } // NOTE: This section works around using programmable regions to serve different function dependent on the environment (Debug; Release) private static void Check3rdBit_Extended_Solution() { Console.Write($"Enter nummber whose 3rd index bit be checked: "); var isValidInput = int.TryParse(Console.ReadLine(), out int number); #if DEBUG // in Debug Mode the compiler will execute this, but in a Release Mode it will skip this section entirely! static void Debug_Visualise_number(int number) { Console.WriteLine($"BIT at 3rd index: {Check3rdBit(number)}"); Console.WriteLine($"Number's meaningful BITS only: {Convert.ToString(number, 2)}"); Console.WriteLine($"Number's full BITS representation: {GetIntBinaryString(number)}"); } Debug_Visualise_number(number); #else Console.WriteLine($"{Check3rdBit(number)}"); #endif } private static int Check3rdBit(int number) { // shift to index [3] var mask = 1 << 3; var result = number & mask; return result >>= 3; } private static string GetIntBinaryString(int number) { char[] b = new char[32]; int pos = 31; int i = 0; while (i < 32 ) { if ((number & (1 << i)) != 0) { b[pos] = '1'; } else { b[pos] = '0'; } pos--; i++; } return new string(b); } } }
31.217391
144
0.491179
[ "MIT" ]
VProfirov/Telerik-Academy-Course-original_version-Homeworks-and-Exams
01.Fundamentals/_03_Operators-and-Expressions/_11_3rdBit/Program.cs
2,156
C#
using System; using System.Collections.Generic; using System.Linq; using Fpm.MainUI.Helpers; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Fpm.MainUITest.Helpers { [TestClass] public class IndicatorSpecifierParserTest { [TestMethod] public void Test() { var detailsList = IndicatorSpecifierParser.Parse(new[] { "1~2~3" }); Assert.AreEqual(1, detailsList.Count); var details = detailsList.First(); Assert.AreEqual(1, details.IndicatorId); Assert.AreEqual(2, details.SexId); Assert.AreEqual(3, details.AgeId); } [TestMethod] public void TestTolerateAgeIdNotBeingPresent() { var detailsList = IndicatorSpecifierParser.Parse(new[] { "1~2" }); Assert.AreEqual(1, detailsList.Count); var details = detailsList.First(); Assert.AreEqual(1, details.IndicatorId); Assert.AreEqual(2, details.SexId); } [TestMethod] public void TestEmptyStringIgnored() { var detailsList = IndicatorSpecifierParser.Parse(new[] { "" }); Assert.IsFalse(detailsList.Any()); } [TestMethod] public void TestEmptyListIgnored() { var detailsList = IndicatorSpecifierParser.Parse(new string[] { }); Assert.IsFalse(detailsList.Any()); } [TestMethod] public void TestNullListIgnored() { var detailsList = IndicatorSpecifierParser.Parse(null); Assert.IsFalse(detailsList.Any()); } [TestMethod] public void TestNullItemsIgnored() { var detailsList = IndicatorSpecifierParser.Parse(new string[] { null }); Assert.IsFalse(detailsList.Any()); } } }
28.30303
84
0.590471
[ "MIT" ]
PublicHealthEngland/fingertips-open
FingertipsProfileManager/MainUITest/Helpers/IndicatorSpecifierParserTest.cs
1,870
C#
using System; using System.Collections.Generic; using System.Text; using Typography.TextBreak; namespace CSharpMath.Rendering { using Enumerations; using Structures; using static Structures.Result; public static class TextBuilder { /* //Paste this into the C# Interactive, fill <username> yourself #r "C:/Users/<username>/source/repos/CSharpMath/Typography/Build/NetStandard/Typography.TextBreak/bin/Debug/netstandard1.3/Typography.TextBreak.dll" using Typography.TextBreak; (int, WordKind, char)[] BreakText(string text) { var breaker = new CustomBreaker(); var breakList = new List<BreakAtInfo>(); breaker.BreakWords(text); breaker.LoadBreakAtList(breakList); //index is after the boundary -> last one will be out of range return breakList.Select(i => (i.breakAt, i.wordKind, text.ElementAtOrDefault(i.breakAt))).ToArray(); } BreakText(@"Here are some text $1 + 12 \frac23 \sqrt4$ $$Display$$ text") */ /* //Version 2 #r "C:/Users/<username>/source/repos/CSharpMath/Typography/Build/NetStandard/Typography.TextBreak/bin/Debug/netstandard1.3/Typography.TextBreak.dll" using Typography.TextBreak; string BreakText(string text, string seperator = "|") { var breaker = new CustomBreaker(); var breakList = new List<BreakAtInfo>(); breaker.BreakWords(text); breaker.LoadBreakAtList(breakList); //reverse to ensure earlier inserts do not affect later ones foreach (var @break in breakList.Select(i => i.breakAt).Reverse()) text = text.Insert(@break, seperator); return text; } BreakText(@"Here are some text $1 + 12 \frac23 \sqrt4$ $$Display$$ text") */ public const int StringArgumentLimit = 25; public static bool NoEnhancedColors { get; set; } private static CustomBreaker breaker = new CustomBreaker { BreakNumberAfterText = true, ThrowIfCharOutOfRange = false }; private const string SpecialChars = @"#$%&\^_{}~"; public static Result<TextAtom> Build(ReadOnlySpan<char> latexSource) { if (latexSource.IsEmpty) return new TextAtom.List(Array.Empty<TextAtom>(), 0); bool? displayMath = null; StringBuilder mathLaTeX = null; bool backslashEscape = false; bool afterCommand = false; //ignore spaces after command bool afterNewline = false; int dollarCount = 0; var globalAtoms = new TextAtomListBuilder(); var breakList = new List<BreakAtInfo>(); breaker.BreakWords(latexSource, breakList); Result CheckDollarCount(TextAtomListBuilder atoms) { switch (dollarCount) { case 0: break; case 1: dollarCount = 0; switch (displayMath) { case true: return "Cannot close display math mode with $"; case false: if (atoms.Add(mathLaTeX.ToString(), false).Error is string mathError) return "[Math mode error] " + mathError; mathLaTeX = null; displayMath = null; break; case null: mathLaTeX = new StringBuilder(); displayMath = false; break; } break; case 2: dollarCount = 0; switch (displayMath) { case true: if (atoms.Add(mathLaTeX.ToString(), true).Error is string mathError) return "[Math mode error] " + mathError; mathLaTeX = null; displayMath = null; break; case false: return "Cannot close inline math mode with $$"; case null: mathLaTeX = new StringBuilder(); displayMath = true; break; } break; default: return "Invalid number of $: " + dollarCount; } return Ok(); } Result<int> BuildBreakList(ReadOnlySpan<char> latex, TextAtomListBuilder atoms, int i, bool oneCharOnly, char stopChar) { void ParagraphBreak() { atoms.Break(3); #warning Should the newline and space occupy the same range? atoms.TextLength -= 3; atoms.Add(Space.ParagraphIndent, 3); } for (; i < breakList.Count; i++) { void ObtainRange(ReadOnlySpan<char> latexInput, int index, out int start, out int end, out ReadOnlySpan<char> section, out WordKind kind) { (start, end) = (index == 0 ? 0 : breakList[index - 1].breakAt, breakList[index].breakAt); section = latexInput.Slice(start, end - start); kind = breakList[index].wordKind; } ObtainRange(latex, i, out var startAt, out var endAt, out var textSection, out var wordKind); bool SetPrevRange(ReadOnlySpan<char> latexInput, ref ReadOnlySpan<char> section) { bool success = i-- > 0; if (success) ObtainRange(latexInput, i, out startAt, out endAt, out section, out wordKind); return success; } bool SetNextRange(ReadOnlySpan<char> latexInput, ref ReadOnlySpan<char> section) { bool success = ++i < breakList.Count; if (success) ObtainRange(latexInput, i, out startAt, out endAt, out section, out wordKind); return success; } Result<TextAtom> ReadArgumentAtom(ReadOnlySpan<char> latexInput) { backslashEscape = false; var argAtoms = new TextAtomListBuilder(); if(BuildBreakList(latexInput, argAtoms, ++i, true, '\0').Bind(index => i = index).Error is string error) return error; return argAtoms.Build(); } SpanResult<char> ReadArgumentString(ReadOnlySpan<char> latexInput, ref ReadOnlySpan<char> section) { afterCommand = false; if (!SetNextRange(latexInput, ref section)) return Err("Missing argument"); if (section.IsNot('{')) return Err("Missing {"); int endingIndex = -1; //startAt + 1 to not start at the { we started at bool isEscape = false; for (int j = startAt + 1, bracketDepth = 0; j < latexInput.Length; j++) { if (latexInput[j] == '\\') isEscape = true; else if (latexInput[j] == '{' && !isEscape) bracketDepth++; else if (latexInput[j] == '}' && !isEscape) if (bracketDepth > 0) bracketDepth--; else { endingIndex = j; break; } else isEscape = false; } if (endingIndex == -1) return Err("Missing }"); var resultText = latexInput.Slice(endAt, endingIndex - endAt); while (startAt < endingIndex) _ = SetNextRange(latexInput, ref section); //this never fails because the above check return Ok(resultText); } ReadOnlySpan<char> LookAheadForPunc(ReadOnlySpan<char> latexInput, ref ReadOnlySpan<char> section) { int start = endAt; while (SetNextRange(latexInput, ref section)) if (wordKind != WordKind.Punc || SpecialChars.Contains(section[0])) { //We have overlooked by one SetPrevRange(latexInput, ref section); break; } return latexInput.Slice(start, endAt - start); } //Nothing should be before dollar sign checking -- dollar sign checking uses continue; atoms.TextLength = startAt; if (textSection.Is('$')) { if (backslashEscape) if (displayMath != null) mathLaTeX.Append(@"\$"); else atoms.Add("$", LookAheadForPunc(latex, ref textSection)); else { dollarCount++; continue; } backslashEscape = false; } else { { if (CheckDollarCount(atoms).Error is string error) return error; } if (!backslashEscape) { //Unescaped text section, inside display/inline math mode if(displayMath != null) switch (textSection) { case var _ when textSection.Is('$'): throw new InvalidCodePathException("The $ case should have been accounted for."); case var _ when textSection.Is('\\'): backslashEscape = true; continue; default: mathLaTeX.Append(textSection); break; } //Unescaped text section, not inside display/inline math mode else switch (textSection) { case var _ when stopChar > 0 && textSection[0] == stopChar: return Ok(i); case var _ when textSection.Is('$'): throw new InvalidCodePathException("The $ case should have been accounted for."); case var _ when textSection.Is('\\'): backslashEscape = true; continue; case var _ when textSection.Is('#'): return "Unexpected command argument reference character # outside of new command definition (currently unsupported)"; case var _ when textSection.Is('^'): case var _ when textSection.Is('_'): return $"Unexpected script indicator {textSection[0]} outside of math mode"; case var _ when textSection.Is('&'): return $"Unexpected alignment tab character & outside of table environments"; case var _ when textSection.Is('~'): atoms.Add(); break; case var _ when textSection.Is('%'): var comment = new StringBuilder(); while (SetNextRange(latex, ref textSection) && wordKind != WordKind.NewLine) comment.Append(textSection); atoms.Comment(comment.ToString()); break; case var _ when textSection.Is('{'): if(BuildBreakList(latex, atoms, ++i, false, '}').Bind(index => i = index).Error is string error) return error; break; case var _ when textSection.Is('}'): return "Unexpected }, unbalanced braces"; case var _ when wordKind == WordKind.NewLine: //Consume newlines after commands //Double newline == paragraph break if (afterNewline) { ParagraphBreak(); afterNewline = false; break; } else { atoms.Add(); afterNewline = true; continue; } case var _ when wordKind == WordKind.Whitespace: //Collpase spaces if (afterCommand) continue; else atoms.Add(); break; default: //Just ordinary text if (oneCharOnly) { if (startAt + 1 < endAt) { //Only re-read if current break span is more than 1 long i--; breakList[i] = new BreakAtInfo(breakList[i].breakAt + 1, breakList[i].wordKind); } //Need to allocate in the end :( //Don't look ahead for punc; we are looking for one char only atoms.Add(textSection[0].ToString(), default(ReadOnlySpan<char>)); } else atoms.Add(textSection.ToString(), LookAheadForPunc(latex, ref textSection)); break; } afterCommand = false; } //Escaped text section but in inline/display math mode else if (displayMath != null) { switch (textSection) { case var _ when textSection.Is('$'): throw new InvalidCodePathException("The $ case should have been accounted for."); case var _ when textSection.Is('('): switch (displayMath) { case true: return "Cannot open inline math mode in display math mode"; case false: return "Cannot open inline math mode in inline math mode"; default: throw new InvalidCodePathException("displayMath is null. This switch should not be hit."); } case var _ when textSection.Is(')'): switch (displayMath) { case true: return "Cannot close inline math mode in display math mode"; case false: if (atoms.Add(mathLaTeX.ToString(), false).Error is string mathError) return "[Math mode error] " + mathError; mathLaTeX = null; displayMath = null; break; default: throw new InvalidCodePathException("displayMath is null. This switch should not be hit."); } break; case var _ when textSection.Is('['): switch (displayMath) { case true: return "Cannot open display math mode in display math mode"; case false: return "Cannot open display math mode in inline math mode"; default: throw new InvalidCodePathException("displayMath is null. This switch should not be hit."); } case var _ when textSection.Is(']'): switch (displayMath) { case true: if (atoms.Add(mathLaTeX.ToString(), true).Error is string mathError) return "[Math mode error] " + mathError; mathLaTeX = null; displayMath = null; break; case false: return "Cannot close display math mode in inline math mode"; default: throw new InvalidCodePathException("displayMath is null. This switch should not be hit."); } break; default: mathLaTeX.Append('\\').Append(textSection); break; } backslashEscape = false; } else { //Escaped text section and not in inline/display math mode afterCommand = true; switch (textSection) { case var _ when textSection.Is('('): mathLaTeX = new StringBuilder(); displayMath = false; break; case var _ when textSection.Is(')'): return "Cannot close inline math mode outside of math mode"; case var _ when textSection.Is('['): mathLaTeX = new StringBuilder(); displayMath = true; break; case var _ when textSection.Is(']'): return "Cannot close display math mode outside of math mode"; case var _ when textSection.Is('\\'): atoms.Break(1); break; case var _ when textSection.Is(','): atoms.Add(Space.ShortSpace, 1); break; case var _ when textSection.Is(':') || textSection.Is('>'): atoms.Add(Space.MediumSpace, 1); break; case var _ when textSection.Is(';'): atoms.Add(Space.LongSpace, 1); break; case var _ when textSection.Is('!'): atoms.Add(-Space.ShortSpace, 1); break; case var _ when wordKind == WordKind.Whitespace: //control space atoms.Add(); break; case var _ when textSection.Is("par"): ParagraphBreak(); break; case var _ when textSection.Is("fontsize"): { if (ReadArgumentString(latex, ref textSection).Bind(fontSize => { if (fontSize.Length > StringArgumentLimit) return Err($"Length of font size has over {StringArgumentLimit} characters. Please shorten it."); Span<byte> charBytes = stackalloc byte[fontSize.Length]; for (int j = 0; j < fontSize.Length; j++) { if (fontSize[j] > 127) return Err("Invalid font size"); charBytes[j] = (byte)fontSize[j]; } return System.Buffers.Text.Utf8Parser.TryParse(charBytes, out float parsedResult, out _, 'f') ? Ok(parsedResult) : Err("Invalid font size"); }).Bind( ReadArgumentAtom(latex), (fontSize, resizedContent) => atoms.Add(resizedContent, fontSize, "fontsize".Length) ).Error is string error ) return error; break; } case var _ when textSection.Is("color"): { if (ReadArgumentString(latex, ref textSection).Bind(color => color.Length > StringArgumentLimit ? Err($"Length of color has over {StringArgumentLimit} characters. Please shorten it.") : Color.Create(color, !NoEnhancedColors) is Color value ? Ok(value) : Err("Invalid color") ).Bind( ReadArgumentAtom(latex), (color, coloredContent) => atoms.Add(coloredContent, color, "color".Length) ).Error is string error ) return error; break; } //case "red", "yellow", ... case var shortColor when !NoEnhancedColors && shortColor.TryAccessDictionary(Color.PredefinedColors, out var color): { int tmp_commandLength = shortColor.Length; if (ReadArgumentAtom(latex).Bind( coloredContent => atoms.Add(coloredContent, color, tmp_commandLength) ).Error is string error ) return error; break; } //case "textbf", "textit", ... bool ValidTextStyle(ReadOnlySpan<char> textStyle, out FontStyle fontStyle) { fontStyle = default; if (textStyle.Length > 3 && textStyle[0] == 'm' && textStyle[1] == 'a' && textStyle[2] == 't' && textStyle[3] == 'h') return false; Span<char> copy = stackalloc char[textStyle.Length]; textStyle.CopyTo(copy); if (textStyle.Length > 3 && textStyle[0] == 't' && textStyle[1] == 'e' && textStyle[2] == 'x' && textStyle[3] == 't') { copy[0] = 'm'; copy[1] = 'a'; copy[2] = 't'; copy[3] = 'h'; } return ((ReadOnlySpan<char>)copy).TryAccessDictionary(FontStyleExtensions.FontStyles, out fontStyle); } case var textStyle when ValidTextStyle(textStyle, out var fontStyle): { int tmp_commandLength = textStyle.Length; if (ReadArgumentAtom(latex) .Bind(builtContent => atoms.Add(builtContent, fontStyle, tmp_commandLength)) .Error is string error) return error; break; } //case "^", "\"", ... case var textAccent when textAccent.TryAccessDictionary(TextAtoms.PredefinedAccents, out var accent): { int tmp_commandLength = textAccent.Length; if (ReadArgumentAtom(latex) .Bind(builtContent => atoms.Add(builtContent, accent, tmp_commandLength)) .Error is string error) return error; break; } //case "textasciicircum", "textless", ... case var textSymbol when textSymbol.TryAccessDictionary(TextAtoms.PredefinedTextSymbols, out var replaceResult): atoms.Add(replaceResult, LookAheadForPunc(latex, ref textSection)); break; case var command: if (displayMath != null) mathLaTeX.Append(command); //don't eat the command when parsing math else return $@"Unknown command \{command.ToString()}"; break; } backslashEscape = false; } } afterNewline = false; if (oneCharOnly) return Ok(i); } if (backslashEscape) return @"Unknown command \"; if (stopChar > 0) return stopChar == '}' ? "Expected }, unbalanced braces" : $@"Expected {stopChar}"; return Ok(i); } { if (BuildBreakList(latexSource, globalAtoms, 0, false, '\0').Error is string error) return error; } { if (CheckDollarCount(globalAtoms).Error is string error) return error; } if (displayMath != null) return "Math mode was not terminated"; return globalAtoms.Build(); } public static StringBuilder Unbuild(TextAtom atom, StringBuilder b) { switch (atom) { case TextAtom.Text t: return b.Append(t.Content); case TextAtom.Newline n: return b.Append(@"\\"); case TextAtom.Math m: return b.Append('\\').Append(m.DisplayStyle ? '[' : '(').Append(Atoms.MathListBuilder.MathListToString(m.Content)).Append('\\').Append(m.DisplayStyle ? ']' : ')'); case TextAtom.Space s: return b.Append(@"\hspace").AppendInBraces(s.Content.Length.ToStringInvariant(), NullHandling.EmptyContent); case TextAtom.ControlSpace c: return b.Append(@"\ "); case TextAtom.Style t: return b.Append('\\').Append(t.FontStyle.FontName()).AppendInBraces(Unbuild(t.Content, new StringBuilder()).ToString(), NullHandling.None); case TextAtom.Size z: return b.Append(@"\fontsize").AppendInBraces(z.PointSize.ToStringInvariant(), NullHandling.EmptyContent) .AppendInBraces(Unbuild(z.Content, new StringBuilder()).ToString(), NullHandling.None); case TextAtom.List l: foreach (var a in l.Content) { b.Append(Unbuild(a, b)); } return b; case null: throw new ArgumentNullException(nameof(atom), "TextAtoms should never be null. You must have sneaked one in."); case var a: throw new InvalidCodePathException($"There should not be an unknown type of TextAtom. However, one with type {a.GetType()} was encountered."); } } } }
49.658947
173
0.523444
[ "MIT" ]
hflexgrig/CSharpMath
CSharpMath.Rendering/Text/TextBuilder.cs
23,588
C#
using System; using System.Collections.Generic; using JetBrains.Annotations; using Orchard.ContentManagement; using Orchard.ContentManagement.Drivers; using Orchard.Localization; using Orchard.Utility.Extensions; using Orchard.Widgets.Models; using Orchard.Widgets.Services; namespace Orchard.Widgets.Drivers { [UsedImplicitly] public class WidgetPartDriver : ContentPartDriver<WidgetPart> { private readonly IWidgetsService _widgetsService; private readonly IContentManager _contentManager; public WidgetPartDriver(IWidgetsService widgetsService, IContentManager contentManager) { _widgetsService = widgetsService; _contentManager = contentManager; T = NullLocalizer.Instance; } public Localizer T { get; set; } protected override string Prefix { get { return "WidgetPart"; } } protected override DriverResult Editor(WidgetPart widgetPart, dynamic shapeHelper) { widgetPart.AvailableZones = _widgetsService.GetZones(); widgetPart.AvailableLayers = _widgetsService.GetLayers(); var results = new List<DriverResult> { ContentShape("Parts_Widgets_WidgetPart", () => shapeHelper.EditorTemplate(TemplateName: "Parts.Widgets.WidgetPart", Model: widgetPart, Prefix: Prefix)) }; if (widgetPart.Id > 0) results.Add(ContentShape("Widget_DeleteButton", deleteButton => deleteButton)); return Combined(results.ToArray()); } protected override DriverResult Editor(WidgetPart widgetPart, IUpdateModel updater, dynamic shapeHelper) { updater.TryUpdateModel(widgetPart, Prefix, null, null); if(string.IsNullOrWhiteSpace(widgetPart.Title)) { updater.AddModelError("Title", T("Title can't be empty.")); } // if there is a name, ensure it's unique if(!string.IsNullOrWhiteSpace(widgetPart.Name)) { widgetPart.Name = widgetPart.Name.ToSafeName(); var widgets = _contentManager.Query<WidgetPart, WidgetPartRecord>().Where(x => x.Name == widgetPart.Name && x.Id != widgetPart.Id).Count(); if(widgets > 0) { updater.AddModelError("Name", T("A Widget with the same Name already exists.")); } } _widgetsService.MakeRoomForWidgetPosition(widgetPart); return Editor(widgetPart, shapeHelper); } protected override void Importing(WidgetPart part, ContentManagement.Handlers.ImportContentContext context) { var title = context.Attribute(part.PartDefinition.Name, "Title"); if (title != null) { part.Title = title; } var position = context.Attribute(part.PartDefinition.Name, "Position"); if (position != null) { part.Position = position; } var zone = context.Attribute(part.PartDefinition.Name, "Zone"); if (zone != null) { part.Zone = zone; } var renderTitle = context.Attribute(part.PartDefinition.Name, "RenderTitle"); if (!string.IsNullOrWhiteSpace(renderTitle)) { part.RenderTitle = Convert.ToBoolean(renderTitle); } var name = context.Attribute(part.PartDefinition.Name, "Name"); if (name != null) { part.Name = name; } } protected override void Exporting(WidgetPart part, ContentManagement.Handlers.ExportContentContext context) { context.Element(part.PartDefinition.Name).SetAttributeValue("Title", part.Title); context.Element(part.PartDefinition.Name).SetAttributeValue("Position", part.Position); context.Element(part.PartDefinition.Name).SetAttributeValue("Zone", part.Zone); context.Element(part.PartDefinition.Name).SetAttributeValue("RenderTitle", part.RenderTitle); context.Element(part.PartDefinition.Name).SetAttributeValue("Name", part.Name); } } }
40.596154
155
0.628612
[ "BSD-3-Clause" ]
ArsenShnurkov/OrchardCMS-1.7.3-for-mono
src/Orchard.Web/Modules/Orchard.Widgets/Drivers/WidgetPartDriver.cs
4,224
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VioletIoc { /// <summary> /// Container. /// </summary> public interface IContainer : IDisposable { /// <summary> /// Register the specified interfaceType, instance and key. /// </summary> /// <returns>The register.</returns> /// <param name="interfaceType">Interface type.</param> /// <param name="instance">Instance.</param> IContainer RegisterSingleton(Type interfaceType, object instance); /// <summary> /// Register the specified interfaceType, asType, key and singleton. /// </summary> /// <returns>The register.</returns> /// <param name="interfaceType">Interface type.</param> /// <param name="asType">As type.</param> /// <param name="singleton">If set to <c>true</c> singleton.</param> IContainer Register(Type interfaceType, Type asType, bool singleton); /// <summary> /// Register the specified interfaceType, factory, key and singleton. /// </summary> /// <returns>The register.</returns> /// <param name="interfaceType">Interface type.</param> /// <param name="factory">Factory.</param> /// <param name="singleton">If set to <c>true</c> singleton.</param> /// <typeparam name="TType">The 1st type parameter.</typeparam> IContainer Register<TType>(Type interfaceType, Func<IContainer, TType> factory, bool singleton) where TType : class; /// <summary> /// Register the specified interfaceType, factory, key and singleton. /// </summary> /// <returns>The register.</returns> /// <param name="interfaceType">Interface type.</param> /// <param name="factory">Factory.</param> /// <param name="singleton">If set to <c>true</c> singleton.</param> /// <typeparam name="TType">The 1st type parameter.</typeparam> IContainer Register<TType>(Type interfaceType, Func<IContainer, ResolutionContext, TType> factory, bool singleton) where TType : class; /// <summary> /// Register this instance. /// </summary> /// <returns>The register.</returns> /// <typeparam name="TType">The 1st type parameter.</typeparam> IContainer Register<TType>() where TType : class; /// <summary> /// Register this instance. /// </summary> /// <returns>The register.</returns> /// <typeparam name="TInterface">The 1st type parameter.</typeparam> /// <typeparam name="TType">The 2nd type parameter.</typeparam> IContainer Register<TInterface, TType>() where TInterface : class where TType : class, TInterface; /// <summary> /// Register the specified factory. /// </summary> /// <returns>The register.</returns> /// <param name="factory">Factory.</param> /// <typeparam name="TInterface">The 1st type parameter.</typeparam> IContainer Register<TInterface>(Func<IContainer, TInterface> factory) where TInterface : class; /// <summary> /// Register the specified factory. /// </summary> /// <returns>The register.</returns> /// <param name="factory">Factory.</param> /// <typeparam name="TInterface">The 1st type parameter.</typeparam> IContainer Register<TInterface>(Func<IContainer, ResolutionContext, TInterface> factory) where TInterface : class; /// <summary> /// Register the specified factory. /// </summary> /// <returns>The register.</returns> /// <param name="factory">Factory.</param> /// <typeparam name="TInterface">The 1st type parameter.</typeparam> IContainer Register<TInterface>(Func<IContainer, object> factory) where TInterface : class; /// <summary> /// Register the specified factory. /// </summary> /// <returns>The register.</returns> /// <param name="factory">Factory.</param> /// <typeparam name="TInterface">The 1st type parameter.</typeparam> IContainer Register<TInterface>(Func<IContainer, ResolutionContext, object> factory) where TInterface : class; /// <summary> /// Register the specified factory. /// </summary> /// <returns>The register.</returns> /// <param name="factory">Factory.</param> /// <typeparam name="TInterface">The 1st type parameter.</typeparam> /// <typeparam name="TType">The 2nd type parameter.</typeparam> IContainer Register<TInterface, TType>(Func<IContainer, TType> factory) where TType : class, TInterface; /// <summary> /// Register the specified factory. /// </summary> /// <returns>The register.</returns> /// <param name="factory">Factory.</param> /// <typeparam name="TInterface">The 1st type parameter.</typeparam> /// <typeparam name="TType">The 2nd type parameter.</typeparam> IContainer Register<TInterface, TType>(Func<IContainer, ResolutionContext, TType> factory) where TType : class, TInterface; /// <summary> /// Register the specified asType. /// </summary> /// <returns>The register.</returns> /// <param name="asType">As type.</param> IContainer Register(Type asType); /// <summary> /// Register the specified interfaceType and asType. /// </summary> /// <returns>The register.</returns> /// <param name="interfaceType">Interface type.</param> /// <param name="asType">As type.</param> IContainer Register(Type interfaceType, Type asType); /// <summary> /// Register the specified interfaceType and factory. /// </summary> /// <returns>The register.</returns> /// <param name="interfaceType">Interface type.</param> /// <param name="factory">Factory.</param> IContainer Register(Type interfaceType, Func<IContainer, object> factory); /// <summary> /// Register the specified interfaceType and factory. /// </summary> /// <returns>The register.</returns> /// <param name="interfaceType">Interface type.</param> /// <param name="factory">Factory.</param> IContainer Register(Type interfaceType, Func<IContainer, ResolutionContext, object> factory); /// <summary> /// Registers the singleton. /// </summary> /// <returns>The singleton.</returns> /// <param name="instance">Instance.</param> /// <typeparam name="TType">The 1st type parameter.</typeparam> IContainer RegisterSingleton<TType>(TType instance) where TType : class; /// <summary> /// Registers the singleton. /// </summary> /// <returns>The singleton.</returns> /// <typeparam name="TType">The 1st type parameter.</typeparam> IContainer RegisterSingleton<TType>() where TType : class; /// <summary> /// Registers the singleton. /// </summary> /// <returns>The singleton.</returns> /// <typeparam name="TInterface">The 1st type parameter.</typeparam> /// <typeparam name="TType">The 2nd type parameter.</typeparam> IContainer RegisterSingleton<TInterface, TType>() where TType : class, TInterface; /// <summary> /// Registers the singleton. /// </summary> /// <returns>The singleton.</returns> /// <param name="instance">Instance.</param> /// <typeparam name="TInterface">The 1st type parameter.</typeparam> /// <typeparam name="TType">The 2nd type parameter.</typeparam> IContainer RegisterSingleton<TInterface, TType>(TType instance) where TType : class, TInterface; /// <summary> /// Registers the singleton. /// </summary> /// <returns>The singleton.</returns> /// <param name="factory">Factory.</param> /// <typeparam name="TType">The 1st type parameter.</typeparam> IContainer RegisterSingleton<TType>(Func<IContainer, TType> factory) where TType : class; /// <summary> /// Registers the singleton. /// </summary> /// <returns>The singleton.</returns> /// <param name="factory">Factory.</param> /// <typeparam name="TType">The 1st type parameter.</typeparam> IContainer RegisterSingleton<TType>(Func<IContainer, ResolutionContext, TType> factory) where TType : class; /// <summary> /// Registers the singleton. /// </summary> /// <returns>The singleton.</returns> /// <param name="factory">Factory.</param> /// <typeparam name="TInterface">The 1st type parameter.</typeparam> /// <typeparam name="TType">The 2nd type parameter.</typeparam> IContainer RegisterSingleton<TInterface, TType>(Func<IContainer, TType> factory) where TType : class, TInterface; /// <summary> /// Registers the singleton. /// </summary> /// <returns>The singleton.</returns> /// <param name="factory">Factory.</param> /// <typeparam name="TInterface">The 1st type parameter.</typeparam> /// <typeparam name="TType">The 2nd type parameter.</typeparam> IContainer RegisterSingleton<TInterface, TType>(Func<IContainer, ResolutionContext, TType> factory) where TType : class, TInterface; /// <summary> /// Registers the singleton. /// </summary> /// <returns>The singleton.</returns> /// <param name="asType">As type.</param> IContainer RegisterSingleton(Type asType); /// <summary> /// Registers the singleton. /// </summary> /// <returns>The singleton.</returns> /// <param name="interfaceType">Interface type.</param> /// <param name="asType">As type.</param> IContainer RegisterSingleton(Type interfaceType, Type asType); /// <summary> /// Registers the singleton. /// </summary> /// <returns>The singleton.</returns> /// <param name="interfaceType">Interface type.</param> /// <param name="factory">Factory.</param> IContainer RegisterSingleton(Type interfaceType, Func<IContainer, object> factory); /// <summary> /// Registers the singleton. /// </summary> /// <returns>The singleton.</returns> /// <param name="interfaceType">Interface type.</param> /// <param name="factory">Factory.</param> IContainer RegisterSingleton(Type interfaceType, Func<IContainer, ResolutionContext, object> factory); /// <summary> /// Registers the singleton. /// </summary> /// <returns>The singleton.</returns> /// <param name="factory">Factory.</param> /// <typeparam name="TInterface">The 1st type parameter.</typeparam> IContainer RegisterSingleton<TInterface>(Func<IContainer, object> factory); /// <summary> /// Registers the singleton. /// </summary> /// <returns>The singleton.</returns> /// <param name="factory">Factory.</param> /// <typeparam name="TInterface">The 1st type parameter.</typeparam> IContainer RegisterSingleton<TInterface>(Func<IContainer, ResolutionContext, object> factory); /// <summary> /// Resolve the specified overrides. /// </summary> /// <returns>The resolve.</returns> /// <param name="overrides">Overrides.</param> /// <typeparam name="T">The 1st type parameter.</typeparam> T Resolve<T>(params IParameterOverride[] overrides) where T : class; /// <summary> /// Creates a resolver. /// </summary> /// <returns>The resolver.</returns> /// <typeparam name="T">The 1st type parameter.</typeparam> IResolver<T> ResolverFor<T>() where T : class; /// <summary> /// Resolve the specified type and overrides. /// </summary> /// <returns>The resolve.</returns> /// <param name="type">Type.</param> /// <param name="overrides">Overrides.</param> object Resolve(Type type, params IParameterOverride[] overrides); /// <summary> /// Resolves the or default. /// </summary> /// <returns>The or default.</returns> /// <param name="overrides">Overrides.</param> /// <typeparam name="T">The 1st type parameter.</typeparam> T ResolveOrDefault<T>(params IParameterOverride[] overrides) where T : class; /// <summary> /// Tries the resolve. /// </summary> /// <returns><c>true</c>, if resolve was tryed, <c>false</c> otherwise.</returns> /// <param name="obj">Object.</param> /// <param name="overrides">Overrides.</param> /// <typeparam name="T">The 1st type parameter.</typeparam> bool TryResolve<T>(out T obj, params IParameterOverride[] overrides) where T : class; /// <summary> /// Tries the resolve. /// </summary> /// <returns><c>true</c>, if resolve was tryed, <c>false</c> otherwise.</returns> /// <param name="type">Type.</param> /// <param name="obj">Object.</param> /// <param name="overrides">Overrides.</param> bool TryResolve(Type type, out object obj, params IParameterOverride[] overrides); /// <summary> /// Gets the parent container. /// </summary> /// <returns>The parent container.</returns> IContainer GetParentContainer(); /// <summary> /// Gets the root container. /// </summary> /// <returns>The root container.</returns> IContainer GetRootContainer(); /// <summary> /// Creates a child container. /// </summary> /// <returns>The child container.</returns> IContainer CreateChildContainer(); /// <summary> /// Creates a child container. /// </summary> /// <returns>The child container.</returns> /// <param name="appendTraceName">Append trace name.</param> IContainer CreateChildContainer(string appendTraceName); /// <summary> /// Cans the resolve. /// </summary> /// <returns><c>true</c>, if resolve was caned, <c>false</c> otherwise.</returns> /// <typeparam name="T">The 1st type parameter.</typeparam> bool CanResolve<T>(); /// <summary> /// Cans the resolve. /// </summary> /// <returns><c>true</c>, if resolve was caned, <c>false</c> otherwise.</returns> /// <param name="type">Type.</param> bool CanResolve(Type type); /// <summary> /// Cans the resolve locally. /// </summary> /// <returns><c>true</c>, if resolve locally was caned, <c>false</c> otherwise.</returns> /// <param name="type">Type.</param> bool CanResolveLocally(Type type); } }
41.688654
123
0.569684
[ "MIT" ]
laurence79/violet-ioc
VioletIoc/IContainer.cs
15,802
C#
using System; using System.Collections.Generic; using System.ComponentModel; namespace CloudRoboticsDefTool { public class SortableBindingList<T> : BindingList<T> { private readonly Dictionary<Type, PropertyComparer<T>> _comparers; private bool _isSorted; private ListSortDirection _listSortDirection; private PropertyDescriptor _propertyDescriptor; public SortableBindingList() : base(new List<T>()) { _comparers = new Dictionary<Type, PropertyComparer<T>>(); } public SortableBindingList(IEnumerable<T> enumeration) : base(new List<T>(enumeration)) { _comparers = new Dictionary<Type, PropertyComparer<T>>(); } protected override bool SupportsSortingCore => true; protected override bool IsSortedCore => _isSorted; protected override PropertyDescriptor SortPropertyCore => _propertyDescriptor; protected override ListSortDirection SortDirectionCore => _listSortDirection; protected override bool SupportsSearchingCore => true; protected override void ApplySortCore(PropertyDescriptor property, ListSortDirection direction) { var itemsList = (List<T>)Items; var propertyType = property.PropertyType; PropertyComparer<T> comparer; if (!_comparers.TryGetValue(propertyType, out comparer)) { comparer = new PropertyComparer<T>(property, direction); _comparers.Add(propertyType, comparer); } comparer.SetPropertyAndDirection(property, direction); itemsList.Sort(comparer); _propertyDescriptor = property; _listSortDirection = direction; _isSorted = true; OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1)); } protected override void RemoveSortCore() { _isSorted = false; _propertyDescriptor = base.SortPropertyCore; _listSortDirection = base.SortDirectionCore; OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1)); } protected override int FindCore(PropertyDescriptor property, object key) { var count = Count; for (var i = 0; i < count; ++i) { var element = this[i]; var elementValue = property.GetValue(element); if (elementValue != null && elementValue.Equals(key)) { return i; } } return -1; } } }
31.940476
103
0.608274
[ "MIT" ]
seijim/cloud-robotics-azure-platform-v1-sdk
CloudRoboticsDefTool/CloudRoboticsDefTool/SortableBindingList.cs
2,685
C#
//----------------------------------------------------------------- // All Rights Reserved. Copyright (C) 2021, DotNet. //----------------------------------------------------------------- using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; namespace DotNet.Business { using Model; using Util; /// <summary> /// BaseUserManager /// 用户管理-用户角色关系管理 /// /// 修改记录 /// /// 2020.12.08 版本:1.5 Troy.Cui 使用CacheUtil缓存 /// 2016.03.02 版本:2.1 JiRiGaLa 方法简化、能把去掉的方法全部去掉、这样调用的来源就好控制了。 /// 2016.02.26 版本:2.0 JiRiGaLa 用户角色关系进行缓存优化。 /// 2015.12.06 版本:1.1 JiRiGaLa 改进参数化、未绑定变量硬解析。 /// 2015.11.17 版本:1.1 JiRiGaLa 谁操作的?哪个系统的?哪个用户是否在哪个角色里?进行改进。 /// 2012.04.12 版本:1.0 JiRiGaLa 主键整理。 /// /// <author> /// <name>Troy.Cui</name> /// <date>2016.03.02</date> /// </author> /// </summary> public partial class BaseUserManager : BaseManager { /// <summary> /// 从缓存中获取角色编号 /// </summary> /// <param name="systemCode">系统编码</param> /// <param name="userId"></param> /// <param name="companyId"></param> /// <returns></returns> public static string[] GetRoleIdsByCache(string systemCode, string userId, string companyId = null) { // 返回值 string[] result = null; if (!string.IsNullOrEmpty(userId)) { //2017.12.20增加默认的HttpRuntime.Cache缓存 var cacheKey = "Array" + systemCode + userId + companyId + "RoleIds"; //var cacheTime = default(TimeSpan); var cacheTime = TimeSpan.FromMilliseconds(86400000); result = CacheUtil.Cache<string[]>(cacheKey, () => { //进行数据库查询 var userManager = new BaseUserManager(); return userManager.GetRoleIds(systemCode, userId, companyId); }, true, false, cacheTime); //// 进行数据库查询 //BaseUserManager userManager = new BaseUserManager(); //result = userManager.GetRoleIds(systemCode, userId, companyId); } return result; } /// <summary> /// 用户是否在角色里 /// 2015-12-24 吉日嘎拉 提供高速缓存使用的方法 /// </summary> /// <param name="systemCode">系统编号</param> /// <param name="userId">用户主键</param> /// <param name="roleCode">角色编号</param> /// <param name="companyId">公司主键</param> /// <returns>在角色中</returns> public static bool IsInRoleByCache(string systemCode, string userId, string roleCode, string companyId = null) { // 返回值 var result = false; if (!string.IsNullOrEmpty(userId)) { // 从缓存里快速得到角色对应的主键盘 var roleId = BaseRoleManager.GetIdByCodeByCache(systemCode, roleCode); if (!string.IsNullOrEmpty(roleId)) { var roleIds = GetRoleIdsByCache(systemCode, userId, companyId); if (roleIds != null && roleIds.Length > 0) { result = (Array.IndexOf(roleIds, roleId) >= 0); } } } return result; } /// <summary> /// 用户是否在某个角色里 /// 包括所在公司的角色也进行判断 /// </summary> /// <param name="userInfo">当前用户</param> /// <param name="roleName">角色名称</param> /// <returns>是否在角色中</returns> public bool IsInRole(BaseUserInfo userInfo, string roleName) { return IsInRole(userInfo.SystemCode, userInfo.Id, roleName); } /// <summary> /// 用户是否在某个角色中 /// </summary> /// <param name="userId">用户主键</param> /// <param name="roleName">角色</param> /// <returns>存在</returns> public bool IsInRole(string userId, string roleName) { var systemCode = "Base"; if (UserInfo != null && !string.IsNullOrWhiteSpace(UserInfo.SystemCode)) { systemCode = UserInfo.SystemCode; } return IsInRole(systemCode, userId, roleName); } /// <summary> /// 2015-11-17 吉日嘎拉 改进判断函数,方便别人调用,弱化当前操作者、可以灵活控制哪个子系统的数据 /// </summary> /// <param name="systemCode">系统编号</param> /// <param name="userId">用户主键</param> /// <param name="roleName">角色名称</param> /// <returns>是否在角色中</returns> public bool IsInRole(string systemCode, string userId, string roleName) { var result = false; // 用户参数不合法 if (string.IsNullOrEmpty(userId)) { return result; } // 角色名称不合法 if (string.IsNullOrEmpty(roleName)) { return result; } // 传入的系统编号不合法,自动认为是基础系统 if (string.IsNullOrEmpty(systemCode)) { systemCode = "Base"; } var roleId = BaseRoleManager.GetIdByNameByCache(systemCode, roleName); // 无法获取角色主键 if (string.IsNullOrEmpty(roleId)) { return false; } // 获取用户的所有角色主键列表 var roleIds = GetRoleIds(systemCode, userId); result = StringUtil.Exists(roleIds, roleId); return result; } /// <summary> /// 用户是否在某个角色里 /// 包括所在公司的角色也进行判断 /// </summary> /// <param name="userInfo">当前用户</param> /// <param name="code">编号</param> /// <returns>是否在角色里</returns> public bool IsInRoleByCode(BaseUserInfo userInfo, string code) { return IsInRoleByCode(userInfo.SystemCode, userInfo.Id, code); } /// <summary> /// 用户是否在某个角色中 /// </summary> /// <param name="userId">用户主键</param> /// <param name="code">角色编号</param> /// <returns>存在</returns> public bool IsInRoleByCode(string userId, string code) { var systemCode = "Base"; if (UserInfo != null && !string.IsNullOrWhiteSpace(UserInfo.SystemCode)) { systemCode = UserInfo.SystemCode; } return IsInRoleByCode(systemCode, userId, code); } /// <summary> /// 用户是否在某个角色中 /// </summary> /// <param name="systemCode">系统编号</param> /// <param name="userId">用户主键</param> /// <param name="roleCode">角色编号</param> /// <param name="useBaseRole">使用基础角色</param> /// <returns>存在</returns> public bool IsInRoleByCode(string systemCode, string userId, string roleCode, bool useBaseRole = true) { var result = false; if (string.IsNullOrEmpty(systemCode)) { return false; } if (string.IsNullOrEmpty(userId)) { return false; } // 2016-05-24 吉日嘎拉,若是Oracle数据库,用户的Id目前都是数值类型,若不是数字就出错了,不用进行运算了。 if (DbHelper.CurrentDbType == CurrentDbType.Oracle || DbHelper.CurrentDbType == CurrentDbType.SqlServer) { if (!ValidateUtil.IsInt(userId)) { return false; } } if (string.IsNullOrEmpty(roleCode)) { return false; } // 2016-01-07 吉日嘎拉 这里用缓存、效率会高 var roleId = BaseRoleManager.GetIdByCodeByCache(systemCode, roleCode); if (string.IsNullOrEmpty(roleId)) { // 2016-01-08 吉日嘎拉 看基础共用的角色里,是否在 if (useBaseRole && !systemCode.Equals("Base")) { roleId = BaseRoleManager.GetIdByCodeByCache("Base", roleCode); } if (string.IsNullOrEmpty(roleId)) { // 表明2个系统里都没了,就真没了 return false; } } var listUserRole = GetUserRoleEntityList(systemCode); result = listUserRole.Exists((t => t.UserId == userId && t.RoleId == roleId)); return result; } /// <summary> /// 获取用户角色实体列表 /// </summary> /// <param name="systemCode">系统编码</param> /// <returns></returns> public List<BaseUserRoleEntity> GetUserRoleEntityList(string systemCode) { var tableName = systemCode + "UserRole"; //2017.12.19增加默认的HttpRuntime.Cache缓存 var cacheKey = "List." + systemCode + ".UserRole"; //var cacheTime = default(TimeSpan); var cacheTime = TimeSpan.FromMilliseconds(86400000); var result = CacheUtil.Cache<List<BaseUserRoleEntity>>(cacheKey, () => { var parametersWhere = new List<KeyValuePair<string, object>> { new KeyValuePair<string, object>(BaseUserRoleEntity.FieldDeleted, 0), new KeyValuePair<string, object>(BaseUserRoleEntity.FieldEnabled, 1) }; return new BaseUserRoleManager(DbHelper, UserInfo, tableName).GetList<BaseUserRoleEntity>(parametersWhere, BaseUserRoleEntity.FieldId); }, true, false, cacheTime); return result; } #region IsHasRoleByCodeContains /// <summary> /// 用户是否拥有包含指定关键字的角色编码 /// </summary> /// <param name="userId">用户编号</param> /// <param name="searchKey">关键字</param> /// <returns></returns> public bool IsHasRoleCodeContains(string userId, string searchKey) { var systemCode = "Base"; if (UserInfo != null && !string.IsNullOrWhiteSpace(UserInfo.SystemCode)) { systemCode = UserInfo.SystemCode; } return IsHasRoleCodeContains(systemCode, userId, searchKey); } /// <summary> /// 用户是否拥有包含指定关键字的角色编码 /// </summary> /// <param name="systemCode">子系统编码</param> /// <param name="userId">用户编号</param> /// <param name="searchKey">关键字</param> /// <returns></returns> public bool IsHasRoleCodeContains(string systemCode, string userId, string searchKey) { var result = false; if (string.IsNullOrEmpty(systemCode)) { return false; } if (string.IsNullOrEmpty(userId)) { return false; } //用户的Id对Oracle和MSSQL目前都是数值类型,若不是数字就出错了,不用浪费时间了。 if (DbHelper.CurrentDbType == CurrentDbType.Oracle || DbHelper.CurrentDbType == CurrentDbType.SqlServer) { if (!ValidateUtil.IsInt(userId)) { return false; } } if (string.IsNullOrWhiteSpace(searchKey)) { return false; } var dt = GetUserRole(systemCode); var strWhere = "UserId = " + userId + " AND Code LIKE '%" + searchKey + "%'"; try { var drs = dt.Select(strWhere); //foreach (var dr in drs) //{ // result = true; // break; //} if (drs.Length > 0) { result = true; } } catch (Exception ex) { LogUtil.WriteException(ex); } return result; } #endregion #region IsHasRoleCodeStartWith /// <summary> /// 用户是否拥有以指定关键字开始的角色编码 /// </summary> /// <param name="userId">用户编号</param> /// <param name="searchKey">关键字</param> /// <returns></returns> public bool IsHasRoleCodeStartWith(string userId, string searchKey) { var systemCode = "Base"; if (UserInfo != null && !string.IsNullOrWhiteSpace(UserInfo.SystemCode)) { systemCode = UserInfo.SystemCode; } return IsHasRoleCodeStartWith(systemCode, userId, searchKey); } /// <summary> /// 用户是否拥有以指定关键字开始的角色编码 /// </summary> /// <param name="systemCode">子系统编码</param> /// <param name="userId">用户编号</param> /// <param name="searchKey">关键字</param> /// <returns></returns> public bool IsHasRoleCodeStartWith(string systemCode, string userId, string searchKey) { var result = false; if (string.IsNullOrEmpty(systemCode)) { return false; } if (string.IsNullOrEmpty(userId)) { return false; } //用户的Id对Oracle和MSSQL目前都是数值类型,若不是数字就出错了,不用浪费时间了。 if (DbHelper.CurrentDbType == CurrentDbType.Oracle || DbHelper.CurrentDbType == CurrentDbType.SqlServer) { if (!ValidateUtil.IsInt(userId)) { return false; } } if (string.IsNullOrWhiteSpace(searchKey)) { return false; } var dt = GetUserRole(systemCode); var strWhere = "UserId = " + userId + " AND Code LIKE '" + searchKey + "%'"; try { var drs = dt.Select(strWhere); //foreach (var dr in drs) //{ // result = true; // break; //} if (drs.Length > 0) { result = true; } } catch (Exception ex) { LogUtil.WriteException(ex); } return result; } #endregion /// <summary> /// 获取所有用户的角色列表 /// </summary> /// <param name="systemCode">系统编号</param> /// <returns>角色数据表</returns> public DataTable GetUserRole(string systemCode) { var result = new DataTable(BaseRoleEntity.TableName); var tableUserRoleName = BaseUserRoleEntity.TableName; if (!string.IsNullOrWhiteSpace(systemCode)) { tableUserRoleName = systemCode + "UserRole"; } var tableRoleName = BaseRoleEntity.TableName; if (!string.IsNullOrWhiteSpace(systemCode)) { tableRoleName = systemCode + "Role"; } var sb = Pool.StringBuilder.Get(); sb.AppendLine("SELECT BaseRole.Code, BaseRole.RealName, BaseRole.Description, UserRole.Id, UserRole.UserId, UserRole.RoleId, UserRole.Enabled, UserRole.DeletionStateCode, UserRole.CreateOn, UserRole.CreateBy, UserRole.ModifiedOn, UserRole.ModifiedBy"); sb.AppendLine(" FROM BaseRole INNER JOIN (SELECT Id, UserId, RoleId, Enabled, DeletionStateCode, CreateOn, CreateBy, ModifiedOn, ModifiedBy FROM BaseUserRole WHERE Enabled = 1 AND " + BaseUserRoleEntity.FieldDeleted + " = 0) UserRole ON BaseRole.Id = UserRole.RoleId"); sb.AppendLine(" WHERE BaseRole.Enabled = 1 AND BaseRole." + BaseRoleEntity.FieldDeleted + " = 0 ORDER BY UserRole.CreateOn DESC"); //替换表名 sb = sb.Replace("BaseUserRole", tableUserRoleName); sb = sb.Replace("BaseRole", tableRoleName); var cacheKey = "DataTable." + systemCode + ".UserRole"; //var cacheTime = default(TimeSpan); var cacheTime = TimeSpan.FromMilliseconds(86400000); result = CacheUtil.Cache<DataTable>(cacheKey, () => Fill(sb.Put()), true, false, cacheTime); return result; } /// <summary> /// 获取用户的角色主键数组 /// </summary> /// <param name="userId">用户主键</param> /// <returns>主键数组</returns> public string[] GetRoleIds(string userId) { return GetRoleIds(UserInfo.SystemCode, userId); } #region public string[] GetRoleIds(string systemCode, string userId, string companyId = null) 获取用户的角色主键数组 /// <summary> /// 获取用户的角色主键数组 /// </summary> /// <param name="systemCode">系统编号</param> /// <param name="userId">用户主键</param> /// <param name="companyId">公司主键</param> /// <returns>角色主键数组</returns> public string[] GetRoleIds(string systemCode, string userId, string companyId = null) { var result = new List<string>(); var userRoleTable = systemCode + "UserRole"; // 被删除的角色不应该显示出来 var sb = Pool.StringBuilder.Get(); sb.Append("SELECT " + BaseUserRoleEntity.FieldRoleId); sb.Append(" FROM " + userRoleTable); sb.Append(" WHERE " + BaseUserRoleEntity.FieldUserId + " = " + DbHelper.GetParameter(BaseUserRoleEntity.FieldUserId)); sb.Append(" AND " + BaseUserRoleEntity.FieldEnabled + " = " + DbHelper.GetParameter(BaseUserRoleEntity.FieldEnabled)); sb.Append(" AND " + BaseUserRoleEntity.FieldDeleted + " = " + DbHelper.GetParameter(BaseUserRoleEntity.FieldDeleted)); var dbParameters = new List<IDbDataParameter> { DbHelper.MakeParameter(BaseUserRoleEntity.FieldUserId, userId), DbHelper.MakeParameter(BaseUserRoleEntity.FieldEnabled, 1), DbHelper.MakeParameter(BaseUserRoleEntity.FieldDeleted, 0) }; /* if (useBaseRole && !systemCode.Equals("Base", StringComparison.OrdinalIgnoreCase)) { // 是否使用基础角色的权限 sql.Append(" UNION SELECT " + BaseUserRoleEntity.FieldRoleId); sql.Append(" FROM " + BaseUserRoleEntity.TableName); sql.Append(" WHERE ( " + BaseUserRoleEntity.FieldUserId + " = " + DbHelper.GetParameter(BaseUserRoleEntity.TableName + "_USEBASE_" + BaseUserRoleEntity.FieldUserId)); sql.Append(" AND " + BaseUserRoleEntity.FieldEnabled + " = 1 "); sql.Append(" AND " + BaseUserRoleEntity.FieldDeleted + " = 0 ) "); dbParameters.Add(DbHelper.MakeParameter(BaseUserRoleEntity.TableName + "_USEBASE_" + BaseUserRoleEntity.FieldUserId, userId)); } if (BaseSystemInfo.UseRoleOrganize && !string.IsNullOrEmpty(companyId)) { string roleOrganizeTableName = systemCode + "RoleOrganize"; sql += " UNION SELECT " + BaseRoleOrganizeEntity.FieldRoleId + " FROM " + roleOrganizeTableName + " WHERE " + BaseRoleOrganizeEntity.FieldOrganizeId + " = " + DbHelper.GetParameter(BaseRoleOrganizeEntity.FieldOrganizeId) + " AND " + BaseRoleOrganizeEntity.FieldEnabled + " = 1 " + " AND " + BaseRoleOrganizeEntity.FieldDeleted + " = 0 "; dbParameters.Add(DbHelper.MakeParameter(BaseRoleOrganizeEntity.FieldOrganizeId, companyId)); } */ using (var dataReader = DbHelper.ExecuteReader(sb.Put(), dbParameters.ToArray())) { while (dataReader.Read()) { result.Add(dataReader[BaseUserRoleEntity.FieldRoleId].ToString()); } dataReader.Close(); } return result.ToArray(); // return BaseUtil.FieldToArray(result, BaseUserRoleEntity.FieldRoleId).Distinct<string>().Where(t => !string.IsNullOrEmpty(t)).ToArray(); } #endregion #region public List<BaseRoleEntity> GetRoleList(string systemCode, string userId, string companyId = null) /// <summary> /// 一个用户的所有的角色列表 /// </summary> /// <param name="systemCode">系统编号</param> /// <param name="userId">用户主键</param> /// <param name="companyId">公司主键</param> /// <param name="useBaseRole"></param> /// <returns>角色列表</returns> public List<BaseRoleEntity> GetRoleList(string systemCode, string userId, string companyId = null, bool useBaseRole = true) { var result = new List<BaseRoleEntity>(); var roleIds = GetRoleIds(systemCode, userId, companyId); if (roleIds != null && roleIds.Length > 0) { var entities = BaseRoleManager.GetEntitiesByCache(systemCode); result = (entities as List<BaseRoleEntity>).Where(t => roleIds.Contains(t.Id) && t.Enabled == 1 && t.DeletionStateCode == 0).ToList(); } return result; /* string userRoleTable = systemCode + "UserRole"; string roleTable = systemCode + "Role"; // 被删除的角色不应该显示出来 string sql = @"SELECT * FROM " + roleTable + " WHERE Enabled = 1 AND " + BaseUserEntity.FieldDeleted + " = 0 AND Id " + " IN (SELECT RoleId FROM " + userRoleTable + " WHERE UserId = " + DbHelper.GetParameter(BaseUserRoleEntity.FieldUserId) + " AND Enabled = 1 AND " + BaseUserRoleEntity.FieldDeleted + " = 0 "; List<IDbDataParameter> dbParameters = new List<IDbDataParameter>(); dbParameters.Add(DbHelper.MakeParameter(BaseUserRoleEntity.FieldUserId, userId)); if (BaseSystemInfo.UseRoleOrganize && !string.IsNullOrEmpty(companyId)) { string roleOrganizeTableName = systemCode + "RoleOrganize"; sql += " UNION SELECT " + BaseRoleOrganizeEntity.FieldRoleId + " FROM " + roleOrganizeTableName + " WHERE " + BaseRoleOrganizeEntity.FieldOrganizeId + " = " + DbHelper.GetParameter(BaseRoleOrganizeEntity.FieldOrganizeId) + " AND " + BaseRoleOrganizeEntity.FieldEnabled + " = 1 " + " AND " + BaseRoleOrganizeEntity.FieldDeleted + " = 0 "; dbParameters.Add(DbHelper.MakeParameter(BaseRoleOrganizeEntity.FieldOrganizeId, companyId)); } sql += ")"; using (IDataReader dataReader = DbHelper.ExecuteReader(sql, dbParameters.ToArray())) { result = BaseEntity.GetList<BaseRoleEntity>(dataReader); } */ } #endregion #region public List<BaseUserEntity> GetListByRole(string systemCode, string roleCode, string companyId = null) 按角色编号获得用户列表 /// <summary> /// 按角色编号获得用户列表 /// </summary> /// <param name="systemCode">系统编号</param> /// <param name="roleCode">角色编号</param> /// <param name="companyId"></param> /// <returns>主键数组</returns> public List<BaseUserEntity> GetListByRole(string systemCode, string roleCode, string companyId = null) { List<BaseUserEntity> result = null; if (string.IsNullOrEmpty(systemCode)) { systemCode = "Base"; } var roleId = BaseRoleManager.GetIdByCodeByCache(systemCode, roleCode); if (!string.IsNullOrEmpty(roleId)) { result = GetListByRole(systemCode, new string[] { roleId }, companyId); } return result; } #endregion /// <summary> /// 根据角色获取清单 /// </summary> /// <param name="systemCode">系统编码</param> /// <param name="roleIds"></param> /// <param name="companyId"></param> /// <returns></returns> public List<BaseUserEntity> GetListByRole(string systemCode, string[] roleIds, string companyId = null) { var result = new List<BaseUserEntity>(); var dbParameters = new List<IDbDataParameter>(); var tableNameUserRole = systemCode + "UserRole"; var sql = "SELECT " + SelectFields + " FROM " + BaseUserEntity.TableName + " , (SELECT " + BaseUserRoleEntity.FieldUserId + " FROM " + tableNameUserRole + " WHERE " + BaseUserRoleEntity.FieldRoleId + " IN (" + string.Join(",", roleIds) + ")" + " AND " + BaseUserRoleEntity.FieldEnabled + " = 1 " + " AND " + BaseUserRoleEntity.FieldDeleted + " = 0) B " + " WHERE " + BaseUserEntity.TableName + "." + BaseUserEntity.FieldId + " = B." + BaseUserRoleEntity.FieldUserId + " AND " + BaseUserEntity.TableName + "." + BaseUserEntity.FieldEnabled + " = 1 " + " AND " + BaseUserEntity.TableName + "." + BaseUserEntity.FieldDeleted + "= 0"; if (!string.IsNullOrWhiteSpace(companyId)) { sql += " AND " + BaseUserEntity.TableName + "." + BaseUserEntity.FieldCompanyId + " = " + DbHelper.GetParameter(BaseUserEntity.FieldCompanyId); dbParameters.Add(DbHelper.MakeParameter(BaseUserEntity.FieldCompanyId, companyId)); } using (var dr = DbHelper.ExecuteReader(sql, dbParameters.ToArray())) { result = GetList<BaseUserEntity>(dr); } return result; } /// <summary> /// 根据角色获取数据表 /// </summary> /// <param name="systemCode">系统编码</param> /// <param name="roleIds"></param> /// <param name="companyId"></param> /// <returns></returns> public DataTable GetDataTableByRole(string systemCode, string[] roleIds, string companyId = null) { if (string.IsNullOrEmpty(systemCode)) { systemCode = "Base"; } var tableNameUserRole = systemCode + "UserRole"; var sql = "SELECT " + SelectFields + " FROM " + BaseUserEntity.TableName + " WHERE " + BaseUserEntity.FieldEnabled + " = 1 " + " AND " + BaseUserEntity.FieldDeleted + "= 0 " + " AND ( " + BaseUserEntity.FieldId + " IN " + " (SELECT " + BaseUserRoleEntity.FieldUserId + " FROM " + tableNameUserRole + " WHERE " + BaseUserRoleEntity.FieldRoleId + " IN (" + string.Join(",", roleIds) + ")" + " AND " + BaseUserRoleEntity.FieldEnabled + " = 1" + " AND " + BaseUserRoleEntity.FieldDeleted + " = 0)) " + " ORDER BY " + BaseUserEntity.FieldSortCode; return DbHelper.Fill(sql); } /// <summary> /// 清空用户 /// </summary> /// <param name="systemCode">系统编码</param> /// <param name="roleId"></param> /// <returns></returns> public int ClearUser(string systemCode, string roleId) { var result = 0; if (string.IsNullOrEmpty(systemCode)) { systemCode = "Base"; } var tableName = systemCode + "UserRole"; var manager = new BaseUserRoleManager(DbHelper, UserInfo, tableName); result += manager.Delete(new List<KeyValuePair<string, object>> { new KeyValuePair<string, object>(BaseUserRoleEntity.FieldRoleId, roleId) }); return result; } /// <summary> /// 清空角色 /// </summary> /// <param name="systemCode">系统编码</param> /// <param name="userId"></param> /// <returns></returns> public int ClearRole(string systemCode, string userId) { var result = 0; if (string.IsNullOrEmpty(systemCode)) { systemCode = "Base"; } var tableName = systemCode + "UserRole"; var manager = new BaseUserRoleManager(DbHelper, UserInfo, tableName); result += manager.Delete(new List<KeyValuePair<string, object>> { new KeyValuePair<string, object>(BaseUserRoleEntity.FieldUserId, userId) }); return result; } /// <summary> /// 获取用户的角色列表 /// </summary> /// <param name="systemCode">系统编号</param> /// <param name="userId">用户主键</param> /// <returns>角色数据表</returns> public DataTable GetUserRoleDataTable(string systemCode, string userId) { var result = new DataTable(BaseRoleEntity.TableName); var tableUserRoleName = BaseUserRoleEntity.TableName; if (!string.IsNullOrWhiteSpace(systemCode)) { tableUserRoleName = systemCode + "UserRole"; } var tableRoleName = BaseRoleEntity.TableName; if (!string.IsNullOrWhiteSpace(systemCode)) { tableRoleName = systemCode + "Role"; } var commandText = @"SELECT BaseRole.Id , BaseRole.Code , BaseRole.RealName , BaseRole.Description , UserRole.UserId , UserRole.Enabled , UserRole.DeletionStateCode , UserRole.CreateOn , UserRole.CreateBy , UserRole.ModifiedOn , UserRole.ModifiedBy FROM BaseRole RIGHT OUTER JOIN (SELECT UserId, RoleId, Enabled, DeletionStateCode, CreateOn, CreateBy, ModifiedOn, ModifiedBy FROM BaseUserRole WHERE UserId = " + DbHelper.GetParameter(BaseUserRoleEntity.FieldUserId) + " AND Enabled = 1 AND " + BaseUserRoleEntity.FieldDeleted + " = 0 " + @") UserRole ON BaseRole.Id = UserRole.RoleId WHERE BaseRole.Enabled = 1 AND BaseRole." + BaseRoleEntity.FieldDeleted + @" = 0 ORDER BY UserRole.CreateOn DESC "; //替换表名 commandText = commandText.Replace("BaseUserRole", tableUserRoleName); commandText = commandText.Replace("BaseRole", tableRoleName); var dbParameters = new List<IDbDataParameter> { DbHelper.MakeParameter(BaseUserRoleEntity.FieldUserId, userId) }; //2017.12.20增加默认的HttpRuntime.Cache缓存 var cacheKey = "DataTable." + systemCode + "." + userId + ".UserRole"; //var cacheTime = default(TimeSpan); var cacheTime = TimeSpan.FromMilliseconds(86400000); result = CacheUtil.Cache<DataTable>(cacheKey, () => Fill(commandText, dbParameters.ToArray()), true, false, cacheTime); return result; } /// <summary> /// 获取某个单位某个角色里的成员 /// 2015-12-05 吉日嘎拉 增加参数化优化。 /// </summary> /// <param name="systemCode">系统编号</param> /// <param name="companyId">公司主键</param> /// <param name="roleId">角色主键</param> /// <returns>用户数据表</returns> public DataTable GetDataTableByCompanyByRole(string systemCode, string companyId, string roleId) { var result = new DataTable(BaseRoleEntity.TableName); var commandText = @"SELECT BaseUser.Id , BaseUser.UserName , BaseUser.Code , BaseUser.Companyname , BaseUser.DepartmentName , BaseUser.RealName , BaseUser.Description , UserRole.Enabled , UserRole.CreateOn , UserRole.CreateBy , UserRole.ModifiedOn , UserRole.ModifiedBy FROM BaseUser RIGHT OUTER JOIN (SELECT UserId, Enabled, CreateOn, CreateBy, ModifiedOn, ModifiedBy FROM BaseUserRole WHERE RoleId = " + DbHelper.GetParameter(BaseUserRoleEntity.FieldRoleId) + " AND DeletionStateCode = " + DbHelper.GetParameter(BaseUserRoleEntity.FieldDeleted) + @") UserRole ON BaseUser.Id = UserRole.UserId WHERE BaseUser.CompanyId = " + DbHelper.GetParameter(BaseUserEntity.FieldCompanyId) + @" ORDER BY UserRole.CreateOn"; var dbParameters = new List<IDbDataParameter> { DbHelper.MakeParameter(BaseUserRoleEntity.FieldRoleId, roleId), DbHelper.MakeParameter(BaseUserRoleEntity.FieldDeleted, 0), DbHelper.MakeParameter(BaseUserEntity.FieldCompanyId, companyId) }; result = Fill(commandText, dbParameters.ToArray()); return result; } /// <summary> /// 是否为管理员 /// </summary> /// <param name="userId"></param> /// <returns></returns> public static bool IsAdministrator(string userId) { var result = false; using (var dbHelper = DbHelperFactory.GetHelper(BaseSystemInfo.UserCenterDbType, BaseSystemInfo.UserCenterDbConnection)) { var commandText = @"SELECT COUNT(*) " + " FROM " + BaseUserEntity.TableName + " WHERE Id = " + dbHelper.GetParameter(BaseUserEntity.FieldId) + " AND " + BaseUserEntity.FieldEnabled + " = " + dbHelper.GetParameter(BaseUserEntity.FieldEnabled) + " AND " + BaseUserEntity.FieldDeleted + " = " + dbHelper.GetParameter(BaseUserEntity.FieldDeleted) + " AND IsAdministrator = 1"; var dbParameters = new List<IDbDataParameter> { dbHelper.MakeParameter(BaseUserEntity.FieldId, userId), dbHelper.MakeParameter(BaseUserEntity.FieldEnabled, 1), dbHelper.MakeParameter(BaseUserEntity.FieldDeleted, 0) }; var isAdministrator = dbHelper.ExecuteScalar(commandText, dbParameters.ToArray()); result = int.Parse(isAdministrator.ToString()) > 0; } return result; } /// <summary> /// 从角色中删除 /// </summary> /// <param name="roleId"></param> /// <returns></returns> public string[] GetUserIdsInRoleId(string roleId) { return GetUserIdsInRoleId(UserInfo.SystemCode, roleId); } /// <summary> /// 获取用户主键数组 /// </summary> /// <param name="roleIds">角色主键数组</param> /// <returns>用户主键数组</returns> public string[] GetUserIds(string[] roleIds) { return GetUserIds("Base", roleIds); } #region public string[] GetUserIdsByRole(string systemCode, string roleCode, string companyId = null) 按角色编号获得用户主键数组 /// <summary> /// 按角色编号获得用户主键数组 /// </summary> /// <param name="systemCode">系统编号</param> /// <param name="roleCode">角色编号</param> /// <param name="companyId">公司主键</param> /// <returns>主键数组</returns> public string[] GetUserIdsByRole(string systemCode, string roleCode, string companyId = null) { string[] result = null; var roleId = BaseRoleManager.GetIdByCodeByCache(systemCode, roleCode); if (!string.IsNullOrEmpty(roleId)) { result = GetUserIdsInRoleId(systemCode, roleId, companyId); } return result; } #endregion #region public string[] GetUserIdsInRoleId(string systemCode, string roleId, string companyId = null) 按角色主键获得用户主键数组 /// <summary> /// 按角色主键获得用户主键数组 /// </summary> /// <param name="systemCode">系统编号</param> /// <param name="roleId">角色主键</param> /// <param name="companyId">公司主键</param> /// <returns>主键数组</returns> public string[] GetUserIdsInRoleId(string systemCode, string roleId, string companyId = null) { string[] result = null; var tableName = "BaseUserRole"; if (!string.IsNullOrEmpty(systemCode)) { tableName = systemCode + "UserRole"; } // 需要显示未被删除的用户 var sql = "SELECT UserId FROM " + tableName + " WHERE RoleId = " + DbHelper.GetParameter(BaseUserRoleEntity.FieldRoleId) + " AND " + BaseUserEntity.FieldDeleted + " = 0 " + " AND ( UserId IN ( SELECT " + BaseUserEntity.FieldId + " FROM " + BaseUserEntity.TableName + " WHERE " + BaseUserEntity.FieldEnabled + " = 1 " + BaseUserEntity.FieldDeleted + " = 0 "; var dbParameters = new List<IDbDataParameter> { DbHelper.MakeParameter(BaseUserRoleEntity.FieldRoleId, roleId) }; if (!string.IsNullOrWhiteSpace(companyId)) { sql += " AND " + BaseUserEntity.FieldCompanyId + " = " + DbHelper.GetParameter(BaseUserEntity.FieldCompanyId); dbParameters.Add(DbHelper.MakeParameter(BaseUserEntity.FieldCompanyId, companyId)); } sql += " ) )"; // var dt = DbHelper.Fill(sql); // return BaseUtil.FieldToArray(dt, BaseUserRoleEntity.FieldUserId).Distinct<string>().Where(t => !string.IsNullOrEmpty(t)).ToArray(); var userIds = new List<string>(); using (var dataReader = DbHelper.ExecuteReader(sql, dbParameters.ToArray())) { while (dataReader.Read()) { userIds.Add(dataReader["UserId"].ToString()); } } result = userIds.ToArray(); return result; } #endregion /// <summary> /// 获取用户主键数组 /// 2015-11-03 吉日嘎拉 优化程序、用ExecuteReader提高性能 /// </summary> /// <param name="systemCode">系统编号</param> /// <param name="roleIds">角色主键数组</param> /// <returns>用户主键数组</returns> public string[] GetUserIds(string systemCode, string[] roleIds) { string[] result = null; if (roleIds != null && roleIds.Length > 0) { // 需要显示未被删除的用户 var tableName = systemCode + "UserRole"; var commandText = "SELECT UserId FROM " + tableName + " WHERE RoleId IN (" + StringUtil.ArrayToList(roleIds) + ") " + " AND (UserId IN (SELECT Id FROM " + BaseUserEntity.TableName + " WHERE " + BaseUserEntity.FieldDeleted + " = 0)) AND (" + BaseUserEntity.FieldDeleted + " = 0)"; var ids = new List<string>(); using (var dr = DbHelper.ExecuteReader(commandText)) { while (dr.Read()) { ids.Add(dr["UserId"].ToString()); } } // 这里不需要有重复数据、用程序的方式把重复的数据去掉 // result = BaseUtil.FieldToArray(dt, BaseUserRoleEntity.FieldUserId).Distinct<string>().Where(t => !string.IsNullOrEmpty(t)).ToArray(); result = ids.ToArray(); } return result; } // // 加入到角色 // /* public string AddToRole(string systemCode, string userId, string roleName, bool enabled = true) { string result = string.Empty; string roleId = BaseRoleManager.GetIdByNameByCache(systemCode, roleName); if (!string.IsNullOrEmpty(roleId)) { result = AddToRoleById(systemCode, userId, roleId, enabled); } return result; } public int AddToRole(string systemCode, string userId, string[] roleIds, bool enabled = true) { int result = 0; for (int i = 0; i < roleIds.Length; i++) { this.AddToRoleById(systemCode, userId, roleIds[i], enabled); result++; } return result; } public int AddToRole(string systemCode, string[] userIds, string roleId) { int result = 0; for (int i = 0; i < userIds.Length; i++) { this.AddToRoleById(systemCode, userIds[i], roleId); result++; } return result; } */ /// <summary> /// 加入到角色 /// </summary> /// <param name="systemCode">系统编码</param> /// <param name="userIds"></param> /// <param name="roleIds"></param> /// <param name="enabled"></param> /// <returns></returns> public int AddToRole(string systemCode, string[] userIds, string[] roleIds, bool enabled = true) { var result = 0; for (var i = 0; i < userIds.Length; i++) { for (var j = 0; j < roleIds.Length; j++) { AddToRoleById(systemCode, userIds[i], roleIds[j], enabled); result++; } } return result; } #region public string AddToRole(string systemCode, string userId, string roleId, bool enabled = true) 为了提高授权的运行速度 /// <summary> /// 为了提高授权的运行速度 /// </summary> /// <param name="systemCode">系统编号</param> /// <param name="userId">用户主键</param> /// <param name="roleId">角色主键</param> /// <param name="enabled">有效状态</param> /// <returns>主键</returns> public string AddToRoleById(string systemCode, string userId, string roleId, bool enabled = true) { var result = string.Empty; if (string.IsNullOrEmpty(systemCode)) { systemCode = "Base"; } if (!string.IsNullOrEmpty(userId) && !string.IsNullOrEmpty(roleId)) { var entity = new BaseUserRoleEntity { UserId = userId, RoleId = roleId, Enabled = enabled ? 1 : 0, DeletionStateCode = 0 }; // 2016-03-02 吉日嘎拉 增加按公司可以区别数据的功能。 //if (this.DbHelper.CurrentDbType == CurrentDbType.MySql) //{ // entity.CompanyId = BaseUserManager.GetCompanyIdByCache(userId); //} // 2015-12-05 吉日嘎拉 把修改人记录起来,若是新增加的 if (UserInfo != null) { entity.CreateUserId = UserInfo.Id; entity.CreateBy = UserInfo.RealName; entity.CreateOn = DateTime.Now; entity.ModifiedUserId = UserInfo.Id; entity.ModifiedBy = UserInfo.RealName; entity.ModifiedOn = DateTime.Now; } var tableName = systemCode + "UserRole"; var manager = new BaseUserRoleManager(DbHelper, UserInfo, tableName); result = manager.Add(entity); } return result; } #endregion // // 从角色中移除用户 // #region public int RemoveFormRole(string systemCode, string userId, string roleId) 将用户从角色移除 /// <summary> /// 将用户从角色移除 /// </summary> /// <param name="systemCode">系统编号</param> /// <param name="userId">用户主键</param> /// <param name="roleId">角色主键</param> /// <returns>影响行数</returns> public int RemoveFormRole(string systemCode, string userId, string roleId) { var tableName = BaseUserRoleEntity.TableName; if (!string.IsNullOrWhiteSpace(systemCode)) { tableName = systemCode + "UserRole"; } var parameters = new List<KeyValuePair<string, object>> { new KeyValuePair<string, object>(BaseUserRoleEntity.FieldUserId, userId), new KeyValuePair<string, object>(BaseUserRoleEntity.FieldRoleId, roleId) }; var manager = new BaseUserRoleManager(DbHelper, UserInfo, tableName); return manager.Delete(parameters); } #endregion /// <summary> /// 从角色中删除 /// </summary> /// <param name="systemCode">系统编码</param> /// <param name="userId"></param> /// <param name="roleIds"></param> /// <returns></returns> public int RemoveFormRole(string systemCode, string userId, string[] roleIds) { var result = 0; for (var i = 0; i < roleIds.Length; i++) { //移除用户角色 result += RemoveFormRole(systemCode, userId, roleIds[i]); } return result; } /// <summary> /// 从角色中删除 /// </summary> /// <param name="systemCode">系统编码</param> /// <param name="userIds"></param> /// <param name="roleId"></param> /// <returns></returns> public int RemoveFormRole(string systemCode, string[] userIds, string roleId) { var result = 0; for (var i = 0; i < userIds.Length; i++) { //移除用户角色 result += RemoveFormRole(systemCode, userIds[i], roleId); } return result; } /// <summary> /// 从角色中删除 /// </summary> /// <param name="systemCode">系统编码</param> /// <param name="userIds"></param> /// <param name="roleIds"></param> /// <returns></returns> public int RemoveFormRole(string systemCode, string[] userIds, string[] roleIds) { var result = 0; for (var i = 0; i < userIds.Length; i++) { for (var j = 0; j < roleIds.Length; j++) { result += RemoveFormRole(systemCode, userIds[i], roleIds[j]); } } return result; } /// <summary> /// 轮循计数器 /// </summary> public static int UserIndex = 0; /// <summary> /// 从某个角色列表中轮循获取一个用户,在线的用户优先。 /// </summary> /// <param name="systemCode">子系统编码</param> /// <param name="roleCode">角色编号</param> /// <returns>用户主键</returns> public string GetRandomUserId(string systemCode, string roleCode) { var result = string.Empty; // 先不管是否在线,总需要能发一个人再说 var userIds = GetUserIdsByRole(systemCode, roleCode); if (userIds != null && userIds.Length > 0) { var index = UserIndex % userIds.Length; result = userIds[index]; // 接着再判断是否有人在线,若有在线的,发给在线的用户 var userLogOnManager = new BaseUserLogOnManager(DbHelper); userIds = userLogOnManager.GetOnLineUserIds(userIds); if (userIds != null && userIds.Length > 0) { index = UserIndex % userIds.Length; result = userIds[index]; } } UserIndex++; return result; } } }
39.167344
281
0.515089
[ "MIT" ]
cuiwenyuan/DotNet.Util
src/DotNet.Business/BaseUser/BaseUserManager.Role.cs
51,273
C#
//---------------------- // <auto-generated> // This file was automatically generated. Any changes to it will be lost if and when the file is regenerated. // </auto-generated> //---------------------- #pragma warning disable using System; using SQEX.Luminous.Core.Object; using System.Collections.Generic; using CodeDom = System.CodeDom; namespace Black.Sequence.Event { [Serializable, CodeDom.Compiler.GeneratedCode("Luminaire", "0.1")] public partial class SequenceEventPlayerStarted : SQEX.Ebony.Framework.Sequence.SequenceEvent { new public static ObjectType ObjectType { get; private set; } private static PropertyContainer fieldProperties; [UnityEngine.SerializeReference] public SQEX.Ebony.Framework.Node.GraphTriggerOutputPin out_= new SQEX.Ebony.Framework.Node.GraphTriggerOutputPin(); new public static void SetupObjectType() { if (ObjectType != null) { return; } var dummy = new SequenceEventPlayerStarted(); var properties = dummy.GetFieldProperties(); ObjectType = new ObjectType("Black.Sequence.Event.SequenceEventPlayerStarted", 0, Black.Sequence.Event.SequenceEventPlayerStarted.ObjectType, Construct, properties, 0, 272); } public override ObjectType GetObjectType() { return ObjectType; } protected override PropertyContainer GetFieldProperties() { if (fieldProperties != null) { return fieldProperties; } fieldProperties = new PropertyContainer("Black.Sequence.Event.SequenceEventPlayerStarted", base.GetFieldProperties(), 550843092, -1613362319); fieldProperties.AddIndirectlyProperty(new Property("refInPorts_", 1035088696, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin*, MEMORY_CATEGORY_FRAMEWORK >", 24, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)4)); fieldProperties.AddIndirectlyProperty(new Property("refOutPorts_", 283683627, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin*, MEMORY_CATEGORY_FRAMEWORK >", 40, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)4)); fieldProperties.AddIndirectlyProperty(new Property("triInPorts_", 291734708, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin*, MEMORY_CATEGORY_FRAMEWORK >", 96, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)4)); fieldProperties.AddIndirectlyProperty(new Property("triOutPorts_", 3107891487, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin*, MEMORY_CATEGORY_FRAMEWORK >", 112, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)4)); fieldProperties.AddIndirectlyProperty(new Property("out_.pinName_", 1137295951, "Base.String", 184, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("out_.name_", 2182257194, "Base.String", 200, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("out_.connections_", 2048532136, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin* >", 216, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)1)); fieldProperties.AddIndirectlyProperty(new Property("out_.delayType_", 124432558, "SQEX.Ebony.Framework.Node.GraphPin.DelayType", 248, 4, 1, Property.PrimitiveType.Enum, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("out_.delayTime_", 3264366185, "float", 252, 4, 1, Property.PrimitiveType.Float, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("out_.delayMaxTime_", 456551125, "float", 256, 4, 1, Property.PrimitiveType.Float, 0, (char)0)); fieldProperties.AddProperty(new Property("out_", 1514340864, "SQEX.Ebony.Framework.Node.GraphTriggerOutputPin", 176, 96, 1, Property.PrimitiveType.ClassField, 0, (char)0)); return fieldProperties; } private static BaseObject Construct() { return new SequenceEventPlayerStarted(); } } }
53.921053
241
0.711323
[ "MIT" ]
Gurrimo/Luminaire
Assets/Editor/Generated/Black/Sequence/Event/SequenceEventPlayerStarted.generated.cs
4,098
C#
namespace Configuration_Tool.Controls { public enum EComparison { Simple, Regex, Range, } }
12.9
38
0.55814
[ "MIT" ]
IAmSilK/CyberPatriot-Scoring-Report
Configuration Tool/Controls/EComparison.cs
131
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void AddAcross_Vector64_UInt16() { var test = new SimpleUnaryOpTest__AddAcross_Vector64_UInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__AddAcross_Vector64_UInt16 { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(UInt16[] inArray1, UInt16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>(); if ( (alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray ) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned( ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1 ); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<UInt16> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned( ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>() ); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__AddAcross_Vector64_UInt16 testClass) { var result = AdvSimd.Arm64.AddAcross(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load( SimpleUnaryOpTest__AddAcross_Vector64_UInt16 testClass ) { fixed (Vector64<UInt16>* pFld1 = &_fld1) { var result = AdvSimd.Arm64.AddAcross(AdvSimd.LoadVector64((UInt16*)(pFld1))); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static Vector64<UInt16> _clsVar1; private Vector64<UInt16> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__AddAcross_Vector64_UInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned( ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>() ); } public SimpleUnaryOpTest__AddAcross_Vector64_UInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned( ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>() ); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data1, new UInt16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.AddAcross( Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.AddAcross( AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64) .GetMethod(nameof(AdvSimd.Arm64.AddAcross), new Type[] { typeof(Vector64<UInt16>) }) .Invoke( null, new object[] { Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr) } ); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64) .GetMethod(nameof(AdvSimd.Arm64.AddAcross), new Type[] { typeof(Vector64<UInt16>) }) .Invoke( null, new object[] { AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr)) } ); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.AddAcross(_clsVar1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<UInt16>* pClsVar1 = &_clsVar1) { var result = AdvSimd.Arm64.AddAcross(AdvSimd.LoadVector64((UInt16*)(pClsVar1))); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArray1Ptr); var result = AdvSimd.Arm64.AddAcross(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArray1Ptr)); var result = AdvSimd.Arm64.AddAcross(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__AddAcross_Vector64_UInt16(); var result = AdvSimd.Arm64.AddAcross(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleUnaryOpTest__AddAcross_Vector64_UInt16(); fixed (Vector64<UInt16>* pFld1 = &test._fld1) { var result = AdvSimd.Arm64.AddAcross(AdvSimd.LoadVector64((UInt16*)(pFld1))); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.AddAcross(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<UInt16>* pFld1 = &_fld1) { var result = AdvSimd.Arm64.AddAcross(AdvSimd.LoadVector64((UInt16*)(pFld1))); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.AddAcross(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.AddAcross(AdvSimd.LoadVector64((UInt16*)(&test._fld1))); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult( Vector64<UInt16> op1, void* result, [CallerMemberName] string method = "" ) { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned( ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>() ); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned( ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<UInt16>>() ); Unsafe.CopyBlockUnaligned( ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt16>>() ); ValidateResult(inArray1, outArray, method); } private void ValidateResult( UInt16[] firstOp, UInt16[] result, [CallerMemberName] string method = "" ) { bool succeeded = true; if (Helpers.AddAcross(firstOp) != result[0]) { succeeded = false; } else { for (int i = 1; i < RetElementCount; i++) { if (result[i] != 0) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation( $"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.AddAcross)}<UInt16>(Vector64<UInt16>): {method} failed:" ); TestLibrary.TestFramework.LogInformation( $" firstOp: ({string.Join(", ", firstOp)})" ); TestLibrary.TestFramework.LogInformation( $" result: ({string.Join(", ", result)})" ); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
35.307971
124
0.551257
[ "MIT" ]
belav/runtime
src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/AddAcross.Vector64.UInt16.cs
19,490
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.AzureStack.V20170601.Outputs { /// <summary> /// Links to product icons. /// </summary> [OutputType] public sealed class IconUrisResponse { /// <summary> /// URI to hero icon. /// </summary> public readonly string? Hero; /// <summary> /// URI to large icon. /// </summary> public readonly string? Large; /// <summary> /// URI to medium icon. /// </summary> public readonly string? Medium; /// <summary> /// URI to small icon. /// </summary> public readonly string? Small; /// <summary> /// URI to wide icon. /// </summary> public readonly string? Wide; [OutputConstructor] private IconUrisResponse( string? hero, string? large, string? medium, string? small, string? wide) { Hero = hero; Large = large; Medium = medium; Small = small; Wide = wide; } } }
23.8
81
0.530812
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/AzureStack/V20170601/Outputs/IconUrisResponse.cs
1,428
C#
using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; //using Microsoft.VisualStudio.TestTools.UnitTesting; using Xunit; namespace TestHelper { /// <summary> /// Superclass of all Unit Tests for DiagnosticAnalyzers /// </summary> public abstract partial class DiagnosticVerifier { #region To be implemented by Test classes /// <summary> /// Get the CSharp analyzer being tested - to be implemented in non-abstract class /// </summary> protected virtual DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return null; } /// <summary> /// Get the Visual Basic analyzer being tested (C#) - to be implemented in non-abstract class /// </summary> protected virtual DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return null; } #endregion #region Verifier wrappers /// <summary> /// Called to test a C# DiagnosticAnalyzer when applied on the single inputted string as a source /// Note: input a DiagnosticResult for each Diagnostic expected /// </summary> /// <param name="source">A class in the form of a string to run the analyzer on</param> /// <param name="expected"> DiagnosticResults that should appear after the analyzer is run on the source</param> protected void VerifyCSharpDiagnostic(string source, params DiagnosticResult[] expected) { VerifyDiagnostics(new[] { source }, LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer(), expected); } /// <summary> /// Called to test a VB DiagnosticAnalyzer when applied on the single inputted string as a source /// Note: input a DiagnosticResult for each Diagnostic expected /// </summary> /// <param name="source">A class in the form of a string to run the analyzer on</param> /// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the source</param> protected void VerifyBasicDiagnostic(string source, params DiagnosticResult[] expected) { VerifyDiagnostics(new[] { source }, LanguageNames.VisualBasic, GetBasicDiagnosticAnalyzer(), expected); } /// <summary> /// Called to test a C# DiagnosticAnalyzer when applied on the inputted strings as a source /// Note: input a DiagnosticResult for each Diagnostic expected /// </summary> /// <param name="sources">An array of strings to create source documents from to run the analyzers on</param> /// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the sources</param> protected void VerifyCSharpDiagnostic(string[] sources, params DiagnosticResult[] expected) { VerifyDiagnostics(sources, LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer(), expected); } /// <summary> /// Called to test a VB DiagnosticAnalyzer when applied on the inputted strings as a source /// Note: input a DiagnosticResult for each Diagnostic expected /// </summary> /// <param name="sources">An array of strings to create source documents from to run the analyzers on</param> /// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the sources</param> protected void VerifyBasicDiagnostic(string[] sources, params DiagnosticResult[] expected) { VerifyDiagnostics(sources, LanguageNames.VisualBasic, GetBasicDiagnosticAnalyzer(), expected); } /// <summary> /// General method that gets a collection of actual diagnostics found in the source after the analyzer is run, /// then verifies each of them. /// </summary> /// <param name="sources">An array of strings to create source documents from to run the analyzers on</param> /// <param name="language">The language of the classes represented by the source strings</param> /// <param name="analyzer">The analyzer to be run on the source code</param> /// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the sources</param> private void VerifyDiagnostics(string[] sources, string language, DiagnosticAnalyzer analyzer, params DiagnosticResult[] expected) { var diagnostics = GetSortedDiagnostics(sources, language, analyzer); VerifyDiagnosticResults(diagnostics, analyzer, expected); } #endregion #region Actual comparisons and verifications /// <summary> /// Checks each of the actual Diagnostics found and compares them with the corresponding DiagnosticResult in the array of expected results. /// Diagnostics are considered equal only if the DiagnosticResultLocation, Id, Severity, and Message of the DiagnosticResult match the actual diagnostic. /// </summary> /// <param name="actualResults">The Diagnostics found by the compiler after running the analyzer on the source code</param> /// <param name="analyzer">The analyzer that was being run on the sources</param> /// <param name="expectedResults">Diagnostic Results that should have appeared in the code</param> private static void VerifyDiagnosticResults(IEnumerable<Diagnostic> actualResults, DiagnosticAnalyzer analyzer, params DiagnosticResult[] expectedResults) { int expectedCount = expectedResults.Count(); int actualCount = actualResults.Count(); if (expectedCount != actualCount) { string diagnosticsOutput = actualResults.Any() ? FormatDiagnostics(analyzer, actualResults.ToArray()) : " NONE."; Assert.True(false, string.Format("Mismatch between number of diagnostics returned, expected \"{0}\" actual \"{1}\"\r\n\r\nDiagnostics:\r\n{2}\r\n", expectedCount, actualCount, diagnosticsOutput)); } for (int i = 0; i < expectedResults.Length; i++) { var actual = actualResults.ElementAt(i); var expected = expectedResults[i]; if (expected.Line == -1 && expected.Column == -1) { if (actual.Location != Location.None) { Assert.True(false, string.Format("Expected:\nA project diagnostic with No location\nActual:\n{0}", FormatDiagnostics(analyzer, actual))); } } else { VerifyDiagnosticLocation(analyzer, actual, actual.Location, expected.Locations.First()); var additionalLocations = actual.AdditionalLocations.ToArray(); if (additionalLocations.Length != expected.Locations.Length - 1) { Assert.True(false, string.Format("Expected {0} additional locations but got {1} for Diagnostic:\r\n {2}\r\n", expected.Locations.Length - 1, additionalLocations.Length, FormatDiagnostics(analyzer, actual))); } for (int j = 0; j < additionalLocations.Length; ++j) { VerifyDiagnosticLocation(analyzer, actual, additionalLocations[j], expected.Locations[j + 1]); } } if (actual.Id != expected.Id) { Assert.True(false, string.Format("Expected diagnostic id to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Id, actual.Id, FormatDiagnostics(analyzer, actual))); } if (actual.Severity != expected.Severity) { Assert.True(false, string.Format("Expected diagnostic severity to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Severity, actual.Severity, FormatDiagnostics(analyzer, actual))); } if (actual.GetMessage() != expected.Message) { Assert.True(false, string.Format("Expected diagnostic message to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Message, actual.GetMessage(), FormatDiagnostics(analyzer, actual))); } } } /// <summary> /// Helper method to VerifyDiagnosticResult that checks the location of a diagnostic and compares it with the location in the expected DiagnosticResult. /// </summary> /// <param name="analyzer">The analyzer that was being run on the sources</param> /// <param name="diagnostic">The diagnostic that was found in the code</param> /// <param name="actual">The Location of the Diagnostic found in the code</param> /// <param name="expected">The DiagnosticResultLocation that should have been found</param> private static void VerifyDiagnosticLocation(DiagnosticAnalyzer analyzer, Diagnostic diagnostic, Location actual, DiagnosticResultLocation expected) { var actualSpan = actual.GetLineSpan(); Assert.True(actualSpan.Path == expected.Path || (actualSpan.Path != null && actualSpan.Path.Contains("Test0.") && expected.Path.Contains("Test.")), string.Format("Expected diagnostic to be in file \"{0}\" was actually in file \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Path, actualSpan.Path, FormatDiagnostics(analyzer, diagnostic))); var actualLinePosition = actualSpan.StartLinePosition; // Only check line position if there is an actual line in the real diagnostic if (actualLinePosition.Line > 0) { if (actualLinePosition.Line + 1 != expected.Line) { Assert.True(false, string.Format("Expected diagnostic to be on line \"{0}\" was actually on line \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Line, actualLinePosition.Line + 1, FormatDiagnostics(analyzer, diagnostic))); } } // Only check column position if there is an actual column position in the real diagnostic if (actualLinePosition.Character > 0) { if (actualLinePosition.Character + 1 != expected.Column) { Assert.True(false, string.Format("Expected diagnostic to start at column \"{0}\" was actually at column \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Column, actualLinePosition.Character + 1, FormatDiagnostics(analyzer, diagnostic))); } } } #endregion #region Formatting Diagnostics /// <summary> /// Helper method to format a Diagnostic into an easily readable string /// </summary> /// <param name="analyzer">The analyzer that this verifier tests</param> /// <param name="diagnostics">The Diagnostics to be formatted</param> /// <returns>The Diagnostics formatted as a string</returns> private static string FormatDiagnostics(DiagnosticAnalyzer analyzer, params Diagnostic[] diagnostics) { var builder = new StringBuilder(); for (int i = 0; i < diagnostics.Length; ++i) { builder.AppendLine("// " + diagnostics[i].ToString()); var analyzerType = analyzer.GetType(); var rules = analyzer.SupportedDiagnostics; foreach (var rule in rules) { if (rule != null && rule.Id == diagnostics[i].Id) { var location = diagnostics[i].Location; if (location == Location.None) { builder.AppendFormat("GetGlobalResult({0}.{1})", analyzerType.Name, rule.Id); } else { Assert.True(location.IsInSource, $"Test base does not currently handle diagnostics in metadata locations. Diagnostic in metadata: {diagnostics[i]}\r\n"); string resultMethodName = diagnostics[i].Location.SourceTree.FilePath.EndsWith(".cs") ? "GetCSharpResultAt" : "GetBasicResultAt"; var linePosition = diagnostics[i].Location.GetLineSpan().StartLinePosition; builder.AppendFormat("{0}({1}, {2}, {3}.{4})", resultMethodName, linePosition.Line + 1, linePosition.Character + 1, analyzerType.Name, rule.Id); } if (i != diagnostics.Length - 1) { builder.Append(','); } builder.AppendLine(); break; } } } return builder.ToString(); } #endregion } }
50.746324
197
0.578353
[ "MIT" ]
CaptainGlac1er/Discord.Net
test/Discord.Net.Tests/AnalyzerTests/Verifiers/DiagnosticVerifier.cs
13,805
C#
namespace Poker { using System; using System.Collections.Generic; public class Hand : IHand { public Hand(IList<ICard> cards) { this.Cards = cards; } public IList<ICard> Cards { get; private set; } public ICard[] OrderHand() { ICard[] array = new ICard[this.Cards.Count]; for (int count = 0; count < this.Cards.Count; count++) { array[count] = this.Cards[count]; } Array.Sort(array, delegate(ICard x, ICard y) { return x.Face.CompareTo(y.Face); }); return array; } public override string ToString() { string handToString = string.Empty; for (int count = 0; count < this.Cards.Count; count++) { ICard current = this.Cards[count]; handToString += current.ToString(); } return handToString; } } }
25.435897
95
0.496976
[ "Apache-2.0" ]
iliantrifonov/TelerikAcademy
HighQualityCode/11.TestDrivenDevelopment/Poker/Hand.cs
994
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace UltimateOrb { public readonly partial struct Boolean8 : IComparable, IComparable<Boolean8>, IConvertible, IEquatable<Boolean8>, ISerializable { // // Member Variables // private readonly byte m_value; // Do not rename (binary serialization) // The true value. // internal const byte TrueValue = 1; // The false value. // internal const byte FalseValue = 0; // // Internal Constants are real consts for performance. // // The internal string representation of true. // internal const string TrueLiteral = "True"; // The internal string representation of false. // internal const string FalseLiteral = "False"; private Boolean8(byte value) { m_value = value; } Boolean8(SerializationInfo info, StreamingContext context) { m_value = (bool)info.GetValue(nameof(m_value), typeof(bool))! ? TrueValue : FalseValue; } internal static readonly Boolean8 True = new Boolean8(TrueValue); internal static readonly Boolean8 False = new Boolean8(FalseValue); public static implicit operator Boolean8(bool value) { return new Boolean8(value ? TrueValue : FalseValue); } public static implicit operator bool(Boolean8 value) { return value.StandardValue; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public bool StandardValue { get => 0 != m_value; } // // Public Constants // // The public string representation of true. // public static readonly string TrueString = TrueLiteral; // The public string representation of false. // public static readonly string FalseString = FalseLiteral; // // Overriden Instance Methods // /*=================================GetHashCode================================== **Args: None **Returns: 1 or 0 depending on whether this instance represents true or false. **Exceptions: None **Overriden From: Value ==============================================================================*/ // Provides a hash code for this instance. public override int GetHashCode() { return StandardValue ? unchecked((int)TrueValue) : unchecked((int)FalseValue); } /*===================================ToString=================================== **Args: None **Returns: "True" or "False" depending on the state of the boolean. **Exceptions: None. ==============================================================================*/ // Converts the boolean value of this instance to a String. public override string ToString() { if (false == StandardValue) { return FalseLiteral; } return TrueLiteral; } public string ToString(IFormatProvider? provider) { return ToString(); } public bool TryFormat(Span<char> destination, out int charsWritten) { if (StandardValue) { if (unchecked((uint)destination.Length) > 3) { // uint cast, per https://github.com/dotnet/runtime/issues/10596 destination[0] = 'T'; destination[1] = 'r'; destination[2] = 'u'; destination[3] = 'e'; charsWritten = 4; return true; } } else { if (unchecked((uint)destination.Length) > 4) { destination[0] = 'F'; destination[1] = 'a'; destination[2] = 'l'; destination[3] = 's'; destination[4] = 'e'; charsWritten = 5; return true; } } charsWritten = 0; return false; } // Determines whether two Boolean objects are equal. public override bool Equals([NotNullWhen(true)] object? obj) { // If it's not a boolean, we're definitely not equal if (!(obj is Boolean8 value)) { return false; } return StandardValue == value.StandardValue; } // [NonVersionable] public bool Equals(Boolean8 obj) { return (0 == m_value) == (0 == obj.m_value); } // Compares this object to another object, returning an integer that // indicates the relationship. For booleans, false sorts before true. // null is considered to be less than any instance. // If object is not of type boolean, this method throws an ArgumentException. // // Returns a value less than zero if this object // public int CompareTo(object? obj) { if (obj == null) { return 1; } if (!(obj is Boolean8)) { throw new ArgumentException("Object must be of type Boolean8."); } if (StandardValue == ((Boolean8)obj).StandardValue) { return 0; } else if (StandardValue == false) { return -1; } return 1; } public int CompareTo(Boolean8 value) { if (StandardValue == value.StandardValue) { return 0; } else if (StandardValue == false) { return -1; } return 1; } // // Static Methods // // Custom string compares for early application use by config switches, etc // internal static bool IsTrueStringIgnoreCase(ReadOnlySpan<char> value) { return value.Length == 4 && (value[0] == 't' || value[0] == 'T') && (value[1] == 'r' || value[1] == 'R') && (value[2] == 'u' || value[2] == 'U') && (value[3] == 'e' || value[3] == 'E'); } internal static bool IsFalseStringIgnoreCase(ReadOnlySpan<char> value) { return value.Length == 5 && (value[0] == 'f' || value[0] == 'F') && (value[1] == 'a' || value[1] == 'A') && (value[2] == 'l' || value[2] == 'L') && (value[3] == 's' || value[3] == 'S') && (value[4] == 'e' || value[4] == 'E'); } // Determines whether a String represents true or false. // public static Boolean8 Parse(string value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return Parse(value.AsSpan()); } public static Boolean8 Parse(ReadOnlySpan<char> value) => TryParse(value, out var result) ? result : throw new FormatException(string.Format("String '{0}' was not recognized as a valid Boolean8.", new string(value))); // Determines whether a String represents true or false. // public static bool TryParse([NotNullWhen(true)] string? value, out Boolean8 result) { if (value == null) { result = new Boolean8(FalseValue); return false; } return TryParse(value.AsSpan(), out result); } public static bool TryParse(ReadOnlySpan<char> value, out Boolean8 result) { if (IsTrueStringIgnoreCase(value)) { result = new Boolean8(TrueValue); return true; } if (IsFalseStringIgnoreCase(value)) { result = new Boolean8(FalseValue); return true; } // Special case: Trim whitespace as well as null characters. value = TrimWhiteSpaceAndNull(value); if (IsTrueStringIgnoreCase(value)) { result = new Boolean8(TrueValue); return true; } if (IsFalseStringIgnoreCase(value)) { result = new Boolean8(FalseValue); return true; } result = new Boolean8(FalseValue); return false; } private static ReadOnlySpan<char> TrimWhiteSpaceAndNull(ReadOnlySpan<char> value) { const char nullChar = (char)0x0000; int start = 0; while (start < value.Length) { if (!char.IsWhiteSpace(value[start]) && value[start] != nullChar) { break; } start++; } int end = value.Length - 1; while (end >= start) { if (!char.IsWhiteSpace(value[end]) && value[end] != nullChar) { break; } end--; } return value.Slice(start, end - start + 1); } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Boolean; } Boolean IConvertible.ToBoolean(IFormatProvider? provider) { return 0 != m_value; } Char IConvertible.ToChar(IFormatProvider? provider) { // throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Boolean8", "Char")); throw new InvalidCastException("Conversion from type 'Boolean8' to type 'Char' is not valid."); } SByte IConvertible.ToSByte(IFormatProvider? provider) { return Convert.ToSByte(StandardValue); } Byte IConvertible.ToByte(IFormatProvider? provider) { return Convert.ToByte(StandardValue); } Int16 IConvertible.ToInt16(IFormatProvider? provider) { return Convert.ToInt16(StandardValue); } UInt16 IConvertible.ToUInt16(IFormatProvider? provider) { return Convert.ToUInt16(StandardValue); } Int32 IConvertible.ToInt32(IFormatProvider? provider) { return Convert.ToInt32(StandardValue); } UInt32 IConvertible.ToUInt32(IFormatProvider? provider) { return Convert.ToUInt32(StandardValue); } Int64 IConvertible.ToInt64(IFormatProvider? provider) { return Convert.ToInt64(StandardValue); } UInt64 IConvertible.ToUInt64(IFormatProvider? provider) { return Convert.ToUInt64(StandardValue); } Single IConvertible.ToSingle(IFormatProvider? provider) { return Convert.ToSingle(StandardValue); } Double IConvertible.ToDouble(IFormatProvider? provider) { return Convert.ToDouble(StandardValue); } Decimal IConvertible.ToDecimal(IFormatProvider? provider) { return Convert.ToDecimal(StandardValue); } DateTime IConvertible.ToDateTime(IFormatProvider? provider) { // throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Boolean8", "DateTime")); throw new InvalidCastException("Conversion from type 'Boolean8' to type 'DateTime' is not valid."); } object IConvertible.ToType(Type type, IFormatProvider? provider) { // Convert.DefaultToType((IConvertible)this, type, provider); return ((IConvertible)StandardValue).ToType(type, provider); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue(nameof(m_value), StandardValue); } public static bool operator ==(Boolean8 left, Boolean8 right) { return left.Equals(right); } public static bool operator !=(Boolean8 left, Boolean8 right) { return !(left == right); } } public readonly partial struct Boolean32 : IComparable, IComparable<Boolean32>, IConvertible, IEquatable<Boolean32>, ISerializable { // // Member Variables // private readonly uint m_value; // Do not rename (binary serialization) // The true value. // internal const uint TrueValue = 1; // The false value. // internal const uint FalseValue = 0; // // Internal Constants are real consts for performance. // // The internal string representation of true. // internal const string TrueLiteral = "True"; // The internal string representation of false. // internal const string FalseLiteral = "False"; private Boolean32(uint value) { m_value = value; } Boolean32(SerializationInfo info, StreamingContext context) { m_value = (bool)info.GetValue(nameof(m_value), typeof(bool))! ? TrueValue : FalseValue; } internal static readonly Boolean32 True = new Boolean32(TrueValue); internal static readonly Boolean32 False = new Boolean32(FalseValue); public static implicit operator Boolean32(bool value) { return new Boolean32(value ? TrueValue : FalseValue); } public static implicit operator bool(Boolean32 value) { return value.StandardValue; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public bool StandardValue { get => 0 != m_value; } // // Public Constants // // The public string representation of true. // public static readonly string TrueString = TrueLiteral; // The public string representation of false. // public static readonly string FalseString = FalseLiteral; // // Overriden Instance Methods // /*=================================GetHashCode================================== **Args: None **Returns: 1 or 0 depending on whether this instance represents true or false. **Exceptions: None **Overriden From: Value ==============================================================================*/ // Provides a hash code for this instance. public override int GetHashCode() { return StandardValue ? unchecked((int)TrueValue) : unchecked((int)FalseValue); } /*===================================ToString=================================== **Args: None **Returns: "True" or "False" depending on the state of the boolean. **Exceptions: None. ==============================================================================*/ // Converts the boolean value of this instance to a String. public override string ToString() { if (false == StandardValue) { return FalseLiteral; } return TrueLiteral; } public string ToString(IFormatProvider? provider) { return ToString(); } public bool TryFormat(Span<char> destination, out int charsWritten) { if (StandardValue) { if (unchecked((uint)destination.Length) > 3) { // uint cast, per https://github.com/dotnet/runtime/issues/10596 destination[0] = 'T'; destination[1] = 'r'; destination[2] = 'u'; destination[3] = 'e'; charsWritten = 4; return true; } } else { if (unchecked((uint)destination.Length) > 4) { destination[0] = 'F'; destination[1] = 'a'; destination[2] = 'l'; destination[3] = 's'; destination[4] = 'e'; charsWritten = 5; return true; } } charsWritten = 0; return false; } // Determines whether two Boolean objects are equal. public override bool Equals([NotNullWhen(true)] object? obj) { // If it's not a boolean, we're definitely not equal if (!(obj is Boolean32 value)) { return false; } return StandardValue == value.StandardValue; } // [NonVersionable] public bool Equals(Boolean32 obj) { return (0 == m_value) == (0 == obj.m_value); } // Compares this object to another object, returning an integer that // indicates the relationship. For booleans, false sorts before true. // null is considered to be less than any instance. // If object is not of type boolean, this method throws an ArgumentException. // // Returns a value less than zero if this object // public int CompareTo(object? obj) { if (obj == null) { return 1; } if (!(obj is Boolean32)) { throw new ArgumentException("Object must be of type Boolean32."); } if (StandardValue == ((Boolean32)obj).StandardValue) { return 0; } else if (StandardValue == false) { return -1; } return 1; } public int CompareTo(Boolean32 value) { if (StandardValue == value.StandardValue) { return 0; } else if (StandardValue == false) { return -1; } return 1; } // // Static Methods // // Custom string compares for early application use by config switches, etc // internal static bool IsTrueStringIgnoreCase(ReadOnlySpan<char> value) { return value.Length == 4 && (value[0] == 't' || value[0] == 'T') && (value[1] == 'r' || value[1] == 'R') && (value[2] == 'u' || value[2] == 'U') && (value[3] == 'e' || value[3] == 'E'); } internal static bool IsFalseStringIgnoreCase(ReadOnlySpan<char> value) { return value.Length == 5 && (value[0] == 'f' || value[0] == 'F') && (value[1] == 'a' || value[1] == 'A') && (value[2] == 'l' || value[2] == 'L') && (value[3] == 's' || value[3] == 'S') && (value[4] == 'e' || value[4] == 'E'); } // Determines whether a String represents true or false. // public static Boolean32 Parse(string value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return Parse(value.AsSpan()); } public static Boolean32 Parse(ReadOnlySpan<char> value) => TryParse(value, out var result) ? result : throw new FormatException(string.Format("String '{0}' was not recognized as a valid Boolean32.", new string(value))); // Determines whether a String represents true or false. // public static bool TryParse([NotNullWhen(true)] string? value, out Boolean32 result) { if (value == null) { result = new Boolean32(FalseValue); return false; } return TryParse(value.AsSpan(), out result); } public static bool TryParse(ReadOnlySpan<char> value, out Boolean32 result) { if (IsTrueStringIgnoreCase(value)) { result = new Boolean32(TrueValue); return true; } if (IsFalseStringIgnoreCase(value)) { result = new Boolean32(FalseValue); return true; } // Special case: Trim whitespace as well as null characters. value = TrimWhiteSpaceAndNull(value); if (IsTrueStringIgnoreCase(value)) { result = new Boolean32(TrueValue); return true; } if (IsFalseStringIgnoreCase(value)) { result = new Boolean32(FalseValue); return true; } result = new Boolean32(FalseValue); return false; } private static ReadOnlySpan<char> TrimWhiteSpaceAndNull(ReadOnlySpan<char> value) { const char nullChar = (char)0x0000; int start = 0; while (start < value.Length) { if (!char.IsWhiteSpace(value[start]) && value[start] != nullChar) { break; } start++; } int end = value.Length - 1; while (end >= start) { if (!char.IsWhiteSpace(value[end]) && value[end] != nullChar) { break; } end--; } return value.Slice(start, end - start + 1); } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Boolean; } Boolean IConvertible.ToBoolean(IFormatProvider? provider) { return 0 != m_value; } Char IConvertible.ToChar(IFormatProvider? provider) { // throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Boolean32", "Char")); throw new InvalidCastException("Conversion from type 'Boolean32' to type 'Char' is not valid."); } SByte IConvertible.ToSByte(IFormatProvider? provider) { return Convert.ToSByte(StandardValue); } Byte IConvertible.ToByte(IFormatProvider? provider) { return Convert.ToByte(StandardValue); } Int16 IConvertible.ToInt16(IFormatProvider? provider) { return Convert.ToInt16(StandardValue); } UInt16 IConvertible.ToUInt16(IFormatProvider? provider) { return Convert.ToUInt16(StandardValue); } Int32 IConvertible.ToInt32(IFormatProvider? provider) { return Convert.ToInt32(StandardValue); } UInt32 IConvertible.ToUInt32(IFormatProvider? provider) { return Convert.ToUInt32(StandardValue); } Int64 IConvertible.ToInt64(IFormatProvider? provider) { return Convert.ToInt64(StandardValue); } UInt64 IConvertible.ToUInt64(IFormatProvider? provider) { return Convert.ToUInt64(StandardValue); } Single IConvertible.ToSingle(IFormatProvider? provider) { return Convert.ToSingle(StandardValue); } Double IConvertible.ToDouble(IFormatProvider? provider) { return Convert.ToDouble(StandardValue); } Decimal IConvertible.ToDecimal(IFormatProvider? provider) { return Convert.ToDecimal(StandardValue); } DateTime IConvertible.ToDateTime(IFormatProvider? provider) { // throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Boolean32", "DateTime")); throw new InvalidCastException("Conversion from type 'Boolean32' to type 'DateTime' is not valid."); } object IConvertible.ToType(Type type, IFormatProvider? provider) { // Convert.DefaultToType((IConvertible)this, type, provider); return ((IConvertible)StandardValue).ToType(type, provider); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue(nameof(m_value), StandardValue); } public static bool operator ==(Boolean32 left, Boolean32 right) { return left.Equals(right); } public static bool operator !=(Boolean32 left, Boolean32 right) { return !(left == right); } } }
33.959212
172
0.529344
[ "MIT" ]
LEI-Hongfaan/UltimateOrb.Core
UltimateOrb.Core/Boolean{Core}.cs
24,147
C#
using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; namespace EventSource { public class EventData// : IEvent { //Aggregate ID public Guid SourceId { get; set; } public int Version { get; set; } //Aggregate Type public string SourceType { get; set; } public string Payload { get; set; } public Guid CorrelationId { get; set; } // Standard metadata. public string AssemblyName { get; set; } public string Namespace { get; set; } public string FullName { get; set; } public string TypeName { get; set; } public DateTime? ProcessedOn { get; set; } } // // public class Event // { // public Guid AggregateId { get; set; } // public string AggregateType { get; set; } // public int Version { get; set; } // public string Payload { get; set; } // public string CorrelationId { get; set; } // // // TODO: Following could be very useful for when rebuilding the read model from the event store, // // to avoid replaying every possible event in the system // // public string EventType { get; set; } // } }
28.512195
108
0.626176
[ "Apache-2.0" ]
JeffJin/link2mono
EventSource/EventStore/EventData.cs
1,169
C#
// Licensed under the BSD license // See the LICENSE file in the project root for more information using NLog.Layouts; using NLog.Targets.Syslog.Policies; using System.Globalization; using NLog.Targets.Syslog.Settings; namespace NLog.Targets.Syslog.MessageCreation { internal class Rfc5424 : MessageBuilder { private const string TimestampFormat = "{0:yyyy-MM-ddTHH:mm:ss.ffffffK}"; private static readonly byte[] SpaceBytes = { 0x20 }; private readonly string version; private readonly Layout hostnameLayout; private readonly Layout appNameLayout; private readonly Layout procIdLayout; private readonly Layout msgIdLayout; private readonly StructuredData structuredData; private readonly bool disableBom; private readonly FqdnHostnamePolicySet hostnamePolicySet; private readonly AppNamePolicySet appNamePolicySet; private readonly ProcIdPolicySet procIdPolicySet; private readonly MsgIdPolicySet msgIdPolicySet; private readonly Utf8MessagePolicy utf8MessagePolicy; public Rfc5424(Facility facility, Rfc5424Config rfc5424Config, EnforcementConfig enforcementConfig) : base(facility, enforcementConfig) { version = rfc5424Config.Version; hostnameLayout = rfc5424Config.Hostname; appNameLayout = rfc5424Config.AppName; procIdLayout = rfc5424Config.ProcId; msgIdLayout = rfc5424Config.MsgId; structuredData = new StructuredData(rfc5424Config.StructuredData, enforcementConfig); disableBom = rfc5424Config.DisableBom; hostnamePolicySet = new FqdnHostnamePolicySet(enforcementConfig, rfc5424Config.DefaultHostname); appNamePolicySet = new AppNamePolicySet(enforcementConfig, rfc5424Config.DefaultAppName); procIdPolicySet = new ProcIdPolicySet(enforcementConfig); msgIdPolicySet = new MsgIdPolicySet(enforcementConfig); utf8MessagePolicy = new Utf8MessagePolicy(enforcementConfig); } protected override void PrepareMessage(ByteArray buffer, LogEventInfo logEvent, string pri, string logEntry) { var encodings = new EncodingSet(!disableBom); AppendHeaderBytes(buffer, pri, logEvent, encodings); buffer.Append(SpaceBytes); AppendStructuredDataBytes(buffer, logEvent, encodings); buffer.Append(SpaceBytes); AppendMsgBytes(buffer, logEntry, encodings); utf8MessagePolicy.Apply(buffer); } private void AppendHeaderBytes(ByteArray buffer, string pri, LogEventInfo logEvent, EncodingSet encodings) { var timestamp = string.Format(CultureInfo.InvariantCulture, TimestampFormat, logEvent.TimeStamp); var hostname = hostnamePolicySet.Apply(hostnameLayout.Render(logEvent)); var appName = appNamePolicySet.Apply(appNameLayout.Render(logEvent)); var procId = procIdPolicySet.Apply(procIdLayout.Render(logEvent)); var msgId = msgIdPolicySet.Apply(msgIdLayout.Render(logEvent)); var header = $"{pri}{version} {timestamp} {hostname} {appName} {procId} {msgId}"; var headerBytes = encodings.Ascii.GetBytes(header); buffer.Append(headerBytes); } private void AppendStructuredDataBytes(ByteArray buffer, LogEventInfo logEvent, EncodingSet encodings) { structuredData.AppendBytes(buffer, logEvent, encodings); } private static void AppendMsgBytes(ByteArray buffer, string logEntry, EncodingSet encodings) { AppendPreambleBytes(buffer, encodings); AppendLogEntryBytes(buffer, logEntry, encodings); } private static void AppendPreambleBytes(ByteArray buffer, EncodingSet encodings) { var preambleBytes = encodings.Utf8.GetPreamble(); buffer.Append(preambleBytes); } private static void AppendLogEntryBytes(ByteArray buffer, string logEntry, EncodingSet encodings) { var logEntryBytes = encodings.Utf8.GetBytes(logEntry); buffer.Append(logEntryBytes); } } }
45.634409
143
0.695335
[ "BSD-3-Clause" ]
304NotModified/NLog.Targets.Syslog
src/NLog.Targets.Syslog/MessageCreation/Rfc5424.cs
4,244
C#
// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. // // To add a suppression to this file, right-click the message in the // Code Analysis results, point to "Suppress Message", and click // "In Suppression File". // You do not need to add suppressions to this file manually. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ebd", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.ActiveDirectoryServiceSettings.#EnableEbdMagicCookie")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.ApplicationTokenProvider.#LoginSilentAsync(System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.ApplicationTokenProvider.#LoginSilentAsync(System.String,System.String,System.String,Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.ApplicationTokenProvider.#LoginSilentAsync(System.String,System.String,System.String,Microsoft.Rest.Azure.Authentication.ActiveDirectoryServiceSettings)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.ApplicationTokenProvider.#LoginSilentAsync(System.String,System.String,System.String,Microsoft.Rest.Azure.Authentication.ActiveDirectoryServiceSettings,Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.ApplicationTokenProvider.#LoginSilentAsync(System.String,Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.ApplicationTokenProvider.#LoginSilentAsync(System.String,Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential,Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.ApplicationTokenProvider.#LoginSilentAsync(System.String,Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential,Microsoft.Rest.Azure.Authentication.ActiveDirectoryServiceSettings)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.ApplicationTokenProvider.#LoginSilentAsync(System.String,Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential,Microsoft.Rest.Azure.Authentication.ActiveDirectoryServiceSettings,Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.ApplicationTokenProvider.#LoginSilentAsync(System.String,System.String,Microsoft.Rest.Azure.Authentication.IApplicationAuthenticationProvider)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.ApplicationTokenProvider.#LoginSilentAsync(System.String,System.String,Microsoft.Rest.Azure.Authentication.IApplicationAuthenticationProvider,Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.ApplicationTokenProvider.#LoginSilentAsync(System.String,System.String,Microsoft.Rest.Azure.Authentication.IApplicationAuthenticationProvider,Microsoft.Rest.Azure.Authentication.ActiveDirectoryServiceSettings)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.ApplicationTokenProvider.#LoginSilentAsync(System.String,System.String,Microsoft.Rest.Azure.Authentication.IApplicationAuthenticationProvider,Microsoft.Rest.Azure.Authentication.ActiveDirectoryServiceSettings,Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.UserTokenProvider.#LoginWithPromptAsync(Microsoft.Rest.Azure.Authentication.ActiveDirectoryClientSettings)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.UserTokenProvider.#LoginWithPromptAsync(Microsoft.Rest.Azure.Authentication.ActiveDirectoryClientSettings,System.String,Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.UserTokenProvider.#LoginWithPromptAsync(Microsoft.Rest.Azure.Authentication.ActiveDirectoryClientSettings,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.UserTokenProvider.#LoginWithPromptAsync(Microsoft.Rest.Azure.Authentication.ActiveDirectoryClientSettings,Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.UserTokenProvider.#LoginWithPromptAsync(System.String,Microsoft.Rest.Azure.Authentication.ActiveDirectoryClientSettings)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.UserTokenProvider.#LoginWithPromptAsync(System.String,Microsoft.Rest.Azure.Authentication.ActiveDirectoryClientSettings,System.String,Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.UserTokenProvider.#LoginWithPromptAsync(System.String,Microsoft.Rest.Azure.Authentication.ActiveDirectoryClientSettings,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.UserTokenProvider.#LoginWithPromptAsync(System.String,Microsoft.Rest.Azure.Authentication.ActiveDirectoryClientSettings,Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.UserTokenProvider.#LoginWithPromptAsync(System.String,Microsoft.Rest.Azure.Authentication.ActiveDirectoryClientSettings,Microsoft.Rest.Azure.Authentication.ActiveDirectoryServiceSettings)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.UserTokenProvider.#LoginWithPromptAsync(System.String,Microsoft.Rest.Azure.Authentication.ActiveDirectoryClientSettings,Microsoft.Rest.Azure.Authentication.ActiveDirectoryServiceSettings,Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.UserTokenProvider.#LoginWithPromptAsync(System.String,Microsoft.Rest.Azure.Authentication.ActiveDirectoryClientSettings,Microsoft.Rest.Azure.Authentication.ActiveDirectoryServiceSettings,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.UserTokenProvider.#LoginWithPromptAsync(System.String,Microsoft.Rest.Azure.Authentication.ActiveDirectoryClientSettings,Microsoft.Rest.Azure.Authentication.ActiveDirectoryServiceSettings,System.String,Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.UserTokenProvider.#LoginWithPromptAsync(System.String,Microsoft.Rest.Azure.Authentication.ActiveDirectoryClientSettings,Microsoft.Rest.Azure.Authentication.ActiveDirectoryServiceSettings,Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier,Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.UserTokenProvider.#LoginSilentAsync(System.String,System.String,System.String,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.UserTokenProvider.#LoginSilentAsync(System.String,System.String,System.String,System.String,Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.UserTokenProvider.#LoginSilentAsync(System.String,System.String,System.String,System.String,Microsoft.Rest.Azure.Authentication.ActiveDirectoryServiceSettings)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.UserTokenProvider.#LoginSilentAsync(System.String,System.String,System.String,System.String,Microsoft.Rest.Azure.Authentication.ActiveDirectoryServiceSettings,Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ebd", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.ActiveDirectoryClientSettings.#EnableEbdMagicCookie")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.ApplicationTokenProvider.#LoginSilentAsync(System.String,System.String,System.Security.Cryptography.X509Certificates.X509Certificate2,Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.ApplicationTokenProvider.#LoginSilentAsync(System.String,System.String,System.Security.Cryptography.X509Certificates.X509Certificate2,Microsoft.Rest.Azure.Authentication.ActiveDirectoryServiceSettings)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.ApplicationTokenProvider.#LoginSilentAsync(System.String,System.String,System.Security.Cryptography.X509Certificates.X509Certificate2,Microsoft.Rest.Azure.Authentication.ActiveDirectoryServiceSettings,Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.ApplicationTokenProvider.#LoginSilentWithCertificateAsync(System.String,Microsoft.IdentityModel.Clients.ActiveDirectory.ClientAssertionCertificate)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.ApplicationTokenProvider.#LoginSilentWithCertificateAsync(System.String,Microsoft.IdentityModel.Clients.ActiveDirectory.ClientAssertionCertificate,Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.ApplicationTokenProvider.#LoginSilentWithCertificateAsync(System.String,Microsoft.IdentityModel.Clients.ActiveDirectory.ClientAssertionCertificate,Microsoft.Rest.Azure.Authentication.ActiveDirectoryServiceSettings)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.ApplicationTokenProvider.#LoginSilentAsync(System.String,Microsoft.IdentityModel.Clients.ActiveDirectory.ClientAssertionCertificate,Microsoft.Rest.Azure.Authentication.ActiveDirectoryServiceSettings,Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.ApplicationTokenProvider.#LoginSilentAsync(System.String,System.String,System.Security.Cryptography.X509Certificates.X509Certificate2)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.ApplicationTokenProvider.#LoginSilentAsync(System.String,System.String,System.Byte[],System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.ApplicationTokenProvider.#LoginSilentAsync(System.String,System.String,System.Byte[],System.String,Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.ApplicationTokenProvider.#LoginSilentAsync(System.String,System.String,System.Byte[],System.String,Microsoft.Rest.Azure.Authentication.ActiveDirectoryServiceSettings)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Rest.Azure.Authentication.ApplicationTokenProvider.#LoginSilentAsync(System.String,System.String,System.Byte[],System.String,Microsoft.Rest.Azure.Authentication.ActiveDirectoryServiceSettings,Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache)")]
294.321429
504
0.840371
[ "MIT" ]
fhoering/autorest
src/client/Microsoft.Rest.ClientRuntime.Azure.Authentication/GlobalSuppressions.cs
16,484
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Placable : MonoBehaviour { public GameObject placable; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } }
16.25
52
0.633846
[ "MIT" ]
0GreenClover0/Neighbour-Rampage-Redux
Neighbour-Rampage-Redux/Assets/Scripts/Placable/Placable.cs
327
C#
using Certes.Acme.Resource; using System; using Xunit; namespace Certes.Tests.Acme.Resource { public class AuthorizationTests { [Fact] public void CanGetSetProperties() { var authz = new Authorization(); authz.VerifyGetterSetter(a => a.Status, AuthorizationStatus.Deactivated); authz.VerifyGetterSetter(a => a.Challenges, new[] { new Challenge() }); authz.VerifyGetterSetter(a => a.Expires, DateTimeOffset.Now); authz.VerifyGetterSetter(a => a.Identifier, new Identifier()); authz.VerifyGetterSetter(a => a.Wildcard, true); authz.VerifyGetterSetter(a => a.Scope, new Uri("http://certes.is.working")); } } }
33.5
88
0.626866
[ "MIT" ]
AMEST/certes
test/Certes.Tests/Acme/Resource/AuthorizationTests.cs
739
C#
using Evolutionary.Individuals; using FluentAssertions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using Troschuetz.Random; using Xunit; namespace Evolutionary.Tests.Individuals { public partial class PermutationTests { public static IEnumerable<Func<Permutation>> Permutations { get; } = new Func<Permutation>[] { () => new Permutation(), () => new Permutation(new int[]{ }, true), () => new Permutation(new int[]{ }, false), () => new Permutation(new int[]{ 2, 1 }, true), () => new Permutation(new int[]{ 1, 2 }, true), () => new Permutation(new int[]{ 2, 1 }, false), () => new Permutation(new int[]{ 1, 2 }, false), () => new Permutation(new int[]{ 2, 1, 0 }, true), () => new Permutation(new int[]{ 1, 2, 0 }, true), () => new Permutation(new int[]{ 2, 1, 0 }, false), () => new Permutation(new int[]{ 1, 2, 0 }, false), }; public static IEnumerable<object[]> ValueEqualityData => from a in Permutations.Select((f, i) => (id: f(), index: i)) from b in Permutations.Select((f, i) => (id: f(), index: i)) select new object[] { a.id, b.id, a.index == b.index }; public static IEnumerable<object[]> ReferenceEqualityData { get { var list = Permutations.Select((f, i) => (id: f(), index: i)).ToList(); return from a in list from b in list select new object[] { a.id, b.id, a.index == b.index }; } } [MemberData(nameof(ValueEqualityData))] [MemberData(nameof(ReferenceEqualityData))] [Theory] public void Equality(Permutation a, Permutation b, bool shouldBeEqual) { if (shouldBeEqual) { // Test Equal(object) a.Equals((object)b) .Should().BeTrue(); a.Equals("string") .Should().BeFalse(); // Test Equal(Permutation) a.Equals(b) .Should().BeTrue(); // operator (a == b) .Should().BeTrue(); (a != b) .Should().BeFalse(); a.GetHashCode() .Should().Be(b.GetHashCode()); } else { // Test Equal(object) a.Equals((object)b) .Should().BeFalse(); a.Equals("string") .Should().BeFalse(); // Test Equal(Permutation) a.Equals(b) .Should().BeFalse(); // operator (a != b) .Should().BeTrue(); (a == b) .Should().BeFalse(); // This is technically not required but the current // implementation fulfills this. If this should ever // fail it could be bad luck or the the implementation // is really broken. a.GetHashCode() .Should().NotBe(b.GetHashCode()); } } public static IEnumerable<object[]> EqualityNullData => Permutations.Select(f => new object[] { f() }); [MemberData(nameof(EqualityNullData))] [Theory] public void EqualityNull(Permutation val) { (val == null) .Should().BeFalse(); (val != null) .Should().BeTrue(); (null == val) .Should().BeFalse(); (null != val) .Should().BeTrue(); // This is using Equals(object) val.Should() .NotBeNull(); } } }
33.116667
100
0.451686
[ "MIT" ]
quinmars/Evolutionary
Evolutionary.Tests/Individuals/PermutationTests.IEquatable.cs
3,976
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201 { using static Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Extensions; /// <summary>Properties of a private endpoint connection.</summary> public partial class ServerPrivateEndpointConnectionProperties : Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPrivateEndpointConnectionProperties, Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPrivateEndpointConnectionPropertiesInternal { /// <summary>Internal Acessors for PrivateEndpoint</summary> Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IPrivateEndpointProperty Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPrivateEndpointConnectionPropertiesInternal.PrivateEndpoint { get => (this._privateEndpoint = this._privateEndpoint ?? new Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.PrivateEndpointProperty()); set { {_privateEndpoint = value;} } } /// <summary>Internal Acessors for PrivateLinkServiceConnectionState</summary> Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPrivateLinkServiceConnectionStateProperty Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPrivateEndpointConnectionPropertiesInternal.PrivateLinkServiceConnectionState { get => (this._privateLinkServiceConnectionState = this._privateLinkServiceConnectionState ?? new Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ServerPrivateLinkServiceConnectionStateProperty()); set { {_privateLinkServiceConnectionState = value;} } } /// <summary>Internal Acessors for PrivateLinkServiceConnectionStateActionsRequired</summary> Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.PrivateLinkServiceConnectionStateActionsRequire? Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPrivateEndpointConnectionPropertiesInternal.PrivateLinkServiceConnectionStateActionsRequired { get => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPrivateLinkServiceConnectionStatePropertyInternal)PrivateLinkServiceConnectionState).ActionsRequired; set => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPrivateLinkServiceConnectionStatePropertyInternal)PrivateLinkServiceConnectionState).ActionsRequired = value; } /// <summary>Internal Acessors for ProvisioningState</summary> Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.PrivateEndpointProvisioningState? Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPrivateEndpointConnectionPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } /// <summary>Backing field for <see cref="PrivateEndpoint" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IPrivateEndpointProperty _privateEndpoint; /// <summary>Private endpoint which the connection belongs to.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Owned)] internal Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IPrivateEndpointProperty PrivateEndpoint { get => (this._privateEndpoint = this._privateEndpoint ?? new Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.PrivateEndpointProperty()); set => this._privateEndpoint = value; } /// <summary>Resource id of the private endpoint.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Inlined)] public string PrivateEndpointId { get => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IPrivateEndpointPropertyInternal)PrivateEndpoint).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IPrivateEndpointPropertyInternal)PrivateEndpoint).Id = value; } /// <summary>Backing field for <see cref="PrivateLinkServiceConnectionState" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPrivateLinkServiceConnectionStateProperty _privateLinkServiceConnectionState; /// <summary>Connection state of the private endpoint connection.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Owned)] internal Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPrivateLinkServiceConnectionStateProperty PrivateLinkServiceConnectionState { get => (this._privateLinkServiceConnectionState = this._privateLinkServiceConnectionState ?? new Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ServerPrivateLinkServiceConnectionStateProperty()); set => this._privateLinkServiceConnectionState = value; } /// <summary>The actions required for private link service connection.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Inlined)] public Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.PrivateLinkServiceConnectionStateActionsRequire? PrivateLinkServiceConnectionStateActionsRequired { get => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPrivateLinkServiceConnectionStatePropertyInternal)PrivateLinkServiceConnectionState).ActionsRequired; } /// <summary>The private link service connection description.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Inlined)] public string PrivateLinkServiceConnectionStateDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPrivateLinkServiceConnectionStatePropertyInternal)PrivateLinkServiceConnectionState).Description; set => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPrivateLinkServiceConnectionStatePropertyInternal)PrivateLinkServiceConnectionState).Description = value; } /// <summary>The private link service connection status.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Inlined)] public Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.PrivateLinkServiceConnectionStateStatus PrivateLinkServiceConnectionStateStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPrivateLinkServiceConnectionStatePropertyInternal)PrivateLinkServiceConnectionState).Status; set => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPrivateLinkServiceConnectionStatePropertyInternal)PrivateLinkServiceConnectionState).Status = value; } /// <summary>Backing field for <see cref="ProvisioningState" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.PrivateEndpointProvisioningState? _provisioningState; /// <summary>State of the private endpoint connection.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Origin(Microsoft.Azure.PowerShell.Cmdlets.MySql.PropertyOrigin.Owned)] public Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.PrivateEndpointProvisioningState? ProvisioningState { get => this._provisioningState; } /// <summary> /// Creates an new <see cref="ServerPrivateEndpointConnectionProperties" /> instance. /// </summary> public ServerPrivateEndpointConnectionProperties() { } } /// Properties of a private endpoint connection. public partial interface IServerPrivateEndpointConnectionProperties : Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IJsonSerializable { /// <summary>Resource id of the private endpoint.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = false, ReadOnly = false, Description = @"Resource id of the private endpoint.", SerializedName = @"id", PossibleTypes = new [] { typeof(string) })] string PrivateEndpointId { get; set; } /// <summary>The actions required for private link service connection.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = false, ReadOnly = true, Description = @"The actions required for private link service connection.", SerializedName = @"actionsRequired", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.PrivateLinkServiceConnectionStateActionsRequire) })] Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.PrivateLinkServiceConnectionStateActionsRequire? PrivateLinkServiceConnectionStateActionsRequired { get; } /// <summary>The private link service connection description.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = true, ReadOnly = false, Description = @"The private link service connection description.", SerializedName = @"description", PossibleTypes = new [] { typeof(string) })] string PrivateLinkServiceConnectionStateDescription { get; set; } /// <summary>The private link service connection status.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = true, ReadOnly = false, Description = @"The private link service connection status.", SerializedName = @"status", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.PrivateLinkServiceConnectionStateStatus) })] Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.PrivateLinkServiceConnectionStateStatus PrivateLinkServiceConnectionStateStatus { get; set; } /// <summary>State of the private endpoint connection.</summary> [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = false, ReadOnly = true, Description = @"State of the private endpoint connection.", SerializedName = @"provisioningState", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.PrivateEndpointProvisioningState) })] Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.PrivateEndpointProvisioningState? ProvisioningState { get; } } /// Properties of a private endpoint connection. internal partial interface IServerPrivateEndpointConnectionPropertiesInternal { /// <summary>Private endpoint which the connection belongs to.</summary> Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IPrivateEndpointProperty PrivateEndpoint { get; set; } /// <summary>Resource id of the private endpoint.</summary> string PrivateEndpointId { get; set; } /// <summary>Connection state of the private endpoint connection.</summary> Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPrivateLinkServiceConnectionStateProperty PrivateLinkServiceConnectionState { get; set; } /// <summary>The actions required for private link service connection.</summary> Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.PrivateLinkServiceConnectionStateActionsRequire? PrivateLinkServiceConnectionStateActionsRequired { get; set; } /// <summary>The private link service connection description.</summary> string PrivateLinkServiceConnectionStateDescription { get; set; } /// <summary>The private link service connection status.</summary> Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.PrivateLinkServiceConnectionStateStatus PrivateLinkServiceConnectionStateStatus { get; set; } /// <summary>State of the private endpoint connection.</summary> Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.PrivateEndpointProvisioningState? ProvisioningState { get; set; } } }
89.522388
634
0.773508
[ "MIT" ]
Arsasana/azure-powershell
src/MySql/generated/api/Models/Api20171201/ServerPrivateEndpointConnectionProperties.cs
11,863
C#
namespace Minotaur.Theseus.RuleCreation { using System; using Minotaur.Classification.Rules; using Minotaur.Collections.Dataset; public sealed class SingleLabelConsequentCreator: IConsequentCreator { private readonly Dataset _dataset; public SingleLabelConsequentCreator(Dataset dataset) { _dataset = dataset; } public Consequent CreateConsequent(ReadOnlySpan<int> indicesOfDatasetInstances) { // @Performance throw new NotImplementedException(); //var labels = new int[indicesOfDatasetInstances.Length]; //for (int i = 0; i < indicesOfDatasetInstances.Length; i++) { // var instanceIndex = indicesOfDatasetInstances[i]; // var label = (SingleLabel) Dataset.GetInstanceLabel(instanceIndex: instanceIndex); // labels[i] = label.Value; //} //Array.Sort(labels); //var commonestValue = labels[labels.Length / 2]; //return new SingleLabel(commonestValue); } } }
27
87
0.739651
[ "MIT" ]
Mirandatz/minotaur
Minotaur/Minotaur/Theseus/RuleCreation/SingleLabelConsequentCreator.cs
918
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("DocTools")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DocTools")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 会使此程序集中的类型 //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("130a8861-0c39-4933-9de8-aa9525488211")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 //通过使用 "*",如下所示: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
25.162162
56
0.714286
[ "MIT" ]
lie-flat/DBCHMForCFPSHomework
DocTools/Properties/AssemblyInfo.cs
1,272
C#
namespace VtConnect.Telnet { /// <summary> /// Telnet commands as per RFC854 /// </summary> /// <remarks> /// In order to make this easier to implement, I've copied from the RFC /// excerpts verbatim. I can't find a copyright statement in the document /// to properly reproduce as is suggested in the IETF Trusts faq. If someone /// finds the "fair use" of this reproduction "not fair", please file /// an issue on the active git of this project and it will be resolved. /// </remarks> public enum ETelnetCommand { /// <summary> /// End of subnegotiation parameters. /// </summary> SE = 240, /// <summary> /// No operation. /// </summary> NOP = 241, /// <summary> /// The data stream portion of a Synch. /// </summary> /// <remarks> /// This should always be accompanied by a TCP Urgent notification. /// </remarks> DataMark = 241, /// <summary> /// NVT character BRK. (Network Virtual Terminal) /// </summary> Break = 243, /// <summary> /// The function IP. /// </summary> /// <remarks> /// Many systems provide a function which suspends, interrupts, /// aborts, or terminates the operation of a user process. This /// function is frequently used when a user believes his process is /// in an unending loop, or when an unwanted process has been /// inadvertently activated. IP is the standard representation for /// invoking this function. It should be noted by implementers /// that IP may be required by other protocols which use TELNET, /// and therefore should be implemented if these other protocols /// are to be supported. /// </remarks> InterruptProcess = 244, /// <summary> /// The function AO. /// </summary> /// <remarks> /// Many systems provide a function which allows a process, which /// is generating output, to run to completion (or to reach the /// same stopping point it would reach if running to completion) /// but without sending the output to the user's terminal. /// Further, this function typically clears any output already /// produced but not yet actually printed (or displayed) on the /// user's terminal. AO is the standard representation for /// invoking this function. For example, some subsystem might /// normally accept a user's command, send a long text string to /// the user's terminal in response, and finally signal readiness /// to accept the next command by sending a "prompt" character /// (preceded by 'CR''LF') to the user's terminal. If the AO were /// received during the transmission of the text string, a /// reasonable implementation would be to suppress the remainder of /// the text string, but transmit the prompt character and the /// preceding 'CR''LF'. (This is possibly in distinction to the /// action which might be taken if an IP were received; the IP /// might cause suppression of the text string and an exit from the /// subsystem.) /// /// It should be noted, by server systems which provide this /// function, that there may be buffers external to the system (in /// the network and the user's local host) which should be cleared; /// the appropriate way to do this is to transmit the "Synch" /// signal (described below) to the user system. /// </remarks> AbortOutput = 254, /// <summary> /// The function AYT. /// </summary> /// <remarks> /// Many systems provide a function which provides the user with /// some visible (e.g., printable) evidence that the system is /// still up and running. This function may be invoked by the user /// when the system is unexpectedly "silent" for a long time, /// because of the unanticipated (by the user) length of a /// computation, an unusually heavy system load, etc. AYT is the /// standard representation for invoking this function. /// </remarks> AreYouThere = 246, /// <summary> /// The function EC. /// </summary> /// <remarks> /// Many systems provide a function which deletes the last /// preceding undeleted character or "print position"* from the /// stream of data being supplied by the user. This function is /// typically used to edit keyboard input when typing mistakes are /// made. EC is the standard representation for invoking this /// function. /// /// *NOTE: A "print position" may contain several characters /// which are the result of overstrikes, or of sequences such as /// 'char1' BS 'char2'... /// </remarks> EraseCharacter = 247, /// <summary> /// The function EL. /// </summary> /// <remarks> /// Many systems provide a function which deletes all the data in /// the current "line" of input. This function is typically used /// to edit keyboard input. EL is the standard representation for /// invoking this function. /// </remarks> EraseLine = 248, /// <summary> /// The GA signal. /// </summary> GoAhead = 249, /// <summary> /// Indicates that what follows is subnegotiation of the indicated option. /// </summary> SB = 250, /// <summary> /// Indicates the desire to begin performing, or confirmation that you are now performing, /// the indicated option. /// </summary> Will = 251, /// <summary> /// Indicates the refusal to perform, or continue performing, the indicated option. /// </summary> Wont = 252, /// <summary> /// Indicates the request that the other party perform, or confirmation that you /// are expecting indicated option. /// </summary> Do = 253, /// <summary> /// Indicates the demand that the other party stop performing, or confirmation that /// you are no longer expecting the other party to perform, the indicated option. /// </summary> Dont = 254, /// <summary> /// Data Byte 255. /// </summary> IAC = 255, } }
39.790419
98
0.584951
[ "MIT" ]
maggch97/PowerTask
modules/VtConnect/VtConnect/Telnet/ETelnetCommand.cs
6,647
C#