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.Collections; using System.Collections.Generic; using UnityEngine; public class ClearColorSweet : ClearedSweet { private ColorSweet.ColorType clearColor; public ColorSweet.ColorType ClearColor { get { return clearColor; } set { clearColor = value; } } public override void Clear() { base.Clear(); sweet.gameManager.ClearColor(clearColor); } }
17.035714
49
0.589099
[ "MIT" ]
IlchKhailtuud/GAME3011_A3_YiliqiXu
Assets/Scripts/ClearColorSweet.cs
479
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Cake.Core.IO; namespace Cake.Core.Tooling { /// <summary> /// Base class for tool settings. /// </summary> public class ToolSettings { /// <summary> /// Gets or sets the tool path. /// </summary> /// <value>The tool path.</value> public FilePath ToolPath { get; set; } /// <summary> /// Gets or sets optional timeout for tool execution. /// </summary> public TimeSpan? ToolTimeout { get; set; } /// <summary> /// Gets or sets the working directory for the tool process. /// </summary> /// <value>The working directory for the tool process.</value> public DirectoryPath WorkingDirectory { get; set; } /// <summary> /// Gets or sets a value indicating whether or not to opt out of using /// an explicit working directory for the process. /// </summary> public bool NoWorkingDirectory { get; set; } /// <summary> /// Gets or sets the argument customization. /// Argument customization is a way that lets you add, replace or reuse arguments passed to a tool. /// This allows you to support new tool arguments, customize arguments or address potential argument issues. /// </summary> /// <example> /// <para>Combining tool specific settings and tool arguments:</para> /// <code> /// NuGetAddSource("Cake", "https://www.myget.org/F/cake/api/v3/index.json", /// new NuGetSourcesSettings { UserName = "user", Password = "incorrect", /// ArgumentCustomization = args=&gt;args.Append("-StorePasswordInClearText") /// }); /// </code> /// </example> /// <example> /// <para>Setting multiple tool arguments:</para> /// <code> /// MSTest(pathPattern, new MSTestSettings() /// { ArgumentCustomization = args=&gt;args.Append("/detail:errormessage") /// .Append("/resultsfile:TestResults.trx") }); /// </code> /// </example> /// <value>The delegate used to customize the <see cref="Cake.Core.IO.ProcessArgumentBuilder" />.</value> public Func<ProcessArgumentBuilder, ProcessArgumentBuilder> ArgumentCustomization { get; set; } /// <summary> /// Gets or sets search paths for files, directories for temporary files, application-specific options, and other similar information. /// </summary> /// <example> /// <code> /// MSBuild("./src/Cake.sln", new MSBuildSettings { /// EnvironmentVariables = new Dictionary&lt;string, string&gt;{ /// { "TOOLSPATH", MakeAbsolute(Directory("./tools")).FullPath } /// }}); /// </code> /// </example> public IDictionary<string, string> EnvironmentVariables { get; set; } = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Gets or sets whether the exit code from the tool process causes an exception to be thrown. /// <para> /// If the delegate is null (the default) or returns false, then an exception is thrown upon a non-zero exit code. /// </para> /// <para> /// If the delegate returns true then no exception is thrown. /// </para> /// <para> /// This can be useful when the exit code should be ignored, or if there is a desire to apply logic that is conditional /// on the exit code value. /// </para> /// </summary> /// <example> /// Don't throw exceptions if DotNetCoreTest returns non-zero: /// <code> /// DotNetCoreTest("MyProject.csproj", new DotNetCoreTestSettings { /// HandleExitCode = _=&gt; true /// }); /// </code> /// </example> /// <example> /// Use custom logic for exit code: /// <code> /// DotNetCoreTest("MyProject.csproj", new DotNetCoreTestSettings { /// HandleExitCode = exitCode =&gt; exitCode switch { /// 0 =&gt; throw new CakeException("ZERO"), /// 1 =&gt; true, // treat 1 and 2 as handled "ok". /// 2 =&gt; true, /// _ =&gt; false // everything else will throw via default implementation /// }; /// }); /// </code> /// </example> public Func<int, bool> HandleExitCode { get; set; } } }
42.40708
145
0.567821
[ "MIT" ]
Acidburn0zzz/cake
src/Cake.Core/Tooling/ToolSettings.cs
4,794
C#
using UnityEngine; using System; using System.Text; using System.IO; using System.Collections; using System.Diagnostics; using UnityEngine.SceneManagement; using UnityEditor; public class AutoForward_City : MonoBehaviour { Rigidbody m_Rigidbody; float AutoMoveSpeed = 1f; public static float m_distanceTraveled = 0f; public static bool AutoMove_on = false; public static bool Finished = false; private bool JoyStick_Returned = true; public GameObject exit_Canvas; public GameObject ControlerModel; public GameObject ArrowPedestrain; public GameObject ArrowBox; public static bool showForwardButton = false; public static bool showBackButton = false; public string ProjectSelectScene; public AudioClip[] ChineseAudios; public static string filename; public static string SavePath; Transform hmd = null; Vector3 oldPosition; public AudioClip[] InstructionAudioClip; private AudioSource InstructionAudioSource; public GameObject[] ObjectHidedInPractice; public GameObject[] ObjectActivatedInPractice; public GameObject[] ObjectHidedInTutorial; public GameObject[] ObjectActivatedInTutorial; public static bool isTutorial; public static bool isPractice = false; public static bool isRealTest = false; public static bool isChangingToPrac = false; public static bool isChangingToReal = false; public static bool isFirstRoute = true; public static bool isRouteTest = false; public static int routeCount = 0; private int instruction_order = 0; private float instructionTimeElapsed; private float keyHoldTimeElapsed; private bool isKeyHoldTimeSatisfied; private bool isBackwardDistanceSatisfied; private bool isForwardDistanceSatisfied; private float pedestrainCollisionPosX; private float lastPlayerPosX; private bool controllerButton_Forward_O = true; private bool controllerButton_Backward_X = true; private bool isInstructionAudioActivated = false; private bool isInstructionFinished = false; private string onCollisionObjectName; private String[] actionsDebugList; void Awake () { hmd = GameObject.Find("Camera (head)").transform; //CenterEyeAnchor oldPosition = transform.position; m_Rigidbody = GameObject.Find("XRRig").GetComponent<Rigidbody>(); SetLanguage(); } void Start () { Finished = false; m_distanceTraveled = 0f; if (!isChangingToPrac && !isChangingToReal) { isTutorial = true; SetObjectInTutorial(); } else if (isChangingToPrac) { isTutorial = false; instruction_order = 21; SetObjectInPrac(); } else if (isChangingToReal) { isTutorial = false; if (SettingLight_City.LightLevel != 1) { SettingLight_City.LightLevel = 3; } } isPractice = isChangingToPrac; isRealTest = isChangingToReal; isChangingToPrac = false; SetSavingPath(); InstructionAudioSource = gameObject.GetComponents<AudioSource>()[3]; actionsDebugList = new String[] { "Action 0 Finished: Welcome", "Action 1 Finished: Introduction", "Action 2 Finished: Forward Test", "Action 3 Finished: Backward Test1", "Action 4 Finished: Backward Test2", "Action 5 Finished: Backward Test3", "Action 6 Finished: Pavement Walk1", "Action 7 Finished: Pavement Walk2", "Action 8 Finished: Obstacle1", "Action 9 Finished: Pedestrian1", "Action 10 Finished: Obstacle2", "Action 11 Finished: Pedestrian2", "Action 12 Finished: Pedestrian3", "Action 13 Finished: BoxCollider1", "Action 14 Finished: BoxCollider2", "Action 15 Finished: BoxCollider3", "Action 16 Finished: Pavement Walk3", "Action 17 Finished: Remind The Car", "Action 18 Finished: Road Crossing", "Action 19 Finished: SecondLast Check Point", "Action 20 Finished: End Check Point", }; } // Update is called once per frame void Update () { if (Input.GetKeyDown(KeyCode.M)) { isChangingToPrac = true; SceneManager.LoadScene(SceneManager.GetActiveScene().name); } CharacterController controller = GetComponent<CharacterController>(); Quaternion prevRot = GameObject.Find("TrackingSpace2").transform.rotation; transform.rotation = Quaternion.Euler(0f,hmd.rotation.eulerAngles.y,0f); GameObject.Find ("TrackingSpace2").transform.rotation = prevRot; try { if (Input.GetKeyDown(KeyCode.Escape)) { exit_Canvas.SetActive(true); } if (Input.GetKeyDown(KeyCode.F1)) { Finished = true; } if (isRealTest && Finished) { if (isRouteTest) { if (routeCount < 9) { routeCount++; SettingBlockage_City.PosChoice++; if (SettingBlockage_City.PosChoice > 5) SettingBlockage_City.PosChoice -= 5; if (isFirstRoute) isFirstRoute = false; if (routeCount >= 5) SettingLight_City.LightLevel = 1; SceneManager.LoadScene(SceneManager.GetActiveScene().name); } else { StartCoroutine(SelectScene(ProjectSelectScene, 2.0f)); } } else { if (SettingLight_City.LightLevel == 1) { StartCoroutine(SelectScene(ProjectSelectScene, 2.0f)); } else { SettingLight_City.LightLevel = 1; SceneManager.LoadScene(SceneManager.GetActiveScene().name); } } } if (Input.GetKeyUp(KeyCode.Return)) { AutoMove_on = true; } if (Input.GetKeyUp(KeyCode.Backspace)) { AutoMove_on = false; } if (!Finished && controllerButton_Forward_O && (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.KeypadEnter) || Input.GetKeyDown(KeyCode.JoystickButton1) || Mathf.Abs(Input.GetAxis("JoyVertical")) > 0.2f)) { AutoMove_on = true; AutoMoveSpeed = 1f; if (Mathf.Abs(Input.GetAxis("JoyVertical")) > 0.2f && JoyStick_Returned) GetComponents<AudioSource>()[2].Play(); if (Mathf.Abs(Input.GetAxis("JoyVertical")) > 0.2f) JoyStick_Returned = false; else GetComponents<AudioSource>()[2].Play(); } if (!Finished && Input.GetKeyDown(KeyCode.JoystickButton3) && controllerButton_Forward_O) { AutoMove_on = true; AutoMoveSpeed = 2f; GetComponents<AudioSource>()[2].Play(); } if (!Finished && Input.GetKeyDown(KeyCode.JoystickButton0) && controllerButton_Backward_X) { AutoMove_on = true; AutoMoveSpeed = -1f; GetComponents<AudioSource>()[2].Play(); } if (Input.GetKeyUp(KeyCode.Space) || Input.GetKeyUp(KeyCode.KeypadEnter) || Input.GetKeyUp(KeyCode.JoystickButton1) || Input.GetKeyUp(KeyCode.JoystickButton3) || Input.GetKeyUp(KeyCode.JoystickButton0) || (!JoyStick_Returned && Mathf.Abs(Input.GetAxis("JoyVertical")) < 0.2f) || (!controllerButton_Backward_X && !controllerButton_Forward_O)) { AutoMove_on = false; if (!JoyStick_Returned && Mathf.Abs(Input.GetAxis("JoyVertical")) < 0.2f) JoyStick_Returned = true; GetComponents<AudioSource>()[2].loop = false; } // Move automatically forward for certain distance when pressed Keypad 6 if (AutoMove_on == true) { //checks to see if the distance traveled is less than 100 * f if (m_distanceTraveled < 66f) { if (Input.GetAxis("JoyVertical") < -0.2f) AutoMoveSpeed = 0.5f * (1f + (Mathf.Abs(Input.GetAxis("JoyVertical")) - 0.2f) / 0.8f * 3f); else if (Input.GetAxis("JoyVertical") > 0.2f) AutoMoveSpeed = -0.5f * (1f + (Mathf.Abs(Input.GetAxis("JoyVertical")) - 0.2f) / 0.8f * 1f); Vector3 moveDirection = new Vector3((Input.GetAxis("Horizontal")), (-Input.GetAxis("Vertical")), 0); moveDirection = transform.TransformDirection(Vector3.forward); controller.Move(moveDirection * AutoMoveSpeed * Time.deltaTime); GetComponents<AudioSource>()[2].loop = true; m_distanceTraveled = Mathf.Abs((oldPosition - transform.position).x); } else { Timer0812_City.enableTimer = false; if (!File.Exists(SavePath + filename)) using (StreamWriter sw = File.CreateText(SavePath + filename)) { } if (!Finished) using (StreamWriter sw = File.AppendText(SavePath + filename)) { sw.WriteLine(String.Join(", ", new string[] { "Final Result", System.DateTime.Now.ToString("yyyy/MM/dd"), System.DateTime.Now.ToString("HH:mm:ss") })); sw.WriteLine(String.Join(", ", new string[] { "Light Level", "Time Used (s)", "No. of Collision", "Obstacle Setting", "Time Touching Blockage (s)", "Distance Travelled (m)", "Patient Age" })); sw.WriteLine(String.Join(", ", new string[] { SettingLight_City.LightLevel.ToString(), Timer0812_City.startTime.ToString("F2"), HitCollisionValue_City.currentHit.ToString(), SettingBlockage_City.PosChoice.ToString(), HealthCollision_City.totalDamage.ToString("F2"), (Mathf.Abs((transform.position - oldPosition).z) + m_distanceTraveled).ToString("F2"), (Convert.ToInt32(System.DateTime.Now.ToString("yyyy")) - Convert.ToInt32(DropdownYearOption.DOBYear)).ToString(),})); sw.WriteLine(); } isInstructionFinished = false; AutoMove_on = false; m_distanceTraveled = 0f; GetComponents<AudioSource>()[2].loop = false; } } ActionsTrigger(); } catch (Exception e) { UnityEngine.Debug.LogFormat( "Unknown encountered on server. Message:'{0}' when writing an object", e.Message); } } private IEnumerator SelectScene(string sceneName, float loadingTime) { yield return new WaitForSeconds(loadingTime); SettingLight_City.LightLevel = 3; SceneManager.LoadScene(sceneName); } private void SetObjectInTutorial() { SetObjectInPrac(); foreach (GameObject objectActiveInTutorial in ObjectActivatedInTutorial) { objectActiveInTutorial.SetActive(true); } foreach (GameObject objectHideInTutorial in ObjectHidedInTutorial) { objectHideInTutorial.SetActive(false); } GameObject.Find("Blockage 0203 - toilet1").transform.position = new Vector3(-49.65f, 0.68f, 10.96f); GameObject.Find("CardboardBox_0").transform.position = new Vector3(-54.91022f, 0.595f, 9.76f); GameObject.Find("CardboardBox_1").transform.position = new Vector3(-56.72f, 0.595f, 8.81f); GameObject.Find("CardboardBox_2").transform.position = new Vector3(-58.37f, 0.39f, 9.03f); m_Rigidbody.constraints = RigidbodyConstraints.FreezePositionY; } private void SetObjectInPrac() { // Setting light in Practice SettingLight_City.LightLevel = 2; foreach (GameObject objectActiveInPrac in ObjectActivatedInPractice) { objectActiveInPrac.SetActive(true); } foreach (GameObject objectHideInPrac in ObjectHidedInPractice) { objectHideInPrac.SetActive(false); } GameObject.Find("Directional light").GetComponent<SettingBlockage_City>().enabled = false; GameObject.Find("Blockage 0206 - books").transform.position = new Vector3(-57f, 0.262f, 5.5f); GameObject.Find("Blockage 0301 - rusty_tricycle").transform.position = new Vector3(-38.25f, 0.25f, 7f); GameObject.Find("Blockage 0105 - FridgeOld").transform.position = new Vector3(-63f, 0.55f, 10f); } private void SetSavingPath() { SavePath = (SettingLight_City.LightLevel == 3) ? DataManager.dataSavingPath[3] : DataManager.dataSavingPath[4]; if (isTutorial) filename = "City_Navigation" + "_Tutorial_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + "_SaveData.csv"; else if (isRealTest) { filename = "City_Navigation" + "_RealTest_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + "_SaveData.csv"; } else if (isPractice) filename = "City_Navigation" + "_Practice_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + "_SaveData.csv"; } private void SetLanguage() { if (UserInfoLanguage.currentLanguage == "Mandarin") { InstructionAudioClip = ChineseAudios; } } private void ActionsTrigger() { if (isTutorial) { try { if (instruction_order == 0) { Action_Welcome(0, 20f); } if (instruction_order == 1) { Action_Introduction(1); } if (instruction_order == 2) { Action_ForwardTest(2, 15f); } if (instruction_order == 3) { Action_BackwardTest1(3); } if (instruction_order == 4) { //Action_BackwardTest2(4, 15f, 0.2f); Action_BackwardTest2(4, 15f, pedestrainCollisionPosX - 0.9f); } if (instruction_order == 5) { Action_BackwardTest3(5, 15f, lastPlayerPosX + 2f); } if (instruction_order == 6) { Action_PavementWalk1(6); } if (instruction_order == 7) { Action_PavementWalk2(7, 15f, "Obstacle1_Trigger"); } if (instruction_order == 8) { Action_Obstacle1(8); } if (instruction_order == 9) { Action_Pedestrian1(9, 20f); } if (instruction_order == 10) { Action_Obstacle2(10); } if (instruction_order == 11) { Action_Pedestrian2(11, 20f, pedestrainCollisionPosX - 0.5f); } if (instruction_order == 12) { Action_Pedestrian3(12, 15f, lastPlayerPosX + 1.3f); } if (instruction_order == 13) { Action_BoxCollider1(13, 15f); } if (instruction_order == 14) { Action_BoxCollider2(14, 20f, pedestrainCollisionPosX - 0.7f); } if (instruction_order == 15) { Action_BoxCollider3(15, 15f, lastPlayerPosX + 1.5f); } if (instruction_order == 16) { Action_PavementWalk3(16, 30f, "CarReminder_Trigger"); } if (instruction_order == 17) { Action_RemindTheCar(17); } if (instruction_order == 18) { Action_RoadCrossing(18, 100f, "LastSecond_Trigger"); } if (instruction_order == 19) { Action_SecondLastCheckPoint(19, 20f, oldPosition.x + 66f); } if (instruction_order == 20) { Action_EndCheckPoint(20, 15f); } } catch (Exception e) { UnityEngine.Debug.Log(e.Message); } } else if (isPractice) { if (!Finished) { if (!isInstructionFinished && instruction_order == 21) PracticeAudio1(21, 15f); } else { PracticeAudio2(22, 15f); } } else if (isRealTest) if (!isInstructionFinished && !Finished) RealTestAudio1(23); } private void Action_Welcome(int audio_order, float audioActivatedDuration) { instructionTimeElapsed += Time.deltaTime; if (instructionTimeElapsed <= audioActivatedDuration) { if (!isInstructionAudioActivated && !InstructionAudioSource.isPlaying) { InstructionAudioPlay(true, audio_order); ControllerButtonAcess(false, false); } else if (isInstructionAudioActivated && InstructionAudioSource.isPlaying) { ControllerButtonAcess(false, false); } else if (isInstructionAudioActivated && !InstructionAudioSource.isPlaying) { ControlerModel.SetActive(true); showForwardButton = true; ControllerButtonAcess(false, false); if (Input.GetKeyDown(KeyCode.JoystickButton1) || Input.GetKeyDown(KeyCode.KeypadEnter)) { isInstructionFinished = true; } } } else { ControlerModel.SetActive(true); showForwardButton = true; //ControllerButtonAcess(true, false); ControllerButtonAcess(false, false); if (Input.GetKeyDown(KeyCode.JoystickButton1) || Input.GetKeyDown(KeyCode.KeypadEnter)) { isInstructionFinished = true; } if (((int)instructionTimeElapsed) % ((int)audioActivatedDuration) == 0 && !InstructionAudioSource.isPlaying) { InstructionAudioPlay(true, audio_order); Flashing_City.isFlashing = false; } } if (isInstructionFinished) { DebugForActionOrder(audio_order); InstructionParametersInit(); InstructionAudioPlay(false, audio_order); ControlerModel.SetActive(false); showForwardButton = false; Flashing_City.isFlashing = false; } } private void Action_Introduction(int audio_order) { if (!isInstructionAudioActivated && !InstructionAudioSource.isPlaying) { InstructionAudioPlay(true, audio_order); isInstructionAudioActivated = true; } else if (isInstructionAudioActivated && InstructionAudioSource.isPlaying) { ControllerButtonAcess(false, false); } else if (isInstructionAudioActivated && !InstructionAudioSource.isPlaying) { isInstructionFinished = true; } if (isInstructionFinished) { DebugForActionOrder(audio_order); InstructionParametersInit(); InstructionAudioPlay(false, audio_order); } } private void Action_ForwardTest(int audio_order, float audioActivatedDuration) { instructionTimeElapsed += Time.deltaTime; if (instructionTimeElapsed <= audioActivatedDuration) { if (!isInstructionAudioActivated && !InstructionAudioSource.isPlaying) { InstructionAudioPlay(true, audio_order); ControllerButtonAcess(false, false); } else if (isInstructionAudioActivated && InstructionAudioSource.isPlaying) { ControllerButtonAcess(false, false); } else if (isInstructionAudioActivated && !InstructionAudioSource.isPlaying) { ControlerModel.SetActive(true); showForwardButton = true; ControllerButtonAcess(true, false); if (onCollisionObjectName == "StreetTable_Trigger") { pedestrainCollisionPosX = GameObject.Find("XRRig").transform.position.x; isInstructionFinished = true; } } } else { ControlerModel.SetActive(true); showForwardButton = true; ControllerButtonAcess(true, false); if (onCollisionObjectName == "StreetTable_Trigger") { pedestrainCollisionPosX = GameObject.Find("XRRig").transform.position.x; isInstructionFinished = true; } if (((int)instructionTimeElapsed) % ((int)audioActivatedDuration) == 0 && !InstructionAudioSource.isPlaying) { InstructionAudioPlay(true, audio_order); Flashing_City.isFlashing = false; } } if (isInstructionFinished) { GameObject.Find(onCollisionObjectName).SetActive(false); DebugForActionOrder(audio_order); InstructionParametersInit(); InstructionAudioPlay(false, audio_order); GameObject.Find("Tutorial_Blockage_StreetTable").transform.GetChild(2).gameObject.SetActive(false); ControlerModel.SetActive(false); showForwardButton = false; Flashing_City.isFlashing = false; } } private void Action_BackwardTest1(int audio_order) { Action_Introduction(audio_order); } private void Action_BackwardTest2(int audio_order, float audioActivatedDuration, float backPosition) { instructionTimeElapsed += Time.deltaTime; if (instructionTimeElapsed <= audioActivatedDuration) { if (!isInstructionAudioActivated && !InstructionAudioSource.isPlaying) { InstructionAudioPlay(true, audio_order); ControllerButtonAcess(false, false); } else if (isInstructionAudioActivated && InstructionAudioSource.isPlaying) { ControllerButtonAcess(false, false); } else if (isInstructionAudioActivated && !InstructionAudioSource.isPlaying) { ControlerModel.SetActive(true); showBackButton = true; ControllerButtonAcess(false, true); isInstructionFinished = BackwardDistanceSatisfied(backPosition); } } else { ControlerModel.SetActive(true); showBackButton = true; ControllerButtonAcess(false, true); isInstructionFinished = BackwardDistanceSatisfied(backPosition); if (((int)instructionTimeElapsed) % ((int)audioActivatedDuration) == 0 && !InstructionAudioSource.isPlaying) { InstructionAudioPlay(true, audio_order); Flashing_City.isFlashing = false; } } if (isInstructionFinished) { DebugForActionOrder(audio_order); InstructionParametersInit(); InstructionAudioPlay(false, audio_order); ControlerModel.SetActive(false); showBackButton = false; Flashing_City.isFlashing = false; } } private void Action_BackwardTest3(int audio_order, float audioActivatedDuration, float forwardPosition) { instructionTimeElapsed += Time.deltaTime; if (instructionTimeElapsed <= audioActivatedDuration) { if (!isInstructionAudioActivated && !InstructionAudioSource.isPlaying) { InstructionAudioPlay(true, audio_order); ControllerButtonAcess(false, false); } else if (isInstructionAudioActivated && InstructionAudioSource.isPlaying) { ControllerButtonAcess(false, false); } else if (isInstructionAudioActivated && !InstructionAudioSource.isPlaying) { ControllerButtonAcess(true, true); isInstructionFinished = ForwardDistanceSatisfied(forwardPosition); } } else { ControllerButtonAcess(true, true); isInstructionFinished = ForwardDistanceSatisfied(forwardPosition); if (((int)instructionTimeElapsed) % ((int)audioActivatedDuration) == 0 && !InstructionAudioSource.isPlaying) { InstructionAudioPlay(true, audio_order); } } if (isInstructionFinished) { DebugForActionOrder(audio_order); InstructionParametersInit(); InstructionAudioPlay(false, audio_order); } } private void Action_PavementWalk1(int audio_order) { Action_Introduction(audio_order); } private void Action_PavementWalk2(int audio_order, float audioActivatedDuration, string collisionObject) { instructionTimeElapsed += Time.deltaTime; if (instructionTimeElapsed <= audioActivatedDuration) { if (!isInstructionAudioActivated && !InstructionAudioSource.isPlaying) { InstructionAudioPlay(true, audio_order); ControllerButtonAcess(false, false); } else if (isInstructionAudioActivated && InstructionAudioSource.isPlaying) { ControllerButtonAcess(false, false); } else if (isInstructionAudioActivated && !InstructionAudioSource.isPlaying) { ControllerButtonAcess(true, true); if (onCollisionObjectName == collisionObject) { isInstructionFinished = true; } } } else { ControllerButtonAcess(true, true); if (onCollisionObjectName == collisionObject) { isInstructionFinished = true; } if (((int)instructionTimeElapsed) % ((int)audioActivatedDuration) == 0 && !InstructionAudioSource.isPlaying) { InstructionAudioPlay(true, audio_order); } } if (isInstructionFinished) { GameObject.Find(onCollisionObjectName).SetActive(false); DebugForActionOrder(audio_order); InstructionParametersInit(); InstructionAudioPlay(false, audio_order); } } private void Action_Obstacle1(int audio_order) { Action_Introduction(audio_order); } private void Action_Pedestrian1(int audio_order, float audioActivatedDuration) { instructionTimeElapsed += Time.deltaTime; if (instructionTimeElapsed <= audioActivatedDuration) { if (!isInstructionAudioActivated && !InstructionAudioSource.isPlaying) { InstructionAudioPlay(true, audio_order); ControllerButtonAcess(false, false); } else if (isInstructionAudioActivated && InstructionAudioSource.isPlaying) { ControllerButtonAcess(false, false); } else if (isInstructionAudioActivated && !InstructionAudioSource.isPlaying) { ControllerButtonAcess(true, true); if (onCollisionObjectName == "Tutorial_Blockage_Pedestrain") { pedestrainCollisionPosX = GameObject.Find("XRRig").transform.position.x; isInstructionFinished = true; } } } else { ControllerButtonAcess(true, true); if (onCollisionObjectName == "Tutorial_Blockage_Pedestrain") { pedestrainCollisionPosX = GameObject.Find("XRRig").transform.position.x; isInstructionFinished = true; } if (((int)instructionTimeElapsed) % ((int)audioActivatedDuration) == 0 && !InstructionAudioSource.isPlaying) { InstructionAudioPlay(true, audio_order); } } if (isInstructionFinished) { DebugForActionOrder(audio_order); InstructionParametersInit(); InstructionAudioPlay(false, audio_order); GameObject.Find("Tutorial_Blockage_Pedestrain").GetComponent<PedestrianWalkingMCS002>().enabled = false; ArrowPedestrain.SetActive(false); } else { ArrowPedestrain.SetActive(true); } } private void Action_Obstacle2(int audio_order) { Action_Introduction(audio_order); } private void Action_Pedestrian2(int audio_order, float audioActivatedDuration, float backPosition) { instructionTimeElapsed += Time.deltaTime; if (instructionTimeElapsed <= audioActivatedDuration) { if (!isInstructionAudioActivated && !InstructionAudioSource.isPlaying) { InstructionAudioPlay(true, audio_order); ControllerButtonAcess(false, false); } else if (isInstructionAudioActivated && InstructionAudioSource.isPlaying) { ControllerButtonAcess(false, false); } else if (isInstructionAudioActivated && !InstructionAudioSource.isPlaying) { ControllerButtonAcess(false, true); isInstructionFinished = BackwardDistanceSatisfied(backPosition); } } else { ControllerButtonAcess(false, true); isInstructionFinished = BackwardDistanceSatisfied(backPosition); if (((int)instructionTimeElapsed) % ((int)audioActivatedDuration) == 0 && !InstructionAudioSource.isPlaying) { InstructionAudioPlay(true, audio_order); } } if (isInstructionFinished) { DebugForActionOrder(audio_order); InstructionParametersInit(); InstructionAudioPlay(false, audio_order); } } private void Action_Pedestrian3(int audio_order, float audioActivatedDuration, float forwardPosition) { instructionTimeElapsed += Time.deltaTime; if (instructionTimeElapsed <= audioActivatedDuration) { if (!isInstructionAudioActivated && !InstructionAudioSource.isPlaying) { InstructionAudioPlay(true, audio_order); ControllerButtonAcess(false, false); } else if (isInstructionAudioActivated && InstructionAudioSource.isPlaying) { ControllerButtonAcess(false, false); } else if (isInstructionAudioActivated && !InstructionAudioSource.isPlaying) { ControllerButtonAcess(true, true); isInstructionFinished = ForwardDistanceSatisfied(forwardPosition); } } else { ControllerButtonAcess(true, true); isInstructionFinished = ForwardDistanceSatisfied(forwardPosition); if (((int)instructionTimeElapsed) % ((int) audioActivatedDuration) == 0 && !InstructionAudioSource.isPlaying) { InstructionAudioPlay(true, audio_order); } } if (isInstructionFinished) { if (audio_order ==12) { ArrowBox.SetActive(true); } DebugForActionOrder(audio_order); InstructionParametersInit(); InstructionAudioPlay(false, audio_order); } } private void Action_BoxCollider1(int audio_order, float audioActivatedDuration) { instructionTimeElapsed += Time.deltaTime; if (instructionTimeElapsed <= audioActivatedDuration) { if (!isInstructionAudioActivated && !InstructionAudioSource.isPlaying) { InstructionAudioPlay(true, audio_order); ControllerButtonAcess(false, false); } else if (isInstructionAudioActivated && InstructionAudioSource.isPlaying) { ControllerButtonAcess(false, false); } else if (isInstructionAudioActivated && !InstructionAudioSource.isPlaying) { ControllerButtonAcess(true, true); if (onCollisionObjectName == "Tutorial_Blockage_BookBoxes") { pedestrainCollisionPosX = GameObject.Find("XRRig").transform.position.x; isInstructionFinished = true; } } } else { ControllerButtonAcess(true, true); if (onCollisionObjectName == "Tutorial_Blockage_BookBoxes") { pedestrainCollisionPosX = GameObject.Find("XRRig").transform.position.x; isInstructionFinished = true; } if (((int)instructionTimeElapsed) % ((int)audioActivatedDuration) == 0 && !InstructionAudioSource.isPlaying) { InstructionAudioPlay(true, audio_order); } } if (isInstructionFinished) { GameObject.Destroy(ArrowBox); DebugForActionOrder(audio_order); InstructionParametersInit(); InstructionAudioPlay(false, audio_order); } } private void Action_BoxCollider2(int audio_order, float audioActivatedDuration, float backPosition) { Action_Pedestrian2(audio_order, audioActivatedDuration, backPosition); } private void Action_BoxCollider3(int audio_order, float audioActivatedDuration, float forwardPosition) { Action_Pedestrian3(audio_order, audioActivatedDuration, forwardPosition); } private void Action_PavementWalk3(int audio_order, float audioActivatedDuration, string collisionObject) { Action_PavementWalk2(audio_order, audioActivatedDuration, collisionObject); } private void Action_RemindTheCar(int audio_order) { Action_Introduction(audio_order); } private void Action_RoadCrossing(int audio_order, float audioActivatedDuration, string collisionObject) { Action_PavementWalk2(audio_order, audioActivatedDuration, collisionObject); } private void Action_SecondLastCheckPoint(int audio_order, float audioActivatedDuration, float forwardPosition) { Action_Pedestrian3(audio_order, audioActivatedDuration, forwardPosition); } private void Action_EndCheckPoint(int audio_order, float audioActivatedDuration) { if (Finished) { instructionTimeElapsed += Time.deltaTime; if (instructionTimeElapsed <= audioActivatedDuration) { if (!isInstructionAudioActivated && !InstructionAudioSource.isPlaying) { InstructionAudioPlay(true, audio_order); ControllerButtonAcess(false, false); } else if (isInstructionAudioActivated && InstructionAudioSource.isPlaying) { ControllerButtonAcess(false, false); } else if (isInstructionAudioActivated && !InstructionAudioSource.isPlaying) { ControllerButtonAcess(false, false); if (Input.GetKeyDown(KeyCode.JoystickButton1) || Input.GetKeyDown(KeyCode.KeypadEnter)) { isInstructionFinished = true; } } } else { ControllerButtonAcess(true, false); if (Input.GetKeyDown(KeyCode.JoystickButton1) || Input.GetKeyDown(KeyCode.KeypadEnter)) { isInstructionFinished = true; } if (((int)instructionTimeElapsed) % ((int)audioActivatedDuration) == 0 && !InstructionAudioSource.isPlaying) { InstructionAudioPlay(true, audio_order); } } if (isInstructionFinished) { DebugForActionOrder(audio_order); InstructionParametersInit(); InstructionAudioPlay(false, audio_order); isChangingToPrac = true; SceneManager.LoadScene(SceneManager.GetActiveScene().name); } } } private void InstructionAudioPlay(bool allowPlay, int instruction_order) { if (allowPlay) { InstructionAudioSource.clip = InstructionAudioClip[instruction_order]; InstructionAudioSource.Play(); isInstructionAudioActivated = true; } if (!allowPlay) { InstructionAudioSource.clip = InstructionAudioClip[instruction_order]; InstructionAudioSource.Stop(); } } private void ControllerButtonAcess(bool button_O, bool button_X) { controllerButton_Backward_X = button_X; controllerButton_Forward_O = button_O; } private void OnControllerColliderHit(ControllerColliderHit hit) { if (hit.gameObject.tag != "Blockage" && hit.gameObject.tag != "NPC" && hit.gameObject.tag != "Trigger" || hit.gameObject.name.Contains("Box")) { if (hit.gameObject.transform.parent.gameObject.tag == "Blockage" || hit.gameObject.transform.parent.gameObject.tag == "NPC") { onCollisionObjectName = hit.gameObject.transform.parent.gameObject.name; } } else { onCollisionObjectName = hit.gameObject.name; } } private bool KeyHoldTimeSatisfied(float requestKeyPeriod, KeyCode key) { if (Input.GetKey(key)) { keyHoldTimeElapsed += Time.deltaTime; } if (Input.GetKeyUp(key)) { if (keyHoldTimeElapsed >= requestKeyPeriod) { isKeyHoldTimeSatisfied = true; keyHoldTimeElapsed = 0f; } else { keyHoldTimeElapsed = 0f; } } return isKeyHoldTimeSatisfied; } private bool BackwardDistanceSatisfied(float backPosition) { if (GameObject.Find("XRRig").transform.position.x <= backPosition) { isBackwardDistanceSatisfied = true; lastPlayerPosX = GameObject.Find("XRRig").transform.position.x; } return isBackwardDistanceSatisfied; } private bool ForwardDistanceSatisfied(float forwardPosition) { if (GameObject.Find("XRRig").transform.position.x >= forwardPosition) { isForwardDistanceSatisfied = true; } return isForwardDistanceSatisfied; } private void InstructionParametersInit(bool audioActivated = false, bool finished = false, bool keyHold = false, float timer = 0f) { if (instruction_order != 20) { instruction_order++; } else { instruction_order = 0; } isInstructionAudioActivated = audioActivated; isInstructionFinished = finished; isKeyHoldTimeSatisfied = keyHold; instructionTimeElapsed = timer; onCollisionObjectName = ""; isBackwardDistanceSatisfied = false; isForwardDistanceSatisfied = false; } private void DebugForActionOrder(int action_order) { UnityEngine.Debug.Log(actionsDebugList[action_order]); } private void PracticeAudio1(int audio_order, float audioActivatedDuration) { instructionTimeElapsed += Time.deltaTime; if (instructionTimeElapsed <= audioActivatedDuration) { if (!isInstructionAudioActivated && !InstructionAudioSource.isPlaying) { InstructionAudioPlay(true, audio_order); ControllerButtonAcess(false, false); } else if (isInstructionAudioActivated && InstructionAudioSource.isPlaying) { ControllerButtonAcess(false, false); } else if (isInstructionAudioActivated && !InstructionAudioSource.isPlaying) { ControllerButtonAcess(true, true); isInstructionFinished = true; } } else { ControllerButtonAcess(true, true); isInstructionFinished = true; if (((int)instructionTimeElapsed) % ((int)audioActivatedDuration) == 0 && !InstructionAudioSource.isPlaying) { InstructionAudioPlay(true, audio_order); } } if (isInstructionFinished) { InstructionAudioPlay(false, audio_order); instructionTimeElapsed = 0f; isInstructionFinished = false; isInstructionAudioActivated = false; instruction_order++; } } private void PracticeAudio2(int audio_order, float audioActivatedDuration) { instructionTimeElapsed += Time.deltaTime; if (instructionTimeElapsed <= audioActivatedDuration) { if (!isInstructionAudioActivated && !InstructionAudioSource.isPlaying) { InstructionAudioPlay(true, audio_order); ControllerButtonAcess(false, false); } else if (isInstructionAudioActivated && InstructionAudioSource.isPlaying) { ControllerButtonAcess(false, false); } else if (isInstructionAudioActivated && !InstructionAudioSource.isPlaying) { ControllerButtonAcess(false, false); if (Input.GetKeyDown(KeyCode.JoystickButton1) || Input.GetKeyDown(KeyCode.KeypadEnter)) { isInstructionFinished = true; } } } else { ControllerButtonAcess(true, true); if (Input.GetKeyDown(KeyCode.JoystickButton1) || Input.GetKeyDown(KeyCode.KeypadEnter)) { isInstructionFinished = true; } if (((int)instructionTimeElapsed) % ((int)audioActivatedDuration) == 0 && !InstructionAudioSource.isPlaying) { InstructionAudioPlay(true, audio_order); } } if (isInstructionFinished) { InstructionAudioPlay(false, audio_order); isChangingToReal = true; SceneManager.LoadScene(SceneManager.GetActiveScene().name); } } private void RealTestAudio1(int audio_order) { InstructionAudioPlay(true, audio_order); isInstructionFinished = true; } }
27.932371
226
0.68862
[ "MIT" ]
RealBrandonChen/VisualDisabilitySim
AutoForward_City.cs
36,761
C#
namespace NumberChecker { using System; public class StartUp { public static void Main() { try { int m = Int32.Parse(Console.ReadLine()); Console.WriteLine("It is a number."); } catch (FormatException e) { Console.WriteLine("Invalid input!", e); } } } }
19.5
56
0.41958
[ "MIT" ]
VeselinBPavlov/programming-fundamentals
03. C# Conditional Statements and Loops - Lab/NumberChecker/StartUp.cs
431
C#
using Aino.Agents.Core; using Aino.Agents.Core.Config; using NUnit.Framework; namespace AinoTests { [TestFixture] class TransactionDataBufferTest { private AgentConfig config; [OneTimeSetUp] public void SetUp() { config = new AgentConfig(); config.GetApplications().AddEntry("app1", "Application 1"); config.GetApplications().AddEntry("app2", "Application 2"); } [Test] public void TestBufferReturnsSingleTransactionWhenSizeThresholdIsZero() { TransactionDataBuffer buffer = new TransactionDataBuffer(0); AssertSingleTransactionsAreReturned(buffer); } [Test] public void TestBufferReturnsSingleTransactionWhenSizeThresholdIsOne() { TransactionDataBuffer buffer = new TransactionDataBuffer(1); AssertSingleTransactionsAreReturned(buffer); } [Test] public void TestBufferReturnsAllTransactionsWhenSizeThresholdGreaterThanOne() { TransactionDataBuffer buffer = new TransactionDataBuffer(2); buffer.AddTransaction(TransactionWrapper()); buffer.AddTransaction(TransactionWrapper()); Assert.NotNull(buffer.GetDataToSend(), "Should have received data to send"); Assert.AreEqual(buffer.GetSize(), 0, "No more transactions should exist"); } private void AssertSingleTransactionsAreReturned(TransactionDataBuffer buffer) { buffer.AddTransaction(TransactionWrapper()); buffer.AddTransaction(TransactionWrapper()); Assert.NotNull(buffer.GetDataToSend(), "Should have received data to send"); Assert.AreEqual(buffer.GetSize(), 1, "Should have returned one transaction"); Assert.NotNull(buffer.GetDataToSend(), "Should have received data to send"); Assert.AreEqual(buffer.GetSize(), 0, "No more transactions should exist"); } private TransactionSerializable TransactionWrapper() { return TransactionSerializable.From(SimpleTransation()); } private Transaction SimpleTransation() { Transaction transaction = new Transaction(config); transaction.SetFromKey("app1"); transaction.SetToKey("app2"); transaction.SetStatus("success"); return transaction; } } }
34.732394
89
0.64193
[ "Apache-2.0" ]
Aino-io/aino-io-agent-net
AinoTests/TransactionDataBufferTest.cs
2,468
C#
namespace DragonsUwU.Database.Models { class DragonTag { public int DragonId { get; set; } public Dragon Dragon { get; set; } public int TagId { get; set; } public Tag Tag { get; set; } } }
19.583333
42
0.561702
[ "MIT" ]
ScuroGuardiano/DragonUwU
src/DragonsUwU.Database/Models/DragonTag.cs
235
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using System.Diagnostics; using ThridWolrdShooterGame.Managers; namespace ThridWolrdShooterGame.Entites.Enemies { public class Worm:Entity { private Enemy[] components = new Enemy[4]; public Worm(Vector2 Position) { this.Position = Position; components[0] = new WormHead(this.Position); for (int i = 0; i < components.Count(); i++) { if (i == 0) { components[i] = new WormHead(this.Position); EntityManager.Add(components[i]); continue; } components[i] = new WormTail(this.Position); EntityManager.Add(components[i]); } } private int expiredCounter; public override void Update(GameTime gametime) { expiredCounter = 0; for (int i = 1; i < components.Count(); i++) { if (i == 1) { components[i].Position = (components[0] as WormHead).LastPosition; if ((components[0] as WormHead).IsExpired) { (components[i] as WormTail).Kill(); expiredCounter++; } continue; } components[i].Position = (components[i - 1] as WormTail).LastPosition ; if ((components[i - 1] as WormTail).IsExpired) { (components[i] as WormTail).Kill(); expiredCounter++; } } if (expiredCounter >= components.Count() - 1) this.IsExpired = true; Debug.WriteLine("Counter " +expiredCounter); } } }
30.515152
88
0.463754
[ "MIT" ]
AlanSosa/Infinite-pew-pew-PC-Version
Infinite pew pew 60fps/Infinite pew pew 60fps/Game/Entites/Enemies/Worm.cs
2,014
C#
#region [ License information ] /* ************************************************************ * * @author Couchbase <info@couchbase.com> * @copyright 2021 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ************************************************************/ #endregion using System; using Akka.Configuration; namespace Akka.Persistence.Couchbase { public abstract class CouchbaseSettings { public string ConnectionString { get; private set; } public string Username { get; private set; } public string Password { get; private set; } protected CouchbaseSettings(Config config) { ConnectionString = config.GetString("connection-string"); Username = config.GetString("username"); Password = config.GetString("password"); } } public class CouchbaseJournalSettings : CouchbaseSettings { public string JournalBucket { get; private set; } public string MetadataBucket { get; private set; } public CouchbaseJournalSettings(Config config) : base(config) { if (config == null) throw new ArgumentNullException(nameof(config), "Couchbase journal settings HOCON section not found"); JournalBucket = config.GetString("journal-bucket"); MetadataBucket = config.GetString("metadata-bucket"); } } public class CouchbaseSnapshotSettings : CouchbaseSettings { public string SnapshotBucket { get; private set; } public CouchbaseSnapshotSettings(Config config) : base(config) { if (config == null) throw new ArgumentNullException(nameof(config), "Couchbase snapshot settings HOCON section not found"); SnapshotBucket = config.GetString("snapshot-bucket"); } } }
33.297297
78
0.612419
[ "Apache-2.0" ]
endercode99/Akka.Persistence.Couchbase
src/Akka.Persistence.Couchbase/CouchbaseSettings.cs
2,466
C#
/* http://www.cgsoso.com/forum-211-1.html CG搜搜 Unity3d 每日Unity3d插件免费更新 更有VIP资源! CGSOSO 主打游戏开发,影视设计等CG资源素材。 插件如若商用,请务必官网购买! daily assets update for try. U should buy the asset from home store if u use it in your project! */ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using System; namespace Org.BouncyCastle.Security.Certificates { #if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || NETFX_CORE) [Serializable] #endif public class CertificateNotYetValidException : CertificateException { public CertificateNotYetValidException() : base() { } public CertificateNotYetValidException(string message) : base(message) { } public CertificateNotYetValidException(string message, Exception exception) : base(message, exception) { } } } #endif
23.666667
108
0.765685
[ "MIT" ]
zhoumingliang/test-git-subtree
Assets/RotateMe/Scripts/Best HTTP (Pro)/BestHTTP/SecureProtocol/security/cert/CertificateNotYetValidException.cs
875
C#
// Copyright (C) 2003-2010 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Alex Yakunin // Created: 2009.03.23 using System; using System.Collections.Generic; using System.Text; using Xtensive.Collections; using Xtensive.Core; using Xtensive.Reflection; using Xtensive.Modelling.Comparison; namespace Xtensive.Modelling.Actions { /// <summary> /// Abstract base class for any node action. /// </summary> [Serializable] public abstract class NodeAction : LockableBase, INodeAction { private string path; private Difference difference; /// <inheritdoc/> public string Path { get { return path; } set { this.EnsureNotLocked(); path = value; } } /// <inheritdoc/> public Difference Difference { get { return difference; } set { this.EnsureNotLocked(); difference = value; } } #region Execute method /// <inheritdoc/> public virtual void Execute(IModel model) { ArgumentValidator.EnsureArgumentNotNull(model, "model"); var item = model.Resolve(path, true); ActionHandler.Current.Execute(this); PerformExecute(model, item); } /// <summary> /// Actually executed <see cref="Execute"/> method call. /// </summary> /// <param name="model">The model.</param> /// <param name="item"><see cref="Path"/> resolution result.</param> protected abstract void PerformExecute(IModel model, IPathNode item); #endregion #region Protected \ internal methods /// <summary> /// Escapes the name in path. /// </summary> /// <param name="name">The name to escape.</param> /// <returns>Escaped name.</returns> protected static string EscapeName(string name) { return new[] {name}.RevertibleJoin(Node.PathEscape, Node.PathDelimiter); } #endregion #region ToString method /// <inheritdoc/> public override string ToString() { var sb = new StringBuilder(); if (this is GroupingNodeAction) sb.Append("["); sb.Append(GetActionName()); var parameters = new List<Pair<string>>(); GetParameters(parameters); foreach (var kvp in parameters) sb.AppendFormat(", {0}={1}", kvp.First, kvp.Second); if (this is GroupingNodeAction) sb.Append("]"); var nestedActions = GetNestedActions(); foreach (var action in nestedActions) sb.AppendLine().Append(action.ToString().Indent(2)); return sb.ToString(); } /// <summary> /// Gets the name of the action for <see cref="ToString"/> formatting. /// </summary> /// <returns>The name of the action.</returns> protected virtual string GetActionName() { string sn = GetType().GetShortName(); return sn.TryCutSuffix("Action"); } /// <summary> /// Gets the parameters for <see cref="ToString"/> formatting. /// </summary> /// <returns>The sequence of parameters.</returns> protected virtual void GetParameters(List<Pair<string>> parameters) { if (path!=null) parameters.Add(new Pair<string>("Path", path)); } /// <summary> /// Gets the sequence of nested actions for <see cref="ToString"/> formatting, if any. /// </summary> /// <returns>The sequence of nested actions.</returns> protected virtual IEnumerable<NodeAction> GetNestedActions() { return EnumerableUtils<NodeAction>.Empty; } #endregion // Constructors /// <summary> /// Initializes new instance of this type. /// </summary> protected NodeAction() { } } }
26
90
0.626219
[ "MIT" ]
NekrasovSt/dataobjects-net
Orm/Xtensive.Orm/Modelling/Actions/NodeAction.cs
3,692
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. #if FEATURE_COMPILE using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using Xunit; namespace System.Linq.Expressions.Tests { public static class StackSpillerTests { [Fact] public static void Spill_Binary() { Test((l, r) => Expression.Add(l, r), Expression.Constant(1), Expression.Constant(2)); } [Fact] public static void Spill_Binary_IndexAssign() { var item = typeof(Dictionary<int, int>).GetProperty("Item"); Test((d, i, v) => { var index = Expression.Property(d, item, i); return Expression.Block( Expression.Assign(index, v), index ); }, Expression.Constant(new Dictionary<int, int>()), Expression.Constant(0), Expression.Constant(1)); } [Fact] public static void Spill_Binary_MemberAssign() { var baz = typeof(Bar).GetProperty(nameof(Bar.Baz)); Test((l, r) => { var prop = Expression.Property(l, baz); return Expression.Block( Expression.Assign(prop, r), prop ); }, Expression.Constant(new Bar()), Expression.Constant(42)); } [Fact] public static void Spill_TryFinally() { Test(a => Expression.TryFinally(a, Expression.Empty()), Expression.Constant(1)); } [Fact] public static void Spill_TryCatch() { foreach (var div in new[] { 1, 0 }) { Test((n, d, a) => Expression.TryCatch(Expression.Divide(n, d), Expression.Catch(typeof(DivideByZeroException), a)), Expression.Constant(1), Expression.Constant(div), Expression.Constant(42)); } } [Fact] public static void Spill_Loop() { Test((a, b) => { var @break = Expression.Label(typeof(int)); return Expression.Add(a, Expression.Loop(Expression.Break(@break, b), @break)); }, Expression.Constant(1), Expression.Constant(2)); } [Fact] public static void Spill_Member() { Test(s => Expression.Property(s, nameof(string.Length)), Expression.Constant("bar")); } [Fact] public static void Spill_TypeBinary() { Test(s => Expression.TypeIs(s, typeof(string)), Expression.Constant("bar", typeof(object))); Test(s => Expression.TypeEqual(s, typeof(string)), Expression.Constant("bar", typeof(object))); } [Fact] public static void Spill_Binary_Logical() { Test((l, r) => Expression.AndAlso(l, r), Expression.Constant(false), Expression.Constant(false)); Test((l, r) => Expression.AndAlso(l, r), Expression.Constant(false), Expression.Constant(true)); Test((l, r) => Expression.AndAlso(l, r), Expression.Constant(true), Expression.Constant(false)); Test((l, r) => Expression.AndAlso(l, r), Expression.Constant(true), Expression.Constant(true)); } [Fact] public static void Spill_Conditional() { Test((t, l, r) => Expression.Condition(t, l, r), Expression.Constant(false), Expression.Constant(1), Expression.Constant(2)); Test((t, l, r) => Expression.Condition(t, l, r), Expression.Constant(true), Expression.Constant(1), Expression.Constant(2)); } [Fact] public static void Spill_Index() { var item = typeof(Dictionary<int, int>).GetProperty("Item"); Test((d, i) => Expression.MakeIndex(d, item, new[] { i }), Expression.Constant(new Dictionary<int, int> { { 1, 2 } }), Expression.Constant(1)); } [Fact] public static void Spill_Call_Static() { var max = typeof(Math).GetMethod(nameof(Math.Max), new[] { typeof(int), typeof(int) }); Test((x, y) => Expression.Call(max, x, y), Expression.Constant(1), Expression.Constant(2)); } [Fact] public static void Spill_Call_Instance() { var substring = typeof(string).GetMethod(nameof(string.Substring), new[] { typeof(int), typeof(int) }); Test((s, i, j) => Expression.Call(s, substring, i, j), Expression.Constant("foobar"), Expression.Constant(1), Expression.Constant(2)); } [Fact] public static void Spill_Invocation() { Test((d, a, b) => Expression.Invoke(d, a, b), Expression.Constant(new Func<int, int, int>((x, y) => x + y)), Expression.Constant(1), Expression.Constant(2)); } [Fact] public static void Spill_Invocation_Inline() { var x = Expression.Parameter(typeof(int)); var y = Expression.Parameter(typeof(int)); Test((a, b) => Expression.Invoke(Expression.Lambda(Expression.Subtract(x, y), x, y), a, b), Expression.Constant(1), Expression.Constant(2)); } [Fact] public static void Spill_New() { var ctor = typeof(TimeSpan).GetConstructor(new[] { typeof(int), typeof(int), typeof(int) }); Test((h, m, s) => Expression.New(ctor, h, m, s), Expression.Constant(1), Expression.Constant(2), Expression.Constant(3)); } [Fact] public static void Spill_NewArrayInit() { Test((a, b, c) => { var p = Expression.Parameter(typeof(int[])); return Expression.Block( new[] { p }, Expression.Assign( p, Expression.NewArrayInit(typeof(int), a, b, c) ), Expression.Multiply( Expression.Add( Expression.ArrayIndex(p, Expression.Constant(0)), Expression.ArrayIndex(p, Expression.Constant(1)) ), Expression.ArrayIndex(p, Expression.Constant(2)) ) ); }, Expression.Constant(2), Expression.Constant(3), Expression.Constant(5)); } [Fact] public static void Spill_NewArrayBounds() { var getUpperBound = typeof(Array).GetMethod(nameof(Array.GetUpperBound)); Test((a, b, c) => { var p = Expression.Parameter(typeof(int[,,])); return Expression.Block( new[] { p }, Expression.Assign( p, Expression.NewArrayBounds(typeof(int), a, b, c) ), Expression.Multiply( Expression.Add( Expression.Call(p, getUpperBound, Expression.Constant(0)), Expression.Call(p, getUpperBound, Expression.Constant(1)) ), Expression.Call(p, getUpperBound, Expression.Constant(2)) ) ); }, Expression.Constant(2), Expression.Constant(3), Expression.Constant(5)); } [Fact] public static void Spill_ListInit() { var item = typeof(List<int>).GetProperty("Item"); Test((a, b, c) => { var p = Expression.Parameter(typeof(List<int>)); return Expression.Block( new[] { p }, Expression.Assign( p, Expression.ListInit(Expression.New(typeof(List<int>)), a, b, c) ), Expression.Multiply( Expression.Add( Expression.MakeIndex(p, item, new[] { Expression.Constant(0) }), Expression.MakeIndex(p, item, new[] { Expression.Constant(1) }) ), Expression.MakeIndex(p, item, new[] { Expression.Constant(2) }) ) ); }, Expression.Constant(2), Expression.Constant(3), Expression.Constant(5)); } [Fact] public static void Spill_MemberInit_Bind() { var baz = typeof(Bar).GetProperty(nameof(Bar.Baz)); var foo = typeof(Bar).GetProperty(nameof(Bar.Foo)); var qux = typeof(Bar).GetProperty(nameof(Bar.Qux)); Test((a, b, c) => { var p = Expression.Parameter(typeof(Bar)); return Expression.Block( new[] { p }, Expression.Assign( p, Expression.MemberInit( Expression.New(typeof(Bar)), Expression.Bind(baz, a), Expression.Bind(foo, b), Expression.Bind(qux, c) ) ), Expression.Multiply( Expression.Add( Expression.Property(p, baz), Expression.Property(p, foo) ), Expression.Property(p, qux) ) ); }, Expression.Constant(2), Expression.Constant(3), Expression.Constant(5)); } [Fact] public static void Spill_MemberInit_MemberBind() { var bar = typeof(BarHolder).GetProperty(nameof(BarHolder.Bar)); var baz = typeof(Bar).GetProperty(nameof(Bar.Baz)); var foo = typeof(Bar).GetProperty(nameof(Bar.Foo)); var qux = typeof(Bar).GetProperty(nameof(Bar.Qux)); Test((a, b, c) => { var p = Expression.Parameter(typeof(BarHolder)); return Expression.Block( new[] { p }, Expression.Assign( p, Expression.MemberInit( Expression.New(typeof(BarHolder)), Expression.MemberBind( bar, Expression.Bind(baz, a), Expression.Bind(foo, b), Expression.Bind(qux, c) ) ) ), Expression.Multiply( Expression.Add( Expression.Property(Expression.Property(p, bar), baz), Expression.Property(Expression.Property(p, bar), foo) ), Expression.Property(Expression.Property(p, bar), qux) ) ); }, Expression.Constant(2), Expression.Constant(3), Expression.Constant(5)); } [Fact] public static void Spill_MemberInit_ListBind() { var xs = typeof(ListHolder).GetProperty(nameof(ListHolder.Xs)); var add = typeof(List<int>).GetMethod(nameof(List<int>.Add)); var item = typeof(List<int>).GetProperty("Item"); Test((a, b, c) => { var p = Expression.Parameter(typeof(ListHolder)); return Expression.Block( new[] { p }, Expression.Assign( p, Expression.MemberInit( Expression.New(typeof(ListHolder)), Expression.ListBind( xs, Expression.ElementInit(add, a), Expression.ElementInit(add, b), Expression.ElementInit(add, c) ) ) ), Expression.Multiply( Expression.Add( Expression.Property(Expression.Property(p, xs), item, Expression.Constant(0)), Expression.Property(Expression.Property(p, xs), item, Expression.Constant(1)) ), Expression.Property(Expression.Property(p, xs), item, Expression.Constant(2)) ) ); }, Expression.Constant(2), Expression.Constant(3), Expression.Constant(5)); } [Fact] public static void Spill_Switch() { Test((v, d, a) => Expression.Switch(v, d, Expression.SwitchCase(a, Expression.Constant(1))), Expression.Constant(1), Expression.Constant(2), Expression.Constant(3)); Test((v, d, a) => Expression.Switch(v, d, Expression.SwitchCase(a, Expression.Constant(7))), Expression.Constant(1), Expression.Constant(2), Expression.Constant(3)); Test((v, d, a) => Expression.Switch(v, d, Expression.SwitchCase(Expression.Constant(7), a)), Expression.Constant(1), Expression.Constant(2), Expression.Constant(3)); Test((v, d, a) => Expression.Switch(v, d, Expression.SwitchCase(Expression.Constant(7), a)), Expression.Constant(1), Expression.Constant(2), Expression.Constant(1)); } [Fact] public static void Spill_Block() { Test((a, b) => Expression.Block(a, b), Expression.Constant(1), Expression.Constant(2)); } [Fact] public static void Spill_LabelGoto() { foreach (var t in new[] { true, false }) { Test((c, a, b) => { var lbl = Expression.Label(typeof(int)); return Expression.Block( Expression.IfThen(c, Expression.Goto(lbl, a)), Expression.Label(lbl, b) ); }, Expression.Constant(t), Expression.Constant(1), Expression.Constant(2)); } } [Fact] public static void Spill_NotRefInstance_IndexAssignment() { // See https://github.com/dotnet/corefx/issues/11740 for documented limitation var v = Expression.Constant(new ValueVector()); var item = typeof(ValueVector).GetProperty("Item"); var i = Expression.Constant(0); var x = Expression.Constant(42); NotSupported(Expression.Assign(Expression.Property(v, item, i), Spill(x))); } [Fact] public static void Spill_NotRefInstance_Index() { // See https://github.com/dotnet/corefx/issues/11740 for documented limitation var v = Expression.Constant(new ValueVector()); var item = typeof(ValueVector).GetProperty("Item"); var i = Expression.Constant(0); NotSupported(Expression.Property(v, item, Spill(i))); } [Fact] public static void Spill_NotRefInstance_MemberAssignment() { // See https://github.com/dotnet/corefx/issues/11740 for documented limitation var v = Expression.Constant(new ValueBar()); var foo = typeof(ValueBar).GetProperty(nameof(ValueBar.Foo)); var x = Expression.Constant(42); NotSupported(Expression.Assign(Expression.Property(v, foo), Spill(x))); } [Fact] public static void Spill_NotRefInstance_Call() { // See https://github.com/dotnet/corefx/issues/11740 for documented limitation var v = Expression.Constant(new ValueBar()); var qux = typeof(ValueBar).GetMethod(nameof(ValueBar.Qux)); var x = Expression.Constant(42); NotSupported(Expression.Call(v, qux, Spill(x))); } [Fact] public static void Spill_RequireNoRefArgs_Call() { // See https://github.com/dotnet/corefx/issues/11740 for documented limitation var assign = typeof(ByRefs).GetMethod(nameof(ByRefs.Assign)); var x = Expression.Parameter(typeof(int)); var v = Expression.Constant(42); var b = Expression.Block(new[] { x }, Expression.Call(assign, x, Spill(v)), x); NotSupported(b); } [Fact] public static void Spill_RequireNoRefArgs_New() { // See https://github.com/dotnet/corefx/issues/11740 for documented limitation var ctor = typeof(ByRefs).GetConstructors()[0]; var x = Expression.Parameter(typeof(int)); var v = Expression.Constant(42); var b = Expression.Block(new[] { x }, Expression.New(ctor, x, Spill(v)), x); NotSupported(b); } [Fact] public static void Spill_Optimizations_Constant() { var xs = Expression.Parameter(typeof(int[])); var i = Expression.Constant(0); var v = Spill(Expression.Constant(1)); var e = Expression.Lambda<Action<int[]>>( Expression.Assign(Expression.ArrayAccess(xs, i), v), xs ); e.VerifyIL(@" .method void ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure,int32[]) { .maxstack 4 .locals init ( [0] int32[], [1] int32, [2] int32 ) // Save instance (`xs`) into V_0 IL_0000: ldarg.1 IL_0001: stloc.0 // Save rhs (`try { 1 } finally {}`) into V_1 .try { IL_0002: ldc.i4.1 IL_0003: stloc.2 IL_0004: leave IL_000a } finally { IL_0009: endfinally } IL_000a: ldloc.2 IL_000b: stloc.1 // Load instance from V_0 IL_000c: ldloc.0 // <OPTIMIZATION> Evaluate index (`0`) </OPTIMIZATION> IL_000d: ldc.i4.0 // Load rhs from V_1 IL_000e: ldloc.1 // Evaluate `instance[index] = rhs` index assignment IL_000f: stelem.i4 IL_0010: ret }" ); } [Fact] public static void Spill_Optimizations_Default() { var xs = Expression.Parameter(typeof(int[])); var i = Expression.Default(typeof(int)); var v = Spill(Expression.Constant(1)); var e = Expression.Lambda<Action<int[]>>( Expression.Assign(Expression.ArrayAccess(xs, i), v), xs ); e.VerifyIL(@" .method void ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure,int32[]) { .maxstack 4 .locals init ( [0] int32[], [1] int32, [2] int32 ) // Save instance (`xs`) into V_0 IL_0000: ldarg.1 IL_0001: stloc.0 // Save rhs (`try { 1 } finally {}`) into V_1 .try { IL_0002: ldc.i4.1 IL_0003: stloc.2 IL_0004: leave IL_000a } finally { IL_0009: endfinally } IL_000a: ldloc.2 IL_000b: stloc.1 // Load instance from V_0 IL_000c: ldloc.0 // <OPTIMIZATION> Evaluate index (`0`) </OPTIMIZATION> IL_000d: ldc.i4.0 // Load rhs from V_1 IL_000e: ldloc.1 // Evaluate `instance[index] = rhs` index assignment IL_000f: stelem.i4 IL_0010: ret }" ); } [Fact] public static void Spill_Optimizations_LiteralField() { var e = Expression.Lambda<Func<double>>( Expression.Add( Expression.Field(null, typeof(Math).GetField(nameof(Math.PI))), Spill(Expression.Constant(0.0)) ) ); e.VerifyIL(@" .method float64 ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure) { .maxstack 3 .locals init ( [0] float64, [1] float64 ) // Save rhs (`try { 0.0 } finally {}`) into V_0 .try { IL_0000: ldc.r8 0 IL_0009: stloc.1 IL_000a: leave IL_0010 } finally { IL_000f: endfinally } IL_0010: ldloc.1 IL_0011: stloc.0 // <OPTIMIZATION> Evaluate lhs (`Math.PI` gets inlined) </OPTIMIZATION> IL_0012: ldc.r8 3.14159265358979 // Load rhs from V_0 IL_001b: ldloc.0 // Evaluate `lhs + rhs` IL_001c: add IL_001d: ret }" ); } [Fact] public static void Spill_Optimizations_StaticReadOnlyField() { var e = Expression.Lambda<Func<string>>( Expression.Call( typeof(string).GetMethod(nameof(string.Concat), new[] { typeof(string), typeof(string) }), Expression.Field(null, typeof(bool).GetField(nameof(bool.TrueString))), Spill(Expression.Constant("!")) ) ); e.VerifyIL(@" .method string ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure) { .maxstack 3 .locals init ( [0] string, [1] string ) // Save arg1 (`try { ""!"" } finally {}`) into V_0 .try { IL_0000: ldstr ""!"" IL_0005: stloc.1 IL_0006: leave IL_000c } finally { IL_000b: endfinally } IL_000c: ldloc.1 IL_000d: stloc.0 // <OPTIMIZATION> Evaluate arg0 (`bool::TrueString`) </OPTIMIZATION> IL_000e: ldsfld bool::TrueString // Load arg1 from V_0 IL_0013: ldloc.0 // Evaluate `string.Concat(arg0, arg1)` call IL_0014: call string string::Concat(string,string) IL_0019: ret }" ); } [Fact] public static void Spill_Optimizations_RuntimeVariables1() { var f = Expression.Parameter(typeof(Action<IRuntimeVariables, int>)); var e = Expression.Lambda<Action<Action<IRuntimeVariables, int>>>( Expression.Invoke( f, Expression.RuntimeVariables(), Spill(Expression.Constant(2)) ), f ); e.VerifyIL(@" .method void ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure,class [System.Private.CoreLib]System.Action`2<class [System.Linq.Expressions]System.Runtime.CompilerServices.IRuntimeVariables,int32>) { .maxstack 4 .locals init ( [0] class [System.Private.CoreLib]System.Action`2<class [System.Linq.Expressions]System.Runtime.CompilerServices.IRuntimeVariables,int32>, [1] int32, [2] int32 ) // Save target (`f`) into V_0 IL_0000: ldarg.1 IL_0001: stloc.0 // Save arg1 (`try { 2 } finally {}`) into V_1 .try { IL_0002: ldc.i4.2 IL_0003: stloc.2 IL_0004: leave IL_000a } finally { IL_0009: endfinally } IL_000a: ldloc.2 IL_000b: stloc.1 // Load target from V_0 IL_000c: ldloc.0 // <OPTIMIZATION> Load arg0 (`RuntimeVariables`) by calling RuntimeOps.CreateRuntimeVariables </OPTIMIZATION> IL_000d: call class [System.Linq.Expressions]System.Runtime.CompilerServices.IRuntimeVariables class [System.Linq.Expressions]System.Runtime.CompilerServices.RuntimeOps::CreateRuntimeVariables() // Load arg1 from V_1 IL_0012: ldloc.1 // Evaluate `target(arg0, arg1)` delegate invocation IL_0013: callvirt instance void class [System.Private.CoreLib]System.Action`2<class [System.Linq.Expressions]System.Runtime.CompilerServices.IRuntimeVariables,int32>::Invoke(class [System.Linq.Expressions]System.Runtime.CompilerServices.IRuntimeVariables,int32) IL_0018: ret }" ); } [Fact] public static void Spill_Optimizations_RuntimeVariables2() { var f = Expression.Parameter(typeof(Action<IRuntimeVariables, int>)); var x = Expression.Parameter(typeof(int)); var e = Expression.Lambda<Action<Action<IRuntimeVariables, int>, int>>( Expression.Invoke( f, Expression.RuntimeVariables(x), Spill(Expression.Constant(2)) ), f, x ); e.VerifyIL(@" .method void ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure,class [System.Private.CoreLib]System.Action`2<class [System.Linq.Expressions]System.Runtime.CompilerServices.IRuntimeVariables,int32>,int32) { .maxstack 10 .locals init ( [0] object[], [1] class [System.Private.CoreLib]System.Action`2<class [System.Linq.Expressions]System.Runtime.CompilerServices.IRuntimeVariables,int32>, [2] int32, [3] int32 ) // Hoist `x` to a closure in V_0 IL_0000: ldc.i4.1 IL_0001: newarr object IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldarg.2 IL_0009: newobj instance void class [System.Runtime]System.Runtime.CompilerServices.StrongBox`1<int32>::.ctor(int32) IL_000e: stelem.ref IL_000f: stloc.0 // Save target (`f`) into V_1 IL_0010: ldarg.1 IL_0011: stloc.1 // Save arg1 (`try { 2 } finally {}`) into V_2 .try { IL_0012: ldc.i4.2 IL_0013: stloc.3 IL_0014: leave IL_001a } finally { IL_0019: endfinally } IL_001a: ldloc.3 IL_001b: stloc.2 // Load target from V_1 IL_001c: ldloc.1 // <OPTIMIZATION> Load arg0 (`RuntimeVariables`) by calling RuntimeOps.CreateRuntimeVariables </OPTIMIZATION> IL_001d: ldloc.0 IL_001e: ldarg.0 IL_001f: ldfld class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure::Constants IL_0024: ldc.i4.0 IL_0025: ldelem.ref IL_0026: castclass int64[] IL_002b: call class [System.Linq.Expressions]System.Runtime.CompilerServices.IRuntimeVariables class [System.Linq.Expressions]System.Runtime.CompilerServices.RuntimeOps::CreateRuntimeVariables(object[],int64[]) // Load arg1 from V_2 IL_0030: ldloc.2 // Evaluate `target(arg0, arg1)` delegate invocation IL_0031: callvirt instance void class [System.Private.CoreLib]System.Action`2<class [System.Linq.Expressions]System.Runtime.CompilerServices.IRuntimeVariables,int32>::Invoke(class [System.Linq.Expressions]System.Runtime.CompilerServices.IRuntimeVariables,int32) IL_0036: ret }" ); } private static void NotSupported(Expression expression) { Assert.Throws<NotSupportedException>(() => { Expression.Lambda<Func<object>>(Expression.Convert(expression, typeof(object))).Compile(); }); } private static void Test(Func<Expression, Expression> factory, Expression arg1) { Test(args => factory(args[0]), new[] { arg1 }); } private static void Test(Func<Expression, Expression, Expression> factory, Expression arg1, Expression arg2) { Test(args => factory(args[0], args[1]), new[] { arg1, arg2 }); } private static void Test(Func<Expression, Expression, Expression, Expression> factory, Expression arg1, Expression arg2, Expression arg3) { Test(args => factory(args[0], args[1], args[2]), new[] { arg1, arg2, arg3 }); } private static void Test(Func<Expression[], Expression> factory, Expression[] args) { var expected = Eval(factory(args)); for (var i = 0; i < args.Length; i++) { var newArgs = args.Select((arg, j) => j == i ? Spill(arg) : arg).ToArray(); Assert.Equal(expected, Eval(factory(newArgs))); } for (var i = 0; i < args.Length; i++) { var newArgs = args.Select((arg, j) => j == i ? new Extension(arg) : arg).ToArray(); Assert.Equal(expected, Eval(factory(newArgs))); } } private static object Eval(Expression expression) { return Expression.Lambda<Func<object>>(Expression.Convert(expression, typeof(object))).Compile()(); } private static Expression Spill(Expression expression) { return Expression.TryFinally(expression, Expression.Empty()); } class BarHolder { public Bar Bar { get; } = new Bar(); } class ListHolder { public List<int> Xs { get; } = new List<int>(); } class Bar { public int Baz { get; set; } public int Foo { get; set; } public int Qux { get; set; } } class Extension : Expression { private readonly Expression _reduced; public Extension(Expression reduced) { _reduced = reduced; } public override bool CanReduce => true; public override ExpressionType NodeType => ExpressionType.Extension; public override Type Type => _reduced.Type; public override Expression Reduce() => _reduced; } struct ValueVector { private int v0; public int this[int x] { get { return v0; } set { v0 = value; } } } struct ValueBar { public int Foo { get; set; } public int Qux(int x) => x + 1; } class ByRefs { public ByRefs(ref int x, int v) { x = v; } public static void Assign(ref int x, int v) { x = v; } } } } #endif
37.244831
281
0.470755
[ "MIT" ]
hgGeorg/corefx
src/System.Linq.Expressions/tests/StackSpillerTests.cs
34,230
C#
using Apstory.ApstoryTsqlCodeGen.Shared.Repositories; using Apstory.ApstoryTsqlCodeGen.Shared.Models; using Apstory.ApstoryTsqlCodeGen.Shared.Repositories; using Microsoft.Extensions.CommandLineUtils; using System; using System.IO; using System.Linq; using System.Text; namespace Apstory.ApstoryTsqlCodeGen.DapperGenerator { class Program { private static string _GenPath = ""; // ".Gen" private static string _ModelGenPath = ""; // "Gen." private static string _GenPathNamespace = ".Gen"; static void Main(string[] args) { CommandLineApplication commandLineApplication = new CommandLineApplication(throwOnUnexpectedArg: false); CommandOption path = commandLineApplication.Option( "-p |--path <Path>", "Path to create and save generated model class files", CommandOptionType.SingleValue); CommandOption classNamespace = commandLineApplication.Option( "-n |--classNamespace <ClassNamespace>", "Class namespace", CommandOptionType.SingleValue); CommandOption conString = commandLineApplication.Option( "-c |--constring <ConnectionString>", "Database connection string", CommandOptionType.MultipleValue); CommandOption genPath = commandLineApplication.Option( "-g |--GenPath <GenPath>", "Add gen path true or false", CommandOptionType.SingleValue); CommandOption genPathNamespace = commandLineApplication.Option( "-gn |--GenPathNamespace <GenPathNamespace>", "Add gen path true or false", CommandOptionType.SingleValue); CommandOption schemaString = commandLineApplication.Option( "-schema |--schemaString <SchemaString>", "Schema (Defaults to 'dbo')", CommandOptionType.MultipleValue); commandLineApplication.HelpOption("-? | -h | --help"); commandLineApplication.OnExecute(() => { var schema = "dbo"; if (schemaString.HasValue()) schema = schemaString.Value(); Console.WriteLine($"Path : {path.Value()}"); Console.WriteLine($"ClassNamepsace : {classNamespace.Value()}"); Console.WriteLine($"ConnectionString : {conString.Value()}"); Console.WriteLine($"SchemaString: {schema}"); var schemaAdd = schema != "dbo"; _ModelGenPath = (schemaAdd ? schema.ToUpper() + "." : ""); if (path.HasValue() && classNamespace.HasValue() && conString.HasValue()) { if (genPath.HasValue()) { if (genPath.Value() == "true") { _GenPath = ".Gen"; if (genPathNamespace.HasValue()) { if (genPathNamespace.Value() == "false") { _GenPathNamespace = ""; } else { _ModelGenPath += "Gen."; } } else { _ModelGenPath += "Gen."; } } } ProcessDapperGenerator(path.Value(), classNamespace.Value(), conString.Value(), schema); } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("ERROR"); Console.WriteLine($"Path and connection string is required"); Console.ForegroundColor = ConsoleColor.White; } return 0; }); commandLineApplication.Execute(args); } private static void ProcessDapperGenerator(string path, string classNamespace, string conString, string schema) { var tablesRepository = new CachedSqlTablesRepository(conString); new DapperGen(tablesRepository, _GenPath, _ModelGenPath, _GenPathNamespace, false).Run(path, classNamespace, schema).Wait(); } } }
43.50495
136
0.533227
[ "MIT" ]
apstory/apstory-tsql-code-gen
Apstory.ApstoryTsqlCodeGen.DapperGenerator/Program.cs
4,396
C#
using System.Collections; namespace Word2Vec.Util { public class DictionaryEnumerator<TKey, TValue> : IDictionaryEnumerator, IDisposable { readonly IEnumerator<KeyValuePair<TKey, TValue>> _impl; public void Dispose() { _impl.Dispose(); } public DictionaryEnumerator(IDictionary<TKey, TValue> value) { _impl = value.GetEnumerator(); } public void Reset() { _impl.Reset(); } public bool MoveNext() { return _impl.MoveNext(); } public DictionaryEntry Entry { get { var pair = _impl.Current; return new DictionaryEntry(pair.Key, pair.Value); } } public object Key { get { return _impl.Current.Key; } } public object Value { get { return _impl.Current.Value; } } public object Current { get { return Entry; } } } }
32.392857
88
0.585447
[ "MIT" ]
ButterscotchV/Word2Vec.Net
Word2Vec/Util/DictionaryEnumerator.cs
907
C#
using BitSharp.Common; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; namespace BitSharp.Node.Domain { public class AddressPayload { public readonly ImmutableArray<NetworkAddressWithTime> NetworkAddresses; public AddressPayload(ImmutableArray<NetworkAddressWithTime> NetworkAddresses) { this.NetworkAddresses = NetworkAddresses; } public AddressPayload With(ImmutableArray<NetworkAddressWithTime>? NetworkAddresses = null) { return new AddressPayload ( NetworkAddresses ?? this.NetworkAddresses ); } } }
26.448276
100
0.658409
[ "Unlicense" ]
dthorpe/BitSharp
BitSharp.Node/Domain/AddressPayload.cs
769
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Input; using Microsoft.MixedReality.Toolkit.Utilities; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.OpenVR.Input { /// <summary> /// Open VR Implementation of the Windows Mixed Reality Motion Controllers. /// </summary> [MixedRealityController( SupportedControllerType.WindowsMixedReality, new[] { Handedness.Left, Handedness.Right }, "StandardAssets/Textures/MotionController")] public class WindowsMixedRealityOpenVRMotionController : GenericOpenVRController { /// <summary> /// Constructor. /// </summary> public WindowsMixedRealityOpenVRMotionController(TrackingState trackingState, Handedness controllerHandedness, IMixedRealityInputSource inputSource = null, MixedRealityInteractionMapping[] interactions = null) : base(trackingState, controllerHandedness, inputSource, interactions) { PointerOffsetAngle = -30f; } /// <inheritdoc /> public override MixedRealityInteractionMapping[] DefaultLeftHandedInteractions => new[] { new MixedRealityInteractionMapping(0, "Spatial Pointer", AxisType.SixDof, DeviceInputType.SpatialPointer, MixedRealityInputAction.None), new MixedRealityInteractionMapping(1, "Spatial Grip", AxisType.SixDof, DeviceInputType.SpatialGrip, MixedRealityInputAction.None), new MixedRealityInteractionMapping(2, "Grip Press", AxisType.SingleAxis, DeviceInputType.TriggerPress, ControllerMappingLibrary.AXIS_11), new MixedRealityInteractionMapping(3, "Trigger Position", AxisType.SingleAxis, DeviceInputType.Trigger, ControllerMappingLibrary.AXIS_9), new MixedRealityInteractionMapping(4, "Trigger Touch", AxisType.SingleAxis, DeviceInputType.TriggerTouch, ControllerMappingLibrary.AXIS_9), new MixedRealityInteractionMapping(5, "Trigger Press (Select)", AxisType.Digital, DeviceInputType.TriggerPress, KeyCode.JoystickButton14), new MixedRealityInteractionMapping(6, "Touchpad Position", AxisType.DualAxis, DeviceInputType.Touchpad, ControllerMappingLibrary.AXIS_17, ControllerMappingLibrary.AXIS_18, false, true), new MixedRealityInteractionMapping(7, "Touchpad Touch", AxisType.Digital, DeviceInputType.TouchpadTouch, KeyCode.JoystickButton16), new MixedRealityInteractionMapping(8, "Touchpad Press", AxisType.Digital, DeviceInputType.TouchpadPress, KeyCode.JoystickButton8), new MixedRealityInteractionMapping(9, "Menu Press", AxisType.Digital, DeviceInputType.ButtonPress, KeyCode.JoystickButton2), new MixedRealityInteractionMapping(10, "Thumbstick Position", AxisType.DualAxis, DeviceInputType.ThumbStick, ControllerMappingLibrary.AXIS_1, ControllerMappingLibrary.AXIS_2, false, true), new MixedRealityInteractionMapping(11, "Thumbstick Press", AxisType.Digital, DeviceInputType.ButtonPress, KeyCode.JoystickButton18), }; /// <inheritdoc /> public override MixedRealityInteractionMapping[] DefaultRightHandedInteractions => new[] { new MixedRealityInteractionMapping(0, "Spatial Pointer", AxisType.SixDof, DeviceInputType.SpatialPointer, MixedRealityInputAction.None), new MixedRealityInteractionMapping(1, "Spatial Grip", AxisType.SixDof, DeviceInputType.SpatialGrip, MixedRealityInputAction.None), new MixedRealityInteractionMapping(2, "Grip Press", AxisType.SingleAxis, DeviceInputType.TriggerPress, ControllerMappingLibrary.AXIS_12), new MixedRealityInteractionMapping(3, "Trigger Position", AxisType.SingleAxis, DeviceInputType.Trigger, ControllerMappingLibrary.AXIS_10), new MixedRealityInteractionMapping(4, "Trigger Touch", AxisType.SingleAxis, DeviceInputType.TriggerTouch, ControllerMappingLibrary.AXIS_10), new MixedRealityInteractionMapping(5, "Trigger Press (Select)", AxisType.Digital, DeviceInputType.TriggerPress, KeyCode.JoystickButton15), new MixedRealityInteractionMapping(6, "Touchpad Position", AxisType.DualAxis, DeviceInputType.Touchpad, ControllerMappingLibrary.AXIS_19, ControllerMappingLibrary.AXIS_20, false, true), new MixedRealityInteractionMapping(7, "Touchpad Touch", AxisType.Digital, DeviceInputType.TouchpadTouch, KeyCode.JoystickButton17), new MixedRealityInteractionMapping(8, "Touchpad Press", AxisType.Digital, DeviceInputType.TouchpadPress, KeyCode.JoystickButton9), new MixedRealityInteractionMapping(9, "Menu Press", AxisType.Digital, DeviceInputType.ButtonPress, KeyCode.JoystickButton0), new MixedRealityInteractionMapping(10, "Thumbstick Position", AxisType.DualAxis, DeviceInputType.ThumbStick, ControllerMappingLibrary.AXIS_4, ControllerMappingLibrary.AXIS_5, false, true), new MixedRealityInteractionMapping(11, "Thumbstick Press", AxisType.Digital, DeviceInputType.ButtonPress, KeyCode.JoystickButton19), }; /// <inheritdoc /> public override void SetupDefaultInteractions(Handedness controllerHandedness) { AssignControllerMappings(controllerHandedness == Handedness.Left ? DefaultLeftHandedInteractions : DefaultRightHandedInteractions); } } }
80.264706
217
0.762917
[ "MIT" ]
Icbyone/MRDL_Unity_Surfaces
Assets/MixedRealityToolkit.Providers/OpenVR/WindowsMixedRealityOpenVRMotionController.cs
5,460
C#
using System; using NUnit.Framework; namespace DryIoc.IssuesTests { [TestFixture] public class Issue178_FallbackContainerDisposesInstanceRegisteredInParent { [Test] public void Test_WithPreventDisposal() { var container = new Container(); var a = new A(); container.RegisterInstance<IA>(a, setup: Setup.With(preventDisposal: true)); using (var c2 = container.CreateFacade()) { c2.Register<B>(serviceKey: ContainerTools.FacadeKey); var p2 = c2.Resolve<B>(); } Assert.IsFalse(a.IsDisposed); } [Test] public void Test_WithPreventDisposalAndReplace() { var container = new Container(); var a = new A(); container.RegisterInstance<IA>(a, setup: Setup.With(preventDisposal: true)); using (var c2 = container.CreateFacade()) { c2.Register<B>(serviceKey: ContainerTools.FacadeKey); var b1 = c2.Resolve<B>(); Assert.IsNotNull(b1.A); } Assert.IsFalse(a.IsDisposed); } [Test] public void Test_WithPreventDisposalAndWeaklyReferenced() { var container = new Container(); var a = new A(); container.RegisterInstance<IA>(a, setup: Setup.With(preventDisposal: true, weaklyReferenced: true)); using (var c2 = container.CreateFacade()) { c2.Register<B>(serviceKey: ContainerTools.FacadeKey); var p2 = c2.Resolve<B>(); } Assert.IsFalse(a.IsDisposed); GC.KeepAlive(a); } public interface IA { } public class A : IA, IDisposable { public Boolean IsDisposed; public void Dispose() { IsDisposed = true; } public override string ToString() => IsDisposed ? "Object is disposed" : "Ok"; } public class B { public B(IA a) { this.A = a; } public IA A; } } }
24.833333
112
0.510515
[ "MIT" ]
0000duck/DryIoc
test/DryIoc.IssuesTests/Issue178_FallbackContainerDisposesInstanceRegisteredInParent.cs
2,235
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die mit einer Assembly verknüpft sind. [assembly: AssemblyTitle("NetOffice Access Examples in C#")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("https://github.com/NetOfficeFw/NetOffice")] [assembly: AssemblyCopyright("Copyright © 2012 Sebastian Lange")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("fec758f4-1476-4f48-8e43-8fe3a289e0c4")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
41.891892
106
0.76129
[ "MIT" ]
DominikPalo/NetOffice
Examples/Access/C#/Standard Examples/AccessExamples/Properties/AssemblyInfo.cs
1,568
C#
namespace Bearded.Utilities { public sealed class Box<T> where T : struct { public T Value { get; } public Box(T value) { Value = value; } } }
15.384615
47
0.49
[ "MIT" ]
MaurizioPz/utilities
Bearded.Utilities/Core/Box.cs
200
C#
using System.Text; namespace test { public class Test { public static int Main() { StringBuilder b = new StringBuilder(); /*b.Append ('A'); b.Append ('b'); b.Append ('r');*/ b.Append("Abr"); if (b.ToString() != "Abr") { System.Console.WriteLine("Got: " + b.ToString()); return 1; } b.Append('a'); b.Append("cadabra"); if (b.ToString() != "Abracadabra") { System.Console.WriteLine("Got: " + b.ToString()); return 2; } return 0; } } }
22.8
65
0.399123
[ "MIT" ]
belav/runtime
src/mono/mono/tests/stringbuilder.cs
684
C#
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and limitations under the License. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Reflection; using Microsoft.VisualStudio.TestTools.UnitTesting; using NakedObjects.Architecture.Component; using NakedObjects.Architecture.Facet; using NakedObjects.Architecture.Reflect; using NakedObjects.Architecture.SpecImmutable; using NakedObjects.Meta.Facet; using NakedObjects.ParallelReflect.FacetFactory; namespace NakedObjects.ParallelReflect.Test.FacetFactory { [TestClass] public class NotNavigableAnnotationFacetFactoryTest : AbstractFacetFactoryTest { private NotNavigableAnnotationFacetFactory facetFactory; protected override Type[] SupportedTypes { get { return new[] {typeof(INotNavigableFacet)}; } } protected override IFacetFactory FacetFactory { get { return facetFactory; } } [TestMethod] public override void TestFeatureTypes() { FeatureType featureTypes = facetFactory.FeatureTypes; Assert.IsTrue(featureTypes.HasFlag(FeatureType.Objects)); Assert.IsTrue(featureTypes.HasFlag(FeatureType.Properties)); Assert.IsFalse(featureTypes.HasFlag(FeatureType.Collections)); Assert.IsFalse(featureTypes.HasFlag(FeatureType.Actions)); Assert.IsFalse(featureTypes.HasFlag(FeatureType.ActionParameters)); } [TestMethod] public void TestNotNavigableAnnotationPickedUpOnCollection() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); PropertyInfo property = FindProperty(typeof(Customer1), "Orders"); metamodel = facetFactory.Process(Reflector, property, MethodRemover, Specification, metamodel); IFacet facet = Specification.GetFacet(typeof(INotNavigableFacet)); Assert.IsNotNull(facet); Assert.IsTrue(facet is NotNavigableFacet); AssertNoMethodsRemoved(); Assert.IsNotNull(metamodel); } [TestMethod] public void TestNotNavigableAnnotationPickedUpOnProperty() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); PropertyInfo property = FindProperty(typeof(Customer), "FirstName"); metamodel = facetFactory.Process(Reflector, property, MethodRemover, Specification, metamodel); IFacet facet = Specification.GetFacet(typeof(INotNavigableFacet)); Assert.IsNotNull(facet); Assert.IsTrue(facet is NotNavigableFacet); AssertNoMethodsRemoved(); Assert.IsNotNull(metamodel); } [TestMethod] public void TestNotNavigableAnnotationPickedUpOnType() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); PropertyInfo property = FindProperty(typeof(Customer2), "FirstName"); metamodel = facetFactory.Process(Reflector, property, MethodRemover, Specification, metamodel); IFacet facet = Specification.GetFacet(typeof(INotNavigableFacet)); Assert.IsNotNull(facet); Assert.IsTrue(facet is NotNavigableFacet); AssertNoMethodsRemoved(); } #region Nested type: Customer private class Customer { [NotNavigable] // ReSharper disable once UnusedMember.Local public string FirstName { get { return null; } } } #endregion #region Nested type: Customer1 private class Customer1 { [NotNavigable] // ReSharper disable once UnusedMember.Local public IList Orders { get { return null; } } } #endregion #region Nested type: Customer2 private class Customer2 { public NotNavigable FirstName { get { return null; } } } #endregion #region Nested type: NotNavigable [NotNavigable] private class NotNavigable { } #endregion #region Setup/Teardown [TestInitialize] public override void SetUp() { base.SetUp(); facetFactory = new NotNavigableAnnotationFacetFactory(0); } [TestCleanup] public override void TearDown() { facetFactory = null; base.TearDown(); } #endregion } // Copyright (c) Naked Objects Group Ltd. }
37.560284
138
0.671828
[ "Apache-2.0" ]
Giovanni-Russo-Boscoli/NakedObjectsFramework
Core/NakedObjects.ParallelReflector.Test/FacetFactory/NotNavigableAnnotationFacetFactoryTest.cs
5,296
C#
namespace GoogleMapsServices.Client; [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.0.22.0 (Newtonsoft.Json v11.0.0.0)")] public partial class TimeZoneResponse { /// <summary>The offset for daylight-savings time in seconds. This will be zero if the time zone is not in Daylight Savings Time during the specified `timestamp`.</summary> [Newtonsoft.Json.JsonProperty("dstOffset", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public double DstOffset { get; set; } /// <summary>The offset from UTC (in seconds) for the given location. This does not take into effect daylight savings.</summary> [Newtonsoft.Json.JsonProperty("rawOffset", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public double RawOffset { get; set; } /// <summary>a string containing the ID of the time zone, such as "America/Los_Angeles" or "Australia/Sydney". These IDs are defined by [Unicode Common Locale Data Repository (CLDR) project](http://cldr.unicode.org/), and currently available in file timezone.xml. When a timezone has several IDs, the canonical one is returned. In xml responses, this is the first alias of each timezone. For example, "Asia/Calcutta" is returned, not "Asia/Kolkata".</summary> [Newtonsoft.Json.JsonProperty("timeZoneId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string TimeZoneId { get; set; } /// <summary>The long form name of the time zone. This field will be localized if the language parameter is set. eg. `Pacific Daylight Time` or `Australian Eastern Daylight Time`.</summary> [Newtonsoft.Json.JsonProperty("timeZoneName", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string TimeZoneName { get; set; } [Newtonsoft.Json.JsonProperty("status", Required = Newtonsoft.Json.Required.Always)] [System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)] [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] public TimeZoneStatus Status { get; set; } /// <summary>Detailed information about the reasons behind the given status code. Included if status other than `Ok`.</summary> [Newtonsoft.Json.JsonProperty("errorMessage", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ErrorMessage { get; set; } private IDictionary<string, object> _additionalProperties = new Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } }
71.195122
463
0.762933
[ "MIT" ]
Jonathan-Hickey/GoogleMapsServices
src/GoogleMapsServices.Client/TimeZoneResponse.cs
2,921
C#
using Diadoc.Api.Http; using Diadoc.Api.Proto.Events; using Diadoc.Api.Proto.Invoicing; namespace Diadoc.Api { public partial class DiadocHttpApi { public GeneratedFile GenerateUniversalTransferDocumentXmlForSeller( string authToken, UniversalTransferDocumentSellerTitleInfo info, bool disableValidation = false) { return GenerateUniversalTransferDocumentXml(authToken, info, false, disableValidation); } public GeneratedFile GenerateUniversalCorrectionDocumentXmlForSeller( string authToken, UniversalCorrectionDocumentSellerTitleInfo correctionInfo, bool disableValidation = false) { return GenerateUniversalTransferDocumentXml(authToken, correctionInfo, true, disableValidation); } private GeneratedFile GenerateUniversalTransferDocumentXml<T>(string authToken, T protoInfo, bool isCorrection, bool disableValidation = false) where T : class { var query = new PathAndQueryBuilder("/GenerateUniversalTransferDocumentXmlForSeller"); if (isCorrection) query.AddParameter("correction", ""); if (disableValidation) query.AddParameter("disableValidation", ""); return PerformGenerateXmlHttpRequest(authToken, query.BuildPathAndQuery(), protoInfo); } public GeneratedFile GenerateUniversalTransferDocumentXmlForBuyer(string authToken, UniversalTransferDocumentBuyerTitleInfo info, string boxId, string sellerTitleMessageId, string sellerTitleAttachmentId) { var query = new PathAndQueryBuilder("/GenerateUniversalTransferDocumentXmlForBuyer"); query.AddParameter("boxId", boxId); query.AddParameter("sellerTitleMessageId", sellerTitleMessageId); query.AddParameter("sellerTitleAttachmentId", sellerTitleAttachmentId); return PerformGenerateXmlHttpRequest(authToken, query.BuildPathAndQuery(), info); } public UniversalTransferDocumentSellerTitleInfo ParseUniversalTransferDocumentSellerTitleXml(byte[] xmlContent) { var query = new PathAndQueryBuilder("/ParseUniversalTransferDocumentSellerTitleXml"); query.AddParameter("documentVersion", DefaultDocumentVersions.Utd); return PerformHttpRequest<UniversalTransferDocumentSellerTitleInfo>(null, "POST", query.BuildPathAndQuery(), xmlContent); } public UniversalTransferDocumentBuyerTitleInfo ParseUniversalTransferDocumentBuyerTitleXml(byte[] xmlContent) { return PerformHttpRequest<UniversalTransferDocumentBuyerTitleInfo>(null, "POST", "/ParseUniversalTransferDocumentBuyerTitleXml", xmlContent); } public UniversalCorrectionDocumentSellerTitleInfo ParseUniversalCorrectionDocumentSellerTitleXml(byte[] xmlContent) { var query = new PathAndQueryBuilder("/ParseUniversalCorrectionDocumentSellerTitleXml"); query.AddParameter("documentVersion", DefaultDocumentVersions.Ucd); return PerformHttpRequest<UniversalCorrectionDocumentSellerTitleInfo>(null, "POST", query.BuildPathAndQuery(), xmlContent); } public UniversalTransferDocumentBuyerTitleInfo ParseUniversalCorrectionDocumentBuyerTitleXml(byte[] xmlContent) { return PerformHttpRequest<UniversalTransferDocumentBuyerTitleInfo>(null, "POST", "/ParseUniversalCorrectionDocumentBuyerTitleXml", xmlContent); } } }
45.085714
161
0.82256
[ "MIT" ]
kostghost/diadocsdk-csharp
src/DiadocHttpApi.UniversalTransferDocument.cs
3,158
C#
/* The MIT License (MIT) Copyright (c) 2016 Roaring Fangs Entertainment Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using UnityEngine; namespace RoaringFangs.Motion { [RequireComponent(typeof(BouncyMove))] public class BouncyFollower : MonoBehaviour, ISerializationCallbackReceiver { [SerializeField] private BouncyMove _BouncyMove; [SerializeField] private Transform _Target; public Transform Target { get { return _Target; } set { _Target = value; } } public void OnAfterDeserialize() { } public void OnBeforeSerialize() { _BouncyMove = _BouncyMove ?? GetComponent<BouncyMove>(); } void Update() { _BouncyMove.TargetPositionWorld = Target.position; } } }
31.948276
79
0.711819
[ "MIT" ]
Tarocco/roaring-fangs-unity
Source/RoaringFangs/Motion/BouncyFollower.cs
1,855
C#
using System.IO; using NiDump; namespace SMPEditor { public static class NifFileEx { public static string GetNiNodeName(this NiHeader hdr,int id) { try { int typeIndex = hdr.GetBlockTypeIdxByName("NiNode"); } catch (System.Exception) { return ""; } //Console.WriteLine("BT idx 'NiNode': {0}", bt_NiNode); if (id >= hdr.blocks.Length) return ""; return hdr.strings[hdr.GetObject<NiNode>(id).name]; } } }
23.76
68
0.491582
[ "MIT" ]
Yu5h1/Skyrim-SMPdocEditor
SMPEditor/SMPEditor/NifFileEx.cs
596
C#
namespace MassTransit.RabbitMqTransport.Tests { using System; using System.Threading.Tasks; using NUnit.Framework; using ObserverableMessages; namespace ObserverableMessages { class SomethingHappened { public string Caption { get; set; } } } [TestFixture] public class Publishing_messages_with_an_observer : RabbitMqTestFixture { [Test] public async Task Should_be_received() { await Bus.Publish(new SomethingHappened {Caption = "System Screw Up"}); await _observer.Received; } EventObserver _observer; protected override void ConfigureRabbitMqReceiveEndpoint(IRabbitMqReceiveEndpointConfigurator configurator) { _observer = new EventObserver(GetTask<SomethingHappened>()); configurator.Observer(_observer); } class EventObserver : IObserver<ConsumeContext<SomethingHappened>> { readonly TaskCompletionSource<SomethingHappened> _completed; public EventObserver(TaskCompletionSource<SomethingHappened> completed) { _completed = completed; } public Task<SomethingHappened> Received => _completed.Task; public void OnNext(ConsumeContext<SomethingHappened> context) { _completed.TrySetResult(context.Message); } public void OnError(Exception error) { } public void OnCompleted() { } } } }
25.41791
116
0.574281
[ "ECL-2.0", "Apache-2.0" ]
Aerodynamite/MassTrans
tests/MassTransit.RabbitMqTransport.Tests/Observer_Specs.cs
1,705
C#
using MagicalLifeAPI.Networking.Client; using MagicalLifeGUIWindows.GUI.Reusable; using Microsoft.Xna.Framework; using MonoGame.Extended.Input.InputListeners; namespace MagicalLifeGUIWindows.GUI.MainMenu.Buttons { public class NewGameButton : MonoButton { public NewGameButton() : base("MenuButton", GetLocation(), true, "New Game") { } public override void Click(MouseEventArgs e) { New_World_Menu.NewWorldMenu.Initialize(); ClientSendRecieve.Initialize(new MagicalLifeAPI.Networking.NetworkSettings(MagicalLifeAPI.Networking.EngineMode.ServerAndClient)); } public override void DoubleClick(MouseEventArgs e) { } private static Rectangle GetLocation() { int width = MainMenuLayout.ButtonWidth; int height = MainMenuLayout.ButtonHeight; int x = MainMenuLayout.ButtonX; int y = MainMenuLayout.NewGameButtonY; return new Rectangle(x, y, width, height); } public string GetTextureName() { return "MenuButton"; } } }
29.410256
142
0.646905
[ "MIT" ]
Batarian711/MagicalLife
MagicalLifeGUIWindows/GUI/MainMenu/Buttons/NewGameButton.cs
1,149
C#
using Lidgren.Network; using LmpCommon.Enums; using LmpCommon.Message.Types; namespace LmpCommon.Message.Data.Admin { public class AdminReplyMsgData : AdminBaseMsgData { /// <inheritdoc /> internal AdminReplyMsgData() { } public override AdminMessageType AdminMessageType => AdminMessageType.Reply; public AdminResponse Response; public override string ClassName { get; } = nameof(AdminReplyMsgData); internal override void InternalSerialize(NetOutgoingMessage lidgrenMsg) { base.InternalSerialize(lidgrenMsg); lidgrenMsg.Write((int)Response); } internal override void InternalDeserialize(NetIncomingMessage lidgrenMsg) { base.InternalDeserialize(lidgrenMsg); Response = (AdminResponse)lidgrenMsg.ReadInt32(); } internal override int InternalGetMessageSize() { return base.InternalGetMessageSize() + sizeof(AdminResponse); } } }
29.970588
84
0.667321
[ "MIT" ]
211network/LunaMultiplayer
LmpCommon/Message/Data/Admin/AdminResponseMsgData.cs
1,021
C#
using MySqlConnector; using RepoDb.Interfaces; using System.Data; namespace RepoDb.Resolvers { /// <summary> /// A class used to resolve the <see cref="DbType"/> into its equivalent database string name. /// </summary> public class MySqlConnectorDbTypeToMySqlStringNameResolver : IResolver<MySqlDbType, string> { /// <summary> /// Returns the equivalent <see cref="DbType"/> of the .NET CLR Types. /// </summary> /// <param name="dbType">The type of the database.</param> /// <returns>The equivalent string name.</returns> public virtual string Resolve(MySqlDbType dbType) { /* Id (System.Int64) ColumnVarchar (System.String) ColumnInt (System.Int32) ColumnDecimal2 (System.Decimal) ColumnDateTime (System.DateTime) ColumnBlob (System.Byte[]) ColumnBlobAsArray (System.Byte[]) ColumnBinary (System.Byte[]) ColumnLongBlob (System.Byte[]) ColumnMediumBlob (System.Byte[]) ColumnTinyBlob (System.Byte[]) ColumnVarBinary (System.Byte[]) ColumnDate (System.DateTime) ColumnDateTime2 (System.DateTime) ColumnTime (System.TimeSpan) ColumnTimeStamp (System.DateTime) ColumnYear (System.Int16) ColumnGeometry (System.Byte[]) ColumnLineString (System.Byte[]) ColumnMultiLineString (System.Byte[]) ColumnMultiPoint (System.Byte[]) ColumnMultiPolygon (System.Byte[]) ColumnPoint (System.Byte[]) ColumnPolygon (System.Byte[]) ColumnBigint (System.Int64) ColumnDecimal (System.Decimal) ColumnDouble (System.Double) ColumnFloat (System.Single) ColumnInt2 (System.Int32) ColumnMediumInt (System.Int32) ColumnReal (System.Double) ColumnSmallInt (System.Int16) ColumnTinyInt (System.SByte) ColumnChar (System.String) ColumnJson (System.String) ColumnNChar (System.String) ColumnNVarChar (System.String) ColumnLongText (System.String) ColumnMediumText (System.String) ColumnText (System.String) ColumnTinyText (System.String) ColumnBit (System.UInt64) */ return dbType switch { MySqlDbType.Binary => "BINARY", MySqlDbType.Bit => "BIT", MySqlDbType.Blob => "BLOB", MySqlDbType.Byte or MySqlDbType.UByte => "TINYINT", MySqlDbType.Date => "DATE", MySqlDbType.DateTime => "DATETIME", MySqlDbType.Decimal => "DECIMAL", MySqlDbType.Double => "DOUBLE", MySqlDbType.Enum or MySqlDbType.Guid or MySqlDbType.Set or MySqlDbType.Text => "TEXT", MySqlDbType.Float => "FLOAT", MySqlDbType.Geometry => "GEOMETRY", MySqlDbType.Int16 or MySqlDbType.Int24 or MySqlDbType.UInt24 or MySqlDbType.UInt16 => "SMALLINT", MySqlDbType.Int32 or MySqlDbType.UInt32 => "INT", MySqlDbType.Int64 or MySqlDbType.UInt64 => "BIGINT", MySqlDbType.JSON => "JSON", MySqlDbType.LongBlob => "LONGBLOB", MySqlDbType.LongText => "LONGTEXT", MySqlDbType.MediumBlob => "MEDIUMBLOB", MySqlDbType.MediumText => "MEDIUMTEXT", MySqlDbType.Newdate => "DATE", MySqlDbType.NewDecimal => "DECIMAL", MySqlDbType.String => "STRING", MySqlDbType.Time => "TIME", MySqlDbType.Timestamp => "TIMESTAMP", MySqlDbType.TinyBlob => "TINYBLOB", MySqlDbType.TinyText => "TINYTEXT", MySqlDbType.VarBinary => "VARBINARY", MySqlDbType.VarChar => "VARCHAR", MySqlDbType.VarString => "VARCHAR", MySqlDbType.Year => "YEAR", _ => "TEXT", }; } } }
42.08
113
0.557747
[ "Apache-2.0" ]
aTiKhan/RepoDb
RepoDb.MySqlConnector/RepoDb.MySqlConnector/Resolvers/MySqlConnectorDbTypeToMySqlStringNameResolver.cs
4,210
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.HybridCompute.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// Instance view status. /// </summary> public partial class MachineExtensionInstanceViewStatus { /// <summary> /// Initializes a new instance of the /// MachineExtensionInstanceViewStatus class. /// </summary> public MachineExtensionInstanceViewStatus() { CustomInit(); } /// <summary> /// Initializes a new instance of the /// MachineExtensionInstanceViewStatus class. /// </summary> /// <param name="code">The status code.</param> /// <param name="level">The level code. Possible values include: /// 'Info', 'Warning', 'Error'</param> /// <param name="displayStatus">The short localizable label for the /// status.</param> /// <param name="message">The detailed status message, including for /// alerts and error messages.</param> /// <param name="time">The time of the status.</param> public MachineExtensionInstanceViewStatus(string code = default(string), string level = default(string), string displayStatus = default(string), string message = default(string), System.DateTime? time = default(System.DateTime?)) { Code = code; Level = level; DisplayStatus = displayStatus; Message = message; Time = time; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets the status code. /// </summary> [JsonProperty(PropertyName = "code")] public string Code { get; private set; } /// <summary> /// Gets the level code. Possible values include: 'Info', 'Warning', /// 'Error' /// </summary> [JsonProperty(PropertyName = "level")] public string Level { get; private set; } /// <summary> /// Gets the short localizable label for the status. /// </summary> [JsonProperty(PropertyName = "displayStatus")] public string DisplayStatus { get; private set; } /// <summary> /// Gets the detailed status message, including for alerts and error /// messages. /// </summary> [JsonProperty(PropertyName = "message")] public string Message { get; private set; } /// <summary> /// Gets the time of the status. /// </summary> [JsonProperty(PropertyName = "time")] public System.DateTime? Time { get; private set; } } }
34.527473
237
0.594526
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/hybridcompute/Microsoft.Azure.Management.HybridCompute/src/Generated/Models/MachineExtensionInstanceViewStatus.cs
3,142
C#
using StackExchange.Redis; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RedisBlue.Models { internal class ExpressionContext { public ExpressionContext(IDatabaseAsync db, string collectionName, string partitionKey, TypeCacheInfo typeInfo, IndexedCollection collection) { Db = db; CollectionName = collectionName; PartitionKey = partitionKey; TypeInfo = typeInfo; Collection = collection; } public IDatabaseAsync Db { get; set; } public string CollectionName { get; set; } public string PartitionKey { get; set; } public TypeCacheInfo TypeInfo { get; set; } public IndexedCollection Collection { get; set; } } }
29.642857
149
0.663855
[ "MIT" ]
danielgerlag/redisblue
RedisBlue/Models/ExpressionContext.cs
832
C#
using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Options; using System.Linq; using TrafficComet.Core.Configs; namespace TrafficComet.Core.Extensions { public static class OptionsExtensions { public static bool IgnoreRequest<TMiddlewareConfig>(this IOptionsSnapshot<TMiddlewareConfig> optionsSnapshot, PathString requestPath) where TMiddlewareConfig : BaseMiddlewareConfig, new() { if (optionsSnapshot?.Value?.StopLogging ?? false) return true; if (requestPath.HasValue) { if (requestPath.Value.Contains(".") && !optionsSnapshot.Value.StartLoggingFileRequest) return true; if (optionsSnapshot != null && optionsSnapshot != null) { if (optionsSnapshot.Value.StopLogging) return true; if (!optionsSnapshot.Value.IgnoreUrls.SafeAny()) return false; return optionsSnapshot.Value.IgnoreUrls.Contains(requestPath.Value); } return false; } return true; } } }
32.972222
135
0.587195
[ "Apache-2.0" ]
maciur/TrafficComet
TrafficComet.Core/Extensions/OptionsExtensions.cs
1,189
C#
using Microsoft.AspNetCore.Mvc.Rendering; namespace Ding.Ui.Services { /// <summary> /// 组件服务 /// </summary> public class UiServiceBase<TModel> : IContext<TModel> { /// <summary> /// 初始化组件服务 /// </summary> /// <param name="helper">HtmlHelper</param> public UiServiceBase( IHtmlHelper<TModel> helper ) { Helper = helper; } /// <summary> /// HtmlHelper /// </summary> public IHtmlHelper<TModel> Helper { get; } } }
24
60
0.534091
[ "MIT" ]
EnhWeb/DC.Framework
src/Ding.Ui.Core/Services/UiServiceBase.cs
552
C#
using System.ComponentModel.DataAnnotations; using DynamicVML; namespace Tests { public class NestedRoot { public int Id { get; set; } public string SomePropertyR { get; set; } public virtual DynamicList<NestedA> Children { get; set; } public NestedRoot(int nA, int nB, int nC) { this.Children = new DynamicList<NestedA>("R"); for (int i = 0; i < nA; i++) { var a = new NestedA(); a.Children = new DynamicList<NestedB>("A"); a.SomePropertyA = $"a: {i}"; for (int j = 0; j < nB; j++) { var b = new NestedB(); b.Children = new DynamicList<NestedC>("B"); b.SomePropertyB = $"a: {i} b: {j}"; for (int k = 0; k < nC; k++) { var c = new NestedC(); c.SomePropertyC = $"a: {i} b: {j} c: {k}"; b.Children.Add(c, m => m.Index = "B" + k); } a.Children.Add(b, m => m.Index = "A" + j); } this.Children.Add(a, m => m.Index = "R" + i); } } } public class NestedA { public string SomePropertyA { get; set; } public virtual DynamicList<NestedB> Children { get; set; } = new DynamicList<NestedB>(); } public class NestedB { public string SomePropertyB { get; set; } public virtual DynamicList<NestedC> Children { get; set; } = new DynamicList<NestedC>(); } public class NestedC { public string SomePropertyC { get; set; } } }
27.046875
96
0.456384
[ "MIT" ]
cesarsouza/dvml
tests/ViewModels/NestedRoot.cs
1,733
C#
using System; namespace R5T.D0116.X001 { /// <summary> /// Recommended extensions. /// </summary> public static class Documentation { } }
13.583333
37
0.595092
[ "MIT" ]
SafetyCone/R5T.D0116
source/R5T.D0116.X001/Code/Documentation.cs
163
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.SQLite; using Microsoft.CodeAnalysis.Storage; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.WorkspaceServices { /// <remarks> /// Tests are inherited from <see cref="AbstractPersistentStorageTests"/>. That way we can /// write tests once and have them run against all <see cref="IPersistentStorageService"/> /// implementations. /// </remarks> public class SQLitePersistentStorageTests : AbstractPersistentStorageTests { internal override AbstractPersistentStorageService GetStorageService(IPersistentStorageLocationService locationService, IPersistentStorageFaultInjector faultInjector) => new SQLitePersistentStorageService(locationService, faultInjector); [Fact] public async Task TestCrashInNewConnection() { var solution = CreateOrOpenSolution(nullPaths: true); var hitInjector = false; var faultInjector = new PersistentStorageFaultInjector( onNewConnection: () => { hitInjector = true; throw new Exception(); }, onFatalError: e => throw e); // Because instantiating the connection will fail, we will not get back // a working persistent storage. using (var storage = GetStorage(solution, faultInjector)) using (var memStream = new MemoryStream()) using (var streamWriter = new StreamWriter(memStream)) { streamWriter.WriteLine("contents"); streamWriter.Flush(); memStream.Position = 0; await storage.WriteStreamAsync("temp", memStream); var readStream = await storage.ReadStreamAsync("temp"); // Because we don't have a real storage service, we should get back // null even when trying to read something we just wrote. Assert.Null(readStream); } Assert.True(hitInjector); // Ensure we don't get a crash due to SqlConnection's finalizer running. for (var i = 0; i < 10; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } } private class PersistentStorageFaultInjector : IPersistentStorageFaultInjector { private readonly Action _onNewConnection; private readonly Action<Exception> _onFatalError; public PersistentStorageFaultInjector( Action onNewConnection = null, Action<Exception> onFatalError = null) { _onNewConnection = onNewConnection; _onFatalError = onFatalError; } public void OnNewConnection() => _onNewConnection?.Invoke(); public void OnFatalError(Exception ex) => _onFatalError?.Invoke(ex); } } }
37.556818
174
0.616339
[ "MIT" ]
douglasg14b/roslyn
src/VisualStudio/CSharp/Test/PersistentStorage/SQLitePersistentStorageTests.cs
3,307
C#
using Shared.Core.Dtos; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Shared.Core.Services { public interface ICheckedListReaderService<T> where T : CheckedDto { List<T> ReadCheckedDto(Guid id); } }
20.066667
70
0.740864
[ "Apache-2.0" ]
MurielSoftware/MyArt
Shared.Core/Services/ICheckedListReaderService.cs
303
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace P01_HospitalDatabase.Data.Models { public class Doctor { [Key] public int DoctorId { get; set; } [Required] [MaxLength(100)] public string Name { get; set; } [Required] [MaxLength(100)] public string Specialty { get; set; } public ICollection<Visitation> Visitations { get; set; } } }
21.045455
64
0.613391
[ "MIT" ]
nikistoianov/CSharp-DB-Fundamentals-Homeworks
Database Advanced - Entity Framework/04.CodeFirst/P01_HospitalDatabase/Data/Models/Doctor.cs
465
C#
namespace ClearHl7.Codes.V282 { /// <summary> /// HL7 Version 2 Table 0396 - Coding System. /// </summary> /// <remarks>https://www.hl7.org/fhir/v2/0396</remarks> public enum CodeCodingSystem { /// <summary> /// 99zzz - Local general code where z is an alphanumeric character. /// </summary> LocalGeneralCode99Zzz, /// <summary> /// ACR - American College of Radiology finding codes. /// </summary> AmericanCollegeOfRadiologyFindingCodes, /// <summary> /// ACTCODE - Table of HL7 Version 3 ActCode values. /// </summary> Hl7Version3ActcodeValues, /// <summary> /// ACTRELSS - Used to indicate that the target of the relationship will be a filtered subset of the total related set of targets. Used when there is a need to limit the number of components to the first, the last, the next, the total, the average or some other filtere. /// </summary> FilteredSubset, /// <summary> /// ALPHAID2006 - German Alpha-ID v2006. /// </summary> GermanAlphaIdV2006, /// <summary> /// ALPHAID2007 - German Alpha-ID v2007. /// </summary> GermanAlphaIdV2007, /// <summary> /// ALPHAID2008 - German Alpha-ID v2008. /// </summary> GermanAlphaIdV2008, /// <summary> /// ALPHAID2009 - German Alpha-ID v2009. /// </summary> GermanAlphaIdV2009, /// <summary> /// ALPHAID2010 - German Alpha-ID v2010. /// </summary> GermanAlphaIdV2010, /// <summary> /// ALPHAID2011 - German Alpha-ID v2011. /// </summary> GermanAlphaIdV2011, /// <summary> /// ALPHAID2012 - German Alpha-ID v2012. /// </summary> GermanAlphaIdV2012, /// <summary> /// ALPHAID2013 - German Alpha-ID v2013. /// </summary> GermanAlphaIdV2013, /// <summary> /// ALPHAID2014 - German Alpha-ID v2014. /// </summary> GermanAlphaIdV2014, /// <summary> /// ALPHAID2015 - German Alpha-ID v2015. /// </summary> GermanAlphaIdV2015, /// <summary> /// ALPHAID2016 - German Alpha-ID v2016. /// </summary> GermanAlphaIdV2016, /// <summary> /// AMTv2 - Australian Medicines Terminology (v2). /// </summary> AustralianMedicinesTerminologyV2, /// <summary> /// ANS+ - HL7 set of units of measure. /// </summary> Hl7SetOfUnitsOfMeasure, /// <summary> /// ART - WHO Adverse Reaction Terms. /// </summary> WhoAdverseReactionTerms, /// <summary> /// AS4 - ASTM E1238/ E1467 Universal. /// </summary> AstmE1238E1467Universal, /// <summary> /// AS4E - AS4 Neurophysiology Codes. /// </summary> As4NeurophysiologyCodes, /// <summary> /// ATC - American Type Culture Collection. /// </summary> AmericanTypeCultureCollection, /// <summary> /// C4 - CPT-4. /// </summary> Cpt4, /// <summary> /// CAPECC - College of American Pathologists Electronic Cancer Checklist. /// </summary> CollegeOfAmericanPathologistsElectronicCancerChecklist, /// <summary> /// CAS - Chemical abstract codes. /// </summary> ChemicalAbstractCodes, /// <summary> /// CCC - Clinical Care Classification system. /// </summary> ClinicalCareClassificationSystem, /// <summary> /// CD2 - CDT-2 Codes. /// </summary> Cdt2Codes, /// <summary> /// CDCA - CDC Analyte Codes. /// </summary> CdcAnalyteCodes, /// <summary> /// CDCEDACUITY - CDC Emergency Department Acuity. /// </summary> CdcEmergencyDepartmentAcuity, /// <summary> /// cdcgs1vis - VIS Bar Codes (IIS). /// </summary> VisBarCodesIis, /// <summary> /// CDCM - CDC Methods/Instruments Codes. /// </summary> CdcMethodsInstrumentsCodes, /// <summary> /// CDCNHSN - CDC National Healthcare Safety Network Codes. /// </summary> CdcNationalHealthcareSafetyNetworkCodes, /// <summary> /// CDCOBS - CDC BioSense RT observations (Census) - CDC. /// </summary> CdcBiosenseRtObservationsCensusCdc, /// <summary> /// CDCPHINVS - CDC PHIN Vocabulary Coding System. /// </summary> CdcPhinVocabularyCodingSystem, /// <summary> /// CDCREC - Race Ethnicity - CDC. /// </summary> RaceEthnicityCdc, /// <summary> /// CDS - CDC Surveillance. /// </summary> CdcSurveillance, /// <summary> /// CE (obsolete) - CEN ECG diagnostic codes. /// </summary> CenEcgDiagnosticCodes, /// <summary> /// CLP - CLIP. /// </summary> Clip, /// <summary> /// CPTM - CPT Modifier Code. /// </summary> CptModifierCode, /// <summary> /// CST - COSTART. /// </summary> Costart, /// <summary> /// CVX - CDC Vaccine Codes. /// </summary> CdcVaccineCodes, /// <summary> /// DCM - DICOM Controlled Terminology. /// </summary> DicomControlledTerminology, /// <summary> /// E - EUCLIDES. /// </summary> Euclides, /// <summary> /// E5 - Euclides quantity codes. /// </summary> EuclidesQuantityCodes, /// <summary> /// E6 - Euclides Lab method codes. /// </summary> EuclidesLabMethodCodes, /// <summary> /// E7 - Euclides Lab equipment codes. /// </summary> EuclidesLabEquipmentCodes, /// <summary> /// EDLEVEL - Education Level. /// </summary> EducationLevel, /// <summary> /// ENTITYCODE - Entity Code. /// </summary> EntityCode, /// <summary> /// ENTITYHDLG - Entity Handling Code. /// </summary> EntityHandlingCode, /// <summary> /// ENZC - Enzyme Codes. /// </summary> EnzymeCodes, /// <summary> /// EPASRS - EPA SRS. /// </summary> EpaSrs, /// <summary> /// FDAUDI - FDA Unique Device Identifier. /// </summary> FdaUniqueDeviceIdentifier, /// <summary> /// FDAUNII - Unique Ingredient Identifier (UNII). /// </summary> UniqueIngredientIdentifierUnii, /// <summary> /// FDDC - First DataBank Drug Codes. /// </summary> FirstDatabankDrugCodes, /// <summary> /// FDDX - First DataBank Diagnostic Codes. /// </summary> FirstDatabankDiagnosticCodes, /// <summary> /// FDK - FDA K10. /// </summary> FdaK10, /// <summary> /// FIPS5_2 - FIPS 5-2 (State). /// </summary> Fips52State, /// <summary> /// FIPS6_4 - FIPS 6-4 (County). /// </summary> Fips64County, /// <summary> /// GDRG2004 - G-DRG German DRG Codes v2004. /// </summary> GDrgGermanDrgCodesV2004, /// <summary> /// GDRG2005 - G-DRG German DRG Codes v2005. /// </summary> GDrgGermanDrgCodesV2005, /// <summary> /// GDRG2006 - G-DRG German DRG Codes v2006. /// </summary> GDrgGermanDrgCodesV2006, /// <summary> /// GDRG2007 - G-DRG German DRG Codes v2007. /// </summary> GDrgGermanDrgCodesV2007, /// <summary> /// GDRG2008 - G-DRG German DRG Codes v2008. /// </summary> GDrgGermanDrgCodesV2008, /// <summary> /// GDRG2009 - G-DRG German DRG Codes v2009. /// </summary> GDrgGermanDrgCodesV2009, /// <summary> /// GMDC2004 - German Major Diagnostic Codes v2004. /// </summary> GermanMajorDiagnosticCodesV2004, /// <summary> /// GMDC2005 - German Major Diagnostic Codes v2005. /// </summary> GermanMajorDiagnosticCodesV2005, /// <summary> /// GMDC2006 - German Major Diagnostic Codes v2006. /// </summary> GermanMajorDiagnosticCodesV2006, /// <summary> /// GMDC2007 - German Major Diagnostic Codes v2007. /// </summary> GermanMajorDiagnosticCodesV2007, /// <summary> /// GMDC2008 - German Major Diagnostic Codes v2008. /// </summary> GermanMajorDiagnosticCodesV2008, /// <summary> /// GMDC2009 - German Major Diagnostic Codes v2009. /// </summary> GermanMajorDiagnosticCodesV2009, /// <summary> /// GS1UDI - GS1 Unique Device Identifier. /// </summary> Gs1UniqueDeviceIdentifier, /// <summary> /// HB - HIBCC. /// </summary> Hibcc, /// <summary> /// HCPCS - CMS (formerly HCFA) Common Procedure Coding System. /// </summary> CmsFormerlyHcfaCommonProcedureCodingSystem, /// <summary> /// HCPT - Health Care Provider Taxonomy. /// </summary> HealthCareProviderTaxonomy, /// <summary> /// HHC - Home Health Care. /// </summary> HomeHealthCare, /// <summary> /// HI - Health Outcomes. /// </summary> HealthOutcomes, /// <summary> /// HIBUDI - HIBCC Unique Device Identifier. /// </summary> HibccUniqueDeviceIdentifier, /// <summary> /// HL7nnnn - HL7 Defined Codes where nnnn is the HL7 table number. /// </summary> Hl7DefinedCodesWhereNnnnIsTheHl7TableNumber, /// <summary> /// HOT - Japanese Nationwide Medicine Code. /// </summary> JapaneseNationwideMedicineCode, /// <summary> /// HPC - CMS (formerly HCFA )Procedure Codes (HCPCS). /// </summary> CmsFormerlyHcfaProcedureCodesHcpcs, /// <summary> /// HSLOC - Healthcare Service Location. /// </summary> HealthcareServiceLocation, /// <summary> /// I10 - ICD-10. /// </summary> Icd10, /// <summary> /// I10C - International Classification of Diseases, 10th Revision, Clinical Modification (ICD-10-CM). /// </summary> Icd10ClinicalModification, /// <summary> /// I10G2004 - ICD 10 Germany 2004. /// </summary> Icd10Germany2004, /// <summary> /// I10G2005 - ICD 10 Germany 2005. /// </summary> Icd10Germany2005, /// <summary> /// I10G2006 - ICD 10 Germany 2006. /// </summary> Icd10Germany2006, /// <summary> /// I10P - ICD-10 Procedure Codes. /// </summary> Icd10ProcedureCodes, /// <summary> /// I9 - ICD9. /// </summary> Icd9, /// <summary> /// I9C - ICD-9CM. /// </summary> Icd9Cm, /// <summary> /// I9CDX - ICD-9CM Diagnosis codes. /// </summary> Icd9CmDiagnosisCodes, /// <summary> /// I9CP - ICD-9CM Procedure codes. /// </summary> Icd9CmProcedureCodes, /// <summary> /// IBT - ISBT. /// </summary> Isbt, /// <summary> /// IBT0001 - ISBT 128 Standard transfusion/transplantation data items. /// </summary> Isbt128StandardTransfusionTransplantationDataItems, /// <summary> /// IBTnnnn - ISBT 128 codes where nnnn specifies a specific table within ISBT 128.. /// </summary> Isbt128Codes, /// <summary> /// IC2 - ICHPPC-2. /// </summary> Ichppc2, /// <summary> /// ICCUDI - ICCBBA Unique Device Identifier. /// </summary> IccbbaUniqueDeviceIdentifier, /// <summary> /// ICD10AM - ICD-10 Australian modification. /// </summary> Icd10AustralianModification, /// <summary> /// ICD10CA - ICD-10 Canada. /// </summary> Icd10Canada, /// <summary> /// ICD10GM2007 - ICD 10 Germany v2007. /// </summary> Icd10GermanyV2007, /// <summary> /// ICD10GM2008 - ICD 10 Germany v2008. /// </summary> Icd10GermanyV2008, /// <summary> /// ICD10GM2009 - ICD 10 Germany v2009. /// </summary> Icd10GermanyV2009, /// <summary> /// ICD10GM2010 - ICD 10 Germany v2010. /// </summary> Icd10GermanyV2010, /// <summary> /// ICD10GM2011 - ICD 10 Germany v2011. /// </summary> Icd10GermanyV2011, /// <summary> /// ICD10GM2012 - ICD 10 Germany v2012. /// </summary> Icd10GermanyV2012, /// <summary> /// ICD10GM2013 - ICD 10 Germany v2013. /// </summary> Icd10GermanyV2013, /// <summary> /// ICD10GM2014 - ICD 10 Germany v2014. /// </summary> Icd10GermanyV2014, /// <summary> /// ICD10GM2015 - ICD 10 Germany v2015. /// </summary> Icd10GermanyV2015, /// <summary> /// ICD10GM2016 - ICD 10 Germany v2016. /// </summary> Icd10GermanyV2016, /// <summary> /// ICDO - International Classification of Diseases for Oncology. /// </summary> IcdForOncology, /// <summary> /// ICDO2 - International Classification of Disease for Oncology Second Edition. /// </summary> IcdForOncologySecondEdition, /// <summary> /// ICDO3 - International Classification of Disease for Oncology Third Edition. /// </summary> IcdForOncologyThirdEdition, /// <summary> /// ICF - International Classification of Functioning, Disability and Health (ICF). /// </summary> Icf, /// <summary> /// ICS - ICCS. /// </summary> Iccs, /// <summary> /// ICSD - International Classification of Sleep Disorders. /// </summary> Icsd, /// <summary> /// IHELAW - IHE Laboratory Analytical Workflow (LAW) Profile Codes.. /// </summary> LaboratoryAnalyticalWorkflowCode, /// <summary> /// ISO - ISO 2955.83 (units of measure) with HL7 extensions. /// </summary> Iso295583UnitsOfMeasure, /// <summary> /// ISO3166_1 - ISO 3166-1 Country Codes. /// </summary> Iso31661CountryCodes, /// <summary> /// ISO3166_2 - ISO 3166-2 Country subdivisions. /// </summary> Iso31662CountrySubdivisions, /// <summary> /// ISO4217 - ISO4217 Currency Codes. /// </summary> Iso4217CurrencyCodes, /// <summary> /// ISO639 - ISO 639 Language. /// </summary> Iso639Language, /// <summary> /// ISOnnnn (deprecated) - ISO Defined Codes where nnnn is the ISO table number. /// </summary> IsoDefinedCodes, /// <summary> /// ITIS - Integrated Taxonomic Information System. /// </summary> IntegratedTaxonomicInformationSystem, /// <summary> /// IUPC - IUPAC/IFCC Component Codes. /// </summary> IupacIfccComponentCodes, /// <summary> /// IUPP - IUPAC/IFCC Property Codes. /// </summary> IupacIfccPropertyCodes, /// <summary> /// JC10 - JLAC/JSLM, nationwide laboratory code. /// </summary> JlacJslmNationwideLaboratoryCode, /// <summary> /// JC8 - Japanese Chemistry. /// </summary> JapaneseChemistry, /// <summary> /// JJ1017 - Japanese Image Examination Cache. /// </summary> JapaneseImageExaminationCache, /// <summary> /// L - Local general code. /// </summary> LocalGeneralCodeL, /// <summary> /// LANGUAL - LanguaL. /// </summary> Langual, /// <summary> /// LB - Local billing code. /// </summary> LocalBillingCode, /// <summary> /// LN - Logical Observation Identifier Names and Codes (LOINCA). /// </summary> LogicalObservationIdentifierNamesAndCodesLoinc, /// <summary> /// MCD - Medicaid. /// </summary> Medicaid, /// <summary> /// MCR - Medicare. /// </summary> Medicare, /// <summary> /// MDC - Medical Device Communication. /// </summary> MedicalDeviceCommunication, /// <summary> /// MDDX - Medispan Diagnostic Codes. /// </summary> MedispanDiagnosticCodes, /// <summary> /// MEDC - Medical Economics Drug Codes. /// </summary> MedicalEconomicsDrugCodes, /// <summary> /// MEDIATYPE - MIME Media Type IANA. /// </summary> MimeMediaTypeIana, /// <summary> /// MEDR - Medical Dictionary for Drug Regulatory Affairs (MEDDRA). /// </summary> MedicalDictionaryForDrugRegulatoryAffairs, /// <summary> /// MEDX - Medical Economics Diagnostic Codes. /// </summary> MedicalEconomicsDiagnosticCodes, /// <summary> /// MGPI - Medispan GPI. /// </summary> MedispanGpi, /// <summary> /// MVX - CDC Vaccine Manufacturer Codes. /// </summary> CdcVaccineManufacturerCodes, /// <summary> /// NAICS - Industry (NAICS). /// </summary> IndustryNaics, /// <summary> /// NCPDPnnnnsss - NCPDP code list for data element nnnn [as used in segment sss]. /// </summary> NcpdpCodeListForDataElement, /// <summary> /// NDA - NANDA. /// </summary> Nanda, /// <summary> /// NDC - National drug codes. /// </summary> NationalDrugCodes, /// <summary> /// NDFRT - NDF-RT (Drug Classification). /// </summary> NdfRtDrugClassification, /// <summary> /// NIC - Nursing Interventions Classification. /// </summary> NursingInterventionsClassification, /// <summary> /// NIP001 - Source of Information (Immunization). /// </summary> SourceOfInformationImmunization, /// <summary> /// NIP002 - Substance refusal reason. /// </summary> SubstanceRefusalReason, /// <summary> /// NIP004 - Vaccination - Contraindications, Precautions, and Immunities. /// </summary> Vaccination, /// <summary> /// NIP007 - Vaccinated at location (facility). /// </summary> VaccinatedAtLocationFacility, /// <summary> /// NIP008 - Vaccine purchased with (Type of funding). /// </summary> VaccinePurchasedWithFunding, /// <summary> /// NIP009 - Reported adverse event previously. /// </summary> ReportedAdverseEventPreviously, /// <summary> /// NIP010 - VAERS Report type. /// </summary> VaersReportType, /// <summary> /// NND - Notifiable Event (Disease/Condition) Code List. /// </summary> NotifiableEventDiseaseConditionCodeList, /// <summary> /// NPI - National Provider Identifier. /// </summary> NationalProviderIdentifier, /// <summary> /// NUBC - National Uniform Billing Committee. /// </summary> NationalUniformBillingCommittee, /// <summary> /// NULLFL - Null Flavor. /// </summary> NullFlavor, /// <summary> /// O301 - German Procedure Codes. /// </summary> GermanProcedureCodes, /// <summary> /// O3012004 - OPS Germany v2004. /// </summary> OpsGermanyV2004, /// <summary> /// O3012005 - OPS Germany v2005. /// </summary> OpsGermanyV2005, /// <summary> /// O3012006 - OPS Germany v2006. /// </summary> OpsGermanyV2006, /// <summary> /// OBSMETHOD - Observation Method Code. /// </summary> ObservationMethodCode, /// <summary> /// OHA - Omaha System. /// </summary> OmahaSystem, /// <summary> /// OPS2007 - OPS Germany v2007. /// </summary> OpsGermanyV2007, /// <summary> /// OPS2008 - OPS Germany v2008. /// </summary> OpsGermanyV2008, /// <summary> /// OPS2009 - OPS Germany v2009. /// </summary> OpsGermanyV2009, /// <summary> /// OPS2010 - OPS Germany v2010. /// </summary> OpsGermanyV2010, /// <summary> /// OPS2011 - OPS Germany v2011. /// </summary> OpsGermanyV2011, /// <summary> /// OPS2012 - OPS Germany v2012. /// </summary> OpsGermanyV2012, /// <summary> /// OPS2013 - OPS Germany v2013. /// </summary> OpsGermanyV2013, /// <summary> /// OPS2014 - OPS Germany v2014. /// </summary> OpsGermanyV2014, /// <summary> /// OPS2015 - OPS Germany v2015. /// </summary> OpsGermanyV2015, /// <summary> /// OPS2016 - OPS Germany v2016. /// </summary> OpsGermanyV2016, /// <summary> /// PHDSCSOPT - Source of Payment Typology. /// </summary> SourceOfPaymentTypology, /// <summary> /// PHINQUESTION - CDC Public Health Information Network (PHIN) Question. /// </summary> CdcPublicHealthInformationNetworkQuestion, /// <summary> /// PLR - CDC PHLIP Lab result codes that are not covered in SNOMED at the time of this implementation. /// </summary> CdcPhlipLabResultCodes, /// <summary> /// PLT - CDC PHLIP Lab test codes, where LOINC concept is too broad or not yet available, especially as needed for ordering and or lab to lab reporting ). /// </summary> CdcPhlipLabTestCodes, /// <summary> /// POS - POS Codes. /// </summary> PosCodes, /// <summary> /// PRTCPTNMODE - Paticipation Mode Code. /// </summary> PaticipationModeCode, /// <summary> /// RC - Read Classification. /// </summary> ReadClassification, /// <summary> /// ROLECLASS - Used initially for contact roles.. /// </summary> UsedInitiallyForContactRoles, /// <summary> /// ROLECODE - Participation Mode. /// </summary> ParticipationMode, /// <summary> /// RSPMODE - Specifies the mode, immediate versus deferred or queued, by which a receiver should communicate its receiver responsibilities.. /// </summary> ModeByWhichReceiverShouldCommunicateResponsibilities, /// <summary> /// RXNORM - RxNorm. /// </summary> Rxnorm, /// <summary> /// SCT - SNOMED Clinical Terms. /// </summary> SnomedClinicalTerms, /// <summary> /// SCT2 - SNOMED Clinical Terms alphanumeric codes. /// </summary> SnomedClinicalTermsAlphanumericCodes, /// <summary> /// SDM - SNOMED- DICOM Microglossary. /// </summary> SnomedDicomMicroglossary, /// <summary> /// SIC - Industry (SIC). /// </summary> IndustrySic, /// <summary> /// SNM - Systemized Nomenclature of Medicine (SNOMED). /// </summary> SystemizedNomenclatureOfMedicineSnomed, /// <summary> /// SNM3 - SNOMED International. /// </summary> SnomedInternational, /// <summary> /// SNT - SNOMED topology codes (anatomic sites). /// </summary> SnomedTopologyCodesAnatomicSites, /// <summary> /// SOC - Occupation (SOC 2000). /// </summary> OccupationSoc2000, /// <summary> /// UB04FL14 - Priority (Type) of Visit. /// </summary> PriorityTypeOfVisit, /// <summary> /// UB04FL15 - Point of Origin. /// </summary> PointOfOrigin, /// <summary> /// UB04FL17 - Patient Discharge Status. /// </summary> PatientDischargeStatus, /// <summary> /// UB04FL31 - Occurrence Code. /// </summary> OccurrenceCode, /// <summary> /// UB04FL35 - Occurrence Span. /// </summary> OccurrenceSpan, /// <summary> /// UB04FL39 - Value Code. /// </summary> ValueCode, /// <summary> /// UC - UCDS. /// </summary> Ucds, /// <summary> /// UCUM - UCUM code set for units of measure(from Regenstrief). /// </summary> UcumCodeSetForUnitsOfMeasureFromRegenstrief, /// <summary> /// UMD - MDNS. /// </summary> Mdns, /// <summary> /// UML - Unified Medical Language. /// </summary> UnifiedMedicalLanguage, /// <summary> /// UPC - Universal Product Code. /// </summary> UniversalProductCode, /// <summary> /// UPIN - UPIN. /// </summary> Upin, /// <summary> /// USGSGNIS - U.S. Board on Geographic Names (USGS - GNIS). /// </summary> USBoardOnGeographicNames, /// <summary> /// USPS - United States Postal Service. /// </summary> UnitedStatesPostalService, /// <summary> /// VIS - Clinicians are required to track the Vaccine Information Sheet (VIS) that was shared with the recipient of a vaccination. This code system contains codes that identify the document type and the owner of the document.. /// </summary> VaccineInformationSheet, /// <summary> /// W1 - WHO record # drug codes (6 digit). /// </summary> WhoRecordDrugCodes6Digit, /// <summary> /// W2 - WHO record # drug codes (8 digit). /// </summary> WhoRecordDrugCodes8Digit, /// <summary> /// W4 - WHO record # code with ASTM extension. /// </summary> WhoRecordCodeWithAstmExtension, /// <summary> /// WC - WHO ATC. /// </summary> WhoAtc, /// <summary> /// X12Dennnn - ASC X12 Code List nnnn. /// </summary> AscX12CodeListNnnn } }
27.335828
278
0.481144
[ "MIT" ]
davebronson/clear-hl7-net
src/ClearHl7.Codes/V282/CodeCodingSystem.cs
29,224
C#
using Amazon.JSII.Runtime.Deputy; #pragma warning disable CS0672,CS0809,CS1591 namespace AlibabaCloud.SDK.ROS.CDK.Cloudfw { #pragma warning disable CS8618 /// <summary>Properties for defining a `ALIYUN::CLOUDFW::ControlPolicy`.</summary> [JsiiByValue(fqn: "@alicloud/ros-cdk-cloudfw.RosControlPolicyProps")] public class RosControlPolicyProps : AlibabaCloud.SDK.ROS.CDK.Cloudfw.IRosControlPolicyProps { /// <remarks> /// <strong>Property</strong>: aclAction: Traffic access control policy set by the cloud of a firewall. /// accept: Release /// drop: rejected /// log: Observation /// </remarks> [JsiiProperty(name: "aclAction", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOverride: true)] public object AclAction { get; set; } /// <remarks> /// <strong>Property</strong>: applicationName: Application types supported by the security policy. /// The following types of applications are supported: ANY, HTTP, HTTPS, MySQL, SMTP, SMTPS, RDP, VNC, SSH, Redis, MQTT, MongoDB, Memcache, SSL /// NOTE ANY indicates that the policy is applied to all types of applications. /// </remarks> [JsiiProperty(name: "applicationName", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOverride: true)] public object ApplicationName { get; set; } /// <remarks> /// <strong>Property</strong>: description: Security access control policy description information. /// </remarks> [JsiiProperty(name: "description", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOverride: true)] public object Description { get; set; } /// <remarks> /// <strong>Property</strong>: destination: Security Access Control destination address policy. /// When DestinationType is net, Destination purpose CIDR. For example: 1.2.3.4/24 /// When DestinationType as a group, Destination for the purpose of the address book name. For example: db_group /// When DestinationType for the domain, Destination for the purpose of a domain name. For example:. * Aliyuncs.com /// When DestinationType as location, Destination area for the purpose (see below position encoding specific regions). For example: [ "BJ11", "ZB"] /// </remarks> [JsiiProperty(name: "destination", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOverride: true)] public object Destination { get; set; } /// <remarks> /// <strong>Property</strong>: destinationType: Security Access Control destination address type of policy. /// net: Destination network segment (CIDR) /// group: destination address book /// domain: The purpose domain /// location: The purpose area /// </remarks> [JsiiProperty(name: "destinationType", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOverride: true)] public object DestinationType { get; set; } /// <remarks> /// <strong>Property</strong>: direction: Security access control traffic direction policies. /// in: internal and external traffic access control /// out: within the flow of external access control /// </remarks> [JsiiProperty(name: "direction", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOverride: true)] public object Direction { get; set; } /// <remarks> /// <strong>Property</strong>: newOrder: Security access control priority policy in force. Priority number increments sequentially from 1, lower the priority number, the higher the priority. /// Description -1 indicates the lowest priority. /// </remarks> [JsiiProperty(name: "newOrder", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOverride: true)] public object NewOrder { get; set; } /// <remarks> /// <strong>Property</strong>: proto: The type of security protocol for traffic access in the security access control policy. Can be set to ANY when you are not sure of the specific protocol type. /// Allowed values: ANY, TCP, UDP, ICMP /// </remarks> [JsiiProperty(name: "proto", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOverride: true)] public object Proto { get; set; } /// <remarks> /// <strong>Property</strong>: source: Security access control source address policy. /// When SourceType for the net, Source is the source CIDR. For example: 1.2.3.0/24 /// When SourceType as a group, Source name for the source address book. For example: db_group /// When SourceType as location, Source source region (specific region position encoder see below). For example, [ "BJ11", "ZB"] /// </remarks> [JsiiProperty(name: "source", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOverride: true)] public object Source { get; set; } /// <remarks> /// <strong>Property</strong>: sourceType: Security access control source address type of policy. /// net: Source segment (CIDR) /// group: source address book /// location: the source area /// </remarks> [JsiiProperty(name: "sourceType", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOverride: true)] public object SourceType { get; set; } /// <remarks> /// <strong>Property</strong>: destPort: Security access control policy access traffic destination port. /// Note When DestPortType to port, set the item. /// </remarks> [JsiiOptional] [JsiiProperty(name: "destPort", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true, isOverride: true)] public object? DestPort { get; set; } /// <remarks> /// <strong>Property</strong>: destPortGroup: Security access control policy access traffic destination port address book name. /// Description DestPortType is group, set the item. /// </remarks> [JsiiOptional] [JsiiProperty(name: "destPortGroup", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true, isOverride: true)] public object? DestPortGroup { get; set; } /// <remarks> /// <strong>Property</strong>: destPortType: Security access control policy access destination port traffic type. /// port: Port /// group: port address book /// </remarks> [JsiiOptional] [JsiiProperty(name: "destPortType", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true, isOverride: true)] public object? DestPortType { get; set; } /// <remarks> /// <strong>Property</strong>: regionId: Region ID. Default to cn-hangzhou. /// </remarks> [JsiiOptional] [JsiiProperty(name: "regionId", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true, isOverride: true)] public object? RegionId { get; set; } } }
45.837838
204
0.583137
[ "Apache-2.0" ]
aliyun/Resource-Orchestration-Service-Cloud-Development-K
multiple-languages/dotnet/AlibabaCloud.SDK.ROS.CDK.Cloudfw/AlibabaCloud/SDK/ROS/CDK/Cloudfw/RosControlPolicyProps.cs
8,480
C#
using Domain.Entities; using MediatR; using ProjectManagement.Core.Base.Mappings; namespace ProjectManagement.Core.UseCases.ProjectAssignments.Commands.UpdateProjectAssignment { public class UpdateProjectAssignmentCommand : IRequest, IMapFrom<ProjectAssignment> { public int UserId { get; set; } public int ProjectId { get; set; } public string MemberType { get; set; } public string ProjectRole { get; set; } public static void Mapping(MappingProfile profile) { profile.CreateMap<UpdateProjectAssignmentCommand, ProjectAssignment>(); } } }
33.368421
93
0.692429
[ "MIT" ]
GoToWinThat/ProjectManagementApi
ProjectManagement/ProjectManagement.Core/UseCases/ProjectAssignments/Commands/UpdateProjectAssignment/UpdateProjectAssignmentCommand.cs
636
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Novel_Google_Translate.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.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; } } } }
34.741935
151
0.585887
[ "MIT" ]
makcimbx/NovelAutoParseAndTranslate
Novel Google Translate/Properties/Settings.Designer.cs
1,079
C#
using Newtonsoft.Json.Bson; using System; using System.Collections.Concurrent; #if DEBUG_LIMITS using System.Diagnostics; #endif using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Discord.Net.Queue { internal class RequestQueue : IDisposable, IAsyncDisposable { public event Func<BucketId, RateLimitInfo?, string, Task> RateLimitTriggered; private readonly ConcurrentDictionary<BucketId, object> _buckets; private readonly SemaphoreSlim _tokenLock; private readonly CancellationTokenSource _cancelTokenSource; //Dispose token private CancellationTokenSource _clearToken; private CancellationToken _parentToken; private CancellationTokenSource _requestCancelTokenSource; private CancellationToken _requestCancelToken; //Parent token + Clear token private DateTimeOffset _waitUntil; private Task _cleanupTask; public RequestQueue() { _tokenLock = new SemaphoreSlim(1, 1); _clearToken = new CancellationTokenSource(); _cancelTokenSource = new CancellationTokenSource(); _requestCancelToken = CancellationToken.None; _parentToken = CancellationToken.None; _buckets = new ConcurrentDictionary<BucketId, object>(); _cleanupTask = RunCleanup(); } public async Task SetCancelTokenAsync(CancellationToken cancelToken) { await _tokenLock.WaitAsync().ConfigureAwait(false); try { _parentToken = cancelToken; _requestCancelTokenSource?.Dispose(); _requestCancelTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancelToken, _clearToken.Token); _requestCancelToken = _requestCancelTokenSource.Token; } finally { _tokenLock.Release(); } } public async Task ClearAsync() { await _tokenLock.WaitAsync().ConfigureAwait(false); try { _clearToken?.Cancel(); _clearToken?.Dispose(); _clearToken = new CancellationTokenSource(); _requestCancelTokenSource?.Dispose(); _requestCancelTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_clearToken.Token, _parentToken); _requestCancelToken = _requestCancelTokenSource.Token; } finally { _tokenLock.Release(); } } public async Task<Stream> SendAsync(RestRequest request) { CancellationTokenSource createdTokenSource = null; if (request.Options.CancelToken.CanBeCanceled) { createdTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_requestCancelToken, request.Options.CancelToken); request.Options.CancelToken = createdTokenSource.Token; } else request.Options.CancelToken = _requestCancelToken; var bucket = GetOrCreateBucket(request.Options, request); var result = await bucket.SendAsync(request).ConfigureAwait(false); createdTokenSource?.Dispose(); return result; } public async Task SendAsync(WebSocketRequest request) { CancellationTokenSource createdTokenSource = null; if (request.Options.CancelToken.CanBeCanceled) { createdTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_requestCancelToken, request.Options.CancelToken); request.Options.CancelToken = createdTokenSource.Token; } else request.Options.CancelToken = _requestCancelToken; var bucket = GetOrCreateBucket(request.Options, request); await bucket.SendAsync(request).ConfigureAwait(false); createdTokenSource?.Dispose(); } internal async Task EnterGlobalAsync(int id, RestRequest request) { int millis = (int)Math.Ceiling((_waitUntil - DateTimeOffset.UtcNow).TotalMilliseconds); if (millis > 0) { #if DEBUG_LIMITS Debug.WriteLine($"[{id}] Sleeping {millis} ms (Pre-emptive) [Global]"); #endif await Task.Delay(millis).ConfigureAwait(false); } } internal void PauseGlobal(RateLimitInfo info) { _waitUntil = DateTimeOffset.UtcNow.AddMilliseconds(info.RetryAfter.Value + (info.Lag?.TotalMilliseconds ?? 0.0)); } internal async Task EnterGlobalAsync(int id, WebSocketRequest request) { //If this is a global request (unbucketed), it'll be dealt in EnterAsync var requestBucket = GatewayBucket.Get(request.Options.BucketId); if (requestBucket.Type == GatewayBucketType.Unbucketed) return; //It's not a global request, so need to remove one from global (per-session) var globalBucketType = GatewayBucket.Get(GatewayBucketType.Unbucketed); var options = RequestOptions.CreateOrClone(request.Options); options.BucketId = globalBucketType.Id; var globalRequest = new WebSocketRequest(null, null, false, false, options); var globalBucket = GetOrCreateBucket(options, globalRequest); await globalBucket.TriggerAsync(id, globalRequest); } private RequestBucket GetOrCreateBucket(RequestOptions options, IRequest request) { var bucketId = options.BucketId; object obj = _buckets.GetOrAdd(bucketId, x => new RequestBucket(this, request, x)); if (obj is BucketId hashBucket) { options.BucketId = hashBucket; return (RequestBucket)_buckets.GetOrAdd(hashBucket, x => new RequestBucket(this, request, x)); } return (RequestBucket)obj; } internal async Task RaiseRateLimitTriggered(BucketId bucketId, RateLimitInfo? info, string endpoint) { await RateLimitTriggered(bucketId, info, endpoint).ConfigureAwait(false); } internal (RequestBucket, BucketId) UpdateBucketHash(BucketId id, string discordHash) { if (!id.IsHashBucket) { var bucket = BucketId.Create(discordHash, id); var hashReqQueue = (RequestBucket)_buckets.GetOrAdd(bucket, _buckets[id]); _buckets.AddOrUpdate(id, bucket, (oldBucket, oldObj) => bucket); return (hashReqQueue, bucket); } return (null, null); } public void ClearGatewayBuckets() { foreach (var gwBucket in (GatewayBucketType[])Enum.GetValues(typeof(GatewayBucketType))) _buckets.TryRemove(GatewayBucket.Get(gwBucket).Id, out _); } private async Task RunCleanup() { try { while (!_cancelTokenSource.IsCancellationRequested) { var now = DateTimeOffset.UtcNow; foreach (var bucket in _buckets.Where(x => x.Value is RequestBucket).Select(x => (RequestBucket)x.Value)) { if ((now - bucket.LastAttemptAt).TotalMinutes > 1.0) { if (bucket.Id.IsHashBucket) foreach (var redirectBucket in _buckets.Where(x => x.Value == bucket.Id).Select(x => (BucketId)x.Value)) _buckets.TryRemove(redirectBucket, out _); //remove redirections if hash bucket _buckets.TryRemove(bucket.Id, out _); } } await Task.Delay(60000, _cancelTokenSource.Token).ConfigureAwait(false); //Runs each minute } } catch (TaskCanceledException) { } catch (ObjectDisposedException) { } } public void Dispose() { if (!(_cancelTokenSource is null)) { _cancelTokenSource.Cancel(); _cancelTokenSource.Dispose(); _cleanupTask.GetAwaiter().GetResult(); } _tokenLock?.Dispose(); _clearToken?.Dispose(); _requestCancelTokenSource?.Dispose(); } public async ValueTask DisposeAsync() { if (!(_cancelTokenSource is null)) { _cancelTokenSource.Cancel(); _cancelTokenSource.Dispose(); await _cleanupTask.ConfigureAwait(false); } _tokenLock?.Dispose(); _clearToken?.Dispose(); _requestCancelTokenSource?.Dispose(); } } }
41.115207
136
0.602555
[ "MIT" ]
Misha-133/Discord.Net
src/Discord.Net.Rest/Net/Queue/RequestQueue.cs
8,922
C#
namespace SkylineBatch { partial class DataServerForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DataServerForm)); this.btnCancel = new System.Windows.Forms.Button(); this.btnSave = new System.Windows.Forms.Button(); this.textNamingPattern = new System.Windows.Forms.TextBox(); this.btnRemoveServer = new System.Windows.Forms.Button(); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); this.linkLabelRegex = new System.Windows.Forms.LinkLabel(); this.linkLabel1 = new System.Windows.Forms.LinkLabel(); this.labelFileInfo = new System.Windows.Forms.Label(); this.btnUpdate = new System.Windows.Forms.Button(); this.listBoxFileNames = new System.Windows.Forms.ListBox(); this.panelRemoteFile = new System.Windows.Forms.Panel(); this.SuspendLayout(); // // btnCancel // resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Name = "btnCancel"; this.btnCancel.UseVisualStyleBackColor = true; // // btnSave // resources.ApplyResources(this.btnSave, "btnSave"); this.btnSave.Name = "btnSave"; this.btnSave.UseVisualStyleBackColor = true; this.btnSave.Click += new System.EventHandler(this.btnAdd_Click); // // textNamingPattern // resources.ApplyResources(this.textNamingPattern, "textNamingPattern"); this.textNamingPattern.Name = "textNamingPattern"; this.textNamingPattern.TextChanged += new System.EventHandler(this.textNamingPattern_TextChanged); // // btnRemoveServer // resources.ApplyResources(this.btnRemoveServer, "btnRemoveServer"); this.btnRemoveServer.Name = "btnRemoveServer"; this.toolTip1.SetToolTip(this.btnRemoveServer, resources.GetString("btnRemoveServer.ToolTip")); this.btnRemoveServer.UseVisualStyleBackColor = true; this.btnRemoveServer.Click += new System.EventHandler(this.btnRemoveServer_Click); // // linkLabelRegex // resources.ApplyResources(this.linkLabelRegex, "linkLabelRegex"); this.linkLabelRegex.Name = "linkLabelRegex"; this.linkLabelRegex.TabStop = true; this.toolTip1.SetToolTip(this.linkLabelRegex, resources.GetString("linkLabelRegex.ToolTip")); this.linkLabelRegex.UseCompatibleTextRendering = true; this.linkLabelRegex.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelRegex_LinkClicked); // // linkLabel1 // resources.ApplyResources(this.linkLabel1, "linkLabel1"); this.linkLabel1.Name = "linkLabel1"; this.toolTip1.SetToolTip(this.linkLabel1, resources.GetString("linkLabel1.ToolTip")); this.linkLabel1.UseCompatibleTextRendering = true; // // labelFileInfo // resources.ApplyResources(this.labelFileInfo, "labelFileInfo"); this.labelFileInfo.Name = "labelFileInfo"; this.toolTip1.SetToolTip(this.labelFileInfo, resources.GetString("labelFileInfo.ToolTip")); // // btnUpdate // resources.ApplyResources(this.btnUpdate, "btnUpdate"); this.btnUpdate.Name = "btnUpdate"; this.btnUpdate.UseVisualStyleBackColor = true; this.btnUpdate.Click += new System.EventHandler(this.btnUpdate_Click); // // listBoxFileNames // resources.ApplyResources(this.listBoxFileNames, "listBoxFileNames"); this.listBoxFileNames.BackColor = System.Drawing.Color.White; this.listBoxFileNames.Name = "listBoxFileNames"; // // panelRemoteFile // resources.ApplyResources(this.panelRemoteFile, "panelRemoteFile"); this.panelRemoteFile.Name = "panelRemoteFile"; // // DataServerForm // this.AcceptButton = this.btnSave; resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.btnCancel; this.Controls.Add(this.labelFileInfo); this.Controls.Add(this.listBoxFileNames); this.Controls.Add(this.btnUpdate); this.Controls.Add(this.linkLabel1); this.Controls.Add(this.btnRemoveServer); this.Controls.Add(this.textNamingPattern); this.Controls.Add(this.btnSave); this.Controls.Add(this.btnCancel); this.Controls.Add(this.linkLabelRegex); this.Controls.Add(this.panelRemoteFile); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "DataServerForm"; this.ShowInTaskbar = false; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.AddServerForm_FormClosing); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnSave; private System.Windows.Forms.TextBox textNamingPattern; private System.Windows.Forms.ToolTip toolTip1; private System.Windows.Forms.Button btnRemoveServer; private System.Windows.Forms.LinkLabel linkLabelRegex; private System.Windows.Forms.LinkLabel linkLabel1; private System.Windows.Forms.Button btnUpdate; private System.Windows.Forms.ListBox listBoxFileNames; private System.Windows.Forms.Label labelFileInfo; private System.Windows.Forms.Panel panelRemoteFile; } }
47.647059
147
0.60727
[ "Apache-2.0" ]
CSi-Studio/pwiz
pwiz_tools/Skyline/Executables/SkylineBatch/SkylineBatch/DataServerForm.Designer.cs
7,292
C#
// ************************************************************* // project: graphql-aspnet // -- // repo: https://github.com/graphql-aspnet // docs: https://graphql-aspnet.github.io // -- // License: MIT // ************************************************************* namespace GraphQL.AspNet.Tests.Middleware { using System; using System.Threading; using System.Threading.Tasks; using GraphQL.AspNet.Execution; using GraphQL.AspNet.Execution.Contexts; using GraphQL.AspNet.Execution.Exceptions; using GraphQL.AspNet.Interfaces.Execution; using GraphQL.AspNet.Middleware.QueryExecution; using GraphQL.AspNet.Middleware.QueryExecution.Components; using Moq; using NUnit.Framework; [TestFixture] public class QueryPipelineComponentTests { public Task EmptyNextDelegate(GraphQueryExecutionContext context, CancellationToken token) { return Task.CompletedTask; } [Test] public void ValidateRequestMiddleware_NullContext_ThrowsException() { var component = new ValidateQueryRequestMiddleware(); Assert.ThrowsAsync<GraphExecutionException>(() => { return component.InvokeAsync(null, EmptyNextDelegate, default); }); } [Test] public async Task ValidateRequestMiddleware_EmptyQueryText_YieldsCriticalMessage() { var component = new ValidateQueryRequestMiddleware(); var req = new Mock<IGraphOperationRequest>(); req.Setup(x => x.QueryText).Returns(null as string); var context = new GraphQueryExecutionContext( req.Object, new Mock<IServiceProvider>().Object); await component.InvokeAsync(context, EmptyNextDelegate, default); Assert.AreEqual(1, context.Messages.Count); Assert.AreEqual(GraphMessageSeverity.Critical, context.Messages[0].Severity); Assert.AreEqual(Constants.ErrorCodes.EXECUTION_ERROR, context.Messages[0].Code); } } }
35.423729
98
0.622967
[ "MIT" ]
NET1211/aspnet-archive-tools
src/tests/graphql-aspnet-tests/Middleware/QueryPipelineComponentTests.cs
2,092
C#
namespace AGS.Types { partial class StringListUIEditorControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { components = new System.ComponentModel.Container(); this.clbItems = new System.Windows.Forms.CheckedListBox(); this.SuspendLayout(); // // clbItems // this.clbItems.Dock = System.Windows.Forms.DockStyle.Fill; this.clbItems.FormattingEnabled = true; this.clbItems.IntegralHeight = false; this.clbItems.BorderStyle = System.Windows.Forms.BorderStyle.None; this.clbItems.CheckOnClick = true; this.clbItems.Location = new System.Drawing.Point(0, 0); this.clbItems.Name = "clbItems"; this.clbItems.Size = new System.Drawing.Size(147, 154); this.clbItems.TabIndex = 0; this.clbItems.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.clbItems_ItemCheck); // // StringListUIEditorControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.clbItems); this.Name = "StringListUIEditorControl"; this.Font = new System.Drawing.Font("Tahoma", 8.25f); this.ResumeLayout(false); } #endregion private System.Windows.Forms.CheckedListBox clbItems; } }
36.265625
111
0.582077
[ "Artistic-2.0" ]
AlanDrake/ags
Editor/AGS.Types/PropertyGridExtras/StringListUIEditorControl.Designer.cs
2,323
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Ched.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Ched.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap AirActionIcon { get { object obj = ResourceManager.GetObject("AirActionIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap AirDownIcon { get { object obj = ResourceManager.GetObject("AirDownIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap AirLeftDownIcon { get { object obj = ResourceManager.GetObject("AirLeftDownIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap AirLeftUpIcon { get { object obj = ResourceManager.GetObject("AirLeftUpIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap AirRightDownIcon { get { object obj = ResourceManager.GetObject("AirRightDownIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap AirRightUpIcon { get { object obj = ResourceManager.GetObject("AirRightUpIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap AirUpIcon { get { object obj = ResourceManager.GetObject("AirUpIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap CopyIcon { get { object obj = ResourceManager.GetObject("CopyIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap CutIcon { get { object obj = ResourceManager.GetObject("CutIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap DamgeIcon { get { object obj = ResourceManager.GetObject("DamgeIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap EditIcon { get { object obj = ResourceManager.GetObject("EditIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap EraserIcon { get { object obj = ResourceManager.GetObject("EraserIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap ErrorIcon { get { object obj = ResourceManager.GetObject("ErrorIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap ExportIcon { get { object obj = ResourceManager.GetObject("ExportIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap ExTapCenterIcon { get { object obj = ResourceManager.GetObject("ExTapCenterIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap ExTapDownIcon { get { object obj = ResourceManager.GetObject("ExTapDownIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap ExTapIcon { get { object obj = ResourceManager.GetObject("ExTapIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap FlickIcon { get { object obj = ResourceManager.GetObject("FlickIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap HoldIcon { get { object obj = ResourceManager.GetObject("HoldIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap InformationIcon { get { object obj = ResourceManager.GetObject("InformationIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). /// </summary> public static System.Drawing.Icon MainIcon { get { object obj = ResourceManager.GetObject("MainIcon", resourceCulture); return ((System.Drawing.Icon)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap NewFileIcon { get { object obj = ResourceManager.GetObject("NewFileIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap OpenFileIcon { get { object obj = ResourceManager.GetObject("OpenFileIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap PasteIcon { get { object obj = ResourceManager.GetObject("PasteIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap RedoIcon { get { object obj = ResourceManager.GetObject("RedoIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap SaveFileIcon { get { object obj = ResourceManager.GetObject("SaveFileIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap SelectionIcon { get { object obj = ResourceManager.GetObject("SelectionIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap SlideCurveIcon { get { object obj = ResourceManager.GetObject("SlideCurveIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap SlideIcon { get { object obj = ResourceManager.GetObject("SlideIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap SlideStepIcon { get { object obj = ResourceManager.GetObject("SlideStepIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap TapIcon { get { object obj = ResourceManager.GetObject("TapIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap UndoIcon { get { object obj = ResourceManager.GetObject("UndoIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap WarningIcon { get { object obj = ResourceManager.GetObject("WarningIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap ZoomInIcon { get { object obj = ResourceManager.GetObject("ZoomInIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> public static System.Drawing.Bitmap ZoomOutIcon { get { object obj = ResourceManager.GetObject("ZoomOutIcon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } } }
38.120773
170
0.541123
[ "MIT" ]
4yn/Ched
Ched/Properties/Resources.Designer.cs
15,784
C#
using Crash; using System.Windows.Forms; namespace CrashEdit { public sealed class OldSLSTSourceBox : UserControl { private ListBox lstValues; public OldSLSTSourceBox(OldSLSTSource slstitem) { lstValues = new ListBox { Dock = DockStyle.Fill }; lstValues.Items.Add(string.Format("Count: {0}",slstitem.Polygons.Count)); lstValues.Items.Add(string.Format("Type: {0}",0)); foreach (OldSLSTPolygonID value in slstitem.Polygons) { lstValues.Items.Add(string.Format("Polygon {0} (World {1})",value.ID,value.World)); } Controls.Add(lstValues); } } }
28
99
0.568681
[ "MIT", "BSD-3-Clause" ]
AraHaan/CrashEd
CrashEdit/Controls/OldSLSTSourceBox.cs
728
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.Soe.V20180724.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class WordRsp : AbstractModel { /// <summary> /// 当前单词语音起始时间点,单位为ms,该字段段落模式下无意义。 /// </summary> [JsonProperty("MemBeginTime")] public long? MemBeginTime{ get; set; } /// <summary> /// 当前单词语音终止时间点,单位为ms,该字段段落模式下无意义。 /// </summary> [JsonProperty("MemEndTime")] public long? MemEndTime{ get; set; } /// <summary> /// 单词发音准确度,取值范围[-1, 100],当取-1时指完全不匹配 /// </summary> [JsonProperty("PronAccuracy")] public float? PronAccuracy{ get; set; } /// <summary> /// 单词发音流利度,取值范围[0, 1] /// </summary> [JsonProperty("PronFluency")] public float? PronFluency{ get; set; } /// <summary> /// 当前词 /// </summary> [JsonProperty("Word")] public string Word{ get; set; } /// <summary> /// 当前词与输入语句的匹配情况,0:匹配单词、1:新增单词、2:缺少单词、3:错读的词、4:未录入单词。 /// </summary> [JsonProperty("MatchTag")] public long? MatchTag{ get; set; } /// <summary> /// 音节评估详情 /// </summary> [JsonProperty("PhoneInfos")] public PhoneInfo[] PhoneInfos{ get; set; } /// <summary> /// 参考词,目前为保留字段。 /// </summary> [JsonProperty("ReferenceWord")] public string ReferenceWord{ get; set; } /// <summary> /// 内部实现,用户禁止调用 /// </summary> internal override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "MemBeginTime", this.MemBeginTime); this.SetParamSimple(map, prefix + "MemEndTime", this.MemEndTime); this.SetParamSimple(map, prefix + "PronAccuracy", this.PronAccuracy); this.SetParamSimple(map, prefix + "PronFluency", this.PronFluency); this.SetParamSimple(map, prefix + "Word", this.Word); this.SetParamSimple(map, prefix + "MatchTag", this.MatchTag); this.SetParamArrayObj(map, prefix + "PhoneInfos.", this.PhoneInfos); this.SetParamSimple(map, prefix + "ReferenceWord", this.ReferenceWord); } } }
32.021505
83
0.594023
[ "Apache-2.0" ]
Darkfaker/tencentcloud-sdk-dotnet
TencentCloud/Soe/V20180724/Models/WordRsp.cs
3,312
C#
namespace iRacing.Enums { public enum ReplaySearchModeTypes { ToStart = 0, ToEnd, PreviousSession, NextSession, PreviousLap, NextLap, PreviousFrame, NextFrame, PreviousIncident, NextIncident } }
17.588235
38
0.531773
[ "MIT" ]
byBlurr/IR.NET
src/irsdkSharp/Enums/ReplaySearchModeTypes.cs
301
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. // </auto-generated> namespace Microsoft.Azure.Management.EventHub.Fluent { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.EventHub; 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> /// NamespacesOperations operations. /// </summary> internal partial class NamespacesOperations : IServiceOperations<EventHubManagementClient>, INamespacesOperations { /// <summary> /// Initializes a new instance of the NamespacesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal NamespacesOperations(EventHubManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the EventHubManagementClient /// </summary> public EventHubManagementClient Client { get; private set; } /// <summary> /// Check the give Namespace name availability. /// </summary> /// <param name='name'> /// Name to check the namespace name availability /// </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<CheckNameAvailabilityResultInner>> CheckNameAvailabilityWithHttpMessagesAsync(string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } CheckNameAvailabilityParameter parameters = new CheckNameAvailabilityParameter(); if (name != null) { parameters.Name = name; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CheckNameAvailability", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.EventHub/CheckNameAvailability").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.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("POST"); _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<CheckNameAvailabilityResultInner>(); _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<CheckNameAvailabilityResultInner>(_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> /// Lists all the available Namespaces within a subscription, irrespective of /// the resource groups. /// </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<NamespaceResourceInner>>> ListBySubscriptionWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListBySubscription", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.EventHub/namespaces").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.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<NamespaceResourceInner>>(); _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<NamespaceResourceInner>>(_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> /// Lists the available Namespaces within a resource group. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </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<NamespaceResourceInner>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroup", 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.EventHub/namespaces").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 (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.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<NamespaceResourceInner>>(); _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<NamespaceResourceInner>>(_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 namespace. Once created, this namespace's resource /// manifest is immutable. This operation is idempotent. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='parameters'> /// Parameters for creating a namespace resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<NamespaceResourceInner>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParametersInner parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<NamespaceResourceInner> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, parameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Deletes an existing namespace. This operation also removes all associated /// resources under the namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the description of the specified namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </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<NamespaceResourceInner>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } } if (namespaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName"); } if (namespaceName != null) { if (namespaceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50); } if (namespaceName.Length < 6) { throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("namespaceName", namespaceName); 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.EventHub/namespaces/{namespaceName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.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 && (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<NamespaceResourceInner>(); _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<NamespaceResourceInner>(_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<NamespaceResourceInner>(_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 namespace. Once created, this namespace's resource /// manifest is immutable. This operation is idempotent. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='parameters'> /// Parameters for updating a namespace resource. /// </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<NamespaceResourceInner>> UpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, NamespaceUpdateParameterInner parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } } if (namespaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName"); } if (namespaceName != null) { if (namespaceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50); } if (namespaceName.Length < 6) { throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6); } } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("namespaceName", namespaceName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Update", 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.EventHub/namespaces/{namespaceName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.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 != 201 && (int)_statusCode != 200 && (int)_statusCode != 202) { 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<NamespaceResourceInner>(); _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 == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<NamespaceResourceInner>(_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 == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<NamespaceResourceInner>(_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 a list of authorization rules for a Namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </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<SharedAccessAuthorizationRuleResourceInner>>> ListAuthorizationRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } } if (namespaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName"); } if (namespaceName != null) { if (namespaceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50); } if (namespaceName.Length < 6) { throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("namespaceName", namespaceName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAuthorizationRules", 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.EventHub/namespaces/{namespaceName}/AuthorizationRules").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.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<SharedAccessAuthorizationRuleResourceInner>>(); _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<SharedAccessAuthorizationRuleResourceInner>>(_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 an AuthorizationRule for a Namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='parameters'> /// The shared access AuthorizationRule. /// </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<SharedAccessAuthorizationRuleResourceInner>> CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParametersInner parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } } if (namespaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName"); } if (namespaceName != null) { if (namespaceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50); } if (namespaceName.Length < 6) { throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6); } } if (authorizationRuleName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "authorizationRuleName"); } if (authorizationRuleName != null) { if (authorizationRuleName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "authorizationRuleName", 50); } if (authorizationRuleName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "authorizationRuleName", 1); } } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("namespaceName", namespaceName); tracingParameters.Add("authorizationRuleName", authorizationRuleName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdateAuthorizationRule", 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.EventHub/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{authorizationRuleName}", System.Uri.EscapeDataString(authorizationRuleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.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) { 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<SharedAccessAuthorizationRuleResourceInner>(); _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<SharedAccessAuthorizationRuleResourceInner>(_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> /// Deletes an AuthorizationRule for a Namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </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> DeleteAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } } if (namespaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName"); } if (namespaceName != null) { if (namespaceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50); } if (namespaceName.Length < 6) { throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6); } } if (authorizationRuleName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "authorizationRuleName"); } if (authorizationRuleName != null) { if (authorizationRuleName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "authorizationRuleName", 50); } if (authorizationRuleName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "authorizationRuleName", 1); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("namespaceName", namespaceName); tracingParameters.Add("authorizationRuleName", authorizationRuleName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "DeleteAuthorizationRule", 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.EventHub/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{authorizationRuleName}", System.Uri.EscapeDataString(authorizationRuleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.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 != 204 && (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(); _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 an AuthorizationRule for a Namespace by rule name. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </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<SharedAccessAuthorizationRuleResourceInner>> GetAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } } if (namespaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName"); } if (namespaceName != null) { if (namespaceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50); } if (namespaceName.Length < 6) { throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6); } } if (authorizationRuleName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "authorizationRuleName"); } if (authorizationRuleName != null) { if (authorizationRuleName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "authorizationRuleName", 50); } if (authorizationRuleName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "authorizationRuleName", 1); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("namespaceName", namespaceName); tracingParameters.Add("authorizationRuleName", authorizationRuleName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetAuthorizationRule", 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.EventHub/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{authorizationRuleName}", System.Uri.EscapeDataString(authorizationRuleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.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<SharedAccessAuthorizationRuleResourceInner>(); _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<SharedAccessAuthorizationRuleResourceInner>(_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 the primary and secondary connection strings for the Namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </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<ResourceListKeysInner>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } } if (namespaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName"); } if (namespaceName != null) { if (namespaceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50); } if (namespaceName.Length < 6) { throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6); } } if (authorizationRuleName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "authorizationRuleName"); } if (authorizationRuleName != null) { if (authorizationRuleName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "authorizationRuleName", 50); } if (authorizationRuleName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "authorizationRuleName", 1); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("namespaceName", namespaceName); tracingParameters.Add("authorizationRuleName", authorizationRuleName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListKeys", 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.EventHub/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}/listKeys").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{authorizationRuleName}", System.Uri.EscapeDataString(authorizationRuleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.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("POST"); _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<ResourceListKeysInner>(); _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<ResourceListKeysInner>(_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> /// Regenerates the primary or secondary connection strings for the specified /// Namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='policykey'> /// Key that needs to be regenerated. Possible values include: 'PrimaryKey', /// 'SecondaryKey' /// </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<ResourceListKeysInner>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Policykey? policykey = default(Policykey?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } } if (namespaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName"); } if (namespaceName != null) { if (namespaceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50); } if (namespaceName.Length < 6) { throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6); } } if (authorizationRuleName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "authorizationRuleName"); } if (authorizationRuleName != null) { if (authorizationRuleName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "authorizationRuleName", 50); } if (authorizationRuleName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "authorizationRuleName", 1); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } RegenerateKeysParameters parameters = new RegenerateKeysParameters(); if (policykey != null) { parameters.Policykey = policykey; } // 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("namespaceName", namespaceName); tracingParameters.Add("authorizationRuleName", authorizationRuleName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "RegenerateKeys", 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.EventHub/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}/regenerateKeys").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{authorizationRuleName}", System.Uri.EscapeDataString(authorizationRuleName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.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("POST"); _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<ResourceListKeysInner>(); _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<ResourceListKeysInner>(_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 namespace. Once created, this namespace's resource /// manifest is immutable. This operation is idempotent. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='parameters'> /// Parameters for creating a namespace resource. /// </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<NamespaceResourceInner>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParametersInner parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } } if (namespaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName"); } if (namespaceName != null) { if (namespaceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50); } if (namespaceName.Length < 6) { throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6); } } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("namespaceName", namespaceName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", 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.EventHub/namespaces/{namespaceName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.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 != 201 && (int)_statusCode != 200 && (int)_statusCode != 202) { 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<NamespaceResourceInner>(); _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 == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<NamespaceResourceInner>(_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 == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<NamespaceResourceInner>(_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> /// Deletes an existing namespace. This operation also removes all associated /// resources under the namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </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> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } } if (namespaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName"); } if (namespaceName != null) { if (namespaceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50); } if (namespaceName.Length < 6) { throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("namespaceName", namespaceName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", 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.EventHub/namespaces/{namespaceName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.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 != 204 && (int)_statusCode != 200 && (int)_statusCode != 202) { 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> /// Lists all the available Namespaces within a subscription, irrespective of /// the resource groups. /// </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<NamespaceResourceInner>>> ListBySubscriptionNextWithHttpMessagesAsync(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, "ListBySubscriptionNext", 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<NamespaceResourceInner>>(); _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<NamespaceResourceInner>>(_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> /// Lists the available Namespaces within 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<NamespaceResourceInner>>> ListByResourceGroupNextWithHttpMessagesAsync(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, "ListByResourceGroupNext", 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<NamespaceResourceInner>>(); _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<NamespaceResourceInner>>(_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 a list of authorization rules for a Namespace. /// </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<SharedAccessAuthorizationRuleResourceInner>>> ListAuthorizationRulesNextWithHttpMessagesAsync(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, "ListAuthorizationRulesNext", 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<SharedAccessAuthorizationRuleResourceInner>>(); _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<SharedAccessAuthorizationRuleResourceInner>>(_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.632687
416
0.560114
[ "MIT" ]
graemefoster/azure-libraries-for-net
src/ResourceManagement/EventHub/Generated/NamespacesOperations.cs
166,059
C#
// Copyright 2004-2021 Castle Project - http://www.castleproject.org/ // // 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 Castle.Components.DictionaryAdapter { using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; /// <summary> /// Support for on-demand value resolution. /// </summary> [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Property, AllowMultiple = false)] public class OnDemandAttribute : DictionaryBehaviorAttribute, IDictionaryPropertyGetter { public OnDemandAttribute() { } public OnDemandAttribute(Type type) { if (type.GetConstructor(Type.EmptyTypes) == null) { throw new ArgumentException( "On-demand values must have a parameterless constructor" ); } Type = type; } public OnDemandAttribute(object value) { Value = value; } public Type Type { get; private set; } public object Value { get; private set; } public object GetPropertyValue( IDictionaryAdapter dictionaryAdapter, string key, object storedValue, PropertyDescriptor property, bool ifExists ) { if (storedValue == null && ifExists == false) { IValueInitializer initializer = null; if (Value != null) { storedValue = Value; } else { var type = Type ?? GetInferredType(dictionaryAdapter, property, out initializer); if (IsAcceptedType(type)) { if (type.IsInterface) { if (property.IsDynamicProperty == false) { if (storedValue == null) { storedValue = dictionaryAdapter.Create(property.PropertyType); } } } else if (type.IsArray) { storedValue = Array.CreateInstance(type.GetElementType(), 0); } else { if (storedValue == null) { object[] args = null; ConstructorInfo constructor = null; if (property.IsDynamicProperty) { constructor = ( from ctor in type.GetConstructors() let parms = ctor.GetParameters() where parms.Length == 1 && parms[0].ParameterType.IsAssignableFrom( dictionaryAdapter.Meta.Type ) select ctor ).FirstOrDefault(); if (constructor != null) args = new[] { dictionaryAdapter }; } if (constructor == null) { constructor = type.GetConstructor(Type.EmptyTypes); } if (constructor != null) { storedValue = constructor.Invoke(args); } } } } } if (storedValue != null) { using (dictionaryAdapter.SuppressNotificationsBlock()) { if (storedValue is ISupportInitialize) { ((ISupportInitialize)storedValue).BeginInit(); ((ISupportInitialize)storedValue).EndInit(); } if (initializer != null) { initializer.Initialize(dictionaryAdapter, storedValue); } property.SetPropertyValue( dictionaryAdapter, property.PropertyName, ref storedValue, dictionaryAdapter.This.Descriptor ); } } } return storedValue; } private static bool IsAcceptedType(Type type) { return type != null && type != typeof(string) && !type.IsPrimitive && !type.IsEnum; } private static Type GetInferredType( IDictionaryAdapter dictionaryAdapter, PropertyDescriptor property, out IValueInitializer initializer ) { Type type = null; initializer = null; type = property.PropertyType; if (typeof(IEnumerable).IsAssignableFrom(type) == false) { return type; } Type collectionType = null; if (type.IsGenericType) { var genericDef = type.GetGenericTypeDefinition(); var genericArg = type.GetGenericArguments()[0]; bool isBindingList = genericDef == typeof(System.ComponentModel.BindingList<>); if (isBindingList || genericDef == typeof(List<>)) { if (dictionaryAdapter.CanEdit) { collectionType = isBindingList ? typeof(EditableBindingList<>) : typeof(EditableList<>); } if (isBindingList && genericArg.IsInterface) { Func<object> addNew = () => dictionaryAdapter.Create(genericArg); initializer = (IValueInitializer)Activator.CreateInstance( typeof(BindingListInitializer<>).MakeGenericType(genericArg), null, addNew, null, null, null ); } } else if (genericDef == typeof(IList<>) || genericDef == typeof(ICollection<>)) { collectionType = dictionaryAdapter.CanEdit ? typeof(EditableList<>) : typeof(List<>); } if (collectionType != null) { return collectionType.MakeGenericType(genericArg); } } else if (type == typeof(IList) || type == typeof(ICollection)) { return dictionaryAdapter.CanEdit ? typeof(EditableList) : typeof(List<object>); } return type; } } }
36.460177
99
0.42767
[ "Apache-2.0" ]
belav/Core
src/Castle.Core/Components.DictionaryAdapter/Attributes/OnDemandAttribute.cs
8,240
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Data.Entity; using System.Data.Entity.Core.Mapping; using System.Data.Entity.Core.Metadata.Edm; using System.Data.Entity.Infrastructure; using System.Linq; namespace Abp.EntityFramework { //TODO: Remove not used class! internal static class DbContextHelper { private static readonly ConcurrentDictionary<string, IReadOnlyList<string>> CachedTableNames = new ConcurrentDictionary<string, IReadOnlyList<string>>(); public static IReadOnlyList<string> GetTableName(this DbContext context, Type type) { var cacheKey = context.GetType().AssemblyQualifiedName + type.AssemblyQualifiedName; return CachedTableNames.GetOrAdd(cacheKey, k => { var metadata = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace; // Get the part of the model that contains info about the actual CLR types var objectItemCollection = ((ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace)); // Get the entity type from the model that maps to the CLR type var entityType = metadata .GetItems<EntityType>(DataSpace.OSpace) .Single(e => objectItemCollection.GetClrType(e) == type); // Get the entity set that uses this entity type var entitySet = metadata .GetItems<EntityContainer>(DataSpace.CSpace) .Single() .EntitySets .Single(s => s.ElementType.Name == entityType.Name); // Find the mapping between conceptual and storage model for this entity set var mapping = metadata.GetItems<EntityContainerMapping>(DataSpace.CSSpace) .Single() .EntitySetMappings .Single(s => s.EntitySet == entitySet); // Find the storage entity sets (tables) that the entity is mapped var tables = mapping .EntityTypeMappings.Single() .Fragments; // Return the table name from the storage entity set return tables.Select(f => (string)f.StoreEntitySet.MetadataProperties["Table"].Value ?? f.StoreEntitySet.Name).ToImmutableList(); }); } } }
43.824561
161
0.622898
[ "MIT" ]
12321/aspnetboilerplate
src/Abp.EntityFramework/EntityFramework/DbContextHelper.cs
2,498
C#
using System; namespace Hertzole.CecilAttributes { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public sealed class MarkInProfilerAttribute : Attribute { } }
25.875
87
0.772947
[ "MIT" ]
Hertzole/cecil-attributes
Runtime/Attributes/MarkInProfilerAttribute.cs
209
C#
using HarmonyLib; using System; namespace ArenaOverhaul.Helpers { internal static class HarmonyHelper { public static bool PatchAll(ref Harmony? harmonyInstance, string sectionName, string logMessage, string chatMessage = "") { try { if (harmonyInstance is null) harmonyInstance = new Harmony("Bannerlord.ArenaOverhaul"); harmonyInstance.PatchAll(); return true; } catch (Exception ex) { DebugHelper.HandleException(ex, sectionName, logMessage, chatMessage); return false; } } } }
27.64
129
0.549928
[ "MIT" ]
Aragas/Bannerlord.ArenaOverhaul
src/ArenaOverhaul/Helpers/HarmonyHelper.cs
693
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace VsxFactory.Modeling.VisualStudio.Synchronization { public sealed class ProjectEventsDisabler : IDisposable { private bool _disposing; private readonly IVsSolutionExplorer _solutionManager; /// <summary> /// Initializes a new instance of the <see cref="ProjectEventsDisabler"/> class. /// </summary> /// <param name="project">The project.</param> public ProjectEventsDisabler(IVsSolutionExplorer solutionManager, string projectName) { Guard.ArgumentNotNull(solutionManager, "solutionManager"); Guard.ArgumentNotNullOrEmptyString(projectName, "projectName"); _solutionManager = solutionManager; _solutionManager.DisableReferenceEventsOnProject(projectName); } /// <summary> /// Releases unmanaged resources and performs other cleanup operations before the /// <see cref="ProjectEventsDisabler"/> is reclaimed by garbage collection. /// </summary> ~ProjectEventsDisabler() { Dispose(); } #region IDisposable Members /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { if (!_disposing) { _disposing = true; if (_solutionManager != null) _solutionManager.EnableReferenceEventsOnProject(); } GC.SuppressFinalize(this); } #endregion } }
31.62963
116
0.620609
[ "MIT" ]
t4generators/t4-SolutionManager
src/VisualStudio.ParsingSolution/Hierarchies/Synchronization/ProjectEventsDisabler.cs
1,710
C#
// <auto-generated /> namespace LearnWord.Migrations { using System.CodeDom.Compiler; using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.Infrastructure; using System.Resources; [GeneratedCode("EntityFramework.Migrations", "6.2.0-61023")] public sealed partial class UpdateUserIdOnWordModel : IMigrationMetadata { private readonly ResourceManager Resources = new ResourceManager(typeof(UpdateUserIdOnWordModel)); string IMigrationMetadata.Id { get { return "201902170034318_UpdateUserIdOnWordModel"; } } string IMigrationMetadata.Source { get { return null; } } string IMigrationMetadata.Target { get { return Resources.GetString("Target"); } } } }
28.333333
106
0.635294
[ "MIT" ]
xChivalrouSx/LearnWord
LearnWord/Migrations/201902170034318_UpdateUserIdOnWordModel.Designer.cs
850
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 pinpoint-2016-12-01.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.Pinpoint.Model { /// <summary> /// This is the response object from the CreateEmailTemplate operation. /// </summary> public partial class CreateEmailTemplateResponse : AmazonWebServiceResponse { private CreateTemplateMessageBody _createTemplateMessageBody; /// <summary> /// Gets and sets the property CreateTemplateMessageBody. /// </summary> [AWSProperty(Required=true)] public CreateTemplateMessageBody CreateTemplateMessageBody { get { return this._createTemplateMessageBody; } set { this._createTemplateMessageBody = value; } } // Check to see if CreateTemplateMessageBody property is set internal bool IsSetCreateTemplateMessageBody() { return this._createTemplateMessageBody != null; } } }
32.890909
107
0.681592
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/Pinpoint/Generated/Model/CreateEmailTemplateResponse.cs
1,809
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; namespace ResidentsSocialCarePlatformApi.V1.Infrastructure.Migrations { public partial class AddVisitsTable : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "dm_visits", schema: "dbo", columns: table => new { visit_id = table.Column<long>(type: "bigint", maxLength: 9, nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), person_id = table.Column<long>(type: "bigint", maxLength: 16, nullable: false), visit_type = table.Column<string>(type: "character varying(20)", maxLength: 20, nullable: false), planned_datetime = table.Column<DateTime>(type: "timestamp without time zone", nullable: true), actual_datetime = table.Column<DateTime>(type: "timestamp without time zone", nullable: true), reason_not_planned = table.Column<string>(type: "character varying(16)", maxLength: 16, nullable: true), reason_visit_not_made = table.Column<string>(type: "character varying(16)", maxLength: 16, nullable: true), seen_alone_flag = table.Column<string>(type: "character varying(1)", maxLength: 1, nullable: true), completed_flag = table.Column<string>(type: "character varying(1)", maxLength: 1, nullable: true), org_id = table.Column<long>(type: "bigint", maxLength: 9, nullable: true), worker_id = table.Column<long>(type: "bigint", maxLength: 9, nullable: true), cp_registration_id = table.Column<long>(type: "bigint", maxLength: 9, nullable: false), cp_visit_schedule_step_id = table.Column<long>(type: "bigint", maxLength: 9, nullable: true), cp_visit_schedule_days = table.Column<long>(type: "bigint", maxLength: 3, nullable: true), cp_visit_on_time = table.Column<string>(type: "character varying(1)", maxLength: 1, nullable: true) }, constraints: table => { table.PrimaryKey("PK_dm_visits", x => x.visit_id); }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "dm_visits", schema: "dbo"); } } }
57.12766
127
0.60149
[ "MIT" ]
LBHackney-IT/residents-social-care-platform-api
ResidentsSocialCarePlatformApi/V1/Infrastructure/Migrations/20210325141726_AddVisitsTable.cs
2,685
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using SharpDX; namespace SpaceSimulator.Common.Models { /// <summary> /// The vertex format used by the geometry /// </summary> [StructLayout(LayoutKind.Sequential)] public struct GeometryVertex { /// <summary> /// The position /// </summary> public Vector3 Position; /// <summary> /// The normal /// </summary> public Vector3 Normal; /// <summary> /// The tangent /// </summary> public Vector3 Tangent; /// <summary> /// The texture coordinates /// </summary> public Vector2 TextureCoordinates; /// <summary> /// Creates a new geometry vertex /// </summary> public GeometryVertex( float px, float py, float pz, float nx, float ny, float nz, float tx, float ty, float tz, float u, float v) { this.Position = new Vector3(px, py, pz); this.Normal = new Vector3(nx, ny, nz); this.Tangent = new Vector3(tx, ty, tz); this.TextureCoordinates = new Vector2(u, v); } } /// <summary> /// Represents a geometry generator /// </summary> public static class GeometryGenerator { /// <summary> /// Creates a m x n grid /// </summary> /// <param name="width">The width of the grid</param> /// <param name="depth">The depth of the grid</param> /// <param name="m">The number of rows</param> /// <param name="n">The number of columns</param> /// <param name="vertices">The created vertices</param> /// <param name="indices">The created indices</param> public static void CreateGrid(float width, float depth, int m, int n, out GeometryVertex[] vertices, out int[] indices) { int vertexCount = m * n; int faceCount = (m - 1) * (n - 1) * 2; // Create the vertices. float halfWidth = 0.5f * width; float halfDepth = 0.5f * depth; float dx = width / (n - 1); float dz = depth / (m - 1); float du = 1.0f / (n - 1); float dv = 1.0f / (m - 1); vertices = new GeometryVertex[vertexCount]; for (int i = 0; i < m; i++) { var z = halfDepth - i * dz; for (int j = 0; j < n; ++j) { float x = -halfWidth + j * dx; var vertex = new GeometryVertex() { Position = new Vector3(x, 0.0f, z), Normal = new Vector3(0.0f, 1.0f, 0.0f), Tangent = new Vector3(1.0f, 0.0f, 0.0f), TextureCoordinates = new Vector2(j * du, i * dv) // Stretch texture over grid. }; vertices[i * n + j] = vertex; } } //Create the indices. indices = new int[faceCount * 3]; // 3 indices per face // Iterate over each quad and compute indices. int k = 0; for (int i = 0; i < m - 1; i++) { for (int j = 0; j < n - 1; j++) { indices[k] = i * n + j; indices[k + 1] = i * n + j + 1; indices[k + 2] = (i + 1) * n + j; indices[k + 3] = (i + 1) * n + j; indices[k + 4] = i * n + j + 1; indices[k + 5] = (i + 1) * n + j + 1; k += 6; // next quad } } } /// <summary> /// Creates a box /// </summary> /// <param name="width">The width of the box</param> /// <param name="height">The height of the box</param> /// <param name="depth">The depth of the box</param> /// <param name="vertices">The created vertices</param> /// <param name="indices">The created indices</param> public static void CreateBox(float width, float height, float depth, out GeometryVertex[] vertices, out int[] indices) { //Create the vertices vertices = new GeometryVertex[24]; float w2 = 0.5f * width; float h2 = 0.5f * height; float d2 = 0.5f * depth; // Fill in the front face vertex data. vertices[0] = new GeometryVertex(-w2, -h2, -d2, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f); vertices[1] = new GeometryVertex(-w2, +h2, -d2, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f); vertices[2] = new GeometryVertex(+w2, +h2, -d2, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f); vertices[3] = new GeometryVertex(+w2, -h2, -d2, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f); // Fill in the back face new GeometryVertex data. vertices[4] = new GeometryVertex(-w2, -h2, +d2, 0.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f); vertices[5] = new GeometryVertex(+w2, -h2, +d2, 0.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f); vertices[6] = new GeometryVertex(+w2, +h2, +d2, 0.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f); vertices[7] = new GeometryVertex(-w2, +h2, +d2, 0.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f); // Fill in the top face new GeometryVertex data. vertices[8] = new GeometryVertex(-w2, +h2, -d2, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f); vertices[9] = new GeometryVertex(-w2, +h2, +d2, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f); vertices[10] = new GeometryVertex(+w2, +h2, +d2, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f); vertices[11] = new GeometryVertex(+w2, +h2, -d2, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f); // Fill in the bottom face new GeometryVertex data. vertices[12] = new GeometryVertex(-w2, -h2, -d2, 0.0f, -1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f); vertices[13] = new GeometryVertex(+w2, -h2, -d2, 0.0f, -1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f); vertices[14] = new GeometryVertex(+w2, -h2, +d2, 0.0f, -1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f); vertices[15] = new GeometryVertex(-w2, -h2, +d2, 0.0f, -1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f); // Fill in the left face new GeometryVertex data. vertices[16] = new GeometryVertex(-w2, -h2, +d2, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f); vertices[17] = new GeometryVertex(-w2, +h2, +d2, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f); vertices[18] = new GeometryVertex(-w2, +h2, -d2, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f); vertices[19] = new GeometryVertex(-w2, -h2, -d2, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f); // Fill in the right face new GeometryVertex data. vertices[20] = new GeometryVertex(+w2, -h2, -d2, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f); vertices[21] = new GeometryVertex(+w2, +h2, -d2, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f); vertices[22] = new GeometryVertex(+w2, +h2, +d2, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f); vertices[23] = new GeometryVertex(+w2, -h2, +d2, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f); // Create the indices. indices = new int[36]; // Fill in the front face index data indices[0] = 0; indices[1] = 1; indices[2] = 2; indices[3] = 0; indices[4] = 2; indices[5] = 3; // Fill in the back face index data indices[6] = 4; indices[7] = 5; indices[8] = 6; indices[9] = 4; indices[10] = 6; indices[11] = 7; // Fill in the top face index data indices[12] = 8; indices[13] = 9; indices[14] = 10; indices[15] = 8; indices[16] = 10; indices[17] = 11; // Fill in the bottom face index data indices[18] = 12; indices[19] = 13; indices[20] = 14; indices[21] = 12; indices[22] = 14; indices[23] = 15; // Fill in the left face index data indices[24] = 16; indices[25] = 17; indices[26] = 18; indices[27] = 16; indices[28] = 18; indices[29] = 19; // Fill in the right face index data indices[30] = 20; indices[31] = 21; indices[32] = 22; indices[33] = 20; indices[34] = 22; indices[35] = 23; } /// <summary> /// Creates a sphere /// </summary> /// <param name="radius">The radius of the sphere</param> /// <param name="sliceCount">The slice count</param> /// <param name="stackCount">The stack count</param> /// <param name="vertices">The created vertices</param> /// <param name="indices">The created indices</param> public static void CreateSphere(float radius, int sliceCount, int stackCount, out GeometryVertex[] vertices, out int[] indices) { var sphereVertices = new List<GeometryVertex>(); var sphereIndices = new List<int>(); //Compute the vertices stating at the top pole and moving down the stacks. var topVertex = new GeometryVertex(0.0f, +radius, 0.0f, 0.0f, +1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f); var bottomVertex = new GeometryVertex(0.0f, -radius, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f); sphereVertices.Add(topVertex); float phiStep = MathUtil.Pi / stackCount; float thetaStep = 2.0f * MathUtil.Pi / sliceCount; //Compute vertices for each stack ring (do not count the poles as rings). for (int i = 1; i <= stackCount - 1; ++i) { float phi = i * phiStep; // Vertices of ring. for (int j = 0; j <= sliceCount; ++j) { float theta = j * thetaStep; GeometryVertex vertex; //spherical to cartesian vertex.Position.X = radius * (float)Math.Sin(phi) * (float)Math.Cos(theta); vertex.Position.Y = radius * (float)Math.Cos(phi); vertex.Position.Z = radius * (float)Math.Sin(phi) * (float)Math.Sin(theta); //Partial derivative of P with respect to theta vertex.Tangent.X = -radius * (float)Math.Sin(phi) * (float)Math.Sin(theta); vertex.Tangent.Y = 0.0f; vertex.Tangent.Z = +radius * (float)Math.Sin(phi) * (float)Math.Cos(theta); vertex.Tangent.Normalize(); vertex.Normal = vertex.Position; vertex.Normal.Normalize(); vertex.TextureCoordinates.X = theta / MathUtil.TwoPi; vertex.TextureCoordinates.Y = phi / MathUtil.Pi; sphereVertices.Add(vertex); } } sphereVertices.Add(bottomVertex); //Compute indices for top stack. The top stack was written first to the vertex buffer //and connects the top pole to the first ring. for (int i = 1; i <= sliceCount; ++i) { sphereIndices.Add(0); sphereIndices.Add(i + 1); sphereIndices.Add(i); } // Compute indices for inner stacks (not connected to poles). // Offset the indices to the index of the first vertex in the first ring. // This is just skipping the top pole vertex. int baseIndex = 1; int ringVertexCount = sliceCount + 1; for (int i = 0; i < stackCount - 2; ++i) { for (int j = 0; j < sliceCount; ++j) { sphereIndices.Add(baseIndex + i * ringVertexCount + j); sphereIndices.Add(baseIndex + i * ringVertexCount + j + 1); sphereIndices.Add(baseIndex + (i + 1) * ringVertexCount + j); sphereIndices.Add(baseIndex + (i + 1) * ringVertexCount + j); sphereIndices.Add(baseIndex + i * ringVertexCount + j + 1); sphereIndices.Add(baseIndex + (i + 1) * ringVertexCount + j + 1); } } // Compute indices for bottom stack. The bottom stack was written last to the vertex buffer // and connects the bottom pole to the bottom ring. //South pole vertex was added last. int southPoleIndex = (int)sphereVertices.Count - 1; //Offset the indices to the index of the first vertex in the last ring. baseIndex = southPoleIndex - ringVertexCount; for (int i = 0; i < sliceCount; ++i) { sphereIndices.Add(southPoleIndex); sphereIndices.Add(baseIndex + i); sphereIndices.Add(baseIndex + i + 1); } vertices = sphereVertices.ToArray(); indices = sphereIndices.ToArray(); } /// <summary> /// Creates a cylinder /// </summary> /// <param name="bottomRadius">The bottom radius</param> /// <param name="topRadius">The top radius</param> /// <param name="height">The height</param> /// <param name="sliceCount">The slice count</param> /// <param name="stackCount">The stack count</param> /// <param name="vertices">The created vertices</param> /// <param name="indices">The created indices</param> public static void CreateCylinder( float bottomRadius, float topRadius, float height, int sliceCount, int stackCount, out GeometryVertex[] vertices, out int[] indices) { var cylinderVertices = new List<GeometryVertex>(); var cylinderIndices = new List<int>(); // Build Stacks. float stackHeight = height / stackCount; //Amount to increment radius as we move up each stack level from bottom to top. float radiusStep = (topRadius - bottomRadius) / stackCount; int ringCount = stackCount + 1; // Compute vertices for each stack ring starting at the bottom and moving up. for (int i = 0; i < ringCount; ++i) { float y = -0.5f * height + i * stackHeight; float r = bottomRadius + i * radiusStep; // vertices of ring float dTheta = 2.0f * MathUtil.Pi / sliceCount; for (int j = 0; j <= sliceCount; ++j) { GeometryVertex vertex; float c = (float)Math.Cos(j * dTheta); float s = (float)Math.Sin(j * dTheta); vertex.Position = new Vector3(r * c, y, r * s); vertex.TextureCoordinates.X = (float)j / sliceCount; vertex.TextureCoordinates.Y = 1.0f - (float)i / stackCount; // Cylinder can be parameterized as follows, where we introduce v // parameter that goes in the same direction as the v tex-coord // so that the bitangent goes in the same direction as the v tex-coord. // Let r0 be the bottom radius and let r1 be the top radius. // y(v) = h - hv for v in [0,1]. // r(v) = r1 + (r0-r1)v // // x(t, v) = r(v)*cos(t) // y(t, v) = h - hv // z(t, v) = r(v)*sin(t) // // dx/dt = -r(v)*sin(t) // dy/dt = 0 // dz/dt = +r(v)*cos(t) // // dx/dv = (r0-r1)*cos(t) // dy/dv = -h // dz/dv = (r0-r1)*sin(t) // This is unit length. vertex.Tangent = new Vector3(-s, 0.0f, c); float dr = bottomRadius - topRadius; var bitangent = new Vector3(dr * c, -height, dr * s); var normal = Vector3.Cross(vertex.Tangent, bitangent); normal.Normalize(); vertex.Normal = normal; cylinderVertices.Add(vertex); } } // Add one because we duplicate the first and last vertex per ring // since the texture coordinates are different. int ringVertexCount = sliceCount + 1; // Compute indices for each stack. for (int i = 0; i < stackCount; ++i) { for (int j = 0; j < sliceCount; ++j) { cylinderIndices.Add(i * ringVertexCount + j); cylinderIndices.Add((i + 1) * ringVertexCount + j); cylinderIndices.Add((i + 1) * ringVertexCount + j + 1); cylinderIndices.Add(i * ringVertexCount + j); cylinderIndices.Add((i + 1) * ringVertexCount + j + 1); cylinderIndices.Add(i * ringVertexCount + j + 1); } } BuildCylinderTopCap(bottomRadius, topRadius, height, sliceCount, stackCount, cylinderVertices, cylinderIndices); BuildCylinderBottomCap(bottomRadius, topRadius, height, sliceCount, stackCount, cylinderVertices, cylinderIndices); vertices = cylinderVertices.ToArray(); indices = cylinderIndices.ToArray(); } /// <summary> /// Builds the top cylinder cap /// </summary> /// <param name="bottomRadius">The bottom radius</param> /// <param name="topRadius">The top radius</param> /// <param name="height">The height</param> /// <param name="sliceCount">The slice count</param> /// <param name="stackCount">The stack count</param> /// <param name="vertices">The vertices list</param> /// <param name="indices">The indices list</param> private static void BuildCylinderTopCap(float bottomRadius, float topRadius, float height, int sliceCount, int stackCount, IList<GeometryVertex> vertices, IList<int> indices) { int baseIndex = vertices.Count; float y = 0.5f * height; float dTheta = 2.0f * MathUtil.Pi / sliceCount; // Duplicate cap ring vertices because the texture coordinates and normals differ. for (int i = 0; i <= sliceCount; ++i) { float x = topRadius * (float)Math.Cos(i * dTheta); float z = topRadius * (float)Math.Sin(i * dTheta); // Scale down by the height to try and make top cap texture coord area // proportional to base. float u = x / height + 0.5f; float v = z / height + 0.5f; vertices.Add(new GeometryVertex(x, y, z, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, u, v)); } // Cap center vertex. vertices.Add(new GeometryVertex(0.0f, y, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.5f, 0.5f)); // Index of center vertex. int centerIndex = vertices.Count - 1; for (int i = 0; i < sliceCount; ++i) { indices.Add(centerIndex); indices.Add(baseIndex + i + 1); indices.Add(baseIndex + i); } } /// <summary> /// Builds the bottom cylinder cap /// </summary> /// <param name="bottomRadius">The bottom radius</param> /// <param name="topRadius">The top radius</param> /// <param name="height">The height</param> /// <param name="sliceCount">The slice count</param> /// <param name="stackCount">The stack count</param> /// <param name="vertices">The vertices list</param> /// <param name="indices">The indices list</param> private static void BuildCylinderBottomCap(float bottomRadius, float topRadius, float height, int sliceCount, int stackCount, IList<GeometryVertex> vertices, IList<int> indices) { //Build bottom cap. int baseIndex = vertices.Count; float y = -0.5f * height; //vertices of ring float dTheta = 2.0f * MathUtil.Pi / sliceCount; for (int i = 0; i <= sliceCount; ++i) { float x = bottomRadius * (float)Math.Cos(i * dTheta); float z = bottomRadius * (float)Math.Sin(i * dTheta); //Scale down by the height to try and make top cap texture coord area //proportional to base. float u = x / height + 0.5f; float v = z / height + 0.5f; vertices.Add(new GeometryVertex(x, y, z, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, u, v)); } //Cap center vertex. vertices.Add(new GeometryVertex(0.0f, y, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.5f, 0.5f)); // Cache the index of center vertex. int centerIndex = vertices.Count - 1; for (int i = 0; i < sliceCount; ++i) { indices.Add(centerIndex); indices.Add(baseIndex + i); indices.Add(baseIndex + i + 1); } } /// <summary> /// Creates a fullscreen quad /// </summary> /// <param name="vertices">The created vertices</param> /// <param name="indices">The created indices</param> public static void CreateFullscreenQuad(out GeometryVertex[] vertices, out int[] indices) { vertices = new GeometryVertex[4]; indices = new int[6]; // Position coordinates specified in NDC space. vertices[0] = new GeometryVertex( -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f); vertices[1] = new GeometryVertex( -1.0f, +1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f); vertices[2] = new GeometryVertex( +1.0f, +1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f); vertices[3] = new GeometryVertex( +1.0f, -1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f); indices[0] = 0; indices[1] = 1; indices[2] = 2; indices[3] = 0; indices[4] = 2; indices[5] = 3; } } }
34.507273
129
0.607566
[ "MIT" ]
svenslaggare/SpaceSimulator.NET
SpaceSimulator.Common/Models/GeometryGenerator.cs
18,981
C#
using BookstoreSystem.Data.API; namespace BookstoreSystem.Data { internal class EventReturn : IEvent { private IState state; private ICustomer customer; private DateTime eventDate; public EventReturn(IState _state, ICustomer _client) { this.state = _state; this.customer = _client; this.eventDate = DateTime.Now; } public IState State { get { return this.state; } } public ICustomer Customer { get { return this.customer; } } public DateTime EventDate { get { return this.eventDate; } } } }
26.73913
68
0.614634
[ "MIT" ]
ArtJSON/PT
BookstoreSystem/Data/EventReturn.cs
617
C#
using System; using System.Collections.Generic; using MenuPlanner.Common.Popups.Models; namespace MenuPlanner.Common.Popups.Managers { public interface IPopupManager { IEnumerable<Popup> Popups { get; } Popup CurrentPopup { get; } event EventHandler<Popup> PopupChanged; IPopupManager ShowPopup<T>(PopupParameters parameters = null) where T : Popup; IPopupManager ShowMessage(string message); void OnClose(Action<PopupClosedEventArgs> toExecuteAction); } }
23.818182
86
0.711832
[ "MIT" ]
TomCortinovis/MenuPlanner
MenuPlanner.Common/Popups/Managers/IPopupManager.cs
526
C#
namespace ImageContestSystem.Web { using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Infrastructure.Mapping; public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AutoMapperConfig.Execute(); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
29.1
70
0.675258
[ "MIT" ]
TeamHOOPRINGHA/ImageContestSystem
Source/Web/ImageContestSystem.Web/Global.asax.cs
584
C#
namespace BingoGameCore4.Forms { partial class SessionBrowser { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose( bool disposing ) { if( disposing && ( components != null ) ) { components.Dispose(); } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.dataGridViewPlayers = new System.Windows.Forms.DataGridView(); this.dataGridViewGames = new System.Windows.Forms.DataGridView(); this.label2 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.listBoxPacks = new System.Windows.Forms.ListBox(); ((System.ComponentModel.ISupportInitialize)(this.dataGridViewPlayers)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.dataGridViewGames)).BeginInit(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(12, 16); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(41, 13); this.label1.TabIndex = 1; this.label1.Text = "Players"; // // dataGridViewPlayers // this.dataGridViewPlayers.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridViewPlayers.Location = new System.Drawing.Point(26, 32); this.dataGridViewPlayers.Name = "dataGridViewPlayers"; this.dataGridViewPlayers.Size = new System.Drawing.Size(221, 387); this.dataGridViewPlayers.TabIndex = 2; // // dataGridViewGames // this.dataGridViewGames.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))); this.dataGridViewGames.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridViewGames.Location = new System.Drawing.Point(408, 86); this.dataGridViewGames.Name = "dataGridViewGames"; this.dataGridViewGames.Size = new System.Drawing.Size(356, 395); this.dataGridViewGames.TabIndex = 3; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(381, 9); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(40, 13); this.label2.TabIndex = 4; this.label2.Text = "Games"; // // button1 // this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.button1.Location = new System.Drawing.Point(664, 46); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(102, 34); this.button1.TabIndex = 5; this.button1.Text = "Show Game"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // listBoxPacks // this.listBoxPacks.FormattingEnabled = true; this.listBoxPacks.Location = new System.Drawing.Point(268, 96); this.listBoxPacks.Name = "listBoxPacks"; this.listBoxPacks.Size = new System.Drawing.Size(120, 238); this.listBoxPacks.TabIndex = 6; // // SessionBrowser // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(776, 493); this.Controls.Add(this.listBoxPacks); this.Controls.Add(this.button1); this.Controls.Add(this.label2); this.Controls.Add(this.dataGridViewGames); this.Controls.Add(this.dataGridViewPlayers); this.Controls.Add(this.label1); this.Name = "SessionBrowser"; this.Text = "SessionBrowser"; this.Load += new System.EventHandler(this.SessionBrowser_Load); ((System.ComponentModel.ISupportInitialize)(this.dataGridViewPlayers)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.dataGridViewGames)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.DataGridView dataGridViewPlayers; private System.Windows.Forms.DataGridView dataGridViewGames; private System.Windows.Forms.Label label2; private System.Windows.Forms.Button button1; private System.Windows.Forms.ListBox listBoxPacks; } }
39.637795
158
0.705205
[ "MIT" ]
d3x0r/xperdex
OpenSkiePOS/bingo_odds/BingoGameCore4/Forms/SessionBrowser.Designer.cs
5,034
C#
namespace EltradeProtocol.Requests { public enum DiscountType { Absolute, Relative } }
12.888889
35
0.603448
[ "Apache-2.0" ]
MahametH/eltrade-fiscal-device-protocol
EltradeProtocol/EltradeProtocol/Requests/DiscountType.cs
118
C#
using System; using System.Threading; using System.Windows.Threading; using Squiggle.UI.Helpers; using Squiggle.Utilities; using Squiggle.Utilities.Threading; using Squiggle.Plugins; using System.Threading.Tasks; namespace Squiggle.UI.Components { class NetworkSignout: IDisposable { bool autoSignout; SignInOptions signInOptions; Action<SignInOptions> signInFunction; Action signoutFunction; bool loggedIn; Dispatcher dispatcher; public NetworkSignout(Dispatcher dispatcher, Action<SignInOptions> signInFunction, Action signoutFunction) { this.dispatcher = dispatcher; this.signInFunction = signInFunction; this.signoutFunction = signoutFunction; System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged; } public void OnSignIn(SignInOptions signInOptions) { this.signInOptions = signInOptions; loggedIn = true; } public void OnSignOut() { autoSignout = false; loggedIn = false; } async void NetworkChange_NetworkAvailabilityChanged(object sender, System.Net.NetworkInformation.NetworkAvailabilityEventArgs e) { if (e.IsAvailable) { await Task.Delay(10.Seconds()); if (autoSignout && signInOptions != null && !loggedIn) this.dispatcher.Invoke(() => signInFunction(signInOptions)); } else { this.dispatcher.Invoke(() => signoutFunction()); if (loggedIn) { autoSignout = true; loggedIn = false; } } } public void Dispose() { System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged -= NetworkChange_NetworkAvailabilityChanged; } } }
29.838235
136
0.604731
[ "MIT" ]
Angellomix/Squiggle
Squiggle.UI/Components/NetworkSignout.cs
2,031
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data.SqlClient; using System.Drawing.Printing; using bv.model.BLToolkit; using DevExpress.XtraPrinting; using DevExpress.XtraReports.UI; using eidss.model.Reports; using eidss.model.Reports.AZ; using EIDSS.Reports.BaseControls.Report; using EIDSS.Reports.Parameterized.Human.AJ.DataSets; namespace EIDSS.Reports.Parameterized.Human.AJ.Reports { [CanWorkWithArchive] [NullableAdapters] public partial class VetSummaryReport : BaseIntervalReport { private bool m_IsRegionPrint = true; public VetSummaryReport() { InitializeComponent(); } public void SetParameters(VetSummaryModel model, DbManagerProxy manager, DbManagerProxy archiveManager) { base.SetParameters(model, manager, archiveManager); BindHeader(model); VetSummaryDataSet.spRepVetSummaryAZDataTable sourceTable = m_SummaryDataSet.spRepVetSummaryAZ; Action<SqlConnection, SqlTransaction> action = ((connection, transaction) => { m_SummaryAdapter.Connection = connection; m_SummaryAdapter.Transaction = transaction; m_SummaryAdapter.CommandTimeout = CommandTimeout; m_SummaryDataSet.EnforceConstraints = false; m_SummaryAdapter.Fill(sourceTable, model); }); var ignoreName = new List<string> {"intRegionOrder", "intSubcolumnCount"}; FillDataTableWithArchive(action, ReportArchiveHelper.RemoveAndAddColumnToArchive, manager, archiveManager, sourceTable, model.Mode, new[] {"strRegion", "strRayon"}, ignoreName.ToArray()); sourceTable.DefaultView.Sort = "intRegionOrder, strRegion, strRayon"; CreateDynamicTable(sourceTable, model); } private void BindHeader(VetSummaryModel model) { DateTimeCell.Text = ReportRebinder.ToDateTimeString(DateTime.Now); ReportNameCell.Text = string.Format(ReportNameCell.Text, ReportRebinder.ToDateString(model.StartDate), ReportRebinder.ToDateString(model.EndDate)); DiagnosisNameCell.Text = String.Format(DiagnosisNameCell.Text, model.DiagnosisName); SurveillanceTypeCell.Text = String.Format(SurveillanceTypeCell.Text, model.SurveillanceTypeName); DynamicDiseaseHeaderCell.Text = model.ActionMethodName; } private void CreateDynamicTable(VetSummaryDataSet.spRepVetSummaryAZDataTable sourceTable, VetSummaryModel model) { if (sourceTable == null || sourceTable.Count == 0) { return; } try { ((ISupportInitialize) (HeaderDynamicTable)).BeginInit(); ((ISupportInitialize) (DetailDynamicTable)).BeginInit(); ((ISupportInitialize) (SubtotalDynamicTable)).BeginInit(); ((ISupportInitialize) (TotalDynamicTable)).BeginInit(); var resources = new ComponentResourceManager(typeof (VetSummaryReport)); bool hideSecondDetail = false; if (model.SurveillanceType == VetSummarySurveillanceType.PassiveSurveillanceIndex) { DynamicFirstHeaderCell.Text = PassiveFirstLabel.Text; DynamicSecondHeaderCell.Text = PassiveSecondLabel.Text; } else if (model.SurveillanceType == VetSummarySurveillanceType.AggregateActionsIndex && sourceTable[0].intSubcolumnCount == 1) { hideSecondDetail = true; DynamicFirstHeaderCell.Text = AggregateFirstLabel.Text; } for (int speciesNum = 1; speciesNum <= model.TakeLimitedCheckedItems.Count; speciesNum++) { string suffix = string.Format("_{0}", speciesNum); CreateSpeciesHeader(resources, suffix); CreateSpeciesSubcolumnHeader(resources, suffix); CreateDetailSubcolumn(resources, DetailDynamicTableRow, SummaryRunning.None, suffix, "DynamicFirstDetailCell", "DynamicSecondDetailCell"); CreateDetailSubcolumn(resources, SubtotalDynamicTableRow, SummaryRunning.Group, suffix, "DynamicTotalSubtotalCell", "DynamicChildrenSubtotalCell"); CreateDetailSubcolumn(resources, TotalDynamicTableRow, SummaryRunning.Report, suffix, "DynamicTotalTotalCell", "DynamicChildrenTotalCell"); } float totalWidth = DynamicDiseaseHeaderCell.WidthF; DynamicMiddleTableRow.Cells.Remove(DynamicSpeciesHeaderCell); DynamicBottomTableRow.Cells.Remove(DynamicFirstHeaderCell); DynamicBottomTableRow.Cells.Remove(DynamicSecondHeaderCell); DetailDynamicTableRow.Cells.Remove(DynamicFirstDetailCell); DetailDynamicTableRow.Cells.Remove(DynamicSecondDetailCell); SubtotalDynamicTableRow.Cells.Remove(DynamicTotalSubtotalCell); SubtotalDynamicTableRow.Cells.Remove(DynamicChildrenSubtotalCell); TotalDynamicTableRow.Cells.Remove(DynamicTotalTotalCell); TotalDynamicTableRow.Cells.Remove(DynamicChildrenTotalCell); float width = totalWidth / (DynamicBottomTableRow.Cells.Count - 2); float subtotalWidth = width; if (hideSecondDetail) { subtotalWidth *= 2; } for (int i = SubtotalDynamicTableRow.Cells.Count-1; i >0 ; i--) { SubtotalDynamicTableRow.Cells[i].WidthF = subtotalWidth; TotalDynamicTableRow.Cells[i].WidthF = subtotalWidth; if (hideSecondDetail && i % 2 == 0) { SubtotalDynamicTableRow.Cells.RemoveAt(i); TotalDynamicTableRow.Cells.RemoveAt(i); } } for (int i = DynamicBottomTableRow.Cells.Count - 1; i > 1; i--) { DynamicBottomTableRow.Cells[i].WidthF = subtotalWidth; DetailDynamicTableRow.Cells[i].WidthF = subtotalWidth; if (hideSecondDetail && i % 2 == 1) { DynamicBottomTableRow.Cells.RemoveAt(i); DetailDynamicTableRow.Cells.RemoveAt(i); } } for (int i = 2; i < DynamicMiddleTableRow.Cells.Count; i++) { DynamicMiddleTableRow.Cells[i].WidthF = 2 * width; } for (int i = 2; i < DynamicTopTableRow.Cells.Count; i++) { DynamicTopTableRow.Cells[i].WidthF = 2 * width; } DynamicDiseaseHeaderCell.WidthF = totalWidth; if (model.SurveillanceType != VetSummarySurveillanceType.AggregateActionsIndex) { HeaderDynamicTable.Rows.Remove(DynamicTopTableRow); RegionHeaderCell.Borders |= BorderSide.Top; RayonHeaderCell.Borders |= BorderSide.Top; } } finally { ((ISupportInitialize) (TotalDynamicTable)).EndInit(); ((ISupportInitialize) (SubtotalDynamicTable)).EndInit(); ((ISupportInitialize) (DetailDynamicTable)).EndInit(); ((ISupportInitialize) (HeaderDynamicTable)).EndInit(); } } private void CreateSpeciesHeader(ComponentResourceManager resources, string suffix) { var speciesCell = new XRTableCell(); DynamicMiddleTableRow.Cells.Add(speciesCell); resources.ApplyResources(speciesCell, "DynamicSpeciesHeaderCell"); string speciesMember = "spRepVetSummaryAZ.strSpecies" + suffix; speciesCell.DataBindings.Add(new XRBinding("Text", null, speciesMember)); speciesCell.Name = "DynamicSpeciesHeaderCell" + suffix; } private void CreateSpeciesSubcolumnHeader(ComponentResourceManager resources, string suffix) { var firstCell = new XRTableCell {Name = "FirstSubcolumn" + suffix}; resources.ApplyResources(firstCell, "DynamicFirstHeaderCell"); firstCell.Text = DynamicFirstHeaderCell.Text; firstCell.Angle = DynamicFirstHeaderCell.Angle; var secondCell = new XRTableCell {Name = "SecondSubcolumn" + suffix}; resources.ApplyResources(secondCell, "DynamicSecondHeaderCell"); secondCell.Text = DynamicSecondHeaderCell.Text; secondCell.Angle = DynamicSecondHeaderCell.Angle; DynamicBottomTableRow.Cells.AddRange(new[] { firstCell, secondCell }); } private static void CreateDetailSubcolumn (ComponentResourceManager resources, XRTableRow row, SummaryRunning summary, string suffix, string firstCellName, string secondCellName) { var firstCell = new XRTableCell(); var secondCell = new XRTableCell(); row.Cells.AddRange(new[] { firstCell, secondCell }); firstCell.DataBindings.Add(new XRBinding("Text", null, "spRepVetSummaryAZ.intFirstSubcolumn" + suffix)); resources.ApplyResources(firstCell, firstCellName); firstCell.Name = firstCellName + suffix; if (summary != SummaryRunning.None) { firstCell.Summary = new XRSummary {Running = summary}; } secondCell.DataBindings.Add(new XRBinding("Text", null, "spRepVetSummaryAZ.intSecondSubcolumn" + suffix)); resources.ApplyResources(secondCell, secondCellName); secondCell.Name = secondCellName + suffix; secondCell.StylePriority.UseBorders = false; secondCell.StylePriority.UseTextAlignment = false; if (summary != SummaryRunning.None) { secondCell.Summary = new XRSummary {Running = summary}; } } private void RegionGroupCell_BeforePrint(object sender, PrintEventArgs e) { if (!m_IsRegionPrint) { RegionDetailCell.Text = string.Empty; RegionDetailCell.Borders = BorderSide.Left | BorderSide.Right; } else { RegionDetailCell.Borders = BorderSide.Left | BorderSide.Top | BorderSide.Right; } m_IsRegionPrint = false; } private void SubtotalCell_BeforePrint(object sender, PrintEventArgs e) { m_IsRegionPrint = true; } } }
42.851301
121
0.583239
[ "BSD-2-Clause" ]
EIDSS/EIDSS-Legacy
EIDSS v6.1/vb/EIDSS/EIDSS.Reports/Parameterized/Human/AJ/Reports/VetSummaryReport.cs
11,529
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace MVCServer { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { ServicePointManager.CheckCertificateRevocationList = false; ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
31.285714
124
0.722603
[ "Apache-2.0" ]
Bigsby/PoC
Web/Certifying/Tests/MVCServer/Global.asax.cs
878
C#
using MoreMountains.Tools; using UnityEngine; using TMPro; using System.Collections; namespace MoreMountains.Feedbacks { /// <summary> /// This feedback lets you control the color of a target TMP's outline over time /// </summary> [AddComponentMenu("")] [FeedbackHelp("This feedback lets you control the color of a target TMP's outline over time.")] [FeedbackPath("TextMesh Pro/TMP Outline Color")] public class MMFeedbackTMPOutlineColor : MMFeedback { public enum ColorModes { Instant, Gradient, Interpolate } /// the duration of this feedback is the duration of the color transition, or 0 if instant public override float FeedbackDuration { get { return (ColorMode == ColorModes.Instant) ? 0f : ApplyTimeMultiplier(Duration); } set { Duration = value; } } /// sets the inspector color for this feedback #if UNITY_EDITOR public override Color FeedbackColor { get { return MMFeedbacksInspectorColors.TMPColor; } } #endif [Header("Target")] /// the TMP_Text component to control [Tooltip("the TMP_Text component to control")] public TMP_Text TargetTMPText; [Header("Outline Color")] /// the selected color mode : /// None : nothing will happen, /// gradient : evaluates the color over time on that gradient, from left to right, /// interpolate : lerps from the current color to the destination one [Tooltip("the selected color mode :" + "None : nothing will happen," + "gradient : evaluates the color over time on that gradient, from left to right," + "interpolate : lerps from the current color to the destination one ")] public ColorModes ColorMode = ColorModes.Interpolate; /// how long the color of the text should change over time [Tooltip("how long the color of the text should change over time")] [MMFEnumCondition("ColorMode", (int)ColorModes.Interpolate, (int)ColorModes.Gradient)] public float Duration = 0.2f; /// the color to apply [Tooltip("the color to apply")] [MMFEnumCondition("ColorMode", (int)ColorModes.Instant)] public Color32 InstantColor = Color.yellow; /// the gradient to use to animate the color over time [Tooltip("the gradient to use to animate the color over time")] [MMFEnumCondition("ColorMode", (int)ColorModes.Gradient)] [GradientUsage(true)] public Gradient ColorGradient; /// the destination color when in interpolate mode [Tooltip("the destination color when in interpolate mode")] [MMFEnumCondition("ColorMode", (int)ColorModes.Interpolate)] public Color32 DestinationColor = Color.yellow; /// the curve to use when interpolating towards the destination color [Tooltip("the curve to use when interpolating towards the destination color")] [MMFEnumCondition("ColorMode", (int)ColorModes.Interpolate)] public AnimationCurve ColorCurve = new AnimationCurve(new Keyframe(0, 0), new Keyframe(0.5f, 1), new Keyframe(1, 0)); /// if this is true, calling that feedback will trigger it, even if it's in progress. If it's false, it'll prevent any new Play until the current one is over [Tooltip("if this is true, calling that feedback will trigger it, even if it's in progress. If it's false, it'll prevent any new Play until the current one is over")] public bool AllowAdditivePlays = false; protected Color _initialColor; protected Coroutine _coroutine; /// <summary> /// On init we store our initial outline color /// </summary> /// <param name="owner"></param> protected override void CustomInitialization(GameObject owner) { base.CustomInitialization(owner); if (TargetTMPText == null) { return; } _initialColor = TargetTMPText.outlineColor; } /// <summary> /// On Play we change our text's outline's color /// </summary> /// <param name="position"></param> /// <param name="feedbacksIntensity"></param> protected override void CustomPlayFeedback(Vector3 position, float feedbacksIntensity = 1.0f) { if (TargetTMPText == null) { return; } if (Active) { switch (ColorMode) { case ColorModes.Instant: TargetTMPText.outlineColor = InstantColor; break; case ColorModes.Gradient: if (!AllowAdditivePlays && (_coroutine != null)) { return; } _coroutine = StartCoroutine(ChangeColor()); break; case ColorModes.Interpolate: if (!AllowAdditivePlays && (_coroutine != null)) { return; } _coroutine = StartCoroutine(ChangeColor()); break; } } } /// <summary> /// Changes the color of the text's outline over time /// </summary> /// <returns></returns> protected virtual IEnumerator ChangeColor() { float journey = NormalPlayDirection ? 0f : FeedbackDuration; while ((journey >= 0) && (journey <= FeedbackDuration) && (FeedbackDuration > 0)) { float remappedTime = MMFeedbacksHelpers.Remap(journey, 0f, FeedbackDuration, 0f, 1f); SetColor(remappedTime); journey += NormalPlayDirection ? FeedbackDeltaTime : -FeedbackDeltaTime; yield return null; } SetColor(FinalNormalizedTime); _coroutine = null; yield break; } /// <summary> /// Applies the color change /// </summary> /// <param name="time"></param> protected virtual void SetColor(float time) { if (ColorMode == ColorModes.Gradient) { // we set our object inactive then active, otherwise for some reason outline color isn't applied. TargetTMPText.gameObject.SetActive(false); TargetTMPText.outlineColor = ColorGradient.Evaluate(time); TargetTMPText.gameObject.SetActive(true); } else if (ColorMode == ColorModes.Interpolate) { float factor = ColorCurve.Evaluate(time); TargetTMPText.gameObject.SetActive(false); TargetTMPText.outlineColor = Color.LerpUnclamped(_initialColor, DestinationColor, factor); TargetTMPText.gameObject.SetActive(true); } } } }
42.506024
175
0.585034
[ "MIT" ]
DuLovell/Battle-Simulator
Assets/Imported Assets/Feel/MMFeedbacks/MMFeedbacksForThirdParty/TextMeshPro/Feedbacks/MMFeedbackTMPOutlineColor.cs
7,058
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Runtime.InteropServices; using System.Drawing.Imaging; namespace WinFormsApp_final { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.SetHighDpiMode(HighDpiMode.SystemAware); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
22.294118
65
0.671504
[ "Apache-2.0" ]
cjh3020889729/The-PaddleX-QT-Visualize-GUI
deploy/cpp/docs/csharp_deploy/c#/Program.cs
758
C#
using System; using UIKit; namespace CustomTransitions { public partial class CPFirstViewController : UIViewController { public CPFirstViewController (IntPtr handle) : base (handle) { } partial void ButtonAction (UIButton sender) { UIViewController secondVC = Storyboard.InstantiateViewController ("SecondViewController"); CustomPresentationController presentationController = new CustomPresentationController (secondVC, this); secondVC.TransitioningDelegate = presentationController; PresentViewController (secondVC, true, null); } } }
27.047619
107
0.788732
[ "MIT" ]
Art-Lav/ios-samples
CustomTransitions/CustomTransitions/CustomPresentation/CPFirstViewController.cs
570
C#
// ReSharper disable all #pragma warning disable 67 #pragma warning disable 414 using System; using TestLibrary.Interfaces; namespace TestLibrary.Classes { public class InheritingClass : IInheritedInterface { public delegate void MyDelegate(); public event EventHandler MyEvent = null!; /// <inheritdoc /> public event EventHandler Event = null!; public string MyProperty { get; set; } = null!; /// <inheritdoc /> public string Property { get; set; } = null!; public void MyMethod() {} /// <inheritdoc /> public void Method() { throw new NotImplementedException(); } } }
20.677419
51
0.661466
[ "MIT" ]
hailstorm75/MarkDoc.Core
tests/TestLibrary/Classes/InheritingClass.cs
643
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.Batch.Protocol.Models { using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Runtime; using System.Runtime.Serialization; /// <summary> /// Defines values for JobAction. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum JobAction { [EnumMember(Value = "none")] None, [EnumMember(Value = "disable")] Disable, [EnumMember(Value = "terminate")] Terminate } internal static class JobActionEnumExtension { internal static string ToSerializedValue(this JobAction? value) { return value == null ? null : ((JobAction)value).ToSerializedValue(); } internal static string ToSerializedValue(this JobAction value) { switch( value ) { case JobAction.None: return "none"; case JobAction.Disable: return "disable"; case JobAction.Terminate: return "terminate"; } return null; } internal static JobAction? ParseJobAction(this string value) { switch( value ) { case "none": return JobAction.None; case "disable": return JobAction.Disable; case "terminate": return JobAction.Terminate; } return null; } } }
28.507463
81
0.560733
[ "MIT" ]
thangnguyen2001/azure-sdk-for-net
src/SDKs/Batch/DataPlane/Azure.Batch/GeneratedProtocol/Models/JobAction.cs
1,910
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace timw255.Sitefinity.RestClient.Model { public class FieldViewModel { public string ContentType { get; set; } public string FieldTypeName { get; set; } public bool IsBuiltIn { get; set; } public bool IsCustom { get; set; } public string Name { get; set; } public WcfFieldDefinition RelatedFieldDefinition { get; set; } public FieldViewModel() { } } }
26.454545
70
0.678694
[ "MIT" ]
timw255/timw255.Sitefinity.RestClient
timw255.Sitefinity.RestClient/Model/FieldViewModel.cs
584
C#
using Newtonsoft.Json; namespace ESI.NET.Models.Character { public class Affiliation { [JsonProperty("alliance_id")] public int AllianceId { get; set; } [JsonProperty("character_id")] public int CharacterId { get; set; } [JsonProperty("corporation_id")] public int CorporationId { get; set; } [JsonProperty("faction_id")] public int FactionId { get; set; } } }
22.1
46
0.608597
[ "MIT" ]
Slazanger/ESI.NET
ESI.NET/Models/Character/Affiliation.cs
444
C#
namespace Server.Utils { public enum UserRole { MANAGER, CLIENT } }
12
24
0.53125
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
ruialmeida51/ARQSI.Catalog
Server/Utils/UserRole.cs
96
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MOE.Common.Business { public class RLMDetectorCollection { private List<MOE.Common.Business.Detector> NBdetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> NBDetectors { get { return NBdetectors; } } private List<MOE.Common.Business.Detector> SBdetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> SBDetectors { get { return SBdetectors; } } private List<MOE.Common.Business.Detector> EBdetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> EBDetectors { get { return EBdetectors; } } private List<MOE.Common.Business.Detector> WBdetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> WBDetectors { get { return WBdetectors; } } private List<MOE.Common.Business.Detector> NBbikedetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> NBBikeDetectors { get { return NBbikedetectors; } } private List<MOE.Common.Business.Detector> SBbikedetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> SBBikeDetectors { get { return SBbikedetectors; } } private List<MOE.Common.Business.Detector> EBbikedetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> EBBikeDetectors { get { return EBbikedetectors; } } private List<MOE.Common.Business.Detector> WBbikedetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> WBBikeDetectors { get { return WBbikedetectors; } } private List<MOE.Common.Business.Detector> NBpeddetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> NBPedDetectors { get { return NBpeddetectors; } } private List<MOE.Common.Business.Detector> SBpeddetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> SBPedDetectors { get { return SBpeddetectors; } } private List<MOE.Common.Business.Detector> EBpeddetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> EBPedDetectors { get { return EBpeddetectors; } } private List<MOE.Common.Business.Detector> WBpeddetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> WBPedDetectors { get { return WBpeddetectors; } } private List<List<Detector>> pedDetectors = new List<List<Detector>>(); public List<List<Detector>> PedDetectors { get { return PedDetectors; } } private List<MOE.Common.Business.Detector> NBleftDetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> NBLeftDetectors { get { return NBleftDetectors; } } private List<MOE.Common.Business.Detector> SBleftDetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> SBLeftDetectors { get { return SBleftDetectors; } } private List<MOE.Common.Business.Detector> EBleftDetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> EBLeftDetectors { get { return EBleftDetectors; } } private List<MOE.Common.Business.Detector> WBleftDetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> WBLeftDetectors { get { return WBleftDetectors; } } private List<MOE.Common.Business.Detector> NBrightDetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> NBRightDetectors { get { return NBrightDetectors; } } private List<MOE.Common.Business.Detector> SBrightDetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> SBRightDetectors { get { return SBrightDetectors; } } private List<MOE.Common.Business.Detector> EBrightDetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> EBRightDetectors { get { return EBrightDetectors; } } private List<MOE.Common.Business.Detector> WBrightDetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> WBRightDetectors { get { return WBrightDetectors; } } private List<MOE.Common.Business.Detector> NBthruDetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> NBThruDetectors { get { return NBthruDetectors; } } private List<MOE.Common.Business.Detector> SBthruDetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> SBThruDetectors { get { return SBthruDetectors; } } private List<MOE.Common.Business.Detector> EBthruDetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> EBThruDetectors { get { return EBthruDetectors; } } private List<MOE.Common.Business.Detector> WBthruDetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> WBThruDetectors { get { return WBthruDetectors; } } private List<MOE.Common.Business.Detector> NBexitDetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> NBExitDetectors { get { return NBexitDetectors; } } private List<MOE.Common.Business.Detector> SBexitDetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> SBExitDetectors { get { return SBexitDetectors; } } private List<MOE.Common.Business.Detector> EBexitDetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> EBExitDetectors { get { return EBexitDetectors; } } private List<MOE.Common.Business.Detector> WBexitDetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> WBExitDetectors { get { return WBexitDetectors; } } private List<MOE.Common.Business.Detector> NBLTbikeDetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> NBLTBikeDetectors { get { return NBLTbikeDetectors; } } private List<MOE.Common.Business.Detector> NBRTbikeDetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> NBRTBikeDetectors { get { return NBRTbikeDetectors; } } private List<MOE.Common.Business.Detector> NBThrubikeDetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> NBThruBikeDetectors { get { return NBThrubikeDetectors; } } private List<MOE.Common.Business.Detector> SBLTbikeDetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> SBLTBikeDetectors { get { return SBLTbikeDetectors; } } private List<MOE.Common.Business.Detector> SBRTbikeDetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> SBRTBikeDetectors { get { return SBRTbikeDetectors; } } private List<MOE.Common.Business.Detector> SBThrubikeDetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> SBThruBikeDetectors { get { return SBThrubikeDetectors; } } private List<MOE.Common.Business.Detector> EBLTbikeDetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> EBLTBikeDetectors { get { return EBLTbikeDetectors; } } private List<MOE.Common.Business.Detector> EBRTbikeDetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> EBRTBikeDetectors { get { return EBRTbikeDetectors; } } private List<MOE.Common.Business.Detector> EBThrubikeDetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> EBThruBikeDetectors { get { return EBThrubikeDetectors; } } private List<MOE.Common.Business.Detector> WBLTbikeDetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> WBLTBikeDetectors { get { return WBLTbikeDetectors; } } private List<MOE.Common.Business.Detector> WBRTbikeDetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> WBRTBikeDetectors { get { return WBRTbikeDetectors; } } private List<MOE.Common.Business.Detector> WBThrubikeDetectors = new List<Detector>(); public List<MOE.Common.Business.Detector> WBThruBikeDetectors { get { return WBThrubikeDetectors; } } private string signalId; public string SignalId { get { return signalId; } } public List<MOE.Common.Business.Detector> DetectorsForRLM = new List<Detector>(); /// <summary> /// Default constructor for the DetectorCollection used in the Turning Movement Counts charts /// </summary> /// <param name="signalID"></param> /// <param name="startdate"></param> /// <param name="enddate"></param> /// <param name="binsize"></param> public RLMDetectorCollection(DateTime startdate, DateTime enddate, int binsize, MOE.Common.Models.Approach approach) { var dets = approach.GetDetectorsForMetricType(11); foreach (MOE.Common.Models.Detector detector in dets) { MOE.Common.Business.Detector Detector = new Detector(detector, startdate, enddate, binsize); DetectorsForRLM.Add(Detector); } //SortDetectors(); } /// <summary> /// Alternate Constructor for PDC type data. /// </summary> /// <param name="signalid"></param> /// <param name="ApproachDirection"></param> public RLMDetectorCollection(string signalID, string ApproachDirection) { MOE.Common.Models.Repositories.ISignalsRepository repository = MOE.Common.Models.Repositories.SignalsRepositoryFactory.Create(); var signal = repository.GetSignalBySignalID(signalID); List<MOE.Common.Models.Detector> dets = signal.GetDetectorsForSignalThatSupportAMetricByApproachDirection(11, ApproachDirection); foreach (MOE.Common.Models.Detector row in dets) { // MOE.Common.Business.Detector Detector = new Detector(row.DetectorID.ToString(), signalID, row.Det_Channel, row.Lane.LaneType, ApproachDirection); MOE.Common.Business.Detector Detector = new Detector(row.DetectorID.ToString(), signalID, row.DetChannel, row.Approach); DetectorsForRLM.Add(Detector); } } public MOE.Common.Business.ControllerEventLogs CombineDetectorData(DateTime startDate, DateTime endDate, string signalId) { MOE.Common.Models.SPM db = new MOE.Common.Models.SPM(); MOE.Common.Business.ControllerEventLogs detectortable = new MOE.Common.Business.ControllerEventLogs(signalId, startDate, endDate); List<MOE.Common.Business.ControllerEventLogs> Tables = new List<MOE.Common.Business.ControllerEventLogs>(); foreach (MOE.Common.Business.Detector Detector in DetectorsForRLM) { MOE.Common.Business.ControllerEventLogs TEMPdetectortable = new MOE.Common.Business.ControllerEventLogs(signalId, startDate, endDate, Detector.Channel, new List<int>() { 82 }); Tables.Add(TEMPdetectortable); } foreach (MOE.Common.Business.ControllerEventLogs Table in Tables) { detectortable.MergeEvents(Table); } return detectortable; } } }
37.954545
163
0.629461
[ "Apache-2.0" ]
AndreRSanchez/ATSPM
MOE.Common/Business/RLM/RLMDetectorCollection.cs
12,527
C#
namespace WindowsFormsApp11 { partial class Form1 { /// <summary> ///Gerekli tasarımcı değişkeni. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> ///Kullanılan tüm kaynakları temizleyin. /// </summary> ///<param name="disposing">yönetilen kaynaklar dispose edilmeliyse doğru; aksi halde yanlış.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer üretilen kod /// <summary> /// Tasarımcı desteği için gerekli metot - bu metodun ///içeriğini kod düzenleyici ile değiştirmeyin. /// </summary> private void InitializeComponent() { this.button1 = new System.Windows.Forms.Button(); this.textBox1 = new System.Windows.Forms.TextBox(); this.textBox2 = new System.Windows.Forms.TextBox(); this.button2 = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.textBox3 = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.textBox4 = new System.Windows.Forms.TextBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.textBox6 = new System.Windows.Forms.TextBox(); this.textBox7 = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.button3 = new System.Windows.Forms.Button(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.SuspendLayout(); // // button1 // this.button1.BackColor = System.Drawing.Color.LightCoral; this.button1.ForeColor = System.Drawing.SystemColors.ControlText; this.button1.Location = new System.Drawing.Point(29, 281); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(173, 38); this.button1.TabIndex = 0; this.button1.Text = "button1"; this.button1.UseVisualStyleBackColor = false; this.button1.Click += new System.EventHandler(this.button1_Click); // // textBox1 // this.textBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.textBox1.Location = new System.Drawing.Point(29, 244); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(199, 31); this.textBox1.TabIndex = 1; this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged); // // textBox2 // this.textBox2.Font = new System.Drawing.Font("Microsoft Sans Serif", 20.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.textBox2.Location = new System.Drawing.Point(111, 30); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(210, 38); this.textBox2.TabIndex = 2; // // button2 // this.button2.BackColor = System.Drawing.Color.Black; this.button2.Location = new System.Drawing.Point(135, 165); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(186, 35); this.button2.TabIndex = 3; this.button2.Text = "button2"; this.button2.UseVisualStyleBackColor = false; this.button2.Click += new System.EventHandler(this.button2_Click); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.label1.Location = new System.Drawing.Point(51, 84); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(55, 20); this.label1.TabIndex = 4; this.label1.Text = "ALAN:"; // // textBox3 // this.textBox3.Font = new System.Drawing.Font("Microsoft Sans Serif", 20.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.textBox3.Location = new System.Drawing.Point(111, 74); this.textBox3.Name = "textBox3"; this.textBox3.Size = new System.Drawing.Size(210, 38); this.textBox3.TabIndex = 5; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.label2.Location = new System.Drawing.Point(37, 30); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(68, 20); this.label2.TabIndex = 6; this.label2.Text = "KENAR:"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.label3.Location = new System.Drawing.Point(37, 134); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(69, 20); this.label3.TabIndex = 7; this.label3.Text = "ÇEVRE:"; // // textBox4 // this.textBox4.Font = new System.Drawing.Font("Microsoft Sans Serif", 20.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.textBox4.Location = new System.Drawing.Point(112, 121); this.textBox4.Name = "textBox4"; this.textBox4.Size = new System.Drawing.Size(210, 38); this.textBox4.TabIndex = 8; // // groupBox1 // this.groupBox1.BackColor = System.Drawing.Color.Maroon; this.groupBox1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; this.groupBox1.Controls.Add(this.textBox4); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.textBox3); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Controls.Add(this.button2); this.groupBox1.Controls.Add(this.textBox2); this.groupBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.groupBox1.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.groupBox1.Location = new System.Drawing.Point(12, 12); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(340, 209); this.groupBox1.TabIndex = 9; this.groupBox1.TabStop = false; this.groupBox1.Text = "KARE "; // // textBox6 // this.textBox6.Font = new System.Drawing.Font("Microsoft Sans Serif", 20.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.textBox6.Location = new System.Drawing.Point(83, 28); this.textBox6.Name = "textBox6"; this.textBox6.Size = new System.Drawing.Size(210, 38); this.textBox6.TabIndex = 11; // // textBox7 // this.textBox7.Font = new System.Drawing.Font("Microsoft Sans Serif", 20.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.textBox7.Location = new System.Drawing.Point(83, 77); this.textBox7.Name = "textBox7"; this.textBox7.Size = new System.Drawing.Size(210, 38); this.textBox7.TabIndex = 12; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.label4.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.label4.Location = new System.Drawing.Point(17, 41); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(60, 20); this.label4.TabIndex = 13; this.label4.Text = "SAYI1:"; // // label5 // this.label5.AutoSize = true; this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.label5.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.label5.Location = new System.Drawing.Point(17, 90); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(60, 20); this.label5.TabIndex = 14; this.label5.Text = "SAYI2:"; // // button3 // this.button3.BackColor = System.Drawing.Color.White; this.button3.ForeColor = System.Drawing.SystemColors.ControlText; this.button3.Location = new System.Drawing.Point(150, 121); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(143, 40); this.button3.TabIndex = 16; this.button3.Text = "HESAPLA"; this.button3.UseVisualStyleBackColor = false; this.button3.Click += new System.EventHandler(this.button3_Click); // // groupBox2 // this.groupBox2.BackColor = System.Drawing.Color.Black; this.groupBox2.Controls.Add(this.button3); this.groupBox2.Controls.Add(this.label5); this.groupBox2.Controls.Add(this.label4); this.groupBox2.Controls.Add(this.textBox7); this.groupBox2.Controls.Add(this.textBox6); this.groupBox2.ForeColor = System.Drawing.SystemColors.ButtonHighlight; this.groupBox2.Location = new System.Drawing.Point(372, 14); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(359, 206); this.groupBox2.TabIndex = 17; this.groupBox2.TabStop = false; this.groupBox2.Text = "HESAPLAMA"; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(128))))); this.ClientSize = new System.Drawing.Size(800, 450); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.Controls.Add(this.textBox1); this.Controls.Add(this.button1); this.Name = "Form1"; this.Text = "Form1"; this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button button1; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.Button button2; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox textBox3; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox textBox4; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.TextBox textBox6; private System.Windows.Forms.TextBox textBox7; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.Button button3; private System.Windows.Forms.GroupBox groupBox2; } }
50.50566
175
0.580992
[ "Apache-2.0" ]
ZEHLAND/Matematik-Hesaplar
WindowsFormsApp11/WindowsFormsApp11/Form1.Designer.cs
13,408
C#
// Copyright © Pixel Crushers. All rights reserved. using UnityEngine; using System.Collections; namespace PixelCrushers { /// <summary> /// Manages localization settings. /// </summary> public class UILocalizationManager : MonoBehaviour { [Tooltip("The PlayerPrefs key to store the player's selected language code.")] [SerializeField] private string m_currentLanguagePlayerPrefsKey = "Language"; [Tooltip("Overrides the global text table.")] [SerializeField] private TextTable m_textTable = null; private string m_currentLanguage = string.Empty; public static UILocalizationManager instance { get; private set; } /// <summary> /// The PlayerPrefs key to store the player's selected language code. /// </summary> public string currentLanguagePlayerPrefsKey { get { return m_currentLanguagePlayerPrefsKey; } set { m_currentLanguagePlayerPrefsKey = value; } } /// <summary> /// Overrides the global text table. /// </summary> public TextTable textTable { get { return (m_textTable != null) ? m_textTable : GlobalTextTable.textTable; } set { m_textTable = value; } } public string currentLanguage { get { return m_currentLanguage; } set { m_currentLanguage = value; UpdateUIs(value); } } private void Awake() { instance = this; if (!string.IsNullOrEmpty(currentLanguagePlayerPrefsKey) && PlayerPrefs.HasKey(currentLanguagePlayerPrefsKey)) { currentLanguage = PlayerPrefs.GetString(currentLanguagePlayerPrefsKey); } } private IEnumerator Start() { yield return new WaitForEndOfFrame(); // Wait for Text components to start. var languageCode = string.Empty; UpdateUIs(languageCode); } /// <summary> /// Updates the current language and all localized UIs. /// </summary> /// <param name="language">Language code defined in your Text Table.</param> public void UpdateUIs(string language) { m_currentLanguage = language; if (!string.IsNullOrEmpty(currentLanguagePlayerPrefsKey)) { PlayerPrefs.SetString(currentLanguagePlayerPrefsKey, language); } var localizeUIs = FindObjectsOfType<LocalizeUI>(); for (int i = 0; i < localizeUIs.Length; i++) { localizeUIs[i].UpdateText(); } } } }
29.755319
122
0.569896
[ "MIT" ]
desdemonhu/Bad-Behavior
Assets/Plugins/Pixel Crushers/Common/Scripts/UI/UILocalizationManager.cs
2,800
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.Web.V20181101.Outputs { [OutputType] public sealed class FileSystemApplicationLogsConfigResponse { /// <summary> /// Log level. /// </summary> public readonly string? Level; [OutputConstructor] private FileSystemApplicationLogsConfigResponse(string? level) { Level = level; } } }
25.071429
81
0.665242
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/Web/V20181101/Outputs/FileSystemApplicationLogsConfigResponse.cs
702
C#
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using System.Threading.Tasks; using Amazon.S3; using Amazon.S3.Model; using Amazon.S3.Transfer; using Branch.Apps.ServiceHalo4.Enums.Waypoint; using Branch.Clients.Cache; using Branch.Clients.Token; using Branch.Clients.Identity; using Branch.Clients.Json; using Branch.Clients.Http.Models; using Branch.Packages.Contracts.Common.Branch; using Branch.Packages.Contracts.ServiceToken; using Branch.Packages.Crypto; using Branch.Packages.Enums.Halo4; using Branch.Packages.Enums.ServiceIdentity; using Branch.Packages.Bae; using Branch.Packages.Extensions; using Branch.Packages.Models.Common.XboxLive; using Branch.Packages.Models.Halo4; using Branch.Packages.Models.XboxLive; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using External = Branch.Apps.ServiceHalo4.Models.Waypoint; using Branch.Clients.S3; namespace Branch.Apps.ServiceHalo4.Services { public partial class WaypointClient : CacheClient { private readonly TokenClient _tokenClient; private readonly JsonClient _presenceClient; private readonly JsonClient _statsClient; private readonly JsonClient _settingsClient; private readonly JsonClient _optionsClient; private readonly Transpiler _transpiler; private readonly Enricher _enricher; private const string presenceUrl = "https://presence.svc.halowaypoint.com/en-US/"; private const string statsUrl = "https://stats.svc.halowaypoint.com/en-US/"; private const string settingsUrl = "https://settings.svc.halowaypoint.com/"; private const string optionsUrl = "https://settings.svc.halowaypoint.com/RegisterClientService.svc/register/webapp/AE5D20DCFA0347B1BCE0A5253D116752"; private const string authHeader = "X-343-Authorization-Spartan"; public WaypointClient(TokenClient tokenClient, IdentityClient identityClient, S3Client s3Client) : base(s3Client) { this._tokenClient = tokenClient; this._transpiler = new Transpiler(); this._enricher = new Enricher(identityClient); this._presenceClient = new JsonClient(presenceUrl); this._statsClient = new JsonClient(statsUrl); this._settingsClient = new JsonClient(settingsUrl); this._optionsClient = new JsonClient(optionsUrl); } private async Task<T> requestWaypointData<T>(string path, Dictionary<string, string> query, string bucketKey) where T : External.WaypointResponse { var auth = await getTokenHeaders(); var opts = new Options(auth); // TODO(0xdeafcafe): Handle waypoint errors var response = await _statsClient.Do<T>("GET", path, query, opts); switch (response.StatusCode) { // Should never happen on player-related requests case ResponseCode.NotFound: throw new BaeException( "content_not_found", new Dictionary<string, object> { { "Path", path }, { "Query", query }, } ); case ResponseCode.PlayerHasNotPlayedHalo4: throw new BaeException("player_never_played"); case ResponseCode.Okay: case ResponseCode.Found: default: return response; } } private async Task<Dictionary<string, string>> getTokenHeaders() { var resp = await _tokenClient.GetHalo4Token(new ReqGetHalo4Token()); return new Dictionary<string, string> {{ "X-343-Tokenorization-Spartan", resp.SpartanToken }}; } public async Task<(ServiceRecordResponse serviceRecord, ICacheInfo cacheInfo)> GetServiceRecord(Identity identity) { var path = $"players/{identity.Gamertag}/h4/servicerecord"; var key = $"halo-4/service-record/{identity.XUIDStr}.json"; var expire = TimeSpan.FromMinutes(10); var cacheInfo = await fetchCacheInfo(key); if (cacheInfo != null && cacheInfo.IsFresh()) return (await fetchContent<ServiceRecordResponse>(key), cacheInfo); var response = await requestWaypointData<External.ServiceRecordResponse>(path, null, key); if (response == null && cacheInfo != null) return (await fetchContent<ServiceRecordResponse>(key), cacheInfo); // Transpile and enrich content var finalCacheInfo = new CacheInfo(DateTime.UtcNow, expire); var final = _transpiler.ServiceRecord(response); final = await _enricher.ServiceRecord(final, response); TaskExt.FireAndForget(() => cacheContent(key, final, finalCacheInfo)); return (final, finalCacheInfo); } public async Task<(RecentMatchesResponse recentMatches, ICacheInfo cacheInfo)> GetRecentMatches(Identity identity, GameMode gameMode, uint startAt, uint count) { var newCount = count + 1; var gameModeStr = gameMode.ToString("d"); var query = new Dictionary<string, string> { { "gamemodeid", gameModeStr }, { "startat", startAt.ToString() }, { "count", newCount.ToString() }, }; var path = $"players/{identity.Gamertag}/h4/matches"; var key = $"halo-4/recent-matches/{identity.XUIDStr}-{gameModeStr}-{startAt}-{newCount}.json"; var expire = TimeSpan.FromMinutes(10); var cacheInfo = await fetchCacheInfo(key); if (cacheInfo != null && cacheInfo.IsFresh()) return (await fetchContent<RecentMatchesResponse>(key), cacheInfo); var response = await requestWaypointData<External.RecentMatchesResponse>(path, query, key); if (response == null && cacheInfo != null) return (await fetchContent<RecentMatchesResponse>(key), cacheInfo); // Transpile and enrich content var final = _transpiler.RecentMatches(response, newCount); // final = await enricher.RecentMatches(final, response); // Nothing to enrich here I think var finalCacheInfo = new CacheInfo(DateTime.UtcNow, expire); TaskExt.FireAndForget(() => cacheContent(key, final, finalCacheInfo)); return (final, finalCacheInfo); } } }
36.918239
162
0.727428
[ "MIT" ]
sgrakeshm/branch
dotnet/Apps/ServiceHalo4/Services/WaypointClient.cs
5,872
C#
using System.Collections.Generic; namespace ScientificReport.DTO.Models.Conference { public class ConferenceIndexModel : PageModel { public IEnumerable<DAL.Entities.Conference> Conferences { get; set; } } }
21.3
71
0.788732
[ "MIT" ]
lnupmi11/ScientificReport
ScientificReport.DTO/Models/Conference/ConferenceIndexModel.cs
213
C#
using System.Linq; using AutoQueryable.Core.Clauses; namespace AutoQueryable.Core.Models { public class AutoQueryableContext : IAutoQueryableContext { private readonly IAutoQueryHandler _autoQueryHandler; public IQueryable<dynamic> TotalCountQuery { get; private set; } public IClauseValueManager ClauseValueManager { get; private set; } public string QueryString { get; private set; } public AutoQueryableContext(IAutoQueryHandler autoQueryHandler) { _autoQueryHandler = autoQueryHandler; } public dynamic GetAutoQuery<T>(IQueryable<T> query) where T : class { var result = _autoQueryHandler.GetAutoQuery(query); TotalCountQuery = _autoQueryHandler.TotalCountQuery; ClauseValueManager = _autoQueryHandler.ClauseValueManager; QueryString = _autoQueryHandler.QueryString; return result; } } }
35.518519
75
0.687174
[ "MIT" ]
Appsum/AutoQueryable
src/AutoQueryable/Core/Models/AutoQueryableContext.cs
961
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Azure.AppService.Outputs { [OutputType] public sealed class AppServiceLogsApplicationLogs { /// <summary> /// An `azure_blob_storage` block as defined below. /// </summary> public readonly Outputs.AppServiceLogsApplicationLogsAzureBlobStorage? AzureBlobStorage; [OutputConstructor] private AppServiceLogsApplicationLogs(Outputs.AppServiceLogsApplicationLogsAzureBlobStorage? azureBlobStorage) { AzureBlobStorage = azureBlobStorage; } } }
30.857143
118
0.715278
[ "ECL-2.0", "Apache-2.0" ]
AdminTurnedDevOps/pulumi-azure
sdk/dotnet/AppService/Outputs/AppServiceLogsApplicationLogs.cs
864
C#
using AzurePipelinesToGitHubActionsConverter.Core.AzurePipelines; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; namespace AzurePipelinesToGitHubActionsConverter.Core.Conversion.Serialization { public class AzurePipelinesSerialization<TTriggers, TVariables> { /// <summary> /// Deserialize an Azure DevOps Pipeline with a simple trigger/ string[] and simple variable list/ Dictionary<string, string> /// </summary> /// <param name="yaml">yaml to convert</param> /// <returns>Azure DevOps Pipeline with simple trigger and simple variables</returns> public static AzurePipelinesRoot<string[], Dictionary<string, string>> DeserializeSimpleTriggerAndSimpleVariables(string yaml) { AzurePipelinesRoot<string[], Dictionary<string, string>> azurePipeline = null; try { yaml = CleanYamlBeforeDeserialization(yaml); azurePipeline = GenericObjectSerialization.DeserializeYaml<AzurePipelinesRoot<string[], Dictionary<string, string>>>(yaml); } catch (Exception ex) { ConversionUtility.WriteLine($"{nameof(DeserializeSimpleTriggerAndSimpleVariables)} swallowed an exception: " + ex.Message, true); //Do nothing } return azurePipeline; } /// <summary> /// Deserialize an Azure DevOps Pipeline with a simple trigger/ string[] and simple variable list/ Dictionary<string, string> /// </summary> /// <param name="yaml">yaml to convert</param> /// <returns>Azure DevOps Pipeline with simple trigger and complex variables</returns> public static AzurePipelinesRoot<string[], AzurePipelines.Variable[]> DeserializeSimpleTriggerAndComplexVariables(string yaml) { AzurePipelinesRoot<string[], AzurePipelines.Variable[]> azurePipeline = null; try { yaml = CleanYamlBeforeDeserialization(yaml); azurePipeline = GenericObjectSerialization.DeserializeYaml<AzurePipelinesRoot<string[], AzurePipelines.Variable[]>>(yaml); } catch (Exception ex) { ConversionUtility.WriteLine($"{nameof(DeserializeSimpleTriggerAndComplexVariables)} swallowed an exception: " + ex.Message, true); //Do nothing } return azurePipeline; } /// <summary> /// Deserialize an Azure DevOps Pipeline with a complex trigger and simple variable list /// </summary> /// <param name="yaml">yaml to convert</param> /// <returns>Azure DevOps Pipeline with complex trigger and simple variables</returns> public static AzurePipelinesRoot<AzurePipelines.Trigger, Dictionary<string, string>> DeserializeComplexTriggerAndSimpleVariables(string yaml) { AzurePipelinesRoot<AzurePipelines.Trigger, Dictionary<string, string>> azurePipeline = null; try { yaml = CleanYamlBeforeDeserialization(yaml); azurePipeline = GenericObjectSerialization.DeserializeYaml<AzurePipelinesRoot<AzurePipelines.Trigger, Dictionary<string, string>>>(yaml); } catch (Exception ex) { ConversionUtility.WriteLine($"{nameof(DeserializeComplexTriggerAndSimpleVariables)} swallowed an exception: " + ex.Message, true); //Do nothing } return azurePipeline; } /// <summary> /// Deserialize an Azure DevOps Pipeline with a complex trigger and complex variable list /// </summary> /// <param name="yaml">yaml to convert</param> /// <returns>Azure DevOps Pipeline with complex trigger and complex variables</returns> public static AzurePipelinesRoot<AzurePipelines.Trigger, AzurePipelines.Variable[]> DeserializeComplexTriggerAndComplexVariables(string yaml) { //DANGER WILL ROBINSON - DANGER //Unlike the other deserializers, we need to leave this last error handler off - so that errors can be returned to the client, where as the others can fail so that they can try the next deserializer method. AzurePipelinesRoot<AzurePipelines.Trigger, AzurePipelines.Variable[]> azurePipeline; //try //{ yaml = CleanYamlBeforeDeserialization(yaml); azurePipeline = GenericObjectSerialization.DeserializeYaml<AzurePipelinesRoot<AzurePipelines.Trigger, AzurePipelines.Variable[]>>(yaml); //} //catch (Exception ex) //{ // //Do nothing //} return azurePipeline; } private static string CleanYamlBeforeDeserialization(string yaml) { //Handle a null input if (yaml == null) { yaml = ""; } //Not well documented, but repo:self is redundent, and hence we remove it if detected (https://stackoverflow.com/questions/53860194/azure-devops-resources-repo-self) yaml = yaml.Replace("- repo: self", ""); //Fix some variables that we can't use for property names because the "-" character is not allowed in c# properties, or it's a reserved word (e.g. if) yaml = yaml.Replace("ref:", "_ref:"); //Handle condition variable insertion syntax. This is a bit ugly. if (yaml.IndexOf("variables") >= 0) { StringBuilder processedYaml = new StringBuilder(); using (StringReader reader = new StringReader(yaml)) { int variablesIndentLevel = 0; bool scanningForVariables = false; string line; while ((line = reader.ReadLine()) != null) { //Find the lines with variables if (line.IndexOf("variables:") >= 0) { //Start tracking variables and record the variables indent level scanningForVariables = true; variablesIndentLevel = ConversionUtility.CountSpacesBeforeText(line); } else if (scanningForVariables == true) { //While scanning for variables, get the indent level. It should be (variablesIndentLevel + 2), if it's more than that, we have a variable insert. ConversionUtility.WriteLine("Scanning for vars: " + line, true); int lineIndentLevel = ConversionUtility.CountSpacesBeforeText(line); if ((variablesIndentLevel - (lineIndentLevel - 2)) == 0) { //If the line starts with a conditional insertation, then comment it out if (line.Trim().StartsWith("${{") == true) { line = "#" + line; } } else if (variablesIndentLevel - (lineIndentLevel - 2) <= 0) { //we found a variable insert and need to remove the first two spaces from the front of the variable line = line.Substring(2, line.Length - 2); } else if (variablesIndentLevel - (lineIndentLevel - 2) >= 0) //we are done with variables, and back at the next root node { scanningForVariables = false; } } processedYaml.AppendLine(line); } } yaml = processedYaml.ToString(); } return yaml; } } }
50.407407
218
0.569434
[ "MIT" ]
bytemech/AzurePipelinesToGitHubActionsConverter
src/AzurePipelinesToGitHubActionsConverter.Core/Conversion/Serialization/AzurePipelinesSerialization.cs
8,168
C#
using System; using System.Collections.Generic; using System.Text; namespace ChatBotPrime.Core.Events.EventArguments { public class ChatCommandReceivedEventArgs : EventArgs { public ChatCommandReceivedEventArgs(ChatCommand chatCommand) { ChatCommand = chatCommand; } public ChatCommand ChatCommand { get; private set; } } }
20.058824
62
0.782991
[ "MIT" ]
CrypticEngima/ChatBotPrime
ChatBotPrime.Core/Events/EventArguments/ChatCommandReceivedEventArgs.cs
343
C#
// // Copyright DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System.Net; using Cassandra.Connections; namespace Cassandra { /// <summary> /// Represents a client-side error indicating that all connections to a certain host have reached /// the maximum amount of in-flight requests supported. /// </summary> public class BusyPoolException : DriverException { /// <summary> /// Gets the host address. /// </summary> public IPEndPoint Address { get; } /// <summary> /// Gets the maximum amount of requests per connection. /// </summary> public int MaxRequestsPerConnection { get; } /// <summary> /// Gets the size of the pool. /// </summary> public int ConnectionLength { get; } /// <summary> /// Creates a new instance of <see cref="BusyPoolException"/>. /// </summary> public BusyPoolException(IPEndPoint address, int maxRequestsPerConnection, int connectionLength) : base(BusyPoolException.GetMessage(address, maxRequestsPerConnection, connectionLength)) { Address = address; MaxRequestsPerConnection = maxRequestsPerConnection; ConnectionLength = connectionLength; } private static string GetMessage(IPEndPoint address, int maxRequestsPerConnection, int connectionLength) { return $"All connections to host {address} are busy, {maxRequestsPerConnection} requests " + $"are in-flight on {(connectionLength > 0 ? "each " : "")}{connectionLength} connection(s)"; } private static string GetMessage(IConnectionEndPoint endPoint, int maxRequestsPerConnection, int connectionLength) { return $"All connections to host {endPoint.EndpointFriendlyName} are busy, {maxRequestsPerConnection} requests " + $"are in-flight on {(connectionLength > 0 ? "each " : "")}{connectionLength} connection(s)"; } } }
39.69697
126
0.642366
[ "Apache-2.0" ]
MendelMonteiro/csharp-driver
src/Cassandra/Exceptions/BusyPoolException.cs
2,622
C#
using System; using System.ComponentModel; using System.Windows.Forms; using System.IO; using HSDRaw; using HSDRawViewer.Tools; using HSDRawViewer.Sound; using System.Linq; namespace HSDRawViewer.GUI.Extra { public partial class SSMTool : Form { private string FilePath; private int StartIndex; public BindingList<DSP> Sounds = new BindingList<DSP>(); private DSPViewer dspViewer = new DSPViewer(); public ContextMenu CMenu = new ContextMenu(); public SSMTool() { InitializeComponent(); listBox1.DataSource = Sounds; listBox1.ContextMenu = CMenu; Text = "SSM Editor"; dspViewer.Dock = DockStyle.Fill; groupBox1.Controls.Add(dspViewer); CenterToScreen(); FormClosing += (sender, args) => { if (args.CloseReason == CloseReason.UserClosing) { dspViewer.Dispose(); args.Cancel = true; Hide(); } }; } #region Controls /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void openToolStripMenuItem_Click(object sender, EventArgs e) { var file = FileIO.OpenFile("SSM (*.ssm, *.sdi)|*.ssm;*.sdi"); if (file != null) { OpenFile(file); } } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { if(listBox1.SelectedItem is DSP dsp) { dspViewer.DSP = dsp; } } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void saveToolStripMenuItem_Click(object sender, EventArgs e) { if (FilePath == null) FilePath = FileIO.SaveFile("SSM (*.ssm)|*.ssm"); if (FilePath != null) Save(FilePath); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void saveAsToolStripMenuItem_Click(object sender, EventArgs e) { var filePath = FileIO.SaveFile("SSM (*.ssm)|*.ssm"); if (filePath != null) { Save(filePath); } } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void importDSPToolStripMenuItem_Click(object sender, EventArgs e) { var files = FileIO.OpenFiles(DSP.SupportedImportFilter); if (files != null) { foreach(var file in files) { var dsp = new DSP(); dsp.FromFormat(File.ReadAllBytes(file), Path.GetExtension(file)); Sounds.Add(dsp); } } } #endregion #region Functions public void MoveUp() { MoveItem(-1); } public void MoveDown() { MoveItem(1); } public void MoveItem(int direction) { // Checking selected item if (listBox1.SelectedItem == null || listBox1.SelectedIndex < 0) return; // No selected item - nothing to do // Calculate new index using move direction int newIndex = listBox1.SelectedIndex + direction; // Checking bounds of the range if (newIndex < 0 || newIndex >= listBox1.Items.Count) return; // Index out of range - nothing to do object selected = listBox1.SelectedItem; // Removing removable element listBox1.Items.Remove(selected); // Insert it in new position listBox1.Items.Insert(newIndex, selected); // Restore selection listBox1.SetSelected(newIndex, true); } #endregion public void OpenFile(string filePath) { Text = "SSM Editor - " + filePath; Sounds.Clear(); FilePath = filePath; if(Path.GetExtension(filePath).ToLower() == ".ssm") OpenSSM(filePath); if (Path.GetExtension(filePath).ToLower() == ".sdi") OpenSDI(filePath); if (listBox1.Items.Count > 0) listBox1.SelectedIndex = 0; } /// <summary> /// Used in Eighting Engine Games /// </summary> /// <param name="filePath"></param> private void OpenSDI(string filePath) { var sam = filePath.Replace(".sdi", ".sam"); if (!File.Exists(sam)) return; using (BinaryReaderExt r = new BinaryReaderExt(new FileStream(filePath, FileMode.Open))) using (BinaryReaderExt d = new BinaryReaderExt(new FileStream(sam, FileMode.Open))) { r.BigEndian = true; while(true) { var id = r.ReadInt32(); if (id == -1) break; var dataoffset = r.ReadUInt32(); var padding = r.ReadInt32(); var flags = r.ReadInt16(); var frequency = r.ReadInt16(); var value = r.ReadInt32(); r.Skip(8); // unknown uint coefOffset = r.ReadUInt32(); DSP dsp = new DSP(); dsp.Frequency = frequency; DSPChannel channel = new DSPChannel(); channel.NibbleCount = value; var temp = r.Position; var end = (uint)d.Length; if(r.ReadInt32() != -1) end = r.ReadUInt32(); r.Seek(coefOffset); r.ReadInt32(); r.ReadInt32(); for (int i = 0; i < 0x10; i++) channel.COEF[i] = r.ReadInt16(); r.Seek(temp); d.Seek(dataoffset); byte[] data = d.ReadBytes((int)(end - dataoffset)); channel.Data = data; channel.InitialPredictorScale = data[0]; dsp.Channels.Add(channel); Sounds.Add(dsp); } } } /// <summary> /// Melee's sound format /// </summary> /// <param name="filePath"></param> private void OpenSSM(string filePath) { var ssm = new SSM(); StartIndex = ssm.StartIndex; ssm.Open(filePath); foreach(var s in ssm.Sounds) Sounds.Add(s); } /// <summary> /// /// </summary> /// <param name="filePath"></param> private void Save(string filePath) { FilePath = filePath; var ssm = new SSM(); ssm.StartIndex = StartIndex; ssm.Sounds = Sounds.ToArray(); ssm.Save(filePath); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void listBox1_DoubleClick(object sender, EventArgs e) { dspViewer.PlaySound(); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void exportAllToolStripMenuItem_Click(object sender, EventArgs e) { var file = FileIO.SaveFile(DSP.SupportedExportFilter); if(file != null) { var sIndex = 0; foreach(var s in Sounds) { var o = Path.Combine(Path.GetDirectoryName(file), Path.GetFileNameWithoutExtension(file) + sIndex++.ToString("D2") + Path.GetExtension(file)); s.ExportFormat(o); //s.ExportFormat(folder + "\\sound_" + sIndex++ + "_channels_" + s.Channels.Count + "_frequency_" + s.Frequency + ".wav"); } } } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void buttonRemove_Click(object sender, EventArgs e) { if(listBox1.SelectedItem is DSP dsp) { Sounds.Remove(dsp); } } } }
28.396226
162
0.462569
[ "MIT" ]
Ploaj/HSDLib
HSDRawViewer/GUI/Extra/SSMTool.cs
9,032
C#
using RACSMicroservice.Models; using System.Collections.Generic; using System.Threading.Tasks; namespace RACSMicroservice.Repository { public interface IRACSSpecialOffer : IGenericRepository<CarSpecialOffer> { Task<IEnumerable<CarSpecialOffer>> GetSpecialOffersOfRacs(int racsId); Task<IEnumerable<CarSpecialOffer>> GetSpecialOffersOfAllRacs(); Task<CarSpecialOffer> GetSpecialOfferById(int specialOfferId); } }
34.538462
78
0.783964
[ "MIT" ]
bojanpisic/PP_WEB
Web2-Microservices/RACSMicroservice/Repository/IRACSSpecialOffer.cs
451
C#
using static AleaTK.Library; using static AleaTK.ML.Library; namespace AleaTK.ML.Operator { public class IteratedRnnCell<T> : Differentiable { public RnnType RnnType { get; } public bool IsTraining { get; } public int InputSize { get; } public int BatchSize { get; } public int HiddenSize { get; } public int NumLayers { get; } public double DropoutProbability { get; } public ulong DropoutSeed { get; } public Variable<T> Input { get; } public Variable<T> Output { get; } public Variable<T> W { get; } public Variable<T> HX { get; } public Variable<T> CX { get; } public Variable<T> HY { get; } public Variable<T> CY { get; } public Variable<T> H { get; } public Variable<T> C { get; } public Variable<byte> ReserveSpace { get; } public readonly Symbol RnnCellDescr = new Symbol(); public IteratedRnnCell(RnnType rnnRnnType, Variable<T> input, int numLayers, int hiddenSize, bool isTraining, double dropoutProbability, ulong dropoutSeed = 1337UL) { RnnType = rnnRnnType; IsTraining = isTraining; NumLayers = numLayers; HiddenSize = hiddenSize; DropoutProbability = isTraining ? dropoutProbability : 0.0; DropoutSeed = dropoutSeed; Util.EnsureEqual(3, input.Shape.Rank, "Input layout: (seqLength, batch, inputSize)"); Util.EnsureTrue(input.Shape[1] >= 0, "Input layout: (seqLength, batch, inputSize)"); Util.EnsureTrue(input.Shape[2] >= 0, "Input layout: (seqLength, batch, inputSize)"); Input = input; BatchSize = (int)input.Shape[1]; InputSize = (int)input.Shape[2]; // output Shape (seqLength, batchSize, hiddenSize) Output = Variable<T>(PartialShape.Create(-1, BatchSize, HiddenSize)); // W shape will be determined during initialization W = Parameter<T>(); // create variables for input hidden and cell state HX =Variable<T>(PartialShape.Create(NumLayers, BatchSize, HiddenSize)); CX =Variable<T>(PartialShape.Create(NumLayers, BatchSize, HiddenSize)); HY =Variable<T>(PartialShape.Create(NumLayers, BatchSize, HiddenSize)); CY =Variable<T>(PartialShape.Create(NumLayers, BatchSize, HiddenSize)); // state variable H and Y = (n - 1, layer, b, d), n is unknown var shape = PartialShape.Create(-1, NumLayers, BatchSize, HiddenSize); H = Library.Variable<T>(shape); C = Library.Variable<T>(shape); ReserveSpace = Library.Variable<byte>(); // construct the graph AddInput(Input); AddInput(W); AddOutput(Output); AddAuxVar(HX); AddAuxVar(CX); AddAuxVar(HY); AddAuxVar(CY); AddAuxVar(H); AddAuxVar(C); AddAuxVar(ReserveSpace); } public override void Initialize(Executor executor) { var cell = new RnnCell<T>(executor, RnnType, W, InputSize, BatchSize, HiddenSize, NumLayers, IsTraining, DropoutProbability, DropoutSeed); executor.Objects[RnnCellDescr] = cell; cell.Initialize(executor); base.Initialize(executor); } public void AssignInitialStates(Executor executor, Tensor<T> hx, Tensor<T> cx) { executor.AssignTensor(HX, hx); executor.AssignTensor(CX, cx); } public void AssignTerminalGradient(Executor executor, Tensor<T> dhy, Tensor<T> dcy) { executor.AssignGradient(HY, dhy, replace: true); executor.AssignGradient(CY, dcy, replace: true); } public void ZeroInitialStates(Executor executor) { executor.AssignTensor(HX, Fill(Shape.Create(HX.Shape.AsArray), ScalarOps.Conv<T>(0.0))); executor.AssignTensor(CX, Fill(Shape.Create(CX.Shape.AsArray), ScalarOps.Conv<T>(0.0))); } public void ZeroTerminalGradient(Executor executor) { executor.AssignGradient(HY, Fill(Shape.Create(HY.Shape.AsArray), ScalarOps.Conv<T>(0.0)), replace: true); executor.AssignGradient(CY, Fill(Shape.Create(CY.Shape.AsArray), ScalarOps.Conv<T>(0.0)), replace: true); } public override void Forward(Executor executor) { var cell = (RnnCell<T>) executor.Objects[RnnCellDescr]; // input should be allocated by the training procedure, so no need to give shape var input = executor.GetTensor(Input); var seqLength = input.Shape[0]; // output is the output of this op, so we need give shape to allocate it var output = executor.GetTensor(Output, Shape.Create(seqLength, BatchSize, HiddenSize)); // hx and cx is input, it must be assigned before running forward // hy and cy is output, we give shape to allocate them var hx = executor.GetTensor(HX); var cx = executor.GetTensor(CX); var hy = executor.GetTensor(HY, Shape.Create(HY.Shape.AsArray)); var cy = executor.GetTensor(CY, Shape.Create(CY.Shape.AsArray)); // h and c are for record the intermediate states h and c, it is of length seqLenght - 1 // if n = 1, then no need for this var shape = seqLength == 1 ? Shape.Create(1) : Shape.Create(seqLength - 1, NumLayers, BatchSize, HiddenSize); var h = seqLength == 1 ? null : executor.GetTensor(H, shape); var c = seqLength == 1 ? null : executor.GetTensor(C, shape); // reserveSpace, according to doc of cuDNN, must be kept for each step var reserveSpace = executor.GetTensor(ReserveSpace, Shape.Create(seqLength, cell.ReserveSize)); // iterate through the sequence one time step at a time for (var t = 0; t < seqLength; ++t) { cell.Input = input.Slice(t); cell.Output = output.Slice(t); cell.ReserveSpace = reserveSpace.Slice(t); if (t == 0) { cell.HX = hx; cell.CX = cx; } else { cell.HX = h.Slice(t - 1).Reshape(NumLayers, BatchSize, HiddenSize); cell.CX = c.Slice(t - 1).Reshape(NumLayers, BatchSize, HiddenSize); } if (t == seqLength - 1) { cell.HY = hy; cell.CY = cy; } else { cell.HY = h.Slice(t).Reshape(NumLayers, BatchSize, HiddenSize); cell.CY = c.Slice(t).Reshape(NumLayers, BatchSize, HiddenSize); } cell.Forward(executor); } } public override void Backward(Executor executor) { var cell = (RnnCell<T>)executor.Objects[RnnCellDescr]; // input and output should be there, cause this is backward() var input = executor.GetTensor(Input); var output = executor.GetTensor(Output); // dOutput should be allocated by the child op, but dInput should be allocated by us var dInput = executor.GetGradient(Input, input.Shape); var dOutput = executor.GetGradient(Output); // dhy and dcy should be set before calling backward, while dhx and dcx is part of // our output, so we give shape to allocate them var dhy = executor.GetGradient(HY); var dcy = executor.GetGradient(CY); var dhx = executor.GetGradient(HX, Shape.Create(HX.Shape.AsArray)); var dcx = executor.GetGradient(CX, Shape.Create(CX.Shape.AsArray)); // hx and cx are input, hy and cy are output of forward, they are allocated, no need // to give shape to allocate var hx = executor.GetTensor(HX); var cx = executor.GetTensor(CX); var hy = executor.GetTensor(HY); var cy = executor.GetTensor(CY); // h and c are there by forward, no need to give shape to allocate // dh and dc we need allocate // TODO: actually dh and dc is not needed for each step, we can use swap to reduce memory cost var seqLength = (int)input.Shape[0]; var shape = seqLength == 1 ? Shape.Create(1) : Shape.Create(seqLength - 1, NumLayers, BatchSize, HiddenSize); var h = seqLength == 1 ? null : executor.GetTensor(H); var c = seqLength == 1 ? null : executor.GetTensor(C); var dh = seqLength == 1 ? null : executor.GetGradient(H, shape); var dc = seqLength == 1 ? null : executor.GetGradient(C, shape); // reserveSpace should be calculated by forward var reserveSpace = executor.GetTensor(ReserveSpace); for (var t = seqLength - 1; t >= 0; --t) { cell.Input = input.Slice(t); cell.Output = output.Slice(t); cell.DOutput = dOutput.Slice(t); cell.DInput = dInput.Slice(t); cell.ReserveSpace = reserveSpace.Slice(t); if (t == seqLength - 1) { cell.HY = hy; cell.CY = cy; cell.DHY = dhy; cell.DCY = dcy; } else { cell.HY = h.Slice(t).Reshape(NumLayers, BatchSize, HiddenSize); cell.CY = c.Slice(t).Reshape(NumLayers, BatchSize, HiddenSize); cell.DHY = dh.Slice(t).Reshape(NumLayers, BatchSize, HiddenSize); cell.DCY = dc.Slice(t).Reshape(NumLayers, BatchSize, HiddenSize); } if (t == 0) { cell.HX = hx; cell.CX = cx; cell.DHX = dhx; cell.DCX = dcx; } else { cell.HX = h.Slice(t - 1).Reshape(NumLayers, BatchSize, HiddenSize); cell.CX = c.Slice(t - 1).Reshape(NumLayers, BatchSize, HiddenSize); cell.DHX = dh.Slice(t - 1).Reshape(NumLayers, BatchSize, HiddenSize); cell.DCX = dc.Slice(t - 1).Reshape(NumLayers, BatchSize, HiddenSize); } cell.Backward(executor); } } } }
42.494071
172
0.552135
[ "Apache-2.0" ]
fastai/AleaTK
src/AleaTK/ML/Operator/IteratedRnnCell.cs
10,751
C#
using Microsoft.Extensions.DependencyInjection; using Ocelot.Configuration; using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; using Shouldly; using System; using TestStack.BDDfy; using Xunit; namespace Ocelot.UnitTests.Configuration { using Microsoft.AspNetCore.Http; using Ocelot.Logging; using System.Net.Http; using System.Threading; using System.Threading.Tasks; public class HttpHandlerOptionsCreatorTests { private IHttpHandlerOptionsCreator _httpHandlerOptionsCreator; private FileReRoute _fileReRoute; private HttpHandlerOptions _httpHandlerOptions; private IServiceProvider _serviceProvider; private IServiceCollection _serviceCollection; public HttpHandlerOptionsCreatorTests() { _serviceCollection = new ServiceCollection(); _serviceProvider = _serviceCollection.BuildServiceProvider(); _httpHandlerOptionsCreator = new HttpHandlerOptionsCreator(_serviceProvider); } [Fact] public void should_not_use_tracing_if_fake_tracer_registered() { var fileReRoute = new FileReRoute { HttpHandlerOptions = new FileHttpHandlerOptions { UseTracing = true } }; var expectedOptions = new HttpHandlerOptions(false, false, false, true); this.Given(x => GivenTheFollowing(fileReRoute)) .When(x => WhenICreateHttpHandlerOptions()) .Then(x => ThenTheFollowingOptionsReturned(expectedOptions)) .BDDfy(); } [Fact] public void should_use_tracing_if_real_tracer_registered() { var fileReRoute = new FileReRoute { HttpHandlerOptions = new FileHttpHandlerOptions { UseTracing = true } }; var expectedOptions = new HttpHandlerOptions(false, false, true, true); this.Given(x => GivenTheFollowing(fileReRoute)) .And(x => GivenARealTracer()) .When(x => WhenICreateHttpHandlerOptions()) .Then(x => ThenTheFollowingOptionsReturned(expectedOptions)) .BDDfy(); } [Fact] public void should_create_options_with_useCookie_false_and_allowAutoRedirect_true_as_default() { var fileReRoute = new FileReRoute(); var expectedOptions = new HttpHandlerOptions(false, false, false, true); this.Given(x => GivenTheFollowing(fileReRoute)) .When(x => WhenICreateHttpHandlerOptions()) .Then(x => ThenTheFollowingOptionsReturned(expectedOptions)) .BDDfy(); } [Fact] public void should_create_options_with_specified_useCookie_and_allowAutoRedirect() { var fileReRoute = new FileReRoute { HttpHandlerOptions = new FileHttpHandlerOptions { AllowAutoRedirect = false, UseCookieContainer = false, UseTracing = false } }; var expectedOptions = new HttpHandlerOptions(false, false, false, true); this.Given(x => GivenTheFollowing(fileReRoute)) .When(x => WhenICreateHttpHandlerOptions()) .Then(x => ThenTheFollowingOptionsReturned(expectedOptions)) .BDDfy(); } [Fact] public void should_create_options_with_useproxy_true_as_default() { var fileReRoute = new FileReRoute { HttpHandlerOptions = new FileHttpHandlerOptions() }; var expectedOptions = new HttpHandlerOptions(false, false, false, true); this.Given(x => GivenTheFollowing(fileReRoute)) .When(x => WhenICreateHttpHandlerOptions()) .Then(x => ThenTheFollowingOptionsReturned(expectedOptions)) .BDDfy(); } [Fact] public void should_create_options_with_specified_useproxy() { var fileReRoute = new FileReRoute { HttpHandlerOptions = new FileHttpHandlerOptions { UseProxy = false } }; var expectedOptions = new HttpHandlerOptions(false, false, false, false); this.Given(x => GivenTheFollowing(fileReRoute)) .When(x => WhenICreateHttpHandlerOptions()) .Then(x => ThenTheFollowingOptionsReturned(expectedOptions)) .BDDfy(); } private void GivenTheFollowing(FileReRoute fileReRoute) { _fileReRoute = fileReRoute; } private void WhenICreateHttpHandlerOptions() { _httpHandlerOptions = _httpHandlerOptionsCreator.Create(_fileReRoute.HttpHandlerOptions); } private void ThenTheFollowingOptionsReturned(HttpHandlerOptions expected) { _httpHandlerOptions.ShouldNotBeNull(); _httpHandlerOptions.AllowAutoRedirect.ShouldBe(expected.AllowAutoRedirect); _httpHandlerOptions.UseCookieContainer.ShouldBe(expected.UseCookieContainer); _httpHandlerOptions.UseTracing.ShouldBe(expected.UseTracing); _httpHandlerOptions.UseProxy.ShouldBe(expected.UseProxy); } private void GivenARealTracer() { var tracer = new FakeTracer(); _serviceCollection.AddSingleton<ITracer, FakeTracer>(); _serviceProvider = _serviceCollection.BuildServiceProvider(); _httpHandlerOptionsCreator = new HttpHandlerOptionsCreator(_serviceProvider); } private class FakeTracer : ITracer { public void Event(HttpContext httpContext, string @event) { throw new NotImplementedException(); } public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken, Action<string> addTraceIdToRepo, Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> baseSendAsync) { throw new NotImplementedException(); } } } }
35.351648
152
0.609263
[ "MIT" ]
AliWieckowicz/Ocelot
test/Ocelot.UnitTests/Configuration/HttpHandlerOptionsCreatorTests.cs
6,436
C#
/* * This is to print 2 threads alternatively. * It can be used to print 2 strings or print even and odd numbers alternatively */ using System; using System.Threading; namespace MultiThreading { public class TikTok { private readonly AutoResetEvent _autoEventTik = new AutoResetEvent(false); private readonly AutoResetEvent _autoEventTok = new AutoResetEvent(false); private int _maxCount = 10; public TikTok() { } public void PrintTik() { for (int i = 0; i < _maxCount; i++) { Console.WriteLine("Tik"); _autoEventTok.Set(); _autoEventTik.WaitOne(); } } public void PrintTok() { for (int i = 0; i < _maxCount; i++) { _autoEventTok.WaitOne(); Console.WriteLine("Tok"); _autoEventTik.Set(); } } private void PrintTik1() { for (int i = 0; i < _maxCount; i++) { lock (this) { Console.WriteLine("Tik"); Thread.Sleep(1000); } } } private void PrintTok1() { for (int i = 0; i < _maxCount; i++) { lock (this) { Console.WriteLine("Tok"); Thread.Sleep(1000); } } } private void PrintEven() { for (int even = 0; even <= 10; even += 1) { if (even % 2 == 0) { Console.WriteLine($"{even}"); _autoEvent.WaitOne(2000); } } } private void PrintOdd() { for (int odd = 0; odd <= 10; odd += 1) { if (odd % 2 == 1) { Console.WriteLine($"{odd}"); _autoEvent.WaitOne(2000); } } } } }
23.933333
82
0.395079
[ "MIT" ]
Divya1384/BasicPrograms
MultiThreading/TikTok.cs
2,156
C#
/* * Copyright 2018 JDCLOUD.COM * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http:#www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Instance-Template * 与实例模板相关的接口 * * OpenAPI spec version: v1 * Contact: * * NOTE: This class is auto generated by the jdcloud code generator program. */ using System; using System.Collections.Generic; using System.Text; using JDCloudSDK.Core.Service; using JDCloudSDK.Core.Annotation; using Newtonsoft.Json; namespace JDCloudSDK.Vm.Apis { /// <summary> /// /// /// 删除单个实例模板。 /// /// /// /// 详细操作说明请参考帮助文档:[删除实例模板](https://docs.jdcloud.com/cn/virtual-machines/delete-instance-template) /// /// /// /// ## 接口说明 /// /// - 关联了高可用组的实例模板不可以删除。 /// /// /// </summary> public class DeleteInstanceTemplateRequest : JdcloudRequest { ///<summary> /// 地域ID。 ///Required:true ///</summary> [Required] [JsonProperty("regionId")] public string RegionIdValue{ get; set; } ///<summary> /// 实例模板ID。 ///Required:true ///</summary> [Required] public string InstanceTemplateId{ get; set; } } }
27.444444
117
0.604396
[ "Apache-2.0" ]
jdcloud-api/jdcloud-sdk-net
sdk/src/Service/Vm/Apis/DeleteInstanceTemplateRequest.cs
1,867
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Xunit; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Microsoft.Azure.Commands.AzureBackup.Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Commands.AzureBackup.Test")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("49823b4f-deb2-4cf5-a8e7-5118fc6a05d6")] // 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("3.3.1")] [assembly: AssemblyFileVersion("3.3.1")] [assembly: CollectionBehavior(DisableTestParallelization = true)]
42.230769
87
0.710838
[ "MIT" ]
yugangw-msft/azure-powershell
src/ResourceManager/AzureBackup/Commands.AzureBackup.Test/Properties/AssemblyInfo.cs
2,148
C#
using System.Collections.Generic; using System.Linq; namespace PoESkillTree.Computation.Common { /// <summary> /// The context for accessing the values of other calculation graph nodes in <see cref="IValue.Calculate"/>. /// </summary> public interface IValueCalculationContext { /// <summary> /// Returns all paths of the given stat. /// </summary> IEnumerable<PathDefinition> GetPaths(IStat stat); /// <summary> /// Returns the value of the specified node. /// </summary> NodeValue? GetValue(IStat stat, NodeType nodeType, PathDefinition path); /// <summary> /// Returns the values of all form nodes of the given form for the given stat-path combinations. /// The value of each form node will only be evaluated and returned at most once. /// </summary> IEnumerable<NodeValue?> GetValues(Form form, IEnumerable<(IStat stat, PathDefinition path)> paths); } public static class ValueCalculationContextExtensions { public static NodeValue? GetValue( this IValueCalculationContext context, IStat stat, NodeType nodeType = NodeType.Total) => context.GetValue(stat, nodeType, PathDefinition.MainPath); /// <summary> /// Returns the values of the nodes of all paths of the given type in the given stat's subgraph. /// </summary> public static IEnumerable<NodeValue?> GetValues( this IValueCalculationContext context, IStat stat, NodeType nodeType) => context.GetPaths(stat).Select(p => context.GetValue(stat, nodeType, p)); public static IEnumerable<NodeValue?> GetValues( this IValueCalculationContext context, Form form, IStat stat) => context.GetValues(form, stat, PathDefinition.MainPath); public static IEnumerable<NodeValue?> GetValues( this IValueCalculationContext context, Form form, IStat stat, PathDefinition path) => context.GetValues(form, new[] { (stat, path) }); public static IEnumerable<NodeValue?> GetValues( this IValueCalculationContext context, Form form, IEnumerable<IStat> stats, PathDefinition path) => context.GetValues(form, stats.Select(s => (s, path))); } }
43.962963
113
0.642376
[ "MIT" ]
ManuelOTuga/PoE
PoESkillTree.Computation.Common/IValueCalculationContext.cs
2,323
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _04_Trainlands { class lands { static void Main(string[] args) { var input = Console.ReadLine(); var trains = new Dictionary<string, Dictionary<string, int>>(); while (input!= "It's Training Men!") { if (input.Contains("=")) { var train = input.Split(new[] { " = " }, StringSplitOptions.RemoveEmptyEntries); var trainName = train[0]; var secondTrain = train[1]; if (trains.ContainsKey(trainName)) { trains.Remove(trainName); trains.Add(trainName, new Dictionary<string, int>()); foreach (var wagon in trains[secondTrain]) { trains[trainName][wagon.Key] = wagon.Value; //var name = wagon.Key; //var power = wagon.Value; // trains[trainName].Add(name, power); } } } else { var train = input.Split(new[] { " -> ", " : " }, StringSplitOptions.RemoveEmptyEntries); if (train.Length>2) { var trainName = train[0]; var wagon = train[1]; var power = int.Parse(train[2]); if (!trains.ContainsKey(trainName)) { trains.Add(trainName, new Dictionary<string, int>()); } if (!trains[trainName].ContainsKey(wagon)) { trains[trainName].Add(wagon, 0); } trains[trainName][wagon] = power; } else { var trainName = train[0]; var secondTrain = train[1]; if (!trains.ContainsKey(trainName)) { trains.Add(trainName, new Dictionary<string, int>()); } foreach (var wagon in trains[secondTrain]) { if (!trains[trainName].ContainsKey(wagon.Key)) { trains[trainName].Add(wagon.Key, 0); } trains[trainName][wagon.Key] = wagon.Value; } trains.Remove(secondTrain); } } input = Console.ReadLine(); } foreach (var train in trains.OrderByDescending(x => x.Value.Sum(z=>z.Value)).ThenBy(x => x.Value.Count())) { Console.WriteLine("Train: {0}", train.Key); foreach (var wagon in train.Value.ToDictionary(x => x.Key, y => y.Value).OrderByDescending(x=>x.Value)) { Console.WriteLine("###{0} - {1}", wagon.Key, wagon.Value); } } } } }
25.565217
109
0.57398
[ "MIT" ]
Tcetso/Fundamentals
Exam August 2017/04 Trainlands/lands.cs
2,354
C#
// ***************************************************************************** // BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) // © Component Factory Pty Ltd, 2006 - 2016, All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 13 Swallows Close, // Mornington, Vic 3931, Australia and are supplied subject to license terms. // // Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.461) // Version 5.461.0.0 www.ComponentFactory.com // ***************************************************************************** using System; using System.Windows.Forms; using ComponentFactory.Krypton.Toolkit; namespace ComponentFactory.Krypton.Ribbon { /// <summary> /// Create and manage the view for a ribbon specific ButtonSpec definition. /// </summary> public class ButtonSpecViewRibbon : ButtonSpecView { #region Instance Fields private ButtonSpecRibbonController _controller; #endregion #region Identity /// <summary> /// Initialize a new instance of the ButtonSpecViewRibbon class. /// </summary> /// <param name="redirector">Palette redirector.</param> /// <param name="paletteMetric">Source for metric values.</param> /// <param name="metricPadding">Padding metric for border padding.</param> /// <param name="manager">Reference to owning manager.</param> /// <param name="buttonSpec">Access</param> public ButtonSpecViewRibbon(PaletteRedirect redirector, IPaletteMetric paletteMetric, PaletteMetricPadding metricPadding, ButtonSpecManagerBase manager, ButtonSpec buttonSpec) : base(redirector, paletteMetric, metricPadding, manager, buttonSpec) { } #endregion #region Protected /// <summary> /// Create a button controller for the view. /// </summary> /// <param name="viewButton">View to be controlled.</param> /// <param name="needPaint">Paint delegate.</param> /// <param name="clickHandler">Reference to click handler.</param> /// <returns>Controller instance.</returns> public override ButtonSpecViewControllers CreateController(ViewDrawButton viewButton, NeedPaintHandler needPaint, MouseEventHandler clickHandler) { // Create a ribbon specific button controller _controller = new ButtonSpecRibbonController(viewButton, needPaint) { BecomesFixed = true }; _controller.Click += clickHandler; // If associated with a tooltip manager then pass mouse messages onto tooltip manager IMouseController mouseController = _controller; if (Manager.ToolTipManager != null) { mouseController = new ToolTipController(Manager.ToolTipManager, viewButton, _controller); } // Return a collection of controllers return new ButtonSpecViewControllers(mouseController, _controller, _controller); } /// <summary> /// Processes the finish of the button being pressed. /// </summary> /// <param name="sender">Source of the event.</param> /// <param name="e">An EventArgs that contains the event data.</param> protected override void OnFinishDelegate(object sender, EventArgs e) { // Ask the button to remove the fixed pressed appearance _controller.RemoveFixed(); } #endregion } }
45.11236
157
0.588792
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy/Krypton-NET-5.461
Source/Krypton Components/ComponentFactory.Krypton.Ribbon/ButtonSpec/ButtonSpecViewRibbon.cs
4,018
C#
using System; using System.Linq; using System.Collections.Generic; using Functional.Test; namespace Functional.Implementation { public static partial class F { // A better cross-type reducer /// <summary>applies a acc function to items in seq of T. fn(x,y) x is the accumulation, y is the item from the sequence, and an initial item, and applies the accumulation function acc to all the element.</summary><returns>A U</returns> [Coverage(TestCoverage.F_reduce_better_TU)] public static U reducebetter<T,U>(IEnumerable<T> seq, Func<T, U, U> fn, U init) { U u = init; foreach (T t in seq) u = fn(t, u); return u; } /// <summary>Takes an enumeration of T, an accumulation function. fn(x,y) x is the accumulation, y is the item from the sequence, and an initial item, and applies the accumulation function acc to all the element.</summary><returns>A U</returns> [Coverage(TestCoverage.F_reduce_init_T)] public static T reduce<T>(IEnumerable<T> lst, Func<T,T,T> fn, T item) { // fn(x,y) x is the accumulation, y is the item from the sequence return lst.Aggregate(item, fn); } /// <summary>Takes a sequence of T and an accumulation function. fn(x,y) x is the accumulation, y is the item from the sequence</summary><returns>the accumulation of the sequence</returns> [Coverage(TestCoverage.F_reduce_naked_T)] public static T reduce<T>(IEnumerable<T> lst, Func<T, T, T> fn) { return lst.Aggregate(fn); } /// <summary>Takes an enumeration of T, and applies the accumulation function acc to all the element.fn(x,y) x is the accumulation, y is the item from the sequence</summary><returns>A U</returns> [Coverage(TestCoverage.F_reduce_init_TU)] public static U reduce<T,U>(IEnumerable<T> lst, Func<U,T,U> fn, U item) { return lst.Aggregate<T,U,U>(item, fn, F.identity<U>); } } }
54.189189
253
0.657357
[ "Apache-2.0" ]
codecore/Functional
Functional/Implementation/Reduce.cs
2,005
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using BenchmarkDotNet.Configs; using BenchmarkDotNet.ConsoleArguments; using BenchmarkDotNet.ConsoleArguments.ListBenchmarks; using BenchmarkDotNet.Environments; using BenchmarkDotNet.Extensions; using BenchmarkDotNet.Loggers; using BenchmarkDotNet.Reports; using JetBrains.Annotations; namespace BenchmarkDotNet.Running { public class BenchmarkSwitcher { private readonly IUserInteraction userInteraction = new UserInteraction(); private readonly List<Type> types = new List<Type>(); private readonly List<Assembly> assemblies = new List<Assembly>(); internal BenchmarkSwitcher(IUserInteraction userInteraction) => this.userInteraction = userInteraction; [PublicAPI] public BenchmarkSwitcher(Type[] types) => this.types.AddRange(types); [PublicAPI] public BenchmarkSwitcher(Assembly assembly) => assemblies.Add(assembly); [PublicAPI] public BenchmarkSwitcher(Assembly[] assemblies) => this.assemblies.AddRange(assemblies); [PublicAPI] public BenchmarkSwitcher With(Type type) { types.Add(type); return this; } [PublicAPI] public BenchmarkSwitcher With(Type[] types) { this.types.AddRange(types); return this; } [PublicAPI] public BenchmarkSwitcher With(Assembly assembly) { assemblies.Add(assembly); return this; } [PublicAPI] public BenchmarkSwitcher With(Assembly[] assemblies) { this.assemblies.AddRange(assemblies); return this; } [PublicAPI] public static BenchmarkSwitcher FromTypes(Type[] types) => new BenchmarkSwitcher(types); [PublicAPI] public static BenchmarkSwitcher FromAssembly(Assembly assembly) => new BenchmarkSwitcher(assembly); [PublicAPI] public static BenchmarkSwitcher FromAssemblies(Assembly[] assemblies) => new BenchmarkSwitcher(assemblies); /// <summary> /// Run all available benchmarks. /// </summary> [PublicAPI] public IEnumerable<Summary> RunAll(IConfig config = null) => Run(new[] { "--filter", "*" }, config); /// <summary> /// Run all available benchmarks and join them to a single summary /// </summary> [PublicAPI] public Summary RunAllJoined(IConfig config = null) => Run(new[] { "--filter", "*", "--join" }, config).Single(); [PublicAPI] public IEnumerable<Summary> Run(string[] args = null, IConfig config = null) { // VS generates bad assembly binding redirects for ValueTuple for Full .NET Framework // we need to keep the logic that uses it in a separate method and create DirtyAssemblyResolveHelper first // so it can ignore the version mismatch ;) using (DirtyAssemblyResolveHelper.Create()) return RunWithDirtyAssemblyResolveHelper(args, config); } [MethodImpl(MethodImplOptions.NoInlining)] private IEnumerable<Summary> RunWithDirtyAssemblyResolveHelper(string[] args, IConfig config) { var notNullArgs = args ?? Array.Empty<string>(); var notNullConfig = config ?? DefaultConfig.Instance; var logger = notNullConfig.GetNonNullCompositeLogger(); var (isParsingSuccess, parsedConfig, options) = ConfigParser.Parse(notNullArgs, logger, notNullConfig); if (!isParsingSuccess) // invalid console args, the ConfigParser printed the error return Array.Empty<Summary>(); if (args == null && Environment.GetCommandLineArgs().Length > 1) // The first element is the executable file name logger.WriteLineHint("You haven't passed command line arguments to BenchmarkSwitcher.Run method. Running with default configuration."); if (options.PrintInformation) { logger.WriteLine(HostEnvironmentInfo.GetInformation()); return Array.Empty<Summary>(); } var effectiveConfig = ManualConfig.Union(notNullConfig, parsedConfig); var (allTypesValid, allAvailableTypesWithRunnableBenchmarks) = TypeFilter.GetTypesWithRunnableBenchmarks(types, assemblies, logger); if (!allTypesValid) // there were some invalid and TypeFilter printed errors return Array.Empty<Summary>(); if (allAvailableTypesWithRunnableBenchmarks.IsEmpty()) { userInteraction.PrintNoBenchmarksError(logger); return Array.Empty<Summary>(); } if (options.ListBenchmarkCaseMode != ListBenchmarkCaseMode.Disabled) { PrintList(logger, effectiveConfig, allAvailableTypesWithRunnableBenchmarks, options); return Array.Empty<Summary>(); } var benchmarksToFilter = options.UserProvidedFilters ? allAvailableTypesWithRunnableBenchmarks : userInteraction.AskUser(allAvailableTypesWithRunnableBenchmarks, logger); var filteredBenchmarks = TypeFilter.Filter(effectiveConfig, benchmarksToFilter); if (filteredBenchmarks.IsEmpty()) { userInteraction.PrintWrongFilterInfo(benchmarksToFilter, logger, options.Filters.ToArray()); return Array.Empty<Summary>(); } return BenchmarkRunnerClean.Run(filteredBenchmarks); } private static void PrintList(ILogger nonNullLogger, IConfig effectiveConfig, IReadOnlyList<Type> allAvailableTypesWithRunnableBenchmarks, CommandLineOptions options) { var printer = new BenchmarkCasesPrinter(options.ListBenchmarkCaseMode); var testNames = TypeFilter.Filter(effectiveConfig, allAvailableTypesWithRunnableBenchmarks) .SelectMany(p => p.BenchmarksCases) .Select(p => p.Descriptor.GetFilterName()) .Distinct(); printer.Print(testNames, nonNullLogger); } } }
46.592308
174
0.678884
[ "MIT" ]
m-mccormick/BenchmarkDotNet
src/BenchmarkDotNet/Running/BenchmarkSwitcher.cs
6,059
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // La información general de un ensamblado se controla mediante el siguiente // conjunto de atributos. Cambie estos valores de atributo para modificar la información // asociada con un ensamblado. [assembly: AssemblyTitle("Community.DataAccess")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Community.DataAccess")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Si establece ComVisible en false, los tipos de este ensamblado no estarán visibles // para los componentes COM. Si es necesario obtener acceso a un tipo en este ensamblado desde // COM, establezca el atributo ComVisible en true en este tipo. [assembly: ComVisible(false)] // El siguiente GUID sirve como id. de typelib si este proyecto se expone a COM. [assembly: Guid("3f972cf0-8ed4-48fc-ba93-00f21a60398f")] // La información de versión de un ensamblado consta de los cuatro valores siguientes: // // Versión principal // Versión secundaria // Número de compilación // Revisión // // Puede especificar todos los valores o usar los números de compilación y de revisión predeterminados // mediante el carácter "*", como se muestra a continuación: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
41.216216
102
0.758689
[ "MIT" ]
uialberto/uidapperusers
SolutionUibasoft/Community.DataAccess/Properties/AssemblyInfo.cs
1,543
C#
using CleanArchitectureCosmosDB.Infrastructure.CosmosDbData.Interfaces; using Microsoft.Azure.Cosmos; namespace CleanArchitectureCosmosDB.Infrastructure.CosmosDbData { public class CosmosDbContainer : ICosmosDbContainer { public Container _container { get; } public CosmosDbContainer(CosmosClient cosmosClient, string databaseName, string containerName) { this._container = cosmosClient.GetContainer(databaseName, containerName); } } }
31.166667
85
0.663102
[ "MIT" ]
AndoxADX/clean-architecture-azure-cosmos-db
src/CleanArchitectureCosmosDB.Infrastructure/CosmosDbData/CosmosDbContainer.cs
563
C#