content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Threading; namespace Haipa.CloudInit.ConfigDrive.Interop { [ClassInterface(ClassInterfaceType.None)] // ReSharper disable once InconsistentNaming internal sealed class DiscFormat2Data_EventsProvider : DiscFormat2Data_Events, IDisposable { public DiscFormat2Data_EventsProvider(object pointContainer) { lock (this) { if (_mConnectionPoint != null) return; _mAEventSinkHelpers = new Hashtable(); var eventsGuid = typeof(DDiscFormat2DataEvents).GUID; var connectionPointContainer = pointContainer as IConnectionPointContainer; connectionPointContainer?.FindConnectionPoint(ref eventsGuid, out _mConnectionPoint); } } public event DiscFormat2Data_EventsHandler Update { add { lock (this) { var helper = new DiscFormat2Data_SinkHelper(value); _mConnectionPoint.Advise(helper, out var cookie); helper.Cookie = cookie; _mAEventSinkHelpers.Add(helper.UpdateDelegate, helper); } } remove { lock (this) { if (!(_mAEventSinkHelpers[value] is DiscFormat2Data_SinkHelper helper)) return; _mConnectionPoint.Unadvise(helper.Cookie); _mAEventSinkHelpers.Remove(helper.UpdateDelegate); } } } public void Dispose() { Cleanup(); GC.SuppressFinalize(this); } ~DiscFormat2Data_EventsProvider() { Cleanup(); } private void Cleanup() { Monitor.Enter(this); try { foreach (DiscFormat2Data_SinkHelper helper in _mAEventSinkHelpers) { _mConnectionPoint.Unadvise(helper.Cookie); } _mAEventSinkHelpers.Clear(); Marshal.ReleaseComObject(_mConnectionPoint); } catch (SynchronizationLockException) { } finally { Monitor.Exit(this); } } private readonly Hashtable _mAEventSinkHelpers; private static IConnectionPoint _mConnectionPoint = null; } }
30.045977
101
0.548967
[ "MIT" ]
dbosoft/CloudInit.ConfigDrive
src/CloudInit.ConfigDrive.WindowsImaging/Interop/DiscFormat2Data_EventsProvider.cs
2,614
C#
using System; using System.Collections.Generic; using System.Reflection; using System.Linq; using UnityEditor; namespace UnityEngine.Rendering.HighDefinition { /// <summary> /// Volume debug settings. /// </summary> public class VolumeDebugSettings { /// <summary>Current volume component to debug.</summary> public int selectedComponent = 0; int m_SelectedCamera = 0; /// <summary>Current camera index to debug.</summary> public int selectedCameraIndex { get { #if UNITY_EDITOR if (m_SelectedCamera < 0 || m_SelectedCamera > cameras.Count + 1) return 0; #else if (m_SelectedCamera < 0 || m_SelectedCamera > cameras.Count) return 0; #endif return m_SelectedCamera; } set { m_SelectedCamera = value; } } /// <summary>Current camera to debug.</summary> public Camera selectedCamera { get { #if UNITY_EDITOR if (m_SelectedCamera <= 0 || m_SelectedCamera > cameras.Count + 1) return null; if (m_SelectedCamera == 1) return SceneView.lastActiveSceneView.camera; else return cameras[m_SelectedCamera - 2].GetComponent<Camera>(); #else if (m_SelectedCamera <= 0 || m_SelectedCamera > cameras.Count) return null; return cameras[m_SelectedCamera - 1].GetComponent<Camera>(); #endif } } /// <summary>Selected camera volume stack.</summary> public VolumeStack selectedCameraVolumeStack { get { Camera cam = selectedCamera; if (cam == null) return null; var stack = HDCamera.GetOrCreate(cam).volumeStack; if (stack != null) return stack; return VolumeManager.instance.stack; } } /// <summary>Selected camera volume layer mask.</summary> public LayerMask selectedCameraLayerMask { get { #if UNITY_EDITOR if (m_SelectedCamera <= 0 || m_SelectedCamera > cameras.Count + 1) return (LayerMask)0; if (m_SelectedCamera == 1) return -1; return cameras[m_SelectedCamera - 2].volumeLayerMask; #else if (m_SelectedCamera <= 0 || m_SelectedCamera > cameras.Count) return (LayerMask)0; return cameras[m_SelectedCamera - 1].volumeLayerMask; #endif } } /// <summary>Selected camera volume position.</summary> public Vector3 selectedCameraPosition { get { Camera cam = selectedCamera; if (cam == null) return Vector3.zero; var anchor = HDCamera.GetOrCreate(cam).volumeAnchor; if (anchor == null) // means the hdcamera has not been initialized { // So we have to update the stack manually if (cam.TryGetComponent<HDAdditionalCameraData>(out var data)) anchor = data.volumeAnchorOverride; if (anchor == null) anchor = cam.transform; var stack = selectedCameraVolumeStack; if (stack != null) VolumeManager.instance.Update(stack, anchor, selectedCameraLayerMask); } return anchor.position; } } /// <summary>Type of the current component to debug.</summary> public Type selectedComponentType { get { return componentTypes[selectedComponent - 1]; } set { var index = componentTypes.FindIndex(t => t == value); if (index != -1) selectedComponent = index + 1; } } static List<Type> s_ComponentTypes; /// <summary>List of Volume component types.</summary> static public List<Type> componentTypes { get { if (s_ComponentTypes == null) { s_ComponentTypes = VolumeManager.instance.baseComponentTypes .Where(t => !t.IsDefined(typeof(VolumeComponentDeprecated), false)) .OrderBy(t => ComponentDisplayName(t)) .ToList(); } return s_ComponentTypes; } } /// <summary>Returns the name of a component from its VolumeComponentMenu.</summary> /// <param name="component">A volume component.</param> /// <returns>The component display name.</returns> static public string ComponentDisplayName(Type component) { Attribute attrib = component.GetCustomAttribute(typeof(VolumeComponentMenu), false); if (attrib != null) return (attrib as VolumeComponentMenu).menu; return component.Name; } /// <summary>List of HD Additional Camera data.</summary> static public List<HDAdditionalCameraData> cameras {get; private set; } = new List<HDAdditionalCameraData>(); /// <summary>Register HDAdditionalCameraData for DebugMenu</summary> /// <param name="camera">The camera to register.</param> public static void RegisterCamera(HDAdditionalCameraData camera) { if (!cameras.Contains(camera)) cameras.Add(camera); } /// <summary>Unregister HDAdditionalCameraData for DebugMenu</summary> /// <param name="camera">The camera to unregister.</param> public static void UnRegisterCamera(HDAdditionalCameraData camera) { if (cameras.Contains(camera)) cameras.Remove(camera); } /// <summary>Get a VolumeParameter from a VolumeComponent</summary> /// <param name="component">The component to get the parameter from.</param> /// <param name="field">The field info of the parameter.</param> /// <returns>The volume parameter.</returns> public VolumeParameter GetParameter(VolumeComponent component, FieldInfo field) { return (VolumeParameter)field.GetValue(component); } /// <summary>Get a VolumeParameter from a VolumeComponent on the <see cref="selectedCameraVolumeStack"/></summary> /// <param name="field">The field info of the parameter.</param> /// <returns>The volume parameter.</returns> public VolumeParameter GetParameter(FieldInfo field) { VolumeStack stack = selectedCameraVolumeStack; return stack == null ? null : GetParameter(stack.GetComponent(selectedComponentType), field); } /// <summary>Get a VolumeParameter from a component of a volume</summary> /// <param name="volume">The volume to get the component from.</param> /// <param name="field">The field info of the parameter.</param> /// <returns>The volume parameter.</returns> public VolumeParameter GetParameter(Volume volume, FieldInfo field) { var profile = volume.HasInstantiatedProfile() ? volume.profile : volume.sharedProfile; if (!profile.TryGet(selectedComponentType, out VolumeComponent component)) return null; var param = GetParameter(component, field); if (!param.overrideState) return null; return param; } float[] weights = null; float ComputeWeight(Volume volume, Vector3 triggerPos) { var profile = volume.HasInstantiatedProfile() ? volume.profile : volume.sharedProfile; if (!volume.gameObject.activeInHierarchy) return 0; if (!volume.enabled || profile == null || volume.weight <= 0f) return 0; if (!profile.TryGet(selectedComponentType, out VolumeComponent component)) return 0; if (!component.active) return 0; float weight = Mathf.Clamp01(volume.weight); if (!volume.isGlobal) { var colliders = volume.GetComponents<Collider>(); // Find closest distance to volume, 0 means it's inside it float closestDistanceSqr = float.PositiveInfinity; foreach (var collider in colliders) { if (!collider.enabled) continue; var closestPoint = collider.ClosestPoint(triggerPos); var d = (closestPoint - triggerPos).sqrMagnitude; if (d < closestDistanceSqr) closestDistanceSqr = d; } float blendDistSqr = volume.blendDistance * volume.blendDistance; if (closestDistanceSqr > blendDistSqr) weight = 0f; else if (blendDistSqr > 0f) weight *= 1f - (closestDistanceSqr / blendDistSqr); } return weight; } Volume[] volumes = null; /// <summary>Get an array of volumes on the <see cref="selectedCameraLayerMask"/></summary> /// <returns>An array of volumes sorted by influence.</returns> public Volume[] GetVolumes() { return VolumeManager.instance.GetVolumes(selectedCameraLayerMask) .Where(v => v.sharedProfile != null) .Reverse().ToArray(); } VolumeParameter[,] savedStates = null; VolumeParameter[,] GetStates() { var fields = selectedComponentType .GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance) .Where(t => t.FieldType.IsSubclassOf(typeof(VolumeParameter))) .ToArray(); VolumeParameter[,] states = new VolumeParameter[volumes.Length, fields.Length]; for (int i = 0; i < volumes.Length; i++) { var profile = volumes[i].HasInstantiatedProfile() ? volumes[i].profile : volumes[i].sharedProfile; if (!profile.TryGet(selectedComponentType, out VolumeComponent component)) continue; for (int j = 0; j < fields.Length; j++) { var param = GetParameter(component, fields[j]);; states[i, j] = param.overrideState ? param : null; } } return states; } bool ChangedStates(VolumeParameter[,] newStates) { if (savedStates.GetLength(1) != newStates.GetLength(1)) return true; for (int i = 0; i < savedStates.GetLength(0); i++) { for (int j = 0; j < savedStates.GetLength(1); j++) { if ((savedStates[i, j] == null) != (newStates[i, j] == null)) return true; } } return false; } /// <summary>Updates the list of volumes and recomputes volume weights</summary> /// <param name="newVolumes">The new list of volumes.</param> /// <returns>True if the volume list have been updated.</returns> public bool RefreshVolumes(Volume[] newVolumes) { bool ret = false; if (volumes == null || !newVolumes.SequenceEqual(volumes)) { volumes = (Volume[])newVolumes.Clone(); savedStates = GetStates(); ret = true; } else { var newStates = GetStates(); if (savedStates == null || ChangedStates(newStates)) { savedStates = newStates; ret = true; } } var triggerPos = selectedCameraPosition; weights = new float[volumes.Length]; for (int i = 0; i < volumes.Length; i++) weights[i] = ComputeWeight(volumes[i], triggerPos); return ret; } /// <summary>Get the weight of a volume computed from the <see cref="selectedCameraPosition"/></summary> /// <param name="volume">The volume to compute weight for.</param> /// <returns>The weight of the volume.</returns> public float GetVolumeWeight(Volume volume) { if (weights == null) return 0; float total = 0f, weight = 0f; for (int i = 0; i < volumes.Length; i++) { weight = weights[i]; weight *= 1f - total; total += weight; if (volumes[i] == volume) return weight; } return 0f; } /// <summary>Determines if a volume as an influence on the interpolated value</summary> /// <param name="volume">The volume.</param> /// <returns>True if the given volume as an influence.</returns> public bool VolumeHasInfluence(Volume volume) { if (weights == null) return false; int index = Array.IndexOf(volumes, volume); if (index == -1) return false; return weights[index] != 0f; } } }
37.829201
150
0.540417
[ "MIT" ]
Acromatic/HDRP-Unity-Template-GitHub-Template
Library/PackageCache/com.unity.render-pipelines.high-definition@10.2.2/Runtime/Debug/VolumeDebug.cs
13,732
C#
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. namespace StyleCop.Analyzers.Test.CSharp7.ReadabilityRules { using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using StyleCop.Analyzers.ReadabilityRules; using Xunit; using static StyleCop.Analyzers.Test.Verifiers.StyleCopCodeFixVerifier< StyleCop.Analyzers.ReadabilityRules.SA1142ReferToTupleElementsByName, StyleCop.Analyzers.ReadabilityRules.SA1142CodeFixProvider>; /// <summary> /// This class contains the CSharp 7.x unit tests for SA1142. /// </summary> /// <seealso cref="SA1142ReferToTupleElementsByName"/> /// <seealso cref="SA1142CodeFixProvider"/> public class SA1142CSharp7UnitTests { /// <summary> /// Validate that tuple fields that are referenced by their name will not produce any diagnostics. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task ValidateFieldNameReferencesAsync() { var testCode = @" public class TestClass { public int TestMethod((int nameA, int nameB) p1, (int, int) p2, (int, int nameC) p3) { return p1.nameA + p1.nameB + p2.Item1 + p2.Item2 + p3.Item1 + p3.nameC; } } "; await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false); } /// <summary> /// Verify that tuple names referenced by their metadata name will produce the expected diagnostics. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [Fact] public async Task ValidateMetadataNameReferencesAsync() { var testCode = @" public class TestClass { public int TestMethod1((int nameA, int nameB) p1) { return p1.[|Item1|] + p1.[|Item2|] /* test */ + p1.ToString().Length; } public int TestMethod2((int nameA, (int subNameA, int subNameB) nameB) p1) { return p1.[|Item1|] + p1.nameB.[|Item1|] + p1.[|Item2|].[|Item2|]; } } "; var fixedCode = @" public class TestClass { public int TestMethod1((int nameA, int nameB) p1) { return p1.nameA + p1.nameB /* test */ + p1.ToString().Length; } public int TestMethod2((int nameA, (int subNameA, int subNameB) nameB) p1) { return p1.nameA + p1.nameB.subNameA + p1.nameB.subNameB; } } "; DiagnosticResult[] expectedDiagnostics = { // diagnostics are specified inline }; await VerifyCSharpFixAsync(testCode, expectedDiagnostics, fixedCode, CancellationToken.None).ConfigureAwait(false); } } }
33.465909
143
0.647199
[ "MIT" ]
AraHaan/StyleCopAnalyzers
StyleCop.Analyzers/StyleCop.Analyzers.Test.CSharp7/ReadabilityRules/SA1142CSharp7UnitTests.cs
2,947
C#
using DemoFluentPWA.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DemoFluentPWA.ViewModel { public class IndexViewModel { public IEnumerable<ItemModel> items { get; set; } } }
19.071429
57
0.737828
[ "MIT" ]
DotNetCodeIT/demoblogpwa
src/DemoFluentPWA/ViewModel/IndexViewModel.cs
269
C#
using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; public class EndScreen : MonoBehaviour { [SerializeField] private TextMeshProUGUI GameResult; [SerializeField] private TextMeshProUGUI TotalScore; public Animator TyAnimator; public readonly int isWon = Animator.StringToHash("IsWon"); public readonly int isLost = Animator.StringToHash("IsLost"); // Start is called before the first frame update void Start() { AudioManager.GetInstance().PlaySceneTrack(AudioManager.MusicTrack.BGM_EndScene,0.1f,0.2f); Cursor.visible = true; if (Data.isVictory) { TyAnimator.SetBool(isWon,true); TyAnimator.SetBool(isLost,false); GameResult.text = "You have Won!"; } else { TyAnimator.gameObject.GetComponent<Transform>().rotation = Quaternion.Euler(new Vector3(0f,90f,0f)); TyAnimator.SetBool(isLost, true); TyAnimator.SetBool(isWon, false); if (Data.isTimeOut) { GameResult.text = "Time Up! :("; } else { GameResult.text = "You Lost :("; } } TotalScore.text = Data.Score.ToString(); } }
26.32
112
0.597264
[ "MIT" ]
vineetk0807/GAME3033_Midterm_KumarVineet
Assets/[Scripts]/Data/EndScreen.cs
1,316
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.Dcdb.V20180411.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class DescribeDBParametersResponse : AbstractModel { /// <summary> /// 实例 ID,形如:dcdbt-ow7t8lmc。 /// </summary> [JsonProperty("InstanceId")] public string InstanceId{ get; set; } /// <summary> /// 请求DB的当前参数值 /// </summary> [JsonProperty("Params")] public ParamDesc[] Params{ get; set; } /// <summary> /// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 /// </summary> [JsonProperty("RequestId")] public string RequestId{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> internal override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "InstanceId", this.InstanceId); this.SetParamArrayObj(map, prefix + "Params.", this.Params); this.SetParamSimple(map, prefix + "RequestId", this.RequestId); } } }
31.12069
83
0.631579
[ "Apache-2.0" ]
ImEdisonJiang/tencentcloud-sdk-dotnet
TencentCloud/Dcdb/V20180411/Models/DescribeDBParametersResponse.cs
1,893
C#
using System.Collections.Generic; using MailChimp.Api.Net.Domain.Reports; namespace MailChimp.Api.Net.Domain.Lists { public class RootGoal { public List<Goal> goals { get; set; } public string list_id { get; set; } public string email_id { get; set; } public List<Link> _links { get; set; } public int total_items { get; set; } } }
25.733333
46
0.632124
[ "MIT" ]
kinamarie016/MailChimp.Api.Net-master
MailChimp.Api.Net/Domain/Lists/RootGoal.cs
388
C#
using SmartifyBotStudio.Models; using SmartifyBotStudio.RobotDesigner.Interfaces; using SmartifyBotStudio.RobotDesigner.Variable; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using SmartifyBotStudio.RobotDesigner.Variable; using Microsoft.Office.Core; using MExcel = Microsoft.Office.Interop.Excel; using System.Runtime.InteropServices; using OfficeOpenXml; using System.Windows; using System.Reflection; namespace SmartifyBotStudio.RobotDesigner.TaskModel.Excel { [Serializable] public class CloseExcel : RobotActionBase, ITask { public string ExcelFileToCloseVar { get; set; } public int ExcelClosingSchemaIndex = 3; public int ExcelInstanceComboIndex = 0; public string newFileName { get; set; } public int newFileNameExtIndex { get; set; } public string Var_StoreDeletedFiles { get; set; } public int Execute() { try { if (ExcelClosingSchemaIndex == 0) { VariableStorage.ExcelVar[ExcelFileToCloseVar].Item2.ActiveWorkbook.Close(false, Missing.Value, Missing.Value); } else if (ExcelClosingSchemaIndex == 1) { VariableStorage.ExcelVar[ExcelFileToCloseVar].Item2.ActiveWorkbook.Save(); VariableStorage.ExcelVar[ExcelFileToCloseVar].Item2.ActiveWorkbook.Close(); } else if (ExcelClosingSchemaIndex == 2) { if (newFileNameExtIndex == 0) { } VariableStorage.ExcelVar[ExcelFileToCloseVar].Item2.ActiveWorkbook.SaveAs(newFileName); VariableStorage.ExcelVar[ExcelFileToCloseVar].Item2.ActiveWorkbook.Close(); } return 1; } catch (Exception ex) { return 0; } } } }
29.385714
130
0.611084
[ "MIT" ]
codertuhin/BotStudio
SmartifyBotStudio/RobotDesigner/TaskModel/Excel/CloseExcel.cs
2,059
C#
using System; using System.Runtime.InteropServices; namespace hds { public class AttributeClass1732 :GameObject { public Attribute Orientation = new Attribute(16, "Orientation"); public Attribute Position = new Attribute(24, "Position"); public Attribute HalfExtents = new Attribute(12, "HalfExtents"); public AttributeClass1732(string name,UInt16 _goid) : base(3, 0, name, _goid, 0xFFFFFFFF) { AddAttribute(ref Orientation, 0, -1); AddAttribute(ref Position, 1, -1); AddAttribute(ref HalfExtents, 2, -1); } } }
24.166667
68
0.677586
[ "MIT" ]
hdneo/mxo-hd
hds/resources/gameobjects/definitions/AttributeClasses/AttributeClass1732.cs
580
C#
/* * Copyright (C) 2016-2020. Autumn Beauchesne. All rights reserved. * Author: Autumn Beauchesne * Date: 21 Nov 2016 * * File: TweenShortcuts.Material.cs * Purpose: Extension methods for creating Tweens affecting * properties on a Material. * * Notes: Ensure you're not accidentally leaking a cloned * material when you use these! */ using UnityEngine; namespace BeauRoutine { /// <summary> /// Contains helper functions for generating tweens. /// </summary> static public partial class TweenShortcuts { #region Alpha private sealed class TweenData_Material_Alpha : ITweenData { private Material m_Material; private float m_Target; private float m_Start; private float m_Delta; public TweenData_Material_Alpha(Material inMaterial, float inTarget) { m_Material = inMaterial; m_Target = inTarget; } public void OnTweenStart() { m_Start = m_Material.color.a; m_Delta = m_Target - m_Start; } public void OnTweenEnd() { } public void ApplyTween(float inPercent) { Color final = m_Material.color; final.a = m_Start + m_Delta * inPercent; m_Material.color = final; } public override string ToString() { return "Material: Alpha"; } } private sealed class TweenData_Material_AlphaProperty : ITweenData { private Material m_Material; private int m_Property; private float m_Target; private float m_Start; private float m_Delta; public TweenData_Material_AlphaProperty(Material inMaterial, int inProperty, float inTarget) { m_Material = inMaterial; m_Property = inProperty; m_Target = inTarget; } public void OnTweenStart() { m_Start = m_Material.GetColor(m_Property).a; m_Delta = m_Target - m_Start; } public void OnTweenEnd() { } public void ApplyTween(float inPercent) { Color final = m_Material.GetColor(m_Property); final.a = m_Start + m_Delta * inPercent; m_Material.SetColor(m_Property, final); } public override string ToString() { return "Material: Alpha (Property)"; } } /// <summary> /// Fades the Material to another alpha over time. /// </summary> static public Tween FadeTo(this Material inMaterial, float inAlpha, float inTime) { return Tween.Create(new TweenData_Material_Alpha(inMaterial, inAlpha), inTime); } /// <summary> /// Fades the Material to another alpha over time. /// </summary> static public Tween FadeTo(this Material inMaterial, float inAlpha, TweenSettings inSettings) { return Tween.Create(new TweenData_Material_Alpha(inMaterial, inAlpha), inSettings); } /// <summary> /// Fades a Material color property to another alpha over time. /// </summary> static public Tween FadeTo(this Material inMaterial, string inProperty, float inAlpha, float inTime) { return Tween.Create(new TweenData_Material_AlphaProperty(inMaterial, Shader.PropertyToID(inProperty), inAlpha), inTime); } /// <summary> /// Fades a Material color property to another alpha over time. /// </summary> static public Tween FadeTo(this Material inMaterial, string inProperty, float inAlpha, TweenSettings inSettings) { return Tween.Create(new TweenData_Material_AlphaProperty(inMaterial, Shader.PropertyToID(inProperty), inAlpha), inSettings); } /// <summary> /// Fades a Material color property to another alpha over time. /// </summary> static public Tween FadeTo(this Material inMaterial, int inPropertyID, float inAlpha, float inTime) { return Tween.Create(new TweenData_Material_AlphaProperty(inMaterial, inPropertyID, inAlpha), inTime); } /// <summary> /// Fades a Material color property to another alpha over time. /// </summary> static public Tween FadeTo(this Material inMaterial, int inPropertyID, float inAlpha, TweenSettings inSettings) { return Tween.Create(new TweenData_Material_AlphaProperty(inMaterial, inPropertyID, inAlpha), inSettings); } #endregion //Alpha #region Color private sealed class TweenData_Material_Color : ITweenData { private Material m_Material; private Color m_Target; private ColorUpdate m_Update; private Color m_Start; public TweenData_Material_Color(Material inMaterial, Color inTarget, ColorUpdate inUpdate) { m_Material = inMaterial; m_Target = inTarget; m_Update = inUpdate; } public void OnTweenStart() { m_Start = m_Material.color; } public void OnTweenEnd() { } public void ApplyTween(float inPercent) { Color final = UnityEngine.Color.LerpUnclamped(m_Start, m_Target, inPercent); if (m_Update == ColorUpdate.PreserveAlpha) final.a = m_Material.color.a; m_Material.color = final; } public override string ToString() { return "Material: Color"; } } private sealed class TweenData_Material_ColorProperty : ITweenData { private Material m_Material; private int m_Property; private Color m_Target; private ColorUpdate m_Update; private Color m_Start; public TweenData_Material_ColorProperty(Material inMaterial, int inProperty, Color inTarget, ColorUpdate inUpdate) { m_Material = inMaterial; m_Property = inProperty; m_Target = inTarget; m_Update = inUpdate; } public void OnTweenStart() { m_Start = m_Material.GetColor(m_Property); } public void OnTweenEnd() { } public void ApplyTween(float inPercent) { Color final = UnityEngine.Color.LerpUnclamped(m_Start, m_Target, inPercent); if (m_Update == ColorUpdate.PreserveAlpha) final.a = m_Material.GetColor(m_Property).a; m_Material.color = final; } public override string ToString() { return "Material: Color (Property)"; } } /// <summary> /// Fades the Material to another color over time. /// </summary> static public Tween ColorTo(this Material inMaterial, Color inTarget, float inTime, ColorUpdate inUpdate = ColorUpdate.PreserveAlpha) { return Tween.Create(new TweenData_Material_Color(inMaterial, inTarget, inUpdate), inTime); } /// <summary> /// Fades the Material to another color over time. /// </summary> static public Tween ColorTo(this Material inMaterial, Color inTarget, TweenSettings inSettings, ColorUpdate inUpdate = ColorUpdate.PreserveAlpha) { return Tween.Create(new TweenData_Material_Color(inMaterial, inTarget, inUpdate), inSettings); } /// <summary> /// Fades a Material color property to another color over time. /// </summary> static public Tween ColorTo(this Material inMaterial, string inProperty, Color inTarget, float inTime, ColorUpdate inUpdate = ColorUpdate.PreserveAlpha) { return Tween.Create(new TweenData_Material_ColorProperty(inMaterial, Shader.PropertyToID(inProperty), inTarget, inUpdate), inTime); } /// <summary> /// Fades a Material color property to another color over time /// </summary> static public Tween ColorTo(this Material inMaterial, string inProperty, Color inTarget, TweenSettings inSettings, ColorUpdate inUpdate = ColorUpdate.PreserveAlpha) { return Tween.Create(new TweenData_Material_ColorProperty(inMaterial, Shader.PropertyToID(inProperty), inTarget, inUpdate), inSettings); } /// <summary> /// Fades a Material color property to another color over time. /// </summary> static public Tween ColorTo(this Material inMaterial, int inPropertyID, Color inTarget, float inTime, ColorUpdate inUpdate = ColorUpdate.PreserveAlpha) { return Tween.Create(new TweenData_Material_ColorProperty(inMaterial, inPropertyID, inTarget, inUpdate), inTime); } /// <summary> /// Fades a Material color property to another color over time /// </summary> static public Tween ColorTo(this Material inMaterial, int inPropertyID, Color inTarget, TweenSettings inSettings, ColorUpdate inUpdate = ColorUpdate.PreserveAlpha) { return Tween.Create(new TweenData_Material_ColorProperty(inMaterial, inPropertyID, inTarget, inUpdate), inSettings); } #endregion // Color #region Gradient private sealed class TweenData_Material_Gradient : ITweenData { private Material m_Material; private Gradient m_Gradient; private ColorUpdate m_Update; public TweenData_Material_Gradient(Material inMaterial, Gradient inTarget, ColorUpdate inUpdate) { m_Material = inMaterial; m_Gradient = inTarget; m_Update = inUpdate; } public void OnTweenStart() { } public void OnTweenEnd() { } public void ApplyTween(float inPercent) { Color final = m_Gradient.Evaluate(inPercent); if (m_Update == ColorUpdate.PreserveAlpha) final.a = m_Material.color.a; m_Material.color = final; } public override string ToString() { return "Material: Gradient"; } } private sealed class TweenData_Material_GradientProperty : ITweenData { private Material m_Material; private int m_Property; private Gradient m_Gradient; private ColorUpdate m_Update; public TweenData_Material_GradientProperty(Material inMaterial, int inProperty, Gradient inTarget, ColorUpdate inUpdate) { m_Material = inMaterial; m_Property = inProperty; m_Gradient = inTarget; m_Update = inUpdate; } public void OnTweenStart() { } public void OnTweenEnd() { } public void ApplyTween(float inPercent) { Color final = m_Gradient.Evaluate(inPercent); if (m_Update == ColorUpdate.PreserveAlpha) final.a = m_Material.GetColor(m_Property).a; m_Material.SetColor(m_Property, final); } public override string ToString() { return "Material: Gradient (Property)"; } } /// <summary> /// Applies a gradient of colors to the Material over time. /// </summary> static public Tween Gradient(this Material inMaterial, Gradient inGradient, float inTime, ColorUpdate inUpdate = ColorUpdate.PreserveAlpha) { return Tween.Create(new TweenData_Material_Gradient(inMaterial, inGradient, inUpdate), inTime); } /// <summary> /// Applies a gradient of colors to the Material over time. /// </summary> static public Tween Gradient(this Material inMaterial, Gradient inGradient, TweenSettings inSettings, ColorUpdate inUpdate = ColorUpdate.PreserveAlpha) { return Tween.Create(new TweenData_Material_Gradient(inMaterial, inGradient, inUpdate), inSettings); } /// <summary> /// Applies a gradient of colors to a Material color property over time. /// </summary> static public Tween Gradient(this Material inMaterial, string inProperty, Gradient inGradient, float inTime, ColorUpdate inUpdate = ColorUpdate.PreserveAlpha) { return Tween.Create(new TweenData_Material_GradientProperty(inMaterial, Shader.PropertyToID(inProperty), inGradient, inUpdate), inTime); } /// <summary> /// Applies a gradient of colors to a Material color property over time. /// </summary> static public Tween Gradient(this Material inMaterial, string inProperty, Gradient inGradient, TweenSettings inSettings, ColorUpdate inUpdate = ColorUpdate.PreserveAlpha) { return Tween.Create(new TweenData_Material_GradientProperty(inMaterial, Shader.PropertyToID(inProperty), inGradient, inUpdate), inSettings); } /// <summary> /// Applies a gradient of colors to a Material color property over time. /// </summary> static public Tween Gradient(this Material inMaterial, int inPropertyID, Gradient inGradient, float inTime, ColorUpdate inUpdate = ColorUpdate.PreserveAlpha) { return Tween.Create(new TweenData_Material_GradientProperty(inMaterial, inPropertyID, inGradient, inUpdate), inTime); } /// <summary> /// Applies a gradient of colors to a Material color property over time. /// </summary> static public Tween Gradient(this Material inMaterial, int inPropertyID, Gradient inGradient, TweenSettings inSettings, ColorUpdate inUpdate = ColorUpdate.PreserveAlpha) { return Tween.Create(new TweenData_Material_GradientProperty(inMaterial, inPropertyID, inGradient, inUpdate), inSettings); } #endregion // Gradient #region Float private sealed class TweenData_Material_FloatProperty : ITweenData { private Material m_Material; private int m_Property; private float m_Target; private float m_Start; private float m_Delta; public TweenData_Material_FloatProperty(Material inMaterial, int inProperty, float inTarget) { m_Material = inMaterial; m_Property = inProperty; m_Target = inTarget; } public void OnTweenStart() { m_Start = m_Material.GetFloat(m_Property); m_Delta = m_Target - m_Start; } public void OnTweenEnd() { } public void ApplyTween(float inPercent) { m_Material.SetFloat(m_Property, m_Start + m_Delta * inPercent); } public override string ToString() { return "Material: Float (Property)"; } } /// <summary> /// Fades a Material float property to another value over time. /// </summary> static public Tween FloatTo(this Material inMaterial, string inProperty, float inValue, float inTime) { return Tween.Create(new TweenData_Material_FloatProperty(inMaterial, Shader.PropertyToID(inProperty), inValue), inTime); } /// <summary> /// Fades a Material float property to another value over time. /// </summary> static public Tween FloatTo(this Material inMaterial, string inProperty, float inValue, TweenSettings inSettings) { return Tween.Create(new TweenData_Material_FloatProperty(inMaterial, Shader.PropertyToID(inProperty), inValue), inSettings); } /// <summary> /// Fades a Material float property to another value over time. /// </summary> static public Tween FloatTo(this Material inMaterial, int inPropertyID, float inValue, float inTime) { return Tween.Create(new TweenData_Material_FloatProperty(inMaterial, inPropertyID, inValue), inTime); } /// <summary> /// Fades a Material float property to another value over time. /// </summary> static public Tween FloatTo(this Material inMaterial, int inPropertyID, float inValue, TweenSettings inSettings) { return Tween.Create(new TweenData_Material_FloatProperty(inMaterial, inPropertyID, inValue), inSettings); } #endregion // Float #region Vector private sealed class TweenData_Material_VectorProperty : ITweenData { private Material m_Material; private int m_Property; private Vector4 m_Target; private Axis m_Axis; private Vector4 m_Start; private Vector4 m_Delta; public TweenData_Material_VectorProperty(Material inMaterial, int inProperty, Vector4 inTarget, Axis inAxis) { m_Material = inMaterial; m_Property = inProperty; m_Target = inTarget; m_Axis = inAxis; } public void OnTweenStart() { m_Start = m_Material.GetVector(m_Property); m_Delta = m_Target - m_Start; } public void OnTweenEnd() { } public void ApplyTween(float inPercent) { Vector4 final = new Vector4( m_Start.x + m_Delta.x * inPercent, m_Start.y + m_Delta.y * inPercent, m_Start.z + m_Delta.z * inPercent, m_Start.w + m_Delta.w * inPercent ); if ((m_Axis & Axis.XYZW) != Axis.XYZW) { Vector4 currentValue = m_Material.GetVector(m_Property); VectorUtil.CopyFrom(ref currentValue, final, m_Axis); final = currentValue; } m_Material.SetVector(m_Property, final); } public override string ToString() { return "Material: Vector (Property)"; } } /// <summary> /// Fades a Material vector property to another value over time. /// </summary> static public Tween VectorTo(this Material inMaterial, string inProperty, Vector4 inValue, float inTime, Axis inAxis = Axis.XYZW) { return Tween.Create(new TweenData_Material_VectorProperty(inMaterial, Shader.PropertyToID(inProperty), inValue, inAxis), inTime); } /// <summary> /// Fades a Material vector property to another value over time. /// </summary> static public Tween VectorTo(this Material inMaterial, string inProperty, Vector4 inValue, TweenSettings inSettings, Axis inAxis = Axis.XYZW) { return Tween.Create(new TweenData_Material_VectorProperty(inMaterial, Shader.PropertyToID(inProperty), inValue, inAxis), inSettings); } /// <summary> /// Fades a Material vector property to another value over time. /// </summary> static public Tween VectorTo(this Material inMaterial, int inPropertyID, Vector4 inValue, float inTime, Axis inAxis = Axis.XYZW) { return Tween.Create(new TweenData_Material_VectorProperty(inMaterial, inPropertyID, inValue, inAxis), inTime); } /// <summary> /// Fades a Material vector property to another value over time. /// </summary> static public Tween VectorTo(this Material inMaterial, int inPropertyID, Vector4 inValue, TweenSettings inSettings, Axis inAxis = Axis.XYZW) { return Tween.Create(new TweenData_Material_VectorProperty(inMaterial, inPropertyID, inValue, inAxis), inSettings); } #endregion // Vector } }
37.865562
178
0.599679
[ "MIT" ]
BeauPrime/BeauRoutine
Assets/BeauRoutine/Tween/Shortcuts/TweenShortcuts.Material.cs
20,563
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 ec2-2016-11-15.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.EC2.Model { /// <summary> /// Container for the parameters to the DeleteNetworkInsightsAnalysis operation. /// Deletes the specified network insights analysis. /// </summary> public partial class DeleteNetworkInsightsAnalysisRequest : AmazonEC2Request { private string _networkInsightsAnalysisId; /// <summary> /// Gets and sets the property NetworkInsightsAnalysisId. /// <para> /// The ID of the network insights analysis. /// </para> /// </summary> [AWSProperty(Required=true)] public string NetworkInsightsAnalysisId { get { return this._networkInsightsAnalysisId; } set { this._networkInsightsAnalysisId = value; } } // Check to see if NetworkInsightsAnalysisId property is set internal bool IsSetNetworkInsightsAnalysisId() { return this._networkInsightsAnalysisId != null; } } }
32.627119
102
0.664416
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/EC2/Generated/Model/DeleteNetworkInsightsAnalysisRequest.cs
1,925
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager.Core; using Azure.ResourceManager.Network.Models; namespace Azure.ResourceManager.Network { internal partial class NetworkWatchersRestOperations { private string subscriptionId; private Uri endpoint; private string apiVersion; private ClientDiagnostics _clientDiagnostics; private HttpPipeline _pipeline; private readonly string _userAgent; /// <summary> Initializes a new instance of NetworkWatchersRestOperations. </summary> /// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param> /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param> /// <param name="options"> The client options used to construct the current client. </param> /// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="endpoint"> server parameter. </param> /// <param name="apiVersion"> Api Version. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> or <paramref name="apiVersion"/> is null. </exception> public NetworkWatchersRestOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, ClientOptions options, string subscriptionId, Uri endpoint = null, string apiVersion = "2021-02-01") { this.subscriptionId = subscriptionId ?? throw new ArgumentNullException(nameof(subscriptionId)); this.endpoint = endpoint ?? new Uri("https://management.azure.com"); this.apiVersion = apiVersion ?? throw new ArgumentNullException(nameof(apiVersion)); _clientDiagnostics = clientDiagnostics; _pipeline = pipeline; _userAgent = HttpMessageUtilities.GetUserAgentName(this, options); } internal HttpMessage CreateCreateOrUpdateRequest(string resourceGroupName, string networkWatcherName, NetworkWatcherData parameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Put; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/networkWatchers/", false); uri.AppendPath(networkWatcherName, true); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Creates or updates a network watcher in the specified resource group. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher. </param> /// <param name="parameters"> Parameters that define the network watcher resource. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="networkWatcherName"/>, or <paramref name="parameters"/> is null. </exception> public async Task<Response<NetworkWatcherData>> CreateOrUpdateAsync(string resourceGroupName, string networkWatcherName, NetworkWatcherData parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateCreateOrUpdateRequest(resourceGroupName, networkWatcherName, parameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 201: { NetworkWatcherData value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = NetworkWatcherData.DeserializeNetworkWatcherData(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Creates or updates a network watcher in the specified resource group. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher. </param> /// <param name="parameters"> Parameters that define the network watcher resource. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="networkWatcherName"/>, or <paramref name="parameters"/> is null. </exception> public Response<NetworkWatcherData> CreateOrUpdate(string resourceGroupName, string networkWatcherName, NetworkWatcherData parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateCreateOrUpdateRequest(resourceGroupName, networkWatcherName, parameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 201: { NetworkWatcherData value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = NetworkWatcherData.DeserializeNetworkWatcherData(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateGetRequest(string resourceGroupName, string networkWatcherName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/networkWatchers/", false); uri.AppendPath(networkWatcherName, true); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Gets the specified network watcher by resource group. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/> or <paramref name="networkWatcherName"/> is null. </exception> public async Task<Response<NetworkWatcherData>> GetAsync(string resourceGroupName, string networkWatcherName, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } using var message = CreateGetRequest(resourceGroupName, networkWatcherName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { NetworkWatcherData value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = NetworkWatcherData.DeserializeNetworkWatcherData(document.RootElement); return Response.FromValue(value, message.Response); } case 404: return Response.FromValue((NetworkWatcherData)null, message.Response); default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Gets the specified network watcher by resource group. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/> or <paramref name="networkWatcherName"/> is null. </exception> public Response<NetworkWatcherData> Get(string resourceGroupName, string networkWatcherName, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } using var message = CreateGetRequest(resourceGroupName, networkWatcherName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { NetworkWatcherData value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = NetworkWatcherData.DeserializeNetworkWatcherData(document.RootElement); return Response.FromValue(value, message.Response); } case 404: return Response.FromValue((NetworkWatcherData)null, message.Response); default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateDeleteRequest(string resourceGroupName, string networkWatcherName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Delete; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/networkWatchers/", false); uri.AppendPath(networkWatcherName, true); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Deletes the specified network watcher resource. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/> or <paramref name="networkWatcherName"/> is null. </exception> public async Task<Response> DeleteAsync(string resourceGroupName, string networkWatcherName, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } using var message = CreateDeleteRequest(resourceGroupName, networkWatcherName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 202: case 204: return message.Response; default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Deletes the specified network watcher resource. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/> or <paramref name="networkWatcherName"/> is null. </exception> public Response Delete(string resourceGroupName, string networkWatcherName, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } using var message = CreateDeleteRequest(resourceGroupName, networkWatcherName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 202: case 204: return message.Response; default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateUpdateTagsRequest(string resourceGroupName, string networkWatcherName, TagsObject parameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Patch; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/networkWatchers/", false); uri.AppendPath(networkWatcherName, true); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Updates a network watcher tags. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher. </param> /// <param name="parameters"> Parameters supplied to update network watcher tags. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="networkWatcherName"/>, or <paramref name="parameters"/> is null. </exception> public async Task<Response<NetworkWatcherData>> UpdateTagsAsync(string resourceGroupName, string networkWatcherName, TagsObject parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateUpdateTagsRequest(resourceGroupName, networkWatcherName, parameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { NetworkWatcherData value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = NetworkWatcherData.DeserializeNetworkWatcherData(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Updates a network watcher tags. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher. </param> /// <param name="parameters"> Parameters supplied to update network watcher tags. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="networkWatcherName"/>, or <paramref name="parameters"/> is null. </exception> public Response<NetworkWatcherData> UpdateTags(string resourceGroupName, string networkWatcherName, TagsObject parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateUpdateTagsRequest(resourceGroupName, networkWatcherName, parameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { NetworkWatcherData value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = NetworkWatcherData.DeserializeNetworkWatcherData(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateListRequest(string resourceGroupName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/networkWatchers", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Gets all network watchers by resource group. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/> is null. </exception> public async Task<Response<NetworkWatcherListResult>> ListAsync(string resourceGroupName, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } using var message = CreateListRequest(resourceGroupName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { NetworkWatcherListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = NetworkWatcherListResult.DeserializeNetworkWatcherListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Gets all network watchers by resource group. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/> is null. </exception> public Response<NetworkWatcherListResult> List(string resourceGroupName, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } using var message = CreateListRequest(resourceGroupName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { NetworkWatcherListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = NetworkWatcherListResult.DeserializeNetworkWatcherListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateListAllRequest() { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/providers/Microsoft.Network/networkWatchers", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Gets all network watchers by subscription. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public async Task<Response<NetworkWatcherListResult>> ListAllAsync(CancellationToken cancellationToken = default) { using var message = CreateListAllRequest(); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { NetworkWatcherListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = NetworkWatcherListResult.DeserializeNetworkWatcherListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Gets all network watchers by subscription. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public Response<NetworkWatcherListResult> ListAll(CancellationToken cancellationToken = default) { using var message = CreateListAllRequest(); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { NetworkWatcherListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = NetworkWatcherListResult.DeserializeNetworkWatcherListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateGetTopologyRequest(string resourceGroupName, string networkWatcherName, TopologyParameters parameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/networkWatchers/", false); uri.AppendPath(networkWatcherName, true); uri.AppendPath("/topology", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Gets the current network topology by resource group. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher. </param> /// <param name="parameters"> Parameters that define the representation of topology. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="networkWatcherName"/>, or <paramref name="parameters"/> is null. </exception> public async Task<Response<Topology>> GetTopologyAsync(string resourceGroupName, string networkWatcherName, TopologyParameters parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateGetTopologyRequest(resourceGroupName, networkWatcherName, parameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { Topology value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = Topology.DeserializeTopology(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Gets the current network topology by resource group. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher. </param> /// <param name="parameters"> Parameters that define the representation of topology. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="networkWatcherName"/>, or <paramref name="parameters"/> is null. </exception> public Response<Topology> GetTopology(string resourceGroupName, string networkWatcherName, TopologyParameters parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateGetTopologyRequest(resourceGroupName, networkWatcherName, parameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { Topology value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = Topology.DeserializeTopology(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateVerifyIPFlowRequest(string resourceGroupName, string networkWatcherName, VerificationIPFlowParameters parameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/networkWatchers/", false); uri.AppendPath(networkWatcherName, true); uri.AppendPath("/ipFlowVerify", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Verify IP flow from the specified VM to a location given the currently configured NSG rules. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher. </param> /// <param name="parameters"> Parameters that define the IP flow to be verified. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="networkWatcherName"/>, or <paramref name="parameters"/> is null. </exception> public async Task<Response> VerifyIPFlowAsync(string resourceGroupName, string networkWatcherName, VerificationIPFlowParameters parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateVerifyIPFlowRequest(resourceGroupName, networkWatcherName, parameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Verify IP flow from the specified VM to a location given the currently configured NSG rules. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher. </param> /// <param name="parameters"> Parameters that define the IP flow to be verified. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="networkWatcherName"/>, or <paramref name="parameters"/> is null. </exception> public Response VerifyIPFlow(string resourceGroupName, string networkWatcherName, VerificationIPFlowParameters parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateVerifyIPFlowRequest(resourceGroupName, networkWatcherName, parameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateGetNextHopRequest(string resourceGroupName, string networkWatcherName, NextHopParameters parameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/networkWatchers/", false); uri.AppendPath(networkWatcherName, true); uri.AppendPath("/nextHop", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Gets the next hop from the specified VM. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher. </param> /// <param name="parameters"> Parameters that define the source and destination endpoint. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="networkWatcherName"/>, or <paramref name="parameters"/> is null. </exception> public async Task<Response> GetNextHopAsync(string resourceGroupName, string networkWatcherName, NextHopParameters parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateGetNextHopRequest(resourceGroupName, networkWatcherName, parameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Gets the next hop from the specified VM. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher. </param> /// <param name="parameters"> Parameters that define the source and destination endpoint. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="networkWatcherName"/>, or <paramref name="parameters"/> is null. </exception> public Response GetNextHop(string resourceGroupName, string networkWatcherName, NextHopParameters parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateGetNextHopRequest(resourceGroupName, networkWatcherName, parameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateGetVMSecurityRulesRequest(string resourceGroupName, string networkWatcherName, SecurityGroupViewParameters parameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/networkWatchers/", false); uri.AppendPath(networkWatcherName, true); uri.AppendPath("/securityGroupView", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Gets the configured and effective security group rules on the specified VM. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher. </param> /// <param name="parameters"> Parameters that define the VM to check security groups for. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="networkWatcherName"/>, or <paramref name="parameters"/> is null. </exception> public async Task<Response> GetVMSecurityRulesAsync(string resourceGroupName, string networkWatcherName, SecurityGroupViewParameters parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateGetVMSecurityRulesRequest(resourceGroupName, networkWatcherName, parameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Gets the configured and effective security group rules on the specified VM. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher. </param> /// <param name="parameters"> Parameters that define the VM to check security groups for. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="networkWatcherName"/>, or <paramref name="parameters"/> is null. </exception> public Response GetVMSecurityRules(string resourceGroupName, string networkWatcherName, SecurityGroupViewParameters parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateGetVMSecurityRulesRequest(resourceGroupName, networkWatcherName, parameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateGetTroubleshootingRequest(string resourceGroupName, string networkWatcherName, TroubleshootingParameters parameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/networkWatchers/", false); uri.AppendPath(networkWatcherName, true); uri.AppendPath("/troubleshoot", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Initiate troubleshooting on a specified resource. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher resource. </param> /// <param name="parameters"> Parameters that define the resource to troubleshoot. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="networkWatcherName"/>, or <paramref name="parameters"/> is null. </exception> public async Task<Response> GetTroubleshootingAsync(string resourceGroupName, string networkWatcherName, TroubleshootingParameters parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateGetTroubleshootingRequest(resourceGroupName, networkWatcherName, parameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Initiate troubleshooting on a specified resource. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher resource. </param> /// <param name="parameters"> Parameters that define the resource to troubleshoot. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="networkWatcherName"/>, or <paramref name="parameters"/> is null. </exception> public Response GetTroubleshooting(string resourceGroupName, string networkWatcherName, TroubleshootingParameters parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateGetTroubleshootingRequest(resourceGroupName, networkWatcherName, parameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateGetTroubleshootingResultRequest(string resourceGroupName, string networkWatcherName, QueryTroubleshootingParameters parameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/networkWatchers/", false); uri.AppendPath(networkWatcherName, true); uri.AppendPath("/queryTroubleshootResult", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Get the last completed troubleshooting result on a specified resource. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher resource. </param> /// <param name="parameters"> Parameters that define the resource to query the troubleshooting result. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="networkWatcherName"/>, or <paramref name="parameters"/> is null. </exception> public async Task<Response> GetTroubleshootingResultAsync(string resourceGroupName, string networkWatcherName, QueryTroubleshootingParameters parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateGetTroubleshootingResultRequest(resourceGroupName, networkWatcherName, parameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Get the last completed troubleshooting result on a specified resource. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher resource. </param> /// <param name="parameters"> Parameters that define the resource to query the troubleshooting result. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="networkWatcherName"/>, or <paramref name="parameters"/> is null. </exception> public Response GetTroubleshootingResult(string resourceGroupName, string networkWatcherName, QueryTroubleshootingParameters parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateGetTroubleshootingResultRequest(resourceGroupName, networkWatcherName, parameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateSetFlowLogConfigurationRequest(string resourceGroupName, string networkWatcherName, FlowLogInformation parameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/networkWatchers/", false); uri.AppendPath(networkWatcherName, true); uri.AppendPath("/configureFlowLog", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Configures flow log and traffic analytics (optional) on a specified resource. </summary> /// <param name="resourceGroupName"> The name of the network watcher resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher resource. </param> /// <param name="parameters"> Parameters that define the configuration of flow log. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="networkWatcherName"/>, or <paramref name="parameters"/> is null. </exception> public async Task<Response> SetFlowLogConfigurationAsync(string resourceGroupName, string networkWatcherName, FlowLogInformation parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateSetFlowLogConfigurationRequest(resourceGroupName, networkWatcherName, parameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Configures flow log and traffic analytics (optional) on a specified resource. </summary> /// <param name="resourceGroupName"> The name of the network watcher resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher resource. </param> /// <param name="parameters"> Parameters that define the configuration of flow log. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="networkWatcherName"/>, or <paramref name="parameters"/> is null. </exception> public Response SetFlowLogConfiguration(string resourceGroupName, string networkWatcherName, FlowLogInformation parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateSetFlowLogConfigurationRequest(resourceGroupName, networkWatcherName, parameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateGetFlowLogStatusRequest(string resourceGroupName, string networkWatcherName, FlowLogStatusParameters parameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/networkWatchers/", false); uri.AppendPath(networkWatcherName, true); uri.AppendPath("/queryFlowLogStatus", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Queries status of flow log and traffic analytics (optional) on a specified resource. </summary> /// <param name="resourceGroupName"> The name of the network watcher resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher resource. </param> /// <param name="parameters"> Parameters that define a resource to query flow log and traffic analytics (optional) status. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="networkWatcherName"/>, or <paramref name="parameters"/> is null. </exception> public async Task<Response> GetFlowLogStatusAsync(string resourceGroupName, string networkWatcherName, FlowLogStatusParameters parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateGetFlowLogStatusRequest(resourceGroupName, networkWatcherName, parameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Queries status of flow log and traffic analytics (optional) on a specified resource. </summary> /// <param name="resourceGroupName"> The name of the network watcher resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher resource. </param> /// <param name="parameters"> Parameters that define a resource to query flow log and traffic analytics (optional) status. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="networkWatcherName"/>, or <paramref name="parameters"/> is null. </exception> public Response GetFlowLogStatus(string resourceGroupName, string networkWatcherName, FlowLogStatusParameters parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateGetFlowLogStatusRequest(resourceGroupName, networkWatcherName, parameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateCheckConnectivityRequest(string resourceGroupName, string networkWatcherName, ConnectivityParameters parameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/networkWatchers/", false); uri.AppendPath(networkWatcherName, true); uri.AppendPath("/connectivityCheck", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Verifies the possibility of establishing a direct TCP connection from a virtual machine to a given endpoint including another VM or an arbitrary remote server. </summary> /// <param name="resourceGroupName"> The name of the network watcher resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher resource. </param> /// <param name="parameters"> Parameters that determine how the connectivity check will be performed. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="networkWatcherName"/>, or <paramref name="parameters"/> is null. </exception> public async Task<Response> CheckConnectivityAsync(string resourceGroupName, string networkWatcherName, ConnectivityParameters parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateCheckConnectivityRequest(resourceGroupName, networkWatcherName, parameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Verifies the possibility of establishing a direct TCP connection from a virtual machine to a given endpoint including another VM or an arbitrary remote server. </summary> /// <param name="resourceGroupName"> The name of the network watcher resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher resource. </param> /// <param name="parameters"> Parameters that determine how the connectivity check will be performed. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="networkWatcherName"/>, or <paramref name="parameters"/> is null. </exception> public Response CheckConnectivity(string resourceGroupName, string networkWatcherName, ConnectivityParameters parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateCheckConnectivityRequest(resourceGroupName, networkWatcherName, parameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateGetAzureReachabilityReportRequest(string resourceGroupName, string networkWatcherName, AzureReachabilityReportParameters parameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/networkWatchers/", false); uri.AppendPath(networkWatcherName, true); uri.AppendPath("/azureReachabilityReport", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> NOTE: This feature is currently in preview and still being tested for stability. Gets the relative latency score for internet service providers from a specified location to Azure regions. </summary> /// <param name="resourceGroupName"> The name of the network watcher resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher resource. </param> /// <param name="parameters"> Parameters that determine Azure reachability report configuration. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="networkWatcherName"/>, or <paramref name="parameters"/> is null. </exception> public async Task<Response> GetAzureReachabilityReportAsync(string resourceGroupName, string networkWatcherName, AzureReachabilityReportParameters parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateGetAzureReachabilityReportRequest(resourceGroupName, networkWatcherName, parameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> NOTE: This feature is currently in preview and still being tested for stability. Gets the relative latency score for internet service providers from a specified location to Azure regions. </summary> /// <param name="resourceGroupName"> The name of the network watcher resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher resource. </param> /// <param name="parameters"> Parameters that determine Azure reachability report configuration. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="networkWatcherName"/>, or <paramref name="parameters"/> is null. </exception> public Response GetAzureReachabilityReport(string resourceGroupName, string networkWatcherName, AzureReachabilityReportParameters parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateGetAzureReachabilityReportRequest(resourceGroupName, networkWatcherName, parameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateListAvailableProvidersRequest(string resourceGroupName, string networkWatcherName, AvailableProvidersListParameters parameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/networkWatchers/", false); uri.AppendPath(networkWatcherName, true); uri.AppendPath("/availableProvidersList", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> NOTE: This feature is currently in preview and still being tested for stability. Lists all available internet service providers for a specified Azure region. </summary> /// <param name="resourceGroupName"> The name of the network watcher resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher resource. </param> /// <param name="parameters"> Parameters that scope the list of available providers. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="networkWatcherName"/>, or <paramref name="parameters"/> is null. </exception> public async Task<Response> ListAvailableProvidersAsync(string resourceGroupName, string networkWatcherName, AvailableProvidersListParameters parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateListAvailableProvidersRequest(resourceGroupName, networkWatcherName, parameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> NOTE: This feature is currently in preview and still being tested for stability. Lists all available internet service providers for a specified Azure region. </summary> /// <param name="resourceGroupName"> The name of the network watcher resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher resource. </param> /// <param name="parameters"> Parameters that scope the list of available providers. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="networkWatcherName"/>, or <paramref name="parameters"/> is null. </exception> public Response ListAvailableProviders(string resourceGroupName, string networkWatcherName, AvailableProvidersListParameters parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateListAvailableProvidersRequest(resourceGroupName, networkWatcherName, parameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateGetNetworkConfigurationDiagnosticRequest(string resourceGroupName, string networkWatcherName, NetworkConfigurationDiagnosticParameters parameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Network/networkWatchers/", false); uri.AppendPath(networkWatcherName, true); uri.AppendPath("/networkConfigurationDiagnostic", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Gets Network Configuration Diagnostic data to help customers understand and debug network behavior. It provides detailed information on what security rules were applied to a specified traffic flow and the result of evaluating these rules. Customers must provide details of a flow like source, destination, protocol, etc. The API returns whether traffic was allowed or denied, the rules evaluated for the specified flow and the evaluation results. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher. </param> /// <param name="parameters"> Parameters to get network configuration diagnostic. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="networkWatcherName"/>, or <paramref name="parameters"/> is null. </exception> public async Task<Response> GetNetworkConfigurationDiagnosticAsync(string resourceGroupName, string networkWatcherName, NetworkConfigurationDiagnosticParameters parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateGetNetworkConfigurationDiagnosticRequest(resourceGroupName, networkWatcherName, parameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Gets Network Configuration Diagnostic data to help customers understand and debug network behavior. It provides detailed information on what security rules were applied to a specified traffic flow and the result of evaluating these rules. Customers must provide details of a flow like source, destination, protocol, etc. The API returns whether traffic was allowed or denied, the rules evaluated for the specified flow and the evaluation results. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="networkWatcherName"> The name of the network watcher. </param> /// <param name="parameters"> Parameters to get network configuration diagnostic. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/>, <paramref name="networkWatcherName"/>, or <paramref name="parameters"/> is null. </exception> public Response GetNetworkConfigurationDiagnostic(string resourceGroupName, string networkWatcherName, NetworkConfigurationDiagnosticParameters parameters, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (networkWatcherName == null) { throw new ArgumentNullException(nameof(networkWatcherName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateGetNetworkConfigurationDiagnosticRequest(resourceGroupName, networkWatcherName, parameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } } }
54.335366
479
0.628022
[ "MIT" ]
DiskRP-Swagger/azure-sdk-for-net
sdk/network/Azure.ResourceManager.Network/src/Generated/RestOperations/NetworkWatchersRestOperations.cs
89,110
C#
using System; using System.IO; using System.Linq; using System.Text.RegularExpressions; using UnityEngine; using UnityEditor; using UnityEditor.Callbacks; using UnityEditor.iOS.Xcode; using Application = UnityEngine.Application; using BuildResult = UnityEditor.Build.Reporting.BuildResult; public class Build { static readonly string ProjectPath = Path.GetFullPath(Path.Combine(Application.dataPath, "..")); static readonly string apkPath = Path.Combine(ProjectPath, "Builds/" + Application.productName + ".apk"); static readonly string androidExportPath = Path.GetFullPath(Path.Combine(ProjectPath, "../../android/UnityExport")); static readonly string iosExportPath = Path.GetFullPath(Path.Combine(ProjectPath, "../../ios/UnityExport")); [MenuItem("Flutter/Export Android (Unity 2019.3.*) %&n", false, 1)] public static void DoBuildAndroidLibrary() { DoBuildAndroid(Path.Combine(apkPath, "unityLibrary")); // Copy over resources from the launcher module that are used by the library Copy(Path.Combine(apkPath + "/launcher/src/main/res"), Path.Combine(androidExportPath, "src/main/res")); } public static void DoBuildAndroid(String buildPath) { if (Directory.Exists(apkPath)) Directory.Delete(apkPath, true); if (Directory.Exists(androidExportPath)) Directory.Delete(androidExportPath, true); EditorUserBuildSettings.androidBuildSystem = AndroidBuildSystem.Gradle; var options = BuildOptions.AcceptExternalModificationsToPlayer; var report = BuildPipeline.BuildPlayer( GetEnabledScenes(), apkPath, BuildTarget.Android, options ); if (report.summary.result != BuildResult.Succeeded) throw new Exception("Build failed"); Copy(buildPath, androidExportPath); // Modify build.gradle var build_file = Path.Combine(androidExportPath, "build.gradle"); var build_text = File.ReadAllText(build_file); build_text = build_text.Replace("com.android.application", "com.android.library"); build_text = build_text.Replace("bundle {", "splits {"); build_text = build_text.Replace("enableSplit = false", "enable false"); build_text = build_text.Replace("enableSplit = true", "enable true"); // build_text = build_text.Replace("implementation fileTree(dir: 'libs', include: ['*.jar'])", "implementation project(':unity-classes')"); build_text = Regex.Replace(build_text, @"\n.*applicationId '.+'.*\n", "\n"); File.WriteAllText(build_file, build_text); // Modify AndroidManifest.xml var manifest_file = Path.Combine(androidExportPath, "src/main/AndroidManifest.xml"); var manifest_text = File.ReadAllText(manifest_file); manifest_text = Regex.Replace(manifest_text, @"<application .*>", "<application>"); Regex regex = new Regex(@"<activity.*>(\s|\S)+?</activity>", RegexOptions.Multiline); manifest_text = regex.Replace(manifest_text, ""); File.WriteAllText(manifest_file, manifest_text); } [MenuItem("Flutter/Export IOS (Unity 2019.3.*) %&i", false, 3)] public static void DoBuildIOS() { Debug.Log("iOS Path: " + iosExportPath); if (Directory.Exists(iosExportPath)) { Debug.Log("Remove iOS Path"); Directory.Delete(iosExportPath, true); } EditorUserBuildSettings.iOSBuildConfigType = iOSBuildType.Release; var options = BuildOptions.AcceptExternalModificationsToPlayer; var report = BuildPipeline.BuildPlayer( GetEnabledScenes(), iosExportPath, BuildTarget.iOS, options ); if (report.summary.result != BuildResult.Succeeded) throw new Exception("Build failed"); } [PostProcessBuild] public static void OnPostProcessBuild(BuildTarget buildTarget, string buildPath) { if (buildTarget == BuildTarget.iOS) { // We need to construct our own PBX project path that corrently refers to the Bridging header // var projPath = PBXProject.GetPBXProjectPath(buildPath); var projPath = iosExportPath + "/Unity-iPhone.xcodeproj/project.pbxproj"; var proj = new PBXProject(); proj.ReadFromFile(projPath); var projectGuid = proj.ProjectGuid(); //// Configure build settings proj.SetBuildProperty(projectGuid, "ENABLE_BITCODE", "NO"); proj.SetBuildProperty(projectGuid, "OTHER_LDFLAGS", "-Wl,-U,_FlutterUnityPluginOnMessage"); proj.SetBuildProperty(projectGuid, "CODE_SIGN_IDENTITY", "iPhone Developer"); proj.WriteToFile(projPath); } } static void Copy(string source, string destinationPath) { if (Directory.Exists(destinationPath)) Directory.Delete(destinationPath, true); Directory.CreateDirectory(destinationPath); foreach (string dirPath in Directory.GetDirectories(source, "*", SearchOption.AllDirectories)) Directory.CreateDirectory(dirPath.Replace(source, destinationPath)); foreach (string newPath in Directory.GetFiles(source, "*.*", SearchOption.AllDirectories)) File.Copy(newPath, newPath.Replace(source, destinationPath), true); } static string[] GetEnabledScenes() { var scenes = EditorBuildSettings.scenes .Where(s => s.enabled) .Select(s => s.path) .ToArray(); return scenes; } }
39.725352
147
0.659812
[ "BSD-3-Clause" ]
duytruong27/flutter-unity
flutter_unity/example/unity/FlutterUnityExample/Assets/Editor/Build.cs
5,643
C#
using System; using NetRuntimeSystem = System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.ComponentModel; using System.Reflection; using System.Collections.Generic; using NetOffice; namespace NetOffice.MSFormsApi { ///<summary> /// DispatchInterface ILabelControl /// SupportByVersion MSForms, 2 ///</summary> [SupportByVersionAttribute("MSForms", 2)] [EntityTypeAttribute(EntityType.IsDispatchInterface)] public class ILabelControl : COMObject { #pragma warning disable #region Type Information private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(ILabelControl); return _type; } } #endregion #region Construction ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public ILabelControl(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ILabelControl(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ILabelControl(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ILabelControl(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ILabelControl(ICOMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ILabelControl() : base() { } /// <param name="progId">registered ProgID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ILabelControl(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersionAttribute("MSForms", 2)] public bool AutoSize { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "AutoSize", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "AutoSize", paramsArray); } } /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersionAttribute("MSForms", 2)] public Int32 BackColor { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "BackColor", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "BackColor", paramsArray); } } /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersionAttribute("MSForms", 2)] public NetOffice.MSFormsApi.Enums.fmBackStyle BackStyle { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "BackStyle", paramsArray); int intReturnItem = NetRuntimeSystem.Convert.ToInt32(returnItem); return (NetOffice.MSFormsApi.Enums.fmBackStyle)intReturnItem; } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "BackStyle", paramsArray); } } /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersionAttribute("MSForms", 2)] public Int32 BorderColor { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "BorderColor", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "BorderColor", paramsArray); } } /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersionAttribute("MSForms", 2)] public NetOffice.MSFormsApi.Enums.fmBorderStyle BorderStyle { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "BorderStyle", paramsArray); int intReturnItem = NetRuntimeSystem.Convert.ToInt32(returnItem); return (NetOffice.MSFormsApi.Enums.fmBorderStyle)intReturnItem; } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "BorderStyle", paramsArray); } } /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersionAttribute("MSForms", 2)] public string Caption { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Caption", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Caption", paramsArray); } } /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersionAttribute("MSForms", 2)] public bool Enabled { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Enabled", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Enabled", paramsArray); } } /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersionAttribute("MSForms", 2)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public NetOffice.MSFormsApi.Font _Font_Reserved { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "_Font_Reserved", paramsArray); NetOffice.MSFormsApi.Font newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.MSFormsApi.Font.LateBindingApiWrapperType) as NetOffice.MSFormsApi.Font; return newObject; } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "_Font_Reserved", paramsArray); } } /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersionAttribute("MSForms", 2)] public NetOffice.MSFormsApi.Font Font { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Font", paramsArray); NetOffice.MSFormsApi.Font newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.MSFormsApi.Font.LateBindingApiWrapperType) as NetOffice.MSFormsApi.Font; return newObject; } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Font", paramsArray); } } /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersionAttribute("MSForms", 2)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public bool FontItalic { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "FontItalic", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "FontItalic", paramsArray); } } /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersionAttribute("MSForms", 2)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public bool FontBold { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "FontBold", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "FontBold", paramsArray); } } /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersionAttribute("MSForms", 2)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public string FontName { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "FontName", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "FontName", paramsArray); } } /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersionAttribute("MSForms", 2)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public float FontSize { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "FontSize", paramsArray); return NetRuntimeSystem.Convert.ToSingle(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "FontSize", paramsArray); } } /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersionAttribute("MSForms", 2)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public bool FontStrikethru { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "FontStrikethru", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "FontStrikethru", paramsArray); } } /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersionAttribute("MSForms", 2)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public bool FontUnderline { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "FontUnderline", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "FontUnderline", paramsArray); } } /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersionAttribute("MSForms", 2)] public Int32 ForeColor { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ForeColor", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ForeColor", paramsArray); } } /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersionAttribute("MSForms", 2)] public stdole.Picture MouseIcon { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "MouseIcon", paramsArray); stdole.Picture newObject = Factory.CreateObjectFromComProxy(this,returnItem) as stdole.Picture; return newObject; } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "MouseIcon", paramsArray); } } /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersionAttribute("MSForms", 2)] public NetOffice.MSFormsApi.Enums.fmMousePointer MousePointer { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "MousePointer", paramsArray); int intReturnItem = NetRuntimeSystem.Convert.ToInt32(returnItem); return (NetOffice.MSFormsApi.Enums.fmMousePointer)intReturnItem; } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "MousePointer", paramsArray); } } /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersionAttribute("MSForms", 2)] public stdole.Picture Picture { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Picture", paramsArray); stdole.Picture newObject = Factory.CreateObjectFromComProxy(this,returnItem) as stdole.Picture; return newObject; } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Picture", paramsArray); } } /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersionAttribute("MSForms", 2)] public NetOffice.MSFormsApi.Enums.fmPicturePosition PicturePosition { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "PicturePosition", paramsArray); int intReturnItem = NetRuntimeSystem.Convert.ToInt32(returnItem); return (NetOffice.MSFormsApi.Enums.fmPicturePosition)intReturnItem; } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "PicturePosition", paramsArray); } } /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersionAttribute("MSForms", 2)] public NetOffice.MSFormsApi.Enums.fmSpecialEffect SpecialEffect { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "SpecialEffect", paramsArray); int intReturnItem = NetRuntimeSystem.Convert.ToInt32(returnItem); return (NetOffice.MSFormsApi.Enums.fmSpecialEffect)intReturnItem; } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "SpecialEffect", paramsArray); } } /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersionAttribute("MSForms", 2)] public NetOffice.MSFormsApi.Enums.fmTextAlign TextAlign { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "TextAlign", paramsArray); int intReturnItem = NetRuntimeSystem.Convert.ToInt32(returnItem); return (NetOffice.MSFormsApi.Enums.fmTextAlign)intReturnItem; } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "TextAlign", paramsArray); } } /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersionAttribute("MSForms", 2)] public bool WordWrap { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "WordWrap", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "WordWrap", paramsArray); } } /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersionAttribute("MSForms", 2)] public string Accelerator { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Accelerator", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Accelerator", paramsArray); } } /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersionAttribute("MSForms", 2)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Int16 FontWeight { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "FontWeight", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "FontWeight", paramsArray); } } /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersionAttribute("MSForms", 2)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public string _Value { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "_Value", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "_Value", paramsArray); } } #endregion #region Methods #endregion #pragma warning restore } }
27.46875
178
0.689192
[ "MIT" ]
brunobola/NetOffice
Source/MSForms/DispatchInterfaces/ILabelControl.cs
17,582
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace shopping_list.DataLayer.Controllers { public class ItemController : PageModel { public static IQueryable<Item> GetItems() { Shopping_listDataContext _sl = new Shopping_listDataContext(); return _sl.Items; } public void OnPostInsert(Item item) { using (Shopping_listDataContext _sl = new Shopping_listDataContext()) { _sl.Items.Add(new Item { ItemName = item.ItemName, ItemDescription = item.ItemDescription }); _sl.SaveChanges(); } } public void OnPostUpdate(Item item) { using (Shopping_listDataContext _sl = new Shopping_listDataContext()) { _sl.Items.Update(item); _sl.SaveChanges(); } } public async Task<IActionResult> OnPostDeleteAsync(string ItemId) { using (Shopping_listDataContext _sl = new Shopping_listDataContext()) { var item = await _sl.Items.FindAsync(ItemId); _sl.Items.Remove(item); _sl.SaveChanges(); } return RedirectToPage(); } } }
28.5
109
0.586667
[ "MIT" ]
cardidemonaco/shopping-list
shopping-list.DataLayer/Controllers/ItemController.cs
1,427
C#
using System; using System.Collections.Generic; namespace MonoDroid.Generation { public interface IRequireGenericMarshal { string GetGenericJavaObjectTypeOverride (); string ToInteroperableJavaObject (string varname); } }
17.769231
52
0.809524
[ "MIT" ]
pjcollins/java.interop
tools/generator/IRequireGenericMarshal.cs
231
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using System.Diagnostics; namespace SignalRChat.Pages { [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] [IgnoreAntiforgeryToken] public class ErrorModel : PageModel { public string? RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); private readonly ILogger<ErrorModel> _logger; public ErrorModel(ILogger<ErrorModel> logger) { _logger = logger; } public void OnGet() { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; } } }
26.222222
88
0.65678
[ "MIT" ]
chrhodes/VNC
VNC.Logging/SignalR/AspNetCore/SignalRChat/Pages/Error.cshtml.cs
708
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 kms-2014-11-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.KeyManagementService.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.KeyManagementService.Model.Internal.MarshallTransformations { /// <summary> /// UpdateCustomKeyStore Request Marshaller /// </summary> public class UpdateCustomKeyStoreRequestMarshaller : IMarshaller<IRequest, UpdateCustomKeyStoreRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((UpdateCustomKeyStoreRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(UpdateCustomKeyStoreRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.KeyManagementService"); string target = "TrentService.UpdateCustomKeyStore"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2014-11-01"; request.HttpMethod = "POST"; request.ResourcePath = "/"; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetCloudHsmClusterId()) { context.Writer.WritePropertyName("CloudHsmClusterId"); context.Writer.Write(publicRequest.CloudHsmClusterId); } if(publicRequest.IsSetCustomKeyStoreId()) { context.Writer.WritePropertyName("CustomKeyStoreId"); context.Writer.Write(publicRequest.CustomKeyStoreId); } if(publicRequest.IsSetKeyStorePassword()) { context.Writer.WritePropertyName("KeyStorePassword"); context.Writer.Write(publicRequest.KeyStorePassword); } if(publicRequest.IsSetNewCustomKeyStoreName()) { context.Writer.WritePropertyName("NewCustomKeyStoreName"); context.Writer.Write(publicRequest.NewCustomKeyStoreName); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static UpdateCustomKeyStoreRequestMarshaller _instance = new UpdateCustomKeyStoreRequestMarshaller(); internal static UpdateCustomKeyStoreRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static UpdateCustomKeyStoreRequestMarshaller Instance { get { return _instance; } } } }
36.884298
155
0.62626
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/KeyManagementService/Generated/Model/Internal/MarshallTransformations/UpdateCustomKeyStoreRequestMarshaller.cs
4,463
C#
namespace SampleBW { public partial class PortfoliosWindow { public PortfoliosWindow() { InitializeComponent(); } } }
12.9
38
0.713178
[ "Apache-2.0" ]
DimTrdr/StockSharp
Samples/BW/SampleBW/PortfoliosWindow.xaml.cs
129
C#
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the RemMedicamentoCronico class. /// </summary> [Serializable] public partial class RemMedicamentoCronicoCollection : ActiveList<RemMedicamentoCronico, RemMedicamentoCronicoCollection> { public RemMedicamentoCronicoCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>RemMedicamentoCronicoCollection</returns> public RemMedicamentoCronicoCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { RemMedicamentoCronico o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Rem_MedicamentoCronico table. /// </summary> [Serializable] public partial class RemMedicamentoCronico : ActiveRecord<RemMedicamentoCronico>, IActiveRecord { #region .ctors and Default Settings public RemMedicamentoCronico() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public RemMedicamentoCronico(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public RemMedicamentoCronico(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public RemMedicamentoCronico(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Rem_MedicamentoCronico", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdMedicamentoCronico = new TableSchema.TableColumn(schema); colvarIdMedicamentoCronico.ColumnName = "idMedicamentoCronico"; colvarIdMedicamentoCronico.DataType = DbType.Int32; colvarIdMedicamentoCronico.MaxLength = 0; colvarIdMedicamentoCronico.AutoIncrement = true; colvarIdMedicamentoCronico.IsNullable = false; colvarIdMedicamentoCronico.IsPrimaryKey = true; colvarIdMedicamentoCronico.IsForeignKey = false; colvarIdMedicamentoCronico.IsReadOnly = false; colvarIdMedicamentoCronico.DefaultSetting = @""; colvarIdMedicamentoCronico.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdMedicamentoCronico); TableSchema.TableColumn colvarIdMedicamento = new TableSchema.TableColumn(schema); colvarIdMedicamento.ColumnName = "idMedicamento"; colvarIdMedicamento.DataType = DbType.Int32; colvarIdMedicamento.MaxLength = 0; colvarIdMedicamento.AutoIncrement = false; colvarIdMedicamento.IsNullable = false; colvarIdMedicamento.IsPrimaryKey = false; colvarIdMedicamento.IsForeignKey = true; colvarIdMedicamento.IsReadOnly = false; colvarIdMedicamento.DefaultSetting = @"((0))"; colvarIdMedicamento.ForeignKeyTableName = "Sys_Medicamento"; schema.Columns.Add(colvarIdMedicamento); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("Rem_MedicamentoCronico",schema); } } #endregion #region Props [XmlAttribute("IdMedicamentoCronico")] [Bindable(true)] public int IdMedicamentoCronico { get { return GetColumnValue<int>(Columns.IdMedicamentoCronico); } set { SetColumnValue(Columns.IdMedicamentoCronico, value); } } [XmlAttribute("IdMedicamento")] [Bindable(true)] public int IdMedicamento { get { return GetColumnValue<int>(Columns.IdMedicamento); } set { SetColumnValue(Columns.IdMedicamento, value); } } #endregion #region ForeignKey Properties /// <summary> /// Returns a SysMedicamento ActiveRecord object related to this RemMedicamentoCronico /// /// </summary> public DalSic.SysMedicamento SysMedicamento { get { return DalSic.SysMedicamento.FetchByID(this.IdMedicamento); } set { SetColumnValue("idMedicamento", value.IdMedicamento); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdMedicamento) { RemMedicamentoCronico item = new RemMedicamentoCronico(); item.IdMedicamento = varIdMedicamento; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdMedicamentoCronico,int varIdMedicamento) { RemMedicamentoCronico item = new RemMedicamentoCronico(); item.IdMedicamentoCronico = varIdMedicamentoCronico; item.IdMedicamento = varIdMedicamento; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdMedicamentoCronicoColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdMedicamentoColumn { get { return Schema.Columns[1]; } } #endregion #region Columns Struct public struct Columns { public static string IdMedicamentoCronico = @"idMedicamentoCronico"; public static string IdMedicamento = @"idMedicamento"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
27.65493
136
0.643876
[ "MIT" ]
saludnqn/Empadronamiento
DalSic/generated/RemMedicamentoCronico.cs
7,854
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.IO; using System.Linq; using System.Reflection; using System.Text; namespace Microsoft.AspNetCore.Testing { /// <summary> /// Provides access to file storage for the running test. Get access by /// implementing <see cref="ITestMethodLifecycle"/>, and accessing <see cref="TestContext.FileOutput"/>. /// </summary> /// <remarks> /// Requires defining <see cref="AspNetTestFramework"/> as the test framework. /// </remarks> public sealed class TestFileOutputContext { private static char[] InvalidFileChars = new char[] { '\"', '<', '>', '|', '\0', (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10, (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20, (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30, (char)31, ':', '*', '?', '\\', '/', ' ', (char)127 }; private readonly TestContext _parent; public TestFileOutputContext(TestContext parent) { _parent = parent; TestName = GetTestMethodName(parent.TestMethod, parent.MethodArguments); TestClassName = GetTestClassName(parent.TestClass); AssemblyOutputDirectory = GetAssemblyBaseDirectory(_parent.TestClass.Assembly); if (!string.IsNullOrEmpty(AssemblyOutputDirectory)) { TestClassOutputDirectory = Path.Combine(AssemblyOutputDirectory, TestClassName); } } public string TestName { get; } public string TestClassName { get; } public string AssemblyOutputDirectory { get; } public string TestClassOutputDirectory { get; } public string GetUniqueFileName(string prefix, string extension) { if (prefix == null) { throw new ArgumentNullException(nameof(prefix)); } if (extension != null && !extension.StartsWith(".", StringComparison.Ordinal)) { throw new ArgumentException("The extension must start with '.' if one is provided.", nameof(extension)); } var path = Path.Combine(TestClassOutputDirectory, $"{prefix}{extension}"); var i = 1; while (File.Exists(path)) { path = Path.Combine(TestClassOutputDirectory, $"{prefix}{i++}{extension}"); } return path; } // Gets the output directory without appending the TFM or assembly name. public static string GetOutputDirectory(Assembly assembly) { var attribute = assembly.GetCustomAttributes().OfType<TestOutputDirectoryAttribute>().FirstOrDefault(); return attribute?.BaseDirectory; } public static string GetAssemblyBaseDirectory(Assembly assembly, string baseDirectory = null) { var attribute = assembly.GetCustomAttributes().OfType<TestOutputDirectoryAttribute>().FirstOrDefault(); baseDirectory = baseDirectory ?? attribute?.BaseDirectory; if (string.IsNullOrEmpty(baseDirectory)) { return string.Empty; } return Path.Combine(baseDirectory, assembly.GetName().Name, attribute.TargetFramework); } public static string GetTestClassName(Type type) { var shortNameAttribute = type.GetCustomAttribute<ShortClassNameAttribute>() ?? type.Assembly.GetCustomAttribute<ShortClassNameAttribute>(); var name = shortNameAttribute == null ? type.FullName : type.Name; // Try to shorten the class name using the assembly name var assemblyName = type.Assembly.GetName().Name; if (name.StartsWith(assemblyName + ".")) { name = name.Substring(assemblyName.Length + 1); } return name; } public static string GetTestMethodName(MethodInfo method, object[] arguments) { var name = arguments.Aggregate(method.Name, (a, b) => $"{a}-{(b ?? "null")}"); return RemoveIllegalFileChars(name); } public static string RemoveIllegalFileChars(string s) { var sb = new StringBuilder(); foreach (var c in s) { if (InvalidFileChars.Contains(c)) { if (sb.Length > 0 && sb[sb.Length - 1] != '_') { sb.Append('_'); } } else { sb.Append(c); } } return sb.ToString(); } } }
35.865248
120
0.566937
[ "Apache-2.0" ]
188867052/Extensions
src/TestingUtils/Microsoft.AspNetCore.Testing/src/TestFileOutputContext.cs
5,057
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.Diagnostics; using Microsoft.ServiceHub.Framework; using Roslyn.Utilities; using StreamJsonRpc; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Describes Roslyn remote brokered service. /// Adds Roslyn specific JSON converters and RPC settings to the default implementation. /// </summary> internal sealed class ServiceDescriptor : ServiceJsonRpcDescriptor { /// <summary> /// Brokered services must be defined in Microsoft.VisualStudio service namespace in order to be considered first party. /// </summary> internal const string ServiceNameTopLevelPrefix = "Microsoft.VisualStudio."; private static readonly JsonRpcTargetOptions s_jsonRpcTargetOptions = new() { // Do not allow JSON-RPC to automatically subscribe to events and remote their calls. NotifyClientOfEvents = false, // Only allow public methods (may be on internal types) to be invoked remotely. AllowNonPublicInvocation = false }; internal readonly string ComponentName; internal readonly string SimpleName; private readonly Func<string, string> _featureDisplayNameProvider; private readonly RemoteSerializationOptions _serializationOptions; private ServiceDescriptor( ServiceMoniker serviceMoniker, string componentName, string simpleName, RemoteSerializationOptions serializationOptions, Func<string, string> displayNameProvider, Type? clientInterface) : base(serviceMoniker, clientInterface, serializationOptions.Formatter, serializationOptions.MessageDelimiters, serializationOptions.MultiplexingStreamOptions) { ComponentName = componentName; SimpleName = simpleName; _featureDisplayNameProvider = displayNameProvider; _serializationOptions = serializationOptions; } private ServiceDescriptor(ServiceDescriptor copyFrom) : base(copyFrom) { ComponentName = copyFrom.ComponentName; SimpleName = copyFrom.SimpleName; _featureDisplayNameProvider = copyFrom._featureDisplayNameProvider; _serializationOptions = copyFrom._serializationOptions; } public static ServiceDescriptor CreateRemoteServiceDescriptor(string componentName, string simpleName, string suffix, RemoteSerializationOptions options, Func<string, string> featureDisplayNameProvider, Type? clientInterface) => new(CreateMoniker(componentName, simpleName, suffix), componentName, simpleName, options, featureDisplayNameProvider, clientInterface); public static ServiceDescriptor CreateInProcServiceDescriptor(string componentName, string simpleName, string suffix, Func<string, string> featureDisplayNameProvider) => new(CreateMoniker(componentName, simpleName, suffix), componentName, simpleName, RemoteSerializationOptions.Default, featureDisplayNameProvider, clientInterface: null); private static ServiceMoniker CreateMoniker(string componentName, string simpleName, string suffix) => new(ServiceNameTopLevelPrefix + componentName + "." + simpleName + suffix); protected override ServiceRpcDescriptor Clone() => new ServiceDescriptor(this); protected override IJsonRpcMessageFormatter CreateFormatter() => _serializationOptions.ConfigureFormatter(base.CreateFormatter()); protected override JsonRpcConnection CreateConnection(JsonRpc jsonRpc) { jsonRpc.CancelLocallyInvokedMethodsWhenConnectionIsClosed = true; var connection = base.CreateConnection(jsonRpc); connection.LocalRpcTargetOptions = s_jsonRpcTargetOptions; return connection; } internal string GetFeatureDisplayName() => _featureDisplayNameProvider(SimpleName); } }
46.811111
233
0.718728
[ "MIT" ]
AlexanderSemenyak/roslyn
src/Workspaces/Remote/Core/ServiceDescriptor.cs
4,215
C#
using System; using Aop.Api.Domain; using System.Collections.Generic; using Aop.Api.Response; namespace Aop.Api.Request { /// <summary> /// AOP API: koubei.marketing.campaign.retail.dm.modify /// </summary> public class KoubeiMarketingCampaignRetailDmModifyRequest : IAopRequest<KoubeiMarketingCampaignRetailDmModifyResponse> { /// <summary> /// 快消店铺展位内容修改接口 /// </summary> public string BizContent { get; set; } #region IAopRequest Members private bool needEncrypt=false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AopObject bizModel; private Dictionary<string, string> udfParams; //add user-defined text parameters public void SetNeedEncrypt(bool needEncrypt){ this.needEncrypt=needEncrypt; } public bool GetNeedEncrypt(){ return this.needEncrypt; } public void SetNotifyUrl(string notifyUrl){ this.notifyUrl = notifyUrl; } public string GetNotifyUrl(){ return this.notifyUrl; } public void SetReturnUrl(string returnUrl){ this.returnUrl = returnUrl; } public string GetReturnUrl(){ return this.returnUrl; } public void SetTerminalType(String terminalType){ this.terminalType=terminalType; } public string GetTerminalType(){ return this.terminalType; } public void SetTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public string GetTerminalInfo(){ return this.terminalInfo; } public void SetProdCode(String prodCode){ this.prodCode=prodCode; } public string GetProdCode(){ return this.prodCode; } public string GetApiName() { return "koubei.marketing.campaign.retail.dm.modify"; } public void SetApiVersion(string apiVersion){ this.apiVersion=apiVersion; } public string GetApiVersion(){ return this.apiVersion; } public void PutOtherTextParam(string key, string value) { if(this.udfParams == null) { this.udfParams = new Dictionary<string, string>(); } this.udfParams.Add(key, value); } public IDictionary<string, string> GetParameters() { AopDictionary parameters = new AopDictionary(); parameters.Add("biz_content", this.BizContent); if(udfParams != null) { parameters.AddAll(this.udfParams); } return parameters; } public AopObject GetBizModel() { return this.bizModel; } public void SetBizModel(AopObject bizModel) { this.bizModel = bizModel; } #endregion } }
26.112903
123
0.56887
[ "Apache-2.0" ]
554393109/alipay-sdk-net-all
AlipaySDKNet.Standard/Request/KoubeiMarketingCampaignRetailDmModifyRequest.cs
3,262
C#
using System; namespace ITShare.CSharp.Module1.Arrays { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); OddEvenClass m = new OddEvenClass(); m.Odds(); //int[] degrees = new int[]{2,4,5 }; //int sumOfDegrees = 0; //for(int i=0;i<degrees.Length;i++) //{ // sumOfDegrees=sumOfDegrees+ degrees[i]; //} //sumOfDegrees = 0; //// foreach //foreach(int degree in degrees) //{ // sumOfDegrees = sumOfDegrees + degree; //} //Console.WriteLine(sumOfDegrees); //sumOfDegrees = 0; //int arrIndex = 0; //do //{ // sumOfDegrees += degrees[arrIndex]; // arrIndex = arrIndex + 1;// or arrIndex++ //}while(!(degrees[arrIndex]< 20)); //Console.WriteLine(sumOfDegrees); } } }
26.538462
58
0.449275
[ "MIT" ]
MahmoudShaaban16/aspnet-core-samples
ITShare.CSharp.Module1.Arrays/Program.cs
1,037
C#
using System; namespace Magnesium.Vulkan { [Flags] internal enum VkBufferCreateFlags : uint { BufferCreateSparseBinding = 0x1, BufferCreateSparseResidency = 0x2, BufferCreateSparseAliased = 0x4, } }
16.153846
41
0.766667
[ "MIT" ]
tgsstdio/Mg
Magnesium.Vulkan/Enums/VkBufferCreateFlags.cs
210
C#
using AutoMapper; using MediatR; using Microsoft.Extensions.Logging; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using VoipProjectEntities.Application.Contracts.Persistence; using VoipProjectEntities.Application.Responses; using VoipProjectEntities.Domain.Entities; namespace VoipProjectEntities.Application.Features.Categories.Queries.GetCategoriesList { public class GetCategoriesListQueryHandler : IRequestHandler<GetCategoriesListQuery, Response<IEnumerable<CategoryListVm>>> { private readonly ICategoryRepository _categoryRepository; private readonly IMapper _mapper; private readonly ILogger _logger; public GetCategoriesListQueryHandler(IMapper mapper, ICategoryRepository categoryRepository, ILogger<GetCategoriesListQueryHandler> logger) { _mapper = mapper; _categoryRepository = categoryRepository; _logger = logger; } public async Task<Response<IEnumerable<CategoryListVm>>> Handle(GetCategoriesListQuery request, CancellationToken cancellationToken) { _logger.LogInformation("Handle Initiated"); var allCategories = (await _categoryRepository.ListAllAsync()).OrderBy(x => x.Name); var category = _mapper.Map<IEnumerable<CategoryListVm>>(allCategories); _logger.LogInformation("Hanlde Completed"); return new Response<IEnumerable<CategoryListVm>>(category, "success"); } } }
38.4
147
0.746094
[ "Apache-2.0" ]
Anagha1009/VoIPCustomerWebPortal-1
src/Core/VoipProjectEntities.Application/Features/Categories/Queries/GetCategoriesList/GetCategoriesListQueryHandler.cs
1,536
C#
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("ALSASharp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("${AuthorCopyright}")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
36.777778
82
0.743202
[ "Apache-2.0" ]
crojewsk/ALSASharp
ALSASharp/Properties/AssemblyInfo.cs
995
C#
namespace Moo.Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class ExpandingGameTable : DbMigration { public override void Up() { AddColumn("dbo.Game", "UserWon", c => c.Boolean(nullable: false)); AddColumn("dbo.Game", "Draw", c => c.Boolean(nullable: false)); AddColumn("dbo.User", "ActiveGameID", c => c.Int(nullable: false)); DropColumn("dbo.Game", "HasUserWon"); DropColumn("dbo.User", "FirstName"); DropColumn("dbo.User", "LastName"); DropColumn("dbo.User", "Email"); } public override void Down() { AddColumn("dbo.User", "Email", c => c.String()); AddColumn("dbo.User", "LastName", c => c.String()); AddColumn("dbo.User", "FirstName", c => c.String()); AddColumn("dbo.Game", "HasUserWon", c => c.Boolean(nullable: false)); DropColumn("dbo.User", "ActiveGameID"); DropColumn("dbo.Game", "Draw"); DropColumn("dbo.Game", "UserWon"); } } }
36.419355
81
0.536758
[ "MIT" ]
achobanov/Moo-at-SoftUni
Moo.Data/Migrations/201803041849277_ExpandingGameTable.cs
1,129
C#
using System; using Core.Errors.Interfaces; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; namespace Core.Errors.Handlers { public class ExceptionHandler : IExceptionHandler { private readonly ILogger<ExceptionHandler> _logger; public ExceptionHandler(ILogger<ExceptionHandler> logger) { _logger = logger; } public Error HandleException(Exception exception) { var error = exception switch { _ => HandleUnexpectedExceptions(exception) }; return error; } private Error HandleUnexpectedExceptions(Exception exception) { _logger.LogError(exception, exception.Message); return new Error { Message = exception.Message, StatusCode = StatusCodes.Status500InternalServerError }; } } }
25.026316
69
0.600421
[ "MIT" ]
GUSTAVPEREIRA/StoreManagerWithDapper
StoreManager/src/Core/Errors/Handlers/ExceptionHandler.cs
951
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: ComplexType.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// The type ExternalItemContent. /// </summary> [JsonObject(MemberSerialization = MemberSerialization.OptIn)] [JsonConverter(typeof(DerivedTypeConverter))] public partial class ExternalItemContent { /// <summary> /// Initializes a new instance of the <see cref="ExternalItemContent"/> class. /// </summary> public ExternalItemContent() { this.ODataType = "microsoft.graph.externalItemContent"; } /// <summary> /// Gets or sets type. /// The type of content in the value property. Possible values are text and html. Required. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "type", Required = Newtonsoft.Json.Required.Default)] public ExternalItemContentType? Type { get; set; } /// <summary> /// Gets or sets value. /// The content for the externalItem. Required. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "value", Required = Newtonsoft.Json.Required.Default)] public string Value { get; set; } /// <summary> /// Gets or sets additional data. /// </summary> [JsonExtensionData(ReadData = true)] public IDictionary<string, object> AdditionalData { get; set; } /// <summary> /// Gets or sets @odata.type. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "@odata.type", Required = Newtonsoft.Json.Required.Default)] public string ODataType { get; set; } } }
38.065574
153
0.596038
[ "MIT" ]
GeertVL/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/model/ExternalItemContent.cs
2,322
C#
using DCL; using DCL.Interface; using ExploreV2Analytics; using System; using System.Collections.Generic; using System.Linq; using UnityEngine; public interface IEventsSubSectionComponentController : IDisposable { /// <summary> /// It will be triggered when the sub-section want to request to close the ExploreV2 main menu. /// </summary> event Action OnCloseExploreV2; /// <summary> /// Request all events from the API. /// </summary> void RequestAllEvents(); /// <summary> /// Load the featured events with the last requested ones. /// </summary> void LoadFeaturedEvents(); /// <summary> /// Load the trending events with the last requested ones. /// </summary> void LoadTrendingEvents(); /// <summary> /// Load the upcoming events with the last requested ones. /// </summary> void LoadUpcomingEvents(); /// <summary> /// Increment the number of upcoming events loaded. /// </summary> void ShowMoreUpcomingEvents(); /// <summary> /// Load the going events with the last requested ones. /// </summary> void LoadGoingEvents(); } public class EventsSubSectionComponentController : IEventsSubSectionComponentController { public event Action OnCloseExploreV2; internal event Action OnEventsFromAPIUpdated; internal const int DEFAULT_NUMBER_OF_FEATURED_EVENTS = 3; internal const int INITIAL_NUMBER_OF_UPCOMING_ROWS = 1; internal const int SHOW_MORE_UPCOMING_ROWS_INCREMENT = 2; internal const string EVENT_DETAIL_URL = "https://events.decentraland.org/event/?id={0}"; internal IEventsSubSectionComponentView view; internal IEventsAPIController eventsAPIApiController; internal List<EventFromAPIModel> eventsFromAPI = new List<EventFromAPIModel>(); internal int currentUpcomingEventsShowed = 0; internal bool reloadEvents = false; internal IExploreV2Analytics exploreV2Analytics; internal float lastTimeAPIChecked = 0; public EventsSubSectionComponentController( IEventsSubSectionComponentView view, IEventsAPIController eventsAPI, IExploreV2Analytics exploreV2Analytics) { this.view = view; this.view.OnReady += FirstLoading; this.view.OnInfoClicked += ShowEventDetailedInfo; this.view.OnJumpInClicked += JumpInToEvent; this.view.OnSubscribeEventClicked += SubscribeToEvent; this.view.OnUnsubscribeEventClicked += UnsubscribeToEvent; this.view.OnShowMoreUpcomingEventsClicked += ShowMoreUpcomingEvents; eventsAPIApiController = eventsAPI; OnEventsFromAPIUpdated += OnRequestedEventsUpdated; this.exploreV2Analytics = exploreV2Analytics; view.ConfigurePools(); } internal void FirstLoading() { reloadEvents = true; lastTimeAPIChecked = Time.realtimeSinceStartup - PlacesAndEventsSectionComponentController.MIN_TIME_TO_CHECK_API; RequestAllEvents(); view.OnEventsSubSectionEnable += RequestAllEvents; DataStore.i.exploreV2.isOpen.OnChange += OnExploreV2Open; } internal void OnExploreV2Open(bool current, bool previous) { if (current) return; reloadEvents = true; } public void RequestAllEvents() { if (!reloadEvents) return; view.RestartScrollViewPosition(); if (Time.realtimeSinceStartup < lastTimeAPIChecked + PlacesAndEventsSectionComponentController.MIN_TIME_TO_CHECK_API) return; currentUpcomingEventsShowed = view.currentUpcomingEventsPerRow * INITIAL_NUMBER_OF_UPCOMING_ROWS; view.SetFeaturedEventsAsLoading(true); view.SetTrendingEventsAsLoading(true); view.SetUpcomingEventsAsLoading(true); view.SetShowMoreUpcomingEventsButtonActive(false); view.SetGoingEventsAsLoading(true); reloadEvents = false; lastTimeAPIChecked = Time.realtimeSinceStartup; if (!DataStore.i.exploreV2.isInShowAnimationTransiton.Get()) RequestAllEventsFromAPI(); else DataStore.i.exploreV2.isInShowAnimationTransiton.OnChange += IsInShowAnimationTransitonChanged; } internal void IsInShowAnimationTransitonChanged(bool current, bool previous) { DataStore.i.exploreV2.isInShowAnimationTransiton.OnChange -= IsInShowAnimationTransitonChanged; RequestAllEventsFromAPI(); } internal void RequestAllEventsFromAPI() { eventsAPIApiController.GetAllEvents( (eventList) => { eventsFromAPI = eventList; OnEventsFromAPIUpdated?.Invoke(); }, (error) => { Debug.LogError($"Error receiving events from the API: {error}"); }); } internal void OnRequestedEventsUpdated() { LoadFeaturedEvents(); LoadTrendingEvents(); LoadUpcomingEvents(); LoadGoingEvents(); } public void LoadFeaturedEvents() { List<EventCardComponentModel> featuredEvents = new List<EventCardComponentModel>(); List<EventFromAPIModel> eventsFiltered = eventsFromAPI.Where(e => e.highlighted).ToList(); if (eventsFiltered.Count == 0) eventsFiltered = eventsFromAPI.Take(DEFAULT_NUMBER_OF_FEATURED_EVENTS).ToList(); foreach (EventFromAPIModel receivedEvent in eventsFiltered) { EventCardComponentModel eventCardModel = ExploreEventsUtils.CreateEventCardModelFromAPIEvent(receivedEvent); featuredEvents.Add(eventCardModel); } view.SetFeaturedEvents(featuredEvents); view.SetFeaturedEventsAsLoading(false); view.SetFeaturedEventsActive(featuredEvents.Count > 0); } public void LoadTrendingEvents() { List<EventCardComponentModel> trendingEvents = new List<EventCardComponentModel>(); List<EventFromAPIModel> eventsFiltered = eventsFromAPI.Where(e => e.trending).ToList(); foreach (EventFromAPIModel receivedEvent in eventsFiltered) { EventCardComponentModel eventCardModel = ExploreEventsUtils.CreateEventCardModelFromAPIEvent(receivedEvent); trendingEvents.Add(eventCardModel); } view.SetTrendingEvents(trendingEvents); view.SetTrendingEventsAsLoading(false); } public void LoadUpcomingEvents() { List<EventCardComponentModel> upcomingEvents = new List<EventCardComponentModel>(); List<EventFromAPIModel> eventsFiltered = eventsFromAPI.Take(currentUpcomingEventsShowed).ToList(); foreach (EventFromAPIModel receivedEvent in eventsFiltered) { EventCardComponentModel eventCardModel = ExploreEventsUtils.CreateEventCardModelFromAPIEvent(receivedEvent); upcomingEvents.Add(eventCardModel); } view.SetUpcomingEvents(upcomingEvents); view.SetShowMoreUpcomingEventsButtonActive(currentUpcomingEventsShowed < eventsFromAPI.Count); view.SetUpcomingEventsAsLoading(false); } public void ShowMoreUpcomingEvents() { List<EventCardComponentModel> upcomingEvents = new List<EventCardComponentModel>(); List<EventFromAPIModel> eventsFiltered = new List<EventFromAPIModel>(); int numberOfExtraItemsToAdd = ((int)Mathf.Ceil((float)currentUpcomingEventsShowed / view.currentUpcomingEventsPerRow) * view.currentUpcomingEventsPerRow) - currentUpcomingEventsShowed; int numberOfItemsToAdd = view.currentUpcomingEventsPerRow * SHOW_MORE_UPCOMING_ROWS_INCREMENT + numberOfExtraItemsToAdd; if (currentUpcomingEventsShowed + numberOfItemsToAdd <= eventsFromAPI.Count) eventsFiltered = eventsFromAPI.GetRange(currentUpcomingEventsShowed, numberOfItemsToAdd); else eventsFiltered = eventsFromAPI.GetRange(currentUpcomingEventsShowed, eventsFromAPI.Count - currentUpcomingEventsShowed); foreach (EventFromAPIModel receivedEvent in eventsFiltered) { EventCardComponentModel placeCardModel = ExploreEventsUtils.CreateEventCardModelFromAPIEvent(receivedEvent); upcomingEvents.Add(placeCardModel); } view.AddUpcomingEvents(upcomingEvents); currentUpcomingEventsShowed += numberOfItemsToAdd; if (currentUpcomingEventsShowed > eventsFromAPI.Count) currentUpcomingEventsShowed = eventsFromAPI.Count; view.SetShowMoreUpcomingEventsButtonActive(currentUpcomingEventsShowed < eventsFromAPI.Count); } public void LoadGoingEvents() { List<EventCardComponentModel> goingEvents = new List<EventCardComponentModel>(); List<EventFromAPIModel> eventsFiltered = eventsFromAPI.Where(e => e.attending).ToList(); foreach (EventFromAPIModel receivedEvent in eventsFiltered) { EventCardComponentModel eventCardModel = ExploreEventsUtils.CreateEventCardModelFromAPIEvent(receivedEvent); goingEvents.Add(eventCardModel); } view.SetGoingEvents(goingEvents); view.SetGoingEventsAsLoading(false); } public void Dispose() { view.OnReady -= FirstLoading; view.OnInfoClicked -= ShowEventDetailedInfo; view.OnJumpInClicked -= JumpInToEvent; view.OnSubscribeEventClicked -= SubscribeToEvent; view.OnUnsubscribeEventClicked -= UnsubscribeToEvent; view.OnShowMoreUpcomingEventsClicked -= ShowMoreUpcomingEvents; view.OnEventsSubSectionEnable -= RequestAllEvents; OnEventsFromAPIUpdated -= OnRequestedEventsUpdated; DataStore.i.exploreV2.isOpen.OnChange -= OnExploreV2Open; } internal void ShowEventDetailedInfo(EventCardComponentModel eventModel) { view.ShowEventModal(eventModel); exploreV2Analytics.SendClickOnEventInfo(eventModel.eventId, eventModel.eventName); } internal void JumpInToEvent(EventFromAPIModel eventFromAPI) { ExploreEventsUtils.JumpInToEvent(eventFromAPI); view.HideEventModal(); OnCloseExploreV2?.Invoke(); exploreV2Analytics.SendEventTeleport(eventFromAPI.id, eventFromAPI.name, new Vector2Int(eventFromAPI.coordinates[0], eventFromAPI.coordinates[1])); } internal void SubscribeToEvent(string eventId) { // TODO (Santi): Remove when the RegisterAttendEvent POST is available. WebInterface.OpenURL(string.Format(EVENT_DETAIL_URL, eventId)); // TODO (Santi): Waiting for the new version of the Events API where we will be able to send a signed POST to register our user in an event. //eventsAPIApiController.RegisterAttendEvent( // eventId, // true, // () => // { // // ... // }, // (error) => // { // Debug.LogError($"Error posting 'attend' message to the API: {error}"); // }); } internal void UnsubscribeToEvent(string eventId) { // TODO (Santi): Remove when the RegisterAttendEvent POST is available. WebInterface.OpenURL(string.Format(EVENT_DETAIL_URL, eventId)); // TODO (Santi): Waiting for the new version of the Events API where we will be able to send a signed POST to unregister our user in an event. //eventsAPIApiController.RegisterAttendEvent( // eventId, // false, // () => // { // // ... // }, // (error) => // { // Debug.LogError($"Error posting 'attend' message to the API: {error}"); // }); } }
37.300319
192
0.690193
[ "Apache-2.0" ]
Timothyoung97/unity-renderer
unity-renderer/Assets/Scripts/MainScripts/DCL/Controllers/ExploreV2/Scripts/Sections/PlacesAndEventsSection/SubSections/EventsSubSection/EventsSubSectionMenu/EventsSubSectionComponentController.cs
11,675
C#
using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; namespace FluidCollections { public static partial class ReactiveDictionaryExtensions { public static ICollectedReactiveSet<TValue> ToValueSet<TKey, TValue>(this IReactiveDictionary<TKey, TValue> dict) { return dict.ToSet().Select(x => x.Value); } public static ICollectedReactiveSet<TKey> ToKeySet<TKey, TValue>(this IReactiveDictionary<TKey, TValue> dict) { return dict.ToSet().Select(x => x.Key); } public static IReactiveSet<KeyValuePair<TKey, TValue>> ToSet<TKey, TValue>(this IReactiveDictionary<TKey, TValue> dict) { return dict.AsObservable().SelectMany(changes => changes.SelectMany(change => { if (change.ChangeReason == ReactiveDictionaryChangeReason.AddOrUpdate) { if (dict.TryGetValue(change.Key, out var oldValue)) { // Updating, so remove the old pair and add the new one return new[] { new ReactiveSetChange<KeyValuePair<TKey, TValue>>( ReactiveSetChangeReason.Remove, new[] { new KeyValuePair<TKey, TValue>(change.Key, oldValue) } ), new ReactiveSetChange<KeyValuePair<TKey, TValue>>( ReactiveSetChangeReason.Add, new[] { new KeyValuePair<TKey, TValue>(change.Key, change.Value) } ) }; } } // Just adding or removing return new[] { new ReactiveSetChange<KeyValuePair<TKey, TValue>>( change.ChangeReason == ReactiveDictionaryChangeReason.AddOrUpdate ? ReactiveSetChangeReason.Add : ReactiveSetChangeReason.Remove, new[] { new KeyValuePair<TKey, TValue>(change.Key, change.Value) } ) }; })) .ToReactiveSet(pair => dict.TryGetValue(pair.Key, out var value) && value.Equals(pair.Value)); } } }
50.636364
153
0.552962
[ "MIT" ]
Blue0500/FluidCollections
src/FluidCollections/ReactiveDictionary/Operators/SetConversions.cs
2,230
C#
using Lykke.SettingsReader.Attributes; namespace Lykke.Job.SolarCoinCashinGrabber.Settings.JobSettings { public class DbSettings { [AzureTableCheck] public string LogsConnString { get; set; } public string MongoConnString { get; set; } [AzureTableCheck] public string AzureQueueConnString { get; set; } } }
23.6875
63
0.649077
[ "MIT" ]
LykkeCity/Lykke.Job.SolarCoinCashinGrabber
src/Lykke.Job.SolarCoinCashinGrabber/Settings/JobSettings/DbSettings.cs
381
C#
namespace Definux.Emeraude.Application.Requests.Identity.Queries.GetUserExternalLoginProviders { /// <summary> /// Wrap for external login provider. /// </summary> public class UserExternalLoginProvider { /// <summary> /// External login provider. /// </summary> public string Provider { get; set; } /// <summary> /// External login provider display name. /// </summary> public string ProviderDisplayName { get; set; } } }
28.444444
95
0.603516
[ "Apache-2.0" ]
Definux/Emeraude
src/Core/Definux.Emeraude.Application/Requests/Identity/Queries/GetUserExternalLoginProviders/UserExternalLoginProvider.cs
514
C#
/* The MIT License (MIT) Copyright 2021 Adam Reilly, Call to Action Software LLC 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. */ namespace Cta.Combat { /// <summary> /// Attach to Unity GameObjects to associate them with MalfunctionTimer /// </summary> [UnityEngine.AddComponentMenu(Defines.CallToActionMenuItem + "/" + Defines.CombatMenuItem + "/MalfunctionTimer")] public class MalfunctionTimerBootstrapWrapper : MalfunctionTimerBootstrap { } }
75.315789
460
0.795248
[ "MIT" ]
areilly711/CtaApi
Unity/CtaApi/Packages/com.calltoaction.ctaapi/CtaUnity/Runtime/Scripts/Wrappers/Combat/MalfunctionTimerBootstrapWrapper.cs
1,431
C#
using System.IO; using ExpressionCompiler.Expressions; using ExpressionCompiler.Tokens; namespace ExpressionCompiler.Emitter.TinyStackMachine { internal class TinyStackMachineEmitter : Emitter<bool> { private readonly TextWriter _writer; private readonly TextWriter _debugInfoWriter; private int _emittedLine; //--------------------------------------------------------------------- public TinyStackMachineEmitter(Expression tree, TextWriter writer, TextWriter debugInfoWriter) : base(tree) { _writer = writer; _debugInfoWriter = debugInfoWriter; } //--------------------------------------------------------------------- public override void Emit() { _writer.WriteLine(".formula"); _emittedLine++; this.Tree.Accept(this); _writer.WriteLine("print"); _emittedLine++; _writer.WriteLine(".end"); _emittedLine++; } //--------------------------------------------------------------------- public override bool Visit(ConstantExpression constant) => this.VisitConstant(constant); public override bool Visit(IndexExpression indexExpression) => this.VisitConstant(indexExpression); //--------------------------------------------------------------------- private bool VisitConstant<T>(ConstantExpression<T> constant) where T : struct { _writer.WriteLine($"push {constant.Value}"); _emittedLine++; this.EmitDebugInfo(constant); return true; } //--------------------------------------------------------------------- public override bool Visit(ArrayIndexExpression arrayIndexExpression) { arrayIndexExpression.Right.Accept(this); _writer.WriteLine("arr_index"); _emittedLine++; this.EmitDebugInfo(arrayIndexExpression); return true; } //--------------------------------------------------------------------- public override bool Visit(AddExpression addExpression) => this.VisitBinaryCore(addExpression , "add"); public override bool Visit(SubtractExpression subtractExpression) => this.VisitBinaryCore(subtractExpression , "sub"); public override bool Visit(MultiplyExpression multiplyExpression) => this.VisitBinaryCore(multiplyExpression , "mul"); public override bool Visit(DivideExpression divideExpression) => this.VisitBinaryCore(divideExpression , "div"); public override bool Visit(ExponentationExpression exponentationExpression) => this.VisitBinaryCore(exponentationExpression, "exp"); public override bool Visit(ModuloExpression moduloExpression) => this.VisitBinaryCore(moduloExpression , "mod"); public override bool Visit(SinExpression sinExpression) => this.VisitInstrinsicsCore(sinExpression, "sin"); public override bool Visit(CosExpression cosExpression) => this.VisitInstrinsicsCore(cosExpression, "cos"); public override bool Visit(TanExpression tanExpression) => this.VisitInstrinsicsCore(tanExpression, "tan"); public override bool Visit(LogExpression logExpression) => this.VisitInstrinsicsCore(logExpression, "log"); public override bool Visit(SqrtExpression sqrtExpression) => this.VisitInstrinsicsCore(sqrtExpression, "sqrt"); //--------------------------------------------------------------------- private bool VisitBinaryCore(BinaryExpression binaryExpression, string cmd) { binaryExpression.Left.Accept(this); binaryExpression.Right.Accept(this); _writer.WriteLine(cmd); _emittedLine++; this.EmitDebugInfo(binaryExpression); return true; } //--------------------------------------------------------------------- private bool VisitInstrinsicsCore(IntrinsicExpression intrinsic, string cmd) { intrinsic.Argument.Accept(this); _writer.WriteLine(cmd); _emittedLine++; this.EmitDebugInfo(intrinsic); return true; } //--------------------------------------------------------------------- private void EmitDebugInfo(Expression expression) { if (_debugInfoWriter == null) return; Position position = expression.Token.Position; _debugInfoWriter.WriteLine($"{_emittedLine} {position.Start} {position.End}"); } } }
47.205882
140
0.538941
[ "MIT" ]
gfoidl-Tests/ExpressionEvaluator
source/ExpressionCompiler/Emitter/TinyStackMachine/TinyStackMachineEmitter.cs
4,817
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LANHelper.Secrets { public partial class SecretKeys { public static readonly string DesktopMAC = ""; public static readonly string LaptopMAC = ""; } }
20.466667
54
0.713355
[ "MIT" ]
alancheung/SleepOnLAN
SleepOnLAN/LANHelper/Secrets/SecretKeys.cs
309
C#
using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ManageCourseAPI.Model.Request { public class UpdateGradeRequest { public IFormFile file { get; set; } public string CurrentUser { get; set; } } }
21.066667
47
0.718354
[ "MIT" ]
hdh-se/classroom-api
ManageCourseAPI/Model/Request/UpdateGradeRequest.cs
318
C#
using System.ComponentModel.DataAnnotations; namespace Core { //Event object that carries event data between processes and is being used when fetching the data public record struct EventDTO( [Required] int Id, [Required, StringLength(50)] string Name, [Required] string Date, [Required] string Location, ICollection<CandidateDTO> Candidates, QuizDTO Quiz, [Required] double Rating, ICollection<int> WinnersId ); }
18.5
101
0.596396
[ "MIT" ]
00kristian/SYST
Core/EventDTO.cs
555
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WastePermits.Model.EarlyBound { [System.Runtime.Serialization.DataContractAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "9.0.0.9369")] public enum Incident_defra_destination { [System.Runtime.Serialization.EnumMemberAttribute()] Email = 910400001, [System.Runtime.Serialization.EnumMemberAttribute()] Letter = 910400000, } }
30.916667
80
0.576819
[ "Unlicense" ]
DEFRA/license-and-permitting-dynamics
Crm/WastePermits/Defra.Lp.WastePermits/Model/EarlyBound/OptionSets/Incident_defra_destination.cs
742
C#
using TechTalk.SpecFlow.Bindings.Reflection; namespace TechTalk.SpecFlow.Bindings.Discovery { public class BindingSourceMethod { public IBindingMethod BindingMethod { get; set; } public bool IsPublic { get; set; } public bool IsStatic { get; set; } public BindingSourceAttribute[] Attributes { get; set; } } }
27.307692
64
0.68169
[ "BSD-3-Clause", "Apache-2.0", "MIT" ]
304NotModified/SpecFlow
TechTalk.SpecFlow/Bindings/Discovery/BindingSourceMethod.cs
355
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Threading; using System.Threading.Tasks; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.Dialogs; namespace Microsoft.BotBuilderSamples { public static class DialogExtensions { public static async Task Run(this Dialog dialog, ITurnContext turnContext, IStatePropertyAccessor<DialogState> accessor, CancellationToken cancellationToken = default(CancellationToken)) { var dialogSet = new DialogSet(accessor); dialogSet.Add(dialog); var dialogContext = await dialogSet.CreateContextAsync(turnContext, cancellationToken); var results = await dialogContext.ContinueDialogAsync(cancellationToken); if (results.Status == DialogTurnStatus.Empty) { await dialogContext.BeginDialogAsync(dialog.Id, null, cancellationToken); } } } }
37.222222
195
0.688557
[ "MIT" ]
Azure-Samples/cognitive-services-language-understanding
documentation-samples/tutorial-web-app-bot-application-insights/v4/luis-csharp-bot-johnsmith-src-telemetry/DialogExtensions.cs
1,005
C#
using MediatR; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using VoipProjectEntities.Application.Features.TrialBalanceCustomers.Commands.CreateTrialBalanceCustomer; using VoipProjectEntities.Application.Features.TrialBalanceCustomers.Commands.DeleteTrialBalanceCustomer; using VoipProjectEntities.Application.Features.TrialBalanceCustomers.Commands.UpdateTrialBalanceCustomer; using VoipProjectEntities.Application.Features.TrailBalanceCustomers.Queries.GetTrailBalanceCustomersList; using Microsoft.AspNetCore.Authorization; namespace VoipProjectEntities.Api.Controllers.v1 { [Route("api/[controller]")] [ApiController] public class TrailBalanceCustomerController : ControllerBase { private readonly IMediator _mediator; public TrailBalanceCustomerController(IMediator mediator) { _mediator = mediator; } [HttpGet(Name = "TrailBalanceCustomers")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesDefaultResponseType] public async Task<ActionResult> GetTrailBalanceCustomers([FromQuery]string fromDate, string toDate) { var dtos = await _mediator.Send(new GetTrailBalanceCustomerListQuery() { FromDate = fromDate, ToDate = toDate}); return Ok(dtos); } [HttpPost(Name = "AddTrailBalanceCustomer")] public async Task<ActionResult> Create([FromBody] CreateTrailBalanceCustomerCommand createTrailBalanceCustomerCommand) { var id = await _mediator.Send(createTrailBalanceCustomerCommand); return Ok(id); } [HttpPut(Name = "UpdateTrailBalanceCustomer")] //[ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesDefaultResponseType] public async Task<ActionResult> Update([FromBody] UpdateTrailBalanceCustomerCommand updateTrailBalanceCustomerCommand) { var response = await _mediator.Send(updateTrailBalanceCustomerCommand); return Ok(response); } [HttpDelete("{id}", Name = "TrailBalanceCustomer")] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesDefaultResponseType] public async Task<ActionResult> Delete(string id) { var deleteMenuAccessCommand = new DeleteTrailBalanceCustomerCommand() { TrailBalanceCustomerId = id }; await _mediator.Send(deleteMenuAccessCommand); return NoContent(); } } }
41.30303
126
0.731475
[ "Apache-2.0" ]
Anagha1009/VoIPCustomerWebPortal-1
src/API/VoipProjectEntities.Api/Controllers/v1/TrailBalanceCustomerController.cs
2,728
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.IO; using System.Text; using System.Windows.Forms; using ManicDigger; using ManicDigger.ClientNative; using ManicDigger.Server; using OpenTK; using OpenTK.Graphics.OpenGL; namespace MdMonsterEditor { public partial class Form1 : Form { public Form1() { InitializeComponent(); } IGetFileStream getfile; private void Form1_Load(object sender, EventArgs e) { // load skin file string[] datapaths = new[] { Path.Combine(Path.Combine(Path.Combine("..", ".."), ".."), "data"), "data" }; getfile = new GetFileStream(datapaths); richTextBox1.Text = new StreamReader(getfile.GetFile("player.txt")).ReadToEnd(); // init UI RichTextBoxContextMenu(richTextBox1); RichTextBoxContextMenu(richTextBox2); UpdateLabels(); // init 3D rendering the3d = new ManicDigger.TextureLoader() { d_Config3d = config3d }; glControl1.Paint += new PaintEventHandler(glControl1_Paint); glControl1.MouseWheel += new System.Windows.Forms.MouseEventHandler(glControl1_MouseWheel); loaded = true; GL.ClearColor(Color.SkyBlue); overheadcameraK.SetDistance(4); overheadcameraK.SetT((float)Math.PI); SetupViewport(); Application.Idle += new EventHandler(Application_Idle); sw.Start(); } private void RichTextBoxContextMenu(RichTextBox richTextBox) { ContextMenu cm = new ContextMenu(); MenuItem mi = new MenuItem("Cut"); mi.Click += (a, b) => { richTextBox.Cut(); }; cm.MenuItems.Add(mi); mi = new MenuItem("Copy"); mi.Click += (a, b) => { richTextBox.Copy(); }; cm.MenuItems.Add(mi); mi = new MenuItem("Paste"); mi.Click += (a, b) => { richTextBox.Paste(DataFormats.GetFormat(DataFormats.UnicodeText)); }; cm.MenuItems.Add(mi); richTextBox.ContextMenu = cm; } private void UpdateLabels() { label1.Text = string.Format("Heading: {0} degrees.", HeadingDeg()); label2.Text = string.Format("Pitch: {0} degrees.", PitchDeg()); } private float HeadingDeg() { return -trackBar1.Value * 30; } private float PitchDeg() { return trackBar2.Value * 15; } Stopwatch sw = new Stopwatch(); float dt; void Application_Idle(object sender, EventArgs e) { // Update dt as time since last call sw.Stop(); double milliseconds = sw.Elapsed.TotalMilliseconds; dt = (float)(milliseconds / 1000); sw.Restart(); // Invalidate the GLControl to force a redraw glControl1.Invalidate(); } void glControl1_MouseWheel(object sender, System.Windows.Forms.MouseEventArgs e) { if (e.Delta != 0) { overheadcameraK.SetDistance(overheadcameraK.GetDistance() - 0.002f * e.Delta); } } void glControl1_Paint(object sender, PaintEventArgs e) { // Forward Paint event to Render() Render(); } bool loaded; int playertexture = -1; bool modelLoaded; private void Render() { if (!loaded || !modelLoaded) { // Do not update if no model is currently loaded return; } // Clear buffers for new frame GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); // Initialize camera GL.MatrixMode(MatrixMode.Modelview); GL.LoadIdentity(); OverheadCamera(); // Load model texture if (playertexture == -1) { LoadPlayerTexture(MyStream.ReadAllBytes(getfile.GetFile("mineplayer.png"))); } // Draw grass and axis lines DrawGrass(); DrawAxisLine(new Vector3(), HeadingDeg(), PitchDeg()); // Try to render the model and display errors GL.Enable(EnableCap.Texture2D); bool exception = false; try { game.GLMatrixModeModelView(); game.GLLoadMatrix(m); GL.BindTexture(TextureTarget.Texture2D, playertexture); game.GLRotate(HeadingDeg(), 0, 1, 0); d.Render(dt, PitchDeg(), 1); } catch (Exception ee) { if (richTextBox2Text != ee.ToString()) { richTextBox2Text = ee.ToString(); richTextBox2.Text = ee.ToString(); } exception = true; } if (!exception) { richTextBox2.Text = ""; richTextBox2Text = ""; progressBar1.Value = (int)((d.GetAnimationFrame() / d.GetAnimationLength()) * progressBar1.Maximum); } // Swap buffers to draw changes glControl1.SwapBuffers(); } string richTextBox2Text = ""; private void DrawAxisLine(Vector3 v, float myheadingdeg, float mypitchdeg) { GL.Disable(EnableCap.Texture2D); GL.PushMatrix(); GL.Translate(v); GL.Rotate(myheadingdeg, 0, 1, 0); GL.Rotate(mypitchdeg, 0, 0, 1); GL.Begin(PrimitiveType.Lines); GL.Color3(Color.Red); GL.Vertex3(0, 0.1, 0); GL.Vertex3(2, 0.1, 0); GL.Color3(Color.Green); GL.Vertex3(0, 0.1, 0); GL.Vertex3(0, 2, 0); GL.Color3(Color.Blue); GL.Vertex3(0, 0.1, 0); GL.Vertex3(0, 0.1, 2); GL.End(); GL.Color3(Color.White); GL.PopMatrix(); } TextureLoader the3d; int grasstexture = -1; private void DrawGrass() { if (grasstexture == -1) { grasstexture = LoadTexture(getfile.GetFile("grass_tiled.png")); } GL.BindTexture(TextureTarget.Texture2D, grasstexture); GL.Enable(EnableCap.Texture2D); GL.Color3(Color.White); GL.Begin(PrimitiveType.Quads); Rectangle r = new Rectangle(-10, -10, 20, 20); DrawWaterQuad(r.X, r.Y, r.Width, r.Height, 0); GL.End(); } public int LoadTexture(Stream file) { using (file) { using (Bitmap bmp = new Bitmap(file)) { return the3d.LoadTexture(bmp); } } } private void LoadPlayerTexture(byte[] file) { playertexture = the3d.LoadTexture(new Bitmap(new MemoryStream(file))); } void DrawWaterQuad(float x1, float y1, float width, float height, float z1) { RectangleF rect = new RectangleF(0, 0, 1 * width, 1 * height); float x2 = x1 + width; float y2 = y1 + height; GL.TexCoord2(rect.Right, rect.Bottom); GL.Vertex3(x2, z1, y2); GL.TexCoord2(rect.Right, rect.Top); GL.Vertex3(x2, z1, y1); GL.TexCoord2(rect.Left, rect.Top); GL.Vertex3(x1, z1, y1); GL.TexCoord2(rect.Left, rect.Bottom); GL.Vertex3(x1, z1, y2); } AnimatedModelRenderer d; AnimationState animstate = new AnimationState(); Config3d config3d = new Config3d(); Kamera overheadcameraK = new Kamera(); Vector3 up = new Vector3(0f, 1f, 0f); private void SetupViewport() { float aspect_ratio = glControl1.Width / (float)glControl1.Height; Matrix4 perspective = Matrix4.CreatePerspectiveFieldOfView(fov, aspect_ratio, znear, zfar); GL.MatrixMode(MatrixMode.Projection); GL.LoadMatrix(ref perspective); OverheadCamera(); } GamePlatformNative platform = new GamePlatformNative(); private void OverheadCamera() { GL.MatrixMode(MatrixMode.Modelview); Vector3Ref position = new Vector3Ref(); overheadcameraK.GetPosition(platform, position); Vector3 position_ = new Vector3(position.GetX(), position.GetY(), position.GetZ()); Vector3Ref center = new Vector3Ref(); overheadcameraK.GetCenter(center); Vector3 center_ = new Vector3(center.GetX(), center.GetY(), center.GetZ()); Matrix4 camera = Matrix4.LookAt(position_, center_, up); m = new float[] { camera.M11, camera.M12, camera.M13, camera.M14, camera.M21, camera.M22, camera.M23, camera.M24, camera.M31, camera.M32, camera.M33, camera.M34, camera.M41, camera.M42, camera.M43, camera.M44 }; GL.LoadMatrix(ref camera); } float[] m; float znear = 0.1f; float zfar { get { return ENABLE_ZFAR ? config3d.GetViewDistance() * 3f / 4 : 99999; } } bool ENABLE_ZFAR = false; public float fov = MathHelper.PiOver3; int oldmousex = 0; int oldmousey = 0; private void glControl1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { oldmousex = e.X; oldmousey = e.Y; down = true; } bool down = false; private void glControl1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) { if (down) { int deltax = e.X - oldmousex; int deltay = e.Y - oldmousey; oldmousex = e.X; oldmousey = e.Y; overheadcameraK.SetT(overheadcameraK.GetT() + (float)deltax * 0.05f); overheadcameraK.SetAngle(overheadcameraK.GetAngle() + (float)deltay * 1f); if (overheadcameraK.GetAngle() > 89) { overheadcameraK.SetAngle(89); } if (overheadcameraK.GetAngle() < -89) { overheadcameraK.SetAngle(-89); } } } private void glControl1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) { down = false; } private void trackBar1_Scroll(object sender, EventArgs e) { UpdateLabels(); } private void trackBar2_Scroll(object sender, EventArgs e) { UpdateLabels(); } private void richTextBox1_TextChanged(object sender, EventArgs e) { LoadModel(); // update animation list int oldAnmimationIndex = listBox1.SelectedIndex; listBox1.Items.Clear(); int animationCount = d.GetAnimationCount(); for (int i = 0; i < animationCount; i++) { listBox1.Items.Add(d.GetAnimationName(i)); } if (oldAnmimationIndex < listBox1.Items.Count) { // if animation still exists switch to the same as before the change listBox1.SelectedIndex = oldAnmimationIndex; } } Game game; void LoadModel() { game = new Game(); game.SetPlatform(new GamePlatformNative()); d = new AnimatedModelRenderer(); AnimatedModel model = new AnimatedModel(); try { model = AnimatedModelSerializer.Deserialize(game.GetPlatform(), richTextBox1.Text); modelLoaded = true; } catch (Exception ex) { modelLoaded = false; model = null; richTextBox2.Text = "Error in LoadModel():" + Environment.NewLine + ex.ToString(); } if (model != null) { d.Start(game, model); } } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { d.SetAnimationId(listBox1.SelectedIndex); } private void loadTextureToolStripMenuItem_Click(object sender, EventArgs e) { DialogResult result = openFileDialog1.ShowDialog(); if (result == DialogResult.OK) { LoadPlayerTexture(File.ReadAllBytes(openFileDialog1.FileName)); } } private void loadModelToolStripMenuItem_Click(object sender, EventArgs e) { DialogResult result = openFileDialog2.ShowDialog(); if (result == DialogResult.OK) { richTextBox1.Text = File.ReadAllText(openFileDialog2.FileName); } } } public static class MyStream { public static byte[] ReadAllBytes(Stream stream) { return new BinaryReader(stream).ReadBytes((int)stream.Length); } } }
25.314286
104
0.674755
[ "Apache-2.0" ]
PowerOlive/manicdigger
MdMonsterEditor/Form1.cs
10,634
C#
namespace JK.Common.FluentValidation.Tests.Validators; public class SocialSecurityNumberValidatorTests : StringValidatorTestsBase { public override StringValidatorBase<MockModel, string> Validator => new SocialSecurityNumberValidator<MockModel, string>(); [Theory] [InlineData("078051120")] [InlineData("078 05 1120")] [InlineData("078-05-1120")] [InlineData("899-05-1120")] // left less than 900 public void IsValid_TrueTheories(string value) { var result = this.MakeAndTestValidator(value); result.ShouldNotHaveValidationErrorFor(x => x.StringValue); } [Theory] [InlineData("000000000")] [InlineData("000 00 0000")] [InlineData("000-00-0000")] [InlineData("111-00-1111")] // middle all 0 [InlineData("111-11-0000")] // right all 0 [InlineData("666-12-4321")] // left 666 [InlineData("900-12-4321")] // left greater than equal 900 public void IsValid_FalseTheories(string value) { var result = this.MakeAndTestValidator(value); result.ShouldHaveValidationErrorFor(x => x.StringValue); } }
34.5625
127
0.688969
[ "MIT" ]
digital-lagniappe/DL.Common
src/JK.Common.FluentValidation.Tests/Validators/SocialSecurityNumberValidatorTests.cs
1,108
C#
using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Text; using Java.Interop; using Android.Runtime; namespace Java.Lang { [DataContract] public partial class Object : IDisposable, IJavaObject, IJavaObjectEx #if JAVA_INTEROP , IJavaPeerable #endif // JAVA_INTEROP { static Dictionary<IntPtr, List<WeakReference>> instances = new Dictionary<IntPtr, List<WeakReference>> (new InstancesKeyComparer ()); IntPtr key_handle; IntPtr weak_handle; JObjectRefType handle_type; IntPtr handle; int refs_added; bool needsActivation; bool isProxy; IntPtr IJavaObjectEx.KeyHandle { get {return key_handle;} set {key_handle = value;} } bool IJavaObjectEx.IsProxy { get {return isProxy;} set {isProxy = value;} } bool IJavaObjectEx.NeedsActivation { get {return needsActivation;} set {needsActivation = true;} } IntPtr IJavaObjectEx.ToLocalJniHandle () { lock (this) { if (handle == IntPtr.Zero) return handle; return JNIEnv.NewLocalRef (handle); } } ~Object () { if (Logger.LogGlobalRef) { JNIEnv._monodroid_gref_log ( string.Format ("Finalizing handle 0x{0}\n", handle.ToString ("x"))); } // FIXME: need hash cleanup mechanism. // Finalization occurs after a test of java persistence. If the // handle still contains a java reference, we can't finalize the // object and should "resurrect" it. refs_added = 0; if (handle != IntPtr.Zero) GC.ReRegisterForFinalize (this); else { Dispose (false); DeregisterInstance (this, key_handle); } } public Object (IntPtr handle, JniHandleOwnership transfer) { // Check if handle was preset by our java activation mechanism if (this.handle != IntPtr.Zero) { needsActivation = true; handle = this.handle; if (handle_type != 0) return; transfer = JniHandleOwnership.DoNotTransfer; } SetHandle (handle, transfer); } // Note: must be internal so that e.g. DataContractJsonSerializer will find it [OnDeserialized] [Preserve] internal void SetHandleOnDeserialized (StreamingContext context) { if (Handle != IntPtr.Zero) return; SetHandle ( JNIEnv.StartCreateInstance (GetType (), "()V"), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, "()V"); } #if JAVA_INTEROP public int JniIdentityHashCode { get {return (int) key_handle;} } public JniObjectReference PeerReference { get { return new JniObjectReference (handle, (JniObjectReferenceType) handle_type); } } public virtual JniPeerMembers JniPeerMembers { get { return _members; } } #endif // JAVA_INTEROP public IntPtr Handle { get { if (weak_handle != IntPtr.Zero) Logger.Log (LogLevel.Warn, "Mono.Android.dll", "Accessing object which is out for collection via original handle"); return handle; } } protected virtual IntPtr ThresholdClass { get { return Class.Object; } } protected virtual System.Type ThresholdType { get { return typeof (Java.Lang.Object); } } internal IntPtr GetThresholdClass () { return ThresholdClass; } internal System.Type GetThresholdType () { return ThresholdType; } #if JAVA_INTEROP JniManagedPeerStates IJavaPeerable.JniManagedPeerState { get { var e = (IJavaObjectEx) this; var s = JniManagedPeerStates.None; if (e.IsProxy) s |= JniManagedPeerStates.Replaceable; if (e.NeedsActivation) s |= JniManagedPeerStates.Activatable; return s; } } void IJavaPeerable.DisposeUnlessReferenced () { var p = PeekObject (handle); if (p == null) { Dispose (); } } public void UnregisterFromRuntime () { DeregisterInstance (this, key_handle); } void IJavaPeerable.Disposed () { throw new NotSupportedException (); } void IJavaPeerable.Finalized () { throw new NotSupportedException (); } void IJavaPeerable.SetJniIdentityHashCode (int value) { key_handle = (IntPtr) value; } void IJavaPeerable.SetJniManagedPeerState (JniManagedPeerStates value) { var e = (IJavaObjectEx) this; if ((value & JniManagedPeerStates.Replaceable) == JniManagedPeerStates.Replaceable) e.IsProxy = true; if ((value & JniManagedPeerStates.Activatable) == JniManagedPeerStates.Activatable) e.NeedsActivation = true; } void IJavaPeerable.SetPeerReference (JniObjectReference reference) { this.handle = reference.Handle; this.handle_type = (JObjectRefType) reference.Type; } #endif // JAVA_INTEROP public void Dispose () { Dispose (true); Dispose (this, ref handle, key_handle, handle_type); GC.SuppressFinalize (this); } protected virtual void Dispose (bool disposing) { } internal static void Dispose (object instance, ref IntPtr handle, IntPtr key_handle, JObjectRefType handle_type) { if (handle == IntPtr.Zero) return; if (Logger.LogGlobalRef) { JNIEnv._monodroid_gref_log ( string.Format ("Disposing handle 0x{0}\n", handle.ToString ("x"))); } DeregisterInstance (instance, key_handle); switch (handle_type) { case JObjectRefType.Global: lock (instance) { JNIEnv.DeleteGlobalRef (handle); handle = IntPtr.Zero; } break; case JObjectRefType.WeakGlobal: lock (instance) { JNIEnv.DeleteWeakGlobalRef (handle); handle = IntPtr.Zero; } break; default: throw new InvalidOperationException ("Trying to dispose handle of type '" + handle_type + "' which is not supported."); } } protected void SetHandle (IntPtr value, JniHandleOwnership transfer) { RegisterInstance (this, value, transfer, out handle); handle_type = JObjectRefType.Global; } internal static void RegisterInstance (IJavaObject instance, IntPtr value, JniHandleOwnership transfer, out IntPtr handle) { if (value == IntPtr.Zero) { handle = value; return; } var transferType = transfer & (JniHandleOwnership.DoNotTransfer | JniHandleOwnership.TransferLocalRef | JniHandleOwnership.TransferGlobalRef); switch (transferType) { case JniHandleOwnership.DoNotTransfer: handle = JNIEnv.NewGlobalRef (value); break; case JniHandleOwnership.TransferLocalRef: handle = JNIEnv.NewGlobalRef (value); JNIEnv.DeleteLocalRef (value); break; case JniHandleOwnership.TransferGlobalRef: handle = value; break; default: throw new ArgumentOutOfRangeException ("transfer", transfer, "Invalid `transfer` value: " + transfer + " on type " + instance.GetType ()); } if (handle == IntPtr.Zero) throw new InvalidOperationException ("Unable to allocate Global Reference for object '" + instance.ToString () + "'!"); IntPtr key = JNIEnv.IdentityHash (handle); if ((transfer & JniHandleOwnership.DoNotRegister) == 0) { _RegisterInstance (instance, key, handle); } var ex = instance as IJavaObjectEx; if (ex != null) ex.KeyHandle = key; if (Logger.LogGlobalRef) { JNIEnv._monodroid_gref_log ("handle 0x" + handle.ToString ("x") + "; key_handle 0x" + key.ToString ("x") + ": Java Type: `" + JNIEnv.GetClassNameFromInstance (handle) + "`; " + "MCW type: `" + instance.GetType ().FullName + "`\n"); } } static void _RegisterInstance (IJavaObject instance, IntPtr key, IntPtr handle) { lock (instances) { List<WeakReference> wrefs; if (!instances.TryGetValue (key, out wrefs)) { wrefs = new List<WeakReference> (1) { new WeakReference (instance, true), }; instances.Add (key, wrefs); } else { bool found = false; for (int i = 0; i < wrefs.Count; ++i) { var wref = wrefs [i]; if (ShouldReplaceMapping (wref, handle)) { found = true; wrefs.Remove (wref); wrefs.Add (new WeakReference (instance, true)); break; } var cur = wref == null ? null : (IJavaObject) wref.Target; var _c = cur == null ? IntPtr.Zero : cur.Handle; if (_c != IntPtr.Zero && JNIEnv.IsSameObject (handle, _c)) { found = true; if (Logger.LogGlobalRef) { Logger.Log (LogLevel.Info, "monodroid-gref", string.Format ("warning: not replacing previous registered handle 0x{0} with handle 0x{1} for key_handle 0x{2}", _c.ToString ("x"), handle.ToString ("x"), key.ToString ("x"))); } break; } } if (!found) { wrefs.Add (new WeakReference (instance, true)); } } } } static bool ShouldReplaceMapping (WeakReference current, IntPtr handle) { if (current == null) return true; // Target has been GC'd; see also FIXME, above, in finalizer object target = current.Target; if (target == null) return true; // It's possible that the instance was GC'd, but the finalizer // hasn't executed yet, so the `instances` entry is stale. var ijo = (IJavaObject) target; if (ijo.Handle == IntPtr.Zero) return true; if (!JNIEnv.IsSameObject (ijo.Handle, handle)) return false; // JNIEnv.NewObject/JNIEnv.CreateInstance() compatibility. // When two MCW's are created for one Java instance [0], // we want the 2nd MCW to replace the 1st, as the 2nd is // the one the dev created; the 1st is an implicit intermediary. // // [0]: If Java ctor invokes overridden virtual method, we'll // transition into managed code w/o a registered instance, and // thus will create an "intermediary" via // (IntPtr, JniHandleOwnership) .ctor. var ex = target as IJavaObjectEx; if (ex != null && ex.IsProxy) return true; return false; } internal static void DeregisterInstance (object instance, IntPtr key_handle) { lock (instances) { List<WeakReference> wrefs; if (instances.TryGetValue (key_handle, out wrefs)) { for (int i = wrefs.Count-1; i >= 0; --i) { var wref = wrefs [i]; if (wref.Target == null || wref.Target == instance) { wrefs.RemoveAt (i); } } if (wrefs.Count == 0) instances.Remove (key_handle); } } } internal static List<WeakReference> GetSurfacedObjects_ForDiagnosticsOnly () { lock (instances) { var surfaced = new List<WeakReference> (instances.Count); foreach (var e in instances) { surfaced.AddRange (e.Value); } return surfaced; } } internal static IJavaObject PeekObject (IntPtr handle, Type requiredType = null) { if (handle == IntPtr.Zero) return null; lock (instances) { List<WeakReference> wrefs; if (instances.TryGetValue (JNIEnv.IdentityHash (handle), out wrefs)) { for (int i = 0; i < wrefs.Count; ++i) { var wref = wrefs [i]; IJavaObject res = wref.Target as IJavaObject; if (res != null && res.Handle != IntPtr.Zero && JNIEnv.IsSameObject (handle, res.Handle)) { if (requiredType != null && !requiredType.IsAssignableFrom (res.GetType ())) return null; return res; } } } } return null; } internal static T PeekObject <T> (IntPtr handle) { return (T)PeekObject (handle, typeof (T)); } public static T GetObject<T> (IntPtr jnienv, IntPtr handle, JniHandleOwnership transfer) where T : class, IJavaObject { JNIEnv.CheckHandle (jnienv); return GetObject<T> (handle, transfer); } public static T GetObject<T> (IntPtr handle, JniHandleOwnership transfer) where T : class, IJavaObject { return _GetObject<T>(handle, transfer); } internal static T _GetObject<T> (IntPtr handle, JniHandleOwnership transfer) { if (handle == IntPtr.Zero) return default (T); return (T) GetObject (handle, transfer, typeof (T)); } internal static IJavaObject GetObject (IntPtr handle, JniHandleOwnership transfer, Type type = null) { if (handle == IntPtr.Zero) return null; lock (instances) { List<WeakReference> wrefs; if (instances.TryGetValue (JNIEnv.IdentityHash (handle), out wrefs)) { for (int i = 0; i < wrefs.Count; ++i) { var wref = wrefs [i]; var result = wref.Target as IJavaObject; var exists = result != null && result.Handle != IntPtr.Zero && JNIEnv.IsSameObject (handle, result.Handle); if (exists) { if (type == null ? true : type.IsAssignableFrom (result.GetType ())) { JNIEnv.DeleteRef (handle, transfer); return result; } /* Logger.Log (LogLevel.Warn, "*jonp*", "# jonp: Object.GetObject: handle=0x" + handle.ToString ("x") + " found but is of type '" + result.GetType ().FullName + "' and not the required targetType of '" + type + "'."); */ } } } } return Java.Interop.TypeManager.CreateInstance (handle, transfer, type); } public T[] ToArray<T>() { return JNIEnv.GetArray<T>(Handle); } public static Java.Lang.Object FromArray<T>(T[] value) { if (value == null) return null; return new Java.Lang.Object (JNIEnv.NewArray (value), JniHandleOwnership.TransferLocalRef); } public static implicit operator Java.Lang.Object (bool value) { return new Java.Lang.Boolean (value); } [Obsolete ("Use `(Java.Lang.Byte)(sbyte) value`", error: true)] public static implicit operator Java.Lang.Object (byte value) { throw new InvalidOperationException ("Should not be reached"); } public static implicit operator Java.Lang.Object (sbyte value) { return new Java.Lang.Byte (value); } public static implicit operator Java.Lang.Object (char value) { return new Java.Lang.Character (value); } [Obsolete ("Use `(Java.Lang.Integer)(int) value`", error: true)] public static implicit operator Java.Lang.Object (uint value) { throw new InvalidOperationException ("Should not be reached"); } public static implicit operator Java.Lang.Object (int value) { return new Java.Lang.Integer (value); } [Obsolete ("Use `(Java.Lang.Long)(long) value`", error: true)] public static implicit operator Java.Lang.Object (ulong value) { throw new InvalidOperationException ("Should not be reached"); } public static implicit operator Java.Lang.Object (long value) { return new Java.Lang.Long (value); } public static implicit operator Java.Lang.Object (float value) { return new Java.Lang.Float (value); } public static implicit operator Java.Lang.Object (double value) { return new Java.Lang.Double (value); } public static implicit operator Java.Lang.Object (string value) { if (value == null) return null; return new Java.Lang.ICharSequenceInvoker (JNIEnv.NewString (value), JniHandleOwnership.TransferLocalRef); } public static explicit operator bool (Java.Lang.Object value) { return Convert.ToBoolean (value); } [Obsolete ("Use `(byte)(sbyte) value`", error: true)] public static explicit operator byte (Java.Lang.Object value) { throw new InvalidOperationException ("Should not be reached"); } public static explicit operator sbyte (Java.Lang.Object value) { return Convert.ToSByte (value); } public static explicit operator char (Java.Lang.Object value) { return Convert.ToChar (value); } [Obsolete ("Use `(uint)(int) value`", error: true)] public static explicit operator uint (Java.Lang.Object value) { throw new InvalidOperationException ("Should not be reached"); } public static explicit operator int (Java.Lang.Object value) { return Convert.ToInt32 (value); } [Obsolete ("Use `(ulong)(long) value`", error: true)] public static explicit operator ulong (Java.Lang.Object value) { throw new InvalidOperationException ("Should not be reached"); } public static explicit operator long (Java.Lang.Object value) { return Convert.ToInt64 (value); } public static explicit operator float (Java.Lang.Object value) { return Convert.ToSingle (value); } public static explicit operator double (Java.Lang.Object value) { return Convert.ToDouble (value); } public static explicit operator string (Java.Lang.Object value) { if (value == null) return null; return Convert.ToString (value); } public static implicit operator Java.Lang.Object (Java.Lang.Object[] value) { if (value == null) return null; return new Java.Lang.Object (JNIEnv.NewArray (value), JniHandleOwnership.TransferLocalRef); } public static implicit operator Java.Lang.Object (bool[] value) { if (value == null) return null; return new Java.Lang.Object (JNIEnv.NewArray (value), JniHandleOwnership.TransferLocalRef); } public static implicit operator Java.Lang.Object (byte[] value) { if (value == null) return null; return new Java.Lang.Object (JNIEnv.NewArray (value), JniHandleOwnership.TransferLocalRef); } public static implicit operator Java.Lang.Object (char[] value) { if (value == null) return null; return new Java.Lang.Object (JNIEnv.NewArray (value), JniHandleOwnership.TransferLocalRef); } public static implicit operator Java.Lang.Object (int[] value) { if (value == null) return null; return new Java.Lang.Object (JNIEnv.NewArray (value), JniHandleOwnership.TransferLocalRef); } public static implicit operator Java.Lang.Object (long[] value) { if (value == null) return null; return new Java.Lang.Object (JNIEnv.NewArray (value), JniHandleOwnership.TransferLocalRef); } public static implicit operator Java.Lang.Object (float[] value) { if (value == null) return null; return new Java.Lang.Object (JNIEnv.NewArray (value), JniHandleOwnership.TransferLocalRef); } public static implicit operator Java.Lang.Object (double[] value) { if (value == null) return null; return new Java.Lang.Object (JNIEnv.NewArray (value), JniHandleOwnership.TransferLocalRef); } public static implicit operator Java.Lang.Object (string[] value) { if (value == null) return null; return new Java.Lang.Object (JNIEnv.NewArray (value), JniHandleOwnership.TransferLocalRef); } public static explicit operator Java.Lang.Object[] (Java.Lang.Object value) { if (value == null) return null; return value.ToArray<Java.Lang.Object>(); } public static explicit operator bool[] (Java.Lang.Object value) { if (value == null) return null; return value.ToArray<bool>(); } public static explicit operator byte[] (Java.Lang.Object value) { if (value == null) return null; return value.ToArray<byte>(); } public static explicit operator char[] (Java.Lang.Object value) { if (value == null) return null; return value.ToArray<char>(); } public static explicit operator int[] (Java.Lang.Object value) { if (value == null) return null; return value.ToArray<int>(); } public static explicit operator long[] (Java.Lang.Object value) { if (value == null) return null; return value.ToArray<long>(); } public static explicit operator float[] (Java.Lang.Object value) { if (value == null) return null; return value.ToArray<float>(); } public static explicit operator double[] (Java.Lang.Object value) { if (value == null) return null; return value.ToArray<double>(); } public static explicit operator string[] (Java.Lang.Object value) { if (value == null) return null; return value.ToArray<string>(); } } class InstancesKeyComparer : IEqualityComparer<IntPtr> { public bool Equals (IntPtr x, IntPtr y) { return x == y; } public int GetHashCode (IntPtr value) { return value.GetHashCode (); } } }
26.575472
164
0.668289
[ "MIT" ]
06051979/xamarin-android
src/Mono.Android/Java.Lang/Object.cs
19,719
C#
namespace BSONSample.Areas.HelpPage.ModelDescriptions { public class DictionaryModelDescription : KeyValuePairModelDescription { } }
24
74
0.791667
[ "Apache-2.0" ]
ASCITSOL/asp.net
samples/aspnet/WebApi/BSONSample/BSONSample/Areas/HelpPage/ModelDescriptions/DictionaryModelDescription.cs
144
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.Storage { /// <summary> /// Properties of the file share, including Id, resource name, resource type, Etag. /// API Version: 2021-02-01. /// </summary> [AzureNativeResourceType("azure-native:storage:FileShare")] public partial class FileShare : Pulumi.CustomResource { /// <summary> /// Access tier for specific share. GpV2 account can choose between TransactionOptimized (default), Hot, and Cool. FileStorage account can choose Premium. /// </summary> [Output("accessTier")] public Output<string?> AccessTier { get; private set; } = null!; /// <summary> /// Indicates the last modification time for share access tier. /// </summary> [Output("accessTierChangeTime")] public Output<string> AccessTierChangeTime { get; private set; } = null!; /// <summary> /// Indicates if there is a pending transition for access tier. /// </summary> [Output("accessTierStatus")] public Output<string> AccessTierStatus { get; private set; } = null!; /// <summary> /// Indicates whether the share was deleted. /// </summary> [Output("deleted")] public Output<bool> Deleted { get; private set; } = null!; /// <summary> /// The deleted time if the share was deleted. /// </summary> [Output("deletedTime")] public Output<string> DeletedTime { get; private set; } = null!; /// <summary> /// The authentication protocol that is used for the file share. Can only be specified when creating a share. /// </summary> [Output("enabledProtocols")] public Output<string?> EnabledProtocols { get; private set; } = null!; /// <summary> /// Resource Etag. /// </summary> [Output("etag")] public Output<string> Etag { get; private set; } = null!; /// <summary> /// Returns the date and time the share was last modified. /// </summary> [Output("lastModifiedTime")] public Output<string> LastModifiedTime { get; private set; } = null!; /// <summary> /// A name-value pair to associate with the share as metadata. /// </summary> [Output("metadata")] public Output<ImmutableDictionary<string, string>?> Metadata { get; private set; } = null!; /// <summary> /// The name of the resource /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// Remaining retention days for share that was soft deleted. /// </summary> [Output("remainingRetentionDays")] public Output<int> RemainingRetentionDays { get; private set; } = null!; /// <summary> /// The property is for NFS share only. The default is NoRootSquash. /// </summary> [Output("rootSquash")] public Output<string?> RootSquash { get; private set; } = null!; /// <summary> /// The maximum size of the share, in gigabytes. Must be greater than 0, and less than or equal to 5TB (5120). For Large File Shares, the maximum size is 102400. /// </summary> [Output("shareQuota")] public Output<int?> ShareQuota { get; private set; } = null!; /// <summary> /// The approximate size of the data stored on the share. Note that this value may not include all recently created or recently resized files. /// </summary> [Output("shareUsageBytes")] public Output<double> ShareUsageBytes { get; private set; } = null!; /// <summary> /// Creation time of share snapshot returned in the response of list shares with expand param "snapshots". /// </summary> [Output("snapshotTime")] public Output<string> SnapshotTime { get; private set; } = null!; /// <summary> /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// The version of the share. /// </summary> [Output("version")] public Output<string> Version { get; private set; } = null!; /// <summary> /// Create a FileShare resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public FileShare(string name, FileShareArgs args, CustomResourceOptions? options = null) : base("azure-native:storage:FileShare", name, args ?? new FileShareArgs(), MakeResourceOptions(options, "")) { } private FileShare(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:storage:FileShare", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:storage:FileShare"}, new Pulumi.Alias { Type = "azure-native:storage/v20190401:FileShare"}, new Pulumi.Alias { Type = "azure-nextgen:storage/v20190401:FileShare"}, new Pulumi.Alias { Type = "azure-native:storage/v20190601:FileShare"}, new Pulumi.Alias { Type = "azure-nextgen:storage/v20190601:FileShare"}, new Pulumi.Alias { Type = "azure-native:storage/v20200801preview:FileShare"}, new Pulumi.Alias { Type = "azure-nextgen:storage/v20200801preview:FileShare"}, new Pulumi.Alias { Type = "azure-native:storage/v20210101:FileShare"}, new Pulumi.Alias { Type = "azure-nextgen:storage/v20210101:FileShare"}, new Pulumi.Alias { Type = "azure-native:storage/v20210201:FileShare"}, new Pulumi.Alias { Type = "azure-nextgen:storage/v20210201:FileShare"}, new Pulumi.Alias { Type = "azure-native:storage/v20210401:FileShare"}, new Pulumi.Alias { Type = "azure-nextgen:storage/v20210401:FileShare"}, new Pulumi.Alias { Type = "azure-native:storage/v20210601:FileShare"}, new Pulumi.Alias { Type = "azure-nextgen:storage/v20210601:FileShare"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing FileShare resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static FileShare Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new FileShare(name, id, options); } } public sealed class FileShareArgs : Pulumi.ResourceArgs { /// <summary> /// Access tier for specific share. GpV2 account can choose between TransactionOptimized (default), Hot, and Cool. FileStorage account can choose Premium. /// </summary> [Input("accessTier")] public InputUnion<string, Pulumi.AzureNative.Storage.ShareAccessTier>? AccessTier { get; set; } /// <summary> /// The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. /// </summary> [Input("accountName", required: true)] public Input<string> AccountName { get; set; } = null!; /// <summary> /// The authentication protocol that is used for the file share. Can only be specified when creating a share. /// </summary> [Input("enabledProtocols")] public InputUnion<string, Pulumi.AzureNative.Storage.EnabledProtocols>? EnabledProtocols { get; set; } /// <summary> /// Optional, used to create a snapshot. /// </summary> [Input("expand")] public Input<string>? Expand { get; set; } [Input("metadata")] private InputMap<string>? _metadata; /// <summary> /// A name-value pair to associate with the share as metadata. /// </summary> public InputMap<string> Metadata { get => _metadata ?? (_metadata = new InputMap<string>()); set => _metadata = value; } /// <summary> /// The name of the resource group within the user's subscription. The name is case insensitive. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// The property is for NFS share only. The default is NoRootSquash. /// </summary> [Input("rootSquash")] public InputUnion<string, Pulumi.AzureNative.Storage.RootSquashType>? RootSquash { get; set; } /// <summary> /// The name of the file share within the specified storage account. File share names must be between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-) character must be immediately preceded and followed by a letter or number. /// </summary> [Input("shareName")] public Input<string>? ShareName { get; set; } /// <summary> /// The maximum size of the share, in gigabytes. Must be greater than 0, and less than or equal to 5TB (5120). For Large File Shares, the maximum size is 102400. /// </summary> [Input("shareQuota")] public Input<int>? ShareQuota { get; set; } public FileShareArgs() { } } }
44.522088
284
0.602291
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Storage/FileShare.cs
11,086
C#
namespace AjTalk.Tests.Compilers.Javascript { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using AjTalk.Compilers; using AjTalk.Compilers.Javascript; using AjTalk.Model; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class NodeCompilerTests { private NodeCompiler compiler; private StringWriter writer; [TestInitialize] public void Setup() { this.writer = new StringWriter(); this.compiler = new NodeCompiler(new SourceWriter(this.writer)); } [TestMethod] [DeploymentItem(@"CodeFiles\SqueakObject.st")] public void CompileSqueakObjectForNodeJs() { ChunkReader chunkReader = new ChunkReader(@"SqueakObject.st"); CodeReader reader = new CodeReader(chunkReader); CodeModel model = new CodeModel(); reader.Process(model); this.compiler.Visit(model); this.writer.Close(); string output = this.writer.ToString(); // TODO more tests Assert.IsTrue(ContainsLine(output, "var base = require('./js/ajtalk-base.js');")); Assert.IsTrue(ContainsLine(output, "var send = base.send;")); Assert.IsTrue(ContainsLine(output, "var sendSuper = base.sendSuper;")); Assert.IsTrue(ContainsLine(output, "var primitives = require('./js/ajtalk-primitives.js');")); Assert.IsTrue(ContainsLine(output, "function Object()")); Assert.IsTrue(ContainsLine(output, "exports.Object = Object;")); } [TestMethod] [DeploymentItem(@"CodeFiles\PharoCoreKernelObjects.st")] [DeploymentItem(@"CodeFiles\PharoCorePoint.st")] public void CompilePharoCorePointForNodeJs() { ChunkReader chunkCoreReader = new ChunkReader(@"PharoCoreKernelObjects.st"); CodeReader coreReader = new CodeReader(chunkCoreReader); ChunkReader chunkReader = new ChunkReader(@"PharoCorePoint.st"); CodeReader reader = new CodeReader(chunkReader); CodeModel model = new CodeModel(); coreReader.Process(model); reader.Process(model); this.compiler.Visit(model); this.writer.Close(); string output = this.writer.ToString(); Assert.IsTrue(ContainsLine(output, "var base = require('./js/ajtalk-base.js');")); Assert.IsTrue(ContainsLine(output, "var send = base.send;")); Assert.IsTrue(ContainsLine(output, "var sendSuper = base.sendSuper;")); Assert.IsTrue(ContainsLine(output, "var primitives = require('./js/ajtalk-primitives.js');")); Assert.IsTrue(ContainsLine(output, "function Point()")); Assert.IsTrue(ContainsLine(output, "PointClass.__super = ObjectClass;")); Assert.IsTrue(ContainsLine(output, "Point.__super = Object;")); Assert.IsTrue(ContainsLine(output, "PointClass.prototype.__proto__ = ObjectClass.prototype;")); Assert.IsTrue(ContainsLine(output, "Point.prototype.__proto__ = Object.prototype;")); Assert.IsTrue(ContainsLine(output, "exports.Point = Point;")); Assert.IsTrue(ContainsLine(output, "Point.prototype.$x = null;")); Assert.IsTrue(ContainsLine(output, "Point.prototype.$y = null;")); } [TestMethod] [DeploymentItem(@"CodeFiles\SqueakKernelObjects.st")] public void CompileSqueakKernelObjectsForNodeJs() { ChunkReader chunkReader = new ChunkReader(@"SqueakKernelObjects.st"); CodeReader reader = new CodeReader(chunkReader); CodeModel model = new CodeModel(); reader.Process(model); this.compiler.Visit(model); this.writer.Close(); string output = this.writer.ToString(); // TODO more tests Assert.IsTrue(ContainsLine(output, "function Object()")); Assert.IsTrue(ContainsLine(output, "function Boolean()")); Assert.IsTrue(ContainsLine(output, "exports.Object = Object;")); Assert.IsTrue(ContainsLine(output, "exports.Boolean = Boolean;")); // Class variables in Object Assert.IsTrue(ContainsLine(output, "ObjectClass.$DependentsFields = null;")); } [TestMethod] [DeploymentItem(@"CodeFiles\PharoCoreKernelObjects.st")] public void CompilePharoCoreKernelObjectsForNodeJs() { ChunkReader chunkReader = new ChunkReader(@"PharoCoreKernelObjects.st"); CodeReader reader = new CodeReader(chunkReader); CodeModel model = new CodeModel(); reader.Process(model); this.compiler.Visit(model); this.writer.Close(); string output = this.writer.ToString(); // TODO more tests Assert.IsTrue(ContainsLine(output, "function Object()")); Assert.IsTrue(ContainsLine(output, "ObjectClass.__super = ProtoObjectClass;")); Assert.IsTrue(ContainsLine(output, "Object.__super = ProtoObject;")); Assert.IsTrue(ContainsLine(output, "ObjectClass.prototype.__proto__ = ProtoObjectClass.prototype;")); Assert.IsTrue(ContainsLine(output, "Object.prototype.__proto__ = ProtoObject.prototype;")); Assert.IsTrue(ContainsLine(output, "BooleanClass.prototype.__proto__ = ObjectClass.prototype;")); Assert.IsTrue(ContainsLine(output, "Boolean.prototype.__proto__ = Object.prototype;")); Assert.IsTrue(ContainsLine(output, "function Boolean()")); Assert.IsTrue(ContainsLine(output, "exports.Object = Object;")); Assert.IsTrue(ContainsLine(output, "exports.Boolean = Boolean;")); Assert.IsTrue(ContainsLine(output, "exports.ProtoObject = ProtoObject;")); } private static IExpression ParseExpression(string text) { ModelParser parser = new ModelParser(text); return parser.ParseExpression(); } private static bool ContainsLine(string text, string line) { StringReader reader = new StringReader(text); string ln; while ((ln = reader.ReadLine()) != null) if (line == ln.Trim()) return true; return false; } } }
42.711538
114
0.607534
[ "MIT" ]
ajlopez/AjTalk
Src/AjTalk.Tests/Compilers/Javascript/NodeCompilerTests.cs
6,665
C#
using Microsoft.Management.Infrastructure; using System; using System.Collections.Generic; using System.Linq; using SimCim.Core; namespace SimCim.Root.V2 { public class Win32PerfFormattedDataCountersIPsecIKEv1IPv6 : Win32PerfFormattedData { public Win32PerfFormattedDataCountersIPsecIKEv1IPv6() { } public Win32PerfFormattedDataCountersIPsecIKEv1IPv6(IInfrastructureObjectScope scope, CimInstance instance): base(scope, instance) { } public System.UInt32? ActiveMainModeSAs { get { System.UInt32? result; this.GetProperty("ActiveMainModeSAs", out result); return result; } set { this.SetProperty("ActiveMainModeSAs", value); } } public System.UInt32? ActiveQuickModeSAs { get { System.UInt32? result; this.GetProperty("ActiveQuickModeSAs", out result); return result; } set { this.SetProperty("ActiveQuickModeSAs", value); } } public System.UInt32? FailedMainModeNegotiations { get { System.UInt32? result; this.GetProperty("FailedMainModeNegotiations", out result); return result; } set { this.SetProperty("FailedMainModeNegotiations", value); } } public System.UInt32? FailedMainModeNegotiationsPersec { get { System.UInt32? result; this.GetProperty("FailedMainModeNegotiationsPersec", out result); return result; } set { this.SetProperty("FailedMainModeNegotiationsPersec", value); } } public System.UInt32? FailedQuickModeNegotiations { get { System.UInt32? result; this.GetProperty("FailedQuickModeNegotiations", out result); return result; } set { this.SetProperty("FailedQuickModeNegotiations", value); } } public System.UInt32? FailedQuickModeNegotiationsPersec { get { System.UInt32? result; this.GetProperty("FailedQuickModeNegotiationsPersec", out result); return result; } set { this.SetProperty("FailedQuickModeNegotiationsPersec", value); } } public System.UInt32? MainModeNegotiationRequestsReceived { get { System.UInt32? result; this.GetProperty("MainModeNegotiationRequestsReceived", out result); return result; } set { this.SetProperty("MainModeNegotiationRequestsReceived", value); } } public System.UInt32? MainModeNegotiationRequestsReceivedPersec { get { System.UInt32? result; this.GetProperty("MainModeNegotiationRequestsReceivedPersec", out result); return result; } set { this.SetProperty("MainModeNegotiationRequestsReceivedPersec", value); } } public System.UInt32? MainModeNegotiations { get { System.UInt32? result; this.GetProperty("MainModeNegotiations", out result); return result; } set { this.SetProperty("MainModeNegotiations", value); } } public System.UInt32? MainModeNegotiationsPersec { get { System.UInt32? result; this.GetProperty("MainModeNegotiationsPersec", out result); return result; } set { this.SetProperty("MainModeNegotiationsPersec", value); } } public System.UInt32? PendingMainModeNegotiations { get { System.UInt32? result; this.GetProperty("PendingMainModeNegotiations", out result); return result; } set { this.SetProperty("PendingMainModeNegotiations", value); } } public System.UInt32? PendingQuickModeNegotiations { get { System.UInt32? result; this.GetProperty("PendingQuickModeNegotiations", out result); return result; } set { this.SetProperty("PendingQuickModeNegotiations", value); } } public System.UInt32? QuickModeNegotiations { get { System.UInt32? result; this.GetProperty("QuickModeNegotiations", out result); return result; } set { this.SetProperty("QuickModeNegotiations", value); } } public System.UInt32? QuickModeNegotiationsPersec { get { System.UInt32? result; this.GetProperty("QuickModeNegotiationsPersec", out result); return result; } set { this.SetProperty("QuickModeNegotiationsPersec", value); } } public System.UInt32? SuccessfulMainModeNegotiations { get { System.UInt32? result; this.GetProperty("SuccessfulMainModeNegotiations", out result); return result; } set { this.SetProperty("SuccessfulMainModeNegotiations", value); } } public System.UInt32? SuccessfulMainModeNegotiationsPersec { get { System.UInt32? result; this.GetProperty("SuccessfulMainModeNegotiationsPersec", out result); return result; } set { this.SetProperty("SuccessfulMainModeNegotiationsPersec", value); } } public System.UInt32? SuccessfulQuickModeNegotiations { get { System.UInt32? result; this.GetProperty("SuccessfulQuickModeNegotiations", out result); return result; } set { this.SetProperty("SuccessfulQuickModeNegotiations", value); } } public System.UInt32? SuccessfulQuickModeNegotiationsPersec { get { System.UInt32? result; this.GetProperty("SuccessfulQuickModeNegotiationsPersec", out result); return result; } set { this.SetProperty("SuccessfulQuickModeNegotiationsPersec", value); } } } }
27.100346
139
0.468973
[ "Apache-2.0" ]
simonferquel/simcim
SimCim.Root.V2/ClassWin32PerfFormattedDataCountersIPsecIKEv1IPv6.cs
7,834
C#
namespace Firefly.CloudFormationParser { using System; using System.Collections.Generic; using Firefly.CloudFormationParser.TemplateObjects; /// <summary> /// Interface describing a CloudFormation Resource. /// </summary> public interface IResource : ITemplateObject { /// <summary> /// <para> /// Gets or sets the resource's condition. /// </para> /// <para> /// When present, associates this output with a condition defined in the <c>Conditions</c> section of the template. /// </para> /// </summary> /// <value> /// The CloudFormation condition which will be <c>null</c> if the template did not provide this property. /// </value> string? Condition { get; set; } /// <summary> /// Gets or sets the creation policy. /// </summary> /// <value> /// The creation policy. /// </value> Dictionary<string, object>? CreationPolicy { get; set; } /// <summary> /// Gets or sets the deletion policy. /// </summary> /// <value> /// The deletion policy. /// </value> string? DeletionPolicy { get; set; } /// <summary> /// <para> /// Gets or sets explicit dependencies on other resources in the template. /// </para> /// <para> /// You should use the convenience property <see cref="ExplicitDependencies"/> to get the list of dependencies. /// </para> /// </summary> /// <value> /// The dependencies which will be <c>null</c> if the template did not provide this property. /// </value> object? DependsOn { get; set; } /// <summary> /// <para> /// Gets or sets the resource's description. /// </para> /// <para> /// A string type that describes the output value. The value for the description declaration must be a literal string that's between 0 and 1024 bytes in length. /// </para> /// </summary> /// <value> /// The resource's description which will be <c>null</c> if the template did not provide this property. /// </value> object? Description { get; set; } /// <summary> /// Gets the explicit dependencies on other resources in the template. /// </summary> /// <value> /// A list of explicit dependencies. /// </value> IEnumerable<string> ExplicitDependencies { get; } /// <summary> /// Gets a value indicating whether this resource is a SAM declaration.. /// </summary> /// <value> /// <c>true</c> if this instance is sam resource; otherwise, <c>false</c>. /// </value> // ReSharper disable once UnusedMember.Global // ReSharper disable once InconsistentNaming bool IsSAMResource { get; } /// <summary> /// <para> /// Gets or sets the metadata. /// </para> /// <para> /// You can use the optional Metadata section to include arbitrary JSON or YAML objects that provide details about the resource. /// Often used with instances or launch templates to provide data for <c>cfn-init</c>. /// </para> /// </summary> /// <value> /// The metadata. /// </value> Dictionary<string, object>? Metadata { get; set; } /// <summary> /// <para> /// Gets or sets the resource properties. /// </para> /// <para> /// Resource properties are additional options that you can specify for a resource. /// For example, for each EC2 instance, you must specify an Amazon Machine Image (AMI) ID for that instance. /// </para> /// </summary> /// <value> /// The properties. /// </value> Dictionary<string, object>? Properties { get; set; } /// <summary> /// <para> /// Gets or sets the resource type. /// </para> /// The resource type identifies the type of resource that you are declaring. For example, AWS::EC2::Instance declares an EC2 instance. /// <para> /// </para> /// </summary> /// <value> /// The type. /// </value> string? Type { get; set; } /// <summary> /// Gets or sets the update policy. /// </summary> /// <value> /// The update policy. /// </value> Dictionary<string, object>? UpdatePolicy { get; set; } /// <summary> /// Gets or sets the update replace policy. /// </summary> /// <value> /// The update replace policy. /// </value> string? UpdateReplacePolicy { get; set; } /// <summary> /// Gets or sets the resource version. /// </summary> /// <value> /// The version. /// </value> /// <remarks> /// This property is valid for custom resources. /// </remarks> string? Version { get; set; } /// <summary> /// Gets a resource property value. See <see href="https://fireflycons.github.io/Firefly.CloudFormationParser/documentation/resource-props.html">Property Manipulation</see> in the documentation. /// </summary> /// <param name="propertyPath">The property path.</param> /// <returns>The value of the property; else <c>null</c> if the property path was not found.</returns> object? GetResourcePropertyValue(string propertyPath); /// <summary> /// <para> /// Updates a property of this resource. See <see href="https://fireflycons.github.io/Firefly.CloudFormationParser/documentation/resource-props.html">Property Manipulation</see> in the documentation. /// </para> /// <para> /// You would want to do this if you were implementing the functionality of <c>aws cloudformation package</c> /// to rewrite local file paths to S3 object locations. /// </para> /// </summary> /// <param name="propertyPath">Path to the property you want to set within this resource's <c>Properties</c> section, /// e.g. for a <c>AWS::Glue::Job</c> the path would be <c>Command.ScriptLocation</c>. /// </param> /// <param name="newValue">The new value.</param> /// <exception cref="FormatException">Resource format is unknown (not JSON or YAML)</exception> void UpdateResourceProperty(string propertyPath, object newValue); } }
37.519774
207
0.554886
[ "MIT" ]
fireflycons/Firefly.CloudFormationParser
src/Firefly.CloudFormationParser/IResource.cs
6,643
C#
// *** WARNING: this file was generated by pulumigen. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Kubernetes.Types.Outputs.FlowControl.V1Beta2 { /// <summary> /// LimitedPriorityLevelConfiguration specifies how to handle requests that are subject to limits. It addresses two issues: /// * How are requests for this priority level limited? /// * What should be done with requests that exceed the limit? /// </summary> [OutputType] public sealed class LimitedPriorityLevelConfiguration { /// <summary> /// `assuredConcurrencyShares` (ACS) configures the execution limit, which is a limit on the number of requests of this priority level that may be exeucting at a given time. ACS must be a positive number. The server's concurrency limit (SCL) is divided among the concurrency-controlled priority levels in proportion to their assured concurrency shares. This produces the assured concurrency value (ACV) --- the number of requests that may be executing at a time --- for each such priority level: /// /// ACV(l) = ceil( SCL * ACS(l) / ( sum[priority levels k] ACS(k) ) ) /// /// bigger numbers of ACS mean more reserved concurrent requests (at the expense of every other PL). This field has a default value of 30. /// </summary> public readonly int AssuredConcurrencyShares; /// <summary> /// `limitResponse` indicates what to do with requests that can not be executed right now /// </summary> public readonly Pulumi.Kubernetes.Types.Outputs.FlowControl.V1Beta2.LimitResponse LimitResponse; [OutputConstructor] private LimitedPriorityLevelConfiguration( int assuredConcurrencyShares, Pulumi.Kubernetes.Types.Outputs.FlowControl.V1Beta2.LimitResponse limitResponse) { AssuredConcurrencyShares = assuredConcurrencyShares; LimitResponse = limitResponse; } } }
48.688889
504
0.696029
[ "Apache-2.0" ]
Threpio/pulumi-kubernetes
sdk/dotnet/FlowControl/V1Beta2/Outputs/LimitedPriorityLevelConfiguration.cs
2,191
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Blog.Application")] [assembly: AssemblyTrademark("")] // 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("3870c648-4aea-4b85-ba3f-f2f63b96136a")]
41.421053
84
0.777637
[ "MIT" ]
LMapundu/Boilerplate-Example
aspnet-core/src/Blog.Application/Properties/AssemblyInfo.cs
789
C#
using System.Threading.Tasks; using Microsoft.CodeAnalysis; namespace HoneydewExtractors.CSharp.RepositoryLoading.SolutionRead { public interface ISolutionProvider { Task<Solution> GetSolution(string path); } }
21.181818
66
0.763948
[ "Apache-2.0" ]
dxworks/honeydew
HoneydewExtractors/CSharp/RepositoryLoading/SolutionRead/ISolutionProvider.cs
235
C#
using UnityEngine; public class PlayerProjectile : MonoBehaviour { [SerializeField] GameObject _hitEffect = null; [SerializeField] AudioClip _hitSound = null; [SerializeField] [Range(1f, 10f)] float _duration = 5f; [SerializeField] int _damage = 1; float _lifeTime; private void OnEnable() { _lifeTime = _duration; } // Update is called once per frame void Update() { _lifeTime -= Time.deltaTime; if (_lifeTime <= 0f) Destroy(gameObject); } private void OnTriggerEnter2D(Collider2D collision) { SoundManager.Instance.PlaySoundEffect(_hitSound); Instantiate(_hitEffect, transform.position, Quaternion.identity); collision.gameObject.GetComponent<IDamageable>()?.TakeDamage(_damage); Destroy(gameObject); } }
25.875
78
0.671498
[ "CC0-1.0" ]
gbradburn/Starcastle
Assets/_project/Scripts/PlayerProjectile.cs
828
C#
//Author Maxim Kuzmin//makc// using System; namespace Vlad2020.Host.Base.Parts.Ldap.Jobs.Login { /// <summary> /// Хост. Основа. Часть "LDAP". Задания. Вход в систему. Исключение. /// </summary> public class HostBasePartLdapJobLoginException : Exception { } }
20.5
72
0.662021
[ "MIT" ]
balkar20/Vlad
net-core/Vlad2020.Host.Base/Parts/Ldap/Jobs/Login/HostBasePartLdapJobLoginException.cs
333
C#
namespace DemoAcmeAp.Application.AppServices { using DemoAcmeAp.Application.Interfaces.Base; using DemoAcmeAp.Domain.Entities; using DemoAcmeAp.Domain.Interfaces.Services; using DemoAcmeAp.Domain.Interfaces.UoW; using global::AutoMapper; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; internal abstract class AppServiceBase<TModel, TViewModel> : IAppServiceBase<TViewModel> where TModel : EntityBase where TViewModel : class { private readonly IServiceBase<TModel> service; protected readonly IUnitOfWork uow; protected readonly IMapper mapper; protected AppServiceBase(IServiceBase<TModel> service, IUnitOfWork uow, IMapper mapper) { this.service = service; this.uow = uow; this.mapper = mapper; } public async Task<TViewModel> Add(TViewModel viewModel) { var entity = mapper.Map<TModel>(viewModel); BeginTransaction(); var result = await service.Add(entity); Commit(); return mapper.Map<TViewModel>(result); } public async Task<TViewModel> Update(long id, TViewModel viewModel) { var entity = mapper.Map<TModel>(viewModel); BeginTransaction(); var result = await service.Update(id, entity); Commit(); return mapper.Map<TViewModel>(result); } public async Task Delete(long id) { BeginTransaction(); await service.Delete(id); Commit(); } public async Task<TViewModel> Get(long id) { var result = await service.Get(id); return mapper.Map<TViewModel>(result); } public async Task<IEnumerable<TViewModel>> List() { var result = await service.List(); return result .Select(r => mapper.Map<TViewModel>(r)) .ToList(); } protected void BeginTransaction() { //uow.BeginTransaction(); } protected void Commit() { uow.Commit(); } protected void RollBack() { uow.Rollback(); } } }
27.223529
143
0.573898
[ "MIT" ]
EngBrunoAlves/ArquiteturaSoftware
DemoAcmeAp/src/DemoAcmeAp.Application/AppServices/Base/AppServiceBase.cs
2,316
C#
// Copyright © 2012-2021 VLINGO LABS. All rights reserved. // // This Source Code Form is subject to the terms of the // Mozilla Public License, v. 2.0. If a copy of the MPL // was not distributed with this file, You can obtain // one at https://mozilla.org/MPL/2.0/. using System; using System.Collections.Generic; using System.Linq; using Vlingo.Xoom.Actors; using Vlingo.Xoom.Actors.TestKit; using Vlingo.Xoom.Common; using Vlingo.Xoom.Lattice.Tests.Query.Fixtures.Store; using Vlingo.Xoom.Symbio; using Vlingo.Xoom.Symbio.Store; using Vlingo.Xoom.Symbio.Store.Dispatch; using Vlingo.Xoom.Symbio.Store.State; using Vlingo.Xoom.Symbio.Store.State.InMemory; using Xunit; using Xunit.Abstractions; using TestState = Vlingo.Xoom.Lattice.Tests.Query.Fixtures.Store.TestState; namespace Vlingo.Xoom.Lattice.Tests.Query { public class StateStoreQueryActorTest : IDisposable { private readonly World _world; private readonly FailingStateStore _stateStore; private readonly ITestQueries _queries; [Fact] public void ItFindsStateByIdAndType() { GivenTestState("1", "Foo"); var testState = _queries.TestStateById("1").Await(TimeSpan.FromMilliseconds(1000)); Assert.Equal("Foo", testState.Name); } [Fact] public void ItReturnsNullIfStateIsNotFoundByIdAndType() { var testState = _queries.TestStateById("1").Await(TimeSpan.FromMilliseconds(1000)); Assert.Null(testState); } [Fact] public void ItFindsStateByIdAndTypeWithNotFoundState() { GivenTestState("1", "Foo"); var testState = _queries.TestStateById("1", TestState.Missing()).Await(TimeSpan.FromMilliseconds(1000)); Assert.Equal("Foo", testState.Name); } [Fact] public void ItReturnsNotFoundStateIfStateIsNotFoundByIdAndType() { var testState = _queries.TestStateById("1", TestState.Missing()).Await(TimeSpan.FromMilliseconds(1000)); Assert.Equal(TestState.MISSING, testState.Name); } [Fact] public void ItFindsObjectStateByIdAndType() { GivenTestStateObject("1", "Foo"); var testState = _queries.TestObjectStateById("1").Await(); // TimeSpan.FromMilliseconds(1000) Assert.True(testState.IsObject); Assert.Equal("Foo", testState.Data.Name); } [Fact] public void ItReturnsNullObjectStateIfNotFoundByIdAndType() { var testState = _queries.TestObjectStateById("1").Await(TimeSpan.FromMilliseconds(1000)); Assert.Equal(ObjectState<TestState>.Null, testState); } [Fact] public void ItFindsObjectStateByIdAndTypeWithNotFoundObjectState() { GivenTestState("1", "Foo"); var notFoundState = new ObjectState<TestState>(); var testState = _queries.TestObjectStateById("1", notFoundState).Await(TimeSpan.FromMilliseconds(1000)); Assert.True(testState.IsObject); Assert.Equal("Foo", testState.Data.Name); } [Fact] public void ItReturnsNullObjectStateIfNotFoundByIdAndTypeWithNotFoundObjectState() { var notFoundState = new ObjectState<TestState>(); var testState = _queries.TestObjectStateById("1", notFoundState).Await(TimeSpan.FromMilliseconds(1000)); Assert.Equal(notFoundState, testState); } [Fact] public void ItStreamsAllStatesByType() { GivenTestState("1", "Foo"); GivenTestState("2", "Bar"); GivenTestState("3", "Baz"); GivenTestState("4", "Bam"); var allStates = new List<TestState>(); var testStates = _queries.All(allStates).Await(TimeSpan.FromMilliseconds(10000)).ToList(); Assert.Equal(4, allStates.Count); Assert.Equal(4, testStates.Count); Assert.Equal(allStates, testStates); Assert.Equal("Foo", testStates[0].Name); Assert.Equal("Bar", testStates[1].Name); Assert.Equal("Baz", testStates[2].Name); Assert.Equal("Bam", testStates[3].Name); } [Fact] public void ItStreamsEmptyStore() { var allStates = new List<TestState>(); var testStates = _queries.All(allStates).Await(TimeSpan.FromSeconds(10)); Assert.Empty(allStates); Assert.Empty(testStates); } [Fact] public void ItFindsStateByIdAndTypeAfterRetries() { GivenTestState("1", "Foo"); GivenStateReadFailures(3); var testState = _queries.TestStateById("1", 100, 3).Await(TimeSpan.FromMilliseconds(2000)); Assert.Equal("Foo", testState.Name); } [Fact] public void ItFindsStateByIdAndTypeWithNotFoundStateAfterRetries() { GivenTestState("1", "Foo"); GivenStateReadFailures(3); var testState = _queries.TestStateById("1", TestState.Missing(), 100, 3).Await(TimeSpan.FromMilliseconds(2000)); Assert.Equal("Foo", testState.Name); } [Fact] public void ItReturnsNotFoundStateIfStateIsNotFoundByIdAndTypeAfterRetries() { GivenTestState("1", "Foo"); GivenStateReadFailures(3); var testState = _queries.TestStateById("1", TestState.Missing(), 100, 2).Await(TimeSpan.FromMilliseconds(2000)); Assert.Equal(TestState.MISSING, testState.Name); } [Fact] public void ItFindsObjectStateByIdAndTypeAfterRetries() { GivenTestStateObject("1", "Foo"); GivenStateReadFailures(3); var testState = _queries.TestObjectStateById("1", 100, 3).Await(TimeSpan.FromMilliseconds(2000)); Assert.True(testState.IsObject); Assert.Equal("Foo", testState.Data.Name); } [Fact] public void ItFindsObjectStateByIdAndTypeWithNotFoundStateAfterRetries() { GivenTestStateObject("1", "Foo"); GivenStateReadFailures(3); var notFoundState = new ObjectState<TestState>(); var testState = _queries.TestObjectStateById("1", notFoundState, 100, 3).Await(TimeSpan.FromMilliseconds(2000)); Assert.True(testState.IsObject); Assert.Equal("Foo", testState.Data.Name); } [Fact] public void ItReturnsNullObjectStateIfStateIsNotFoundByIdAndTypeAfterRetries() { GivenTestStateObject("1", "Foo"); GivenStateReadFailures(3); var notFoundState = new ObjectState<TestState>(); var testState = _queries.TestObjectStateById("1", notFoundState, 100, 2).Await(TimeSpan.FromMilliseconds(2000)); Assert.Equal(notFoundState, testState); } public StateStoreQueryActorTest(ITestOutputHelper output) { var converter = new Converter(output); Console.SetOut(converter); _world = TestWorld.StartWithDefaults("test-state-store-query").World; // adapters has to be declared and configured before the store is instantiated var stateAdapterProvider = new StateAdapterProvider(_world); stateAdapterProvider.RegisterAdapter(new TestStateAdapter()); stateAdapterProvider.RegisterAdapter(new ObjectTestStateAdapter()); StateTypeStateStoreMap.StateTypeToStoreName(nameof(TestState), typeof(TestState)); StateTypeStateStoreMap.StateTypeToStoreName(nameof(ObjectState<TestState>), typeof(ObjectState<TestState>)); _stateStore = new FailingStateStore(_world.ActorFor<IStateStore>(() => new InMemoryStateStoreActor<TextState>(new NoOpDispatcher()))); //StatefulTypeRegistry.RegisterAll(_world, _stateStore, typeof(ObjectState<TestState>)); _queries = _world.ActorFor<ITestQueries>(() => new TestQueriesActor(_stateStore)); } public void Dispose() => _world?.Terminate(); private void GivenStateReadFailures(int failures) => _stateStore.ExpectReadFailures(failures); private void GivenTestState(string id, string name) { _stateStore.Write( id, TestState.NamedWithId(name, id), 1, new NoOpWriteResultInterest() ); } private void GivenTestStateObject(string id, string name) { _stateStore.Write( id, new ObjectState<TestState>("1", typeof(ObjectState<TestState>), 1, TestState.NamedWithId(name, id), 1), 1, new NoOpWriteResultInterest() ); } } internal class NoOpWriteResultInterest : IWriteResultInterest { public void WriteResultedIn<TState, TSource>(IOutcome<StorageException, Result> outcome, string id, TState state, int stateVersion, IEnumerable<TSource> sources, object? @object) { } } }
34.916981
124
0.625743
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
Luteceo/vlingo-net-lattice
src/Vlingo.Xoom.Lattice.Tests/Query/StateStoreQueryActorTest.cs
9,254
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Windows.Navigation; namespace TestApplication.Tests.Alignments { public partial class TopLeftTest : Page { public TopLeftTest() { InitializeComponent(); } // Executes when the user navigates to this page. protected override void OnNavigatedTo(NavigationEventArgs e) { } } }
22.133333
68
0.707831
[ "MIT" ]
Barjonp/OpenSilver
src/Tests/TestApplication/TestApplication/Tests/Alignments/TopLeftTest.xaml.cs
666
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace BarManager.Windows { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { } }
18.444444
42
0.707831
[ "MIT" ]
N1K0232/BarManagerApplication
BarManagerApplication.Windows/src/BarManager.Windows/App.xaml.cs
334
C#
using NextGenSoftware.OASIS.API.Providers.MapboxOASIS.Enums; namespace NextGenSoftware.OASIS.API.Providers.MapboxOASIS.Models.Requests { public class GetRasterTileRequest { public string TilesetId { get; set; } public decimal Zoom { get; set; } public decimal X { get; set; } public decimal Y { get; set; } public RasterTileFormat Format { get; set; } } }
31.461538
73
0.669927
[ "CC0-1.0" ]
HirenBodhi/Our-World-OASIS-API-HoloNET-HoloUnity-And-.NET-HDK
NextGenSoftware.OASIS.API.Providers.MapboxOASIS/Models/Requests/GetRasterTileRequest.cs
411
C#
using MasterDevs.ChromeDevTools; using Newtonsoft.Json; using System; using System.Collections.Generic; namespace MasterDevs.ChromeDevTools.Protocol.Chrome.Runtime { /// <summary> /// Compiles expression. /// </summary> [CommandResponse(ProtocolName.Runtime.CompileScript)] [SupportedBy("Chrome")] public class CompileScriptCommandResponse { /// <summary> /// Gets or sets Id of the script. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public string ScriptId { get; set; } /// <summary> /// Gets or sets Exception details. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public ExceptionDetails ExceptionDetails { get; set; } } }
26.518519
62
0.73743
[ "MIT" ]
rollrat/custom-crawler
ChromeDevTools/Protocol/Chrome/Runtime/CompileScriptCommandResponse.cs
716
C#
using Coldairarrow.Entity.MiniPrograms; using Coldairarrow.Util; using System.Collections.Generic; using System.Threading.Tasks; namespace Coldairarrow.Business.MiniPrograms { public interface Imini_projectBusiness { Task<PageResult<mini_project>> GetDataListAsync(PageInput<ConditionDTO> input); Task<mini_project> GetTheDataAsync(string id); Task AddDataAsync(mini_project data); Task UpdateDataAsync(mini_project data); Task DeleteDataAsync(List<string> ids); } }
32.5
87
0.755769
[ "MIT" ]
fanxinshun/HS.Admin.AntVue
src/Coldairarrow.IBusiness/MiniPrograms/Imini_projectBusiness.cs
522
C#
using System.Threading.Tasks; using Common.Log; using Lykke.Common.Log; using Lykke.Job.QuorumTransactionWatcher.Contract; using Lykke.RabbitMqBroker.Subscriber; using MAVN.Service.PrivateBlockchainFacade.Domain.RabbitMq; namespace MAVN.Service.PrivateBlockchainFacade.DomainServices.RabbitMq.Subscribers { public class StakeReleasedSubscriber : JsonRabbitSubscriber<StakeReleasedEvent> { private readonly ILog _log; private readonly IStakedBalanceChangedHandler _handler; public StakeReleasedSubscriber( string connectionString, string exchangeName, string queueName, ILogFactory logFactory, IStakedBalanceChangedHandler handler) : base(connectionString, exchangeName, queueName, true, logFactory) { _handler = handler; _log = logFactory.CreateLog(this); } protected override async Task ProcessMessageAsync(StakeReleasedEvent evt) { await _handler.HandleAsync(evt.WalletAddress); _log.Info("Processed StakeReleasedEvent", evt); } } }
33.029412
117
0.706144
[ "MIT" ]
IliyanIlievPH/MAVN.Service.PrivateBlockchainFacade
src/MAVN.Service.PrivateBlockchainFacade.DomainServices/RabbitMq/Subscribers/StakeReleasedSubscriber.cs
1,123
C#
namespace PilaLibros { interface Libro { string mostrar(); } }
11.857143
25
0.554217
[ "Apache-2.0" ]
cmontellanob/programacionIIIcmb
2doParcial/2/PilaLibros/PilaLibros/Libro.cs
85
C#
#if WITH_GAME #if PLATFORM_32BITS using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace UnrealEngine { public partial class UCanvas { static readonly int OrgX__Offset; public float OrgX { get{ CheckIsValid();return (float)Marshal.PtrToStructure(_this.Get()+OrgX__Offset, typeof(float));} } static readonly int OrgY__Offset; public float OrgY { get{ CheckIsValid();return (float)Marshal.PtrToStructure(_this.Get()+OrgY__Offset, typeof(float));} } static readonly int ClipX__Offset; public float ClipX { get{ CheckIsValid();return (float)Marshal.PtrToStructure(_this.Get()+ClipX__Offset, typeof(float));} } static readonly int ClipY__Offset; public float ClipY { get{ CheckIsValid();return (float)Marshal.PtrToStructure(_this.Get()+ClipY__Offset, typeof(float));} } static readonly int DrawColor__Offset; public FColor DrawColor { get{ CheckIsValid();return (FColor)Marshal.PtrToStructure(_this.Get()+DrawColor__Offset, typeof(FColor));} } static readonly int bCenterX__Offset; public bool bCenterX { get{ CheckIsValid();return BoolWrap.Get(_this.Get(), bCenterX__Offset, 1, 0, 1, 1);} } static readonly int bCenterY__Offset; public bool bCenterY { get{ CheckIsValid();return BoolWrap.Get(_this.Get(), bCenterY__Offset, 1, 0, 2, 2);} } static readonly int bNoSmooth__Offset; public bool bNoSmooth { get{ CheckIsValid();return BoolWrap.Get(_this.Get(), bNoSmooth__Offset, 1, 0, 4, 4);} } static readonly int SizeX__Offset; public int SizeX { get{ CheckIsValid();return (int)Marshal.PtrToStructure(_this.Get()+SizeX__Offset, typeof(int));} } static readonly int SizeY__Offset; public int SizeY { get{ CheckIsValid();return (int)Marshal.PtrToStructure(_this.Get()+SizeY__Offset, typeof(int));} } static readonly int ColorModulate__Offset; public FPlane ColorModulate { get{ CheckIsValid();return (FPlane)Marshal.PtrToStructure(_this.Get()+ColorModulate__Offset, typeof(FPlane));} } static readonly int DefaultTexture__Offset; public UTexture2D DefaultTexture { get{ CheckIsValid(); IntPtr v = Marshal.ReadIntPtr(_this.Get() + DefaultTexture__Offset); if (v == IntPtr.Zero)return null; UTexture2D retValue = new UTexture2D(); retValue._this = v; return retValue; } } static readonly int GradientTexture0__Offset; public UTexture2D GradientTexture0 { get{ CheckIsValid(); IntPtr v = Marshal.ReadIntPtr(_this.Get() + GradientTexture0__Offset); if (v == IntPtr.Zero)return null; UTexture2D retValue = new UTexture2D(); retValue._this = v; return retValue; } } static readonly int ReporterGraph__Offset; public UReporterGraph ReporterGraph { get{ CheckIsValid(); IntPtr v = Marshal.ReadIntPtr(_this.Get() + ReporterGraph__Offset); if (v == IntPtr.Zero)return null; UReporterGraph retValue = new UReporterGraph(); retValue._this = v; return retValue; } } static UCanvas() { IntPtr NativeClassPtr=GetNativeClassFromName("Canvas"); OrgX__Offset=GetPropertyOffset(NativeClassPtr,"OrgX"); OrgY__Offset=GetPropertyOffset(NativeClassPtr,"OrgY"); ClipX__Offset=GetPropertyOffset(NativeClassPtr,"ClipX"); ClipY__Offset=GetPropertyOffset(NativeClassPtr,"ClipY"); DrawColor__Offset=GetPropertyOffset(NativeClassPtr,"DrawColor"); bCenterX__Offset=GetPropertyOffset(NativeClassPtr,"bCenterX"); bCenterY__Offset=GetPropertyOffset(NativeClassPtr,"bCenterY"); bNoSmooth__Offset=GetPropertyOffset(NativeClassPtr,"bNoSmooth"); SizeX__Offset=GetPropertyOffset(NativeClassPtr,"SizeX"); SizeY__Offset=GetPropertyOffset(NativeClassPtr,"SizeY"); ColorModulate__Offset=GetPropertyOffset(NativeClassPtr,"ColorModulate"); DefaultTexture__Offset=GetPropertyOffset(NativeClassPtr,"DefaultTexture"); GradientTexture0__Offset=GetPropertyOffset(NativeClassPtr,"GradientTexture0"); ReporterGraph__Offset=GetPropertyOffset(NativeClassPtr,"ReporterGraph"); } } } #endif #endif
30.789474
212
0.742369
[ "MIT" ]
RobertAcksel/UnrealCS
Engine/Plugins/UnrealCS/UECSharpDomain/UnrealEngine/GeneratedScriptFile_Game_32bits/UCanvas_FixSize.cs
4,095
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TextureDataCache : MonoBehaviour { private static Dictionary<Texture, TextureData> textureDataMap = new Dictionary<Texture, TextureData>(); public static TextureData GetTextureData(Texture texture) { TextureData textureData = null; textureDataMap.TryGetValue(texture, out textureData); return textureData; } public static void SetTexureData(Texture texture, TextureData textureData) { textureDataMap[texture] = textureData; } }
27.809524
108
0.736301
[ "MIT" ]
sereilly/uimirror
Assets/UIMirror/Scripts/Caches/TextureDataCache.cs
586
C#
using Mono.Cecil; using Mono.Collections.Generic; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace DocfxAnnotationGenerator { /// <summary> /// A member loaded via reflection. /// </summary> public class ReflectionMember { /// <summary> /// The UID Docfx would use for this member. See /// https://dotnet.github.io/docfx/spec/metadata_dotnet_spec.html /// </summary> public string DocfxUid { get; } // Never null, but only actually relevant for methods, properties and indexers. public IEnumerable<string> NotNullParameters { get; } = Enumerable.Empty<string>(); // Methods, indexers, properties. public bool NotNullReturn { get; } public static IEnumerable<ReflectionMember> Load(Stream stream) => ModuleDefinition.ReadModule(stream).Types.Where(t => t.IsPublic).SelectMany(GetMembers); private static IEnumerable<ReflectionMember> GetMembers(TypeDefinition type) { yield return new ReflectionMember(type); if (type.BaseType?.FullName == "System.MulticastDelegate") { yield break; } foreach (var property in type.Properties.Where(p => IsAccessible(p.GetMethod) || IsAccessible(p.SetMethod))) { yield return new ReflectionMember(property); } // TODO: Do we want protected methods? foreach (var method in type.Methods.Where(m => !m.IsGetter && !m.IsSetter && IsAccessible(m))) { yield return new ReflectionMember(method); } foreach (var field in type.Fields.Where(m => m.IsPublic && !m.IsSpecialName)) { yield return new ReflectionMember(field); } foreach (var nestedMember in type.NestedTypes.Where(t => t.IsNestedPublic).SelectMany(GetMembers)) { yield return nestedMember; } } private static bool IsAccessible(MethodDefinition method) { // This is pretty crude at the moment... // Handy for properties if (method == null) { return false; } // Overrides is used to check for explicit interface implementation return method.IsPublic || method.IsFamily || method.Overrides.Count != 0; } // TODO: More specifically, is it an explicit interface implementation for a public interface? // (Doesn't seem to affect us right now...) private ReflectionMember(TypeDefinition type) { DocfxUid = GetUid(type); } private ReflectionMember(PropertyDefinition property) { // property.Name will be Type.Name for explicit interface implementations, e.g. NodaTime.IClock.Now DocfxUid = $"{GetUid(property.DeclaringType)}.{property.Name.Replace('.', '#')}{GetParameterNames(property.Parameters)}"; NotNullReturn = HasNotNullAttribute(property); } private ReflectionMember(MethodDefinition method) { DocfxUid = GetUid(method); NotNullReturn = HasNotNullAttribute(method); NotNullParameters = method.Parameters.Where(p => HasNotNullAttribute(p) && !p.IsOut).Select(p => p.Name).ToList(); } private ReflectionMember(FieldDefinition field) { DocfxUid = $"{GetUid(field.DeclaringType)}.{field.Name}"; } private string GetUid(MethodDefinition method) { if (method.Overrides.Count == 1) { var interfaceMethod = method.Overrides[0]; var interfaceMethodNameUid = $"{GetUid(interfaceMethod.DeclaringType)}.{interfaceMethod.Name}".Replace('.', '#'); return $"{GetUid(method.DeclaringType)}.{interfaceMethodNameUid}{GetParameterNames(method.Parameters)}"; } string name = method.Name.Replace('.', '#'); string arity = method.HasGenericParameters ? $"``{method.GenericParameters.Count}" : ""; return $"{GetUid(method.DeclaringType)}.{name}{arity}{GetParameterNames(method.Parameters)}"; } private string GetUid(TypeDefinition type) { return GetUid(type, false); } private string GetUid(TypeReference type) { return GetUid(type, true); } private string GetUid(TypeReference type, bool useTypeArgumentNames) { string name = type.FullName.Replace('/', '.'); // TODO: Check whether this handles nested types involving generics switch (type) { case ByReferenceType brt: return $"{GetUid(brt.ElementType, useTypeArgumentNames)}@"; case GenericParameter gp when useTypeArgumentNames: return gp.Name; case GenericParameter gp when gp.DeclaringType != null: return $"`{gp.Position}"; case GenericParameter gp when gp.DeclaringMethod != null: return $"``{gp.Position}"; case GenericParameter gp: throw new InvalidOperationException("Unhandled generic parameter"); case GenericInstanceType git: return $"{RemoveArity(name)}{GetGenericArgumentNames(git.GenericArguments, useTypeArgumentNames)}"; default: return name; } } private string GetGenericArgumentNames(Collection<TypeReference> arguments, bool useTypeArgumentNames) => arguments.Count == 0 ? "" : $"{{{string.Join(",", arguments.Select(arg => GetUid(arg, useTypeArgumentNames)))}}}"; private string GetParameterNames(Collection<ParameterDefinition> parameters) => parameters.Count == 0 ? "" : $"({string.Join(",", parameters.Select(p => GetUid(p.ParameterType, false)))})"; private string RemoveArity(string name) { // TODO: Nested types, e.g. Foo`1.Bar or Foo`1.Bar`1 int index = name.IndexOf('`'); return index == -1 ? name : name.Substring(0, index); } private ReflectionMember(string uid) { DocfxUid = uid; } private bool HasNotNullAttribute(ICustomAttributeProvider provider) => provider != null && provider.HasCustomAttributes && provider.CustomAttributes.Any(attr => attr.AttributeType.FullName == "JetBrains.Annotations.NotNullAttribute"); } }
40.398773
145
0.604404
[ "Apache-2.0" ]
SeanFarrow/nodatime
build/DocfxAnnotationGenerator/ReflectionMember.cs
6,587
C#
using System; using System.Collections.Generic; using System.Linq; namespace HidLibrary { public interface IHidEnumerator { bool IsConnected(string devicePath); IHidDevice GetDevice(string devicePath); IEnumerable<IHidDevice> Enumerate(); IEnumerable<IHidDevice> Enumerate(string devicePath); IEnumerable<IHidDevice> Enumerate(int vendorId, params int[] productIds); IEnumerable<IHidDevice> Enumerate(int vendorId); } // Instance class that wraps HidDevices // The purpose of this is to allow consumer classes to create // their own enumeration abstractions, either for testing or // for comparing different implementations public class HidEnumerator : IHidEnumerator { public bool IsConnected(string devicePath) { return HidDevices.IsConnected(devicePath); } public IHidDevice GetDevice(string devicePath) { return HidDevices.GetDevice(devicePath) as IHidDevice; } public IEnumerable<IHidDevice> Enumerate() { return HidDevices.Enumerate(). Select(d => d as IHidDevice); } public IEnumerable<IHidDevice> Enumerate(string devicePath) { return HidDevices.Enumerate(devicePath). Select(d => d as IHidDevice); } public IEnumerable<IHidDevice> Enumerate(int vendorId, params int[] productIds) { return HidDevices.Enumerate(vendorId, productIds). Select(d => d as IHidDevice); } public IEnumerable<IHidDevice> Enumerate(int vendorId) { return HidDevices.Enumerate(vendorId). Select(d => d as IHidDevice); } } }
30.724138
87
0.632997
[ "MIT" ]
BOZWXJ/HidLibrary
src/HidLibrary/IHidEnumerator.cs
1,784
C#
#pragma checksum "C:\Users\Batuhan\source\repos\CoreProject_MVC\CoreProject_MVC\Views\Blog\Index.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "9d8fd721956c66a8ab19afca3beeb0f1e03ba0ed" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Blog_Index), @"mvc.1.0.view", @"/Views/Blog/Index.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "C:\Users\Batuhan\source\repos\CoreProject_MVC\CoreProject_MVC\Views\_ViewImports.cshtml" using MVC_CoreProject; #line default #line hidden #nullable disable #nullable restore #line 2 "C:\Users\Batuhan\source\repos\CoreProject_MVC\CoreProject_MVC\Views\_ViewImports.cshtml" using MVC_CoreProject.Models; #line default #line hidden #nullable disable #nullable restore #line 1 "C:\Users\Batuhan\source\repos\CoreProject_MVC\CoreProject_MVC\Views\Blog\Index.cshtml" using X.PagedList; #line default #line hidden #nullable disable #nullable restore #line 2 "C:\Users\Batuhan\source\repos\CoreProject_MVC\CoreProject_MVC\Views\Blog\Index.cshtml" using X.PagedList.Mvc.Core; #line default #line hidden #nullable disable #nullable restore #line 3 "C:\Users\Batuhan\source\repos\CoreProject_MVC\CoreProject_MVC\Views\Blog\Index.cshtml" using X.PagedList.Web.Common; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"9d8fd721956c66a8ab19afca3beeb0f1e03ba0ed", @"/Views/Blog/Index.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"489d51d8aff94f7b19f5c397c763638bcd9574ac", @"/Views/_ViewImports.cshtml")] public class Views_Blog_Index : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<IPagedList<EntityLayer.Concrete.Blog>> { #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { #nullable restore #line 5 "C:\Users\Batuhan\source\repos\CoreProject_MVC\CoreProject_MVC\Views\Blog\Index.cshtml" ViewData["Title"] = "Index"; Layout = "~/Views/Shared/_MainLayout.cshtml"; #line default #line hidden #nullable disable WriteLiteral("<section class=\"main-content-w3layouts-agileits\">\r\n\t\t<div class=\"container\">\r\n\t\t\t<h3 class=\"tittle\">Bloglar</h3>\r\n\t\t\t<div class=\"inner-sec\">\r\n\t\t\t\t<!--left-->\r\n\t\t\t\t<div class=\"left-blog-info-w3layouts-agileits text-left\">\r\n\t\t\t\t\t<div class=\"row\">\r\n"); #nullable restore #line 16 "C:\Users\Batuhan\source\repos\CoreProject_MVC\CoreProject_MVC\Views\Blog\Index.cshtml" foreach (var item in Model) { #line default #line hidden #nullable disable WriteLiteral("\t\t\t\t\t\t<div class=\"col-lg-4 card\">\r\n\t\t\t\t\t\t\t<a"); BeginWriteAttribute("href", " href=\"", 574, "\"", 610, 2); WriteAttributeValue("", 581, "/Blog/BlogDetail/", 581, 17, true); #nullable restore #line 21 "C:\Users\Batuhan\source\repos\CoreProject_MVC\CoreProject_MVC\Views\Blog\Index.cshtml" WriteAttributeValue("", 598, item.BlogID, 598, 12, false); #line default #line hidden #nullable disable EndWriteAttribute(); WriteLiteral(">\r\n\t\t\t\t\t\t\t\t<img"); BeginWriteAttribute("src", " src=\"", 626, "\"", 647, 1); #nullable restore #line 22 "C:\Users\Batuhan\source\repos\CoreProject_MVC\CoreProject_MVC\Views\Blog\Index.cshtml" WriteAttributeValue("", 632, item.BlogImage, 632, 15, false); #line default #line hidden #nullable disable EndWriteAttribute(); WriteLiteral(" class=\"card-img-top img-fluid\""); BeginWriteAttribute("alt", " alt=\"", 679, "\"", 685, 0); EndWriteAttribute(); WriteLiteral(">\r\n\t\t\t\t\t\t\t</a>\r\n\t\t\t\t\t\t\t<div class=\"card-body\">\r\n\t\t\t\t\t\t\t\t<ul class=\"blog-icons my-4\">\r\n\t\t\t\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t\t\t\t<a href=\"#\">\r\n\t\t\t\t\t\t\t\t\t\t\t<i class=\"far fa-calendar-alt\"></i>"); #nullable restore #line 28 "C:\Users\Batuhan\source\repos\CoreProject_MVC\CoreProject_MVC\Views\Blog\Index.cshtml" Write(((DateTime)@item.BlogCreateDate).ToString("dd-MMM-yyyy")); #line default #line hidden #nullable disable WriteLiteral("</a>\r\n\t\t\t\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t\t\t\t<li class=\"mx-2\">\r\n\t\t\t\t\t\t\t\t\t\t<a href=\"#\">\r\n\t\t\t\t\t\t\t\t\t\t\t<i class=\"far fa-comment\"></i>9</a>\r\n\t\t\t\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t\t\t\t<li>\r\n\t\t\t\t\t\t\t\t\t\t<a"); BeginWriteAttribute("href", " href=\"", 1081, "\"", 1117, 2); WriteAttributeValue("", 1088, "/Blog/BlogDetail/", 1088, 17, true); #nullable restore #line 35 "C:\Users\Batuhan\source\repos\CoreProject_MVC\CoreProject_MVC\Views\Blog\Index.cshtml" WriteAttributeValue("", 1105, item.BlogID, 1105, 12, false); #line default #line hidden #nullable disable EndWriteAttribute(); WriteLiteral(">\r\n\t\t\t\t\t\t\t\t\t\t\t<i class=\"fas fa-eye\"></i>"); #nullable restore #line 36 "C:\Users\Batuhan\source\repos\CoreProject_MVC\CoreProject_MVC\Views\Blog\Index.cshtml" Write(item.Category.CategoryName); #line default #line hidden #nullable disable WriteLiteral("</a>\r\n\t\t\t\t\t\t\t\t\t</li>\r\n\r\n\t\t\t\t\t\t\t\t</ul>\r\n\t\t\t\t\t\t\t\t<h5 class=\"card-title\">\r\n\t\t\t\t\t\t\t\t\t<a"); BeginWriteAttribute("href", " href=\"", 1268, "\"", 1304, 2); WriteAttributeValue("", 1275, "/Blog/BlogDetail/", 1275, 17, true); #nullable restore #line 41 "C:\Users\Batuhan\source\repos\CoreProject_MVC\CoreProject_MVC\Views\Blog\Index.cshtml" WriteAttributeValue("", 1292, item.BlogID, 1292, 12, false); #line default #line hidden #nullable disable EndWriteAttribute(); WriteLiteral(">"); #nullable restore #line 41 "C:\Users\Batuhan\source\repos\CoreProject_MVC\CoreProject_MVC\Views\Blog\Index.cshtml" Write(item.BlogTitle); #line default #line hidden #nullable disable WriteLiteral("</a>\r\n\t\t\t\t\t\t\t\t</h5>\r\n\t\t\t\t\t\t\t\t<p class=\"card-text mb-3\">"); #nullable restore #line 43 "C:\Users\Batuhan\source\repos\CoreProject_MVC\CoreProject_MVC\Views\Blog\Index.cshtml" Write(item.BlogContent.Substring(0,100)); #line default #line hidden #nullable disable WriteLiteral("</p>\r\n\t\t\t\t\t\t\t\t<a"); BeginWriteAttribute("href", " href=\"", 1426, "\"", 1462, 2); WriteAttributeValue("", 1433, "/Blog/BlogDetail/", 1433, 17, true); #nullable restore #line 44 "C:\Users\Batuhan\source\repos\CoreProject_MVC\CoreProject_MVC\Views\Blog\Index.cshtml" WriteAttributeValue("", 1450, item.BlogID, 1450, 12, false); #line default #line hidden #nullable disable EndWriteAttribute(); WriteLiteral(" class=\"btn btn-primary read-m\">Devamını Oku</a>\r\n\t\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t</div>\t\t\t\t\r\n"); #nullable restore #line 47 "C:\Users\Batuhan\source\repos\CoreProject_MVC\CoreProject_MVC\Views\Blog\Index.cshtml" } #line default #line hidden #nullable disable WriteLiteral("\t\t\t\t\t</div>\r\n\t\t\t\t\t\r\n\t\t\t\t\t<!--//left-->\r\n\t\t\t\t</div>\r\n\t\t\t</div>\r\n\t\t</div>\r\n\t</section>\r\n\t<div style=\"margin-left:auto; margin-right:auto;\">\r\n\t\t"); #nullable restore #line 56 "C:\Users\Batuhan\source\repos\CoreProject_MVC\CoreProject_MVC\Views\Blog\Index.cshtml" Write(Html.PagedListPager((IPagedList)Model,page => Url.Action("Index", new {page}), new PagedListRenderOptions() { LinkToFirstPageFormat = "<< İlk", LinkToPreviousPageFormat = "< Önceki", LinkToNextPageFormat = "Sonraki >", LinkToLastPageFormat = "Son >>" , PageClasses = new string[] { "page-link " }, LiElementClasses = new string[] { "page-item" }, })); #line default #line hidden #nullable disable WriteLiteral("\r\n\t</div>\r\n\r\n\r\n"); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<IPagedList<EntityLayer.Concrete.Blog>> Html { get; private set; } } } #pragma warning restore 1591
46.268293
322
0.674644
[ "MIT" ]
batuhansariikaya/MVC_CoreBlogProject
CoreProject_MVC/CoreProject_MVC/obj/Debug/net5.0/Razor/Views/Blog/Index.cshtml.g.cs
9,489
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 System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.GraphModel; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { using Workspace = Microsoft.CodeAnalysis.Workspace; internal class GraphQueryManager { private readonly Workspace _workspace; private readonly IAsynchronousOperationListener _asyncListener; /// <summary> /// This gate locks manipulation of <see cref="_trackedQueries"/>. /// </summary> private readonly object _gate = new(); private readonly List<ValueTuple<WeakReference<IGraphContext>, List<IGraphQuery>>> _trackedQueries = new(); // We update all of our tracked queries when this delay elapses. private ResettableDelay? _delay; internal GraphQueryManager(Workspace workspace, IAsynchronousOperationListener asyncListener) { _workspace = workspace; _asyncListener = asyncListener; } internal void AddQueries(IGraphContext context, List<IGraphQuery> graphQueries) { var asyncToken = _asyncListener.BeginAsyncOperation("GraphQueryManager.AddQueries"); var solution = _workspace.CurrentSolution; var populateTask = PopulateContextGraphAsync(solution, graphQueries, context); // We want to ensure that no matter what happens, this initial context is completed var task = populateTask.SafeContinueWith( _ => context.OnCompleted(), context.CancelToken, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); if (context.TrackChanges) { task = task.SafeContinueWith( _ => TrackChangesAfterFirstPopulate(graphQueries, context, solution), context.CancelToken, TaskContinuationOptions.None, TaskScheduler.Default); } task.CompletesAsyncOperation(asyncToken); } private void TrackChangesAfterFirstPopulate(List<IGraphQuery> graphQueries, IGraphContext context, Solution solution) { var workspace = solution.Workspace; var contextWeakReference = new WeakReference<IGraphContext>(context); lock (_gate) { if (_trackedQueries.IsEmpty()) { _workspace.WorkspaceChanged += OnWorkspaceChanged; } _trackedQueries.Add(ValueTuple.Create(contextWeakReference, graphQueries)); } EnqueueUpdateIfSolutionIsStale(solution); } private void EnqueueUpdateIfSolutionIsStale(Solution solution) { // It's possible the workspace changed during our initial population, so let's enqueue an update if it did if (_workspace.CurrentSolution != solution) { EnqueueUpdate(); } } private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e) => EnqueueUpdate(); private void EnqueueUpdate() { const int WorkspaceUpdateDelay = 1500; var delay = _delay; if (delay == null) { var newDelay = new ResettableDelay(WorkspaceUpdateDelay, _asyncListener); if (Interlocked.CompareExchange(ref _delay, newDelay, null) == null) { var asyncToken = _asyncListener.BeginAsyncOperation("WorkspaceGraphQueryManager.EnqueueUpdate"); newDelay.Task.SafeContinueWithFromAsync(_ => UpdateAsync(), CancellationToken.None, TaskScheduler.Default) .CompletesAsyncOperation(asyncToken); } return; } delay.Reset(); } private Task UpdateAsync() { List<ValueTuple<IGraphContext, List<IGraphQuery>>> liveQueries; lock (_gate) { liveQueries = _trackedQueries.Select(t => ValueTuple.Create(t.Item1.GetTarget(), t.Item2)).Where(t => t.Item1 != null).ToList()!; } var solution = _workspace.CurrentSolution; var tasks = liveQueries.Select(t => PopulateContextGraphAsync(solution, t.Item2, t.Item1)).ToArray(); var whenAllTask = Task.WhenAll(tasks); return whenAllTask.SafeContinueWith(t => PostUpdate(solution), TaskScheduler.Default); } private void PostUpdate(Solution solution) { _delay = null; lock (_gate) { // See if each context is still alive. It's possible it's already been GC'ed meaning we should stop caring about the query _trackedQueries.RemoveAll(t => !IsTrackingContext(t.Item1)); if (_trackedQueries.IsEmpty()) { _workspace.WorkspaceChanged -= OnWorkspaceChanged; return; } } EnqueueUpdateIfSolutionIsStale(solution); } private static bool IsTrackingContext(WeakReference<IGraphContext> weakContext) { var context = weakContext.GetTarget(); return context != null && !context.CancelToken.IsCancellationRequested; } /// <summary> /// Populate the graph of the context with the values for the given Solution. /// </summary> private static async Task PopulateContextGraphAsync(Solution solution, List<IGraphQuery> graphQueries, IGraphContext context) { try { var cancellationToken = context.CancelToken; var graphBuilderTasks = graphQueries.Select(q => q.GetGraphAsync(solution, context, cancellationToken)).ToArray(); var graphBuilders = await Task.WhenAll(graphBuilderTasks).ConfigureAwait(false); // Perform the actual graph transaction using var transaction = new GraphTransactionScope(); // Remove any links that may have been added by a previous population. We don't // remove nodes to maintain node identity, matching the behavior of the old // providers. context.Graph.Links.Clear(); foreach (var graphBuilder in graphBuilders) { graphBuilder.ApplyToGraph(context.Graph, cancellationToken); context.OutputNodes.AddAll(graphBuilder.GetCreatedNodes(cancellationToken)); } transaction.Complete(); } catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex)) { throw ExceptionUtilities.Unreachable; } } } }
39.322581
145
0.622915
[ "MIT" ]
333fred/roslyn
src/VisualStudio/Core/Def/Implementation/Progression/GraphQueryManager.cs
7,316
C#
using Supermarket.API.Domain.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Supermarket.API.Domain.Repositories { public interface IProductRepository { Task<IEnumerable<Product>> ListAsync(); Task AddAsync(Product product); Task<Product> FindByIdAsync(int id); void Update(Product product); void Remove(Product product); } }
23.578947
47
0.712054
[ "MIT" ]
choipureum/Supermarket.API
src/Domain/Repositories/IProductRepository.cs
450
C#
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Dialogflow.V2.Snippets { using Google.Api.Gax; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; using gcdv = Google.Cloud.Dialogflow.V2; /// <summary>Generated snippets.</summary> public sealed class GeneratedVersionsClientSnippets { /// <summary>Snippet for ListVersions</summary> public void ListVersionsRequestObject() { // Snippet: ListVersions(ListVersionsRequest, CallSettings) // Create client VersionsClient versionsClient = VersionsClient.Create(); // Initialize request argument(s) ListVersionsRequest request = new ListVersionsRequest { ParentAsAgentName = AgentName.FromProject("[PROJECT]"), }; // Make the request PagedEnumerable<ListVersionsResponse, gcdv::Version> response = versionsClient.ListVersions(request); // Iterate over all response items, lazily performing RPCs as required foreach (gcdv::Version item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListVersionsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (gcdv::Version item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<gcdv::Version> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (gcdv::Version item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListVersionsAsync</summary> public async Task ListVersionsRequestObjectAsync() { // Snippet: ListVersionsAsync(ListVersionsRequest, CallSettings) // Create client VersionsClient versionsClient = await VersionsClient.CreateAsync(); // Initialize request argument(s) ListVersionsRequest request = new ListVersionsRequest { ParentAsAgentName = AgentName.FromProject("[PROJECT]"), }; // Make the request PagedAsyncEnumerable<ListVersionsResponse, gcdv::Version> response = versionsClient.ListVersionsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((gcdv::Version item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListVersionsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (gcdv::Version item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<gcdv::Version> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (gcdv::Version item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListVersions</summary> public void ListVersions() { // Snippet: ListVersions(string, string, int?, CallSettings) // Create client VersionsClient versionsClient = VersionsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/agent"; // Make the request PagedEnumerable<ListVersionsResponse, gcdv::Version> response = versionsClient.ListVersions(parent); // Iterate over all response items, lazily performing RPCs as required foreach (gcdv::Version item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListVersionsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (gcdv::Version item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<gcdv::Version> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (gcdv::Version item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListVersionsAsync</summary> public async Task ListVersionsAsync() { // Snippet: ListVersionsAsync(string, string, int?, CallSettings) // Create client VersionsClient versionsClient = await VersionsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/agent"; // Make the request PagedAsyncEnumerable<ListVersionsResponse, gcdv::Version> response = versionsClient.ListVersionsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((gcdv::Version item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListVersionsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (gcdv::Version item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<gcdv::Version> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (gcdv::Version item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListVersions</summary> public void ListVersionsResourceNames() { // Snippet: ListVersions(AgentName, string, int?, CallSettings) // Create client VersionsClient versionsClient = VersionsClient.Create(); // Initialize request argument(s) AgentName parent = AgentName.FromProject("[PROJECT]"); // Make the request PagedEnumerable<ListVersionsResponse, gcdv::Version> response = versionsClient.ListVersions(parent); // Iterate over all response items, lazily performing RPCs as required foreach (gcdv::Version item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListVersionsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (gcdv::Version item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<gcdv::Version> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (gcdv::Version item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListVersionsAsync</summary> public async Task ListVersionsResourceNamesAsync() { // Snippet: ListVersionsAsync(AgentName, string, int?, CallSettings) // Create client VersionsClient versionsClient = await VersionsClient.CreateAsync(); // Initialize request argument(s) AgentName parent = AgentName.FromProject("[PROJECT]"); // Make the request PagedAsyncEnumerable<ListVersionsResponse, gcdv::Version> response = versionsClient.ListVersionsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((gcdv::Version item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListVersionsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (gcdv::Version item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<gcdv::Version> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (gcdv::Version item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetVersion</summary> public void GetVersionRequestObject() { // Snippet: GetVersion(GetVersionRequest, CallSettings) // Create client VersionsClient versionsClient = VersionsClient.Create(); // Initialize request argument(s) GetVersionRequest request = new GetVersionRequest { VersionName = VersionName.FromProjectVersion("[PROJECT]", "[VERSION]"), }; // Make the request gcdv::Version response = versionsClient.GetVersion(request); // End snippet } /// <summary>Snippet for GetVersionAsync</summary> public async Task GetVersionRequestObjectAsync() { // Snippet: GetVersionAsync(GetVersionRequest, CallSettings) // Additional: GetVersionAsync(GetVersionRequest, CancellationToken) // Create client VersionsClient versionsClient = await VersionsClient.CreateAsync(); // Initialize request argument(s) GetVersionRequest request = new GetVersionRequest { VersionName = VersionName.FromProjectVersion("[PROJECT]", "[VERSION]"), }; // Make the request gcdv::Version response = await versionsClient.GetVersionAsync(request); // End snippet } /// <summary>Snippet for GetVersion</summary> public void GetVersion() { // Snippet: GetVersion(string, CallSettings) // Create client VersionsClient versionsClient = VersionsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/agent/versions/[VERSION]"; // Make the request gcdv::Version response = versionsClient.GetVersion(name); // End snippet } /// <summary>Snippet for GetVersionAsync</summary> public async Task GetVersionAsync() { // Snippet: GetVersionAsync(string, CallSettings) // Additional: GetVersionAsync(string, CancellationToken) // Create client VersionsClient versionsClient = await VersionsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/agent/versions/[VERSION]"; // Make the request gcdv::Version response = await versionsClient.GetVersionAsync(name); // End snippet } /// <summary>Snippet for GetVersion</summary> public void GetVersionResourceNames() { // Snippet: GetVersion(VersionName, CallSettings) // Create client VersionsClient versionsClient = VersionsClient.Create(); // Initialize request argument(s) VersionName name = VersionName.FromProjectVersion("[PROJECT]", "[VERSION]"); // Make the request gcdv::Version response = versionsClient.GetVersion(name); // End snippet } /// <summary>Snippet for GetVersionAsync</summary> public async Task GetVersionResourceNamesAsync() { // Snippet: GetVersionAsync(VersionName, CallSettings) // Additional: GetVersionAsync(VersionName, CancellationToken) // Create client VersionsClient versionsClient = await VersionsClient.CreateAsync(); // Initialize request argument(s) VersionName name = VersionName.FromProjectVersion("[PROJECT]", "[VERSION]"); // Make the request gcdv::Version response = await versionsClient.GetVersionAsync(name); // End snippet } /// <summary>Snippet for CreateVersion</summary> public void CreateVersionRequestObject() { // Snippet: CreateVersion(CreateVersionRequest, CallSettings) // Create client VersionsClient versionsClient = VersionsClient.Create(); // Initialize request argument(s) CreateVersionRequest request = new CreateVersionRequest { ParentAsAgentName = AgentName.FromProject("[PROJECT]"), Version = new gcdv::Version(), }; // Make the request gcdv::Version response = versionsClient.CreateVersion(request); // End snippet } /// <summary>Snippet for CreateVersionAsync</summary> public async Task CreateVersionRequestObjectAsync() { // Snippet: CreateVersionAsync(CreateVersionRequest, CallSettings) // Additional: CreateVersionAsync(CreateVersionRequest, CancellationToken) // Create client VersionsClient versionsClient = await VersionsClient.CreateAsync(); // Initialize request argument(s) CreateVersionRequest request = new CreateVersionRequest { ParentAsAgentName = AgentName.FromProject("[PROJECT]"), Version = new gcdv::Version(), }; // Make the request gcdv::Version response = await versionsClient.CreateVersionAsync(request); // End snippet } /// <summary>Snippet for CreateVersion</summary> public void CreateVersion() { // Snippet: CreateVersion(string, Version, CallSettings) // Create client VersionsClient versionsClient = VersionsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/agent"; gcdv::Version version = new gcdv::Version(); // Make the request gcdv::Version response = versionsClient.CreateVersion(parent, version); // End snippet } /// <summary>Snippet for CreateVersionAsync</summary> public async Task CreateVersionAsync() { // Snippet: CreateVersionAsync(string, Version, CallSettings) // Additional: CreateVersionAsync(string, Version, CancellationToken) // Create client VersionsClient versionsClient = await VersionsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/agent"; gcdv::Version version = new gcdv::Version(); // Make the request gcdv::Version response = await versionsClient.CreateVersionAsync(parent, version); // End snippet } /// <summary>Snippet for CreateVersion</summary> public void CreateVersionResourceNames() { // Snippet: CreateVersion(AgentName, Version, CallSettings) // Create client VersionsClient versionsClient = VersionsClient.Create(); // Initialize request argument(s) AgentName parent = AgentName.FromProject("[PROJECT]"); gcdv::Version version = new gcdv::Version(); // Make the request gcdv::Version response = versionsClient.CreateVersion(parent, version); // End snippet } /// <summary>Snippet for CreateVersionAsync</summary> public async Task CreateVersionResourceNamesAsync() { // Snippet: CreateVersionAsync(AgentName, Version, CallSettings) // Additional: CreateVersionAsync(AgentName, Version, CancellationToken) // Create client VersionsClient versionsClient = await VersionsClient.CreateAsync(); // Initialize request argument(s) AgentName parent = AgentName.FromProject("[PROJECT]"); gcdv::Version version = new gcdv::Version(); // Make the request gcdv::Version response = await versionsClient.CreateVersionAsync(parent, version); // End snippet } /// <summary>Snippet for UpdateVersion</summary> public void UpdateVersionRequestObject() { // Snippet: UpdateVersion(UpdateVersionRequest, CallSettings) // Create client VersionsClient versionsClient = VersionsClient.Create(); // Initialize request argument(s) UpdateVersionRequest request = new UpdateVersionRequest { Version = new gcdv::Version(), UpdateMask = new FieldMask(), }; // Make the request gcdv::Version response = versionsClient.UpdateVersion(request); // End snippet } /// <summary>Snippet for UpdateVersionAsync</summary> public async Task UpdateVersionRequestObjectAsync() { // Snippet: UpdateVersionAsync(UpdateVersionRequest, CallSettings) // Additional: UpdateVersionAsync(UpdateVersionRequest, CancellationToken) // Create client VersionsClient versionsClient = await VersionsClient.CreateAsync(); // Initialize request argument(s) UpdateVersionRequest request = new UpdateVersionRequest { Version = new gcdv::Version(), UpdateMask = new FieldMask(), }; // Make the request gcdv::Version response = await versionsClient.UpdateVersionAsync(request); // End snippet } /// <summary>Snippet for UpdateVersion</summary> public void UpdateVersion() { // Snippet: UpdateVersion(Version, FieldMask, CallSettings) // Create client VersionsClient versionsClient = VersionsClient.Create(); // Initialize request argument(s) gcdv::Version version = new gcdv::Version(); FieldMask updateMask = new FieldMask(); // Make the request gcdv::Version response = versionsClient.UpdateVersion(version, updateMask); // End snippet } /// <summary>Snippet for UpdateVersionAsync</summary> public async Task UpdateVersionAsync() { // Snippet: UpdateVersionAsync(Version, FieldMask, CallSettings) // Additional: UpdateVersionAsync(Version, FieldMask, CancellationToken) // Create client VersionsClient versionsClient = await VersionsClient.CreateAsync(); // Initialize request argument(s) gcdv::Version version = new gcdv::Version(); FieldMask updateMask = new FieldMask(); // Make the request gcdv::Version response = await versionsClient.UpdateVersionAsync(version, updateMask); // End snippet } /// <summary>Snippet for DeleteVersion</summary> public void DeleteVersionRequestObject() { // Snippet: DeleteVersion(DeleteVersionRequest, CallSettings) // Create client VersionsClient versionsClient = VersionsClient.Create(); // Initialize request argument(s) DeleteVersionRequest request = new DeleteVersionRequest { VersionName = VersionName.FromProjectVersion("[PROJECT]", "[VERSION]"), }; // Make the request versionsClient.DeleteVersion(request); // End snippet } /// <summary>Snippet for DeleteVersionAsync</summary> public async Task DeleteVersionRequestObjectAsync() { // Snippet: DeleteVersionAsync(DeleteVersionRequest, CallSettings) // Additional: DeleteVersionAsync(DeleteVersionRequest, CancellationToken) // Create client VersionsClient versionsClient = await VersionsClient.CreateAsync(); // Initialize request argument(s) DeleteVersionRequest request = new DeleteVersionRequest { VersionName = VersionName.FromProjectVersion("[PROJECT]", "[VERSION]"), }; // Make the request await versionsClient.DeleteVersionAsync(request); // End snippet } /// <summary>Snippet for DeleteVersion</summary> public void DeleteVersion() { // Snippet: DeleteVersion(string, CallSettings) // Create client VersionsClient versionsClient = VersionsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/agent/versions/[VERSION]"; // Make the request versionsClient.DeleteVersion(name); // End snippet } /// <summary>Snippet for DeleteVersionAsync</summary> public async Task DeleteVersionAsync() { // Snippet: DeleteVersionAsync(string, CallSettings) // Additional: DeleteVersionAsync(string, CancellationToken) // Create client VersionsClient versionsClient = await VersionsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/agent/versions/[VERSION]"; // Make the request await versionsClient.DeleteVersionAsync(name); // End snippet } /// <summary>Snippet for DeleteVersion</summary> public void DeleteVersionResourceNames() { // Snippet: DeleteVersion(VersionName, CallSettings) // Create client VersionsClient versionsClient = VersionsClient.Create(); // Initialize request argument(s) VersionName name = VersionName.FromProjectVersion("[PROJECT]", "[VERSION]"); // Make the request versionsClient.DeleteVersion(name); // End snippet } /// <summary>Snippet for DeleteVersionAsync</summary> public async Task DeleteVersionResourceNamesAsync() { // Snippet: DeleteVersionAsync(VersionName, CallSettings) // Additional: DeleteVersionAsync(VersionName, CancellationToken) // Create client VersionsClient versionsClient = await VersionsClient.CreateAsync(); // Initialize request argument(s) VersionName name = VersionName.FromProjectVersion("[PROJECT]", "[VERSION]"); // Make the request await versionsClient.DeleteVersionAsync(name); // End snippet } } }
43.631083
123
0.590616
[ "Apache-2.0" ]
LaudateCorpus1/google-cloud-dotnet
apis/Google.Cloud.Dialogflow.V2/Google.Cloud.Dialogflow.V2.Snippets/VersionsClientSnippets.g.cs
27,793
C#
using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using ServiceStack; using ServiceStack.DataAnnotations; using ServiceStack.OrmLite; namespace FoxValleyMeetup.Web.Configurations.c05_Bookmarks { public class BookmarksService : Service { public IAutoQueryDb AutoQuery { get; set; } //Override with custom implementation public object Any(FindBookmarks query) { var q = AutoQuery.CreateQuery(query, base.Request); return AutoQuery.Execute(query, q); } } [Authenticate] public class BookmarksCrudService : Service { public async Task<object> Post(Bookmark request) { var user = GetSession(true); Console.WriteLine("Files: " + Request.Files.Length); if (Request.Files != null && Request.Files.Length > 0) { Console.WriteLine("Uploading files"); foreach(var file in Request.Files) { var bookmarks = BookmarkUtils.ToBookmarks(file.InputStream); foreach(var bookmark in bookmarks) { bookmark.CreatedBy = user.UserName; bookmark.CreatedById = user.Id.ToInt(); bookmark.CreatedOn = DateTime.UtcNow; bookmark.ModifiedBy = user.UserName; bookmark.ModifiedById = user.Id.ToInt(); bookmark.ModifiedOn = request.CreatedOn; try { await Db.InsertAsync(bookmark); } catch {} } } return null; } if (string.IsNullOrWhiteSpace(request.Url)) throw new ArgumentNullException(nameof(request.Url)); if (string.IsNullOrWhiteSpace(request.Title)) throw new ArgumentNullException(nameof(request.Title)); var id = await Db.InsertAsync(request, true); return await Db.SingleByIdAsync<Bookmark>(id); } public async Task<object> Get(Bookmark request) { return await Db.SingleByIdAsync<Bookmark>(request.Id); } public async Task<object> Put(Bookmark request) { if (string.IsNullOrWhiteSpace(request.Url)) throw new ArgumentNullException(nameof(request.Url)); if (string.IsNullOrWhiteSpace(request.Title)) throw new ArgumentNullException(nameof(request.Title)); var existing = await Db.SingleByIdAsync<Bookmark>(request.Id); if (existing == null) throw HttpError.NotFound("Not Found"); var user = GetSession(true); request.ModifiedBy = user.UserName; request.ModifiedById = user.Id.ToInt(); request.ModifiedOn = DateTime.UtcNow; await Db.UpdateAsync(request); return await Db.SingleByIdAsync<Bookmark>(request.Id); } public async Task<object> Patch(Bookmark request) { var existing = await Db.SingleByIdAsync<Bookmark>(request.Id); if (existing == null) throw HttpError.NotFound("Not Found"); existing.PopulateWithNonDefaultValues(request); var user = GetSession(true); existing.ModifiedBy = user.UserName; existing.ModifiedById = user.Id.ToInt(); existing.ModifiedOn = DateTime.UtcNow; await Db.UpdateAsync(existing); return await Db.SingleByIdAsync<Bookmark>(request.Id); } public async Task<object> Delete(Bookmark request) { var existing = await Db.SingleByIdAsync<Bookmark>(request.Id); if (existing == null) throw HttpError.NotFound("Not Found"); await Db.DeleteAsync(request); return await Db.SingleByIdAsync<Bookmark>(request.Id); } } public static class BookmarkUtils { // for now assumes Url,Title,Description,Category,Tags public static List<Bookmark> ToBookmarks(this Stream stream) { var bookmarks = new List<Bookmark>(); var firstLine = true; foreach (var line in stream.ReadLines()) { if (firstLine) { firstLine = false; continue; } var items = line.Split(','); var bookmark = new Bookmark(); if (items.Length > 0) bookmark.Url = items[0]; if (items.Length > 1) bookmark.Title = items[1]; if (items.Length > 2) bookmark.Description = items[2]; if (items.Length > 3) bookmark.Category = items[3]; if (!string.IsNullOrWhiteSpace(bookmark.Url) && !string.IsNullOrWhiteSpace(bookmark.Title)) bookmarks.Add(bookmark); } return bookmarks; } } [Route("/bookmarks", "GET")] public class FindBookmarks : QueryDb<Bookmark> { } [Route("/bookmarks", "POST")] [Route("/bookmarks/{Id}", "GET,PUT,PATCH,DELETE")] [Alias("Bookmarks")] public class Bookmark: IReturn<Bookmark> { [PrimaryKey, AutoIncrement] public int Id { get; set; } [Required, StringLength(256)] public string Url { get; set; } [Required, StringLength(256)] public string Title { get; set; } public string Description { get; set; } public string Category { get; set; } public string[] Tags { get; set; } public DateTime? CreatedOn { get; set; } public string CreatedBy { get; set; } public int? CreatedById { get; set; } public DateTime? ModifiedOn { get; set; } public string ModifiedBy { get; set; } public int? ModifiedById { get; set; } } }
35.189655
107
0.55169
[ "MIT" ]
mattjcowan/foxvalleymeetup-servicestack
src/FoxValleyMeetup.Web/Configurations/c05_Bookmarks/BookmarksService.cs
6,123
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DungeonCrawl")] [assembly: AssemblyProduct("DungeonCrawl")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyDescription("")] [assembly: AssemblyCompany("")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("1c2aaf91-d0eb-498a-8921-6fdd6b4b1fce")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.756757
84
0.745168
[ "CC0-1.0" ]
KarlitoBandito/DungeonCrawl
DungeonCrawl/DungeonCrawl/Properties/AssemblyInfo.cs
1,400
C#
namespace jsxbin_to_jsx.JsxbinDecoding { public interface INode { NodeType NodeType { get; } string Marker { get; } void Decode(); string PrettyPrint(); bool PrintStructure { get; set; } int IndentLevel { get; set; } double JsxbinVersion { get; } string DecodeId(); bool DecodeBool(); } }
23.375
41
0.564171
[ "MIT" ]
892768447/jsxbin-to-jsx-converter
jsxbin_to_jsx/JsxbinDecoding/INode.cs
376
C#
#region using KoiVM.Runtime.Dynamic; using KoiVM.Runtime.Execution; #endregion namespace KoiVM.Runtime.OpCodes { internal class NorDword : IOpCode { public byte Code => Constants.OP_NOR_DWORD; public void Run(VMContext ctx, out ExecutionState state) { var sp = ctx.Registers[Constants.REG_SP].U4; var op1Slot = ctx.Stack[sp - 1]; var op2Slot = ctx.Stack[sp]; sp -= 1; ctx.Stack.SetTopPosition(sp); ctx.Registers[Constants.REG_SP].U4 = sp; var slot = new VMSlot(); slot.U4 = ~(op1Slot.U4 | op2Slot.U4); ctx.Stack[sp] = slot; var mask = (byte) (Constants.FL_ZERO | Constants.FL_SIGN); var fl = ctx.Registers[Constants.REG_FL].U1; Utils.UpdateFL(op1Slot.U4, op2Slot.U4, slot.U4, slot.U4, ref fl, mask); ctx.Registers[Constants.REG_FL].U1 = fl; state = ExecutionState.Next; } } internal class NorQword : IOpCode { public byte Code => Constants.OP_NOR_QWORD; public void Run(VMContext ctx, out ExecutionState state) { var sp = ctx.Registers[Constants.REG_SP].U4; var op1Slot = ctx.Stack[sp - 1]; var op2Slot = ctx.Stack[sp]; sp -= 1; ctx.Stack.SetTopPosition(sp); ctx.Registers[Constants.REG_SP].U4 = sp; var slot = new VMSlot(); slot.U8 = ~(op1Slot.U8 | op2Slot.U8); ctx.Stack[sp] = slot; var mask = (byte) (Constants.FL_ZERO | Constants.FL_SIGN); var fl = ctx.Registers[Constants.REG_FL].U1; Utils.UpdateFL(op1Slot.U8, op2Slot.U8, slot.U8, slot.U8, ref fl, mask); ctx.Registers[Constants.REG_FL].U1 = fl; state = ExecutionState.Next; } } }
30.704918
83
0.5622
[ "MIT" ]
BedTheGod/ConfuserEx-Mod-By-Bed
KoiVM.Runtime/OpCodes/Nor.cs
1,875
C#
/* * Copyright (c) 2012-2019 Snowflake Computing Inc. All rights reserved. */ using System; using System.ComponentModel; using System.Collections.Generic; using System.Data; using System.Globalization; using System.Text; using System.Threading; using Snowflake.Data.Log; using Snowflake.Data.Client; namespace Snowflake.Data.Core { public enum SFDataType { None, FIXED, REAL, TEXT, DATE, VARIANT, TIMESTAMP_LTZ, TIMESTAMP_NTZ, TIMESTAMP_TZ, OBJECT, BINARY, TIME, BOOLEAN, ARRAY } class SFDataConverter { private static readonly SFLogger Logger = SFLoggerFactory.GetLogger<SFDataConverter>(); private static readonly DateTime UnixEpoch = new DateTime( 1970, 1, 1, 0, 0, 0, DateTimeKind.Utc ); private Dictionary<Type, TypeConverter> typeConverters = new Dictionary<Type, TypeConverter>(); internal SFDataConverter() { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; } internal object ConvertToCSharpVal( string srcVal, SFDataType srcType, Type destType ) { //Logger.DebugFmt("src value: {0}, srcType: {1}, destType: {2}", srcVal, srcType, destType); if( srcVal == null ) return DBNull.Value; if( destType == typeof( short ) || destType == typeof( int ) || destType == typeof( long ) || destType == typeof( Guid ) || destType == typeof( double ) || destType == typeof( float ) || destType == typeof( decimal ) ) { if( !typeConverters.ContainsKey( destType ) ) { typeConverters.Add( destType, TypeDescriptor.GetConverter( destType ) ); } return typeConverters[ destType ].ConvertFrom( srcVal ); } else if( destType == typeof( Boolean ) ) { return srcVal.Equals( "1", StringComparison.OrdinalIgnoreCase ) || srcVal.Equals( "true", StringComparison.OrdinalIgnoreCase ); } else if( destType == typeof( string ) ) { return srcVal; } else if( destType == typeof( DateTime ) ) { return ConvertToDateTime( srcVal, srcType ); } else if( destType == typeof( DateTimeOffset ) ) { return ConvertToDateTimeOffset( srcVal, srcType ); } else if( destType == typeof( byte[] ) ) { return srcType == SFDataType.BINARY ? HexToBytes( srcVal ) : Encoding.UTF8.GetBytes( srcVal ); } else { throw new SnowflakeDbException( SFError.INTERNAL_ERROR, "Invalid destination type." ); } } private static DateTime ConvertToDateTime( string srcVal, SFDataType srcType ) { switch( srcType ) { case SFDataType.DATE: long srcValLong = Int64.Parse( srcVal ); return UnixEpoch.AddDays( srcValLong ); case SFDataType.TIME: case SFDataType.TIMESTAMP_NTZ: Tuple<long, long> secAndNsec = ExtractTimestamp( srcVal ); var tickDiff = secAndNsec.Item1 * 10000000L + secAndNsec.Item2 / 100L; return UnixEpoch.AddTicks( tickDiff ); default: throw new SnowflakeDbException( SFError.INVALID_DATA_CONVERSION, srcVal, srcType, typeof( DateTime ) ); } } private static DateTimeOffset ConvertToDateTimeOffset( string srcVal, SFDataType srcType ) { switch( srcType ) { case SFDataType.TIMESTAMP_TZ: int spaceIndex = srcVal.IndexOf( ' ' ); if( spaceIndex == -1 ) { throw new SnowflakeDbException( SFError.INTERNAL_ERROR, $"Invalid timestamp_tz value: {srcVal}" ); } else { Tuple<long, long> secAndNsecTZ = ExtractTimestamp( srcVal.Substring( 0, spaceIndex ) ); int offset = Int32.Parse( srcVal.Substring( spaceIndex + 1, srcVal.Length - spaceIndex - 1 ) ); TimeSpan offSetTimespan = new TimeSpan( ( offset - 1440 ) / 60, 0, 0 ); return new DateTimeOffset( UnixEpoch.Ticks + ( secAndNsecTZ.Item1 * 1000 * 1000 * 1000 + secAndNsecTZ.Item2 ) / 100, TimeSpan.Zero ).ToOffset( offSetTimespan ); } case SFDataType.TIMESTAMP_LTZ: Tuple<long, long> secAndNsecLTZ = ExtractTimestamp( srcVal ); return new DateTimeOffset( UnixEpoch.Ticks + ( secAndNsecLTZ.Item1 * 1000 * 1000 * 1000 + secAndNsecLTZ.Item2 ) / 100, TimeSpan.Zero ).ToLocalTime(); default: throw new SnowflakeDbException( SFError.INVALID_DATA_CONVERSION, srcVal, srcType, typeof( DateTimeOffset ).ToString() ); } } private static Tuple<long, long> ExtractTimestamp( string srcVal ) { int dotIndex = srcVal.IndexOf( '.' ); if( dotIndex == -1 ) { return Tuple.Create( Int64.Parse( srcVal ), (long)0 ); } else { var intPart = Int64.Parse( srcVal.Substring( 0, dotIndex ) ); var decimalPartLength = srcVal.Length - dotIndex - 1; var decimalPartStr = srcVal.Substring( dotIndex + 1, decimalPartLength ); var decimalPart = Int64.Parse( decimalPartStr ); // If the decimal part contained less than nine characters, we must convert the value to nanoseconds by // multiplying by 10^[precision difference]. if( decimalPartLength < 9 ) { decimalPart *= (int)Math.Pow( 10, 9 - decimalPartLength ); } return Tuple.Create( intPart, decimalPart ); } } internal static Tuple<string, string> csharpTypeValToSfTypeVal( DbType srcType, object srcVal ) { string destType; string destVal; var srcValAsCultureInvariantString = ( srcVal == DBNull.Value ) ? null : string.Format( CultureInfo.InvariantCulture, "{0}", srcVal ); switch( srcType ) { case DbType.Decimal: case DbType.Int16: case DbType.Int32: case DbType.Int64: case DbType.UInt16: case DbType.UInt32: case DbType.UInt64: case DbType.VarNumeric: destType = SFDataType.FIXED.ToString(); destVal = srcValAsCultureInvariantString; break; case DbType.Boolean: destType = SFDataType.BOOLEAN.ToString(); destVal = srcValAsCultureInvariantString; break; case DbType.Double: destType = SFDataType.REAL.ToString(); destVal = srcValAsCultureInvariantString; break; case DbType.Guid: case DbType.String: case DbType.StringFixedLength: destType = SFDataType.TEXT.ToString(); destVal = srcValAsCultureInvariantString; break; case DbType.Date: destType = SFDataType.DATE.ToString(); if( srcVal.GetType() != typeof( DateTime ) ) { throw new SnowflakeDbException( SFError.INVALID_DATA_CONVERSION, srcVal, srcVal.GetType().ToString(), DbType.Date.ToString() ); } else { DateTime dt = ( (DateTime)srcVal ).Date; var ts = dt.Subtract( UnixEpoch ); long millis = (long)( ts.TotalMilliseconds ); destVal = millis.ToString(); } break; case DbType.Time: destType = SFDataType.TIME.ToString(); if( srcVal.GetType() != typeof( DateTime ) ) { throw new SnowflakeDbException( SFError.INVALID_DATA_CONVERSION, srcVal, srcVal.GetType().ToString(), DbType.Time.ToString() ); } else { DateTime srcDt = ( (DateTime)srcVal ); long nanoSinceMidNight = (long)( srcDt.Ticks - srcDt.Date.Ticks ) * 100L; destVal = nanoSinceMidNight.ToString(); } break; case DbType.DateTime: destType = SFDataType.TIMESTAMP_NTZ.ToString(); if( srcVal.GetType() != typeof( DateTime ) ) { throw new SnowflakeDbException( SFError.INVALID_DATA_CONVERSION, srcVal, srcVal.GetType().ToString(), DbType.DateTime.ToString() ); } else { DateTime srcDt = (DateTime)srcVal; var diff = srcDt.Subtract( UnixEpoch ); var tickDiff = diff.Ticks; destVal = $"{tickDiff}00"; // Cannot multiple tickDiff by 100 because long might overflow. } break; // by default map DateTimeoffset to TIMESTAMP_TZ case DbType.DateTimeOffset: destType = SFDataType.TIMESTAMP_TZ.ToString(); if( srcVal.GetType() != typeof( DateTimeOffset ) ) { throw new SnowflakeDbException( SFError.INVALID_DATA_CONVERSION, srcVal, srcVal.GetType().ToString(), DbType.DateTimeOffset.ToString() ); } else { DateTimeOffset dtOffset = (DateTimeOffset)srcVal; destVal = String.Format( "{0} {1}", ( dtOffset.UtcTicks - UnixEpoch.Ticks ) * 100L, dtOffset.Offset.TotalMinutes + 1440 ); } break; case DbType.Binary: destType = SFDataType.BINARY.ToString(); if( srcVal.GetType() != typeof( byte[] ) ) { throw new SnowflakeDbException( SFError.INVALID_DATA_CONVERSION, srcVal, srcVal.GetType().ToString(), DbType.Binary.ToString() ); } else { destVal = BytesToHex( (byte[])srcVal ); } break; default: destType = SFDataType.TEXT.ToString(); destVal = srcValAsCultureInvariantString; break; } return Tuple.Create( destType, destVal ); } private static string BytesToHex( byte[] bytes ) { StringBuilder hexBuilder = new StringBuilder( bytes.Length * 2 ); foreach( byte b in bytes ) { hexBuilder.AppendFormat( "{0:x2}", b ); } return hexBuilder.ToString(); } private static byte[] HexToBytes( string hex ) { int NumberChars = hex.Length; byte[] bytes = new byte[ NumberChars / 2 ]; for( int i = 0; i < NumberChars; i += 2 ) bytes[ i / 2 ] = Convert.ToByte( hex.Substring( i, 2 ), 16 ); return bytes; } internal static string csharpValToSfVal( SFDataType sfDataType, object srcVal ) { switch( sfDataType ) { case SFDataType.TIMESTAMP_LTZ: if( srcVal.GetType() != typeof( DateTimeOffset ) ) { throw new SnowflakeDbException( SFError.INVALID_DATA_CONVERSION, srcVal, srcVal.GetType().ToString(), SFDataType.TIMESTAMP_LTZ.ToString() ); } else { return ( (long)( ( (DateTimeOffset)srcVal ).UtcTicks - UnixEpoch.Ticks ) * 100 ).ToString(); } case SFDataType.TIMESTAMP_TZ: return ""; // ( (long)( ( (DateTime)srcVal ).Ticks - UnixEpoch.Ticks ) * 100 ).ToString(); case SFDataType.TIMESTAMP_NTZ: return ( (long)( ( (DateTime)srcVal ).Ticks - UnixEpoch.Ticks ) * 100 ).ToString(); //return $"{( (DateTime)srcVal ).ToString( "s" ).Replace( "T", " " )}"; default: return srcVal.ToString(); } } internal static string toDateString( DateTime date, string formatter ) { // change formatter from "YYYY-MM-DD" to "yyyy-MM-dd" formatter = formatter.Replace( "Y", "y" ).Replace( "m", "M" ).Replace( "D", "d" ); return date.ToString( formatter ); } } }
42.262687
147
0.481636
[ "Apache-2.0" ]
jmcasal/snowflake-connector-net
Snowflake.Data/Core/SFDataConverter.cs
14,160
C#
//---------------------- // <auto-generated> // Generated using the NSwag toolchain v13.0.5.0 (NJsonSchema v10.0.22.0 (Newtonsoft.Json v11.0.0.0)) (http://NSwag.org) // </auto-generated> //---------------------- #pragma warning disable 108 // Disable "CS0108 '{derivedDto}.ToJson()' hides inherited member '{dtoBase}.ToJson()'. Use the new keyword if hiding was intended." #pragma warning disable 114 // Disable "CS0114 '{derivedDto}.RaisePropertyChanged(String)' hides inherited member 'dtoBase.RaisePropertyChanged(String)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword." #pragma warning disable 472 // Disable "CS0472 The result of the expression is always 'false' since a value of type 'Int32' is never equal to 'null' of type 'Int32?' #pragma warning disable 1573 // Disable "CS1573 Parameter '...' has no matching param tag in the XML comment for ... #pragma warning disable 1591 // Disable "CS1591 Missing XML comment for publicly visible type or member ..." namespace User { [System.CodeDom.Compiler.GeneratedCode("NSwag", "13.0.5.0 (NJsonSchema v10.0.22.0 (Newtonsoft.Json v11.0.0.0))")] public partial class UserClient { private string _baseUrl = "http://localhost:7071/api"; private System.Net.Http.HttpClient _httpClient; private System.Lazy<Newtonsoft.Json.JsonSerializerSettings> _settings; public UserClient(System.Net.Http.HttpClient httpClient) { _httpClient = httpClient; _settings = new System.Lazy<Newtonsoft.Json.JsonSerializerSettings>(() => { var settings = new Newtonsoft.Json.JsonSerializerSettings(); UpdateJsonSerializerSettings(settings); return settings; }); } public string BaseUrl { get { return _baseUrl; } set { _baseUrl = value; } } protected Newtonsoft.Json.JsonSerializerSettings JsonSerializerSettings { get { return _settings.Value; } } partial void UpdateJsonSerializerSettings(Newtonsoft.Json.JsonSerializerSettings settings); partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, string url); partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, System.Text.StringBuilder urlBuilder); partial void ProcessResponse(System.Net.Http.HttpClient client, System.Net.Http.HttpResponseMessage response); /// <returns>Operation succeeded</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public System.Threading.Tasks.Task SendAsync(User body) { return SendAsync(body, System.Threading.CancellationToken.None); } /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Operation succeeded</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public async System.Threading.Tasks.Task SendAsync(User body, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/UserLogin"); var client_ = _httpClient; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(body, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) headers_[item_.Key] = item_.Value; } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200") { return; } else if (status_ == "400") { string responseText_ = ( response_.Content == null ) ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("Bad request", (int)response_.StatusCode, responseText_, headers_, null); } else if (status_ != "200" && status_ != "204") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null); } } finally { if (response_ != null) response_.Dispose(); } } } finally { } } protected struct ObjectResponseResult<T> { public ObjectResponseResult(T responseObject, string responseText) { this.Object = responseObject; this.Text = responseText; } public T Object { get; } public string Text { get; } } public bool ReadResponseAsString { get; set; } protected virtual async System.Threading.Tasks.Task<ObjectResponseResult<T>> ReadObjectResponseAsync<T>(System.Net.Http.HttpResponseMessage response, System.Collections.Generic.IReadOnlyDictionary<string, System.Collections.Generic.IEnumerable<string>> headers) { if (response == null || response.Content == null) { return new ObjectResponseResult<T>(default(T), string.Empty); } if (ReadResponseAsString) { var responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(false); try { var typedBody = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(responseText, JsonSerializerSettings); return new ObjectResponseResult<T>(typedBody, responseText); } catch (Newtonsoft.Json.JsonException exception) { var message = "Could not deserialize the response body string as " + typeof(T).FullName + "."; throw new ApiException(message, (int)response.StatusCode, responseText, headers, exception); } } else { try { using (var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) using (var streamReader = new System.IO.StreamReader(responseStream)) using (var jsonTextReader = new Newtonsoft.Json.JsonTextReader(streamReader)) { var serializer = Newtonsoft.Json.JsonSerializer.Create(JsonSerializerSettings); var typedBody = serializer.Deserialize<T>(jsonTextReader); return new ObjectResponseResult<T>(typedBody, string.Empty); } } catch (Newtonsoft.Json.JsonException exception) { var message = "Could not deserialize the response body stream as " + typeof(T).FullName + "."; throw new ApiException(message, (int)response.StatusCode, string.Empty, headers, exception); } } } private string ConvertToString(object value, System.Globalization.CultureInfo cultureInfo) { if (value is System.Enum) { string name = System.Enum.GetName(value.GetType(), value); if (name != null) { var field = System.Reflection.IntrospectionExtensions.GetTypeInfo(value.GetType()).GetDeclaredField(name); if (field != null) { var attribute = System.Reflection.CustomAttributeExtensions.GetCustomAttribute(field, typeof(System.Runtime.Serialization.EnumMemberAttribute)) as System.Runtime.Serialization.EnumMemberAttribute; if (attribute != null) { return attribute.Value != null ? attribute.Value : name; } } } } else if (value is bool) { return System.Convert.ToString(value, cultureInfo).ToLowerInvariant(); } else if (value is byte[]) { return System.Convert.ToBase64String((byte[]) value); } else if (value != null && value.GetType().IsArray) { var array = System.Linq.Enumerable.OfType<object>((System.Array) value); return string.Join(",", System.Linq.Enumerable.Select(array, o => ConvertToString(o, cultureInfo))); } return System.Convert.ToString(value, cultureInfo); } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.0.22.0 (Newtonsoft.Json v11.0.0.0)")] public partial class User { [Newtonsoft.Json.JsonProperty("userName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string UserName { get; set; } [Newtonsoft.Json.JsonProperty("password", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Password { get; set; } [Newtonsoft.Json.JsonProperty("userType", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string UserType { get; set; } } [System.CodeDom.Compiler.GeneratedCode("NSwag", "13.0.5.0 (NJsonSchema v10.0.22.0 (Newtonsoft.Json v11.0.0.0))")] public partial class ApiException : System.Exception { public int StatusCode { get; private set; } public string Response { get; private set; } public System.Collections.Generic.IReadOnlyDictionary<string, System.Collections.Generic.IEnumerable<string>> Headers { get; private set; } public ApiException(string message, int statusCode, string response, System.Collections.Generic.IReadOnlyDictionary<string, System.Collections.Generic.IEnumerable<string>> headers, System.Exception innerException) : base(message + "\n\nStatus: " + statusCode + "\nResponse: \n" + response.Substring(0, response.Length >= 512 ? 512 : response.Length), innerException) { StatusCode = statusCode; Response = response; Headers = headers; } public override string ToString() { return string.Format("HTTP Response: \n\n{0}\n\n{1}", Response, base.ToString()); } } [System.CodeDom.Compiler.GeneratedCode("NSwag", "13.0.5.0 (NJsonSchema v10.0.22.0 (Newtonsoft.Json v11.0.0.0))")] public partial class ApiException<TResult> : ApiException { public TResult Result { get; private set; } public ApiException(string message, int statusCode, string response, System.Collections.Generic.IReadOnlyDictionary<string, System.Collections.Generic.IEnumerable<string>> headers, TResult result, System.Exception innerException) : base(message, statusCode, response, headers, innerException) { Result = result; } } } #pragma warning restore 1591 #pragma warning restore 1573 #pragma warning restore 472 #pragma warning restore 114 #pragma warning restore 108
50.194757
269
0.590509
[ "MIT" ]
Yanivv77/PromoIt
Client/UI/obj/UserClient.cs
13,404
C#
using PKISharp.WACS.Clients.DNS; using PKISharp.WACS.Services; using System.Linq; namespace PKISharp.WACS.Plugins.ValidationPlugins.Dns { class Manual : DnsValidation<ManualOptions, Manual> { private IInputService _input; public Manual( LookupClientProvider dnsClient, ILogService log, IInputService input, ManualOptions options, string identifier) : base(dnsClient, log, options, identifier) { // Usually it's a big no-no to rely on user input in validation plugin // because this should be able to run unattended. This plugin is for testing // only and therefor we will allow it. Future versions might be more advanced, // e.g. shoot an email to an admin and complete the order later. _input = input; } public override void CreateRecord(string recordName, string token) { _input.Show("Domain", _identifier, true); _input.Show("Record", recordName); _input.Show("Type", "TXT"); _input.Show("Content", $"\"{token}\""); _input.Show("Note 1", "Some DNS control panels add quotes automatically. Only one set is required."); _input.Show("Note 2", "Make sure your name servers are synchronised, this may take several minutes!"); _input.Wait("Please press enter after you've created and verified the record"); // Pre-pre-validate, allowing the manual user to correct mistakes while (true) { if (PreValidate()) { break; } else { var retry = _input.PromptYesNo( "The correct record is not yet found by the local resolver. " + "Check your configuration and/or wait for the name servers to " + "synchronize and press <Enter> to try again. Answer 'N' to " + "try ACME validation anyway.", true); if (!retry) { break; } } } } public override void DeleteRecord(string recordName, string token) { _input.Show("Domain", _identifier, true); _input.Show("Record", recordName); _input.Show("Type", "TXT"); _input.Show("Content", $"\"{token}\""); _input.Wait("Please press enter after you've deleted the record"); } } }
39.014706
114
0.53562
[ "Apache-2.0" ]
rdaunce/letsencrypt-win-simple
src/main/Plugins/ValidationPlugins/Dns/Manual/Manual.cs
2,655
C#
using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using Random = UnityEngine.Random; public class Dice : MonoBehaviour { public Image topFace; public List<Sprite> faces; public int result; public void Awake() { PickUp(); } public void Throw() { topFace.enabled = true; result = Random.Range(1, 6); topFace.sprite = faces[(result - 1) * 4 + Random.Range(0, 4)]; ServerManager.MessagesToSend.Add(new ServerManager.Msg {topic = "actions", payload = new List<string> {"Roll", GameManager.LocalPlayer.name, result.ToString()}}); } public void Throw(int forceResult) { topFace.enabled = true; result = forceResult; topFace.sprite = faces[(result - 1) * 4 + Random.Range(0, 4)]; } public void PickUp() { topFace.enabled = false; result = 0; } }
22.487805
119
0.601952
[ "MIT" ]
Manzanero/rat-race
Assets/Scripts/Dice.cs
922
C#
using System.Threading; using System.Threading.Tasks; namespace MediatR.Extensions.Autofac.DependencyInjection.Tests.Behaviors { public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> { public Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next) { return next(); } } }
33.153846
133
0.712297
[ "MIT" ]
alsami/MediatR.Extensions.Autofac.DependencyInjection
test/MediatR.Extensions.Autofac.DependencyInjection.Tests/Behaviors/LoggingBehavior.cs
433
C#
using System; using System.Collections.Generic; using System.Collections; using System.Linq; using System.Text; using Handelabra.Sentinels.Engine.Controller; using Handelabra.Sentinels.Engine.Model; using Jp.ParahumansOfTheWormverse.Utility; namespace Jp.ParahumansOfTheWormverse.TheSimurgh { public class ATragicEndCardController : CardController { public ATragicEndCardController(Card card, TurnTakerController controller) : base(card, controller) {} public override IEnumerator Play() { // "When this card is flipped face up, destroy all non-character card targets. var results = new List<DestroyCardAction>(); var e = GameController.DestroyCards( DecisionMaker, new LinqCardCriteria(c => c.IsTarget && !c.IsCharacter, "non-character targets", useCardsSuffix: false), storedResults: results, cardSource: GetCardSource() ); if (UseUnityCoroutines) { yield return GameController.StartCoroutine(e); } else { GameController.ExhaustCoroutine(e); } // {TheSimurghCharacter} deals each hero target X projectile damage, where X is the number of targets destroyed this way.", var destroyedCount = results.Count(dca => dca.WasCardDestroyed); e = DealDamage(CharacterCard, c => c.Is().Hero().Target(), destroyedCount, DamageType.Projectile); if (UseUnityCoroutines) { yield return GameController.StartCoroutine(e); } else { GameController.ExhaustCoroutine(e); } } } }
33.490566
135
0.609577
[ "BSD-2-Clause" ]
jamespicone/potw
Mod/Villains/TheSimurgh/Cards/Traps/ATragicEndCardController.cs
1,777
C#
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Reflection; using System.Linq; using System.Xml.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Amazon.CodeAnalysis.Shared; namespace Amazon.DataPipeline.CodeAnalysis { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class PropertyValueAssignmentAnalyzer : AbstractPropertyValueAssignmentAnalyzer { public override string GetServiceName() { return "DataPipeline"; } } }
27.48
91
0.751092
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/DataPipeline/Generated/PropertyValueAssignmentAnalyzer.cs
687
C#
// Copyright (c) KhooverSoft. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Khooversoft.Toolbox; using Khooversoft.Toolbox.Actor; using Khooversoft.Toolbox.Security; using Khooversoft.Toolbox.Services; using System.Threading.Tasks; namespace Khooversoft.Net { /// <summary> /// Token client actor, cache and retrieve updated token from authorization server /// </summary> public class TokenClientActor : ActorBase, ITokenClientActor { private readonly ICertificateRepository _certificateRepository; private readonly IRestClientConfiguration _restClientConfiguration; private IClientTokenManagerConfiguration _clientTokenManagerConfiguration; private IClientTokenManager _clientTokenManager; private JwtTokenDetails _jwtTokenDetails; public TokenClientActor(ActorKey actorKey, IActorManager actorManager, ICertificateRepository certificateRepository, IRestClientConfiguration restClientConfiguration) : base(actorKey, actorManager) { Verify.IsNotNull(nameof(certificateRepository), certificateRepository); Verify.IsNotNull(nameof(restClientConfiguration), restClientConfiguration); _certificateRepository = certificateRepository; _restClientConfiguration = restClientConfiguration; } public TokenClientActor( ActorKey actorKey, IActorManager actorManager, ICertificateRepository certificateRepository, IRestClientConfiguration restClientConfiguration, IClientTokenManagerConfiguration clientTokenManagerConfiguration) : this(actorKey, actorManager, certificateRepository, restClientConfiguration) { Verify.IsNotNull(nameof(clientTokenManagerConfiguration), clientTokenManagerConfiguration); _clientTokenManagerConfiguration = clientTokenManagerConfiguration; _clientTokenManager = new ClientTokenManager(_certificateRepository, _clientTokenManagerConfiguration, _restClientConfiguration); } public Task SetConfiguration(IWorkContext context, IClientTokenManagerConfiguration clientTokenManagerConfiguration) { Verify.IsNotNull(nameof(clientTokenManagerConfiguration), clientTokenManagerConfiguration); Verify.Assert(clientTokenManagerConfiguration.TokenKey.Value == ActorKey.VectorKey, "Configuration does not match actor key"); _clientTokenManagerConfiguration = clientTokenManagerConfiguration; _clientTokenManager = new ClientTokenManager(_certificateRepository, _clientTokenManagerConfiguration, _restClientConfiguration); return Task.FromResult(0); } /// <summary> /// Get token, return cache or get new token /// </summary> /// <param name="context">context</param> /// <returns>Api key</returns> public async Task<string> GetApiKey(IWorkContext context) { Verify.Assert(_clientTokenManager != null, "Configuration has not been set"); if (!(await Validate(context))) { return null; } return _jwtTokenDetails.ApiKey; } /// <summary> /// Validate current JWT server authorization token and renew if expired /// </summary> /// <param name="context">context</param> /// <returns>true if authorization server's authorization token is valid, false if not</returns> private async Task<bool> Validate(IWorkContext context, bool renewIfRequired = true) { Verify.IsNotNull(nameof(context), context); if (_jwtTokenDetails != null && !_jwtTokenDetails.IsExpired) { return true; } string requestToken = await _clientTokenManager.CreateRequestToken(context); if (requestToken == null || !renewIfRequired) { return false; } RestResponse<string> response = await _clientTokenManager.RequestServerAuthorizationToken(context, requestToken); response.AssertSuccessStatusCode(context); Verify.IsNotNull(nameof(response.Value), response.Value); JwtTokenDetails jwtToken = await _clientTokenManager.ParseAuthorizationToken(context, response.Value); _jwtTokenDetails = jwtToken; return true; } } }
43.028302
174
0.693488
[ "MIT" ]
khoover768/Toolbox
Src/Dev/Khooversoft.Net/Services/TokenClientActor.cs
4,563
C#
using System; using BenchmarkDotNet.Running; using Tedd.RandomUtils.Benchmarks.Benchmarks; namespace Tedd.RandomUtils.Benchmarks { class Program { static void Main(string[] args) { { var speedTest = new SpeedTest_Single(); speedTest.GlobalSetup(); speedTest.IterationSetup(); speedTest.SystemRandom(); speedTest.LehmerNaive(); speedTest.LehmerStatic(); speedTest.LehmerSIMD(); } { var speedTest = new SpeedTest_Array(); speedTest.GlobalSetup(); speedTest.IterationSetup(); speedTest.SystemRandom(); speedTest.LehmerNaive(); //speedTest.LehmerStatic(); speedTest.LehmerSIMD(); } { var speedTest = new SpeedTest_All(); speedTest.GlobalSetup(); speedTest.IterationSetup(); speedTest.SystemRandom(); speedTest.CryptoRandom(); speedTest.FastRandom(); speedTest.FastRandomStatic(); speedTest.GlobalCleanup(); } { var speedTest = new SpeedTest_Double(); speedTest.GlobalSetup(); speedTest.IterationSetup(); speedTest.SystemRandom(); speedTest.FastRandom(); } //var summary1 = BenchmarkRunner.Run<SpeedTest_Single>(); //var summary2 = BenchmarkRunner.Run<SpeedTest_Array>(); //var summary3 = BenchmarkRunner.Run<SpeedTest_All>(); var summary4 = BenchmarkRunner.Run<SpeedTest_Double>(); } } }
28.3125
69
0.511038
[ "MIT" ]
tedd/Tedd.RandomUtils
src/Tedd.RandomUtils.Benchmarks/Program.cs
1,814
C#
using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Linq; using Discord; using NLog; using NadekoBot.Core.Services.Database.Models; using NadekoBot.Common; using Newtonsoft.Json; using System.IO; namespace NadekoBot.Core.Services.Impl { public class Localization : ILocalization { private readonly Logger _log; private readonly DbService _db; public ConcurrentDictionary<ulong, CultureInfo> GuildCultureInfos { get; } public CultureInfo DefaultCultureInfo { get; private set; } = CultureInfo.CurrentCulture; private static readonly Dictionary<string, CommandData> _commandData; static Localization() { _commandData = JsonConvert.DeserializeObject<Dictionary<string, CommandData>>( File.ReadAllText("./_strings/cmd/command_strings.json")); } private Localization() { } public Localization(IBotConfigProvider bcp, NadekoBot bot, DbService db) { _log = LogManager.GetCurrentClassLogger(); var cultureInfoNames = bot.AllGuildConfigs.ToDictionary(x => x.GuildId, x => x.Locale); var defaultCulture = bcp.BotConfig.Locale; _db = db; if (string.IsNullOrWhiteSpace(defaultCulture)) DefaultCultureInfo = new CultureInfo("en-US"); else { try { DefaultCultureInfo = new CultureInfo(defaultCulture); } catch { _log.Warn("Unable to load default bot's locale/language. Using en-US."); DefaultCultureInfo = new CultureInfo("en-US"); } } GuildCultureInfos = new ConcurrentDictionary<ulong, CultureInfo>(cultureInfoNames.ToDictionary(x => x.Key, x => { CultureInfo cultureInfo = null; try { if (x.Value == null) return null; cultureInfo = new CultureInfo(x.Value); } catch { } return cultureInfo; }).Where(x => x.Value != null)); } public void SetGuildCulture(IGuild guild, CultureInfo ci) => SetGuildCulture(guild.Id, ci); public void SetGuildCulture(ulong guildId, CultureInfo ci) { if (ci == DefaultCultureInfo) { RemoveGuildCulture(guildId); return; } using (var uow = _db.UnitOfWork) { var gc = uow.GuildConfigs.For(guildId, set => set); gc.Locale = ci.Name; uow.Complete(); } GuildCultureInfos.AddOrUpdate(guildId, ci, (id, old) => ci); } public void RemoveGuildCulture(IGuild guild) => RemoveGuildCulture(guild.Id); public void RemoveGuildCulture(ulong guildId) { if (GuildCultureInfos.TryRemove(guildId, out var _)) { using (var uow = _db.UnitOfWork) { var gc = uow.GuildConfigs.For(guildId, set => set); gc.Locale = null; uow.Complete(); } } } public void SetDefaultCulture(CultureInfo ci) { using (var uow = _db.UnitOfWork) { var bc = uow.BotConfig.GetOrCreate(set => set); bc.Locale = ci.Name; uow.Complete(); } DefaultCultureInfo = ci; } public void ResetDefaultCulture() => SetDefaultCulture(CultureInfo.CurrentCulture); public CultureInfo GetCultureInfo(IGuild guild) => GetCultureInfo(guild?.Id); public CultureInfo GetCultureInfo(ulong? guildId) { if (guildId == null) return DefaultCultureInfo; GuildCultureInfos.TryGetValue(guildId.Value, out CultureInfo info); return info ?? DefaultCultureInfo; } public static CommandData LoadCommand(string key) { _commandData.TryGetValue(key, out var toReturn); if (toReturn == null) return new CommandData { Cmd = key, Desc = key, Usage = new[] { key }, }; return toReturn; } } }
31.684932
123
0.529183
[ "MIT" ]
1337r34p3r/shadow-bot
NadekoBot.Core/Services/Impl/Localization.cs
4,628
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Rhea.Data { /// <summary> /// 房产Collection名称 /// </summary> public static class EstateCollection { #region Field /// <summary> /// 校区表 /// campus /// </summary> public static readonly string Campus = "campus"; /// <summary> /// 建筑表 /// building /// </summary> public static readonly string Building = "building"; /// <summary> /// 房间表 /// room /// </summary> public static readonly string Room = "room"; /// <summary> /// 校区备份表 /// campusBackup /// </summary> public static readonly string CampusBackup = "campusBackup"; /// <summary> /// 建筑备份表 /// buildingBackup /// </summary> public static readonly string BuildingBackup = "buildingBackup"; /// <summary> /// 房间备份表 /// roomBackup /// </summary> public static readonly string RoomBackup = "roomBackup"; /// <summary> /// 房间归档表 /// roomArchive /// </summary> public static readonly string RoomArchive = "roomArchive"; /// <summary> /// 青教住户表 /// inhabitant /// </summary> public static readonly string Inhabitant = "inhabitant"; /// <summary> /// 青教入住记录表 /// resideRecord /// </summary> public static readonly string ResideRecord = "resideRecord"; /// <summary> /// 青教业务记录表 /// apartmentTransaction /// </summary> public static readonly string ApartmentTransaction = "apartmentTransaction"; #endregion //Field } }
24.103896
84
0.521013
[ "BSD-3-Clause" ]
robertzml/Rhea
Rhea.Data/EstateCollection.cs
1,962
C#
// ----------------------------------------------------------------------- // <copyright file="RemoveDuplicateNames.cs" company="Ubiquity.NET Contributors"> // Copyright (c) Ubiquity.NET Contributors. All rights reserved. // </copyright> // ----------------------------------------------------------------------- using System.Collections.Generic; using CppSharp.AST; using CppSharp.Passes; namespace LlvmBindingsGenerator.Passes { internal class IgnoreDuplicateNamesPass : TranslationUnitPass { public IgnoreDuplicateNamesPass( ) { VisitOptions.VisitClassBases = false; VisitOptions.VisitClassFields = false; VisitOptions.VisitClassMethods = false; VisitOptions.VisitClassProperties = false; VisitOptions.VisitClassTemplateSpecializations = false; VisitOptions.VisitEventParameters = false; VisitOptions.VisitFunctionParameters = false; VisitOptions.VisitFunctionReturnType = false; VisitOptions.VisitNamespaceEnums = true; VisitOptions.VisitNamespaceEvents = false; VisitOptions.VisitNamespaceTemplates = false; VisitOptions.VisitNamespaceTypedefs = true; VisitOptions.VisitNamespaceVariables = true; VisitOptions.VisitPropertyAccessors = false; VisitOptions.VisitTemplateArguments = false; } public override bool VisitASTContext( ASTContext context ) { VisitedNames.Clear( ); foreach( TranslationUnit unit in context.GeneratedUnits( ) ) { VisitTranslationUnit( unit ); } return true; } public override bool VisitFunctionDecl( Function function ) { if( !base.VisitFunctionDecl( function ) ) { return false; } if( !VisitedNames.Add( function.Name ) ) { function.Ignore = true; } return true; } private readonly HashSet<string> VisitedNames = new HashSet<string>(); } }
32.606061
81
0.574349
[ "Apache-2.0" ]
kevinhartman/Llvm.NET
src/Interop/LlvmBindingsGenerator/Passes/IgnoreDuplicateNamesPass.cs
2,154
C#
namespace GBX.NET.Engines.Game; [Node(0x03145000)] public sealed class CGameCtnMediaBlockShoot : CGameCtnMediaBlock, CGameCtnMediaBlock.IHasTwoKeys { #region Fields private TimeSpan start; private TimeSpan end = TimeSpan.FromSeconds(3); #endregion #region Properties [NodeMember] public TimeSpan Start { get => start; set => start = value; } [NodeMember] public TimeSpan End { get => end; set => end = value; } #endregion #region Constructors private CGameCtnMediaBlockShoot() { } #endregion #region Chunks #region 0x000 chunk [Chunk(0x03145000)] public class Chunk03145000 : Chunk<CGameCtnMediaBlockShoot> { public override void ReadWrite(CGameCtnMediaBlockShoot n, GameBoxReaderWriter rw) { rw.Single_s(ref n.start); rw.Single_s(ref n.end); } } #endregion #endregion }
16.827586
96
0.617828
[ "Unlicense" ]
ArkadySK/gbx-net
Src/GBX.NET/Engines/Game/CGameCtnMediaBlockShoot.cs
978
C#
using Juno.Sdk.Converters; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.Json.Serialization; using System.Threading.Tasks; namespace Juno.Sdk.Models.Notifications { public class PaymentNotification : DefaultNotification<PaymentNotification.Payment> { public class Payment { public string DigitalAccountId { get; set; } public DateTime? CreatedOn { get; set; } public DateTime? Date { get; set; } public DateTime? ReleaseDate { get; set; } public decimal? Amount { get; set; } public decimal? Fee { get; set; } [JsonConverter(typeof(StringNullableEnumConverter<PaymentStatus>))] public PaymentStatus Status { get; set; } [JsonConverter(typeof(StringNullableEnumConverter<PaymentType>))] public PaymentType Type { get; set; } public DateTime? PaybackDate { get; set; } public decimal? PaybackAmount { get; set; } public PaymentCharge Charge { get; set; } public class PaymentCharge { public string Id { get; set; } public long Code { get; set; } public DateTime? DueDate { get; set; } public decimal? Amount { get; set; } } } } }
26.807692
87
0.592539
[ "MIT" ]
marivaaldo/juno-sdk-net
src/Juno.Sdk/Models/Notifications/PaymentNotification.cs
1,396
C#
using Polly; namespace TileDB.Cloud { public class Client { public static void Login(string token = default(string), string username = default(string), string password = default(string), string host=default(string)) { TileDB.Cloud.Config cfg = new Config(); if(!string.IsNullOrEmpty(token)) { cfg.GetConfig().AddApiKey("X-TILEDB-REST-API-KEY", token); cfg.GetConfig().AccessToken = token; } if(!string.IsNullOrEmpty(username)) { cfg.GetConfig().Username = username; } if(!string.IsNullOrEmpty(password)) { cfg.GetConfig().Password = password; } if(!string.IsNullOrEmpty(host)) { if (host.EndsWith("/v1")) { host = host.Remove(host.Length - "/v1".Length); } else if (host.EndsWith("/v1/")) { host = host.Remove(host.Length - "/v1/".Length); } cfg.GetConfig().BasePath = host + "/v1"; } //Save configuration to json string cloud_config_dir = Config.DefaultConfigDir; if(!System.IO.Directory.Exists(cloud_config_dir)) { try { var dirinfo = System.IO.Directory.CreateDirectory(cloud_config_dir); System.Console.WriteLine("created directory:{0}", dirinfo.ToString()); } catch (System.IO.IOException ioe) { System.Console.WriteLine("caught IOException:{0}", ioe.Message); } catch (System.UnauthorizedAccessException uae) { System.Console.WriteLine("caught UnauthorizedAccessException:{0}", uae.Message); } catch (System.Exception e) { System.Console.WriteLine("caught Exception:{0}", e.Message); } } string cloud_json_file = Config.DefaultConfigFile; System.Text.StringBuilder sb = new System.Text.StringBuilder(); System.IO.StringWriter sw = new System.IO.StringWriter(sb); using(Newtonsoft.Json.JsonWriter jsonWritter = new Newtonsoft.Json.JsonTextWriter(sw)) { jsonWritter.Formatting = Newtonsoft.Json.Formatting.Indented; jsonWritter.WriteStartObject(); if(!string.IsNullOrEmpty(cfg.GetConfig().AccessToken)) { jsonWritter.WritePropertyName("api_key"); jsonWritter.WriteStartObject(); jsonWritter.WritePropertyName("X-TILEDB-REST-API-KEY"); jsonWritter.WriteValue(cfg.GetConfig().AccessToken); jsonWritter.WriteEndObject(); } if(!string.IsNullOrEmpty(cfg.GetConfig().BasePath)) { string temp_host = cfg.GetConfig().BasePath; if (temp_host.EndsWith("/v1")) { temp_host = temp_host.Remove(temp_host.Length - "/v1".Length); } else if (temp_host.EndsWith("/v1/")) { temp_host = temp_host.Remove(temp_host.Length - "/v1/".Length); } jsonWritter.WritePropertyName("host"); jsonWritter.WriteValue(temp_host); } if(!string.IsNullOrEmpty(cfg.GetConfig().Username)) { jsonWritter.WritePropertyName("username"); jsonWritter.WriteValue(cfg.GetConfig().Username); } if (!string.IsNullOrEmpty(cfg.GetConfig().Password)) { jsonWritter.WritePropertyName("password"); jsonWritter.WriteValue(cfg.GetConfig().Password); } jsonWritter.WritePropertyName("verify_ssl"); jsonWritter.WriteValue(true); jsonWritter.WriteEndObject(); } System.IO.File.WriteAllText(cloud_json_file, sb.ToString()); _instance = new Client(cfg); TileDB.Config tdb_config = new TileDB.Config(); if (!string.IsNullOrEmpty(cfg.GetConfig().Username)) { tdb_config.set("rest.username", cfg.GetConfig().Username); } if (!string.IsNullOrEmpty(cfg.GetConfig().Password)) { tdb_config.set("rest.password", cfg.GetConfig().Password); } if (!string.IsNullOrEmpty(cfg.GetConfig().AccessToken)) { tdb_config.set("rest.token", cfg.GetConfig().AccessToken); } if (!string.IsNullOrEmpty(cfg.GetConfig().BasePath)) { string temp_host = cfg.GetConfig().BasePath; if (temp_host.EndsWith("/v1")) { temp_host = temp_host.Remove(temp_host.Length - "/v1".Length); } else if (temp_host.EndsWith("/v1/")) { temp_host = temp_host.Remove(temp_host.Length - "/v1/".Length); } if(!string.IsNullOrEmpty(temp_host)) { tdb_config.set("rest.server_address", temp_host); } } _context = new TileDB.Context(tdb_config); } private static TileDB.Context _context = new TileDB.Context(new TileDB.Config()); public static TileDB.Context GetContext() { return _context; } private static Client _instance = null; public static Client GetInstance() { if(_instance == null) { Login(); } return _instance; } protected TileDB.Cloud.Config _cfg = null; protected TileDB.Cloud.Rest.Client.ApiClient _apiClient = null; protected TileDB.Cloud.Rest.Api.ArrayApi _arrayApi = null; protected TileDB.Cloud.Rest.Api.FilesApi _filesApi = null; protected TileDB.Cloud.Rest.Api.NotebookApi _notebookApi = null; protected TileDB.Cloud.Rest.Api.OrganizationApi _organizationApi = null; protected TileDB.Cloud.Rest.Api.SqlApi _sqlApi = null; protected TileDB.Cloud.Rest.Api.TasksApi _tasksApi = null; protected TileDB.Cloud.Rest.Api.UdfApi _udfApi = null; protected TileDB.Cloud.Rest.Api.UserApi _userApi = null; public TileDB.Cloud.Config GetConfig() { return _cfg; } public TileDB.Cloud.Rest.Client.ApiClient GetApiClient() { return _apiClient; } public TileDB.Cloud.Rest.Api.ArrayApi GetArrayApi() { return _arrayApi; } public TileDB.Cloud.Rest.Api.FilesApi GetFilesApi() { return _filesApi; } public TileDB.Cloud.Rest.Api.NotebookApi GetNotebookApi() { return _notebookApi; } public TileDB.Cloud.Rest.Api.OrganizationApi GetOrganizationApi() { return _organizationApi; } public TileDB.Cloud.Rest.Api.SqlApi GetSqlApi() { return _sqlApi; } public TileDB.Cloud.Rest.Api.TasksApi GetTasksApi() { return _tasksApi; } public TileDB.Cloud.Rest.Api.UdfApi GetUdfApi() { return _udfApi; } public TileDB.Cloud.Rest.Api.UserApi GetUserApi() { return _userApi; } public Client(TileDB.Cloud.Config cfg) { _cfg = cfg; //Set timeout for restclient to 3600 seconds _cfg.GetConfig().Timeout = 3600000; _apiClient = new Rest.Client.ApiClient(_cfg.GetConfig()); _arrayApi = new Rest.Api.ArrayApi(_cfg.GetConfig()); _filesApi = new Rest.Api.FilesApi(_cfg.GetConfig()); _notebookApi = new Rest.Api.NotebookApi(_cfg.GetConfig()); _organizationApi = new Rest.Api.OrganizationApi(_cfg.GetConfig()); _sqlApi = new Rest.Api.SqlApi(_cfg.GetConfig()); _tasksApi = new Rest.Api.TasksApi(_cfg.GetConfig()); _udfApi = new Rest.Api.UdfApi(_cfg.GetConfig()); _userApi = new Rest.Api.UserApi(_cfg.GetConfig()); } #region Retry Policy private int GetPositiveIntConfigValue(string key) { int result = 0; if (_cfg != null && _cfg.GetConfig() != null && _cfg.GetConfig().ApiKey.ContainsKey(key)) { string str = _cfg.GetConfig().ApiKey[key]; if (int.TryParse(str, out int v)) { if (v > 0) { result = v; } } } return result; } public int GetRetryNumber() { int retryNumber = 3; //default value string key = "rest.retries"; int v = GetPositiveIntConfigValue(key); if(v>0) { retryNumber = v; } return retryNumber; } public int GetSleepMilliseconds() { int result = 1000; string key = "rest.sleepmilliseconds"; int v = GetPositiveIntConfigValue(key); if(v>0) { result = v; } return result; } public int GetTimeoutSeconds() { int result = 3600; string key = "rest.timeoutseconds"; int v = GetPositiveIntConfigValue(key); if (v > 0) { result = v; } return result; } public Polly.Wrap.AsyncPolicyWrap GetRetryAsyncPolicyWrap() { int retryNumber = GetRetryNumber(); int retrySleep = GetSleepMilliseconds(); int timeoutSeconds = GetTimeoutSeconds(); var retry = Polly.Policy.Handle<Rest.Client.ApiException>() .WaitAndRetryAsync(retryNumber, retryAttemp => System.TimeSpan.FromMilliseconds(retryNumber * retrySleep), (ex, timeSpan, context) => { System.Console.WriteLine("Caught exception and start to retry! {0}", ex.Message); } ); var timeout = Polly.Policy.TimeoutAsync(timeoutSeconds); return Polly.Policy.WrapAsync(retry, timeout); } public Polly.Wrap.PolicyWrap GetRetryPolicyWrap() { int retryNumber = GetRetryNumber(); int retrySleep = GetSleepMilliseconds(); int timeoutSeconds = GetTimeoutSeconds(); var retry = Polly.Policy.Handle<Rest.Client.ApiException>() .WaitAndRetry(retryNumber, retryAttemp => System.TimeSpan.FromMilliseconds( retryNumber * retrySleep), (ex,timeSpan,context) => { System.Console.WriteLine("Caught exception and start to retry! {0}",ex.Message); } ); var timeout = Polly.Policy.Timeout(timeoutSeconds); return Polly.Policy.Wrap(retry, timeout); } #endregion Retry Policy } }
36.46395
163
0.522352
[ "MIT" ]
TileDB-Inc/TileDB-Cloud-CSharp
TileDB.Cloud/Client.cs
11,632
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.Analysis.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// Status of gateway is error. /// </summary> public partial class GatewayListStatusError { /// <summary> /// Initializes a new instance of the GatewayListStatusError class. /// </summary> public GatewayListStatusError() { CustomInit(); } /// <summary> /// Initializes a new instance of the GatewayListStatusError class. /// </summary> /// <param name="error">Error of the list gateway status.</param> public GatewayListStatusError(GatewayError error = default(GatewayError)) { Error = error; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets error of the list gateway status. /// </summary> [JsonProperty(PropertyName = "error")] public GatewayError Error { get; set; } } }
29.326923
90
0.615082
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/analysisservices/Microsoft.Azure.Management.AnalysisServices/src/Generated/Models/GatewayListStatusError.cs
1,525
C#
using System.Collections.Generic; using AutoMapper; using Codenation.Challenge.DTOs; using Codenation.Challenge.Models; using Codenation.Challenge.Services; using Microsoft.AspNetCore.Mvc; namespace Codenation.Challenge.Controllers { [Route("api/[controller]")] [ApiController] public class AccelerationController : ControllerBase { private IAccelerationService _service; private IMapper _mapper; public AccelerationController(IAccelerationService service, IMapper mapper) { _service = service; this._mapper = mapper; } [HttpGet("{id}")] public ActionResult<AccelerationDTO> Get(int id) => Ok(_mapper .Map<AccelerationDTO>(_service .FindById(id))); [HttpGet] public ActionResult<IEnumerable<AccelerationDTO>> GetAll(int? companyId) { if (companyId == null) return NoContent(); return Ok(_mapper.Map<List<AccelerationDTO>>(_service.FindByCompanyId(companyId.Value))); } [HttpPost] public ActionResult<AccelerationDTO> Post(AccelerationDTO expected) => Ok(_mapper .Map<AccelerationDTO>(_service .Save(_mapper .Map<Acceleration>(expected)))); } }
28.702128
101
0.621942
[ "MIT" ]
RMiike/acelera-dev-challenges
csharp-9/Source/Controllers/AccelerationController.cs
1,351
C#
using HEVCDemo.Views; using Prism.Ioc; using Prism.Modularity; using Rasyidf.Localization; using System.Windows; namespace HEVCDemo { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App { protected override Window CreateShell() { return Container.Resolve<MainWindow>(); } protected override void RegisterTypes(IContainerRegistry containerRegistry) { } protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog) { base.ConfigureModuleCatalog(moduleCatalog); moduleCatalog.AddModule<MainModule>(); } protected override void OnStartup(StartupEventArgs e) { // Set the language packs folder and default language LocalizationService.Current.Initialize(); base.OnStartup(e); } } }
25.394737
85
0.60829
[ "BSD-3-Clause" ]
TomNere/hevc-demo
HEVCDemo/App.xaml.cs
967
C#
using Microsoft.Extensions.Logging; namespace Silky.Core.Logging { public interface IHasLogLevel { LogLevel LogLevel { get; set; } } }
17.222222
39
0.677419
[ "MIT" ]
Dishone/silky
framework/src/Silky.Core/Logging/IHasLogLevel.cs
155
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using Bicep.Core.Diagnostics; using Bicep.Core.Emit; using Bicep.Core.FileSystem; using Bicep.Core.PrettyPrint; using Bicep.Core.PrettyPrint.Options; using Bicep.Core.Semantics; using Bicep.Core.Syntax; using Bicep.Core.TypeSystem.Az; using Bicep.Core.UnitTests.Assertions; using Bicep.Core.UnitTests.Utils; using Bicep.Core.Workspaces; using FluentAssertions; using FluentAssertions.Execution; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Bicep.Core.Samples { [TestClass] public class ExamplesTests { [NotNull] public TestContext? TestContext { get; set; } public class ExampleData { public ExampleData(string bicepStreamName, string jsonStreamName, string outputFolderName) { BicepStreamName = bicepStreamName; JsonStreamName = jsonStreamName; OutputFolderName = outputFolderName; } public string BicepStreamName { get; } public string JsonStreamName { get; } public string OutputFolderName { get; } public static string GetDisplayName(MethodInfo info, object[] data) => ((ExampleData)data[0]).BicepStreamName!; } private static IEnumerable<object[]> GetExampleData() { const string pathPrefix = "docs/examples/"; const string bicepExtension = ".bicep"; foreach (var streamName in typeof(ExamplesTests).Assembly.GetManifestResourceNames().Where(p => p.StartsWith(pathPrefix, StringComparison.Ordinal))) { var extension = Path.GetExtension(streamName); if (!StringComparer.OrdinalIgnoreCase.Equals(extension, bicepExtension)) { continue; } var outputFolderName = streamName .Substring(0, streamName.Length - bicepExtension.Length) .Substring(pathPrefix.Length) .Replace('/', '_'); var exampleData = new ExampleData(streamName, Path.ChangeExtension(streamName, "json"), outputFolderName); yield return new object[] { exampleData }; } } private static bool IsPermittedMissingTypeDiagnostic(Diagnostic diagnostic) { if (diagnostic.Code != "BCP081") { return false; } var permittedMissingTypeDiagnostics = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Resource type \"Microsoft.AppConfiguration/configurationStores@2020-07-01-preview\" does not have types available.", "Resource type \"Microsoft.AppConfiguration/configurationStores/keyValues@2020-07-01-preview\" does not have types available.", "Resource type \"Microsoft.Web/sites/config@2018-11-01\" does not have types available.", "Resource type \"Microsoft.KeyVault/vaults/keys@2019-09-01\" does not have types available.", "Resource type \"Microsoft.KeyVault/vaults/secrets@2018-02-14\" does not have types available.", "Resource type \"microsoft.web/serverFarms@2018-11-01\" does not have types available.", "Resource type \"Microsoft.OperationalInsights/workspaces/providers/diagnosticSettings@2017-05-01-preview\" does not have types available.", "Resource type \"Microsoft.Sql/servers@2020-02-02-preview\" does not have types available.", "Resource type \"Microsoft.Sql/servers/databases@2020-02-02-preview\" does not have types available.", "Resource type \"Microsoft.Sql/servers/databases/transparentDataEncryption@2017-03-01-preview\" does not have types available.", "Resource type \"Microsoft.Web/sites/config@2020-06-01\" does not have types available.", "Resource type \"Microsoft.KeyVault/vaults/secrets@2019-09-01\" does not have types available.", "Resource type \"Microsoft.KeyVault/vaults@2019-06-01\" does not have types available.", "Resource type \"microsoft.network/networkSecurityGroups@2020-08-01\" does not have types available.", "Resource type \"Microsoft.Web/sites/siteextensions@2020-06-01\" does not have types available." }; return permittedMissingTypeDiagnostics.Contains(diagnostic.Message); } [TestMethod] public void ExampleData_should_return_a_number_of_records() { GetExampleData().Should().HaveCountGreaterOrEqualTo(30, "sanity check to ensure we're finding examples to test"); } [DataTestMethod] [DynamicData(nameof(GetExampleData), DynamicDataSourceType.Method, DynamicDataDisplayNameDeclaringType = typeof(ExampleData), DynamicDataDisplayName = nameof(ExampleData.GetDisplayName))] public void ExampleIsValid(ExampleData example) { // save all the files in the containing directory to disk so that we can test module resolution var parentStream = Path.GetDirectoryName(example.BicepStreamName)!.Replace('\\', '/'); var outputDirectory = FileHelper.SaveEmbeddedResourcesWithPathPrefix(TestContext, typeof(ExamplesTests).Assembly, example.OutputFolderName, parentStream); var bicepFileName = Path.Combine(outputDirectory, Path.GetFileName(example.BicepStreamName)); var jsonFileName = Path.Combine(outputDirectory, Path.GetFileName(example.JsonStreamName)); var syntaxTreeGrouping = SyntaxTreeGroupingBuilder.Build(new FileResolver(), new Workspace(), PathHelper.FilePathToFileUrl(bicepFileName)); var compilation = new Compilation(new AzResourceTypeProvider(), syntaxTreeGrouping); var emitter = new TemplateEmitter(compilation.GetEntrypointSemanticModel()); // group assertion failures using AssertionScope, rather than reporting the first failure using (new AssertionScope()) { foreach (var (syntaxTree, diagnostics) in compilation.GetAllDiagnosticsBySyntaxTree()) { var nonPermittedDiagnostics = diagnostics.Where(x => !IsPermittedMissingTypeDiagnostic(x)); nonPermittedDiagnostics.Should().BeEmpty($"\"{syntaxTree.FileUri.LocalPath}\" should not have warnings or errors"); } var exampleExists = File.Exists(jsonFileName); exampleExists.Should().BeTrue($"Generated example \"{jsonFileName}\" should be checked in"); using var stream = new MemoryStream(); var result = emitter.Emit(stream); result.Status.Should().Be(EmitStatus.Succeeded); if (result.Status == EmitStatus.Succeeded) { stream.Position = 0; var generated = new StreamReader(stream).ReadToEnd(); var actual = JToken.Parse(generated); File.WriteAllText(jsonFileName + ".actual", generated); actual.Should().EqualWithJsonDiffOutput( TestContext, exampleExists ? JToken.Parse(File.ReadAllText(jsonFileName)) : new JObject(), example.JsonStreamName, jsonFileName + ".actual"); } } } [DataTestMethod] [DynamicData(nameof(GetExampleData), DynamicDataSourceType.Method, DynamicDataDisplayNameDeclaringType = typeof(ExampleData), DynamicDataDisplayName = nameof(ExampleData.GetDisplayName))] public void Example_uses_consistent_formatting(ExampleData example) { // save all the files in the containing directory to disk so that we can test module resolution var parentStream = Path.GetDirectoryName(example.BicepStreamName)!.Replace('\\', '/'); var outputDirectory = FileHelper.SaveEmbeddedResourcesWithPathPrefix(TestContext, typeof(ExamplesTests).Assembly, example.OutputFolderName, parentStream); var bicepFileName = Path.Combine(outputDirectory, Path.GetFileName(example.BicepStreamName)); var originalContents = File.ReadAllText(bicepFileName); var program = ParserHelper.Parse(originalContents); var printOptions = new PrettyPrintOptions(NewlineOption.LF, IndentKindOption.Space, 2, true); var formattedContents = PrettyPrinter.PrintProgram(program, printOptions); formattedContents.Should().NotBeNull(); File.WriteAllText(bicepFileName + ".formatted", formattedContents); originalContents.Should().EqualWithLineByLineDiffOutput( TestContext, formattedContents!, expectedLocation: example.BicepStreamName, actualLocation: bicepFileName + ".formatted"); } } }
49.684492
195
0.653536
[ "MIT" ]
jongio/bicep
src/Bicep.Core.Samples/ExamplesTests.cs
9,291
C#
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using Xunit; namespace System.Web.Mvc.Test { public class DescriptorUtilTest { [Fact] public void CreateUniqueId_FromIUniquelyIdentifiable() { // Arrange CustomUniquelyIdentifiable custom = new CustomUniquelyIdentifiable("hello-world"); // Act string retVal = DescriptorUtil.CreateUniqueId(custom); // Assert Assert.Equal("[11]hello-world", retVal); } [Fact] public void CreateUniqueId_FromMemberInfo() { // Arrange string moduleVersionId = typeof(DescriptorUtilTest).Module.ModuleVersionId.ToString(); string metadataToken = typeof(DescriptorUtilTest).MetadataToken.ToString(); string expected = String.Format("[{0}]{1}[{2}]{3}", moduleVersionId.Length, moduleVersionId, metadataToken.Length, metadataToken); // Act string retVal = DescriptorUtil.CreateUniqueId(typeof(DescriptorUtilTest)); // Assert Assert.Equal(expected, retVal); } [Fact] public void CreateUniqueId_FromSimpleTypes() { // Act string retVal = DescriptorUtil.CreateUniqueId("foo", null, 12345); // Assert Assert.Equal("[3]foo[-1][5]12345", retVal); } private sealed class CustomUniquelyIdentifiable : IUniquelyIdentifiable { public CustomUniquelyIdentifiable(string uniqueId) { UniqueId = uniqueId; } public string UniqueId { get; private set; } } } }
30.465517
142
0.596491
[ "Apache-2.0" ]
Distrotech/mono
external/aspnetwebstack/test/System.Web.Mvc.Test/Test/DescriptorUtilTest.cs
1,769
C#
/********************************************************************************************************************** FocusOPEN Digital Asset Manager (TM) (c) Daydream Interactive Limited 1995-2010, All Rights Reserved The name and trademarks of copyright holders may NOT be used in advertising or publicity pertaining to the software without specific, written prior permission. Title to copyright in this software and any associated documentation will at all times remain with copyright holders. Please refer to licences/focusopen.txt or http://www.digitalassetmanager.com for licensing information about this software. **********************************************************************************************************************/ using System; namespace FocusOPEN.Data { [Serializable] public class NullLightboxLinked : LightboxLinked { #region Singleton implementation private NullLightboxLinked() { } private static readonly NullLightboxLinked m_instance = new NullLightboxLinked(); public static NullLightboxLinked Instance { get { return m_instance; } } #endregion #region Accessors /// <summary> /// Returns the LightboxId of the LightboxLinked object. /// </summary> public override int LightboxId { get { return 0; } set { ; } } /// <summary> /// Returns the UserId of the LightboxLinked object. /// </summary> public override int UserId { get { return 0; } set { ; } } /// <summary> /// Returns the IsEditable of the LightboxLinked object. /// </summary> public override Nullable <Boolean> IsEditable { get { return null; } set { ; } } /// <summary> /// Returns the ExpiryDate of the LightboxLinked object. /// </summary> public override Nullable <DateTime> ExpiryDate { get { return null; } set { ; } } /// <summary> /// Returns the Disabled of the LightboxLinked object. /// </summary> public override Nullable <Boolean> Disabled { get { return null; } set { ; } } #endregion public override bool IsNull { get { return true; } } } }
23.466667
119
0.609375
[ "MIT" ]
MatfRS2/SeminarskiRadovi
programski-projekti/Matf-RS2-FocusOpen/FocusOPEN_OS_Source_3_3_9_5/FocusOPEN.Data/Entities/Nulls/NullLightboxLinked.cs
2,112
C#
using System; using System.Drawing; using System.Threading; using Sharp2D.Game.Worlds; using System.Collections.Generic; using System.Diagnostics; using Sharp2D; using Sharp2D.Game; using Sharp2D.Core.Interfaces; namespace TestGame { class Program { public static TestSprite spriteSause; public static void Main(string[] args) { try { ScreenSettings settings = new ScreenSettings(); settings.UseOpenTKLoop = false; Screen.DisplayScreenAsync(settings); System.Threading.Thread.Sleep(1000); Stopwatch watch = new Stopwatch(); Console.WriteLine("Staring world load timer.."); watch.Start(); TestWorld world = new TestWorld(); world.Load(); world.Display(); watch.Stop(); Console.WriteLine("World loaded and displayed in: " + watch.ElapsedMilliseconds); Random rand = new Random(); Screen.Camera.Z = 100f; int TEST = 1; for (int i = 0; i < TEST; i++) { TestSprite wat = new TestSprite(); wat.X = rand.Next(600 - 400) + 400; wat.Y = rand.Next(700 - 500) + 580; wat.Layer = (float)i / (float)TEST; world.AddSprite(wat); wat.GetFirstModule<AnimationModule>().Animations[0]["hat"].Play(); Screen.Camera.Y = wat.Y - 55; Screen.Camera.X = -wat.X; } Light light2 = new Light(456, 500, 1f, 50f, LightType.DynamicPointLight); Light light = new Light(456, 680, 1f, 50f, LightType.DynamicPointLight); Screen.Camera.X = -406; Screen.Camera.Y = 680; light2.Color = Color.FromArgb(rand.Next(255), rand.Next(255), rand.Next(255)); light.Color = Color.FromArgb(rand.Next(255), rand.Next(255), rand.Next(255)); light.Radius = 100; light2.Radius = 100; world.AddLight(light); world.AddLight(light2); int testCount = 10; for (int i = 0; i < testCount; i++) { light = new Light(50f * i, 600, 1f, 50f, LightType.StaticPointLight); light.Color = Color.FromArgb(rand.Next(255), rand.Next(255), rand.Next(255)); light.Radius = 100; world.AddLight(light); } world.AmbientBrightness = 0.5f; double count = 0; world.AddLogical(delegate { count += 0.2; double c = Math.Cos(count); double s = Math.Sin(count); light.X = 456f + (float)(c * 50.0); light.Y = 680f + (float)(s * 50.0); light2.X = 456f + (float)(-c * 100.0); light2.Y = 500f + (float)(-s * 100.0); }); } catch (Exception e) { Logger.Debug(e.ToString()); } } public static void TestBitmapDrawing(TestWorld world) { Font font = new Font("Oxygen", 18f, FontStyle.Regular, GraphicsUnit.Point); //Get font object Texture texture = Texture.NewTexture("jkhjlkjh"); //Create a new texture texture.BlankTexture(128, font.Height + 16); //Set the texture to a blank texture with the width of 128 and the height of 16 + the font's height Sharp2D.Game.Sprites.DefaultSprite sprite = new Sharp2D.Game.Sprites.DefaultSprite(); //Create a new default sprite sprite.Texture = texture; //Set it's texture to the one we just made sprite.Displayed += delegate //Handle the Displayed event { texture.CreateOrUpdate(); //And have it create the texture }; sprite.Height = texture.TextureHeight; //Set the height sprite.Width = texture.TextureWidth; //Set the width sprite.X = 600; //Set the X sprite.Y = 600; //Set the Y world.AddSprite(sprite); //And lastely, add the sprite to the world Random rand = new Random(); char[] chars = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; using (var g = Graphics.FromImage(sprite.Texture.Bitmap)) { using (var b = new SolidBrush(Color.Black)) { using (var back = new SolidBrush(Color.Green)) { g.FillRectangle(back, 0, 0, sprite.Width, sprite.Height); float x = 0f; while (true) { if (x > sprite.Width) continue; string s = "" + chars[rand.Next(chars.Length)]; g.DrawString(s, font, b, x, 0); Screen.Invoke(new Action(delegate { if (x > sprite.Width) { texture.ClearTexture(); g.FillRectangle(back, 0, 0, sprite.Width, sprite.Height); x = 0f; } texture.CreateOrUpdate(); })); x += g.MeasureString(s, font).Width; Thread.Sleep(1000); } } } } } } class MoveCamera : ILogical { public long Start; public void Update() { Screen.Camera.X -= 2; Logger.WriteAt(0, 0, "FPS: " + Screen.Fps); } public void Dispose() { } } class CheckKeys : ILogical { public void Update() { if (Input.Keyboard["Jump"]) { Logger.Log("I LIKE TURTLES!"); } if (Input.Mouse["Shoot"]) { Logger.Log("SCOOTALOO IS THE BEST PONY!"); } } public void Dispose() { } } }
34.158974
171
0.44678
[ "Apache-2.0" ]
CatinaCupGames/Sharp2D
Sharp2D/TestGame/Program.cs
6,663
C#