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
// Copyright 2020 Confluent Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Refer to LICENSE for more information. using System; using System.Collections.Generic; using System.Linq; using Confluent.Kafka; namespace Confluent.SchemaRegistry.Serdes { /// <summary> /// <see cref="Confluent.SchemaRegistry.Serdes.JsonSerializer{T}" /> /// configuration properties. /// </summary> public class JsonSerializerConfig : Config { /// <summary> /// Configuration property names specific to /// <see cref="Confluent.SchemaRegistry.Serdes.JsonSerializer{T}" />. /// </summary> public static class PropertyNames { /// <summary> /// Specifies the initial size (in bytes) of the buffer used for JSON message /// serialization. Use a value high enough to avoid resizing the buffer, but /// small enough to avoid excessive memory use. Inspect the size of the byte /// array returned by the Serialize method to estimate an appropriate value. /// Note: each call to serialize creates a new buffer. /// /// default: 1024 /// </summary> public const string BufferBytes = "json.serializer.buffer.bytes"; /// <summary> /// Specifies whether or not the JSON serializer should attempt to auto-register /// unrecognized schemas with Confluent Schema Registry. /// /// default: true /// </summary> public const string AutoRegisterSchemas = "json.serializer.auto.register.schemas"; /// <summary> /// The subject name strategy to use for schema registration / lookup. /// Possible values: <see cref="Confluent.SchemaRegistry.SubjectNameStrategy" /> /// </summary> public const string SubjectNameStrategy = "json.serializer.subject.name.strategy"; } /// <summary> /// Initialize a new <see cref="JsonSerializerConfig" />. /// </summary> public JsonSerializerConfig() { } /// <summary> /// Initialize a new <see cref="JsonSerializerConfig" /> from the provided /// key/value pair collection. /// </summary> public JsonSerializerConfig(IEnumerable<KeyValuePair<string, string>> config) : base(config.ToDictionary(v => v.Key, v => v.Value)) { } /// <summary> /// Specifies the initial size (in bytes) of the buffer used for Protobuf message /// serialization. Use a value high enough to avoid resizing the buffer, but /// small enough to avoid excessive memory use. Inspect the size of the byte /// array returned by the Serialize method to estimate an appropriate value. /// Note: each call to serialize creates a new buffer. /// /// default: 1024 /// </summary> public int? BufferBytes { get { return GetInt(PropertyNames.BufferBytes); } set { SetObject(PropertyNames.BufferBytes, value); } } /// <summary> /// Specifies whether or not the Protobuf serializer should attempt to auto-register /// unrecognized schemas with Confluent Schema Registry. /// /// default: true /// </summary> public bool? AutoRegisterSchemas { get { return GetBool(PropertyNames.AutoRegisterSchemas); } set { SetObject(PropertyNames.AutoRegisterSchemas, value); } } /// <summary> /// Subject name strategy. /// /// default: SubjectNameStrategy.Topic /// </summary> public SubjectNameStrategy? SubjectNameStrategy { get { var r = Get(PropertyNames.SubjectNameStrategy); if (r == null) { return null; } else { SubjectNameStrategy result; if (!Enum.TryParse<SubjectNameStrategy>(r, out result)) throw new ArgumentException( $"Unknown ${PropertyNames.SubjectNameStrategy} value: {r}."); else return result; } } set { if (value == null) { this.properties.Remove(PropertyNames.SubjectNameStrategy); } else { this.properties[PropertyNames.SubjectNameStrategy] = value.ToString(); } } } } }
38.338235
143
0.575949
[ "Apache-2.0" ]
ChadJessup/confluent-kafka-dotnet
src/Confluent.SchemaRegistry.Serdes.Json/JsonSerializerConfig.cs
5,214
C#
using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore; namespace Tracker.PostgreSQL.Core.Data.Mapping { public partial class TaskExtendedMap : IEntityTypeConfiguration<Tracker.PostgreSQL.Core.Data.Entities.TaskExtended> { public void Configure(Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder<Tracker.PostgreSQL.Core.Data.Entities.TaskExtended> builder) { #region Generated Configure // table builder.ToTable("TaskExtended", "public"); // key builder.HasKey(t => t.TaskId); // properties builder.Property(t => t.TaskId) .IsRequired() .HasColumnName("TaskId") .HasColumnType("uuid"); builder.Property(t => t.UserAgent) .HasColumnName("UserAgent") .HasColumnType("text"); builder.Property(t => t.Browser) .HasColumnName("Browser") .HasColumnType("character varying(256)") .HasMaxLength(256); builder.Property(t => t.OperatingSystem) .HasColumnName("OperatingSystem") .HasColumnType("character varying(256)") .HasMaxLength(256); builder.Property(t => t.Created) .IsRequired() .HasColumnName("Created") .HasColumnType("timestamp with time zone") .HasDefaultValueSql("(now() AT TIME ZONE 'utc'::text)"); builder.Property(t => t.CreatedBy) .HasColumnName("CreatedBy") .HasColumnType("character varying(100)") .HasMaxLength(100); builder.Property(t => t.Updated) .IsRequired() .HasColumnName("Updated") .HasColumnType("timestamp with time zone") .HasDefaultValueSql("(now() AT TIME ZONE 'utc'::text)"); builder.Property(t => t.UpdatedBy) .HasColumnName("UpdatedBy") .HasColumnType("character varying(100)") .HasMaxLength(100); builder.Property(t => t.RowVersion) .HasColumnName("RowVersion") .HasColumnType("bytea"); // relationships builder.HasOne(t => t.Task) .WithOne(t => t.TaskExtended) .HasForeignKey<Tracker.PostgreSQL.Core.Data.Entities.TaskExtended>(d => d.TaskId) .HasConstraintName("FK_TaskExtended_Task_TaskId"); #endregion } #region Generated Constants public struct Table { public const string Schema = "public"; public const string Name = "TaskExtended"; } public struct Columns { public const string TaskId = "TaskId"; public const string UserAgent = "UserAgent"; public const string Browser = "Browser"; public const string OperatingSystem = "OperatingSystem"; public const string Created = "Created"; public const string CreatedBy = "CreatedBy"; public const string Updated = "Updated"; public const string UpdatedBy = "UpdatedBy"; public const string RowVersion = "RowVersion"; } #endregion } }
35.46875
156
0.557709
[ "MIT" ]
Enric-Gilabert/EntityFrameworkCore.Generator
sample/Tracker.PostgreSQL/Tracker.PostgreSQL.Core/Data/Mapping/TaskExtendedMap.cs
3,405
C#
using System; namespace XLua.LuaDLL { using System.Runtime.InteropServices; #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || XLUA_GENERAL || (UNITY_WSA && !UNITY_EDITOR) [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void TableSizeReport(IntPtr p, int size); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void ObjectRelationshipReport(IntPtr parent, IntPtr child, RelationshipType type, string key, double d, string key2); #else public delegate void TableSizeReport(IntPtr p, int size); public delegate void ObjectRelationshipReport(IntPtr parent, IntPtr child, RelationshipType type, string key, double d, string key2); #endif public enum RelationshipType { TableValue = 1, NumberKeyTableValue = 2, KeyOfTable = 3, Metatable = 4, Upvalue = 5, } public partial class Lua { [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void xlua_report_table_size(IntPtr L, TableSizeReport cb, int fast); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void xlua_report_object_relationship(IntPtr L, ObjectRelationshipReport cb); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr xlua_registry_pointer(IntPtr L); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr xlua_global_pointer(IntPtr L); } } namespace XLua { using System.Collections.Generic; using System.Text; using System.Linq; public static class LuaMemoryLeakChecker { const string UNKNOW_KEY = "???"; const string METATABLE_KEY = "__metatable"; const string KEY_OF_TABLE = "!KEY!"; public class Data { internal int Memroy = 0; internal Dictionary<IntPtr, int> TableSizes = new Dictionary<IntPtr, int>(); public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendFormat("memroy:{0}, table count:{1}", Memroy, TableSizes.Count); sb.AppendLine(); if (TableSizes.Count < 10) { foreach (var kv in TableSizes) { sb.AppendLine(string.Format("table({0}) : {1}", kv.Key, kv.Value)); } } else { sb.AppendLine("too much table..."); } return sb.ToString(); } public int PotentialLeakCount { get { return TableSizes.Count; } } } static Data getSizeReport(LuaEnv env) { Data data = new Data(); data.Memroy = env.Memroy; LuaDLL.Lua.xlua_report_table_size(env.L, (IntPtr p, int size) => { data.TableSizes.Add(p, size); }, 0); return data; } struct RefInfo { public string Key; public bool HasNext; public IntPtr Parent; public bool IsNumberKey; } static string makeKey(LuaDLL.RelationshipType type, string key, double d, string key2) { switch(type) { case LuaDLL.RelationshipType.TableValue: return key== null ? ((LuaTypes)(int)d).ToString() : key; case LuaDLL.RelationshipType.NumberKeyTableValue: return string.Format("[{0}]", d); case LuaDLL.RelationshipType.KeyOfTable: return KEY_OF_TABLE; case LuaDLL.RelationshipType.Metatable: return METATABLE_KEY; case LuaDLL.RelationshipType.Upvalue: return string.Format("{0}:local {1}", key, key2); } return UNKNOW_KEY; } static Dictionary<IntPtr, List<RefInfo>> getRelationship(LuaEnv env) { Dictionary<IntPtr, List<RefInfo>> result = new Dictionary<IntPtr, List<RefInfo>>(); int top = LuaDLL.Lua.lua_gettop(env.L); IntPtr registryPointer = LuaDLL.Lua.xlua_registry_pointer(env.L); IntPtr globalPointer = LuaDLL.Lua.xlua_global_pointer(env.L); LuaDLL.Lua.xlua_report_object_relationship(env.L, (IntPtr parent, IntPtr child, LuaDLL.RelationshipType type, string key, double d, string key2) => { List<RefInfo> infos; try { if (!result.TryGetValue(child, out infos)) { infos = new List<RefInfo>(); result.Add(child, infos); } string keyOfRef = makeKey(type, key, d, key2); bool hasNext = type != LuaDLL.RelationshipType.Upvalue; if (hasNext) { if (parent == registryPointer) { keyOfRef = "_R." + keyOfRef; hasNext = false; } else if (parent == globalPointer) { keyOfRef = "_G." + keyOfRef; hasNext = false; } } infos.Add(new RefInfo() { Key = keyOfRef, HasNext = hasNext, Parent = parent, IsNumberKey = type == LuaDLL.RelationshipType.NumberKeyTableValue, }); } catch (Exception e) { UnityEngine.Debug.LogError(e.Message); } }); LuaDLL.Lua.lua_settop(env.L, top); return result; } public static Data StartMemoryLeakCheck(this LuaEnv env) { env.FullGc(); return getSizeReport(env); } static Data findGrowing(Data from, Data to) { Data result = new Data(); result.Memroy = to.Memroy; bool keepEqual = to.Memroy <= from.Memroy; foreach (var kv in to.TableSizes) { int oldSize; if (from.TableSizes.TryGetValue(kv.Key, out oldSize) && (oldSize < kv.Value || (keepEqual && oldSize == kv.Value))) // exist table { result.TableSizes.Add(kv.Key, kv.Value); } } return result; } public static Data MemoryLeakCheck(this LuaEnv env, Data last) { env.FullGc(); return findGrowing(last, getSizeReport(env)); } public static string MemoryLeakReport(this LuaEnv env, Data data, int maxLevel = 10) { env.FullGc(); var relationshipInfo = getRelationship(env); StringBuilder sb = new StringBuilder(); sb.AppendLine("total memroy: " + data.Memroy); foreach(var kv in data.TableSizes) { List<RefInfo> infos; if (!relationshipInfo.TryGetValue(kv.Key, out infos)) { continue; } List<string> paths = new List<string>(); for(int i = 0; i < maxLevel; i++) { int pathCount = paths.Count; paths.AddRange(infos.Where(info => !info.HasNext).Select(info => info.Key)); if ((paths.Count - pathCount) != infos.Count) { infos = infos.Where(info => info.HasNext) .SelectMany((info) => { List<RefInfo> infosOfParent; if (!relationshipInfo.TryGetValue(info.Parent, out infosOfParent)) { return new List<RefInfo>(); } return infosOfParent.Select(pinfo => { var parentkey = pinfo.Key; return new RefInfo() { HasNext = pinfo.HasNext, Key = string.Format(info.IsNumberKey ? "{0}{1}" : "{0}.{1}", pinfo.Key, info.Key), Parent = pinfo.Parent, IsNumberKey = pinfo.IsNumberKey, }; }); }).ToList(); } else { break; } } infos = infos.Where(info => info.HasNext).ToList(); if (infos.Count != 0) { paths.AddRange(infos.Select(info => "..." + info.Key)); } sb.AppendLine(string.Format("potential leak({0}) in {{{1}}}", kv.Value, string.Join(",", paths.ToArray()))); } return sb.ToString(); } } }
37.075472
162
0.46799
[ "BSD-3-Clause" ]
107191613/xLua
General/LuaMemoryLeakChecker/LuaMemoryLeakChecker.cs
9,827
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.Diagnostics; using System.Linq; using Xunit; namespace Collections.Pooled.Tests { /// <summary> /// Provides a base set of generic operations that are used by all other generic testing interfaces. /// </summary> public abstract class TestBase<T> : TestBase { #region Helper Methods /// <summary> /// To be implemented in the concrete collections test classes. Creates an instance of T that /// is dependent only on the seed passed as input and will return the same value on repeated /// calls with the same seed. /// </summary> protected abstract T CreateT(int seed); /// <summary> /// The EqualityComparer that can be used in the overriding class when creating test enumerables /// or test collections. Default if not overridden is the default comparator. /// </summary> protected virtual IEqualityComparer<T> GetIEqualityComparer() => EqualityComparer<T>.Default; /// <summary> /// The Comparer that can be used in the overriding class when creating test enumerables /// or test collections. Default if not overridden is the default comparator. protected virtual IComparer<T> GetIComparer() => Comparer<T>.Default; private static IEnumerable<int[]> GetTestData() { foreach (object[] collectionSizeArray in ValidCollectionSizes()) { int count = (int)collectionSizeArray[0]; foreach (EnumerableType et in Enum.GetValues(typeof(EnumerableType))) { int enumerableType = (int)et; yield return new int[] { enumerableType, count, 0, 0, 0 }; // Empty Enumerable yield return new int[] { enumerableType, count, count + 1, 0, 0 }; // Enumerable that is 1 larger if (count >= 1) { yield return new int[] { enumerableType, count, count, 0, 0 }; // Enumerable of the same size yield return new int[] { enumerableType, count, count - 1, 0, 0 }; // Enumerable that is 1 smaller yield return new int[] { enumerableType, count, count, 1, 0 }; // Enumerable of the same size with 1 matching element yield return new int[] { enumerableType, count, count + 1, 1, 0 }; // Enumerable that is 1 longer with 1 matching element yield return new int[] { enumerableType, count, count, count, 0 }; // Enumerable with all elements matching yield return new int[] { enumerableType, count, count + 1, count, 0 }; // Enumerable with all elements matching plus one extra } if (count >= 2) { yield return new int[] { enumerableType, count, count - 1, 1, 0 }; // Enumerable that is 1 smaller with 1 matching element yield return new int[] { enumerableType, count, count + 2, 2, 0 }; // Enumerable that is 2 longer with 2 matching element yield return new int[] { enumerableType, count, count - 1, count - 1, 0 }; // Enumerable with all elements matching minus one yield return new int[] { enumerableType, count, count, 2, 0 }; // Enumerable of the same size with 2 matching element if (et == EnumerableType.List || et == EnumerableType.Queue) yield return new int[] { enumerableType, count, count, 0, 1 }; // Enumerable with 1 element duplicated } if (count >= 3) { if (et == EnumerableType.List || et == EnumerableType.Queue) yield return new int[] { enumerableType, count, count, 0, 1 }; // Enumerable with all elements duplicated yield return new int[] { enumerableType, count, count - 1, 2, 0 }; // Enumerable that is 1 smaller with 2 matching elements } } } } private class IntArrayComparer : IEqualityComparer<int[]> { public bool Equals(int[] x, int[] y) { if (ReferenceEquals(x, y)) return true; if (x is null || y is null) return false; if (x.Length != y.Length) return false; return x.AsSpan().SequenceEqual(y.AsSpan()); } public int GetHashCode(int[] obj) { int hash = 17; foreach (int x in obj) { hash ^= x.GetHashCode(); } return hash; } } private static readonly Lazy<object[][]> TestData = new Lazy<object[][]>(() => { return GetTestData() .Distinct(new IntArrayComparer()) .Select(ints => new object[] { (EnumerableType)ints[0], ints[1], ints[2], ints[3], ints[4] }) .ToArray(); }); /// <summary> /// MemberData to be passed to tests that take an IEnumerable{T}. This method returns every permutation of /// EnumerableType to test on (e.g. HashSet, Queue), and size of set to test with (e.g. 0, 1, etc.). /// </summary> public static IEnumerable<object[]> EnumerableTestData() => TestData.Value; /// <summary> /// Helper function to create an enumerable fulfilling the given specific parameters. The function will /// create an enumerable of the desired type using the Default constructor for that type and then add values /// to it until it is full. It will begin by adding the desired number of matching and duplicate elements, /// followed by random (deterministic) elements until the desired count is reached. /// </summary> protected IEnumerable<T> CreateEnumerable(EnumerableType type, IEnumerable<T> enumerableToMatchTo, int count, int numberOfMatchingElements, int numberOfDuplicateElements) { Debug.Assert(count >= numberOfMatchingElements); Debug.Assert(count >= numberOfDuplicateElements); switch (type) { case EnumerableType.HashSet: Debug.Assert(numberOfDuplicateElements == 0, "Can not create a HashSet with duplicate elements - numberOfDuplicateElements must be zero"); return CreateHashSet(enumerableToMatchTo, count, numberOfMatchingElements); case EnumerableType.List: return CreateList(enumerableToMatchTo, count, numberOfMatchingElements, numberOfDuplicateElements); case EnumerableType.SortedSet: Debug.Assert(numberOfDuplicateElements == 0, "Can not create a SortedSet with duplicate elements - numberOfDuplicateElements must be zero"); return CreateSortedSet(enumerableToMatchTo, count, numberOfMatchingElements); case EnumerableType.Queue: return CreateQueue(enumerableToMatchTo, count, numberOfMatchingElements, numberOfDuplicateElements); case EnumerableType.Lazy: return CreateLazyEnumerable(enumerableToMatchTo, count, numberOfMatchingElements, numberOfDuplicateElements); default: Debug.Assert(false, "Check that the 'EnumerableType' Enum returns only types that are special-cased in the CreateEnumerable function within the Iset_Generic_Tests class"); return null; } } /// <summary> /// Helper function to create a Queue fulfilling the given specific parameters. The function will /// create an Queue and then add values /// to it until it is full. It will begin by adding the desired number of matching, /// followed by random (deterministic) elements until the desired count is reached. /// </summary> protected IEnumerable<T> CreateQueue(IEnumerable<T> enumerableToMatchTo, int count, int numberOfMatchingElements, int numberOfDuplicateElements) { PooledQueue<T> queue = new PooledQueue<T>(count); RegisterForDispose(queue); int seed = 528; int duplicateAdded = 0; List<T> match = null; // Enqueue Matching elements if (enumerableToMatchTo != null) { match = enumerableToMatchTo.ToList(); for (int i = 0; i < numberOfMatchingElements; i++) { queue.Enqueue(match[i]); while (duplicateAdded++ < numberOfDuplicateElements) queue.Enqueue(match[i]); } } // Enqueue elements to reach the desired count while (queue.Count < count) { T toEnqueue = CreateT(seed++); while (queue.Contains(toEnqueue) || (match != null && match.Contains(toEnqueue))) // Don't want any unexpectedly duplicate values toEnqueue = CreateT(seed++); queue.Enqueue(toEnqueue); while (duplicateAdded++ < numberOfDuplicateElements) queue.Enqueue(toEnqueue); } // Validate that the Enumerable fits the guidelines as expected Debug.Assert(queue.Count == count); if (match != null) { int actualMatchingCount = 0; foreach (T lookingFor in match) actualMatchingCount += queue.Contains(lookingFor) ? 1 : 0; Assert.Equal(numberOfMatchingElements, actualMatchingCount); } return queue; } /// <summary> /// Helper function to create an List fulfilling the given specific parameters. The function will /// create an List and then add values /// to it until it is full. It will begin by adding the desired number of matching, /// followed by random (deterministic) elements until the desired count is reached. /// </summary> protected IEnumerable<T> CreateList(IEnumerable<T> enumerableToMatchTo, int count, int numberOfMatchingElements, int numberOfDuplicateElements) { List<T> list = new List<T>(count); int seed = 528; int duplicateAdded = 0; List<T> match = null; // Add Matching elements if (enumerableToMatchTo != null) { match = enumerableToMatchTo.ToList(); for (int i = 0; i < numberOfMatchingElements; i++) { list.Add(match[i]); while (duplicateAdded++ < numberOfDuplicateElements) list.Add(match[i]); } } // Add elements to reach the desired count while (list.Count < count) { T toAdd = CreateT(seed++); while (list.Contains(toAdd) || (match != null && match.Contains(toAdd))) // Don't want any unexpectedly duplicate values toAdd = CreateT(seed++); list.Add(toAdd); while (duplicateAdded++ < numberOfDuplicateElements) list.Add(toAdd); } // Validate that the Enumerable fits the guidelines as expected Debug.Assert(list.Count == count); if (match != null) { int actualMatchingCount = 0; foreach (T lookingFor in match) actualMatchingCount += list.Contains(lookingFor) ? 1 : 0; Assert.Equal(numberOfMatchingElements, actualMatchingCount); } return list; } /// <summary> /// Helper function to create an HashSet fulfilling the given specific parameters. The function will /// create an HashSet using the Comparer constructor and then add values /// to it until it is full. It will begin by adding the desired number of matching, /// followed by random (deterministic) elements until the desired count is reached. /// </summary> protected IEnumerable<T> CreateHashSet(IEnumerable<T> enumerableToMatchTo, int count, int numberOfMatchingElements) { var set = new PooledSet<T>(GetIEqualityComparer()); RegisterForDispose(set); int seed = 528; List<T> match = null; // Add Matching elements if (enumerableToMatchTo != null) { match = enumerableToMatchTo.ToList(); for (int i = 0; i < numberOfMatchingElements; i++) set.Add(match[i]); } // Add elements to reach the desired count while (set.Count < count) { T toAdd = CreateT(seed++); while (set.Contains(toAdd) || (match != null && match.Contains(toAdd, GetIEqualityComparer()))) // Don't want any unexpectedly duplicate values toAdd = CreateT(seed++); set.Add(toAdd); } // Validate that the Enumerable fits the guidelines as expected Debug.Assert(set.Count == count); if (match != null) { int actualMatchingCount = 0; foreach (T lookingFor in match) actualMatchingCount += set.Contains(lookingFor) ? 1 : 0; Assert.Equal(numberOfMatchingElements, actualMatchingCount); } return set; } /// <summary> /// Helper function to create an SortedSet fulfilling the given specific parameters. The function will /// create an SortedSet using the Comparer constructor and then add values /// to it until it is full. It will begin by adding the desired number of matching, /// followed by random (deterministic) elements until the desired count is reached. /// </summary> protected IEnumerable<T> CreateSortedSet(IEnumerable<T> enumerableToMatchTo, int count, int numberOfMatchingElements) { SortedSet<T> set = new SortedSet<T>(GetIComparer()); int seed = 528; List<T> match = null; // Add Matching elements if (enumerableToMatchTo != null) { match = enumerableToMatchTo.ToList(); for (int i = 0; i < numberOfMatchingElements; i++) set.Add(match[i]); } // Add elements to reach the desired count while (set.Count < count) { T toAdd = CreateT(seed++); while (set.Contains(toAdd) || (match != null && match.Contains(toAdd, GetIEqualityComparer()))) // Don't want any unexpectedly duplicate values toAdd = CreateT(seed++); set.Add(toAdd); } // Validate that the Enumerable fits the guidelines as expected Debug.Assert(set.Count == count); if (match != null) { int actualMatchingCount = 0; foreach (T lookingFor in match) actualMatchingCount += set.Contains(lookingFor) ? 1 : 0; Assert.Equal(numberOfMatchingElements, actualMatchingCount); } return set; } protected IEnumerable<T> CreateLazyEnumerable(IEnumerable<T> enumerableToMatchTo, int count, int numberOfMatchingElements, int numberOfDuplicateElements) { IEnumerable<T> list = CreateList(enumerableToMatchTo, count, numberOfMatchingElements, numberOfDuplicateElements); return list.Select(item => item); } #endregion } }
47.624277
191
0.564996
[ "MIT" ]
ipavel83/Collections.Pooled
Collections.Pooled.Tests/TestBase.Generic.cs
16,480
C#
using AutoMapper; using Business.Resources.Location; namespace Business.Mapping.Location { public class ModelToResourceProfile : Profile { public ModelToResourceProfile() { CreateMap<Domain.Models.Location, LocationResource>(); } } }
20.285714
66
0.669014
[ "MIT" ]
dong-nguyen-hd/HR-Management
BE/Business/Mapping/Location/ModelToResourceProfile.cs
286
C#
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; [RequireComponent(typeof(CanvasGroup))] public class CanvasFader : MonoBehaviour { private CanvasGroup _canvasGroupEntity; private CanvasGroup _canvasGroup { get { if(_canvasGroupEntity == null) { _canvasGroupEntity = GetComponent<CanvasGroup>(); if(_canvasGroupEntity == null) { _canvasGroupEntity = gameObject.AddComponent<CanvasGroup>(); } } return _canvasGroupEntity; } } public float Alpha { get { return _canvasGroup.alpha; } set { _canvasGroup.alpha = value; } } // フェードの状態 private enum FadeState { None, FadeIn, FadeOut } private FadeState _fadeState = FadeState.None; // フェードインしているか public bool IsFading { get { return _fadeState != FadeState.None; } } // フェード時間 [SerializeField] private float _duration; public float Duration { get { return _duration; } } //タイムスケールを無視するか [SerializeField] private bool _ignoreTimeScale = true; //フェード終了後のコールバック private event Action _onFinished = null; // Update is called once per frame void Update() { if (!IsFading) { return; } float fadeSpeed = 1f / _duration; if (_ignoreTimeScale) { fadeSpeed *= Time.unscaledDeltaTime; } else { fadeSpeed *= Time.deltaTime; } Alpha += fadeSpeed * (_fadeState == FadeState.FadeIn ? 1f : -1f); // フェード終了判定 if(Alpha > 0 && Alpha < 1) { return; } _fadeState = FadeState.None; this.enabled = false; if(_onFinished != null) { _onFinished(); } } // 対象のオブジェクトのフェードを開始する public static void Begin(GameObject target,bool isFadeOut, float duration) { CanvasFader canvasFader = target.GetComponent<CanvasFader>(); if(canvasFader == null) { canvasFader = target.AddComponent<CanvasFader>(); } canvasFader.enabled = true; canvasFader.Play(isFadeOut, duration); } // フェードを開始する public void Play(bool isFadeOut , float duration, bool ignoretimeScale = true , Action onFinished = null) { this.enabled = true; _ignoreTimeScale = ignoretimeScale; _onFinished = onFinished; Alpha = isFadeOut ? 1 : 0; _fadeState = isFadeOut ? FadeState.FadeOut : FadeState.FadeIn; _duration = duration; } // フェード停止 public void Stop() { _fadeState = FadeState.None; this.enabled = false; } }
21.489655
110
0.515725
[ "MIT" ]
kuro0096/RaceGame
RaceGame/Assets/Script/Scene/CanvasFader.cs
3,304
C#
#if !NOJSONNET using System.IO; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace NBitcoin.RPC { //{"code":-32601,"message":"Method not found"} public class RPCError { internal RPCError(JObject error) { Code = (RPCErrorCode)((int)error.GetValue("code")); Message = (string)error.GetValue("message"); } public RPCErrorCode Code { get; set; } public string Message { get; set; } } //{"result":null,"error":{"code":-32601,"message":"Method not found"},"id":1} public class RPCResponse { internal RPCResponse(JObject json) { var error = json.GetValue("error") as JObject; if(error != null) { Error = new RPCError(error); } Result = json.GetValue("result") as JToken; } public RPCError Error { get; set; } #if !NOJSONNET public #else internal #endif JToken Result { get; set; } public string ResultString { get { if(Result == null) return null; return Result.ToString(); } } public static RPCResponse Load(Stream stream) { JsonTextReader reader = new JsonTextReader(new StreamReader(stream, Encoding.UTF8)); return new RPCResponse(JObject.Load(reader)); } public void ThrowIfError() { if(Error != null) { throw new RPCException(Error.Code, Error.Message, this); } } } } #endif
22.072289
96
0.476528
[ "MIT" ]
MIPPL/StratisBitcoinFullNode
src/NBitcoin/RPC/RPCResponse.cs
1,834
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="App.cs" company="Flush Arcade Pty Ltd."> // Copyright (c) 2015 Flush Arcade Pty Ltd. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- [assembly: Xamarin.Forms.Xaml.XamlCompilation(Xamarin.Forms.Xaml.XamlCompilationOptions.Compile)] namespace Stocklist.XamForms { using Xamarin.Forms; using Stocklist.Portable.Ioc; /// <summary> /// The App. /// </summary> public partial class App : Application { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="T:Stocklist.XamForms.App"/> class. /// </summary> public App() { InitializeComponent(); // The Application ResourceDictionary is available in Xamarin.Forms 1.3 and later if (Application.Current.Resources == null) { Application.Current.Resources = new ResourceDictionary(); } MainPage = IoC.Resolve<NavigationPage>(); } #endregion #region Protected Methods /// <summary> /// Override the starting function /// </summary> /// <returns>The start.</returns> protected override void OnStart() { // Handle when your app starts } /// <summary> /// Override the OnSleep function /// </summary> /// <returns>The sleep.</returns> protected override void OnSleep() { // Handle when your app sleeps } /// <summary> /// Overrides the OnResume function /// </summary> /// <returns>The resume.</returns> protected override void OnResume() { // Handle when your app resumes } #endregion } }
24.225352
120
0.575
[ "MIT" ]
PacktPublishing/Xamarin-Blueprints
Chapter 5/App.xaml.cs
1,722
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.RazorPages; namespace SignalRTest.Pages { public class AboutModel : PageModel { public string Message { get; set; } public void OnGet() { Message = "Your application description page."; } } }
20.894737
60
0.627204
[ "MIT" ]
abcamitan/NetCoreSignalRChat
Pages/About.cshtml.cs
399
C#
/* Based on code from MVVM Dialogs, located at https://github.com/FantasticFiasco/mvvm-dialogs Specifically FileDialogSettings.cs, located at https://github.com/FantasticFiasco/mvvm-dialogs/blob/master/src/net/FrameworkDialogs/FileDialogSettings.cs MVVM Dialogs is licensed under the Apache License 2.0, Copyright 2009-2020 Mattias Kindborg. The full text of the license is available at https://github.com/FantasticFiasco/mvvm-dialogs/blob/master/LICENSE */ namespace VideoScriptEditor.Services.Dialog { /// <summary> /// Settings for the system file dialog. /// </summary> public abstract class SystemFileDialogSettings { /// <summary> /// Gets or sets a value indicating whether a file dialog automatically adds an extension /// to a file name if the user omits an extension. /// </summary> /// <value> /// <c>true</c> if extensions are added; otherwise, <c>false</c>. The default is /// <c>true</c>. /// </value> public bool AddExtension { get; set; } = true; /// <summary> /// Gets or sets a value that specifies whether warnings are displayed if the user types /// invalid paths and file names. /// </summary> /// <value> /// <c>true</c> if warnings are displayed; otherwise, <c>false</c>. The default is /// <c>true</c>. /// </value> public bool CheckPathExists { get; set; } = true; /// <summary> /// Gets or sets a value that specifies the default extension string to use to filter the /// list of files that are displayed. /// </summary> /// <value> /// The default extension string. The default is <see cref="string.Empty"/>. /// </value> /// <remarks> /// The extension string must contain the leading period. For example, set the /// <see cref="DefaultExt"/> property to ".txt" to select all text files. /// <para/> /// By default, the <see cref="AddExtension"/> property attempts to determine the extension /// to filter the displayed file list from the <see cref="Filter"/> property. If the /// extension cannot be determined from the <see cref="Filter"/> property, /// <see cref="DefaultExt"/> will be used instead. /// </remarks> public string DefaultExt { get; set; } = string.Empty; /// <summary> /// Gets or sets a value indicating whether a file dialog returns either the location of /// the file referenced by a shortcut or the location of the shortcut file (.lnk). /// </summary> /// <value> /// <c>true</c> to return the location referenced; <c>false</c> to return the shortcut /// location. The default is <c>true</c>. /// </value> public bool DereferenceLinks { get; set; } = true; /// <summary> /// Gets or sets a string containing the full path of the file selected in a file dialog. /// </summary> /// <value> /// A <see cref="string"/> that is the full path of the file selected in the file dialog. /// The default is <see cref="string.Empty"/>. /// </value> /// <remarks> /// If more than one file name is selected (length of <see cref="FileNames"/> is greater /// than one) then <see cref="FileName"/> contains the first selected file name. If no file /// name is selected, this property contains <see cref="string.Empty"/> rather than /// <c>null</c>. /// </remarks> public string FileName { get; set; } = string.Empty; /// <summary> /// Gets an array that contains one file name for each selected file. /// </summary> /// <value> /// An array of <see cref="string"/> that contains one file name for each selected file. /// The default is an array with a single item whose value is <see cref="string.Empty"/>. /// </value> public string[] FileNames { get; set; } = { string.Empty }; /// <summary> /// Gets or sets the filter string that determines what types of files are displayed from /// either the open file dialog or the save file dialog. /// </summary> /// <value> /// A <see cref="string"/> that contains the filter. The default is /// <see cref="string.Empty"/>, which means that no filter is applied and all file types /// are displayed. /// </value> /// <remarks> /// If <see cref="Filter"/> is either <c>null</c> or <see cref="string.Empty"/>, all files /// are displayed, and folders are always displayed. /// <para/> /// You can specify a subset of file types to be displayed by setting the /// <see cref="Filter"/> property. Each file type can represent a specific type of file, /// such as the following: /// <list type="bullet"> /// <item><description>Word Documents (*.doc)</description></item> /// <item><description>Excel Worksheets (*.xls)</description></item> /// <item><description>PowerPoint Presentations (*.ppt)</description></item> /// </list> /// Alternatively, a file type can represent a group of related file types, such as the /// following: /// <list type="bullet"> /// <item><description>Office Files (*.doc, *.xls, *.ppt)</description></item> /// <item><description>All Files (*.*)</description></item> /// </list> /// To specify a subset of the types of files that are displayed, you set the /// <see cref="Filter"/> property with a string value (the <i>filter string</i>) that /// specifies one or more types of files to filter by. The following shows the expected /// format of the filter string: /// <code> /// FileType1[[|FileType2]...[|FileTypeN]] /// </code> /// You use the following format to describe each file type: /// <code> /// Label|Extension1[[;Extension2]...[;ExtensionN]] /// </code> /// The <i>Label</i> part is a human-readable string value that describes the file type, /// such as the following: /// <list type="bullet"> /// <item><description>"Word Documents"</description></item> /// <item><description>"Excel Worksheets"</description></item> /// <item><description>"PowerPoint Presentations"</description></item> /// <item><description>"Office Files"</description></item> /// <item><description>"All Files"</description></item> /// </list> /// Each file type must be described by at least one <i>Extension</i>. If more than one /// <i>Extension</i> is used, each <i>Extension</i> must be separated by a semicolon (";"). /// For example: /// <list type="bullet"> /// <item><description>"*.doc"</description></item> /// <item><description>"*.xls;"</description></item> /// <item><description>"*.ppt"</description></item> /// <item><description>"*.doc;*.xls;*.ppt"</description></item> /// <item><description>"*.*"</description></item> /// </list> /// The following are complete examples of valid <see cref="Filter"/> string values: /// <list type="bullet"> /// <item><description>Word Documents|*.doc</description></item> /// <item><description>Excel Worksheets|*.xls</description></item> /// <item><description>PowerPoint Presentations|*.ppt</description></item> /// <item><description>Office Files|*.doc;*.xls;*.ppt</description></item> /// <item><description>All Files|*.*</description></item> /// <item><description>Word Documents|*.doc|Excel Worksheets|*.xls|PowerPoint Presentations|*.ppt|Office Files|*.doc;*.xls;*.ppt|All Files|*.*</description></item> /// </list> /// Each file type that is included in the filter is added as a separate item to the /// <b>Files of type</b>: drop-down list in the open file dialog or the save file dialog. /// <para/> /// The user can choose a file type from this list to filter by. By default, the first item /// in the list (for example, the first file type) is selected when the open file dialog or /// save file dialog is displayed. To specify that another file type to be selected, you /// set the <see cref="FilterIndex"/> property before showing the open file dialog or the /// save file dialog. /// </remarks> public string Filter { get; set; } = string.Empty; /// <summary> /// Gets or sets the index of the filter currently selected in a file dialog. /// </summary> /// <value> /// The <see cref="int" /> that is the index of the selected filter. The default is 1. /// </value> /// <remarks> /// This index is 1-based, not 0-based, due to compatibility requirements with the /// underlying Win32 API. /// </remarks> public int FilterIndex { get; set; } = 1; /// <summary> /// Gets or sets the initial directory that is displayed by a file dialog. /// </summary> /// <value> /// A <see cref="string"/> that contains the initial directory. The default is /// <see cref="string.Empty"/>. /// </value> /// <remarks> /// If there is no initial directory set, this property will contain /// <see cref="string.Empty"/> rather than a <c>null</c> string. /// </remarks> public string InitialDirectory { get; set; } = string.Empty; /// <summary> /// Gets a string that only contains the file name for the selected file. /// </summary> /// <value> /// A <see cref="string"/> that only contains the file name for the selected file. The /// default is <see cref="string.Empty"/>, which is also the value when either no file is /// selected or a directory is selected. /// </value> /// <remarks> /// This value is the <see cref="FileName"/> with all path information removed. Removing /// the paths makes the value appropriate for use in partial trust applications, since it /// prevents applications from discovering information about the local file system. /// <para/> /// If more than one file name is selected (length of <see cref="SafeFileNames"/> is /// greater than one) then this property contains only the first selected file name. /// </remarks> public string SafeFileName { internal set; get; } = string.Empty; /// <summary> /// Gets an array that contains one safe file name for each selected file. /// </summary> /// <value> /// An array of <see cref="string"/> that contains one safe file name for each selected /// file. The default is an array with a single item whose value is /// <see cref="string.Empty"/>. /// </value> /// <remarks> /// This value is the <see cref="FileNames"/> with all path information removed. Removing /// the paths makes the value appropriate for use in partial trust applications, since it /// prevents applications from discovering information about the local file system. /// </remarks> public string[] SafeFileNames { internal set; get; } = new string[0]; /// <summary> /// Gets or sets the text that appears in the title bar of a file dialog. /// </summary> /// <value> /// A <see cref="string"/> that is the text that appears in the title bar of a file dialog. /// The default is <see cref="string.Empty"/>. /// </value> /// <remarks> /// If <see cref="Title"/> is <c>null</c> or <see cref="string.Empty"/>, a default, /// localized value is used, such as "Save As" or "Open". /// </remarks> public string Title { get; set; } = string.Empty; /// <summary> /// Gets or sets a value indicating whether the dialog accepts only valid Win32 file names. /// </summary> /// <value> /// <c>true</c> if warnings will be shown when an invalid file name is provided; otherwise, /// <c>false</c>. The default is <c>true</c>. /// </value> public bool ValidateNames { get; set; } = true; } }
50.95935
171
0.590619
[ "MIT" ]
danjoconnell/VideoScriptEditor
VideoScriptEditor/VideoScriptEditor.Core/Services/Dialog/SystemFileDialogSettings.cs
12,538
C#
using RadarSoft.RadarCube.Enums; namespace RadarSoft.RadarCube.Interfaces { internal interface IChartGridZone { ChartGridZone Zone { get; } } }
18.222222
40
0.707317
[ "MIT" ]
RadarSoft/radarcube-olap-analysis
src/Interfaces/IChartGridZone.cs
164
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("Sort The Odd")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Hewlett-Packard")] [assembly: AssemblyProduct("Sort The Odd")] [assembly: AssemblyCopyright("Copyright © Hewlett-Packard 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("64bc9fb9-0d2e-4275-8655-91a060c58b63")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.432432
84
0.748945
[ "MIT" ]
Uendy/CodeWars
CodeWars/Sort The Odd/Properties/AssemblyInfo.cs
1,425
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.KeyVault.Models; using Microsoft.Azure.WebJobs.Script.Config; using Microsoft.Azure.WebJobs.Script.Diagnostics; using Microsoft.Azure.WebJobs.Script.WebHost.Properties; using Microsoft.Extensions.Logging; using DataProtectionCostants = Microsoft.Azure.Web.DataProtection.Constants; namespace Microsoft.Azure.WebJobs.Script.WebHost { public class SecretManager : IDisposable, ISecretManager { private readonly ConcurrentDictionary<string, Dictionary<string, string>> _secretsMap = new ConcurrentDictionary<string, Dictionary<string, string>>(); private readonly IKeyValueConverterFactory _keyValueConverterFactory; private readonly ILogger _logger; private readonly ISecretsRepository _repository; private readonly HostNameProvider _hostNameProvider; private HostSecretsInfo _hostSecrets; private SemaphoreSlim _hostSecretsLock = new SemaphoreSlim(1, 1); private IMetricsLogger _metricsLogger; private string _repositoryClassName; // for testing public SecretManager() { } public SecretManager(ISecretsRepository repository, ILogger logger, IMetricsLogger metricsLogger, HostNameProvider hostNameProvider, bool createHostSecretsIfMissing = false) : this(repository, new DefaultKeyValueConverterFactory(repository.IsEncryptionSupported), logger, metricsLogger, hostNameProvider, createHostSecretsIfMissing) { } public SecretManager(ISecretsRepository repository, IKeyValueConverterFactory keyValueConverterFactory, ILogger logger, IMetricsLogger metricsLogger, HostNameProvider hostNameProvider, bool createHostSecretsIfMissing = false) { _repository = repository; _keyValueConverterFactory = keyValueConverterFactory; _repository.SecretsChanged += OnSecretsChanged; _logger = logger; _metricsLogger = metricsLogger ?? throw new ArgumentNullException(nameof(metricsLogger)); _repositoryClassName = _repository.GetType().Name.ToLower(); _hostNameProvider = hostNameProvider; if (createHostSecretsIfMissing) { // GetHostSecrets will create host secrets if not present GetHostSecretsAsync().GetAwaiter().GetResult(); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { (_repository as IDisposable)?.Dispose(); _hostSecretsLock.Dispose(); } } public async virtual Task<HostSecretsInfo> GetHostSecretsAsync() { using (_metricsLogger.LatencyEvent(GetMetricEventName(MetricEventNames.SecretManagerGetHostSecrets))) { if (_hostSecrets == null) { HostSecrets hostSecrets; // Allow only one thread to modify the secrets await _hostSecretsLock.WaitAsync(); try { hostSecrets = await LoadSecretsAsync<HostSecrets>(); if (hostSecrets == null) { // host secrets do not yet exist so generate them _logger.LogDebug(Resources.TraceHostSecretGeneration); hostSecrets = GenerateHostSecrets(); await PersistSecretsAsync(hostSecrets); } try { // Host secrets will be in the original persisted state at this point (e.g. encrypted), // so we read the secrets running them through the appropriate readers hostSecrets = ReadHostSecrets(hostSecrets); } catch (CryptographicException ex) { string message = string.Format(Resources.TraceNonDecryptedHostSecretRefresh, ex); _logger?.LogDebug(message); await PersistSecretsAsync(hostSecrets, null, true); hostSecrets = GenerateHostSecrets(hostSecrets); await RefreshSecretsAsync(hostSecrets); } // If the persistence state of any of our secrets is stale (e.g. the encryption key has been rotated), update // the state and persist the secrets if (hostSecrets.HasStaleKeys) { _logger.LogDebug(Resources.TraceStaleHostSecretRefresh); await RefreshSecretsAsync(hostSecrets); } _hostSecrets = new HostSecretsInfo { MasterKey = hostSecrets.MasterKey.Value, FunctionKeys = hostSecrets.FunctionKeys.ToDictionary(s => s.Name, s => s.Value), SystemKeys = hostSecrets.SystemKeys.ToDictionary(s => s.Name, s => s.Value) }; } finally { _hostSecretsLock.Release(); } } return _hostSecrets; } } public async virtual Task<IDictionary<string, string>> GetFunctionSecretsAsync(string functionName, bool merged = false) { using (_metricsLogger.LatencyEvent(GetMetricEventName(MetricEventNames.SecretManagerGetFunctionSecrets), functionName)) { if (string.IsNullOrEmpty(functionName)) { throw new ArgumentNullException(nameof(functionName)); } functionName = functionName.ToLowerInvariant(); Dictionary<string, string> functionSecrets; _secretsMap.TryGetValue(functionName, out functionSecrets); if (functionSecrets == null) { FunctionSecrets secrets = await LoadFunctionSecretsAsync(functionName); if (secrets == null) { // no secrets exist for this function so generate them string message = string.Format(Resources.TraceFunctionSecretGeneration, functionName); _logger.LogDebug(message); secrets = GenerateFunctionSecrets(); await PersistSecretsAsync(secrets, functionName); } try { // Read all secrets, which will run the keys through the appropriate readers secrets.Keys = secrets.Keys.Select(k => _keyValueConverterFactory.ReadKey(k)).ToList(); } catch (CryptographicException ex) { string message = string.Format(Resources.TraceNonDecryptedFunctionSecretRefresh, functionName, ex); _logger?.LogDebug(message); await PersistSecretsAsync(secrets, functionName, true); secrets = GenerateFunctionSecrets(secrets); await RefreshSecretsAsync(secrets, functionName); } if (secrets.HasStaleKeys) { _logger.LogDebug(string.Format(Resources.TraceStaleFunctionSecretRefresh, functionName)); await RefreshSecretsAsync(secrets, functionName); } Dictionary<string, string> result = secrets.Keys.ToDictionary(s => s.Name, s => s.Value); functionSecrets = _secretsMap.AddOrUpdate(functionName, result, (n, r) => result); } if (merged) { // If merged is true, we combine function specific keys with host level function keys, // prioritizing function specific keys HostSecretsInfo hostSecrets = await GetHostSecretsAsync(); Dictionary<string, string> hostFunctionSecrets = hostSecrets.FunctionKeys; functionSecrets = functionSecrets.Union(hostFunctionSecrets.Where(s => !functionSecrets.ContainsKey(s.Key))) .ToDictionary(kv => kv.Key, kv => kv.Value); } return functionSecrets; } } public async Task<KeyOperationResult> AddOrUpdateFunctionSecretAsync(string secretName, string secret, string keyScope, ScriptSecretsType secretsType) { using (_metricsLogger.LatencyEvent(GetMetricEventName(MetricEventNames.SecretManagerAddOrUpdateFunctionSecret), GetFunctionName(keyScope, secretsType))) { Func<ScriptSecrets> secretsFactory = null; if (secretsType == ScriptSecretsType.Function) { secretsFactory = () => new FunctionSecrets(new List<Key>()); } else if (secretsType == ScriptSecretsType.Host) { secretsType = ScriptSecretsType.Host; secretsFactory = GenerateHostSecrets; } else { throw new NotSupportedException($"Secrets type {secretsType.ToString("G")} not supported."); } KeyOperationResult result = await AddOrUpdateSecretAsync(secretsType, keyScope, secretName, secret, secretsFactory); _logger.LogInformation(string.Format(Resources.TraceAddOrUpdateFunctionSecret, secretsType, secretName, keyScope ?? "host", result.Result)); return result; } } public async Task<KeyOperationResult> SetMasterKeyAsync(string value = null) { using (_metricsLogger.LatencyEvent(GetMetricEventName(MetricEventNames.SecretManagerSetMasterKey))) { HostSecrets secrets = await LoadSecretsAsync<HostSecrets>(); if (secrets == null) { secrets = GenerateHostSecrets(); } OperationResult result; string masterKey; if (value == null) { // Generate a new secret (clear) masterKey = GenerateSecret(); result = OperationResult.Created; } else { // Use the provided secret masterKey = value; result = OperationResult.Updated; } // Creates a key with the new master key (which will be encrypted, if required) secrets.MasterKey = CreateKey(ScriptConstants.DefaultMasterKeyName, masterKey); await PersistSecretsAsync(secrets); _logger.LogInformation(string.Format(Resources.TraceMasterKeyCreatedOrUpdated, result)); return new KeyOperationResult(masterKey, result); } } public async Task<bool> DeleteSecretAsync(string secretName, string keyScope, ScriptSecretsType secretsType) { using (_metricsLogger.LatencyEvent(GetMetricEventName(MetricEventNames.SecretManagerDeleteSecret), GetFunctionName(keyScope, secretsType))) { bool deleted = await ModifyFunctionSecretAsync(secretsType, keyScope, secretName, (secrets, key) => { secrets?.RemoveKey(key, keyScope); return secrets; }); if (deleted) { string target = secretsType == ScriptSecretsType.Function ? $"Function ('{keyScope}')" : $"Host (scope: '{keyScope}')"; _logger.LogInformation(string.Format(Resources.TraceSecretDeleted, target, secretName)); } return deleted; } } private async Task<KeyOperationResult> AddOrUpdateSecretAsync(ScriptSecretsType secretsType, string keyScope, string secretName, string secret, Func<ScriptSecrets> secretsFactory) { OperationResult result = OperationResult.NotFound; secret = secret ?? GenerateSecret(); await ModifyFunctionSecretsAsync(secretsType, keyScope, secrets => { Key key = secrets.GetFunctionKey(secretName, keyScope); var createAndUpdateKey = new Action<OperationResult>((o) => { var newKey = CreateKey(secretName, secret); secrets.AddKey(newKey, keyScope); result = o; }); if (key == null) { createAndUpdateKey(OperationResult.Created); } else if (secrets.RemoveKey(key, keyScope)) { createAndUpdateKey(OperationResult.Updated); } return secrets; }, secretsFactory).ContinueWith(t => { if (t.IsFaulted && t.Exception.InnerException is KeyVaultErrorException) { result = OperationResult.Forbidden; } }); return new KeyOperationResult(secret, result); } private async Task<bool> ModifyFunctionSecretAsync(ScriptSecretsType secretsType, string keyScope, string secretName, Func<ScriptSecrets, Key, ScriptSecrets> keyChangeHandler, Func<ScriptSecrets> secretFactory = null) { bool secretFound = false; await ModifyFunctionSecretsAsync(secretsType, keyScope, secrets => { Key key = secrets?.GetFunctionKey(secretName, keyScope); if (key != null) { secretFound = true; secrets = keyChangeHandler(secrets, key); } return secrets; }, secretFactory); return secretFound; } private async Task ModifyFunctionSecretsAsync(ScriptSecretsType secretsType, string keyScope, Func<ScriptSecrets, ScriptSecrets> changeHandler, Func<ScriptSecrets> secretFactory) { ScriptSecrets currentSecrets = await LoadSecretsAsync(secretsType, keyScope); if (currentSecrets == null) { currentSecrets = secretFactory?.Invoke(); } var newSecrets = changeHandler(currentSecrets); if (newSecrets != null) { await PersistSecretsAsync(newSecrets, keyScope); } } private Task<FunctionSecrets> LoadFunctionSecretsAsync(string functionName) => LoadSecretsAsync<FunctionSecrets>(functionName); private async Task<T> LoadSecretsAsync<T>(string keyScope = null) where T : ScriptSecrets { ScriptSecretsType type = GetSecretsType<T>(); var result = await LoadSecretsAsync(type, keyScope); return result as T; } private async Task<ScriptSecrets> LoadSecretsAsync(ScriptSecretsType type, string keyScope) { return await _repository.ReadAsync(type, keyScope).ConfigureAwait(false); } private static ScriptSecretsType GetSecretsType<T>() where T : ScriptSecrets { return typeof(HostSecrets).IsAssignableFrom(typeof(T)) ? ScriptSecretsType.Host : ScriptSecretsType.Function; } private HostSecrets GenerateHostSecrets() { return new HostSecrets { MasterKey = GenerateKey(ScriptConstants.DefaultMasterKeyName), FunctionKeys = new List<Key> { GenerateKey(ScriptConstants.DefaultFunctionKeyName) }, SystemKeys = new List<Key>() }; } private HostSecrets GenerateHostSecrets(HostSecrets secrets) { if (secrets.MasterKey.IsEncrypted) { secrets.MasterKey.Value = GenerateSecret(); } secrets.SystemKeys = RegenerateKeys(secrets.SystemKeys); secrets.FunctionKeys = RegenerateKeys(secrets.FunctionKeys); return secrets; } private FunctionSecrets GenerateFunctionSecrets() { return new FunctionSecrets { Keys = new List<Key> { GenerateKey(ScriptConstants.DefaultFunctionKeyName) } }; } private FunctionSecrets GenerateFunctionSecrets(FunctionSecrets secrets) { secrets.Keys = RegenerateKeys(secrets.Keys); return secrets; } private IList<Key> RegenerateKeys(IList<Key> list) { return list.Select(k => { if (k.IsEncrypted) { k.Value = GenerateSecret(); } return k; }).ToList(); } private Task RefreshSecretsAsync<T>(T secrets, string keyScope = null) where T : ScriptSecrets { var refreshedSecrets = secrets.Refresh(_keyValueConverterFactory); return PersistSecretsAsync(refreshedSecrets, keyScope); } private async Task PersistSecretsAsync<T>(T secrets, string keyScope = null, bool isNonDecryptable = false) where T : ScriptSecrets { if (secrets != null) { secrets.HostName = _hostNameProvider.Value; } ScriptSecretsType secretsType = secrets.SecretsType; if (isNonDecryptable) { string[] secretBackups = await _repository.GetSecretSnapshots(secrets.SecretsType, keyScope); if (secretBackups.Length >= ScriptConstants.MaximumSecretBackupCount) { string message = string.Format(Resources.ErrorTooManySecretBackups, ScriptConstants.MaximumSecretBackupCount, string.IsNullOrEmpty(keyScope) ? "host" : keyScope, await AnalyzeSnapshots(secretBackups)); _logger?.LogDebug(message); throw new InvalidOperationException(message); } await _repository.WriteSnapshotAsync(secretsType, keyScope, secrets); } else { // We want to store encryption keys hashes to investigate sudden regenerations string hashes = GetEncryptionKeysHashes(); secrets.DecryptionKeyId = hashes; _logger?.LogInformation("Encription keys hashes: {0}", hashes); await _repository.WriteAsync(secretsType, keyScope, secrets); } } private HostSecrets ReadHostSecrets(HostSecrets hostSecrets) { return new HostSecrets { MasterKey = _keyValueConverterFactory.ReadKey(hostSecrets.MasterKey), FunctionKeys = hostSecrets.FunctionKeys.Select(k => _keyValueConverterFactory.ReadKey(k)).ToList(), SystemKeys = hostSecrets.SystemKeys?.Select(k => _keyValueConverterFactory.ReadKey(k)).ToList() ?? new List<Key>() }; } private Key GenerateKey(string name = null) { string secret = GenerateSecret(); return CreateKey(name, secret); } private Key CreateKey(string name, string secret) { var key = new Key(name, secret); return _keyValueConverterFactory.WriteKey(key); } internal static string GenerateSecret() { using (var rng = RandomNumberGenerator.Create()) { byte[] data = new byte[40]; rng.GetBytes(data); string secret = Convert.ToBase64String(data); // Replace pluses as they are problematic as URL values return secret.Replace('+', 'a'); } } private void OnSecretsChanged(object sender, SecretsChangedEventArgs e) { // clear the cached secrets if they exist // they'll be reloaded on demand next time if (e.SecretsType == ScriptSecretsType.Host) { _hostSecrets = null; } else { if (string.IsNullOrEmpty(e.Name)) { _secretsMap.Clear(); } else { _secretsMap.TryRemove(e.Name, out _); } } } private async Task<string> AnalyzeSnapshots(string[] secretBackups) { string analyzeResult = string.Empty; try { List<ScriptSecrets> shapShots = new List<ScriptSecrets>(); foreach (string secretPath in secretBackups) { ScriptSecrets secrets = await _repository.ReadAsync(ScriptSecretsType.Function, Path.GetFileNameWithoutExtension(secretPath)); shapShots.Add(secrets); } string[] hosts = shapShots.Select(x => x.HostName).Distinct().ToArray(); if (hosts.Length > 1) { analyzeResult = string.Format(Resources.ErrorSameSecrets, string.Join(",", hosts)); } } catch { // best effort } return analyzeResult; } public async Task PurgeOldSecretsAsync(string rootScriptPath, ILogger logger) { using (_metricsLogger.LatencyEvent(GetMetricEventName(MetricEventNames.SecretManagerPurgeOldSecrets))) { if (!Directory.Exists(rootScriptPath)) { return; } // Create a lookup of all potential functions (whether they're valid or not) // It is important that we determine functions based on the presence of a folder, // not whether we've identified a valid function from that folder. This ensures // that we don't delete logs/secrets for functions that transition into/out of // invalid unparsable states. var currentFunctions = Directory.EnumerateDirectories(rootScriptPath).Select(p => Path.GetFileName(p)).ToList(); await _repository.PurgeOldSecretsAsync(currentFunctions, logger); } } private string GetMetricEventName(string name) { return string.Format(CultureInfo.InvariantCulture, name, _repositoryClassName); } private string GetFunctionName(string keyScope, ScriptSecretsType secretsType) { return (secretsType == ScriptSecretsType.Function) ? keyScope : null; } private string GetEncryptionKeysHashes() { string result = string.Empty; string azureWebsiteLocalEncryptionKey = SystemEnvironment.Instance.GetEnvironmentVariable(DataProtectionCostants.AzureWebsiteLocalEncryptionKey) ?? string.Empty; SHA256Managed hash = new SHA256Managed(); if (!string.IsNullOrEmpty(azureWebsiteLocalEncryptionKey)) { byte[] hashBytes = hash.ComputeHash(Encoding.UTF8.GetBytes(azureWebsiteLocalEncryptionKey)); string azureWebsiteLocalEncryptionKeyHash = Convert.ToBase64String(hashBytes); result += $"{DataProtectionCostants.AzureWebsiteLocalEncryptionKey}={azureWebsiteLocalEncryptionKeyHash};"; } string azureWebsiteEnvironmentMachineKey = SystemEnvironment.Instance.GetEnvironmentVariable(DataProtectionCostants.AzureWebsiteEnvironmentMachineKey) ?? string.Empty; if (!string.IsNullOrEmpty(azureWebsiteEnvironmentMachineKey)) { byte[] hashBytes = hash.ComputeHash(Encoding.UTF8.GetBytes(azureWebsiteEnvironmentMachineKey)); string azureWebsiteEnvironmentMachineKeyHash = Convert.ToBase64String(hashBytes); result += $"{DataProtectionCostants.AzureWebsiteEnvironmentMachineKey}={azureWebsiteEnvironmentMachineKeyHash};"; } return result; } } }
41.067742
233
0.571165
[ "Apache-2.0", "MIT" ]
AtOMiCNebula/azure-functions-host
src/WebJobs.Script.WebHost/Security/KeyManagement/SecretManager.cs
25,464
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.Cpdp.V20190820.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class CreateRedInvoiceResponse : AbstractModel { /// <summary> /// 红冲结果 /// </summary> [JsonProperty("Result")] public CreateRedInvoiceResult Result{ 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.SetParamObj(map, prefix + "Result.", this.Result); this.SetParamSimple(map, prefix + "RequestId", this.RequestId); } } }
30.529412
83
0.64483
[ "Apache-2.0" ]
ImEdisonJiang/tencentcloud-sdk-dotnet
TencentCloud/Cpdp/V20190820/Models/CreateRedInvoiceResponse.cs
1,623
C#
#region License /* Copyright © 2014-2021 European Support Limited Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using Amdocs.Ginger.Common; using System.Windows.Controls; using GingerCore.Actions; using GingerCore.Actions.Java; using GingerWPF.UserControlsLib.UCTreeView; namespace Ginger.WindowExplorer.Java { class JavaTabTreeItem : JavaElementTreeItem, ITreeViewItem, IWindowExplorerTreeItem { StackPanel ITreeViewItem.Header() { return TreeViewUtils.CreateItemHeader(Name, Amdocs.Ginger.Common.Enums.eImageType.Agent); } ObservableList<Act> IWindowExplorerTreeItem.GetElementActions() { ObservableList<Act> list = new ObservableList<Act>(); list.Add(new ActJavaElement() { Description = "Select Tab " + Name, ControlAction = ActJavaElement.eControlAction.Select }); list.Add(new ActJavaElement() { Description = "Get Selected Tab Value " + Name, ControlAction = ActJavaElement.eControlAction.GetValue }); return list; } } }
31.301887
101
0.685353
[ "Apache-2.0" ]
Ginger-Automation/Ginger
Ginger/Ginger/AutomatePageLib/AddActionMenu/WindowExplorer/Java/JavaTabTreeItem.cs
1,660
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Xml; using Microsoft.Build.Evaluation; using Microsoft.Build.Utilities; namespace Dnt.Commands { public static class ProjectExtensions { public static bool GeneratesPackage(this Project project) { return project.GetProperty("GeneratePackageOnBuild")?.EvaluatedValue.ToLowerInvariant() == "true"; } public static bool HasVersion(this Project project) { var data = File.ReadAllText(project.FullPath); return data.Contains("<Version>"); //return project.Properties.Any(i => i.Name == "Version" && !string.IsNullOrEmpty(i.UnevaluatedValue)); } public static bool IsSupportedProject(string projectAbsolutePath) { projectAbsolutePath = projectAbsolutePath.ToLower(); return (projectAbsolutePath.EndsWith(".csproj") || projectAbsolutePath.EndsWith(".vbproj")); } public static ProjectInformation LoadProject(string projectPath) { // Based on https://daveaglick.com/posts/running-a-design-time-build-with-msbuild-apis using (var reader = XmlReader.Create(projectPath)) { if (reader.MoveToContent() == XmlNodeType.Element && reader.HasAttributes) { var isSdkStyle = reader.MoveToAttribute("Sdk"); if (isSdkStyle) { return GetSdkroject(projectPath); } else { return GetLegacyProject(projectPath); } } } throw new InvalidOperationException("Not a project: " + projectPath); } private static ProjectInformation GetLegacyProject(string projectPath) { var toolsPath = GetToolsPath(); var globalProperties = GetLegacyGlobalProperties(projectPath, toolsPath); var projectCollection = new ProjectCollection(globalProperties); projectCollection.AddToolset(new Toolset(ToolLocationHelper.CurrentToolsVersion, toolsPath, projectCollection, string.Empty)); var project = projectCollection.LoadProject(projectPath); return new ProjectInformation(projectCollection, project, false); } private static ProjectInformation GetSdkroject(string projectPath) { var toolsPath = GetSdkBasePath(projectPath); var globalProperties = GetSdkGlobalProperties(projectPath, toolsPath); Environment.SetEnvironmentVariable( "MSBuildExtensionsPath", globalProperties["MSBuildExtensionsPath"]); Environment.SetEnvironmentVariable( "MSBuildSDKsPath", globalProperties["MSBuildSDKsPath"]); var projectCollection = new ProjectCollection(globalProperties); projectCollection.AddToolset(new Toolset(ToolLocationHelper.CurrentToolsVersion, toolsPath, projectCollection, string.Empty)); var project = projectCollection.LoadProject(projectPath); return new ProjectInformation(projectCollection, project, true); } private static string GetToolsPath() { var toolsPath = ToolLocationHelper.GetPathToBuildToolsFile("msbuild.exe", ToolLocationHelper.CurrentToolsVersion); if (string.IsNullOrEmpty(toolsPath)) { toolsPath = PollForToolsPath().FirstOrDefault(); } if (string.IsNullOrEmpty(toolsPath)) { throw new Exception("Could not locate the tools (MSBuild) path."); } return Path.GetDirectoryName(toolsPath); } private static string[] PollForToolsPath() { var programFilesX86 = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86); return new[] { Path.Combine(programFilesX86, @"Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\MSBuild.exe"), Path.Combine(programFilesX86, @"Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\MSBuild.exe"), Path.Combine(programFilesX86, @"Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\MSBuild.exe"), Path.Combine(programFilesX86, @"MSBuild\14.0\Bin\MSBuild.exe"), Path.Combine(programFilesX86, @"MSBuild\12.0\Bin\MSBuild.exe") }.Where(File.Exists).ToArray(); } private static Dictionary<string, string> GetLegacyGlobalProperties(string projectPath, string toolsPath) { var solutionDir = Path.GetDirectoryName(projectPath); var extensionsPath = Path.GetFullPath(Path.Combine(toolsPath, @"..\..\")); var sdksPath = Path.Combine(extensionsPath, "Sdks"); var roslynTargetsPath = Path.Combine(toolsPath, "Roslyn"); return new Dictionary<string, string> { { "SolutionDir", solutionDir }, { "MSBuildExtensionsPath", extensionsPath }, { "MSBuildExtensionsPath32", extensionsPath }, { "MSBuildSDKsPath", sdksPath }, { "RoslynTargetsPath", roslynTargetsPath } }; } private static Dictionary<string, string> GetSdkGlobalProperties(string projectPath, string toolsPath) { var solutionDir = Path.GetDirectoryName(projectPath); var extensionsPath = toolsPath; var sdksPath = Path.Combine(toolsPath, "Sdks"); var roslynTargetsPath = Path.Combine(toolsPath, "Roslyn"); return new Dictionary<string, string> { { "SolutionDir", solutionDir }, { "MSBuildExtensionsPath", extensionsPath }, { "MSBuildSDKsPath", sdksPath }, { "RoslynTargetsPath", roslynTargetsPath } }; } private static string GetSdkBasePath(string projectPath) { // Ensure that we set the DOTNET_CLI_UI_LANGUAGE environment variable to "en-US" before // running 'dotnet --info'. Otherwise, we may get localized results. var originalCliLanguage = Environment.GetEnvironmentVariable("DOTNET_CLI_UI_LANGUAGE"); Environment.SetEnvironmentVariable("DOTNET_CLI_UI_LANGUAGE", "en-US"); try { // Create the process info var startInfo = new ProcessStartInfo("dotnet", "--info") { // global.json may change the version, so need to set working directory WorkingDirectory = Path.GetDirectoryName(projectPath), CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; // Execute the process using (var process = Process.Start(startInfo)) { var lines = new List<string>(); process.OutputDataReceived += (_, e) => { if (!string.IsNullOrWhiteSpace(e.Data)) { lines.Add(e.Data); } }; process.BeginOutputReadLine(); process.WaitForExit(); return ParseSdkBasePath(lines); } } finally { Environment.SetEnvironmentVariable("DOTNET_CLI_UI_LANGUAGE", originalCliLanguage); } } private static string ParseSdkBasePath(List<string> lines) { if (lines == null || lines.Count == 0) { throw new Exception("Could not get results from `dotnet --info` call"); } foreach (string line in lines) { var colonIndex = line.IndexOf(':'); if (colonIndex >= 0 && line.Substring(0, colonIndex).Trim().Equals("Base Path", StringComparison.OrdinalIgnoreCase)) { return line.Substring(colonIndex + 1).Trim(); } } throw new Exception("Could not locate base path in `dotnet --info` results"); } } }
40.674528
138
0.578453
[ "MIT" ]
MaartenBE/DNT
src/Dnt.Commands/ProjectExtensions.cs
8,625
C#
using System; using System.Collections.Generic; using System.Text; namespace SkiRental { public class Ski { public Ski(string manufacturer,string model,int year) { Manufacturer = manufacturer; Model = model; Year = year; } public string Manufacturer { get; set; } public string Model { get; set; } public int Year { get; set; } public override string ToString() { return $"{Manufacturer} - {Model} - {Year}"; } } }
21.192308
61
0.546279
[ "MIT" ]
IvanIvTodorov/SoftUniEducation
C#Advanced/C#AdvancedExams/Exam26June2021/SkiRental/Ski.cs
553
C#
using AllReady.ViewModels.Shared; using MediatR; namespace AllReady.Features.Tasks { public class VolunteerTaskSignupCommand : IAsyncRequest<VolunteerTaskSignupResult> { public VolunteerTaskSignupViewModel TaskSignupModel { get; set; } } }
23.818182
86
0.767176
[ "MIT" ]
7as8ydh/allReady
AllReadyApp/Web-App/AllReady/Features/Tasks/VolunteerTaskSignupCommand.cs
264
C#
using MasterDevs.ChromeDevTools; using Newtonsoft.Json; using System; using System.Collections.Generic; namespace MasterDevs.ChromeDevTools.Protocol.Chrome.Page { [CommandResponse(ProtocolName.Page.GetManifestIcons)] [SupportedBy("Chrome")] public class GetManifestIconsCommandResponse { /// <summary> /// Gets or sets PrimaryIcon /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public string PrimaryIcon { get; set; } } }
24.526316
62
0.774678
[ "MIT" ]
rollrat/custom-crawler
ChromeDevTools/Protocol/Chrome/Page/GetManifestIconsCommandResponse.cs
466
C#
// Copyright (c) 2019 Alachisoft // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License using System; using System.Runtime.InteropServices; using System.Security.Permissions; using System.ComponentModel; namespace Alachisoft.NCache.Common.Util { /// <summary> /// Gets and sets the processor affinity of the current thread. /// </summary> public static class ProcessorAffinity { static class Win32Native { //GetCurrentThread() returns only a pseudo handle. No need for a SafeHandle here. [DllImport("kernel32.dll")] public static extern IntPtr GetCurrentThread(); [HostProtectionAttribute(SelfAffectingThreading = true)] [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern UIntPtr SetThreadAffinityMask(IntPtr handle, UIntPtr mask); } public struct ProcessorAffinityHelper : IDisposable { UIntPtr lastaffinity; internal ProcessorAffinityHelper(UIntPtr lastaffinity) { this.lastaffinity = lastaffinity; } #region IDisposable Members public void Dispose() { if (lastaffinity != UIntPtr.Zero) { Win32Native.SetThreadAffinityMask(Win32Native.GetCurrentThread(), lastaffinity); lastaffinity = UIntPtr.Zero; } } #endregion } static ulong maskfromids(params int[] ids) { ulong mask = 0; foreach (int id in ids) { if (id < 0 || id >= Environment.ProcessorCount) throw new ArgumentOutOfRangeException("CPUId", id.ToString()); mask |= 1UL << id; } return mask; } /// <summary> /// Sets a processor affinity mask for the current thread. /// </summary> /// <param name="mask">A thread affinity mask where each bit set to 1 specifies a logical processor on which this thread is allowed to run. /// <remarks>Note: a thread cannot specify a broader set of CPUs than those specified in the process affinity mask.</remarks> /// </param> /// <returns>The previous affinity mask for the current thread.</returns> public static UIntPtr SetThreadAffinityMask(UIntPtr mask) { UIntPtr lastaffinity = Win32Native.SetThreadAffinityMask(Win32Native.GetCurrentThread(), mask); if (lastaffinity == UIntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error()); return lastaffinity; } /// <summary> /// Sets the logical CPUs that the current thread is allowed to execute on. /// </summary> /// <param name="CPUIds">One or more logical processor identifier(s) the current thread is allowed to run on.<remarks>Note: numbering starts from 0.</remarks></param> /// <returns>The previous affinity mask for the current thread.</returns> public static UIntPtr SetThreadAffinity(params int[] CPUIds) { return SetThreadAffinityMask(((UIntPtr)maskfromids(CPUIds))); } /// <summary> /// Restrict a code block to run on the specified logical CPUs in conjuction with /// the <code>using</code> statement. /// </summary> /// <param name="CPUIds">One or more logical processor identifier(s) the current thread is allowed to run on.<remarks>Note: numbering starts from 0.</remarks></param> /// <returns>A helper structure that will reset the affinity when its Dispose() method is called at the end of the using block.</returns> public static ProcessorAffinityHelper BeginAffinity(params int[] CPUIds) { return new ProcessorAffinityHelper(SetThreadAffinityMask(((UIntPtr)maskfromids(CPUIds)))); } } }
40.756757
174
0.627542
[ "Apache-2.0" ]
delsoft/NCache
Src/NCCommon/Util/ProcessorAffinity.cs
4,524
C#
using CSharpSpeed; using System.Diagnostics; using System.Runtime.CompilerServices; using static InstrumentedLibrary.Maths; namespace InstrumentedLibrary { /// <summary> /// /// </summary> public static class ElasticOutInValueEasingTests { /// <summary> /// /// </summary> /// <param name="t"></param> /// <param name="b"></param> /// <param name="c"></param> /// <param name="d"></param> /// <returns></returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] [Signature] public static double ElasticOutIn(double t, double b, double c, double d) => ElasticOutIn1(t, b, c, d); /// <summary> /// Easing equation function for an elastic (exponentially decaying sine wave) easing out/in: /// deceleration until halfway, then acceleration. /// </summary> /// <param name="t">Current time elapsed in ticks.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> /// <acknowledgment> /// https://github.com/darrendavid/wpf-animation /// </acknowledgment> [DebuggerStepThrough] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double ElasticOutIn1(double t, double b, double c, double d) { return (t < d * OneHalf) ? ElasticOutValueEasingTests.ElasticOut(t * 2d, b, c * OneHalf, d) : ElasticInValueEasingTests.ElasticIn((t * 2d) - d, b + (c * OneHalf), c * OneHalf, d); } } }
36.869565
191
0.591392
[ "MIT" ]
Shkyrockett/CSharpSpeed
InstrumentedLibrary/Dynamics/ValueEasing/ElasticOutInValueEasingTests.cs
1,698
C#
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Threading.Tasks; using ANYWAYS.UrbanisticPolygons.Graphs.Polygons; using ANYWAYS.UrbanisticPolygons.Tiles; using NetTopologySuite.Features; using OsmSharp; using OsmSharp.Tags; namespace ANYWAYS.UrbanisticPolygons { public static class TiledPolygonGraphBuilder { public static async IAsyncEnumerable<Feature> GetPolygonsForTile((uint x, uint y, int zoom) tile, string folder, Func<uint, IEnumerable<OsmGeo>> getTile, Func<TagsCollectionBase, bool> isBarrier, bool build = true) { if (tile.zoom > 14) throw new ArgumentException("Zoom has to maximum 14."); if (tile.zoom == 14) { foreach (var (p, _) in await GetPolygonsForTile(TileStatic.ToLocalId(tile.x, tile.y, tile.zoom), folder, getTile, isBarrier, build)) { yield return p; } } else { var faceGuids = new HashSet<Guid>(); foreach (var t in tile.SubTilesFor(14)) { var ps = await GetPolygonsForTile(TileStatic.ToLocalId(t.x, t.y, 14), folder, getTile, isBarrier, build); foreach (var (p, id) in ps) { if (faceGuids.Contains(id)) continue; faceGuids.Add(id); yield return p; } } } } private static async Task<IEnumerable<(Feature feature, Guid id)>> GetPolygonsForTile(uint tile, string folder, Func<uint, IEnumerable<OsmGeo>> getTile, Func<TagsCollectionBase, bool> isBarrier, bool build = true) { if (build) await TiledBarrierGraphBuilder.BuildForTile(tile, folder, getTile, isBarrier); var file = Path.Combine(folder, $"{tile}.tile.graph.zip"); if (!File.Exists(file)) return Enumerable.Empty<(Feature feature, Guid id)>(); await using var stream = File.OpenRead(file); await using var gzipStream = new GZipStream(stream, CompressionMode.Decompress); var polygonGraph = new TiledPolygonGraph(); polygonGraph.AddTileFromStream(tile, gzipStream); return polygonGraph.GetAllPolygons(); } } }
37.268657
125
0.579495
[ "MIT" ]
anyways-open/coherent-polygons
src/ANYWAYS.UrbanisticPolygons/TiledPolygonGraphBuilder.cs
2,497
C#
using System; using System.Collections; using System.Collections.Generic; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; using NetOffice.CollectionsGeneric; namespace NetOffice.DAOApi { /// <summary> /// DispatchInterface TableDefs /// SupportByVersion DAO, 3.6,12.0 /// </summary> [SupportByVersion("DAO", 3.6,12.0)] [EntityType(EntityType.IsDispatchInterface), Enumerator(Enumerator.Reference, EnumeratorInvoke.Method, "DAO", 3.6, 12.0), HasIndexProperty(IndexInvoke.Property, "Item")] [TypeId("0000004B-0000-0010-8000-00AA006D2EA4")] public interface TableDefs : _DynaCollection, IEnumerableProvider<NetOffice.DAOApi.TableDef> { #region Properties /// <summary> /// SupportByVersion DAO 3.6, 12.0 /// Get /// </summary> /// <param name="item">object item</param> [SupportByVersion("DAO", 3.6,12.0)] [NetRuntimeSystem.Runtime.CompilerServices.IndexerName("Item"), IndexProperty] NetOffice.DAOApi.TableDef this[object item] { get; } #endregion #region IEnumerable<NetOffice.DAOApi.TableDef> /// <summary> /// SupportByVersion DAO, 3.6,12.0 /// </summary> [SupportByVersion("DAO", 3.6, 12.0)] new IEnumerator<NetOffice.DAOApi.TableDef> GetEnumerator(); #endregion } }
29.863636
170
0.703196
[ "MIT" ]
igoreksiz/NetOffice
Source/DAO/DispatchInterfaces/TableDefs.cs
1,316
C#
using System; using System.Text; using System.IO; using System.Globalization; using System.Collections.Generic; //check out ccd2iso linux program? //https://wiki.archlinux.org/index.php/CD_Burning#TOC.2FCUE.2FBIN_for_mixed-mode_disks advice here //also referencing mednafen sources //TODO - copy mednafen sanity checking //TODO - check subcode vs TOC (warnings if different) //TODO - check TOC vs tracks (warnings if different) namespace BizHawk.Emulation.DiscSystem { public class CCD_Format { /// <summary> /// Represents a CCD file, faithfully. Minimal interpretation of the data happens. /// Currently the [TRACK] sections aren't parsed, though. /// </summary> public class CCDFile { /// <summary> /// which version CCD file this came from. We hope it shouldn't affect the semantics of anything else in here, but just in case.. /// </summary> public int Version; /// <summary> /// this is probably a 0 or 1 bool /// </summary> public int DataTracksScrambled; /// <summary> /// ??? /// </summary> public int CDTextLength; /// <summary> /// The [Session] sections /// </summary> public List<CCDSession> Sessions = new List<CCDSession>(); /// <summary> /// The [Entry] sctions /// </summary> public List<CCDTocEntry> TOCEntries = new List<CCDTocEntry>(); /// <summary> /// The [TRACK] sections /// </summary> public List<CCDTrack> Tracks = new List<CCDTrack>(); /// <summary> /// The [TRACK] sections, indexed by number /// </summary> public Dictionary<int, CCDTrack> TracksByNumber = new Dictionary<int, CCDTrack>(); } /// <summary> /// Represents an [Entry] section from a CCD file /// </summary> public class CCDTocEntry { public CCDTocEntry(int entryNum) { EntryNum = entryNum; } /// <summary> /// these should be 0-indexed /// </summary> public int EntryNum; /// <summary> /// the CCD specifies this, but it isnt in the actual disc data as such, it is encoded some other (likely difficult to extract) way and thats why CCD puts it here /// </summary> public int Session; /// <summary> /// this seems just to be the LBA corresponding to AMIN:ASEC:AFRAME (give or take 150). It's not stored on the disc, and it's redundant. /// </summary> public int ALBA; /// <summary> /// this seems just to be the LBA corresponding to PMIN:PSEC:PFRAME (give or take 150). It's not stored on the disc, and it's redundant. /// </summary> public int PLBA; //these correspond pretty directly to values in the Q subchannel fields //NOTE: they're specified as absolute MSF. That means, they're 2 seconds off from what they should be when viewed as final TOC values public int Control; public int ADR; public int TrackNo; public int Point; public int AMin; public int ASec; public int AFrame; public int Zero; public int PMin; public int PSec; public int PFrame; } /// <summary> /// Represents a [Track] section from a CCD file /// </summary> public class CCDTrack { public CCDTrack(int number) { this.Number = number; } /// <summary> /// note: this is 1-indexed /// </summary> public int Number; /// <summary> /// The specified data mode. /// </summary> public int Mode; /// <summary> /// The indexes specified for the track (these are 0-indexed) /// </summary> public Dictionary<int, int> Indexes = new Dictionary<int, int>(); } /// <summary> /// Represents a [Session] section from a CCD file /// </summary> public class CCDSession { public CCDSession(int number) { this.Number = number; } /// <summary> /// note: this is 1-indexed. /// </summary> public int Number; //Not sure what the default should be.. ive only seen mode=2 public int PregapMode; /// <summary> /// this is probably a 0 or 1 bool /// </summary> public int PregapSubcode; } public class CCDParseException : Exception { public CCDParseException(string message) : base(message) { } } class CCDSection : Dictionary<string,int> { public string Name; public int FetchOrDefault(int def, string key) { TryGetValue(key, out def); return def; } public int FetchOrFail(string key) { int ret; if(!TryGetValue(key, out ret)) throw new CCDParseException("Malformed or unexpected CCD format: missing required [Entry] key: " + key); return ret; } } List<CCDSection> ParseSections(Stream stream) { List<CCDSection> sections = new List<CCDSection>(); //TODO - do we need to attempt to parse out the version tag in a first pass? //im doing this from a version 3 example StreamReader sr = new StreamReader(stream); CCDSection currSection = null; for (; ; ) { var line = sr.ReadLine(); if (line == null) break; if (line == "") continue; if (line.StartsWith("[")) { currSection = new CCDSection(); currSection.Name = line.Trim('[', ']').ToUpper(); sections.Add(currSection); } else { var parts = line.Split('='); if (parts.Length != 2) throw new CCDParseException("Malformed or unexpected CCD format: parsing item into two parts"); int val; if (parts[1].StartsWith("0x") || parts[1].StartsWith("0X")) val = int.Parse(parts[1].Substring(2), NumberStyles.HexNumber); else val = int.Parse(parts[1]); currSection[parts[0].ToUpper()] = val; } } //loop until lines exhausted return sections; } int PreParseIntegrityCheck(List<CCDSection> sections) { if (sections.Count == 0) throw new CCDParseException("Malformed CCD format: no sections"); //we need at least a CloneCD and Disc section if (sections.Count < 2) throw new CCDParseException("Malformed CCD format: insufficient sections"); var ccdSection = sections[0]; if (ccdSection.Name != "CLONECD") throw new CCDParseException("Malformed CCD format: confusing first section name"); if (!ccdSection.ContainsKey("VERSION")) throw new CCDParseException("Malformed CCD format: missing version in CloneCD section"); if(sections[1].Name != "DISC") throw new CCDParseException("Malformed CCD format: section[1] isn't [Disc]"); int version = ccdSection["VERSION"]; return version; } /// <summary> /// Parses a CCD file contained in the provided stream /// </summary> public CCDFile ParseFrom(Stream stream) { CCDFile ccdf = new CCDFile(); var sections = ParseSections(stream); ccdf.Version = PreParseIntegrityCheck(sections); var discSection = sections[1]; int nTocEntries = discSection["TOCENTRIES"]; //its conceivable that this could be missing int nSessions = discSection["SESSIONS"]; //its conceivable that this could be missing ccdf.DataTracksScrambled = discSection.FetchOrDefault(0, "DATATRACKSSCRAMBLED"); ccdf.CDTextLength = discSection.FetchOrDefault(0, "CDTEXTLENGTH"); if (ccdf.DataTracksScrambled==1) throw new CCDParseException("Malformed CCD format: DataTracksScrambled=1 not supported. Please report this, so we can understand what it means."); for (int i = 2; i < sections.Count; i++) { var section = sections[i]; if (section.Name.StartsWith("SESSION")) { int sesnum = int.Parse(section.Name.Split(' ')[1]); CCDSession session = new CCDSession(sesnum); ccdf.Sessions.Add(session); if (sesnum != ccdf.Sessions.Count) throw new CCDParseException("Malformed CCD format: wrong session number in sequence"); session.PregapMode = section.FetchOrDefault(0, "PREGAPMODE"); session.PregapSubcode = section.FetchOrDefault(0, "PREGAPSUBC"); } else if (section.Name.StartsWith("ENTRY")) { int entryNum = int.Parse(section.Name.Split(' ')[1]); CCDTocEntry entry = new CCDTocEntry(entryNum); ccdf.TOCEntries.Add(entry); entry.Session = section.FetchOrFail("SESSION"); entry.Point = section.FetchOrFail("POINT"); entry.ADR = section.FetchOrFail("ADR"); entry.Control = section.FetchOrFail("CONTROL"); entry.TrackNo = section.FetchOrFail("TRACKNO"); entry.AMin = section.FetchOrFail("AMIN"); entry.ASec = section.FetchOrFail("ASEC"); entry.AFrame = section.FetchOrFail("AFRAME"); entry.ALBA = section.FetchOrFail("ALBA"); entry.Zero = section.FetchOrFail("ZERO"); entry.PMin = section.FetchOrFail("PMIN"); entry.PSec = section.FetchOrFail("PSEC"); entry.PFrame = section.FetchOrFail("PFRAME"); entry.PLBA = section.FetchOrFail("PLBA"); //note: LBA 0 is Ansolute MSF 00:02:00 if (new Timestamp(entry.AMin, entry.ASec, entry.AFrame).Sector != entry.ALBA + 150) throw new CCDParseException("Warning: inconsistency in CCD ALBA vs computed A MSF"); if (new Timestamp(entry.PMin, entry.PSec, entry.PFrame).Sector != entry.PLBA + 150) throw new CCDParseException("Warning: inconsistency in CCD PLBA vs computed P MSF"); if(entry.Session != 1) throw new CCDParseException("Malformed CCD format: not yet supporting multi-session files"); } else if (section.Name.StartsWith("TRACK")) { int entryNum = int.Parse(section.Name.Split(' ')[1]); CCDTrack track = new CCDTrack(entryNum); ccdf.Tracks.Add(track); ccdf.TracksByNumber[entryNum] = track; foreach (var kvp in section) { if (kvp.Key == "MODE") track.Mode = kvp.Value; if (kvp.Key.StartsWith("INDEX")) { int inum = int.Parse(kvp.Key.Split(' ')[1]); track.Indexes[inum] = kvp.Value; } } } } //sections loop return ccdf; } public class LoadResults { public List<RawTOCEntry> RawTOCEntries; public CCDFile ParsedCCDFile; public bool Valid; public Exception FailureException; public string ImgPath; public string SubPath; public string CcdPath; } public static LoadResults LoadCCDPath(string path) { LoadResults ret = new LoadResults(); ret.CcdPath = path; ret.ImgPath = Path.ChangeExtension(path, ".img"); ret.SubPath = Path.ChangeExtension(path, ".sub"); try { if (!File.Exists(path)) throw new CCDParseException("Malformed CCD format: nonexistent CCD file!"); CCDFile ccdf; using (var infCCD = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) ccdf = new CCD_Format().ParseFrom(infCCD); ret.ParsedCCDFile = ccdf; ret.Valid = true; } catch (CCDParseException ex) { ret.FailureException = ex; } return ret; } public static void Dump(Disc disc, string path) { using (var sw = new StreamWriter(path)) { //NOTE: IsoBuster requires the A0,A1,A2 RawTocEntries to be first or else it can't do anything with the tracks //if we ever get them in a different order, we'll have to re-order them here sw.WriteLine("[CloneCD]"); sw.WriteLine("Version=3"); sw.WriteLine(); sw.WriteLine("[Disc]"); sw.WriteLine("TocEntries={0}", disc.RawTOCEntries.Count); sw.WriteLine("Sessions=1"); sw.WriteLine("DataTracksScrambled=0"); sw.WriteLine("CDTextLength=0"); //not supported anyway sw.WriteLine(); sw.WriteLine("[Session 1]"); sw.WriteLine("PreGapMode=2"); sw.WriteLine("PreGapSubC=1"); sw.WriteLine(); for (int i = 0; i < disc.RawTOCEntries.Count; i++) { var entry = disc.RawTOCEntries[i]; //ehhh something's wrong with how I track these int point = entry.QData.q_index.DecimalValue; if (point == 100) point = 0xA0; if (point == 101) point = 0xA1; if (point == 102) point = 0xA2; sw.WriteLine("[Entry {0}]", i); sw.WriteLine("Session=1"); sw.WriteLine("Point=0x{0:x2}", point); sw.WriteLine("ADR=0x{0:x2}", entry.QData.ADR); sw.WriteLine("Control=0x{0:x2}", (int)entry.QData.CONTROL); sw.WriteLine("TrackNo={0}", entry.QData.q_tno.DecimalValue); sw.WriteLine("AMin={0}", entry.QData.min.DecimalValue); sw.WriteLine("ASec={0}", entry.QData.sec.DecimalValue); sw.WriteLine("AFrame={0}", entry.QData.frame.DecimalValue); sw.WriteLine("ALBA={0}", entry.QData.Timestamp - 150); //remember to adapt the absolute MSF to an LBA (this field is redundant...) sw.WriteLine("Zero={0}", entry.QData.zero); sw.WriteLine("PMin={0}", entry.QData.ap_min.DecimalValue); sw.WriteLine("PSec={0}", entry.QData.ap_sec.DecimalValue); sw.WriteLine("PFrame={0}", entry.QData.ap_frame.DecimalValue); sw.WriteLine("PLBA={0}", entry.QData.AP_Timestamp - 150); //remember to adapt the absolute MSF to an LBA (this field is redundant...) sw.WriteLine(); } //this is nonsense, really. the whole CCD track list shouldn't be needed. //but in order to make a high quality CCD which can be inspected by various other tools, we need it //now, regarding the indexes.. theyre truly useless. having indexes written out with the tracks is bad news. //index information is only truly stored in subQ for (int tnum = 1; tnum <= disc.Session1.LastInformationTrack.Number; tnum++) { var track = disc.Session1.Tracks[tnum]; sw.WriteLine("[TRACK {0}]", track.Number); sw.WriteLine("MODE={0}", track.Mode); //indexes are BS, dont write them. but we certainly need an index 1 sw.WriteLine("INDEX 1={0}", track.LBA); sw.WriteLine(); } } //TODO - actually re-add //dump the img and sub //TODO - acquire disk size first string imgPath = Path.ChangeExtension(path, ".img"); string subPath = Path.ChangeExtension(path, ".sub"); var buf2448 = new byte[2448]; DiscSectorReader dsr = new DiscSectorReader(disc); using (var imgFile = File.OpenWrite(imgPath)) using (var subFile = File.OpenWrite(subPath)) { int nLBA = disc.Session1.LeadoutLBA; for (int lba = 0; lba < nLBA; lba++) { dsr.ReadLBA_2448(lba, buf2448, 0); imgFile.Write(buf2448, 0, 2352); subFile.Write(buf2448, 2352, 96); } } } class SS_CCD : ISectorSynthJob2448 { public void Synth(SectorSynthJob job) { //CCD is always containing everything we'd need (unless a .sub is missing?) so don't worry about flags var imgBlob = job.Disc.DisposableResources[0] as IBlob; var subBlob = job.Disc.DisposableResources[1] as IBlob; //Read_2442(job.LBA, job.DestBuffer2448, job.DestOffset); //read the IMG data if needed if ((job.Parts & ESectorSynthPart.UserAny) != 0) { long ofs = job.LBA * 2352; imgBlob.Read(ofs, job.DestBuffer2448, 0, 2352); } //if subcode is needed, read it if ((job.Parts & (ESectorSynthPart.SubcodeAny)) != 0) { long ofs = job.LBA * 96; subBlob.Read(ofs, job.DestBuffer2448, 2352, 96); //subcode comes to us deinterleved; we may still need to interleave it if ((job.Parts & (ESectorSynthPart.SubcodeDeinterleave)) == 0) { SynthUtils.InterleaveSubcodeInplace(job.DestBuffer2448, job.DestOffset + 2352); } } } } /// <summary> /// Loads a CCD at the specified path to a Disc object /// </summary> public Disc LoadCCDToDisc(string ccdPath, DiscMountPolicy IN_DiscMountPolicy) { var loadResults = LoadCCDPath(ccdPath); if (!loadResults.Valid) throw loadResults.FailureException; Disc disc = new Disc(); IBlob imgBlob = null, subBlob = null; long imgLen = -1, subLen; //mount the IMG file //first check for a .ecm in place of the img var imgPath = loadResults.ImgPath; if (!File.Exists(imgPath)) { var ecmPath = Path.ChangeExtension(imgPath, ".img.ecm"); if (File.Exists(ecmPath)) { if (Disc.Blob_ECM.IsECM(ecmPath)) { var ecm = new Disc.Blob_ECM(); ecm.Load(ecmPath); imgBlob = ecm; imgLen = ecm.Length; } } } if (imgBlob == null) { if (!File.Exists(loadResults.ImgPath)) throw new CCDParseException("Malformed CCD format: nonexistent IMG file!"); var imgFile = new Disc.Blob_RawFile() { PhysicalPath = loadResults.ImgPath }; imgLen = imgFile.Length; imgBlob = imgFile; } disc.DisposableResources.Add(imgBlob); //mount the SUB file if (!File.Exists(loadResults.SubPath)) throw new CCDParseException("Malformed CCD format: nonexistent SUB file!"); var subFile = new Disc.Blob_RawFile() { PhysicalPath = loadResults.SubPath }; subBlob = subFile; disc.DisposableResources.Add(subBlob); subLen = subFile.Length; //quick integrity check of file sizes if (imgLen % 2352 != 0) throw new CCDParseException("Malformed CCD format: IMG file length not multiple of 2352"); int NumImgSectors = (int)(imgLen / 2352); if (subLen != NumImgSectors * 96) throw new CCDParseException("Malformed CCD format: SUB file length not matching IMG"); var ccdf = loadResults.ParsedCCDFile; //the only instance of a sector synthesizer we'll need SS_CCD synth = new SS_CCD(); //generate DiscTOCRaw items from the ones specified in the CCD file //TODO - range validate these (too many truncations to byte) disc.RawTOCEntries = new List<RawTOCEntry>(); foreach (var entry in ccdf.TOCEntries) { BCD2 tno, ino; //this should actually be zero. im not sure if this is stored as BCD2 or not tno = BCD2.FromDecimal(entry.TrackNo); //these are special values.. I think, taken from this: //http://www.staff.uni-mainz.de/tacke/scsi/SCSI2-14.html //the CCD will contain Points as decimal values except for these specially converted decimal values which should stay as BCD. //Why couldn't they all be BCD? I don't know. I guess because BCD is inconvenient, but only A0 and friends have special meaning. It's confusing. ino = BCD2.FromDecimal(entry.Point); if (entry.Point == 0xA0) ino.BCDValue = 0xA0; else if (entry.Point == 0xA1) ino.BCDValue = 0xA1; else if (entry.Point == 0xA2) ino.BCDValue = 0xA2; var q = new SubchannelQ { q_status = SubchannelQ.ComputeStatus(entry.ADR, (EControlQ)(entry.Control & 0xF)), q_tno = tno, q_index = ino, min = BCD2.FromDecimal(entry.AMin), sec = BCD2.FromDecimal(entry.ASec), frame = BCD2.FromDecimal(entry.AFrame), zero = (byte)entry.Zero, ap_min = BCD2.FromDecimal(entry.PMin), ap_sec = BCD2.FromDecimal(entry.PSec), ap_frame = BCD2.FromDecimal(entry.PFrame), q_crc = 0, //meaningless }; disc.RawTOCEntries.Add(new RawTOCEntry { QData = q }); } //analyze the RAWTocEntries to figure out what type of track track 1 is var tocSynth = new Synthesize_DiscTOC_From_RawTOCEntries_Job() { Entries = disc.RawTOCEntries }; tocSynth.Run(); //Add sectors for the mandatory track 1 pregap, which isn't stored in the CCD file //We reuse some CUE code for this. //If we load other formats later we might should abstract this even further (to a synthesizer job) //It can't really be abstracted from cue files though due to the necessity of merging this with other track 1 pregaps CUE.CueTrackType pregapTrackType = CUE.CueTrackType.Audio; if (tocSynth.Result.TOCItems[1].IsData) { if (tocSynth.Result.Session1Format == SessionFormat.Type20_CDXA) pregapTrackType = CUE.CueTrackType.Mode2_2352; else if (tocSynth.Result.Session1Format == SessionFormat.Type10_CDI) pregapTrackType = CUE.CueTrackType.CDI_2352; else if (tocSynth.Result.Session1Format == SessionFormat.Type00_CDROM_CDDA) pregapTrackType = CUE.CueTrackType.Mode1_2352; } for (int i = 0; i < 150; i++) { var ss_gap = new CUE.SS_Gap() { Policy = IN_DiscMountPolicy, TrackType = pregapTrackType }; disc._Sectors.Add(ss_gap); int qRelMSF = i - 150; //tweak relMSF due to ambiguity/contradiction in yellowbook docs if (!IN_DiscMountPolicy.CUE_PregapContradictionModeA) qRelMSF++; //setup subQ byte ADR = 1; //absent some kind of policy for how to set it, this is a safe assumption: ss_gap.sq.SetStatus(ADR, tocSynth.Result.TOCItems[1].Control); ss_gap.sq.q_tno = BCD2.FromDecimal(1); ss_gap.sq.q_index = BCD2.FromDecimal(0); ss_gap.sq.AP_Timestamp = i; ss_gap.sq.Timestamp = qRelMSF; //setup subP ss_gap.Pause = true; } //build the sectors: //set up as many sectors as we have img/sub for, even if the TOC doesnt reference them //(the TOC is unreliable, and the Track records are redundant) for (int i = 0; i < NumImgSectors; i++) { disc._Sectors.Add(synth); } return disc; } } //class CCD_Format }
33.618067
183
0.646066
[ "MIT" ]
Asnivor/BizHawk
BizHawk.Emulation.DiscSystem/DiscFormats/CCD_format.cs
21,215
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 opsworks-2013-02-18.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.OpsWorks.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.OpsWorks.Model.Internal.MarshallTransformations { /// <summary> /// ListTags Request Marshaller /// </summary> public class ListTagsRequestMarshaller : IMarshaller<IRequest, ListTagsRequest> , 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((ListTagsRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(ListTagsRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.OpsWorks"); string target = "OpsWorks_20130218.ListTags"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2013-02-18"; 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.IsSetMaxResults()) { context.Writer.WritePropertyName("MaxResults"); context.Writer.Write(publicRequest.MaxResults); } if(publicRequest.IsSetNextToken()) { context.Writer.WritePropertyName("NextToken"); context.Writer.Write(publicRequest.NextToken); } if(publicRequest.IsSetResourceArn()) { context.Writer.WritePropertyName("ResourceArn"); context.Writer.Write(publicRequest.ResourceArn); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static ListTagsRequestMarshaller _instance = new ListTagsRequestMarshaller(); internal static ListTagsRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static ListTagsRequestMarshaller Instance { get { return _instance; } } } }
34.8
131
0.611694
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/OpsWorks/Generated/Model/Internal/MarshallTransformations/ListTagsRequestMarshaller.cs
4,002
C#
using Cellarium.Api; using Cellarium.Commands.Aliases; using Cellarium.Commands.Base; using Cellarium.Commands.Parameters; using Cellarium.Handlers; using YandexDisk.Client.Http; namespace Cellarium.Commands; public class ClearExpiredCommand : BaseCommand { public sealed override string Description { get; init; } public sealed override List<BaseAlias> Aliases { get; init; } public sealed override List<BaseParameter>? Parameters { get; init; } public override void Run(params BaseParameter [] arguments) { base.Run(arguments); var externalPath = arguments.First(x => x.Content == "external_path").Value; if (!int.TryParse(arguments.First(x => x.Content == "delta").Value, out var delta)) throw new ArgumentException("Bad delta passed"); var deletePermanently = false; var _dp = arguments.FirstOrDefault(x => x.Content == "delete_permanently")?.Value; if (!String.IsNullOrEmpty(_dp)) if (!Boolean.TryParse(_dp, out deletePermanently)) throw new ArgumentException("Bad delete_permanently passed"); var yandexCloudApi = new YandexCloudApi(new DiskHttpApi(Environment.GetEnvironmentVariable("token"))); var handler = new IoHandler(yandexCloudApi, externalPath); handler.ClearExpired(delta, deletePermanently); } public ClearExpiredCommand() { Description = "Clear old files"; Aliases = new List<BaseAlias> { new() { Type = AliasTypeEnum.Abbreviation, Content = "ce" }, new () { Type = AliasTypeEnum.Fully, Content = "clear_expired" } }; Parameters = new List<BaseParameter> { new () { Content = "external_path", Value = "/", Optional = false }, new () { Content = "delta", Value = "30", Optional = false }, new () { Content = "delete_permanently", Value = "false" } }; } }
31.068493
110
0.555115
[ "MIT" ]
icYFTL/Cellarium
Cellarium/Commands/ClearExpiredCommand.cs
2,270
C#
using NSubstitute; using Xunit; using Xunit.Sdk; using Yak2D.Internal; using Yak2D.Surface; namespace Yak2D.Tests { public class GpuSurfaceManagerTest { private IGpuSurfaceManager SetUpManagerWithFakes() { var components = Substitute.For<ISystemComponents>(); var appassembly = Substitute.For<IApplicationAssembly>(); var fonts = Substitute.For<IFontsAssembly>(); var surface = Substitute.For<ISurfaceAssembly>(); var messenger = Substitute.For<IFrameworkMessenger>(); var id = Substitute.For<IIdGenerator>(); var props = Substitute.For<IStartupPropertiesCache>(); var surfaceCollection = Substitute.For<IGpuSurfaceCollection>(); var imagesharp = Substitute.For<IImageSharpLoader>(); var surfacefactory = Substitute.For<IGpuSurfaceFactory>(); var filesystem = Substitute.For<IFileSystem>(); var userProps = Substitute.For<StartupConfig>(); userProps.AutoClearMainWindowColourEachFrame = true; userProps.AutoClearMainWindowDepthEachFrame = true; props.User.Returns(userProps); IGpuSurfaceManager manager = new GpuSurfaceManager(appassembly, fonts, surface, messenger, id, props, surfaceCollection, imagesharp, surfacefactory, components, filesystem); return manager; } [Fact] public void SurfaceManager_CheckSurfaceCounts_ReturnStubbedFigures() { var components = Substitute.For<ISystemComponents>(); var appassembly = Substitute.For<IApplicationAssembly>(); var fonts = Substitute.For<IFontsAssembly>(); var surface = Substitute.For<ISurfaceAssembly>(); var messenger = Substitute.For<IFrameworkMessenger>(); var id = Substitute.For<IIdGenerator>(); var props = Substitute.For<IStartupPropertiesCache>(); var surfaceCollection = Substitute.For<IGpuSurfaceCollection>(); var imagesharp = Substitute.For<IImageSharpLoader>(); var surfacefactory = Substitute.For<IGpuSurfaceFactory>(); var filesystem = Substitute.For<IFileSystem>(); var userProps = Substitute.For<StartupConfig>(); userProps.AutoClearMainWindowColourEachFrame = true; userProps.AutoClearMainWindowDepthEachFrame = true; props.User.Returns(userProps); IGpuSurfaceManager manager = new GpuSurfaceManager(appassembly, fonts, surface, messenger, id, props, surfaceCollection, imagesharp, surfacefactory, components, filesystem); surfaceCollection.CountOfType(GpuSurfaceType.RenderTarget | GpuSurfaceType.User).Returns(6); surfaceCollection.CountOfType(GpuSurfaceType.Texture | GpuSurfaceType.User).Returns(4); Assert.Equal(10, manager.TotalUserSurfaceCount); Assert.Equal(6, manager.UserRenderTargetCount); Assert.Equal(4, manager.UserTextureCount); } [Fact] public void SurfaceManager_LoadTextureFromEmbeddedPngCatchesNullOrEmptyString_ThrowsException() { var manager = SetUpManagerWithFakes(); Assert.Throws<Yak2DException>(() => { manager.CreateTextureFromEmbeddedResourceInUserApplication(null, ImageFormat.PNG, SamplerType.Anisotropic, true); }); Assert.Throws<Yak2DException>(() => { manager.CreateTextureFromEmbeddedResourceInUserApplication("", ImageFormat.PNG, SamplerType.Anisotropic, true); }); } [Fact] public void SurfaceManager_LoadFontTextureFromEmbeddedPngCatchesNullOrEmptyString_ThrowsException() { var manager = SetUpManagerWithFakes(); Assert.Throws<Yak2DException>(() => { manager.CreateFontTextureFromEmbeddedResource(true, null, ImageFormat.PNG, SamplerType.Anisotropic); }); Assert.Throws<Yak2DException>(() => { manager.CreateFontTextureFromEmbeddedResource(true, "", ImageFormat.PNG, SamplerType.Anisotropic); }); } [Fact] public void SurfaceManager_LoadTextureFromPngFileCatchesNullOrEmptyString_ThrowsException() { var manager = SetUpManagerWithFakes(); Assert.Throws<Yak2DException>(() => { manager.CreateTextureFromFile(null, ImageFormat.PNG, SamplerType.Anisotropic, true); }); Assert.Throws<Yak2DException>(() => { manager.CreateTextureFromFile("", ImageFormat.PNG, SamplerType.Anisotropic, true); }); } [Fact] public void SurfaceManager_LoadFontTextureFromPngFileCatchesNullOrEmptyString_ThrowsException() { var manager = SetUpManagerWithFakes(); Assert.Throws<Yak2DException>(() => { manager.CreateFontTextureFromFile(null, ImageFormat.PNG, SamplerType.Anisotropic); }); Assert.Throws<Yak2DException>(() => { manager.CreateFontTextureFromFile("", ImageFormat.PNG, SamplerType.Anisotropic); }); } } }
51.793388
167
0.544918
[ "Apache-2.0" ]
AlzPatz/yak2d
src/Yak2D.Tests/Surface/GpuSurfaceManagerTest.cs
6,267
C#
namespace GeoLib { public class Coords { public double Longitude { get; set; } public double Latitude { get; set; } } }
14.222222
39
0.664063
[ "MIT" ]
hardsky/HotelFinder
src/GeoLib/Coords.cs
130
C#
namespace Patterns.Creational.AbstractFactory { public interface IFactory<out T> where T : IProduct { T Create(); } }
19.714286
55
0.652174
[ "MIT" ]
SeletskySergey/Patterns
Creational/AbstractFactory/IFactory.cs
140
C#
using System; using System.Collections.Generic; using System.Linq; using NetFabric.Assertive; using Xunit; namespace NetFabric.Tests { public class AppendTests { [Fact] void AppendNullLeft() { // Arrange // Act Action action = () => DoublyLinkedList.Append(null, new DoublyLinkedList<int>()); // Assert action.Must() .Throw<ArgumentNullException>() .EvaluateTrue(exception => exception.ParamName == "left"); } [Fact] void AppendNullRight() { // Arrange // Act Action action = () => DoublyLinkedList.Append(new DoublyLinkedList<int>(), null); // Assert action.Must() .Throw<ArgumentNullException>() .EvaluateTrue(exception => exception.ParamName == "right"); } public static TheoryData<IReadOnlyList<int>, IReadOnlyList<int>, IReadOnlyList<int>> AppendData => new() { { Array.Empty<int>(), Array.Empty<int>(), Array.Empty<int>() }, { Array.Empty<int>(), new[] { 1 } , new[] { 1 } }, { new[] { 1 }, Array.Empty<int>(), new[] { 1 } }, { Array.Empty<int>(), new[] { 1, 2, 3, 4, 5 } , new[] { 1, 2, 3, 4, 5 } }, { new[] { 1, 2, 3, 4, 5 }, Array.Empty<int>(), new[] { 1, 2, 3, 4, 5 } }, { new[] { 1 }, new[] { 2, 3, 4, 5 }, new[] { 1, 2, 3, 4, 5 } }, { new[] { 1, 2, 3, 4 }, new[] { 5 } , new[] { 1, 2, 3, 4, 5 } }, { new[] { 1, 2, 3 }, new[] { 4, 5, 6 }, new[] { 1, 2, 3, 4, 5, 6 } }, }; [Theory] [MemberData(nameof(AppendData))] void Append(IReadOnlyList<int> left, IReadOnlyList<int> right, IReadOnlyCollection<int> expected) { // Arrange var leftList = new DoublyLinkedList<int>(left); var leftVersion = leftList.Version; var rightList = new DoublyLinkedList<int>(right); var rightVersion = rightList.Version; // Act var result = DoublyLinkedList.Append(leftList, rightList); // Assert leftList.Version.Must() .BeEqualTo(leftVersion); leftList.Forward.Must() .BeEnumerableOf<int>() .BeEqualTo(left); rightList.Version.Must() .BeEqualTo(rightVersion); rightList.Forward.Must() .BeEnumerableOf<int>() .BeEqualTo(right); result.Forward.Must() .BeEnumerableOf<int>() .BeEqualTo(expected); result.Backward.Must() .BeEnumerableOf<int>() .BeEqualTo(expected.Reverse()); } } }
34.670455
106
0.450016
[ "MIT" ]
NetFabric/NetFabric.DoubleLinkedList
NetFabric.DoublyLinkedList.Tests/AppendTests.cs
3,051
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.Windows.Controls; using System.Windows; using System.Windows.Input; namespace Microsoft.Test.Stability.Extensions.Actions { #if TESTBUILD_CLR40 public class SetDataGridSelectionAction : ApplyDataGridItemsSourceAction { public Boolean SelectedByIndex { get; set; } public Double Rate { get; set; } public override void Perform() { SetupDataGridItemsSource(); if (!(DataGrid.SelectionUnit == DataGridSelectionUnit.FullRow && DataGrid.SelectionMode == DataGridSelectionMode.Single)) { DataGrid.SelectAllCells(); DataGrid.UnselectAllCells(); } if (DataGrid.SelectionUnit != DataGridSelectionUnit.Cell) { if (DataGrid.SelectionMode != DataGridSelectionMode.Single) { DataGrid.SelectAll(); DataGrid.UnselectAll(); } else { if (DataGrid.Items.Count != 0) { int itemIndex = (int)(Rate * DataGrid.Items.Count); if (itemIndex < 0) { itemIndex = 0; } else if (itemIndex >= DataGrid.Items.Count) { itemIndex = DataGrid.Items.Count - 1; } if (SelectedByIndex) { DataGrid.SelectedIndex = itemIndex; } else { DataGrid.SelectedItem = DataGrid.Items[itemIndex]; } } } } } } public class SetDataGridCurrentColumnAction : ApplyDataGridItemsSourceAction { public Double Rate { get; set; } public override void Perform() { SetupDataGridItemsSource(); if (DataGrid.Columns.Count != 0) { int colIndex = (int)(Rate * DataGrid.Columns.Count); if (colIndex < 0) { colIndex = 0; } else if (colIndex >= DataGrid.Columns.Count) { colIndex = DataGrid.Columns.Count - 1; } DataGrid.CurrentColumn = DataGrid.Columns[colIndex]; } } } public class SetDataGridCurrentItemAction : ApplyDataGridItemsSourceAction { public Double Rate { get; set; } public override void Perform() { SetupDataGridItemsSource(); if (DataGrid.Items.Count != 0) { int itemIndex = (int)(Rate * DataGrid.Items.Count); if (itemIndex < 0) { itemIndex = 0; } else if (itemIndex >= DataGrid.Items.Count) { itemIndex = DataGrid.Items.Count - 1; } DataGrid.CurrentItem = DataGrid.Items[itemIndex]; } } } #endif }
31.809091
133
0.470134
[ "MIT" ]
batzen/wpf-test
src/Test/Common/Code/Microsoft/Test/Stability/Extensions/Actions/DataGridSelectAction.cs
3,501
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Azure.Devices.Common { using System; static class CommonConstants { // TODO: move these to ConfigProvider public const string DeviceAudienceFormat = "{0}/devices/{1}"; public const string MediaTypeForDeviceManagementApis = "application/json"; public const string AmqpsScheme = "amqps"; public const string AmqpScheme = "amqp"; public const string AmqpDnsWSPrefix = "amqpws"; public const ulong AmqpMaxMessageSize = 256 * 1024 * 4; // Temporarily accept messages upto 1Mb in size. Reduce to 256 kb after fixing client behavior public const int HttpsPort = 443; public const int AmqpsPort = 5671; // IotHub WindowsFabric Constants public const int WindowsFabricRetryLimit = 20; public const int WindowsFabricRetryWaitInMilliseconds = 3000; public const int WindowsFabricClientConnectionPort = 19000; // AzureStorage Constants public const int AzureStorageRetryLimit = 3; public const int AzureStorageRetryWaitInMilliseconds = 3000; public const string IotHubApplicationName = "fabric:/microsoft.azure.devices.container"; public const string IotHubApplicationTypeName = "microsoft.azure.devices.container"; public const string IotHubServiceTypeName = "microsoft.azure.devices.container.service"; public const string ThrottlingApplicationName = "fabric:/microsoft.azure.devices.throttling"; public const string ThrottlingApplicationTypeName = "microsoft.azure.devices.throttling"; public const string ThrottlingServiceTypeName = "microsoft.azure.devices.throttling.service"; public const string MicrosoftOwinContextPropertyName = "MS_OwinContext"; // EventHub public const int EventHubEndpointPortNumber = 5671; public const string EventHubConnectionStringTemplate = "{0};PartitionCount={1}"; // Namespace paths public const string ResourceProviderNamespace = "Microsoft.Devices"; public const string ResourceProviderServiceResourceType = ResourceProviderNamespace + "/IotHubs"; public const string ResourceProviderBasePathTemplate = "/subscriptions/{0}/resourceGroups/{1}/providers/" + ResourceProviderServiceResourceType + "/{2}"; // Runtime Retry Constants public const int RuntimeRetryLimit = 3; public const int RuntimeRetryWaitInMilliseconds = 5000; // Device URI Templates public const string DeviceEventPathTemplate = "/devices/{0}/messages/events"; public const string DeviceBoundPathTemplate = "/devices/{0}/messages/deviceBound"; public const string DeviceBoundPathCompleteTemplate = DeviceBoundPathTemplate + "/{1}"; public const string DeviceBoundPathAbandonTemplate = DeviceBoundPathCompleteTemplate + "/abandon"; public const string DeviceBoundPathRejectTemplate = DeviceBoundPathCompleteTemplate + "?reject"; // IotHub constants public const int IotHubDefaultMaxAuthorizationRules = 16; // IotHub provisioning terminal states (CSM/ARM) public const string ProvisioningStateSucceed = "Succeeded"; public const string ProvisioningStateFailed = "Failed"; public const string ProvisioningStateCanceled = "Canceled"; // IotHub provisioning initial state public const string ProvisioingStateAccepted = "Accepted"; public const string DeviceToCloudOperation = "d2c"; public const string CloudToDeviceOperation = "c2d"; public const string ApiVersionQueryParameterName = "api-version"; public const string WildCardEtag = "*"; // Service configurable parameters public const string PartitionCount = "PartitionCount"; public const string TargetReplicaSetSize = "TargetReplicaSetSize"; public const string MinReplicaSetSize = "MinReplicaSetSize"; public const string SkuMaxUnitOverride = "SkuMaxUnitOverride"; public const string ContentTypeHeaderName = "Content-Type"; public const string ContentEncodingHeaderName = "Content-Encoding"; public const string BatchedMessageContentType = "application/vnd.microsoft.iothub.json"; public const string BatchedFeedbackContentType = "application/vnd.microsoft.iothub.feedback.json"; public const string IotHubSystemStoreServiceName = "iothub-systemstore"; public const string IotHubStatsCacheKey = "_cache_key_for_iothub_stats"; public const string SystemStoreStatsPartitionKey = "__system_store_iothub_stats_partition_key__"; public const string SystemStoreScaleUnitConfigPartitionKey = "__system_store_scaleunit_config_partition_key__"; public const string SystemStoreScaleUnitConfigRowKey = "__system_store_scaleunit_config_row_key__"; public const string ScaleUnitSettingsKey = "_cache_key_for_scaleunit_settings"; public const int SystemStoreMaxRetries = 5; public const string ConnectedDeviceCountProperty = "ConnectedDeviceCount"; public const string EnabledDeviceCountProperty = "EnabledDeviceCount"; public const string DisabledDeviceCountProperty = "DisabledDeviceCount"; public const string TotalDeviceCountProperty = "TotalDeviceCount"; public const long MaxStringLengthForAzureTableColumn = 23 * 1024; public const long MaxDeviceUpdateStatsCount = 500; public const string ListenKeyName = "listen"; public const string DefaultEventHubEndpointName = "events"; public const string ExportDevicesBlobName = "devices.txt"; public const string ImportDevicesOutputBlobName = "importErrors.log"; public static readonly TimeSpan SystemStoreMaximumExecutionTime = TimeSpan.FromSeconds(60); public static readonly TimeSpan SystemStoreDeltaBackOff = TimeSpan.FromSeconds(5); public const double RpDatabaseResourceLowThreshold = 70.0; public const double RpDatabaseResourceHighThreshold = 90.0; public const double IotHubResourcePoolsLowThreshold = 40.0; public const double IotHubResourcePoolsCriticallyLowThreshold = 10.0; public static readonly TimeSpan ProcessThreadCheckInterval = TimeSpan.FromMinutes(1); public const int MaxThreadsCountThreshold = 700; //Service Analytics related public static class ServiceAnalytics { public const string SendEventStatName = "SendEvent"; public const string EnqueueMessageStatName = "EnqueueMessage"; } // Quota Related public static class Quota { public const string IotHubQuotaMetricsCacheKeyPrefix = "_cache_key_for_iothub_quota_metrics"; public const string IotHubQuotaMetricsPartitionKeyPrefix = "__system_store_iothub_quota_partition_key__"; public const double DefaultMessageCountQuotaChunkSizeInKBytes = 64; } // Usage Related public static class Usage { public const long DefaultUsageMetricFlushThreshold = 100; public const long SendEventUsageMetricFlushThreshold = 1000; public const long EnqueueMessageUsageMetricFlushThreshold = 500; public static readonly TimeSpan QuotaUsageMetricFlushInterval = TimeSpan.FromMinutes(1); public static readonly TimeSpan UsageMetricDefaultFlushInterval = TimeSpan.FromMinutes(3); } public static class CommonServiceConfiguration { public const string GlobalEncryptionCertificateThumbprint = "IotHub.EncryptionCertificateThumbprint"; public const string GlobalPrimaryEncryptionKey = "Global.PrimaryEncryptionKey"; public const string GlobalSecondaryEncryptionKey = "Global.SecondaryEncryptionKey"; } // Billing related public static class Billing { public const int UsageRecordPartitionCount = 16; public const string FreeSkuMeterId = "a435c5fc-1ab7-4be4-8cf4-223a670cae26"; public const string Standard1SkuMeterId = "2885a6b2-5013-4fa9-8f3b-fc3ead8d136d"; public const string Standard2SkuMeterId = "a36d229a-595c-44ad-a66c-1287be4bf433"; public const int EventHubThroughputUnitRatioStandard1 = 1000; public const int EventHubThroughputUnitRatioStandard2 = 30; } public static class CloudToDevice { public const int DefaultMaxDeliveryCount = 10; public const int MaximumMaxDeliveryCount = 100; public const int MinimumMaxDeliveryCount = 1; public static readonly TimeSpan DefaultTtl = TimeSpan.FromHours(1); public static readonly TimeSpan MaximumDefaultTtl = TimeSpan.FromDays(2); public static readonly TimeSpan MinimumDefaultTtl = TimeSpan.FromMinutes(1); } public static class Feedback { public const string FeedbackQueueInternalOwnerKeyName = "owner"; public static readonly TimeSpan DefaultLockDuration = TimeSpan.FromMinutes(1); public static readonly TimeSpan MaximumLockDuration = TimeSpan.FromMinutes(5); public static readonly TimeSpan MinimumLockDuration = TimeSpan.FromSeconds(5); public static readonly TimeSpan DefaultTtl = TimeSpan.FromHours(1); public static readonly TimeSpan MaximumTtl = TimeSpan.FromDays(2); public static readonly TimeSpan MinimumTtl = TimeSpan.FromMinutes(1); public const int DefaultMaxDeliveryCount = 10; public const int MaximumMaxDeliveryCount = 100; public const int MinimumMaxDeliveryCount = 1; public const int FreeSkuQueuePartitionSizeInMegabytes = 1024; public const int StandardSkuQueuePartitionSizeInMegabytes = 5120; } public static class EventHub { public const string ScaleUnitSendKeyNamePrefix = "scaleunitsend"; public const string OwnerKeyNamePrefix = "owner"; public const int MinPartitionCount = 2; public const int MaxPartitionCount = 32; public const int DefaultStandardPartitionCount = 4; public const int MinRetentionTimeInDays = 1; public const int MaxRetentionTimeInDays = 7; public const int MaxMessageSize = 255 * 1024; } } }
52
161
0.716158
[ "MIT" ]
5dprinted/azure-iot-sdks
csharp/service/Microsoft.Azure.Devices/Common/CommonConstants.cs
10,608
C#
using System; using System.Numerics; class Program { static void Main() { int n = int.Parse(Console.ReadLine()); BigInteger player1TotalScore = 0; BigInteger player2TotalScore = 0; int player1GamesWon = 0; int player2GamesWon = 0; for (int i = 0; i < n; i++) { BigInteger heandScore1 = 0; BigInteger heandScore2 = 0; bool player1HasXcard = false; bool player2HasXCard = false; //player one for (int j = 0; j < 3; j++) { string card = Console.ReadLine(); switch (card) { case "A": heandScore1 += 1; break; case "K": heandScore1 += 13; break; case "Q": heandScore1 += 12; break; case "J": heandScore1 += 11; break; case "X": player1HasXcard = true; ; break; case "Y": player1TotalScore -= 200; break; case "Z": player1TotalScore *= 2; break; default: heandScore1 += 12 - int.Parse(card); break; } } for (int j = 0; j < 3; j++) { string card = Console.ReadLine(); switch (card) { case "A": heandScore2 += 1; break; case "K": heandScore2 += 13; break; case "Q": heandScore2 += 12; break; case "J": heandScore2 += 11; break; case "X": player2HasXCard = true; ; break; case "Y": player2TotalScore -= 200; break; case "Z": player2TotalScore *= 2; break; default: heandScore2 += 12 - int.Parse(card); break; } } if (player1HasXcard&&player2HasXCard) { player1TotalScore += 50; player2TotalScore += 50; } else if (player1HasXcard) { Console.WriteLine("X card drawn! Player one wins the match!"); return; } else if (player2HasXCard) { Console.WriteLine("X card drawn! Player two wins the match!"); return; } if (heandScore1>heandScore2) { player1TotalScore += heandScore1; ++player1GamesWon; } else if (heandScore1<heandScore2) { player2TotalScore += heandScore2; ++player2GamesWon; } } if (player1TotalScore==player2TotalScore) { Console.WriteLine(@"It's a tie! Score: {0}", player2TotalScore); } else { if (player1TotalScore>player2TotalScore) { Console.WriteLine(@"First player wins! Score: {0} Games won: {1}", player1TotalScore, player1GamesWon); } else { Console.WriteLine(@"Second player wins! Score: {0} Games won: {1}", player2TotalScore, player2GamesWon); } } } }
31.970297
78
0.449055
[ "MIT" ]
ilian1902/BGcoder-C-1-exam
C#1 - 2013 2014/Telerik Academy Exam 1 @ 24 June 2013 Evening/03.CardWars/Program.cs
3,231
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.Reflection; using Microsoft.Toolkit.Uwp.Helpers; using Windows.UI; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Media; namespace Microsoft.Toolkit.Uwp.SampleApp.Common { public class SolidColorBrushConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { if (value is string) { return value; } var brush = (SolidColorBrush)value; return brush.Color.ToString(); } public object ConvertBack(object value, Type targetType, object parameter, string language) { #if HAS_UNO // Check if what we're getting back is a named color so that we can keep it as its name if it is. var prop = typeof(Colors).GetTypeInfo().GetDeclaredField(value.ToString()); #else // Check if what we're getting back is a named color so that we can keep it as its name if it is. var prop = typeof(Colors).GetTypeInfo().GetDeclaredProperty(value.ToString()); #endif if (prop != null) { return value.ToString(); } return new SolidColorBrush(value.ToString().ToColor()); } } }
31.808511
109
0.637458
[ "MIT" ]
IamNeha99/Uno.WindowsCommunityToolkit
Microsoft.Toolkit.Uwp.SampleApp.Shared/Common/SolidColorBrushConverter.cs
1,495
C#
using Newtonsoft.Json; namespace Tiny.RestClient.Tests.Models { public class SnakeResponse { [JsonProperty("id")] public int Id { get; set; } [JsonProperty("response_data")] public string ResponseData { get; set; } } }
20.384615
48
0.615094
[ "MIT" ]
btbensoft/Tiny.RestClient
Tests/Tiny.RestClient.ForTest.Api/Models/SnakeResponse.cs
267
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.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Text; using Microsoft.AspNetCore.Certificates.Generation; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal; using Microsoft.AspNetCore.Server.Kestrel.Https; using Microsoft.AspNetCore.Server.Kestrel.Https.Internal; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Microsoft.AspNetCore.Server.Kestrel.Core { /// <summary> /// Provides programmatic configuration of Kestrel-specific features. /// </summary> public class KestrelServerOptions { // internal to fast-path header decoding when RequestHeaderEncodingSelector is unchanged. internal static readonly Func<string, Encoding?> DefaultRequestHeaderEncodingSelector = _ => null; private Func<string, Encoding?> _requestHeaderEncodingSelector = DefaultRequestHeaderEncodingSelector; // The following two lists configure the endpoints that Kestrel should listen to. If both lists are empty, the "urls" config setting (e.g. UseUrls) is used. internal List<ListenOptions> CodeBackedListenOptions { get; } = new List<ListenOptions>(); internal List<ListenOptions> ConfigurationBackedListenOptions { get; } = new List<ListenOptions>(); internal IEnumerable<ListenOptions> ListenOptions => CodeBackedListenOptions.Concat(ConfigurationBackedListenOptions); // For testing and debugging. internal List<ListenOptions> OptionsInUse { get; } = new List<ListenOptions>(); /// <summary> /// Gets or sets whether the <c>Server</c> header should be included in each response. /// </summary> /// <remarks> /// Defaults to true. /// </remarks> public bool AddServerHeader { get; set; } = true; /// <summary> /// Gets or sets a value that controls whether dynamic compression of response headers is allowed. /// For more information about the security considerations of HPack dynamic header compression, visit /// https://tools.ietf.org/html/rfc7541#section-7. /// </summary> /// <remarks> /// Defaults to true. /// </remarks> public bool AllowResponseHeaderCompression { get; set; } = true; /// <summary> /// Gets or sets a value that controls whether synchronous IO is allowed for the <see cref="HttpContext.Request"/> and <see cref="HttpContext.Response"/> /// </summary> /// <remarks> /// Defaults to false. /// </remarks> public bool AllowSynchronousIO { get; set; } = false; /// <summary> /// Gets or sets a value that controls whether the string values materialized /// will be reused across requests; if they match, or if the strings will always be reallocated. /// </summary> /// <remarks> /// Defaults to false. /// </remarks> public bool DisableStringReuse { get; set; } = false; /// <summary> /// Controls whether to return the AltSvcHeader from on an HTTP/2 or lower response for HTTP/3 /// </summary> /// <remarks> /// Defaults to false. /// </remarks> public bool EnableAltSvc { get; set; } = false; /// <summary> /// Gets or sets a callback that returns the <see cref="Encoding"/> to decode the value for the specified request header name, /// or <see langword="null"/> to use the default <see cref="UTF8Encoding"/>. /// </summary> public Func<string, Encoding?> RequestHeaderEncodingSelector { get => _requestHeaderEncodingSelector; set => _requestHeaderEncodingSelector = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// Enables the Listen options callback to resolve and use services registered by the application during startup. /// Typically initialized by UseKestrel(). /// </summary> public IServiceProvider ApplicationServices { get; set; } = default!; // This should typically be set /// <summary> /// Provides access to request limit options. /// </summary> public KestrelServerLimits Limits { get; } = new KestrelServerLimits(); /// <summary> /// Provides a configuration source where endpoints will be loaded from on server start. /// The default is <see langword="null"/>. /// </summary> public KestrelConfigurationLoader? ConfigurationLoader { get; set; } /// <summary> /// A default configuration action for all endpoints. Use for Listen, configuration, the default url, and URLs. /// </summary> private Action<ListenOptions> EndpointDefaults { get; set; } = _ => { }; /// <summary> /// A default configuration action for all https endpoints. /// </summary> private Action<HttpsConnectionAdapterOptions> HttpsDefaults { get; set; } = _ => { }; /// <summary> /// The default server certificate for https endpoints. This is applied lazily after HttpsDefaults and user options. /// </summary> internal X509Certificate2? DefaultCertificate { get; set; } /// <summary> /// Has the default dev certificate load been attempted? /// </summary> internal bool IsDevCertLoaded { get; set; } /// <summary> /// Specifies a configuration Action to run for each newly created endpoint. Calling this again will replace /// the prior action. /// </summary> public void ConfigureEndpointDefaults(Action<ListenOptions> configureOptions) { EndpointDefaults = configureOptions ?? throw new ArgumentNullException(nameof(configureOptions)); } internal void ApplyEndpointDefaults(ListenOptions listenOptions) { listenOptions.KestrelServerOptions = this; ConfigurationLoader?.ApplyEndpointDefaults(listenOptions); EndpointDefaults(listenOptions); } /// <summary> /// Specifies a configuration Action to run for each newly created https endpoint. Calling this again will replace /// the prior action. /// </summary> public void ConfigureHttpsDefaults(Action<HttpsConnectionAdapterOptions> configureOptions) { HttpsDefaults = configureOptions ?? throw new ArgumentNullException(nameof(configureOptions)); } internal void ApplyHttpsDefaults(HttpsConnectionAdapterOptions httpsOptions) { ConfigurationLoader?.ApplyHttpsDefaults(httpsOptions); HttpsDefaults(httpsOptions); } internal void ApplyDefaultCert(HttpsConnectionAdapterOptions httpsOptions) { if (httpsOptions.ServerCertificate != null || httpsOptions.ServerCertificateSelector != null) { return; } EnsureDefaultCert(); httpsOptions.ServerCertificate = DefaultCertificate; } private void EnsureDefaultCert() { if (DefaultCertificate == null && !IsDevCertLoaded) { IsDevCertLoaded = true; // Only try once var logger = ApplicationServices!.GetRequiredService<ILogger<KestrelServer>>(); try { DefaultCertificate = CertificateManager.Instance.ListCertificates(StoreName.My, StoreLocation.CurrentUser, isValid: true) .FirstOrDefault(); if (DefaultCertificate != null) { var status = CertificateManager.Instance.CheckCertificateState(DefaultCertificate, interactive: false); if (!status.Success) { // Display a warning indicating to the user that a prompt might appear and provide instructions on what to do in that // case. The underlying implementation of this check is specific to Mac OS and is handled within CheckCertificateState. // Kestrel must NEVER cause a UI prompt on a production system. We only attempt this here because Mac OS is not supported // in production. Debug.Assert(status.FailureMessage != null, "Status with a failure result must have a message."); logger.DeveloperCertificateFirstRun(status.FailureMessage); // Now that we've displayed a warning in the logs so that the user gets a notification that a prompt might appear, try // and access the certificate key, which might trigger a prompt. status = CertificateManager.Instance.CheckCertificateState(DefaultCertificate, interactive: true); if (!status.Success) { logger.BadDeveloperCertificateState(); } } logger.LocatedDevelopmentCertificate(DefaultCertificate); } else { logger.UnableToLocateDevelopmentCertificate(); } } catch { logger.UnableToLocateDevelopmentCertificate(); } } } /// <summary> /// Creates a configuration loader for setting up Kestrel. /// </summary> /// <returns>A <see cref="KestrelConfigurationLoader"/> for configuring endpoints.</returns> public KestrelConfigurationLoader Configure() => Configure(new ConfigurationBuilder().Build()); /// <summary> /// Creates a configuration loader for setting up Kestrel that takes an <see cref="IConfiguration"/> as input. /// This configuration must be scoped to the configuration section for Kestrel. /// Call <see cref="Configure(IConfiguration, bool)"/> to enable dynamic endpoint binding updates. /// </summary> /// <param name="config">The configuration section for Kestrel.</param> /// <returns>A <see cref="KestrelConfigurationLoader"/> for further endpoint configuration.</returns> public KestrelConfigurationLoader Configure(IConfiguration config) => Configure(config, reloadOnChange: false); /// <summary> /// Creates a configuration loader for setting up Kestrel that takes an <see cref="IConfiguration"/> as input. /// This configuration must be scoped to the configuration section for Kestrel. /// </summary> /// <param name="config">The configuration section for Kestrel.</param> /// <param name="reloadOnChange"> /// If <see langword="true"/>, Kestrel will dynamically update endpoint bindings when configuration changes. /// This will only reload endpoints defined in the "Endpoints" section of your <paramref name="config"/>. Endpoints defined in code will not be reloaded. /// </param> /// <returns>A <see cref="KestrelConfigurationLoader"/> for further endpoint configuration.</returns> public KestrelConfigurationLoader Configure(IConfiguration config, bool reloadOnChange) { if (ApplicationServices is null) { throw new InvalidOperationException($"{nameof(ApplicationServices)} must not be null. This is normally set automatically via {nameof(IConfigureOptions<KestrelServerOptions>)}."); } var hostEnvironment = ApplicationServices.GetRequiredService<IHostEnvironment>(); var logger = ApplicationServices.GetRequiredService<ILogger<KestrelServer>>(); var httpsLogger = ApplicationServices.GetRequiredService<ILogger<HttpsConnectionMiddleware>>(); var loader = new KestrelConfigurationLoader(this, config, hostEnvironment, reloadOnChange, logger, httpsLogger); ConfigurationLoader = loader; return loader; } /// <summary> /// Bind to given IP address and port. /// </summary> public void Listen(IPAddress address, int port) { Listen(address, port, _ => { }); } /// <summary> /// Bind to given IP address and port. /// The callback configures endpoint-specific settings. /// </summary> public void Listen(IPAddress address, int port, Action<ListenOptions> configure) { if (address == null) { throw new ArgumentNullException(nameof(address)); } Listen(new IPEndPoint(address, port), configure); } /// <summary> /// Bind to the given IP endpoint. /// </summary> public void Listen(IPEndPoint endPoint) { Listen((EndPoint)endPoint); } /// <summary> /// Bind to the given endpoint. /// </summary> /// <param name="endPoint"></param> public void Listen(EndPoint endPoint) { Listen(endPoint, _ => { }); } /// <summary> /// Bind to given IP address and port. /// The callback configures endpoint-specific settings. /// </summary> public void Listen(IPEndPoint endPoint, Action<ListenOptions> configure) { Listen((EndPoint)endPoint, configure); } /// <summary> /// Bind to the given endpoint. /// The callback configures endpoint-specific settings. /// </summary> public void Listen(EndPoint endPoint, Action<ListenOptions> configure) { if (endPoint == null) { throw new ArgumentNullException(nameof(endPoint)); } if (configure == null) { throw new ArgumentNullException(nameof(configure)); } var listenOptions = new ListenOptions(endPoint); ApplyEndpointDefaults(listenOptions); configure(listenOptions); CodeBackedListenOptions.Add(listenOptions); } /// <summary> /// Listens on ::1 and 127.0.0.1 with the given port. Requesting a dynamic port by specifying 0 is not supported /// for this type of endpoint. /// </summary> public void ListenLocalhost(int port) => ListenLocalhost(port, options => { }); /// <summary> /// Listens on ::1 and 127.0.0.1 with the given port. Requesting a dynamic port by specifying 0 is not supported /// for this type of endpoint. /// </summary> public void ListenLocalhost(int port, Action<ListenOptions> configure) { if (configure == null) { throw new ArgumentNullException(nameof(configure)); } var listenOptions = new LocalhostListenOptions(port); ApplyEndpointDefaults(listenOptions); configure(listenOptions); CodeBackedListenOptions.Add(listenOptions); } /// <summary> /// Listens on all IPs using IPv6 [::], or IPv4 0.0.0.0 if IPv6 is not supported. /// </summary> public void ListenAnyIP(int port) => ListenAnyIP(port, options => { }); /// <summary> /// Listens on all IPs using IPv6 [::], or IPv4 0.0.0.0 if IPv6 is not supported. /// </summary> public void ListenAnyIP(int port, Action<ListenOptions> configure) { if (configure == null) { throw new ArgumentNullException(nameof(configure)); } var listenOptions = new AnyIPListenOptions(port); ApplyEndpointDefaults(listenOptions); configure(listenOptions); CodeBackedListenOptions.Add(listenOptions); } /// <summary> /// Bind to given Unix domain socket path. /// </summary> public void ListenUnixSocket(string socketPath) { ListenUnixSocket(socketPath, _ => { }); } /// <summary> /// Bind to given Unix domain socket path. /// Specify callback to configure endpoint-specific settings. /// </summary> public void ListenUnixSocket(string socketPath, Action<ListenOptions> configure) { if (socketPath == null) { throw new ArgumentNullException(nameof(socketPath)); } if (!Path.IsPathRooted(socketPath)) { throw new ArgumentException(CoreStrings.UnixSocketPathMustBeAbsolute, nameof(socketPath)); } if (configure == null) { throw new ArgumentNullException(nameof(configure)); } var listenOptions = new ListenOptions(socketPath); ApplyEndpointDefaults(listenOptions); configure(listenOptions); CodeBackedListenOptions.Add(listenOptions); } /// <summary> /// Open a socket file descriptor. /// </summary> public void ListenHandle(ulong handle) { ListenHandle(handle, _ => { }); } /// <summary> /// Open a socket file descriptor. /// The callback configures endpoint-specific settings. /// </summary> public void ListenHandle(ulong handle, Action<ListenOptions> configure) { if (configure == null) { throw new ArgumentNullException(nameof(configure)); } var listenOptions = new ListenOptions(handle); ApplyEndpointDefaults(listenOptions); configure(listenOptions); CodeBackedListenOptions.Add(listenOptions); } } }
42.34633
194
0.607377
[ "Apache-2.0" ]
DavidKlempfner/aspnetcore
src/Servers/Kestrel/Core/src/KestrelServerOptions.cs
18,463
C#
using UnityEngine; [System.Serializable] public class FlyingEnemy : IEnemy { int health; int attackDmg; EnemyType enemyType; public FlyingEnemy() { health = 10; attackDmg = 5; enemyType = EnemyType.FLYING_ENEMY; } public int Health { get { return health; } set { health = value; } } public int AttackDmg { get { return attackDmg; } set { attackDmg = value; } } public EnemyType EnemyType { get { return enemyType; } set { enemyType = value; } } public void Attact() { Debug.Log("Flying Enemy Attack Called"); } public void Move() { Debug.Log("Flying Enemy Move Called"); } public void TakeDamage() { Debug.Log("Flying Enemy Take Damage Called"); } }
14.571429
53
0.457843
[ "Apache-2.0" ]
gmostofa/Design-Pattern-in-Unity-using-C-
Factory/Assets/_module/_enemy/FlyingEnemy.cs
1,020
C#
// // CEF provides functions for converting between UTF-8, -16 and -32 strings. // CEF string types are safe for reading from multiple threads but not for // modification. It is the user's responsibility to provide synchronization if // modifying CEF strings from multiple threads. // // // This file manually written from cef/include/internal/cef_string_types.h. // // See also: // /Interop/Base/cef_string_t.cs // /Interop/Base/cef_string_userfree.cs // namespace ShoppingWebCrawler.Cef.Core.Interop { using System; using System.Runtime.InteropServices; using System.Security; internal static unsafe partial class libcef { // These functions set string values. If |copy| is true (1) the value will be // copied instead of referenced. It is up to the user to properly manage // the lifespan of references. [DllImport(DllName, EntryPoint = "cef_string_utf16_set", CallingConvention = CEF_CALL)] public static extern int string_set(char* src, UIntPtr src_len, cef_string_t* output, int copy); // These functions clear string values. The structure itself is not freed. [DllImport(DllName, EntryPoint = "cef_string_utf16_clear", CallingConvention = CEF_CALL)] public static extern void string_clear(cef_string_t* str); // These functions allocate a new string structure. They must be freed by // calling the associated free function. [DllImport(DllName, EntryPoint = "cef_string_userfree_utf16_alloc", CallingConvention = CEF_CALL)] public static extern cef_string_userfree* string_userfree_alloc(); // These functions free the string structure allocated by the associated // alloc function. Any string contents will first be cleared. [DllImport(DllName, EntryPoint = "cef_string_userfree_utf16_free", CallingConvention = CEF_CALL)] public static extern void string_userfree_free(cef_string_userfree* str); } }
39.52
106
0.725709
[ "Apache-2.0" ]
dongshengfengniaowu/ShoppingWebCrawler
ShoppingWebCrawler.Cef.Core/Interop/libcef.string.cs
1,978
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _04.Palindromes { class Program { static void Main(string[] args) { string[] text = Console.ReadLine().Split(new char[] { ' ', '.', ',', '?', '!' } , StringSplitOptions.RemoveEmptyEntries); List<String> listOfPalindromes = new List<String>(); for (int i = 0; i < text.Length; i++) { bool isTrueOrFalse = IsPalindrome(text[i]); if (isTrueOrFalse) { listOfPalindromes.Add(text[i]); } } listOfPalindromes = listOfPalindromes.OrderBy(x => x).Distinct().ToList(); Console.WriteLine(string.Join(", ", listOfPalindromes)); } private static bool IsPalindrome(string word) { string reversed = new string(word.Reverse().ToArray()); if (reversed == word) { return true; } else { return false; } } } }
27.069767
133
0.498282
[ "MIT" ]
stoyanovmiroslav/Tech-Module-Practice
Programming Fundamentals/Strings and Text Processing - Lab/04. Palindromes/Program.cs
1,166
C#
using System; using Newtonsoft.Json; using OpenEventSourcing.Events; namespace OpenEventSourcing.Serialization.Json.Converters { public sealed class EventIdJsonConverter : JsonConverter<EventId> { public override void WriteJson(JsonWriter writer, EventId value, JsonSerializer serializer) { serializer.Serialize(writer, value.ToString()); } public override EventId ReadJson(JsonReader reader, Type objectType, EventId existingValue, bool hasExistingValue, JsonSerializer serializer) { var value = serializer.Deserialize<string>(reader); return EventId.From(value); } } }
31
122
0.690616
[ "MIT" ]
danielcirket/OpenEventSourcing
src/OpenEventSourcing.Serialization.Json/Converters/EventIdJsonConverter.cs
684
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using UFO.Commander.Helper; using UFO.Commander.ViewModel.Entities; using UFO.Server.Bll.Common; using GalaSoft.MvvmLight.Messaging; using UFO.Commander.Messages; using UFO.Commander.Proxy; using UFO.Server.Domain; namespace UFO.Commander.ViewModel { public class PerformanceEditViewModel : ViewModelBase { private readonly IViewAccessBll _viewAccessBll = BllAccessHandler.ViewAccessBll; private readonly IAdminAccessBll _adminAccessBll = BllAccessHandler.AdminAccessBll; public PerformanceEditViewModel() { InitializeData(); } private void InitializeData() { SaveCommand = new RelayCommand((() => { if (CurrentVenueViewModel == null || CurrentArtistViewModel == null || string.IsNullOrEmpty(DateTimeViewModel.Hour)) return; var performance = new Performance { DateTime = DateTimeViewModel.DateTime, Artist = CurrentArtistViewModel.ToDomainObject<Artist>(), Venue = CurrentVenueViewModel.ToDomainObject<Venue>() }; _adminAccessBll.ModifyPerformance(BllAccessHandler.SessionToken, performance); Locator.PerformanceOverviewViewModel.Performances.Add(performance.ToViewModelObject<PerformanceViewModel>()); ResetData(); Locator.PerformanceOverviewViewModel.AddNotification( performance.ToViewModelObject<PerformanceViewModel>(), (IsNew) ? NotificationType.Add : NotificationType.Modified); Messenger.Default.Send(new HideDialogMessage(Locator.PerformanceEditViewModel)); })); CancelCommand = new RelayCommand((() => { Messenger.Default.Send(new HideDialogMessage(Locator.PerformanceEditViewModel)); })); DateTimeViewModel = DateTime.Now; for (var i = 14; i < 25; i++) { var hour = $"{i%24}:00"; if (i == 24) hour = $"0{hour}"; Hours.Add(hour); } LoadData(); } private bool IsNew { get; set; } public void ResetData() { CurrentVenueViewModel = new VenueViewModel(); CurrentArtistViewModel = new ArtistViewModel(); DateTimeViewModel = DateTime.Now; IsNew = true; } public void InitializePreset(VenueViewModel venue, ArtistViewModel artist, DateTimeViewModel dateTime) { CurrentVenueViewModel = venue; CurrentArtistViewModel = artist; DateTimeViewModel = dateTime; IsNew = false; } private async void LoadData() { await Task.Run((() => { Artists.Clear(); var page = _viewAccessBll.RequestArtistPagingData(); var artists = _viewAccessBll.GetArtists(page); while (artists != null && artists.Any()) { foreach (var artist in artists) { Artists.Add(artist.ToViewModelObject<ArtistViewModel>()); } page.ToNextPage(); artists = _viewAccessBll.GetArtists(page); } Artists = new ObservableCollection<ArtistViewModel>(Artists.OrderBy(model => model.ArtistId)); Venues.Clear(); page = _viewAccessBll.RequestVenuePagingData(); var venues = _viewAccessBll.GetVenues(page); while (venues != null && venues.Any()) { foreach (var venue in venues) { Venues.Add(venue.ToViewModelObject<VenueViewModel>()); } page.ToNextPage(); venues = _viewAccessBll.GetVenues(page); } Venues = new ObservableCollection<VenueViewModel>(Venues.OrderBy(model => model.VenueId)); })); } private DateTimeViewModel _dateTimeViewModel; public DateTimeViewModel DateTimeViewModel { get { return _dateTimeViewModel; } set { Set(ref _dateTimeViewModel, value); } } public ObservableCollection<string> Hours { get; } = new ObservableCollection<string>(); private ObservableCollection<ArtistViewModel> _artists = new ObservableCollection<ArtistViewModel>(); public ObservableCollection<ArtistViewModel> Artists { get { return _artists; } set { Set(ref _artists, value); } } public ArtistViewModel CurrentArtistViewModel { get; set; } private ObservableCollection<VenueViewModel> _venues = new ObservableCollection<VenueViewModel>(); public ObservableCollection<VenueViewModel> Venues { get { return _venues; } set { Set(ref _venues, value); } } public VenueViewModel CurrentVenueViewModel { get; set; } public RelayCommand SaveCommand { get; set; } public RelayCommand CancelCommand { get; set; } public override string ToString() { return "Add new Performance"; } } }
36.171975
135
0.576334
[ "Apache-2.0" ]
Xpitfire/ufo
UFO.Commander/UFO.Commander/ViewModel/PerformanceEditViewModel.cs
5,681
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace BatMap { internal class ProjectionVisitor : ExpressionVisitor { private readonly MapConfiguration _mapConfiguration; private readonly IEnumerable<IncludePath> _includes; internal ProjectionVisitor(MapConfiguration mapConfiguration, IEnumerable<IncludePath> includes) { _mapConfiguration = mapConfiguration; _includes = includes; } internal LambdaExpression VisitProjector(LambdaExpression projector) { var newBody = Visit(projector.Body); return Expression.Lambda(newBody, projector.Parameters[0]); } protected override Expression VisitMemberInit(MemberInitExpression node) { node = (MemberInitExpression)base.VisitMemberInit(node); var newBindings = new List<MemberBinding>(); foreach (var binding in node.Bindings) { var assignment = binding as MemberAssignment; if (assignment?.Expression is DefaultExpression) continue; newBindings.Add(binding); } return Expression.MemberInit(node.NewExpression, newBindings); } protected override Expression VisitMethodCall(MethodCallExpression node) { if (node.Method.DeclaringType == typeof(MapContext)) return VisitMapContextCall(node); if (node.Method.DeclaringType == typeof(Enumerable) && node.Method.Name == "Select") return VisitSelectCall(node); return base.VisitMethodCall(node); } private Expression VisitMapContextCall(MethodCallExpression node) { switch (node.Method.Name) { case "Map": { var inPrm = node.Arguments[0]; var inType = inPrm.Type; var outType = node.Method.ReturnType; if (_includes != null && !CheckInclude(inPrm)) return Expression.Default(outType); var mapDefinition = _mapConfiguration.GetMapDefinition(inType, outType); var projector = mapDefinition.Projector; var oldInPrm = projector.Parameters[0]; var memberInit = (MemberInitExpression)projector.Body; var replaceParams = new Dictionary<ParameterExpression, Expression> { { oldInPrm, inPrm } }; var parameterReplaceVisitor = new ParameterReplaceVisitor(replaceParams); return Visit(parameterReplaceVisitor.Visit(memberInit)); } case "MapToList": { var retType = node.Method.ReturnType; var inPrm = node.Arguments[0]; var genPrms = node.Method.GetGenericArguments(); var inType = genPrms[0]; var outType = genPrms[1]; IncludePath memberIncludePath = null; if (_includes != null && !TryGetIncludePath(inPrm, out memberIncludePath)) return Expression.Default(retType); var mapDefinition = _mapConfiguration.GetMapDefinition(inType, outType); var subValue = new ProjectionVisitor(_mapConfiguration, memberIncludePath?.Children).VisitProjector(mapDefinition.Projector); var methodName = node.Method.Name.Substring(3); var subProjector = Expression.Call(typeof(Enumerable), "Select", new[] { node.Method.GetGenericArguments()[0], node.Method.GetGenericArguments()[1] }, node.Arguments[0], subValue); #if NET_STANDARD var typeArg = node.Method.ReturnType.GenericTypeArguments[0]; #else var typeArg = node.Method.ReturnType.GetGenericArguments()[0]; #endif return Expression.Call(typeof(Enumerable), methodName, new[] { typeArg }, subProjector); } default: throw new InvalidOperationException( $"Projection does not support MapContext method '{node.Method.Name}', only 'Map' and 'MapToList' are supported." ); } } private Expression VisitSelectCall(MethodCallExpression node) { var inPrm = node.Arguments[0]; IEnumerable<IncludePath> childPaths = null; if (_includes != null) { IncludePath subPath; TryGetIncludePath(inPrm, out subPath); childPaths = subPath?.Children ?? Enumerable.Empty<IncludePath>(); } var subValue = new ProjectionVisitor(_mapConfiguration, childPaths).Visit(node.Arguments[1]); return Expression.Call(typeof(Enumerable), "Select", new[] { node.Method.GetGenericArguments()[0], node.Method.GetGenericArguments()[1] }, node.Arguments[0], subValue); } private bool CheckInclude(Expression member) { IncludePath includePath; return TryGetIncludePath(member, out includePath); } private bool TryGetIncludePath(Expression memberExp, out IncludePath includePath) { includePath = null; var path = Helper.GetMemberPath(memberExp); var includes = _includes; foreach (var member in path) { includePath = includes.FirstOrDefault(i => i.Member == member); if (includePath == null) return false; includes = includePath.Children; } return true; } } }
42.217391
145
0.586165
[ "MIT" ]
liamwang/BatMap
BatMap/ProjectionVisitor.cs
5,826
C#
namespace ABCo.ABSave.Mapping.Description { public enum SaveMembersMode : byte { Fields = 1, Properties = 2 } public enum SaveInheritanceMode { /// <summary> /// Tells ABSave to use the index the type appears in the list provided to store what sub-type is present. /// </summary> Index, /// <summary> /// Tells ABSave to use a named key (provided as an attribute on each sub-type) to store what sub-type is present. /// The ABSave document has a built-in caching feature so the key is only ever stored once if used. /// You still need to provide a list of all the types with this key. You may add them via settings too /// </summary> Key, /// <summary> /// When this attribute is applied you must provide two arrays: One for <see cref="SaveInheritanceMode.Index"/> mode /// and one for <see cref="SaveInheritanceMode.Key"/> mode. /// </summary> IndexOrKey, } }
34.233333
126
0.609542
[ "MIT" ]
ABCo-Src/ABSave
ABCo.ABSave/Mapping/Description/SaveMembersMode.cs
1,029
C#
using UnityEngine; using UnityEditor; using System.Linq; using ParadoxEngine.Utilities; [CustomEditor(typeof(NHideCharacter))] public class NHideCharacterEditor : Editor { private GUIStyle _title; private NHideCharacter _node; private Container _characterContainer; private int _characterSelected; private int _spriteSelected; private void OnEnable() { _node = (NHideCharacter)target; _characterContainer = (Container)AssetDatabase.LoadAssetAtPath("Assets/Paradox Engine/Database/Data/Characters.asset", typeof(Container)); if (_characterContainer.data == null || !_characterContainer.data.Any() || !_characterContainer.data.Contains(_node.character)) { _node.character = null; _node.sprite = null; return; } if (_node.character != null) _characterSelected = _characterContainer.data.Select(x => (DCharacter)x).IndexOf(x => x == _node.character); else { _node.character = (DCharacter)_characterContainer.data.Select(x => x as DCharacter).First(); _characterSelected = 0; } if (_node.sprite != null) { if (_node.character.ContainsSprite(_node.sprite)) _spriteSelected = _node.character.SpriteForeach().IndexOf(x => x.Item2 == _node.sprite); else { _node.sprite = _node.character.SpriteForeach().GetValue(0).Item2; _spriteSelected = 0; } } else { _node.sprite = _node.character.SpriteForeach().GetValue(0).Item2; _spriteSelected = 0; } } public override void OnInspectorGUI() { _title = new GUIStyle(GUI.skin.label) { fontSize = 16, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleCenter, stretchWidth = true }; GUILayout.Space(10); GUILayout.Label("PARADOX ENGINE" + "\n" + "HIDE CHARACTER STATE", _title); GUILayout.Space(10); EditorGUI.DrawRect(GUILayoutUtility.GetRect(100, 2), Color.black); GUILayout.Space(20); EditorGUILayout.LabelField("Info:"); GUILayout.BeginVertical("BOX"); EditorGUILayout.LabelField("\n The hide character state takes out a character in the scene.\n", new GUIStyle(GUI.skin.label) { wordWrap = true, fontStyle = FontStyle.Italic }); GUILayout.EndVertical(); GUILayout.Space(10); if (_characterContainer.data == null || !_characterContainer.data.Any()) { GUILayout.BeginVertical("BOX"); EditorGUILayout.HelpBox("The database don't have Characters.", MessageType.Warning); _node.character = null; _node.sprite = null; GUILayout.EndVertical(); return; } if (_node.character == null) { _node.character = (DCharacter)_characterContainer.data.Select(x => x as DCharacter).First(); _characterSelected = 0; _node.sprite = _node.character.SpriteForeach().GetValue(0).Item2; _spriteSelected = 0; } var allCharacaters = _characterContainer.data.Select(x => x as DCharacter).Select(x => x.name).ToArray(); GUILayout.BeginHorizontal(); EditorGUI.BeginChangeCheck(); EditorGUILayout.LabelField(new GUIContent("Character:", "Select a Character to takes out.")); _characterSelected = EditorGUILayout.Popup(_characterSelected, allCharacaters); GUILayout.EndHorizontal(); if (EditorGUI.EndChangeCheck()) { _node.character = (DCharacter)_characterContainer.data.Select(x => x as DCharacter) .GetValue(_characterSelected); EngineGraphUtilities.SetDirty(_node); } GUILayout.Space(5); EditorGUI.BeginChangeCheck(); GUILayout.BeginVertical("BOX"); GUILayout.BeginHorizontal(); EditorGUILayout.LabelField(new GUIContent("Duration time:", "Duration of the transition.")); _node.timeDuration = EditorGUILayout.FloatField(_node.timeDuration); GUILayout.EndHorizontal(); if (_node.timeDuration < 0) _node.timeDuration = 0; GUILayout.Space(3); GUILayout.BeginHorizontal(); EditorGUILayout.LabelField(new GUIContent("Transition type:", "Type of transition to introduce Character.")); _node.transition = (EnumCharacterTransition)EditorGUILayout.EnumPopup(_node.transition); if (EditorGUI.EndChangeCheck()) EngineGraphUtilities.SetDirty(_node); GUILayout.EndHorizontal(); GUILayout.EndVertical(); } }
32.344595
184
0.62231
[ "MIT" ]
deadlysmiletm/ADayWithArcueid
Assets/Paradox Engine/Graph/Editor/CustomInspector/Nodes/NHideCharacterEditor.cs
4,789
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text.Encodings.Web; using System.Threading.Tasks; using JRPC_HMS.Services.Mail; namespace Microsoft.AspNetCore.Mvc { public static class MailManagerExtensions { public static Task SendEmailConfirmationAsync(this IMailManager emailManager, string email, string link) { return emailManager.SendEmailAsync(email, "Confirm your email", $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(link)}'>clicking here</a>."); } public static Task SendResetPasswordAsync(this IMailManager emailManager, string email, string callbackUrl) { return emailManager.SendEmailAsync(email, "Reset Password", $"Please reset your password by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); } } }
36.56
121
0.699125
[ "MIT" ]
rudman11/JRPC_HMS
Extensions/MailManagerExtensions.cs
914
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Transactions { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2229", Justification = "Serialization not yet supported and will be done using DistributedTransaction")] [Serializable] public sealed class DependentTransaction : Transaction { private bool _blocking; // Create a transaction with the given settings // internal DependentTransaction(IsolationLevel isoLevel, InternalTransaction internalTransaction, bool blocking) : base(isoLevel, internalTransaction) { _blocking = blocking; lock (_internalTransaction) { if (blocking) { _internalTransaction.State.CreateBlockingClone(_internalTransaction); } else { _internalTransaction.State.CreateAbortingClone(_internalTransaction); } } } public void Complete() { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this); } lock (_internalTransaction) { if (Disposed) { throw new ObjectDisposedException(nameof(DependentTransaction)); } if (_complete) { throw TransactionException.CreateTransactionCompletedException(DistributedTxId); } _complete = true; if (_blocking) { _internalTransaction.State.CompleteBlockingClone(_internalTransaction); } else { _internalTransaction.State.CompleteAbortingClone(_internalTransaction); } } if (etwLog.IsEnabled()) { etwLog.TransactionDependentCloneComplete(this, "DependentTransaction"); etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this); } } } }
33.232877
179
0.563067
[ "MIT" ]
Aevitas/corefx
src/System.Transactions.Local/src/System/Transactions/DependentTransaction.cs
2,426
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using NUnit.Framework; using ProtoBuf; using ProtoBuf.Meta; namespace Examples.Issues { [TestFixture] public class SO11317045 { [ProtoContract] [ProtoInclude(1, typeof(A), DataFormat = DataFormat.Group)] public class ABase { } [ProtoContract] public class A : ABase { [ProtoMember(1, DataFormat = DataFormat.Group)] public B B { get; set; } } [ProtoContract] public class B { [ProtoMember(1, DataFormat = DataFormat.Group)] public List<byte[]> Data { get; set; } } [Test] public void Execute() { var a = new A(); var b = new B(); a.B = b; b.Data = new List<byte[]> { Enumerable.Range(0, 1999).Select(v => (byte)v).ToArray(), Enumerable.Range(2000, 3999).Select(v => (byte)v).ToArray(), }; var stream = new MemoryStream(); var model = TypeModel.Create(); model.AutoCompile = false; #if DEBUG // this is only available in debug builds; if set, an exception is // thrown if the stream tries to buffer model.ForwardsOnly = true; #endif CheckClone(model, a); model.CompileInPlace(); CheckClone(model, a); CheckClone(model.Compile(), a); } void CheckClone(TypeModel model, A original) { int sum = original.B.Data.Sum(x => x.Sum(b => (int)b)); var clone = (A)model.DeepClone(original); Assert.IsInstanceOfType(typeof(A), clone); Assert.IsInstanceOfType(typeof(B), clone.B); Assert.AreEqual(sum, clone.B.Data.Sum(x => x.Sum(b => (int)b))); } [Test] public void TestProtoIncludeWithStringKnownTypeName() { NamedProtoInclude.Foo foo = new NamedProtoInclude.Bar(); var clone = Serializer.DeepClone(foo); Assert.IsInstanceOfType(typeof(NamedProtoInclude.Bar), foo); } } } namespace Examples.Issues.NamedProtoInclude { [ProtoContract] [ProtoInclude(1, "Examples.Issues.NamedProtoInclude.Bar")] internal class Foo { } [ProtoContract] internal class Bar : Foo { } }
24.903846
76
0.523938
[ "MIT" ]
Bhaskers-Blu-Org2/vsminecraft
dependencies/protobuf-net/Examples/Issues/SO11317045.cs
2,592
C#
using System.Threading.Tasks; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Host; using Microsoft.Extensions.Logging; using TextMood.Backend.Common; namespace TextMood.Functions { [StorageAccount(QueueNameConstants.AzureWebJobsStorage)] public static class SaveTextModelToDatabase { [FunctionName(nameof(SaveTextModelToDatabase))] public static async Task Run([QueueTrigger(QueueNameConstants.TextModelForDatabase)]TextMoodModel textModel, ILogger log) { log.LogInformation("Saving TextModel to Database"); if (textModel.Text.Length > 128) textModel.Text = textModel.Text.Substring(0, 128); await TextMoodDatabase.InsertTextModel(textModel).ConfigureAwait(false); } } }
30.384615
129
0.722785
[ "MIT" ]
AzureAdvocateBit/TextMood
TextMood.Functions/Functions/SaveTextModelToDatabase.cs
790
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ManagerApp_GUI.View { interface ICategoryManagerView { void ClearCategoryList(); void AddCategoryToList(int id, string name); void BlockEditControls(); void UnblockEditControls(); void SetCategoryId(string id); void SetCategoryName(string name); void AddFilterToList(int id, string name); void SetFilterCheckbox(int id, bool state); void ClearFiltersList(); void ShowError(string msg); } }
23.703704
53
0.651563
[ "MIT" ]
pacmancoder/WebTrainingYard
client/ManagerApp/ManagerApp_GUI/View/ICategoryManagerView.cs
642
C#
using System.Threading.Tasks; using MAVN.Service.SmsProviderInfobip.InfobipClient.Models.Requests; using MAVN.Service.SmsProviderInfobip.InfobipClient.Models.Responses; using Refit; namespace MAVN.Service.SmsProviderInfobip.InfobipClient { /// <summary> /// Interface that describes Infobip SMS client access /// </summary> public interface IInfobip { /// <summary> /// Infobip endpoint that is used to send SMS /// </summary> /// <param name="requestModel">SMS data</param> /// <returns></returns> [Post("/sms/2/text/single")] Task<SmsResponseModel> SendSmsAsync([Body] SendSmsRequestModel requestModel); } }
31.409091
85
0.680174
[ "MIT" ]
HannaAndreevna/MAVN.Service.SMSProviderInfobip
client/MAVN.Service.SmsProviderInfobip.InfobipClient/IInfobip.cs
691
C#
using System; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Xamarin.MacDev; using Xamarin.Localization.MSBuild; namespace Xamarin.MacDev.Tasks { public abstract class GetNativeExecutableNameTaskBase : XamarinTask { #region Inputs [Required] public string AppManifest { get; set; } #endregion #region Outputs [Output] public string ExecutableName { get; set; } #endregion public override bool Execute () { PDictionary plist; try { plist = PDictionary.FromFile (AppManifest); } catch (Exception ex) { Log.LogError (MSBStrings.E0055, ex.Message); return false; } ExecutableName = plist.GetCFBundleExecutable (); return !Log.HasLoggedErrors; } } }
16.772727
68
0.714092
[ "BSD-3-Clause" ]
Therzok/xamarin-macios
msbuild/Xamarin.MacDev.Tasks.Core/Tasks/GetNativeExecutableNameTaskBase.cs
740
C#
using System.Collections.Generic; using Math = System.Math; using UnityEngine; #if UNITY_5_5_OR_NEWER using UnityEngine.Profiling; #endif namespace Pathfinding { using Pathfinding.Serialization; using Pathfinding.Util; [JsonOptIn] /// <summary> /// Generates a grid of nodes. /// The GridGraph does exactly what the name implies, generates nodes in a grid pattern.\n /// Grid graphs suit well to when you already have a grid based world. /// Features: /// - You can update the graph during runtime (good for e.g Tower Defence or RTS games) /// - Throw any scene at it, with minimal configurations you can get a good graph from it. /// - Supports raycast and the funnel algorithm /// - Predictable pattern /// - Can apply penalty and walkability values from a supplied image /// - Perfect for terrain worlds since it can make areas unwalkable depending on the slope /// /// [Open online documentation to see images] /// [Open online documentation to see images] /// /// The <b>The Snap Size</b> button snaps the internal size of the graph to exactly contain the current number of nodes, i.e not contain 100.3 nodes but exactly 100 nodes.\n /// This will make the "center" coordinate more accurate.\n /// /// <b>Updating the graph during runtime</b>\n /// Any graph which implements the IUpdatableGraph interface can be updated during runtime.\n /// For grid graphs this is a great feature since you can update only a small part of the grid without causing any lag like a complete rescan would.\n /// If you for example just have instantiated a sphere obstacle in the scene and you want to update the grid where that sphere was instantiated, you can do this:\n /// <code> AstarPath.active.UpdateGraphs (ob.collider.bounds); </code> /// Where ob is the obstacle you just instantiated (a GameObject).\n /// As you can see, the UpdateGraphs function takes a Bounds parameter and it will send an update call to all updateable graphs.\n /// A grid graph will update that area and a small margin around it equal to \link Pathfinding.GraphCollision.diameter collision testing diameter/2 \endlink /// See: graph-updates (view in online documentation for working links) for more info about updating graphs during runtime /// /// <b>Hexagon graphs</b>\n /// The graph can be configured to work like a hexagon graph with some simple settings. Since 4.1.x the grid graph has a 'Shape' dropdown. /// If you set it to 'Hexagonal' the graph will behave as a hexagon graph. /// Often you may want to rotate the graph +45 or -45 degrees. /// [Open online documentation to see images] /// /// Note however that the snapping to the closest node is not exactly as you would expect in a real hexagon graph, /// but it is close enough that you will likely not notice. /// /// <b>Configure using code</b>\n /// <code> /// // This holds all graph data /// AstarData data = AstarPath.active.data; /// /// // This creates a Grid Graph /// GridGraph gg = data.AddGraph(typeof(GridGraph)) as GridGraph; /// /// // Setup a grid graph with some values /// int width = 50; /// int depth = 50; /// float nodeSize = 1; /// /// gg.center = new Vector3(10, 0, 0); /// /// // Updates internal size from the above values /// gg.SetDimensions(width, depth, nodeSize); /// /// // Scans all graphs /// AstarPath.active.Scan(); /// </code> /// /// \ingroup graphs /// \nosubgrouping /// /// <b>Tree colliders</b>\n /// It seems that Unity will only generate tree colliders at runtime when the game is started. /// For this reason, the grid graph will not pick up tree colliders when outside of play mode /// but it will pick them up once the game starts. If it still does not pick them up /// make sure that the trees actually have colliders attached to them and that the tree prefabs are /// in the correct layer (the layer should be included in the 'Collision Testing' mask). /// /// See: <see cref="Pathfinding.GraphCollision"/> for documentation on the 'Height Testing' and 'Collision Testing' sections /// of the grid graph settings. /// </summary> public class GridGraph : NavGraph, IUpdatableGraph, ITransformedGraph { /// <summary>This function will be called when this graph is destroyed</summary> protected override void OnDestroy () { base.OnDestroy(); // Clean up a reference in a static variable which otherwise should point to this graph forever and stop the GC from collecting it RemoveGridGraphFromStatic(); } protected override void DestroyAllNodes () { GetNodes(node => { // If the grid data happens to be invalid (e.g we had to abort a graph update while it was running) using 'false' as // the parameter will prevent the Destroy method from potentially throwing IndexOutOfRange exceptions due to trying // to access nodes outside the graph. It is safe to do this because we are destroying all nodes in the graph anyway. // We do however need to clear custom connections in both directions (node as GridNodeBase).ClearCustomConnections(true); node.ClearConnections(false); node.Destroy(); }); } void RemoveGridGraphFromStatic () { GridNode.SetGridGraph(AstarPath.active.data.GetGraphIndex(this), null); } /// <summary> /// This is placed here so generators inheriting from this one can override it and set it to false. /// If it is true, it means that the nodes array's length will always be equal to width*depth /// It is used mainly in the editor to do auto-scanning calls, setting it to false for a non-uniform grid will reduce the number of scans /// </summary> public virtual bool uniformWidthDepthGrid { get { return true; } } /// <summary> /// Number of layers in the graph. /// For grid graphs this is always 1, for layered grid graphs it can be higher. /// The nodes array has the size width*depth*layerCount. /// </summary> public virtual int LayerCount { get { return 1; } } public override int CountNodes () { return nodes.Length; } public override void GetNodes (System.Action<GraphNode> action) { if (nodes == null) return; for (int i = 0; i < nodes.Length; i++) action(nodes[i]); } /// <summary> /// \name Inspector - Settings /// \{ /// </summary> /// <summary> /// Determines the layout of the grid graph inspector in the Unity Editor. /// This field is only used in the editor, it has no effect on the rest of the game whatsoever. /// </summary> [JsonMember] public InspectorGridMode inspectorGridMode = InspectorGridMode.Grid; /// <summary> /// Determines how the size of each hexagon is set in the inspector. /// For hexagons the normal nodeSize field doesn't really correspond to anything specific on the hexagon's geometry, so this enum is used to give the user the opportunity to adjust more concrete dimensions of the hexagons /// without having to pull out a calculator to calculate all the square roots and complicated conversion factors. /// /// This field is only used in the graph inspector, the <see cref="nodeSize"/> field will always use the same internal units. /// If you want to set the node size through code then you can use <see cref="ConvertHexagonSizeToNodeSize"/>. /// /// See: <see cref="InspectorGridHexagonNodeSize"/> /// See: <see cref="ConvertHexagonSizeToNodeSize"/> /// See: <see cref="ConvertNodeSizeToHexagonSize"/> /// </summary> [JsonMember] public InspectorGridHexagonNodeSize inspectorHexagonSizeMode = InspectorGridHexagonNodeSize.Width; /// <summary>Width of the grid in nodes. See: SetDimensions</summary> public int width; /// <summary>Depth (height) of the grid in nodes. See: SetDimensions</summary> public int depth; /// <summary> /// Scaling of the graph along the X axis. /// This should be used if you want different scales on the X and Y axis of the grid /// </summary> [JsonMember] public float aspectRatio = 1F; /// <summary> /// Angle to use for the isometric projection. /// If you are making a 2D isometric game, you may want to use this parameter to adjust the layout of the graph to match your game. /// This will essentially scale the graph along one of its diagonals to produce something like this: /// /// A perspective view of an isometric graph. /// [Open online documentation to see images] /// /// A top down view of an isometric graph. Note that the graph is entirely 2D, there is no perspective in this image. /// [Open online documentation to see images] /// /// Usually the angle that you want to use is either 30 degrees (alternatively 90-30 = 60 degrees) or atan(1/sqrt(2)) which is approximately 35.264 degrees (alternatively 90 - 35.264 = 54.736 degrees). /// You might also want to rotate the graph plus or minus 45 degrees around the Y axis to get the oritientation required for your game. /// /// You can read more about it on the wikipedia page linked below. /// /// See: http://en.wikipedia.org/wiki/Isometric_projection /// See: https://en.wikipedia.org/wiki/Isometric_graphics_in_video_games_and_pixel_art /// See: rotation /// </summary> [JsonMember] public float isometricAngle; /// <summary> /// If true, all edge costs will be set to the same value. /// If false, diagonals will cost more. /// This is useful for a hexagon graph where the diagonals are actually the same length as the /// normal edges (since the graph has been skewed) /// </summary> [JsonMember] public bool uniformEdgeCosts; /// <summary>Rotation of the grid in degrees</summary> [JsonMember] public Vector3 rotation; /// <summary>Center point of the grid</summary> [JsonMember] public Vector3 center; /// <summary>Size of the grid. Might be negative or smaller than <see cref="nodeSize"/></summary> [JsonMember] public Vector2 unclampedSize; /// <summary> /// Size of one node in world units. /// See: <see cref="SetDimensions"/> /// </summary> [JsonMember] public float nodeSize = 1; /* Collision and stuff */ /// <summary>Settings on how to check for walkability and height</summary> [JsonMember] public GraphCollision collision; /// <summary> /// The max position difference between two nodes to enable a connection. /// Set to 0 to ignore the value. /// </summary> [JsonMember] public float maxClimb = 0.4F; /// <summary>The max slope in degrees for a node to be walkable.</summary> [JsonMember] public float maxSlope = 90; /// <summary> /// Use heigh raycasting normal for max slope calculation. /// True if <see cref="maxSlope"/> is less than 90 degrees. /// </summary> protected bool useRaycastNormal { get { return Math.Abs(90-maxSlope) > float.Epsilon; } } /// <summary> /// Erosion of the graph. /// The graph can be eroded after calculation. /// This means a margin is put around unwalkable nodes or other unwalkable connections. /// It is really good if your graph contains ledges where the nodes without erosion are walkable too close to the edge. /// /// Below is an image showing a graph with erode iterations 0, 1 and 2 /// [Open online documentation to see images] /// /// Note: A high number of erode iterations can seriously slow down graph updates during runtime (GraphUpdateObject) /// and should be kept as low as possible. /// See: erosionUseTags /// </summary> [JsonMember] public int erodeIterations; /// <summary> /// Use tags instead of walkability for erosion. /// Tags will be used for erosion instead of marking nodes as unwalkable. The nodes will be marked with tags in an increasing order starting with the tag <see cref="erosionFirstTag"/>. /// Debug with the Tags mode to see the effect. With this enabled you can in effect set how close different AIs are allowed to get to walls using the Valid Tags field on the Seeker component. /// [Open online documentation to see images] /// [Open online documentation to see images] /// See: erosionFirstTag /// </summary> [JsonMember] public bool erosionUseTags; /// <summary> /// Tag to start from when using tags for erosion. /// See: <see cref="erosionUseTags"/> /// See: <see cref="erodeIterations"/> /// </summary> [JsonMember] public int erosionFirstTag = 1; /// <summary> /// Number of neighbours for each node. /// Either four, six, eight connections per node. /// /// Six connections is primarily for emulating hexagon graphs. /// </summary> [JsonMember] public NumNeighbours neighbours = NumNeighbours.Eight; /// <summary> /// If disabled, will not cut corners on obstacles. /// If \link <see cref="neighbours"/> connections \endlink is Eight, obstacle corners might be cut by a connection, /// setting this to false disables that. \image html images/cutCorners.png /// </summary> [JsonMember] public bool cutCorners = true; /// <summary> /// Offset for the position when calculating penalty. /// See: penaltyPosition /// </summary> [JsonMember] public float penaltyPositionOffset; /// <summary>Use position (y-coordinate) to calculate penalty</summary> [JsonMember] public bool penaltyPosition; /// <summary> /// Scale factor for penalty when calculating from position. /// See: penaltyPosition /// </summary> [JsonMember] public float penaltyPositionFactor = 1F; [JsonMember] public bool penaltyAngle; /// <summary> /// How much penalty is applied depending on the slope of the terrain. /// At a 90 degree slope (not that exactly 90 degree slopes can occur, but almost 90 degree), this penalty is applied. /// At a 45 degree slope, half of this is applied and so on. /// Note that you may require very large values, a value of 1000 is equivalent to the cost of moving 1 world unit. /// </summary> [JsonMember] public float penaltyAngleFactor = 100F; /// <summary>How much extra to penalize very steep angles</summary> [JsonMember] public float penaltyAnglePower = 1; /// <summary>Show an outline of the grid nodes in the Unity Editor</summary> [JsonMember] public bool showMeshOutline = true; /// <summary>Show the connections between the grid nodes in the Unity Editor</summary> [JsonMember] public bool showNodeConnections; /// <summary>Show the surface of the graph. Each node will be drawn as a square (unless e.g hexagon graph mode has been enabled).</summary> [JsonMember] public bool showMeshSurface = true; /// <summary>\}</summary> /// <summary> /// Size of the grid. Will always be positive and larger than <see cref="nodeSize"/>. /// See: <see cref="UpdateTransform"/> /// </summary> public Vector2 size { get; protected set; } /* End collision and stuff */ /// <summary> /// Index offset to get neighbour nodes. Added to a node's index to get a neighbour node index. /// /// <code> /// Z /// | /// | /// /// 6 2 5 /// \ | / /// -- 3 - X - 1 ----- X /// / | \ /// 7 0 4 /// /// | /// | /// </code> /// </summary> [System.NonSerialized] public readonly int[] neighbourOffsets = new int[8]; /// <summary>Costs to neighbour nodes</summary> [System.NonSerialized] public readonly uint[] neighbourCosts = new uint[8]; /// <summary>Offsets in the X direction for neighbour nodes. Only 1, 0 or -1</summary> [System.NonSerialized] public readonly int[] neighbourXOffsets = new int[8]; /// <summary>Offsets in the Z direction for neighbour nodes. Only 1, 0 or -1</summary> [System.NonSerialized] public readonly int[] neighbourZOffsets = new int[8]; /// <summary>Which neighbours are going to be used when <see cref="neighbours"/>=6</summary> internal static readonly int[] hexagonNeighbourIndices = { 0, 1, 5, 2, 3, 7 }; /// <summary>In GetNearestForce, determines how far to search after a valid node has been found</summary> public const int getNearestForceOverlap = 2; /// <summary> /// All nodes in this graph. /// Nodes are laid out row by row. /// /// The first node has grid coordinates X=0, Z=0, the second one X=1, Z=0\n /// the last one has grid coordinates X=width-1, Z=depth-1. /// /// <code> /// var gg = AstarPath.active.data.gridGraph; /// int x = 5; /// int z = 8; /// GridNode node = gg.nodes[z*gg.width + x]; /// </code> /// /// See: <see cref="GetNode"/> /// See: <see cref="GetNodes"/> /// </summary> public GridNode[] nodes; /// <summary> /// Determines how the graph transforms graph space to world space. /// See: <see cref="UpdateTransform"/> /// </summary> public GraphTransform transform { get; private set; } public GridGraph () { unclampedSize = new Vector2(10, 10); nodeSize = 1F; collision = new GraphCollision(); transform = new GraphTransform(Matrix4x4.identity); } public override void RelocateNodes (Matrix4x4 deltaMatrix) { // It just makes a lot more sense to use the other overload and for that case we don't have to serialize the matrix throw new System.Exception("This method cannot be used for Grid Graphs. Please use the other overload of RelocateNodes instead"); } /// <summary> /// Relocate the grid graph using new settings. /// This will move all nodes in the graph to new positions which matches the new settings. /// </summary> public void RelocateNodes (Vector3 center, Quaternion rotation, float nodeSize, float aspectRatio = 1, float isometricAngle = 0) { var previousTransform = transform; this.center = center; this.rotation = rotation.eulerAngles; this.aspectRatio = aspectRatio; this.isometricAngle = isometricAngle; SetDimensions(width, depth, nodeSize); GetNodes(node => { var gnode = node as GridNodeBase; var height = previousTransform.InverseTransform((Vector3)node.position).y; node.position = GraphPointToWorld(gnode.XCoordinateInGrid, gnode.ZCoordinateInGrid, height); }); } /// <summary> /// Transform a point in graph space to world space. /// This will give you the node position for the node at the given x and z coordinate /// if it is at the specified height above the base of the graph. /// </summary> public Int3 GraphPointToWorld (int x, int z, float height) { return (Int3)transform.Transform(new Vector3(x+0.5f, height, z+0.5f)); } public static float ConvertHexagonSizeToNodeSize (InspectorGridHexagonNodeSize mode, float value) { if (mode == InspectorGridHexagonNodeSize.Diameter) value *= 1.5f/(float)System.Math.Sqrt(2.0f); else if (mode == InspectorGridHexagonNodeSize.Width) value *= (float)System.Math.Sqrt(3.0f/2.0f); return value; } public static float ConvertNodeSizeToHexagonSize (InspectorGridHexagonNodeSize mode, float value) { if (mode == InspectorGridHexagonNodeSize.Diameter) value *= (float)System.Math.Sqrt(2.0f)/1.5f; else if (mode == InspectorGridHexagonNodeSize.Width) value *= (float)System.Math.Sqrt(2.0f/3.0f); return value; } public int Width { get { return width; } set { width = value; } } public int Depth { get { return depth; } set { depth = value; } } public uint GetConnectionCost (int dir) { return neighbourCosts[dir]; } public GridNode GetNodeConnection (GridNode node, int dir) { if (!node.HasConnectionInDirection(dir)) return null; if (!node.EdgeNode) { return nodes[node.NodeInGridIndex + neighbourOffsets[dir]]; } else { int index = node.NodeInGridIndex; //int z = Math.DivRem (index,Width, out x); int z = index/Width; int x = index - z*Width; return GetNodeConnection(index, x, z, dir); } } public bool HasNodeConnection (GridNode node, int dir) { if (!node.HasConnectionInDirection(dir)) return false; if (!node.EdgeNode) { return true; } else { int index = node.NodeInGridIndex; int z = index/Width; int x = index - z*Width; return HasNodeConnection(index, x, z, dir); } } public void SetNodeConnection (GridNode node, int dir, bool value) { int index = node.NodeInGridIndex; int z = index/Width; int x = index - z*Width; SetNodeConnection(index, x, z, dir, value); } /// <summary> /// Get the connecting node from the node at (x,z) in the specified direction. /// Returns: A GridNode if the node has a connection to that node. Null if no connection in that direction exists /// /// See: GridNode /// </summary> private GridNode GetNodeConnection (int index, int x, int z, int dir) { if (!nodes[index].HasConnectionInDirection(dir)) return null; /// <summary>TODO: Mark edge nodes and only do bounds checking for them</summary> int nx = x + neighbourXOffsets[dir]; if (nx < 0 || nx >= Width) return null; /// <summary>TODO: Modify to get adjacent grid graph here</summary> int nz = z + neighbourZOffsets[dir]; if (nz < 0 || nz >= Depth) return null; int nindex = index + neighbourOffsets[dir]; return nodes[nindex]; } /// <summary> /// Set if connection in the specified direction should be enabled. /// Note that bounds checking will still be done when getting the connection value again, /// so it is not necessarily true that HasNodeConnection will return true just because you used /// SetNodeConnection on a node to set a connection to true. /// /// Note: This is identical to Pathfinding.Node.SetConnectionInternal /// /// Deprecated: /// </summary> /// <param name="index">Index of the node</param> /// <param name="x">X coordinate of the node</param> /// <param name="z">Z coordinate of the node</param> /// <param name="dir">Direction from 0 up to but excluding 8.</param> /// <param name="value">Enable or disable the connection</param> public void SetNodeConnection (int index, int x, int z, int dir, bool value) { nodes[index].SetConnectionInternal(dir, value); } public bool HasNodeConnection (int index, int x, int z, int dir) { if (!nodes[index].HasConnectionInDirection(dir)) return false; /// <summary>TODO: Mark edge nodes and only do bounds checking for them</summary> int nx = x + neighbourXOffsets[dir]; if (nx < 0 || nx >= Width) return false; /// <summary>TODO: Modify to get adjacent grid graph here</summary> int nz = z + neighbourZOffsets[dir]; if (nz < 0 || nz >= Depth) return false; return true; } /// <summary> /// Updates <see cref="unclampedSize"/> from <see cref="width"/>, <see cref="depth"/> and <see cref="nodeSize"/> values. /// Also \link UpdateTransform generates a new matrix \endlink. /// Note: This does not rescan the graph, that must be done with Scan /// /// You should use this method instead of setting the <see cref="width"/> and <see cref="depth"/> fields /// as the grid dimensions are not defined by the <see cref="width"/> and <see cref="depth"/> variables but by /// the <see cref="unclampedSize"/> and <see cref="center"/> variables. /// /// <code> /// var gg = AstarPath.active.data.gridGraph; /// var width = 80; /// var depth = 60; /// var nodeSize = 1.0f; /// /// gg.SetDimensions(width, depth, nodeSize); /// /// // Recalculate the graph /// AstarPath.active.Scan(); /// </code> /// </summary> public void SetDimensions (int width, int depth, float nodeSize) { unclampedSize = new Vector2(width, depth)*nodeSize; this.nodeSize = nodeSize; UpdateTransform(); } /// <summary>Updates <see cref="unclampedSize"/> from <see cref="width"/>, <see cref="depth"/> and <see cref="nodeSize"/> values. Deprecated: Use <see cref="SetDimensions"/> instead</summary> [System.Obsolete("Use SetDimensions instead")] public void UpdateSizeFromWidthDepth () { SetDimensions(width, depth, nodeSize); } /// <summary> /// Generates the matrix used for translating nodes from grid coordinates to world coordinates. /// Deprecated: This method has been renamed to <see cref="UpdateTransform"/> /// </summary> [System.Obsolete("This method has been renamed to UpdateTransform")] public void GenerateMatrix () { UpdateTransform(); } /// <summary> /// Updates the <see cref="transform"/> field which transforms graph space to world space. /// In graph space all nodes are laid out in the XZ plane with the first node having a corner in the origin. /// One unit in graph space is one node so the first node in the graph is at (0.5,0) the second one at (1.5,0) etc. /// /// This takes the current values of the parameters such as position and rotation into account. /// The transform that was used the last time the graph was scanned is stored in the <see cref="transform"/> field. /// /// The <see cref="transform"/> field is calculated using this method when the graph is scanned. /// The width, depth variables are also updated based on the <see cref="unclampedSize"/> field. /// </summary> public void UpdateTransform () { CalculateDimensions(out width, out depth, out nodeSize); transform = CalculateTransform(); } /// <summary> /// Returns a new transform which transforms graph space to world space. /// Does not update the <see cref="transform"/> field. /// See: <see cref="UpdateTransform"/> /// </summary> public GraphTransform CalculateTransform () { int newWidth, newDepth; float newNodeSize; CalculateDimensions(out newWidth, out newDepth, out newNodeSize); // Generate a matrix which shrinks the graph along one of the diagonals // corresponding to the isometricAngle var isometricMatrix = Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0, 45, 0), Vector3.one); isometricMatrix = Matrix4x4.Scale(new Vector3(Mathf.Cos(Mathf.Deg2Rad*isometricAngle), 1, 1)) * isometricMatrix; isometricMatrix = Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0, -45, 0), Vector3.one) * isometricMatrix; // Generate a matrix for the bounds of the graph // This moves a point to the correct offset in the world and the correct rotation and the aspect ratio and isometric angle is taken into account // The unit is still world units however var boundsMatrix = Matrix4x4.TRS(center, Quaternion.Euler(rotation), new Vector3(aspectRatio, 1, 1)) * isometricMatrix; // Generate a matrix where Vector3.zero is the corner of the graph instead of the center // The unit is nodes here (so (0.5,0,0.5) is the position of the first node and (1.5,0,0.5) is the position of the second node) // 0.5 is added since this is the node center, not its corner. In graph space a node has a size of 1 var m = Matrix4x4.TRS(boundsMatrix.MultiplyPoint3x4(-new Vector3(newWidth*newNodeSize, 0, newDepth*newNodeSize)*0.5F), Quaternion.Euler(rotation), new Vector3(newNodeSize*aspectRatio, 1, newNodeSize)) * isometricMatrix; // Set the matrix of the graph // This will also set inverseMatrix return new GraphTransform(m); } /// <summary> /// Calculates the width/depth of the graph from <see cref="unclampedSize"/> and <see cref="nodeSize"/>. /// The node size may be changed due to constraints that the width/depth is not /// allowed to be larger than 1024 (artificial limit). /// </summary> void CalculateDimensions (out int width, out int depth, out float nodeSize) { var newSize = unclampedSize; // Make sure size is positive newSize.x *= Mathf.Sign(newSize.x); newSize.y *= Mathf.Sign(newSize.y); // Clamp the nodeSize so that the graph is never larger than 1024*1024 nodeSize = Mathf.Max(this.nodeSize, newSize.x/1024F); nodeSize = Mathf.Max(this.nodeSize, newSize.y/1024F); // Prevent the graph to become smaller than a single node newSize.x = newSize.x < nodeSize ? nodeSize : newSize.x; newSize.y = newSize.y < nodeSize ? nodeSize : newSize.y; size = newSize; // Calculate the number of nodes along each side width = Mathf.FloorToInt(size.x / nodeSize); depth = Mathf.FloorToInt(size.y / nodeSize); // Take care of numerical edge cases if (Mathf.Approximately(size.x / nodeSize, Mathf.CeilToInt(size.x / nodeSize))) { width = Mathf.CeilToInt(size.x / nodeSize); } if (Mathf.Approximately(size.y / nodeSize, Mathf.CeilToInt(size.y / nodeSize))) { depth = Mathf.CeilToInt(size.y / nodeSize); } } public override NNInfoInternal GetNearest (Vector3 position, NNConstraint constraint, GraphNode hint) { if (nodes == null || depth*width != nodes.Length) { return new NNInfoInternal(); } // Calculate the closest node and the closest point on that node position = transform.InverseTransform(position); float xf = position.x; float zf = position.z; int x = Mathf.Clamp((int)xf, 0, width-1); int z = Mathf.Clamp((int)zf, 0, depth-1); var nn = new NNInfoInternal(nodes[z*width+x]); float y = transform.InverseTransform((Vector3)nodes[z*width+x].position).y; nn.clampedPosition = transform.Transform(new Vector3(Mathf.Clamp(xf, x, x+1f), y, Mathf.Clamp(zf, z, z+1f))); return nn; } public override NNInfoInternal GetNearestForce (Vector3 position, NNConstraint constraint) { if (nodes == null || depth*width != nodes.Length) { return new NNInfoInternal(); } // Position in global space Vector3 globalPosition = position; // Position in graph space position = transform.InverseTransform(position); // Find the coordinates of the closest node float xf = position.x; float zf = position.z; int x = Mathf.Clamp((int)xf, 0, width-1); int z = Mathf.Clamp((int)zf, 0, depth-1); // Closest node GridNode node = nodes[x+z*width]; GridNode minNode = null; float minDist = float.PositiveInfinity; int overlap = getNearestForceOverlap; Vector3 clampedPosition = Vector3.zero; var nn = new NNInfoInternal(null); // If the closest node was suitable if (constraint == null || constraint.Suitable(node)) { minNode = node; minDist = ((Vector3)minNode.position-globalPosition).sqrMagnitude; float y = transform.InverseTransform((Vector3)node.position).y; clampedPosition = transform.Transform(new Vector3(Mathf.Clamp(xf, x, x+1f), y, Mathf.Clamp(zf, z, z+1f))); } if (minNode != null) { nn.node = minNode; nn.clampedPosition = clampedPosition; // We have a node, and we don't need to search more, so just return if (overlap == 0) return nn; overlap--; } // Search up to this distance float maxDist = constraint == null || constraint.constrainDistance ? AstarPath.active.maxNearestNodeDistance : float.PositiveInfinity; float maxDistSqr = maxDist*maxDist; // Search a square/spiral pattern around the point for (int w = 1;; w++) { //Check if the nodes are within distance limit if (nodeSize*w > maxDist) { break; } bool anyInside = false; int nx; int nz = z+w; int nz2 = nz*width; // Side 1 on the square for (nx = x-w; nx <= x+w; nx++) { if (nx < 0 || nz < 0 || nx >= width || nz >= depth) continue; anyInside = true; if (constraint == null || constraint.Suitable(nodes[nx+nz2])) { float dist = ((Vector3)nodes[nx+nz2].position-globalPosition).sqrMagnitude; if (dist < minDist && dist < maxDistSqr) { // Minimum distance so far minDist = dist; minNode = nodes[nx+nz2]; // Closest point on the node if the node is treated as a square clampedPosition = transform.Transform(new Vector3(Mathf.Clamp(xf, nx, nx+1f), transform.InverseTransform((Vector3)minNode.position).y, Mathf.Clamp(zf, nz, nz+1f))); } } } nz = z-w; nz2 = nz*width; // Side 2 on the square for (nx = x-w; nx <= x+w; nx++) { if (nx < 0 || nz < 0 || nx >= width || nz >= depth) continue; anyInside = true; if (constraint == null || constraint.Suitable(nodes[nx+nz2])) { float dist = ((Vector3)nodes[nx+nz2].position-globalPosition).sqrMagnitude; if (dist < minDist && dist < maxDistSqr) { minDist = dist; minNode = nodes[nx+nz2]; clampedPosition = transform.Transform(new Vector3(Mathf.Clamp(xf, nx, nx+1f), transform.InverseTransform((Vector3)minNode.position).y, Mathf.Clamp(zf, nz, nz+1f))); } } } nx = x-w; // Side 3 on the square for (nz = z-w+1; nz <= z+w-1; nz++) { if (nx < 0 || nz < 0 || nx >= width || nz >= depth) continue; anyInside = true; if (constraint == null || constraint.Suitable(nodes[nx+nz*width])) { float dist = ((Vector3)nodes[nx+nz*width].position-globalPosition).sqrMagnitude; if (dist < minDist && dist < maxDistSqr) { minDist = dist; minNode = nodes[nx+nz*width]; clampedPosition = transform.Transform(new Vector3(Mathf.Clamp(xf, nx, nx+1f), transform.InverseTransform((Vector3)minNode.position).y, Mathf.Clamp(zf, nz, nz+1f))); } } } nx = x+w; // Side 4 on the square for (nz = z-w+1; nz <= z+w-1; nz++) { if (nx < 0 || nz < 0 || nx >= width || nz >= depth) continue; anyInside = true; if (constraint == null || constraint.Suitable(nodes[nx+nz*width])) { float dist = ((Vector3)nodes[nx+nz*width].position-globalPosition).sqrMagnitude; if (dist < minDist && dist < maxDistSqr) { minDist = dist; minNode = nodes[nx+nz*width]; clampedPosition = transform.Transform(new Vector3(Mathf.Clamp(xf, nx, nx+1f), transform.InverseTransform((Vector3)minNode.position).y, Mathf.Clamp(zf, nz, nz+1f))); } } } // We found a suitable node if (minNode != null) { // If we don't need to search more, just return // Otherwise search for 'overlap' iterations more if (overlap == 0) { break; } overlap--; } // No nodes were inside grid bounds // We will not be able to find any more valid nodes // so just return if (!anyInside) { break; } } // Copy fields to the NNInfo struct and return nn.node = minNode; nn.clampedPosition = clampedPosition; return nn; } /// <summary> /// Sets up <see cref="neighbourOffsets"/> with the current settings. <see cref="neighbourOffsets"/>, <see cref="neighbourCosts"/>, <see cref="neighbourXOffsets"/> and <see cref="neighbourZOffsets"/> are set up.\n /// The cost for a non-diagonal movement between two adjacent nodes is RoundToInt (<see cref="nodeSize"/> * Int3.Precision)\n /// The cost for a diagonal movement between two adjacent nodes is RoundToInt (<see cref="nodeSize"/> * Sqrt (2) * Int3.Precision) /// </summary> public virtual void SetUpOffsetsAndCosts () { //First 4 are for the four directly adjacent nodes the last 4 are for the diagonals neighbourOffsets[0] = -width; neighbourOffsets[1] = 1; neighbourOffsets[2] = width; neighbourOffsets[3] = -1; neighbourOffsets[4] = -width+1; neighbourOffsets[5] = width+1; neighbourOffsets[6] = width-1; neighbourOffsets[7] = -width-1; uint straightCost = (uint)Mathf.RoundToInt(nodeSize*Int3.Precision); // Diagonals normally cost sqrt(2) (approx 1.41) times more uint diagonalCost = uniformEdgeCosts ? straightCost : (uint)Mathf.RoundToInt(nodeSize*Mathf.Sqrt(2F)*Int3.Precision); neighbourCosts[0] = straightCost; neighbourCosts[1] = straightCost; neighbourCosts[2] = straightCost; neighbourCosts[3] = straightCost; neighbourCosts[4] = diagonalCost; neighbourCosts[5] = diagonalCost; neighbourCosts[6] = diagonalCost; neighbourCosts[7] = diagonalCost; /* Z * | * | * * 6 2 5 * \ | / * -- 3 - X - 1 ----- X * / | \ * 7 0 4 * * | * | */ neighbourXOffsets[0] = 0; neighbourXOffsets[1] = 1; neighbourXOffsets[2] = 0; neighbourXOffsets[3] = -1; neighbourXOffsets[4] = 1; neighbourXOffsets[5] = 1; neighbourXOffsets[6] = -1; neighbourXOffsets[7] = -1; neighbourZOffsets[0] = -1; neighbourZOffsets[1] = 0; neighbourZOffsets[2] = 1; neighbourZOffsets[3] = 0; neighbourZOffsets[4] = -1; neighbourZOffsets[5] = 1; neighbourZOffsets[6] = 1; neighbourZOffsets[7] = -1; } protected override IEnumerable<Progress> ScanInternal () { if (nodeSize <= 0) { yield break; } // Make sure the matrix is up to date UpdateTransform(); if (width > 1024 || depth > 1024) { Debug.LogError("One of the grid's sides is longer than 1024 nodes"); yield break; } SetUpOffsetsAndCosts(); // Set a global reference to this graph so that nodes can find it GridNode.SetGridGraph((int)graphIndex, this); yield return new Progress(0.05f, "Creating nodes"); // Create all nodes nodes = new GridNode[width*depth]; for (int z = 0; z < depth; z++) { for (int x = 0; x < width; x++) { var index = z*width+x; var node = nodes[index] = new GridNode(active); node.GraphIndex = graphIndex; node.NodeInGridIndex = index; } } // Create and initialize the collision class if (collision == null) { collision = new GraphCollision(); } collision.Initialize(transform, nodeSize); int progressCounter = 0; const int YieldEveryNNodes = 1000; for (int z = 0; z < depth; z++) { // Yield with a progress value at most every N nodes if (progressCounter >= YieldEveryNNodes) { progressCounter = 0; yield return new Progress(Mathf.Lerp(0.1f, 0.7f, z/(float)depth), "Calculating positions"); } progressCounter += width; for (int x = 0; x < width; x++) { // Updates the position of the node // and a bunch of other things RecalculateCell(x, z); } } progressCounter = 0; for (int z = 0; z < depth; z++) { // Yield with a progress value at most every N nodes if (progressCounter >= YieldEveryNNodes) { progressCounter = 0; yield return new Progress(Mathf.Lerp(0.7f, 0.9f, z/(float)depth), "Calculating connections"); } progressCounter += width; for (int x = 0; x < width; x++) { // Recalculate connections to other nodes CalculateConnections(x, z); } } yield return new Progress(0.95f, "Calculating erosion"); // Apply erosion ErodeWalkableArea(); } /// <summary> /// Updates position, walkability and penalty for the node. /// Assumes that collision.Initialize (...) has been called before this function /// /// Deprecated: Use RecalculateCell instead which works both for grid graphs and layered grid graphs. /// </summary> [System.Obsolete("Use RecalculateCell instead which works both for grid graphs and layered grid graphs")] public virtual void UpdateNodePositionCollision (GridNode node, int x, int z, bool resetPenalty = true) { RecalculateCell(x, z, resetPenalty, false); } /// <summary> /// Recalculates single node in the graph. /// /// For a layered grid graph this will recalculate all nodes at a specific (x,z) cell in the grid. /// For grid graphs this will simply recalculate the single node at those coordinates. /// /// Note: This must only be called when it is safe to update nodes. /// For example when scanning the graph or during a graph update. /// /// Note: This will not recalculate any connections as this method is often run for several adjacent nodes at a time. /// After you have recalculated all the nodes you will have to recalculate the connections for the changed nodes /// as well as their neighbours. /// See: CalculateConnections /// </summary> /// <param name="x">X coordinate of the cell</param> /// <param name="z">Z coordinate of the cell</param> /// <param name="resetPenalties">If true, the penalty of the nodes will be reset to the initial value as if the graph had just been scanned /// (this excludes texture data however which is only done when scanning the graph).</param> /// <param name="resetTags">If true, the tag will be reset to zero (the default tag).</param> public virtual void RecalculateCell (int x, int z, bool resetPenalties = true, bool resetTags = true) { var node = nodes[z*width + x]; // Set the node's initial position with a y-offset of zero node.position = GraphPointToWorld(x, z, 0); RaycastHit hit; bool walkable; // Calculate the actual position using physics raycasting (if enabled) // walkable will be set to false if no ground was found (unless that setting has been disabled) Vector3 position = collision.CheckHeight((Vector3)node.position, out hit, out walkable); node.position = (Int3)position; if (resetPenalties) { node.Penalty = initialPenalty; // Calculate a penalty based on the y coordinate of the node if (penaltyPosition) { node.Penalty += (uint)Mathf.RoundToInt((node.position.y-penaltyPositionOffset)*penaltyPositionFactor); } } if (resetTags) { node.Tag = 0; } // Check if the node is on a slope steeper than permitted if (walkable && useRaycastNormal && collision.heightCheck) { if (hit.normal != Vector3.zero) { // Take the dot product to find out the cosinus of the angle it has (faster than Vector3.Angle) float angle = Vector3.Dot(hit.normal.normalized, collision.up); // Add penalty based on normal if (penaltyAngle && resetPenalties) { node.Penalty += (uint)Mathf.RoundToInt((1F-Mathf.Pow(angle, penaltyAnglePower))*penaltyAngleFactor); } // Cosinus of the max slope float cosAngle = Mathf.Cos(maxSlope*Mathf.Deg2Rad); // Check if the ground is flat enough to stand on if (angle < cosAngle) { walkable = false; } } } // If the walkable flag has already been set to false, there is no point in checking for it again // Check for obstacles node.Walkable = walkable && collision.Check((Vector3)node.position); // Store walkability before erosion is applied. Used for graph updates node.WalkableErosion = node.Walkable; } /// <summary> /// True if the node has any blocked connections. /// For 4 and 8 neighbours the 4 axis aligned connections will be checked. /// For 6 neighbours all 6 neighbours will be checked. /// /// Internal method used for erosion. /// </summary> protected virtual bool ErosionAnyFalseConnections (GraphNode baseNode) { var node = baseNode as GridNode; if (neighbours == NumNeighbours.Six) { // Check the 6 hexagonal connections for (int i = 0; i < 6; i++) { if (!HasNodeConnection(node, hexagonNeighbourIndices[i])) { return true; } } } else { // Check the four axis aligned connections for (int i = 0; i < 4; i++) { if (!HasNodeConnection(node, i)) { return true; } } } return false; } /// <summary>Internal method used for erosion</summary> void ErodeNode (GraphNode node) { if (node.Walkable && ErosionAnyFalseConnections(node)) { node.Walkable = false; } } /// <summary>Internal method used for erosion</summary> void ErodeNodeWithTagsInit (GraphNode node) { if (node.Walkable && ErosionAnyFalseConnections(node)) { node.Tag = (uint)erosionFirstTag; } else { node.Tag = 0; } } /// <summary>Internal method used for erosion</summary> void ErodeNodeWithTags (GraphNode node, int iteration) { var gnode = node as GridNodeBase; if (gnode.Walkable && gnode.Tag >= erosionFirstTag && gnode.Tag < erosionFirstTag + iteration) { if (neighbours == NumNeighbours.Six) { // Check the 6 hexagonal connections for (int i = 0; i < 6; i++) { var other = gnode.GetNeighbourAlongDirection(hexagonNeighbourIndices[i]); if (other != null) { uint tag = other.Tag; if (tag > erosionFirstTag + iteration || tag < erosionFirstTag) { other.Tag = (uint)(erosionFirstTag+iteration); } } } } else { // Check the four axis aligned connections for (int i = 0; i < 4; i++) { var other = gnode.GetNeighbourAlongDirection(i); if (other != null) { uint tag = other.Tag; if (tag > erosionFirstTag + iteration || tag < erosionFirstTag) { other.Tag = (uint)(erosionFirstTag+iteration); } } } } } } /// <summary> /// Erodes the walkable area. /// See: <see cref="erodeIterations"/> /// </summary> public virtual void ErodeWalkableArea () { ErodeWalkableArea(0, 0, Width, Depth); } /// <summary> /// Erodes the walkable area. /// /// xmin, zmin (inclusive)\n /// xmax, zmax (exclusive) /// /// See: <see cref="erodeIterations"/> /// </summary> public void ErodeWalkableArea (int xmin, int zmin, int xmax, int zmax) { if (erosionUseTags) { if (erodeIterations+erosionFirstTag > 31) { Debug.LogError("Too few tags available for "+erodeIterations+" erode iterations and starting with tag " + erosionFirstTag + " (erodeIterations+erosionFirstTag > 31)", active); return; } if (erosionFirstTag <= 0) { Debug.LogError("First erosion tag must be greater or equal to 1", active); return; } } if (erodeIterations == 0) return; // Get all nodes inside the rectangle var rect = new IntRect(xmin, zmin, xmax - 1, zmax - 1); var nodesInRect = GetNodesInRegion(rect); int nodeCount = nodesInRect.Count; for (int it = 0; it < erodeIterations; it++) { if (erosionUseTags) { if (it == 0) { for (int i = 0; i < nodeCount; i++) { ErodeNodeWithTagsInit(nodesInRect[i]); } } else { for (int i = 0; i < nodeCount; i++) { ErodeNodeWithTags(nodesInRect[i], it); } } } else { // Loop through all nodes and mark as unwalkble the nodes which // have at least one blocked connection to another node for (int i = 0; i < nodeCount; i++) { ErodeNode(nodesInRect[i]); } for (int i = 0; i < nodeCount; i++) { CalculateConnections(nodesInRect[i] as GridNodeBase); } } } // Return the list to the pool Pathfinding.Util.ListPool<GraphNode>.Release(ref nodesInRect); } /// <summary> /// Returns true if a connection between the adjacent nodes n1 and n2 is valid. /// Also takes into account if the nodes are walkable. /// /// This method may be overriden if you want to customize what connections are valid. /// It must however hold that IsValidConnection(a,b) == IsValidConnection(b,a). /// /// This is used for calculating the connections when the graph is scanned or updated. /// /// See: CalculateConnections /// </summary> public virtual bool IsValidConnection (GridNodeBase node1, GridNodeBase node2) { if (!node1.Walkable || !node2.Walkable) { return false; } if (maxClimb <= 0 || collision.use2D) return true; if (transform.onlyTranslational) { // Common case optimization. // If the transformation is only translational, that is if the graph is not rotated or transformed // in any other way than changing its center. Then we can use this simplified code. // This code is hot when scanning so it does have an impact. return System.Math.Abs(node1.position.y - node2.position.y) <= maxClimb*Int3.Precision; } else { var p1 = (Vector3)node1.position; var p2 = (Vector3)node2.position; var up = transform.WorldUpAtGraphPosition(p1); return System.Math.Abs(Vector3.Dot(up, p1) - Vector3.Dot(up, p2)) <= maxClimb; } } /// <summary> /// Calculates the grid connections for a cell as well as its neighbours. /// This is a useful utility function if you want to modify the walkability of a single node in the graph. /// /// <code> /// AstarPath.active.AddWorkItem(ctx => { /// var grid = AstarPath.active.data.gridGraph; /// int x = 5; /// int z = 7; /// /// // Mark a single node as unwalkable /// grid.GetNode(x, z).Walkable = false; /// /// // Recalculate the connections for that node as well as its neighbours /// grid.CalculateConnectionsForCellAndNeighbours(x, z); /// }); /// </code> /// </summary> public void CalculateConnectionsForCellAndNeighbours (int x, int z) { CalculateConnections(x, z); for (int i = 0; i < 8; i++) { int nx = x + neighbourXOffsets[i]; int nz = z + neighbourZOffsets[i]; CalculateConnections(nx, nz); } } /// <summary> /// Calculates the grid connections for a single node. /// Deprecated: Use the instance function instead /// </summary> [System.Obsolete("Use the instance function instead")] public static void CalculateConnections (GridNode node) { (AstarData.GetGraph(node) as GridGraph).CalculateConnections((GridNodeBase)node); } /// <summary> /// Calculates the grid connections for a single node. /// Convenience function, it's slightly faster to use CalculateConnections(int,int) /// but that will only show when calculating for a large number of nodes. /// This function will also work for both grid graphs and layered grid graphs. /// </summary> public virtual void CalculateConnections (GridNodeBase node) { int index = node.NodeInGridIndex; int x = index % width; int z = index / width; CalculateConnections(x, z); } /// <summary> /// Calculates the grid connections for a single node. /// Deprecated: Use CalculateConnections(x,z) or CalculateConnections(node) instead /// </summary> [System.Obsolete("Use CalculateConnections(x,z) or CalculateConnections(node) instead")] public virtual void CalculateConnections (int x, int z, GridNode node) { CalculateConnections(x, z); } /// <summary> /// Calculates the grid connections for a single node. /// Note that to ensure that connections are completely up to date after updating a node you /// have to calculate the connections for both the changed node and its neighbours. /// /// In a layered grid graph, this will recalculate the connections for all nodes /// in the (x,z) cell (it may have multiple layers of nodes). /// /// See: CalculateConnections(GridNodeBase) /// </summary> public virtual void CalculateConnections (int x, int z) { var node = nodes[z*width + x]; // All connections are disabled if the node is not walkable if (!node.Walkable) { // Reset all connections // This makes the node have NO connections to any neighbour nodes node.ResetConnectionsInternal(); return; } // Internal index of where in the graph the node is int index = node.NodeInGridIndex; if (neighbours == NumNeighbours.Four || neighbours == NumNeighbours.Eight) { // Bitpacked connections // bit 0 is set if connection 0 is enabled // bit 1 is set if connection 1 is enabled etc. int conns = 0; // Loop through axis aligned neighbours (down, right, up, left) or (-Z, +X, +Z, -X) for (int i = 0; i < 4; i++) { int nx = x + neighbourXOffsets[i]; int nz = z + neighbourZOffsets[i]; // Check if the new position is inside the grid // Bitwise AND (&) is measurably faster than && // (not much, but this code is hot) if (nx >= 0 & nz >= 0 & nx < width & nz < depth) { var other = nodes[index+neighbourOffsets[i]]; if (IsValidConnection(node, other)) { // Enable connection i conns |= 1 << i; } } } // Bitpacked diagonal connections int diagConns = 0; // Add in the diagonal connections if (neighbours == NumNeighbours.Eight) { if (cutCorners) { for (int i = 0; i < 4; i++) { // If at least one axis aligned connection // is adjacent to this diagonal, then we can add a connection. // Bitshifting is a lot faster than calling node.HasConnectionInDirection. // We need to check if connection i and i+1 are enabled // but i+1 may overflow 4 and in that case need to be wrapped around // (so 3+1 = 4 goes to 0). We do that by checking both connection i+1 // and i+1-4 at the same time. Either i+1 or i+1-4 will be in the range // from 0 to 4 (exclusive) if (((conns >> i | conns >> (i+1) | conns >> (i+1-4)) & 1) != 0) { int directionIndex = i+4; int nx = x + neighbourXOffsets[directionIndex]; int nz = z + neighbourZOffsets[directionIndex]; if (nx >= 0 & nz >= 0 & nx < width & nz < depth) { GridNode other = nodes[index+neighbourOffsets[directionIndex]]; if (IsValidConnection(node, other)) { diagConns |= 1 << directionIndex; } } } } } else { for (int i = 0; i < 4; i++) { // If exactly 2 axis aligned connections is adjacent to this connection // then we can add the connection // We don't need to check if it is out of bounds because if both of // the other neighbours are inside the bounds this one must be too if ((conns >> i & 1) != 0 && ((conns >> (i+1) | conns >> (i+1-4)) & 1) != 0) { GridNode other = nodes[index+neighbourOffsets[i+4]]; if (IsValidConnection(node, other)) { diagConns |= 1 << (i+4); } } } } } // Set all connections at the same time node.SetAllConnectionInternal(conns | diagConns); } else { // Hexagon layout // Reset all connections // This makes the node have NO connections to any neighbour nodes node.ResetConnectionsInternal(); // Loop through all possible neighbours and try to connect to them for (int j = 0; j < hexagonNeighbourIndices.Length; j++) { var i = hexagonNeighbourIndices[j]; int nx = x + neighbourXOffsets[i]; int nz = z + neighbourZOffsets[i]; if (nx >= 0 & nz >= 0 & nx < width & nz < depth) { var other = nodes[index+neighbourOffsets[i]]; node.SetConnectionInternal(i, IsValidConnection(node, other)); } } } } public override void OnDrawGizmos (RetainedGizmos gizmos, bool drawNodes) { using (var helper = gizmos.GetSingleFrameGizmoHelper(active)) { // The width and depth fields might not be up to date, so recalculate // them from the #unclampedSize field int w, d; float s; CalculateDimensions(out w, out d, out s); var bounds = new Bounds(); bounds.SetMinMax(Vector3.zero, new Vector3(w, 0, d)); var trans = CalculateTransform(); helper.builder.DrawWireCube(trans, bounds, Color.white); int nodeCount = nodes != null ? nodes.Length : -1; if (drawNodes && width*depth*LayerCount != nodeCount) { var color = new Color(1, 1, 1, 0.2f); for (int z = 0; z < d; z++) { helper.builder.DrawLine(trans.Transform(new Vector3(0, 0, z)), trans.Transform(new Vector3(w, 0, z)), color); } for (int x = 0; x < w; x++) { helper.builder.DrawLine(trans.Transform(new Vector3(x, 0, 0)), trans.Transform(new Vector3(x, 0, d)), color); } } } if (!drawNodes) { return; } // Loop through chunks of size chunkWidth*chunkWidth and create a gizmo mesh for each of those chunks. // This is done because rebuilding the gizmo mesh (such as when using Unity Gizmos) every frame is pretty slow // for large graphs. However just checking if any mesh needs to be updated is relatively fast. So we just store // a hash together with the mesh and rebuild the mesh when necessary. const int chunkWidth = 32; GridNodeBase[] allNodes = ArrayPool<GridNodeBase>.Claim(chunkWidth*chunkWidth*LayerCount); for (int cx = width/chunkWidth; cx >= 0; cx--) { for (int cz = depth/chunkWidth; cz >= 0; cz--) { Profiler.BeginSample("Hash"); var allNodesCount = GetNodesInRegion(new IntRect(cx*chunkWidth, cz*chunkWidth, (cx+1)*chunkWidth - 1, (cz+1)*chunkWidth - 1), allNodes); var hasher = new RetainedGizmos.Hasher(active); hasher.AddHash(showMeshOutline ? 1 : 0); hasher.AddHash(showMeshSurface ? 1 : 0); hasher.AddHash(showNodeConnections ? 1 : 0); for (int i = 0; i < allNodesCount; i++) { hasher.HashNode(allNodes[i]); } Profiler.EndSample(); if (!gizmos.Draw(hasher)) { Profiler.BeginSample("Rebuild Retained Gizmo Chunk"); using (var helper = gizmos.GetGizmoHelper(active, hasher)) { if (showNodeConnections) { for (int i = 0; i < allNodesCount; i++) { // Don't bother drawing unwalkable nodes if (allNodes[i].Walkable) { helper.DrawConnections(allNodes[i]); } } } if (showMeshSurface || showMeshOutline) CreateNavmeshSurfaceVisualization(allNodes, allNodesCount, helper); } Profiler.EndSample(); } } } ArrayPool<GridNodeBase>.Release(ref allNodes); if (active.showUnwalkableNodes) DrawUnwalkableNodes(nodeSize * 0.3f); } /// <summary> /// Draw the surface as well as an outline of the grid graph. /// The nodes will be drawn as squares (or hexagons when using <see cref="neighbours"/> = Six). /// </summary> void CreateNavmeshSurfaceVisualization (GridNodeBase[] nodes, int nodeCount, GraphGizmoHelper helper) { // Count the number of nodes that we will render int walkable = 0; for (int i = 0; i < nodeCount; i++) { if (nodes[i].Walkable) walkable++; } var neighbourIndices = neighbours == NumNeighbours.Six ? hexagonNeighbourIndices : new [] { 0, 1, 2, 3 }; var offsetMultiplier = neighbours == NumNeighbours.Six ? 0.333333f : 0.5f; // 2 for a square-ish grid, 4 for a hexagonal grid. var trianglesPerNode = neighbourIndices.Length-2; var verticesPerNode = 3*trianglesPerNode; // Get arrays that have room for all vertices/colors (the array might be larger) var vertices = ArrayPool<Vector3>.Claim(walkable*verticesPerNode); var colors = ArrayPool<Color>.Claim(walkable*verticesPerNode); int baseIndex = 0; for (int i = 0; i < nodeCount; i++) { var node = nodes[i]; if (!node.Walkable) continue; var nodeColor = helper.NodeColor(node); // Don't bother drawing transparent nodes if (nodeColor.a <= 0.001f) continue; for (int dIndex = 0; dIndex < neighbourIndices.Length; dIndex++) { // For neighbours != Six // n2 -- n3 // | | // n -- n1 // // n = this node var d = neighbourIndices[dIndex]; var nextD = neighbourIndices[(dIndex + 1) % neighbourIndices.Length]; GridNodeBase n1, n2, n3 = null; n1 = node.GetNeighbourAlongDirection(d); if (n1 != null && neighbours != NumNeighbours.Six) { n3 = n1.GetNeighbourAlongDirection(nextD); } n2 = node.GetNeighbourAlongDirection(nextD); if (n2 != null && n3 == null && neighbours != NumNeighbours.Six) { n3 = n2.GetNeighbourAlongDirection(d); } // Position in graph space of the vertex Vector3 p = new Vector3(node.XCoordinateInGrid + 0.5f, 0, node.ZCoordinateInGrid + 0.5f); // Offset along diagonal to get the correct XZ coordinates p.x += (neighbourXOffsets[d] + neighbourXOffsets[nextD]) * offsetMultiplier; p.z += (neighbourZOffsets[d] + neighbourZOffsets[nextD]) * offsetMultiplier; // Interpolate the y coordinate of the vertex so that the mesh will be seamless (except in some very rare edge cases) p.y += transform.InverseTransform((Vector3)node.position).y; if (n1 != null) p.y += transform.InverseTransform((Vector3)n1.position).y; if (n2 != null) p.y += transform.InverseTransform((Vector3)n2.position).y; if (n3 != null) p.y += transform.InverseTransform((Vector3)n3.position).y; p.y /= (1f + (n1 != null ? 1f : 0f) + (n2 != null ? 1f : 0f) + (n3 != null ? 1f : 0f)); // Convert the point from graph space to world space // This handles things like rotations, scale other transformations p = transform.Transform(p); vertices[baseIndex + dIndex] = p; } if (neighbours == NumNeighbours.Six) { // Form the two middle triangles vertices[baseIndex + 6] = vertices[baseIndex + 0]; vertices[baseIndex + 7] = vertices[baseIndex + 2]; vertices[baseIndex + 8] = vertices[baseIndex + 3]; vertices[baseIndex + 9] = vertices[baseIndex + 0]; vertices[baseIndex + 10] = vertices[baseIndex + 3]; vertices[baseIndex + 11] = vertices[baseIndex + 5]; } else { // Form the last triangle vertices[baseIndex + 4] = vertices[baseIndex + 0]; vertices[baseIndex + 5] = vertices[baseIndex + 2]; } // Set all colors for the node for (int j = 0; j < verticesPerNode; j++) { colors[baseIndex + j] = nodeColor; } // Draw the outline of the node for (int j = 0; j < neighbourIndices.Length; j++) { var other = node.GetNeighbourAlongDirection(neighbourIndices[(j+1) % neighbourIndices.Length]); // Just a tie breaker to make sure we don't draw the line twice. // Using NodeInGridIndex instead of NodeIndex to make the gizmos deterministic for a given grid layout. // This is important because if the graph would be re-scanned and only a small part of it would change // then most chunks would be cached by the gizmo system, but the node indices may have changed and // if NodeIndex was used then we might get incorrect gizmos at the borders between chunks. if (other == null || (showMeshOutline && node.NodeInGridIndex < other.NodeInGridIndex)) { helper.builder.DrawLine(vertices[baseIndex + j], vertices[baseIndex + (j+1) % neighbourIndices.Length], other == null ? Color.black : nodeColor); } } baseIndex += verticesPerNode; } if (showMeshSurface) helper.DrawTriangles(vertices, colors, baseIndex*trianglesPerNode/verticesPerNode); ArrayPool<Vector3>.Release(ref vertices); ArrayPool<Color>.Release(ref colors); } /// <summary> /// A rect with all nodes that the bounds could touch. /// This correctly handles rotated graphs and other transformations. /// The returned rect is guaranteed to not extend outside the graph bounds. /// </summary> protected IntRect GetRectFromBounds (Bounds bounds) { // Take the bounds and transform it using the matrix // Then convert that to a rectangle which contains // all nodes that might be inside the bounds bounds = transform.InverseTransform(bounds); Vector3 min = bounds.min; Vector3 max = bounds.max; int minX = Mathf.RoundToInt(min.x-0.5F); int maxX = Mathf.RoundToInt(max.x-0.5F); int minZ = Mathf.RoundToInt(min.z-0.5F); int maxZ = Mathf.RoundToInt(max.z-0.5F); var originalRect = new IntRect(minX, minZ, maxX, maxZ); // Rect which covers the whole grid var gridRect = new IntRect(0, 0, width-1, depth-1); // Clamp the rect to the grid return IntRect.Intersection(originalRect, gridRect); } /// <summary>Deprecated: This method has been renamed to GetNodesInRegion</summary> [System.Obsolete("This method has been renamed to GetNodesInRegion", true)] public List<GraphNode> GetNodesInArea (Bounds bounds) { return GetNodesInRegion(bounds); } /// <summary>Deprecated: This method has been renamed to GetNodesInRegion</summary> [System.Obsolete("This method has been renamed to GetNodesInRegion", true)] public List<GraphNode> GetNodesInArea (GraphUpdateShape shape) { return GetNodesInRegion(shape); } /// <summary>Deprecated: This method has been renamed to GetNodesInRegion</summary> [System.Obsolete("This method has been renamed to GetNodesInRegion", true)] public List<GraphNode> GetNodesInArea (Bounds bounds, GraphUpdateShape shape) { return GetNodesInRegion(bounds, shape); } /// <summary> /// All nodes inside the bounding box. /// Note: Be nice to the garbage collector and pool the list when you are done with it (optional) /// See: Pathfinding.Util.ListPool /// /// See: GetNodesInRegion(GraphUpdateShape) /// </summary> public List<GraphNode> GetNodesInRegion (Bounds bounds) { return GetNodesInRegion(bounds, null); } /// <summary> /// All nodes inside the shape. /// Note: Be nice to the garbage collector and pool the list when you are done with it (optional) /// See: Pathfinding.Util.ListPool /// /// See: GetNodesInRegion(Bounds) /// </summary> public List<GraphNode> GetNodesInRegion (GraphUpdateShape shape) { return GetNodesInRegion(shape.GetBounds(), shape); } /// <summary> /// All nodes inside the shape or if null, the bounding box. /// If a shape is supplied, it is assumed to be contained inside the bounding box. /// See: GraphUpdateShape.GetBounds /// </summary> protected virtual List<GraphNode> GetNodesInRegion (Bounds bounds, GraphUpdateShape shape) { var rect = GetRectFromBounds(bounds); if (nodes == null || !rect.IsValid() || nodes.Length != width*depth) { return ListPool<GraphNode>.Claim(); } // Get a buffer we can use var inArea = ListPool<GraphNode>.Claim(rect.Width*rect.Height); // Loop through all nodes in the rectangle for (int x = rect.xmin; x <= rect.xmax; x++) { for (int z = rect.ymin; z <= rect.ymax; z++) { int index = z*width+x; GraphNode node = nodes[index]; // If it is contained in the bounds (and optionally the shape) // then add it to the buffer if (bounds.Contains((Vector3)node.position) && (shape == null || shape.Contains((Vector3)node.position))) { inArea.Add(node); } } } return inArea; } /// <summary>Get all nodes in a rectangle.</summary> /// <param name="rect">Region in which to return nodes. It will be clamped to the grid.</param> public virtual List<GraphNode> GetNodesInRegion (IntRect rect) { // Clamp the rect to the grid // Rect which covers the whole grid var gridRect = new IntRect(0, 0, width-1, depth-1); rect = IntRect.Intersection(rect, gridRect); if (nodes == null || !rect.IsValid() || nodes.Length != width*depth) return ListPool<GraphNode>.Claim(0); // Get a buffer we can use var inArea = ListPool<GraphNode>.Claim(rect.Width*rect.Height); for (int z = rect.ymin; z <= rect.ymax; z++) { var zw = z*Width; for (int x = rect.xmin; x <= rect.xmax; x++) { inArea.Add(nodes[zw + x]); } } return inArea; } /// <summary> /// Get all nodes in a rectangle. /// Returns: The number of nodes written to the buffer. /// /// Note: This method is much faster than GetNodesInRegion(IntRect) which returns a list because this method can make use of the highly optimized /// System.Array.Copy method. /// </summary> /// <param name="rect">Region in which to return nodes. It will be clamped to the grid.</param> /// <param name="buffer">Buffer in which the nodes will be stored. Should be at least as large as the number of nodes that can exist in that region.</param> public virtual int GetNodesInRegion (IntRect rect, GridNodeBase[] buffer) { // Clamp the rect to the grid // Rect which covers the whole grid var gridRect = new IntRect(0, 0, width-1, depth-1); rect = IntRect.Intersection(rect, gridRect); if (nodes == null || !rect.IsValid() || nodes.Length != width*depth) return 0; if (buffer.Length < rect.Width*rect.Height) throw new System.ArgumentException("Buffer is too small"); int counter = 0; for (int z = rect.ymin; z <= rect.ymax; z++, counter += rect.Width) { System.Array.Copy(nodes, z*Width + rect.xmin, buffer, counter, rect.Width); } return counter; } /// <summary> /// Node in the specified cell. /// Returns null if the coordinate is outside the grid. /// /// <code> /// var gg = AstarPath.active.data.gridGraph; /// int x = 5; /// int z = 8; /// GridNodeBase node = gg.GetNode(x, z); /// </code> /// /// If you know the coordinate is inside the grid and you are looking to maximize performance then you /// can look up the node in the internal array directly which is slightly faster. /// See: <see cref="nodes"/> /// </summary> public virtual GridNodeBase GetNode (int x, int z) { if (x < 0 || z < 0 || x >= width || z >= depth) return null; return nodes[x + z*width]; } GraphUpdateThreading IUpdatableGraph.CanUpdateAsync (GraphUpdateObject o) { return GraphUpdateThreading.UnityThread; } void IUpdatableGraph.UpdateAreaInit (GraphUpdateObject o) {} void IUpdatableGraph.UpdateAreaPost (GraphUpdateObject o) {} protected void CalculateAffectedRegions (GraphUpdateObject o, out IntRect originalRect, out IntRect affectRect, out IntRect physicsRect, out bool willChangeWalkability, out int erosion) { // Take the bounds and transform it using the matrix // Then convert that to a rectangle which contains // all nodes that might be inside the bounds var bounds = transform.InverseTransform(o.bounds); Vector3 min = bounds.min; Vector3 max = bounds.max; int minX = Mathf.RoundToInt(min.x-0.5F); int maxX = Mathf.RoundToInt(max.x-0.5F); int minZ = Mathf.RoundToInt(min.z-0.5F); int maxZ = Mathf.RoundToInt(max.z-0.5F); //We now have coordinates in local space (i.e 1 unit = 1 node) originalRect = new IntRect(minX, minZ, maxX, maxZ); affectRect = originalRect; physicsRect = originalRect; erosion = o.updateErosion ? erodeIterations : 0; willChangeWalkability = o.updatePhysics || o.modifyWalkability; //Calculate the largest bounding box which might be affected if (o.updatePhysics && !o.modifyWalkability) { // Add the collision.diameter margin for physics calls if (collision.collisionCheck) { Vector3 margin = new Vector3(collision.diameter, 0, collision.diameter)*0.5F; min -= margin*1.02F;//0.02 safety margin, physics is rarely very accurate max += margin*1.02F; physicsRect = new IntRect( Mathf.RoundToInt(min.x-0.5F), Mathf.RoundToInt(min.z-0.5F), Mathf.RoundToInt(max.x-0.5F), Mathf.RoundToInt(max.z-0.5F) ); affectRect = IntRect.Union(physicsRect, affectRect); } } if (willChangeWalkability || erosion > 0) { // Add affect radius for erosion. +1 for updating connectivity info at the border affectRect = affectRect.Expand(erosion + 1); } } /// <summary>Internal function to update an area of the graph</summary> void IUpdatableGraph.UpdateArea (GraphUpdateObject o) { if (nodes == null || nodes.Length != width*depth) { Debug.LogWarning("The Grid Graph is not scanned, cannot update area"); //Not scanned return; } IntRect originalRect, affectRect, physicsRect; bool willChangeWalkability; int erosion; CalculateAffectedRegions(o, out originalRect, out affectRect, out physicsRect, out willChangeWalkability, out erosion); #if ASTARDEBUG var debugMatrix = transform * Matrix4x4.TRS(new Vector3(0.5f, 0, 0.5f), Quaternion.identity, Vector3.one); originalRect.DebugDraw(debugMatrix, Color.red); #endif // Rect which covers the whole grid var gridRect = new IntRect(0, 0, width-1, depth-1); // Clamp the rect to the grid bounds IntRect clampedRect = IntRect.Intersection(affectRect, gridRect); // Mark nodes that might be changed for (int z = clampedRect.ymin; z <= clampedRect.ymax; z++) { for (int x = clampedRect.xmin; x <= clampedRect.xmax; x++) { o.WillUpdateNode(nodes[z*width+x]); } } // Update Physics if (o.updatePhysics && !o.modifyWalkability) { collision.Initialize(transform, nodeSize); clampedRect = IntRect.Intersection(physicsRect, gridRect); for (int z = clampedRect.ymin; z <= clampedRect.ymax; z++) { for (int x = clampedRect.xmin; x <= clampedRect.xmax; x++) { RecalculateCell(x, z, o.resetPenaltyOnPhysics, false); } } } //Apply GUO clampedRect = IntRect.Intersection(originalRect, gridRect); for (int z = clampedRect.ymin; z <= clampedRect.ymax; z++) { for (int x = clampedRect.xmin; x <= clampedRect.xmax; x++) { int index = z*width+x; GridNode node = nodes[index]; if (o.bounds.Contains((Vector3)node.position)) { if (willChangeWalkability) { node.Walkable = node.WalkableErosion; o.Apply(node); node.WalkableErosion = node.Walkable; } else { o.Apply(node); } } } } #if ASTARDEBUG physicsRect.DebugDraw(debugMatrix, Color.blue); affectRect.DebugDraw(debugMatrix, Color.black); #endif // Recalculate connections if (willChangeWalkability && erosion == 0) { clampedRect = IntRect.Intersection(affectRect, gridRect); for (int x = clampedRect.xmin; x <= clampedRect.xmax; x++) { for (int z = clampedRect.ymin; z <= clampedRect.ymax; z++) { CalculateConnections(x, z); } } } else if (willChangeWalkability && erosion > 0) { clampedRect = IntRect.Union(originalRect, physicsRect); IntRect erosionRect1 = clampedRect.Expand(erosion); IntRect erosionRect2 = erosionRect1.Expand(erosion); erosionRect1 = IntRect.Intersection(erosionRect1, gridRect); erosionRect2 = IntRect.Intersection(erosionRect2, gridRect); #if ASTARDEBUG erosionRect1.DebugDraw(debugMatrix, Color.magenta); erosionRect2.DebugDraw(debugMatrix, Color.cyan); #endif // * all nodes inside clampedRect might have had their walkability changed // * all nodes inside erosionRect1 might get affected by erosion from clampedRect and erosionRect2 // * all nodes inside erosionRect2 (but outside erosionRect1) will be reset to previous walkability // after calculation since their erosion might not be correctly calculated (nodes outside erosionRect2 might have an effect) for (int x = erosionRect2.xmin; x <= erosionRect2.xmax; x++) { for (int z = erosionRect2.ymin; z <= erosionRect2.ymax; z++) { int index = z*width+x; GridNode node = nodes[index]; bool tmp = node.Walkable; node.Walkable = node.WalkableErosion; if (!erosionRect1.Contains(x, z)) { //Save the border's walkabilty data (will be reset later) node.TmpWalkable = tmp; } } } for (int x = erosionRect2.xmin; x <= erosionRect2.xmax; x++) { for (int z = erosionRect2.ymin; z <= erosionRect2.ymax; z++) { CalculateConnections(x, z); } } // Erode the walkable area ErodeWalkableArea(erosionRect2.xmin, erosionRect2.ymin, erosionRect2.xmax+1, erosionRect2.ymax+1); for (int x = erosionRect2.xmin; x <= erosionRect2.xmax; x++) { for (int z = erosionRect2.ymin; z <= erosionRect2.ymax; z++) { if (erosionRect1.Contains(x, z)) continue; int index = z*width+x; GridNode node = nodes[index]; //Restore temporarily stored data node.Walkable = node.TmpWalkable; } } // Recalculate connections of all affected nodes for (int x = erosionRect2.xmin; x <= erosionRect2.xmax; x++) { for (int z = erosionRect2.ymin; z <= erosionRect2.ymax; z++) { CalculateConnections(x, z); } } } } /// <summary> /// Returns if node is connected to it's neighbour in the specified direction. /// This will also return true if <see cref="neighbours"/> = NumNeighbours.Four, the direction is diagonal and one can move through one of the adjacent nodes /// to the targeted node. /// /// See: neighbourOffsets /// </summary> public bool CheckConnection (GridNode node, int dir) { if (neighbours == NumNeighbours.Eight || neighbours == NumNeighbours.Six || dir < 4) { return HasNodeConnection(node, dir); } else { int dir1 = (dir-4-1) & 0x3; int dir2 = (dir-4+1) & 0x3; if (!HasNodeConnection(node, dir1) || !HasNodeConnection(node, dir2)) { return false; } else { GridNode n1 = nodes[node.NodeInGridIndex+neighbourOffsets[dir1]]; GridNode n2 = nodes[node.NodeInGridIndex+neighbourOffsets[dir2]]; if (!n1.Walkable || !n2.Walkable) { return false; } if (!HasNodeConnection(n2, dir1) || !HasNodeConnection(n1, dir2)) { return false; } } return true; } } protected override void SerializeExtraInfo (GraphSerializationContext ctx) { if (nodes == null) { ctx.writer.Write(-1); return; } ctx.writer.Write(nodes.Length); for (int i = 0; i < nodes.Length; i++) { nodes[i].SerializeNode(ctx); } } protected override void DeserializeExtraInfo (GraphSerializationContext ctx) { int count = ctx.reader.ReadInt32(); if (count == -1) { nodes = null; return; } nodes = new GridNode[count]; for (int i = 0; i < nodes.Length; i++) { nodes[i] = new GridNode(active); nodes[i].DeserializeNode(ctx); } } protected override void DeserializeSettingsCompatibility (GraphSerializationContext ctx) { base.DeserializeSettingsCompatibility(ctx); aspectRatio = ctx.reader.ReadSingle(); rotation = ctx.DeserializeVector3(); center = ctx.DeserializeVector3(); unclampedSize = (Vector2)ctx.DeserializeVector3(); nodeSize = ctx.reader.ReadSingle(); collision.DeserializeSettingsCompatibility(ctx); maxClimb = ctx.reader.ReadSingle(); ctx.reader.ReadInt32(); maxSlope = ctx.reader.ReadSingle(); erodeIterations = ctx.reader.ReadInt32(); erosionUseTags = ctx.reader.ReadBoolean(); erosionFirstTag = ctx.reader.ReadInt32(); ctx.reader.ReadBoolean(); // Old field neighbours = (NumNeighbours)ctx.reader.ReadInt32(); cutCorners = ctx.reader.ReadBoolean(); penaltyPosition = ctx.reader.ReadBoolean(); penaltyPositionFactor = ctx.reader.ReadSingle(); penaltyAngle = ctx.reader.ReadBoolean(); penaltyAngleFactor = ctx.reader.ReadSingle(); penaltyAnglePower = ctx.reader.ReadSingle(); isometricAngle = ctx.reader.ReadSingle(); uniformEdgeCosts = ctx.reader.ReadBoolean(); } protected override void PostDeserialization (GraphSerializationContext ctx) { UpdateTransform(); SetUpOffsetsAndCosts(); GridNode.SetGridGraph((int)graphIndex, this); if (nodes == null || nodes.Length == 0) return; if (width*depth != nodes.Length) { Debug.LogError("Node data did not match with bounds data. Probably a change to the bounds/width/depth data was made after scanning the graph just prior to saving it. Nodes will be discarded"); nodes = new GridNode[0]; return; } for (int z = 0; z < depth; z++) { for (int x = 0; x < width; x++) { var node = nodes[z*width+x]; if (node == null) { Debug.LogError("Deserialization Error : Couldn't cast the node to the appropriate type - GridGenerator"); return; } node.NodeInGridIndex = z*width+x; } } } } /// <summary> /// Number of neighbours for a single grid node. /// \since The 'Six' item was added in 3.6.1 /// </summary> public enum NumNeighbours { Four, Eight, Six } }
36.34537
223
0.668535
[ "MIT" ]
BilJose/2D-Game
Assets/AstarPathfindingProject/Generators/GridGenerator.cs
78,506
C#
using System.Net; using System.Threading.Tasks; using VSphere.Models.JsonConvert; namespace VSphere.Services.Inteface { public interface IService { Task<VMConverter> GetVMsAPI(string url, string username, string password); Task<HostConverter> GetHostsAPI(string url, string username, string password); Task<HttpStatusCode> CreateVM(string url, string username, string password, VMPost vmModelConvertered); Task<DataStoreConvert> GetDataStoreAPI(string url, string username, string password); Task<FolderConverter> GetFolderAPI(string url, string username, string password); Task<ResourcePoolConverter> GetResourcePoolAPI(string url, string username, string password); Task<HttpStatusCode> DeleteVMAPI(string url, string username, string password, string name); Task<HttpStatusCode> TurnOnOrTurnOffVMAPI(string url, string username, string password, string name, bool turnOn); byte[] GetFile(string fileName); string PDFGenerator(string html); } }
32.875
122
0.741445
[ "MIT" ]
caioaugusto1/VCenterVMWare
VSphere/Services/Inteface/IService.cs
1,054
C#
using System; namespace SRATS.Utils { public static class NMath { static int FACTMAX; static double PI; static double LOG_2PI; // static double LOG_PI; static public double ZERO = 1.0e-14; static int N; static double B2; static double B4; static double B6; static double B8; static double B10; static double B12; static double B14; static double B16; static double[] nfact; static double[] lognfact; static NMath() { FACTMAX = 20; PI = 3.14159265358979324; // pi LOG_2PI = 1.83787706640934548; // LOG_PI = 1.14472988584940017; // log(pi) N = 8; //static double B0 = 1; //static double B1 = (-1.0 / 2.0); B2 = (1.0 / 6.0); B4 = (-1.0 / 30.0); B6 = (1.0 / 42.0); B8 = (-1.0 / 30.0); B10 = (5.0 / 66.0); B12 = (-691.0 / 2730.0); B14 = (7.0 / 6.0); B16 = (-3617.0 / 510.0); nfact = new double[FACTMAX + 1]; nfact[0] = 1.0; // 0 nfact[1] = 1.0; // 1 nfact[2] = 2.0; // 2 nfact[3] = 6.0; // 3 nfact[4] = 24.0; // 4 nfact[5] = 120.0; // 5 nfact[6] = 720.0; // 6 nfact[7] = 5040.0; // 7 nfact[8] = 40320.0; // 8 nfact[9] = 362880.0; // 9 nfact[10] = 3628800.0; // 10 nfact[11] = 39916800.0; // 11 nfact[12] = 479001600.0; // 12 nfact[13] = 6227020800.0; // 13 nfact[14] = 87178291200.0; // 14 nfact[15] = 1307674368000.0; // 15 nfact[16] = 20922789888000.0; // 16 nfact[17] = 355687428096000.0; // 17 nfact[18] = 6402373705728000.0; // 18 nfact[19] = 121645100408832000.0; // 19 nfact[20] = 2432902008176640000.0; // 20 lognfact = new double[FACTMAX + 1]; lognfact[0] = 0.0; lognfact[1] = 0.0; lognfact[2] = 0.6931471805599453; lognfact[3] = 1.791759469228055; lognfact[4] = 3.1780538303479458; lognfact[5] = 4.787491742782046; lognfact[6] = 6.579251212010101; lognfact[7] = 8.525161361065415; lognfact[8] = 10.60460290274525; lognfact[9] = 12.801827480081469; lognfact[10] = 15.104412573075516; lognfact[11] = 17.502307845873887; lognfact[12] = 19.987214495661885; lognfact[13] = 22.552163853123425; lognfact[14] = 25.19122118273868; lognfact[15] = 27.89927138384089; lognfact[16] = 30.671860106080672; lognfact[17] = 33.50507345013689; lognfact[18] = 36.39544520803305; lognfact[19] = 39.339884187199495; lognfact[20] = 42.335616460753485; } static public double Exp(double x) { return Math.Exp(x); } static public double Abs(double x) { return Math.Abs(x); } static public double Log(double x) { return Math.Log(x); } static public double Sqrt(double x) { return Math.Sqrt(x); } static public double Pow(double x, double y) { return Math.Pow(x, y); } static public double Max(params double[] x) { double maxx = x[0]; for (int i = 1; i < x.Length; i++) { if (maxx < x[i]) { maxx = x[i]; } } return maxx; } static public double Min(params double[] x) { double minx = x[0]; for (int i = 1; i < x.Length; i++) { if (minx > x[i]) { minx = x[i]; } } return minx; } static public double Expm1(double x) { if (Math.Abs(x) < 1.0e-5) { return x + 0.5 * x * x; } else { return Exp(x) - 1.0; } } static public double Lgamma(double x) { double v, w; v = 1; while (x < N) { v *= x; x++; } w = 1 / (x * x); return ((((((((B16 / (16 * 15)) * w + (B14 / (14 * 13))) * w + (B12 / (12 * 11))) * w + (B10 / (10 * 9))) * w + (B8 / (8 * 7))) * w + (B6 / (6 * 5))) * w + (B4 / (4 * 3))) * w + (B2 / (2 * 1))) / x + 0.5 * LOG_2PI - Log(v) - x + (x - 0.5) * Log(x); } static public double Tgamma(double x) { if (x < 0) { return PI / (Math.Sin(PI * x) * Exp(Lgamma(1 - x))); } return Exp(Lgamma(x)); } static public double Psi(double x) { double v, w; v = 0; while (x < N) { v += 1 / x; x++; } w = 1 / (x * x); v += ((((((((B16 / 16) * w + (B14 / 14)) * w + (B12 / 12)) * w + (B10 / 10)) * w + (B8 / 8)) * w + (B6 / 6)) * w + (B4 / 4)) * w + (B2 / 2)) * w + 0.5 / x; return Log(x) - v; } static public double Polygamma(int n, double x) { int k; double t, u, v, w; u = 1; for (k = 1 - n; k < 0; k++) u *= k; v = 0; while (x < N) { v += 1 / Math.Pow(x, n + 1); x++; } w = x * x; t = (((((((B16 * (n + 15.0) * (n + 14) / (16 * 15 * w) + B14) * (n + 13.0) * (n + 12) / (14 * 13 * w) + B12) * (n + 11.0) * (n + 10) / (12 * 11 * w) + B10) * (n + 9.0) * (n + 8) / (10 * 9 * w) + B8) * (n + 7.0) * (n + 6) / (8 * 7 * w) + B6) * (n + 5.0) * (n + 4) / (6 * 5 * w) + B4) * (n + 3.0) * (n + 2) / (4 * 3 * w) + B2) * (n + 1.0) * n / (2 * 1 * w) + 0.5 * n / x + 1; return u * (t / Math.Pow(x, n) + n * v); } static public double Tfact(int s) { if (s <= FACTMAX) { return nfact[s]; } else { return Exp(Lgamma(1.0 + s)); } } static public double Lfact(int s) { if (s <= FACTMAX) { return lognfact[s]; } else { return Lgamma(1.0 + s); } } /// error functions static public double Derf(double x) { int k; double w, t, y; double[] a = { 5.958930743e-11, -1.13739022964e-9, 1.466005199839e-8, -1.635035446196e-7, 1.6461004480962e-6, -1.492559551950604e-5, 1.2055331122299265e-4, -8.548326981129666e-4, 0.00522397762482322257, -0.0268661706450773342, 0.11283791670954881569, -0.37612638903183748117, 1.12837916709551257377, 2.372510631e-11, -4.5493253732e-10, 5.90362766598e-9, -6.642090827576e-8, 6.7595634268133e-7, -6.21188515924e-6, 5.10388300970969e-5, -3.7015410692956173e-4, 0.00233307631218880978, -0.0125498847718219221, 0.05657061146827041994, -0.2137966477645600658, 0.84270079294971486929, 9.49905026e-12, -1.8310229805e-10, 2.39463074e-9, -2.721444369609e-8, 2.8045522331686e-7, -2.61830022482897e-6, 2.195455056768781e-5, -1.6358986921372656e-4, 0.00107052153564110318, -0.00608284718113590151, 0.02986978465246258244, -0.13055593046562267625, 0.67493323603965504676, 3.82722073e-12, -7.421598602e-11, 9.793057408e-10, -1.126008898854e-8, 1.1775134830784e-7, -1.1199275838265e-6, 9.62023443095201e-6, -7.404402135070773e-5, 5.0689993654144881e-4, -0.00307553051439272889, 0.01668977892553165586, -0.08548534594781312114, 0.56909076642393639985, 1.55296588e-12, -3.032205868e-11, 4.0424830707e-10, -4.71135111493e-9, 5.011915876293e-8, -4.8722516178974e-7, 4.30683284629395e-6, -3.445026145385764e-5, 2.4879276133931664e-4, -0.00162940941748079288, 0.00988786373932350462, -0.05962426839442303805, 0.49766113250947636708 }; double[] b = { -2.9734388465e-10, 2.69776334046e-9, -6.40788827665e-9, -1.6678201321e-8, -2.1854388148686e-7, 2.66246030457984e-6, 1.612722157047886e-5, -2.5616361025506629e-4, 1.5380842432375365e-4, 0.00815533022524927908, -0.01402283663896319337, -0.19746892495383021487, 0.71511720328842845913, -1.951073787e-11, -3.2302692214e-10, 5.22461866919e-9, 3.42940918551e-9, -3.5772874310272e-7, 1.9999935792654e-7, 2.687044575042908e-5, -1.1843240273775776e-4, -8.0991728956032271e-4, 0.00661062970502241174, 0.00909530922354827295, -0.2016007277849101314, 0.51169696718727644908, 3.147682272e-11, -4.8465972408e-10, 6.3675740242e-10, 3.377623323271e-8, -1.5451139637086e-7, -2.03340624738438e-6, 1.947204525295057e-5, 2.854147231653228e-5, -0.00101565063152200272, 0.00271187003520095655, 0.02328095035422810727, -0.16725021123116877197, 0.32490054966649436974, 2.31936337e-11, -6.303206648e-11, -2.64888267434e-9, 2.050708040581e-8, 1.1371857327578e-7, -2.11211337219663e-6, 3.68797328322935e-6, 9.823686253424796e-5, -6.5860243990455368e-4, -7.5285814895230877e-4, 0.02585434424202960464, -0.11637092784486193258, 0.18267336775296612024, -3.67789363e-12, 2.0876046746e-10, -1.93319027226e-9, -4.35953392472e-9, 1.8006992266137e-7, -7.8441223763969e-7, -6.75407647949153e-6, 8.428418334440096e-5, -1.7604388937031815e-4, -0.0023972961143507161, 0.0206412902387602297, -0.06905562880005864105, 0.09084526782065478489 }; w = x < 0 ? -x : x; if (w < 2.2) { t = w * w; k = (int)t; t -= k; k *= 13; y = ((((((((((((a[k] * t + a[k + 1]) * t + a[k + 2]) * t + a[k + 3]) * t + a[k + 4]) * t + a[k + 5]) * t + a[k + 6]) * t + a[k + 7]) * t + a[k + 8]) * t + a[k + 9]) * t + a[k + 10]) * t + a[k + 11]) * t + a[k + 12]) * w; } else if (w < 6.9) { k = (int)w; t = w - k; k = 13 * (k - 2); y = (((((((((((b[k] * t + b[k + 1]) * t + b[k + 2]) * t + b[k + 3]) * t + b[k + 4]) * t + b[k + 5]) * t + b[k + 6]) * t + b[k + 7]) * t + b[k + 8]) * t + b[k + 9]) * t + b[k + 10]) * t + b[k + 11]) * t + b[k + 12]; y *= y; y *= y; y *= y; y = 1 - y * y; } else { y = 1; } return x < 0 ? -y : y; } static public double Derfc(double x) { double t, u, y; t = 3.97886080735226 / (Math.Abs(x) + 3.97886080735226); u = t - 0.5; y = (((((((((0.00127109764952614092 * u + 1.19314022838340944e-4) * u - 0.003963850973605135) * u - 8.70779635317295828e-4) * u + 0.00773672528313526668) * u + 0.00383335126264887303) * u - 0.0127223813782122755) * u - 0.0133823644533460069) * u + 0.0161315329733252248) * u + 0.0390976845588484035) * u + 0.00249367200053503304; y = ((((((((((((y * u - 0.0838864557023001992) * u - 0.119463959964325415) * u + 0.0166207924969367356) * u + 0.357524274449531043) * u + 0.805276408752910567) * u + 1.18902982909273333) * u + 1.37040217682338167) * u + 1.31314653831023098) * u + 1.07925515155856677) * u + 0.774368199119538609) * u + 0.490165080585318424) * u + 0.275374741597376782) * t * Exp(-x * x); return x < 0 ? 2 - y : y; } static public double Dierfc(double y) { double s, t, u, w, x, z; z = y; if (y > 1) { z = 2 - y; } w = 0.916461398268964 - Log(z); u = Sqrt(w); s = (Log(u) + 0.488826640273108) / w; t = 1 / (u + 0.231729200323405); x = u * (1 - s * (s * 0.124610454613712 + 0.5)) - ((((-0.0728846765585675 * t + 0.269999308670029) * t + 0.150689047360223) * t + 0.116065025341614) * t + 0.499999303439796) * t; t = 3.97886080735226 / (x + 3.97886080735226); u = t - 0.5; s = (((((((((0.00112648096188977922 * u + 1.05739299623423047e-4) * u - 0.00351287146129100025) * u - 7.71708358954120939e-4) * u + 0.00685649426074558612) * u + 0.00339721910367775861) * u - 0.011274916933250487) * u - 0.0118598117047771104) * u + 0.0142961988697898018) * u + 0.0346494207789099922) * u + 0.00220995927012179067; s = ((((((((((((s * u - 0.0743424357241784861) * u - 0.105872177941595488) * u + 0.0147297938331485121) * u + 0.316847638520135944) * u + 0.713657635868730364) * u + 1.05375024970847138) * u + 1.21448730779995237) * u + 1.16374581931560831) * u + 0.956464974744799006) * u + 0.686265948274097816) * u + 0.434397492331430115) * u + 0.244044510593190935) * t - z * Exp(x * x - 0.120782237635245222); x += s * (x * s + 1); if (y > 1) { x = -x; } return x; } // private for gamma static public double P_gamma(double a, double x, double loggamma_a) { int k; double result, term, previous; if (x >= 1 + a) return 1 - Q_gamma(a, x, loggamma_a); if (x == 0) return 0; result = term = NMath.Exp(a * NMath.Log(x) - x - loggamma_a) / a; for (k = 1; k < 1000; k++) { term *= x / (a + k); previous = result; result += term; if (result == previous) return result; } return result; } static public double Q_gamma(double a, double x, double loggamma_a) { int k; double result, w, temp, previous; double la, lb; la = 1; lb = 1 + x - a; if (x < 1 + a) return 1 - P_gamma(a, x, loggamma_a); w = NMath.Exp(a * NMath.Log(x) - x - loggamma_a); result = w / lb; for (k = 2; k < 1000; k++) { temp = ((k - 1 - a) * (lb - la) + (k + x) * lb) / k; la = lb; lb = temp; w *= (k - 1 - a) / k; temp = w / (la * lb); previous = result; result += temp; if (result == previous) return result; } return result; } /////// integral public delegate double Integrand(double x); public static void GaussWeights(double[] x, double[] w, double eps) { int n = x.Length; int i, l, m; double p0, p1, p2; double q0, q1, q2; double tmp, dt; switch (n) { case 1: x[0] = 0.0; w[0] = 2.0; return; case 2: x[0] = Sqrt(1.0 / 3.0); w[0] = 1.0; x[1] = -x[0]; w[1] = w[0]; return; case 3: x[0] = Sqrt(0.6); w[0] = 5.0 / 9.0; x[1] = 0.0; w[1] = 8.0 / 9.0; x[2] = -x[0]; w[2] = w[0]; return; } m = n / 2; for (i = 0; i < m; i++) { tmp = Math.Cos((i + 1.0 - 1.0 / 4.0) / (n + 1.0 / 2.0) * PI); do { p1 = tmp; p2 = (3.0 * tmp * tmp - 1.0) / 2.0; q1 = 1.0; q2 = 3.0 * tmp; for (l = 3; l <= n; l++) { p0 = p1; p1 = p2; p2 = ((2.0 * l - 1) * tmp * p1 - (l - 1) * p0) / l; q0 = q1; q1 = q2; q2 = ((2.0 * l - 1) * (tmp * q1 + p1) - (l - 1) * q0) / l; } dt = p2 / q2; tmp = tmp - dt; } while (Math.Abs(dt) > Math.Abs(tmp) * eps); x[i] = tmp; w[i] = 2.0 / (n * p1 * q2); } if (n % 2 != 0) { x[n / 2] = 0.0; tmp = (double) n; for (i = 1; i <= m; i++) tmp = tmp * (0.5 - i) / i; w[n / 2] = 2.0 / (tmp * tmp); } for (i = 0; i < m; i++) { x[n - 1 - i] = -x[i]; w[n - 1 - i] = w[i]; } return; } public static double Tapezoid(Integrand func, double a, double b, double eps, int maxiter = 200) { int i, k; int n = 1; double s, h, t, tn = 0.0; h = b - a; t = h * (func(a) + func(b)) / 2.0; for (k = 1; k <= maxiter; k++) { n = 2 * n; h = h / 2.0; s = 0.0; for (i = 1; i <= n - 1; i += 2) { s += func(a + i * h); } tn = t / 2.0 + h * s; if (Math.Abs(tn - t) / Math.Abs(t) < eps) { break; } t = tn; } return tn; } public static double Deintde(Integrand f, double a, double b, out double err, double eps) { /* ---- adjustable parameter ---- */ const int mmax = 256; const double efs = 0.1, hoff = 8.5; double pi2 = 2 * Math.Atan(1.0); /* ------------------------------ */ int m; double res, epsln, epsh, h0, ehp, ehm, epst, ba, ir, h, iback, irback, t, ep, em, xw, xa, wg, fa, fb, errt, errh = 0.0, errd; epsln = 1 - Log(efs * eps); epsh = Sqrt(efs * eps); h0 = hoff / epsln; ehp = Exp(h0); ehm = 1 / ehp; epst = Exp(-ehm * epsln); ba = b - a; ir = f((a + b) * 0.5) * (ba * 0.25); res = ir * (2 * pi2); err = Math.Abs(res) * epst; h = 2 * h0; m = 1; do { iback = res; irback = ir; t = h * 0.5; do { em = Exp(t); ep = pi2 * em; em = pi2 / em; do { xw = 1 / (1 + Exp(ep - em)); xa = ba * xw; wg = xa * (1 - xw); fa = f(a + xa) * wg; fb = f(b - xa) * wg; ir += fa + fb; res += (fa + fb) * (ep + em); errt = (Math.Abs(fa) + Math.Abs(fb)) * (ep + em); if (m == 1) err += errt * epst; ep *= ehp; em *= ehm; } while (errt > err || xw > epsh); t += h; } while (t < h0); if (m == 1) { errh = (err / epst) * epsh * h0; errd = 1 + 2 * errh; } else { errd = h * (Math.Abs(res - 2 * iback) + 4 * Math.Abs(ir - 2 * irback)); } h *= 0.5; m *= 2; } while (errd > errh && m < mmax); res *= h; if (errd > errh) { err = -errd * m; } else { err = errh * epsh * m / (2 * efs); } return res; } //public static double deintde(Integrand f, double a, double b, Sci.DVector param, // out double err, double eps = Double.Epsilon) //{ // f.setParam(param); // return deintde(f, a, b, out err, eps); //} public static double Deintdei(Integrand f, double a, out double err, double eps) { /* ---- adjustable parameter ---- */ const int mmax = 256; const double efs = 0.1, hoff = 11.0; double pi4 = Math.Atan(1.0); /* ------------------------------ */ int m; double res, epsln, epsh, h0, ehp, ehm, epst, ir, h, iback, irback, t, ep, em, xp, xm, fp, fm, errt, errh = 0.0, errd; epsln = 1 - Log(efs * eps); epsh = Sqrt(efs * eps); h0 = hoff / epsln; ehp = Exp(h0); ehm = 1 / ehp; epst = Exp(-ehm * epsln); ir = f(a + 1); res = ir * (2 * pi4); err = Math.Abs(res) * epst; h = 2 * h0; m = 1; do { iback = res; irback = ir; t = h * 0.5; do { em = Exp(t); ep = pi4 * em; em = pi4 / em; do { xp = Exp(ep - em); xm = 1 / xp; fp = f(a + xp) * xp; fm = f(a + xm) * xm; ir += fp + fm; res += (fp + fm) * (ep + em); errt = (Math.Abs(fp) + Math.Abs(fm)) * (ep + em); if (m == 1) err += errt * epst; ep *= ehp; em *= ehm; } while (errt > err || xm > epsh); t += h; } while (t < h0); if (m == 1) { errh = (err / epst) * epsh * h0; errd = 1 + 2 * errh; } else { errd = h * (Math.Abs(res - 2 * iback) + 4 * Math.Abs(ir - 2 * irback)); } h *= 0.5; m *= 2; } while (errd > errh && m < mmax); res *= h; if (errd > errh) { err = -errd * m; } else { err = errh * epsh * m / (2 * efs); } return res; } //public static double deintdei(Integrand f, double a, Sci.DVector param, // out double err, double eps = Double.Epsilon) //{ // f.setParam(param); // return deintdei(f, a, out err, eps); //} public static double Gauss(Integrand f, double a, double b, double[] x, double[] w) { int n = x.Length; double t1 = (b - a) / 2.0; double t2 = (b + a) / 2.0; double sum = 0.0; for (int i = 0; i < n; i++) { sum += w[i] * f(t1 * x[i] + t2); } sum *= t1; return sum; } //public static double gauss(Integrand f, double a, double b, // Sci.DVector param, double[] x, double[] w) //{ // f.setParam(param); // return gauss(f, a, b, x, w); //} } }
33.657754
104
0.378138
[ "MIT" ]
SwReliab/SRATS2017
SRATS2017/Utils/NMath.cs
25,176
C#
using System; using DynamicMVC.ApplicationMetadataLibrary.Interfaces; using DynamicMVC.Shared.Enums; using DynamicMVC.Shared.Interfaces; using ReflectionLibrary.Enums; namespace DynamicMVC.ApplicationMetadataLibrary.Strategies.SimpleTypeParsers { /// <summary> /// Simple Type Parser for Nullable UInt64 datatype /// </summary> public class SimpleTypeUInt64NullableParser : ISimpleTypeParser { public Type GetSimpleType() { return typeof(ulong?); } public dynamic Parse(string value) { return (ulong?)ulong.Parse(value); } public SimpleTypeEnum SimpleTypeEnum() { return ReflectionLibrary.Enums.SimpleTypeEnum.UInt64Nullable; } } }
25.566667
76
0.672751
[ "Apache-2.0" ]
PrecisionWebTechnologies/DynamicMVC
DynamicMVC.ApplicationMetadataLibrary/Strategies/SimpleTypeParsers/SimpleTypeUInt64NullableParser.cs
767
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Newtonsoft.Json; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.ROS.Transform; using Aliyun.Acs.ROS.Transform.V20190910; namespace Aliyun.Acs.ROS.Model.V20190910 { public class ListStackResourcesRequest : RpcAcsRequest<ListStackResourcesResponse> { public ListStackResourcesRequest() : base("ROS", "2019-09-10", "ListStackResources", "ros", "openAPI") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Endpoint.endpointRegionalType, null); } Method = MethodType.POST; } private string stackId; public string StackId { get { return stackId; } set { stackId = value; DictionaryUtil.Add(QueryParameters, "StackId", value); } } public override bool CheckShowJsonItemName() { return false; } public override ListStackResourcesResponse GetResponse(UnmarshallerContext unmarshallerContext) { return ListStackResourcesResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
32.4
134
0.699735
[ "Apache-2.0" ]
chys0404/aliyun-openapi-net-sdk
aliyun-net-sdk-ros/ROS/Model/V20190910/ListStackResourcesRequest.cs
2,268
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.Tasks; using Microsoft.DotNet.Maestro.Client; using Microsoft.DotNet.Maestro.Client.Models; using Microsoft.Extensions.Logging; namespace Microsoft.DotNet.DarcLib { public class Remote : IRemote { private readonly IMaestroApi _barClient; private readonly GitFileManager _fileManager; private readonly IGitRepo _gitClient; private readonly ILogger _logger; public Remote(DarcSettings settings, ILogger logger) { ValidateSettings(settings); _logger = logger; if (settings.GitType == GitRepoType.GitHub) { _gitClient = new GitHubClient(settings.PersonalAccessToken, _logger); } else if (settings.GitType == GitRepoType.AzureDevOps) { _gitClient = new AzureDevOpsClient(settings.PersonalAccessToken, _logger); } // Only initialize the file manager if we have a git client, which excludes "None" if (_gitClient != null) { _fileManager = new GitFileManager(_gitClient, _logger); } // Initialize the bar client if there is a password if (!string.IsNullOrEmpty(settings.BuildAssetRegistryPassword)) { if (!string.IsNullOrEmpty(settings.BuildAssetRegistryBaseUri)) { _barClient = ApiFactory.GetAuthenticated( settings.BuildAssetRegistryBaseUri, settings.BuildAssetRegistryPassword); } else { _barClient = ApiFactory.GetAuthenticated(settings.BuildAssetRegistryPassword); } } } /// <summary> /// Retrieve a list of default channel associations. /// </summary> /// <param name="repository">Optionally filter by repository</param> /// <param name="branch">Optionally filter by branch</param> /// <param name="channel">Optionally filter by channel</param> /// <returns>Collection of default channels.</returns> public async Task<IEnumerable<DefaultChannel>> GetDefaultChannelsAsync( string repository = null, string branch = null, string channel = null) { CheckForValidBarClient(); IList<DefaultChannel> channels = await _barClient.DefaultChannels.ListAsync(repository, branch); if (!string.IsNullOrEmpty(channel)) { return channels.Where(c => c.Channel.Name.Equals(channel, StringComparison.OrdinalIgnoreCase)); } // Filter away based on channel info. return channels; } /// <summary> /// Adds a default channel association. /// </summary> /// <param name="repository">Repository receiving the default association</param> /// <param name="branch">Branch receiving the default association</param> /// <param name="channel">Name of channel that builds of 'repository' on 'branch' should automatically be applied to.</param> /// <returns>Async task.</returns> public async Task AddDefaultChannelAsync(string repository, string branch, string channel) { CheckForValidBarClient(); // Look up channel to translate to channel id. Channel foundChannel = (await _barClient.Channels.GetAsync()) .Where(c => c.Name.Equals(channel, StringComparison.OrdinalIgnoreCase)) .SingleOrDefault(); if (foundChannel == null) { throw new ArgumentException($"Channel {channel} is not a valid channel."); } var defaultChannelsData = new PostData { Branch = branch, Repository = repository, ChannelId = foundChannel.Id.Value }; await _barClient.DefaultChannels.CreateAsync(defaultChannelsData); } /// <summary> /// Removes a default channel based on the specified criteria /// </summary> /// <param name="repository">Repository having a default association</param> /// <param name="branch">Branch having a default association</param> /// <param name="channel">Name of channel that builds of 'repository' on 'branch' are being applied to.</param> /// <returns>Async task</returns> public async Task DeleteDefaultChannelAsync(string repository, string branch, string channel) { CheckForValidBarClient(); DefaultChannel existingDefaultChannel = (await GetDefaultChannelsAsync(repository, branch, channel)).SingleOrDefault(); if (existingDefaultChannel != null) { // Find the existing default channel. If none found then nothing to do. await _barClient.DefaultChannels.DeleteAsync(existingDefaultChannel.Id.Value); } } /// <summary> /// Creates a new channel in the Build Asset Registry /// </summary> /// <param name="name">Name of channel</param> /// <param name="classification">Classification of the channel</param> /// <returns>Newly created channel</returns> public async Task<Channel> CreateChannelAsync(string name, string classification) { CheckForValidBarClient(); return await _barClient.Channels.CreateChannelAsync(name, classification); } /// <summary> /// Deletes a channel from the Build Asset Registry /// </summary> /// <param name="name">Name of channel</param> /// <returns>Channel just deleted</returns> public async Task<Channel> DeleteChannelAsync(int id) { CheckForValidBarClient(); return await _barClient.Channels.DeleteChannelAsync(id); } public async Task<IEnumerable<Subscription>> GetSubscriptionsAsync( string sourceRepo = null, string targetRepo = null, int? channelId = null) { CheckForValidBarClient(); return await _barClient.Subscriptions.GetAllSubscriptionsAsync(sourceRepo, targetRepo, channelId); } public async Task<Subscription> GetSubscriptionAsync(string subscriptionId) { CheckForValidBarClient(); if (!Guid.TryParse(subscriptionId, out Guid subscriptionGuid)) { throw new ArgumentException($"Subscription id '{subscriptionId}' is not a valid guid."); } return await _barClient.Subscriptions.GetSubscriptionAsync(subscriptionGuid); } /// <summary> /// Create a new subscription /// </summary> /// <param name="channelName">Name of source channel</param> /// <param name="sourceRepo">URL of source repository</param> /// <param name="targetRepo">URL of target repository where updates should be made</param> /// <param name="targetBranch">Name of target branch where updates should be made</param> /// <param name="updateFrequency">Frequency of updates, can be 'none', 'everyBuild' or 'everyDay'</param> /// <param name="mergePolicies"> /// Dictionary of merge policies. Each merge policy is a name of a policy with an associated blob /// of metadata /// </param> /// <returns>Newly created subscription, if successful</returns> public async Task<Subscription> CreateSubscriptionAsync( string channelName, string sourceRepo, string targetRepo, string targetBranch, string updateFrequency, List<MergePolicy> mergePolicies) { CheckForValidBarClient(); var subscriptionData = new SubscriptionData { ChannelName = channelName, SourceRepository = sourceRepo, TargetRepository = targetRepo, TargetBranch = targetBranch, Policy = new SubscriptionPolicy { UpdateFrequency = updateFrequency, MergePolicies = mergePolicies } }; return await _barClient.Subscriptions.CreateAsync(subscriptionData); } /// <summary> /// Delete a subscription by id /// </summary> /// <param name="subscriptionId">Id of subscription to delete</param> /// <returns>Information on deleted subscriptio</returns> public async Task<Subscription> DeleteSubscriptionAsync(string subscriptionId) { CheckForValidBarClient(); if (!Guid.TryParse(subscriptionId, out Guid subscriptionGuid)) { throw new ArgumentException($"Subscription id '{subscriptionId}' is not a valid guid."); } return await _barClient.Subscriptions.DeleteSubscriptionAsync(subscriptionGuid); } /// <summary> /// Retrieve subscription history. /// </summary> /// <param name="subscriptionId">ID of subscription</param> /// <returns>Subscription history</returns> public async Task<IEnumerable<SubscriptionHistoryItem>> GetSubscriptionHistoryAsync(string subscriptionId) { CheckForValidBarClient(); if (!Guid.TryParse(subscriptionId, out Guid subscriptionGuid)) { throw new ArgumentException($"Subscription id '{subscriptionId}' is not a valid guid."); } return await _barClient.Subscriptions.GetSubscriptionHistoryAsync(subscriptionGuid); } /// <summary> /// Retry subscription operation. /// </summary> /// <param name="subscriptionId">Id of subscription that should have its action retried</param> /// <param name="actionIdentifier">Timestamp of the action that needs to be retried</param> public Task RetrySubscriptionUpdateAsync(string subscriptionId, long actionIdentifier) { CheckForValidBarClient(); if (!Guid.TryParse(subscriptionId, out Guid subscriptionGuid)) { throw new ArgumentException($"Subscription id '{subscriptionId}' is not a valid guid."); } return _barClient.Subscriptions.RetrySubscriptionActionAsyncAsync(subscriptionGuid, actionIdentifier); } public async Task CreateNewBranchAsync(string repoUri, string baseBranch, string newBranch) { await _gitClient.CreateBranchAsync(repoUri, newBranch, baseBranch); } public async Task<IList<Check>> GetPullRequestChecksAsync(string pullRequestUrl) { CheckForValidGitClient(); _logger.LogInformation($"Getting status checks for pull request '{pullRequestUrl}'..."); IList<Check> checks = await _gitClient.GetPullRequestChecksAsync(pullRequestUrl); return checks; } public async Task<IEnumerable<int>> SearchPullRequestsAsync( string repoUri, string pullRequestBranch, PrStatus status, string keyword = null, string author = null) { CheckForValidGitClient(); return await _gitClient.SearchPullRequestsAsync(repoUri, pullRequestBranch, status, keyword, author); } public Task<IList<Commit>> GetPullRequestCommitsAsync(string pullRequestUrl) { return _gitClient.GetPullRequestCommitsAsync(pullRequestUrl); } public Task CreateOrUpdatePullRequestStatusCommentAsync(string pullRequestUrl, string message) { CheckForValidGitClient(); return _gitClient.CreateOrUpdatePullRequestDarcCommentAsync(pullRequestUrl, message); } public async Task<PrStatus> GetPullRequestStatusAsync(string pullRequestUrl) { CheckForValidGitClient(); _logger.LogInformation($"Getting the status of pull request '{pullRequestUrl}'..."); PrStatus status = await _gitClient.GetPullRequestStatusAsync(pullRequestUrl); _logger.LogInformation($"Status of pull request '{pullRequestUrl}' is '{status}'"); return status; } public Task UpdatePullRequestAsync(string pullRequestUri, PullRequest pullRequest) { return _gitClient.UpdatePullRequestAsync(pullRequestUri, pullRequest); } public async Task MergePullRequestAsync(string pullRequestUrl, MergePullRequestParameters parameters) { CheckForValidGitClient(); _logger.LogInformation($"Merging pull request '{pullRequestUrl}'..."); await _gitClient.MergePullRequestAsync(pullRequestUrl, parameters ?? new MergePullRequestParameters()); _logger.LogInformation($"Merging pull request '{pullRequestUrl}' succeeded!"); } public async Task<List<DependencyDetail>> GetRequiredUpdatesAsync( string repoUri, string branch, string sourceCommit, IEnumerable<AssetData> assets) { CheckForValidGitClient(); _logger.LogInformation($"Check if repo '{repoUri}' and branch '{branch}' needs updates..."); var toUpdate = new List<DependencyDetail>(); IEnumerable<DependencyDetail> dependencyDetails = await _fileManager.ParseVersionDetailsXmlAsync(repoUri, branch); Dictionary<string, DependencyDetail> dependencies = dependencyDetails.ToDictionary(d => d.Name); foreach (AssetData asset in assets) { if (!dependencies.TryGetValue(asset.Name, out DependencyDetail dependency)) { _logger.LogInformation($"No dependency found for updated asset '{asset.Name}'"); continue; } dependency.Version = asset.Version; dependency.Commit = sourceCommit; toUpdate.Add(dependency); } _logger.LogInformation( $"Getting dependencies which need to be updated in repo '{repoUri}' and branch '{branch}' succeeded!"); return toUpdate; } public async Task CommitUpdatesAsync( string repoUri, string branch, List<DependencyDetail> itemsToUpdate, string message) { CheckForValidGitClient(); GitFileContentContainer fileContainer = await _fileManager.UpdateDependencyFiles(itemsToUpdate, repoUri, branch); List<GitFile> filesToCommit = fileContainer.GetFilesToCommit(); // If we are updating the arcade sdk we need to update the eng/common files as well DependencyDetail arcadeItem = itemsToUpdate.FirstOrDefault( i => string.Equals(i.Name, "Microsoft.DotNet.Arcade.Sdk", StringComparison.OrdinalIgnoreCase)); if (arcadeItem != null && repoUri != arcadeItem.RepoUri) { // Files in arcade repository List<GitFile> engCommonFiles = await GetCommonScriptFilesAsync(arcadeItem.RepoUri, arcadeItem.Commit); filesToCommit.AddRange(engCommonFiles); // Files in the target repo string latestCommit = await _gitClient.GetLastCommitShaAsync(_gitClient.GetOwnerAndRepoFromRepoUri(repoUri), branch); List<GitFile> targetEngCommonFiles = await GetCommonScriptFilesAsync(repoUri, latestCommit); foreach (GitFile file in targetEngCommonFiles) { if (!engCommonFiles.Where(f => f.FilePath == file.FilePath).Any()) { file.Operation = GitFileOperation.Delete; filesToCommit.Add(file); } } } await _gitClient.PushFilesAsync(filesToCommit, repoUri, branch, message); } public Task<PullRequest> GetPullRequestAsync(string pullRequestUri) { return _gitClient.GetPullRequestAsync(pullRequestUri); } public Task<string> CreatePullRequestAsync(string repoUri, PullRequest pullRequest) { return _gitClient.CreatePullRequestAsync(repoUri, pullRequest); } /// <summary> /// Retrieve the list of channels from the build asset registry. /// </summary> /// <param name="classification">Optional classification to get</param> /// <returns></returns> public async Task<IEnumerable<Channel>> GetChannelsAsync(string classification = null) { CheckForValidBarClient(); return await _barClient.Channels.GetAsync(classification); } /// <summary> /// Retrieve a specific channel by name. /// </summary> /// <param name="channel">Channel name.</param> /// <returns>Channel or null if not found.</returns> public async Task<Channel> GetChannelAsync(string channel) { CheckForValidBarClient(); return (await _barClient.Channels.GetAsync()).Where(c => c.Name.Equals(channel, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); } /// <summary> /// Retrieve the latest build of a repository on a specific channel. /// </summary> /// <param name="repoUri">URI of repository to obtain a build for.</param> /// <param name="channelId">Channel the build was applied to.</param> /// <returns>Latest build of <paramref name="repoUri"/> on channel <paramref name="channelId"/>, /// or null if there is no latest.</returns> /// <remarks>The build's assets are returned</remarks> public Task<Build> GetLatestBuildAsync(string repoUri, int channelId) { CheckForValidBarClient(); return _barClient.Builds.GetLatestAsync(repository: repoUri, channelId: channelId, loadCollections: true); } public async Task<IEnumerable<DependencyDetail>> GetDependenciesAsync(string repoUri, string branch, string name = null) { CheckForValidGitClient(); return (await _fileManager.ParseVersionDetailsXmlAsync(repoUri, branch)).Where( dependency => string.IsNullOrEmpty(name) || dependency.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); } /// <summary> /// Called prior to operations requiring the BAR. Throws if a bar client isn't available. /// </summary> private void CheckForValidBarClient() { if (_barClient == null) { throw new ArgumentException("Must supply a build asset registry password"); } } /// <summary> /// Called prior to operations requiring the BAR. Throws if a git client isn't available; /// </summary> private void CheckForValidGitClient() { if (_gitClient == null) { throw new ArgumentException("Must supply a valid GitHub/Azure DevOps PAT"); } } private void ValidateSettings(DarcSettings settings) { // Should have a git repo type of AzureDevOps, GitHub, or None. if (settings.GitType == GitRepoType.GitHub || settings.GitType == GitRepoType.AzureDevOps) { // PAT is required for these types. if (string.IsNullOrEmpty(settings.PersonalAccessToken)) { throw new ArgumentException("The personal access token is missing..."); } } else if (settings.GitType != GitRepoType.None) { throw new ArgumentException($"Unexpected git repo type: {settings.GitType}"); } } public async Task<List<GitFile>> GetCommonScriptFilesAsync(string repoUri, string commit) { CheckForValidGitClient(); _logger.LogInformation("Generating commits for script files"); List<GitFile> files = await _gitClient.GetFilesForCommitAsync(repoUri, commit, "eng/common"); _logger.LogInformation("Generating commits for script files succeeded!"); return files; } } }
41.9002
146
0.611042
[ "MIT" ]
AzureMentor/arcade-services
src/Microsoft.DotNet.Darc/src/DarcLib/Actions/Remote.cs
20,992
C#
namespace PostalCodeDistance.NETStandard.Readers { public interface INameTransfer { string Transfer(string name); } }
17.375
49
0.697842
[ "MIT" ]
MeilCli/PostalCodeDistance
PostalCodeDistance.NETStandard/Readers/INameTransfer.cs
141
C#
// ConcurrentStack.cs // // Authors: // Marek Safar <marek.safar@gmail.com> // // Copyright (c) 2008 Jérémie "Garuma" Laval // Copyright (C) 2014 Xamarin Inc (http://www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // #if NET_4_0 using System; using System.Threading; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; namespace System.Collections.Concurrent { [System.Diagnostics.DebuggerDisplay ("Count = {Count}")] [System.Diagnostics.DebuggerTypeProxy (typeof (CollectionDebuggerView<>))] public class ConcurrentStack<T> : IProducerConsumerCollection<T>, IEnumerable<T>, ICollection, IEnumerable { class Node { public T Value = default (T); public Node Next; } Node head; int count; public ConcurrentStack () { } public ConcurrentStack (IEnumerable<T> collection) { if (collection == null) throw new ArgumentNullException ("collection"); foreach (T item in collection) Push (item); } bool IProducerConsumerCollection<T>.TryAdd (T elem) { Push (elem); return true; } public void Push (T item) { Node temp = new Node (); temp.Value = item; do { temp.Next = head; } while (Interlocked.CompareExchange (ref head, temp, temp.Next) != temp.Next); Interlocked.Increment (ref count); } public void PushRange (T[] items) { if (items == null) throw new ArgumentNullException ("items"); PushRange (items, 0, items.Length); } public void PushRange (T[] items, int startIndex, int count) { RangeArgumentsCheck (items, startIndex, count); Node insert = null; Node first = null; for (int i = startIndex; i < count; i++) { Node temp = new Node (); temp.Value = items[i]; temp.Next = insert; insert = temp; if (first == null) first = temp; } do { first.Next = head; } while (Interlocked.CompareExchange (ref head, insert, first.Next) != first.Next); Interlocked.Add (ref count, count); } public bool TryPop (out T result) { Node temp; do { temp = head; // The stak is empty if (temp == null) { result = default (T); return false; } } while (Interlocked.CompareExchange (ref head, temp.Next, temp) != temp); Interlocked.Decrement (ref count); result = temp.Value; return true; } public int TryPopRange (T[] items) { if (items == null) throw new ArgumentNullException ("items"); return TryPopRange (items, 0, items.Length); } public int TryPopRange (T[] items, int startIndex, int count) { RangeArgumentsCheck (items, startIndex, count); Node temp; Node end; do { temp = head; if (temp == null) return 0; end = temp; for (int j = 0; j < count; j++) { end = end.Next; if (end == null) break; } } while (Interlocked.CompareExchange (ref head, end, temp) != temp); int i; for (i = startIndex; i < startIndex + count && temp != null; i++) { items[i] = temp.Value; end = temp; temp = temp.Next; } Interlocked.Add (ref this.count, -(i - startIndex)); return i - startIndex; } public bool TryPeek (out T result) { Node myHead = head; if (myHead == null) { result = default (T); return false; } result = myHead.Value; return true; } public void Clear () { // This is not satisfactory count = 0; head = null; } IEnumerator IEnumerable.GetEnumerator () { return (IEnumerator)InternalGetEnumerator (); } public IEnumerator<T> GetEnumerator () { return InternalGetEnumerator (); } IEnumerator<T> InternalGetEnumerator () { Node my_head = head; if (my_head == null) { yield break; } else { do { yield return my_head.Value; } while ((my_head = my_head.Next) != null); } } void ICollection.CopyTo (Array array, int index) { ICollection ic = new List<T> (this); ic.CopyTo (array, index); } public void CopyTo (T[] array, int index) { if (array == null) throw new ArgumentNullException ("array"); if (index < 0) throw new ArgumentOutOfRangeException ("index"); if (index > array.Length) throw new ArgumentException ("index is equals or greather than array length", "index"); IEnumerator<T> e = InternalGetEnumerator (); int i = index; while (e.MoveNext ()) { if (i == array.Length - index) throw new ArgumentException ("The number of elememts in the collection exceeds the capacity of array", "array"); array[i++] = e.Current; } } bool ICollection.IsSynchronized { get { return false; } } bool IProducerConsumerCollection<T>.TryTake (out T item) { return TryPop (out item); } object ICollection.SyncRoot { get { throw new NotSupportedException (); } } public T[] ToArray () { return new List<T> (this).ToArray (); } public int Count { get { return count; } } public bool IsEmpty { get { return count == 0; } } static void RangeArgumentsCheck (T[] items, int startIndex, int count) { if (items == null) throw new ArgumentNullException ("items"); if (startIndex < 0 || startIndex >= items.Length) throw new ArgumentOutOfRangeException ("startIndex"); if (count < 0) throw new ArgumentOutOfRangeException ("count"); if (startIndex + count > items.Length) throw new ArgumentException ("startIndex + count is greater than the length of items."); } } } #endif
23.477032
117
0.642234
[ "Apache-2.0" ]
eiz/mono
mcs/class/corlib/System.Collections.Concurrent/ConcurrentStack.cs
6,646
C#
//----------Permission开始---------- using System; using YBlog.Core.FrameWork.IServices; using YBlog.Core.FrameWork.IRepository; using YBlog.Core.FrameWork.Entity; namespace YBlog.Core.FrameWork.Services { /// <summary> /// PermissionServices /// </summary> public class PermissionServices : BaseServices<Permission>, IPermissionServices { IPermissionRepository dal; public PermissionServices(IPermissionRepository dal) { this.dal = dal; base.baseDal = dal; } } } //----------Permission结束----------
20.310345
80
0.616299
[ "MIT" ]
yb123speed/YBlog
YBlog.Core.FrameWork/YBlog.Core.FrameWork.Services/work/PermissionServices.cs
597
C#
using System; using System.Collections.Generic; using NueDeck.Scripts.Enums; using NueDeck.Scripts.Managers; using NueExtentions; using UnityEngine; namespace NueDeck.Scripts.Data.Collection { [CreateAssetMenu(fileName = "Card Data",menuName = "Data/Collection/Card",order = 0)] public class CardData : ScriptableObject { [Header("Card Defaults")] public int myID; public ActionTargets myTargets; public bool usableWithoutTarget; public int myManaCost; public string myName; public string MyDescription { get; set; } public Sprite mySprite; public List<CardActionData> actionList; public List<DescriptionData> descriptionDataList; public AudioActionType audioType; public void UpdateDescription() { MyDescription = ""; foreach (var descriptionData in descriptionDataList) { MyDescription += descriptionData.GetDescription(); } } } [Serializable] public class CardActionData { public CardActionType myPlayerActionType; public float value; } [Serializable] public class DescriptionData { [SerializeField]private bool useText = true; [SerializeField]private bool useValue = true; [SerializeField]private string text; [SerializeField]private int defaultValue; [Header("Color")] [SerializeField]private bool useValueColor; [SerializeField]private Color valueColor; [SerializeField]private bool useTextColor; [SerializeField]private Color textColor; [Header("Modifer")] [SerializeField]private bool useModifer; [SerializeField]private StatusType modiferStatus; public string GetDescription() { var str = ""; if (useText) { str += text; if (useTextColor) str = ColorExtentions.ColorString(str,textColor); } if (useValue) { var value = defaultValue; if (useModifer) { var player = CombatManager.Instance.currentAllies[0]; if (player) { var modifer =player.CharacterStats.StatusDict[modiferStatus].StatusValue; value += modifer; if (modifer!= 0) { str += "*"; } } } str += value; if (useValueColor) str = ColorExtentions.ColorString(str,valueColor); } return str; } } }
28.134615
97
0.529733
[ "MIT" ]
Arefnue/UNOG-Fall-Jam
Assets/NueDeck/Scripts/Data/Collection/CardData.cs
2,928
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DamageOnHit : MonoBehaviour { [SerializeField] private int damage = 1; private void OnTriggerEnter(Collider other) { if (other.GetComponent<Enemy>()) { other.GetComponent<Enemy>().TakeDamage(transform, damage); } } }
21.411765
70
0.664835
[ "MIT" ]
RosieMable/TinyGame2_21stOct
BoxBorne/Assets/Scripts/DamageOnHit.cs
366
C#
using System; namespace Composable.Persistence.Common.EventStore { public class EventDuplicateKeyException : Exception { //Todo: Oracle exceptions has property: IsRecoverable. Research what this means and if there is something equivalent for the other providers and how this could be useful to us. public EventDuplicateKeyException(Exception sqlException) : base( @" A duplicate key exception occurred while persisting new events. This is most likely caused by multiple transactions updating the same aggregate and the persistence provider implementation, or database engine, failing to lock appropriately.", sqlException) {} } }
45.6
184
0.75731
[ "Apache-2.0" ]
mlidbom/Composable
src/framework/Composable.CQRS.ExternalDependencies/Persistence/Common/EventStore/EventDuplicateKeyException.cs
684
C#
using System; using BindingsRx.Bindings; using BindingsRx.Converters; using BindingsRx.Filters; using TMPro; using UniRx; using UnityEngine; namespace BindingsRx.TMP { public static class TMP_TextExtensions { public static IDisposable BindTextTo(this TMP_Text input, IReadOnlyReactiveProperty<string> property, params IFilter<string>[] filters) { return GenericBindings.Bind(x => input.text = x, property, filters).AddTo(input); } public static IDisposable BindTextTo(this TMP_Text input, IReactiveProperty<string> property, params IFilter<string>[] filters) { return GenericBindings.Bind(() => input.text, x => input.text = x, property, BindingTypes.OneWay, filters) .AddTo(input); } public static IDisposable BindTextTo(this TMP_Text input, IReactiveProperty<int> property, params IFilter<string>[] filters) { return GenericBindings.Bind(() => input.text, x => input.text = x, property, new TextToIntConverter(), BindingTypes.OneWay, filters).AddTo(input); } public static IDisposable BindTextTo(this TMP_Text input, IReactiveProperty<float> property, params IFilter<string>[] filters) { return GenericBindings.Bind(() => input.text, x => input.text = x, property, new TextToFloatConverter(), BindingTypes.OneWay, filters).AddTo(input); } public static IDisposable BindTextTo(this TMP_Text input, IReactiveProperty<double> property, params IFilter<string>[] filters) { return GenericBindings.Bind(() => input.text, x => input.text = x, property, new TextToDoubleConverter(), BindingTypes.OneWay, filters).AddTo(input); } public static IDisposable BindTextTo(this TMP_Text input, IReactiveProperty<DateTime> property, string dateTimeFormat = "d", params IFilter<string>[] filters) { return GenericBindings.Bind(() => input.text, x => input.text = x, property, new TextToDateConverter(dateTimeFormat), BindingTypes.OneWay, filters).AddTo(input); } public static IDisposable BindTextTo(this TMP_Text input, IReactiveProperty<TimeSpan> property, params IFilter<string>[] filters) { return GenericBindings.Bind(() => input.text, x => input.text = x, property, new TextToTimeSpanConverter(), BindingTypes.OneWay, filters).AddTo(input); } public static IDisposable BindTextTo<T>(this TMP_Text input, IReactiveProperty<T> property, IConverter<string, T> converter, params IFilter<string>[] filters) { return GenericBindings.Bind(() => input.text, x => input.text = x, property, converter, BindingTypes.OneWay, filters).AddTo(input); } public static IDisposable BindTextTo(this TMP_Text input, Func<string> getter, params IFilter<string>[] filters) { return GenericBindings .Bind(() => input.text, x => input.text = x, getter, null, BindingTypes.OneWay, filters).AddTo(input); } public static IDisposable BindTextTo<T>(this TMP_Text input, Func<T> getter, IConverter<string, T> converter, params IFilter<string>[] filters) { return GenericBindings.Bind(() => input.text, x => input.text = x, getter, null, converter, BindingTypes.OneWay, filters).AddTo(input); } public static IDisposable BindFontSizeTo(this TMP_Text input, IReactiveProperty<float> property, params IFilter<float>[] filters) { return GenericBindings .Bind(() => input.fontSize, x => input.fontSize = x, property, BindingTypes.OneWay, filters) .AddTo(input); } public static IDisposable BindFontSizeTo(this TMP_Text input, IReadOnlyReactiveProperty<float> property, params IFilter<float>[] filters) { return GenericBindings.Bind(x => input.fontSize = x, property, filters).AddTo(input); } public static IDisposable BindFontSizeTo(this TMP_Text input, Func<float> getter, params IFilter<float>[] filters) { return GenericBindings.Bind(() => input.fontSize, x => input.fontSize = x, getter, null, BindingTypes.OneWay, filters).AddTo(input); } public static IDisposable BindColorTo(this TMP_Text input, IReactiveProperty<Color> property, BindingTypes bindingType = BindingTypes.Default, params IFilter<Color>[] filters) { return GenericBindings.Bind(() => input.color, x => input.color = x, property, bindingType, filters) .AddTo(input); } public static IDisposable BindColorTo(this TMP_Text input, IReadOnlyReactiveProperty<Color> property, params IFilter<Color>[] filters) { return GenericBindings.Bind(x => input.color = x, property, filters).AddTo(input); } public static IDisposable BindColorTo(this TMP_Text input, Func<Color> getter, Action<Color> setter, BindingTypes bindingType = BindingTypes.Default, params IFilter<Color>[] filters) { return GenericBindings.Bind(() => input.color, x => input.color = x, getter, setter, bindingType, filters) .AddTo(input); } } }
44.269841
120
0.630154
[ "MIT" ]
starikcetin/BindingsRx-TextMeshPro
UnityProject/Packages/com.starikcetin.bindingsrx-textmeshpro/src/TMP_TextExtensions.cs
5,580
C#
namespace MySkillsServer.Web.ViewModels.Educations { using MySkillsServer.Data.Models; using MySkillsServer.Services.Mapping; public class EducationExportModel : IMapFrom<Education> { public int Id { get; set; } public string Degree { get; set; } public string Speciality { get; set; } public string Institution { get; set; } public int StartYear { get; set; } public int EndYear { get; set; } public string IconClassName { get; set; } public string Details { get; set; } public string UserId { get; set; } } }
22.703704
59
0.621533
[ "MIT" ]
Paulina-Dyulgerska/MySkillsServer
Web/MySkillsServer.Web.ViewModels/Educations/EducationExportModel.cs
615
C#
using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace SamplesCommon.SamplePages { /// <summary> /// Interaction logic for SampleStandardSizingPage.xaml /// </summary> public partial class SampleStandardSizingPage : UserControl { public SampleStandardSizingPage() { InitializeComponent(); } } }
23.888889
63
0.731783
[ "MIT" ]
DaveCS1/ModernWpf
samples/SamplesCommon/SamplePages/SampleStandardSizingPage.xaml.cs
647
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.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; using Xunit; namespace Microsoft.AspNetCore.Mvc.FunctionalTests { public class GlobalAuthorizationFilterEndpointRoutingTest : GlobalAuthorizationFilterTestBase, IClassFixture<MvcTestFixture<SecurityWebSite.StartupWithGlobalDenyAnonymousFilter>> { public GlobalAuthorizationFilterEndpointRoutingTest(MvcTestFixture<SecurityWebSite.StartupWithGlobalDenyAnonymousFilter> fixture) { Factory = fixture.Factories.FirstOrDefault() ?? fixture.WithWebHostBuilder(ConfigureWebHostBuilder); Client = Factory.CreateDefaultClient(); } private static void ConfigureWebHostBuilder(IWebHostBuilder builder) => builder.UseStartup<SecurityWebSite.StartupWithGlobalDenyAnonymousFilter>(); public WebApplicationFactory<SecurityWebSite.StartupWithGlobalDenyAnonymousFilter> Factory { get; } [Fact(Skip = "https://github.com/aspnet/AspNetCore/issues/8387")] public override Task DeniesAnonymousUsers_ByDefault() { return Task.CompletedTask; } } }
42.3125
182
0.761448
[ "Apache-2.0" ]
SeppPenner/AspNetCore
src/Mvc/test/Mvc.FunctionalTests/GlobalAuthorizationFilterEndpointRoutingTest.cs
1,354
C#
using System; using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using ESRI.ArcGIS.Client; using ESRI.ArcGIS.Client.Symbols; using ESRI.ArcGIS.Client.Tasks; using ESRI.ArcGIS.Client.Geometry; namespace ArcGISSilverlightSDK { public partial class DriveTimes : UserControl { Geoprocessor _geoprocessorTask; string jobid; GraphicsLayer graphicsLayer; List<FillSymbol> bufferSymbols; MapPoint inputPoint; string descText; public DriveTimes() { InitializeComponent(); graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer; bufferSymbols = new List<FillSymbol>( new FillSymbol[] { LayoutRoot.Resources["FillSymbol1"] as FillSymbol, LayoutRoot.Resources["FillSymbol2"] as FillSymbol, LayoutRoot.Resources["FillSymbol3"] as FillSymbol }); _geoprocessorTask = new Geoprocessor("http://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/GPServer/Generate%20Service%20Areas"); _geoprocessorTask.JobCompleted += GeoprocessorTask_JobCompleted; _geoprocessorTask.StatusUpdated += GeoprocessorTask_StatusUpdated; _geoprocessorTask.GetResultDataCompleted += GeoprocessorTask_GetResultDataCompleted; _geoprocessorTask.Failed += GeoprocessorTask_Failed; descText = InformationText.Text; } private void MyMap_MouseClick(object sender, ESRI.ArcGIS.Client.Map.MouseEventArgs e) { //Submit a new job only when the previous is completed if (jobid == null) { inputPoint = null; SubmitJob(e.MapPoint); } } private void SubmitJob(MapPoint mp) { graphicsLayer.Graphics.Clear(); Graphic graphic = new Graphic() { Symbol = LayoutRoot.Resources["DefaultMarkerSymbol"] as Symbol, Geometry = mp }; graphic.SetZIndex(1); graphicsLayer.Graphics.Add(graphic); List<GPParameter> parameters = new List<GPParameter>(); parameters.Add(new GPFeatureRecordSetLayer("Facilities", new FeatureSet(graphicsLayer.Graphics))); parameters.Add(new GPString("Break_Values", "1 2 3")); parameters.Add(new GPString("Break_Units", "Minutes")); _geoprocessorTask.SubmitJobAsync(parameters); InformationText.Text += "\n\nProcessing"; } void GeoprocessorTask_StatusUpdated(object sender, JobInfoEventArgs e) { if(InformationText.Text.Length > 102) InformationText.Text = descText + "\n\nProcessing"; else InformationText.Text += "."; jobid = e.JobInfo.JobStatus == esriJobStatus.esriJobCancelled || e.JobInfo.JobStatus == esriJobStatus.esriJobDeleted || e.JobInfo.JobStatus == esriJobStatus.esriJobFailed ? null : e.JobInfo.JobId; if (e.JobInfo.JobStatus == esriJobStatus.esriJobCancelling && inputPoint != null) { SubmitJob(inputPoint); inputPoint = null; } } private void GeoprocessorTask_JobCompleted(object sender, JobInfoEventArgs e) { jobid = null; InformationText.Text = descText; if (e.JobInfo.JobStatus == esriJobStatus.esriJobSucceeded) _geoprocessorTask.GetResultDataAsync(e.JobInfo.JobId, "ServiceAreas"); if (e.JobInfo.JobStatus == esriJobStatus.esriJobFailed) MessageBox.Show("Geoprocessing service failed! Check the Geoproccessing Parameters."); } void GeoprocessorTask_GetResultDataCompleted(object sender, GPParameterEventArgs e) { if (e.Parameter is GPFeatureRecordSetLayer) { GPFeatureRecordSetLayer gpLayer = e.Parameter as GPFeatureRecordSetLayer; int count = 0; foreach (Graphic graphic in gpLayer.FeatureSet.Features) { graphic.Symbol = bufferSymbols[count++]; graphicsLayer.Graphics.Add(graphic); } } } private void GeoprocessorTask_Failed(object sender, TaskFailedEventArgs e) { InformationText.Text = descText; jobid = null; MessageBox.Show("Geoprocessing service failed: " + e.Error); } } }
37.222222
172
0.608529
[ "Apache-2.0" ]
Esri/arcgis-samples-silverlight
src/ArcGISSilverlightSDK/Geoprocessor/DriveTimes.xaml.cs
4,692
C#
/* Copyright (C) 2005 <Paratrooper> paratrooper666@gmx.net * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * any later version. */ using System; using System.Collections; using System.Text.RegularExpressions; namespace CrypTool.MathParser { public enum Mode { RAD, DEG, GRAD }; public class Parser { private ArrayList FunctionList = new ArrayList(new string[] { "abs", "acos", "asin", "atan", "ceil", "cos", "cosh", "exp", "floor", "ln", "log", "sign", "sin", "sinh", "sqrt", "tan", "tanh" }); private double Value; private double Factor; private Mode mode; // Constructor public Parser() { this.Mode = Mode.RAD; } public Parser(Mode mode) { this.Mode = mode; } // Getter & Setter public double Result { get { return this.Value; } } public Mode Mode { get { return this.mode; } set { this.mode = value; switch (value) { case Mode.RAD: this.Factor = 1.0; break; case Mode.DEG: this.Factor = 2.0 * Math.PI / 360.0; break; case Mode.GRAD: this.Factor = 2.0 * Math.PI / 400.0; break; } } } public bool Evaluate(string Expression) { try { // **************************************************************************************** // ** MathParser in action: ** // ** Expression = "-(5 - 10)^(-1) ( 3 + 2( cos( 3 Pi )+( 2+ ln( exp(1) ) ) ^3))" ** // **************************************************************************************** // // // ---------- // - Step 1 - // ---------- // Remove blank. // // -(5 - 10)^(-1) ( 3 + 2( cos( 3 Pi )+( 2+ ln( exp(1) ) ) ^3)) -> -(5-10)^(-1)(3+2(cos(3Pi)+(2+ln(exp(1)))^3)) // Expression = Expression.Replace(" ", ""); // // ---------- // - Step 2 - // ---------- // Insert '*' if necessary. // // _ _ _ // -(5-10)^(-1)(3+2(cos(3Pi)+(2+ln(exp(1)))^3)) -> -(5-10)^(-1)*(3+2*(cos(3*Pi)+(2+ln(exp(1)))^3)) // | | | // Regex regEx = new Regex(@"(?<=[\d\)])(?=[a-df-z\(])|(?<=pi)(?=[^\+\-\*\/\\^!)])|(?<=\))(?=\d)|(?<=[^\/\*\+\-])(?=exp)", RegexOptions.IgnoreCase); Expression = regEx.Replace(Expression, "*"); // // ---------- // - Step 4 - // ---------- // Search for parentheses an solve the expression between it. // /* _____ * -(5-10)^(-1)*(3+2*(cos(3*3,14)+(2+ln(exp(1)))^3)) -> -{-5}^(-1)*(3+2*(cos(3*3,14)+(2+ln(exp(1)))^3)) * |_____| * __ * -{-5}^(-1)*(3+2*(cos(3*3,14)+(2+ln(exp(1)))^3)) -> -{-5}^-1*(3+2*(cos(3*3,14)+(2+ln(exp(1)))^3)) * |__| * ____ * -{-5}^-1*(3+2*(cos(3*3,14)+(2+ln(exp(1)))^3)) -> -{-5}^-1*(3+2*(cos9,42+(2+ln(exp(1)))^3)) * |______| * _ * -{-5}^-1*(3+2*(cos9,72+(2+ln(exp(1)))^3)) -> -{-5}^-1*(3+2*(cos9,72+(2+ln(exp1))^3)) * |_| * ____ * -{-5}^-1*(3+2*(cos9,72+(2+ln(exp1))^3)) -> -{-5}^-1*(3+2*(cos9,72+(2+ln2,71)^3)) * |____| * ____ * -{-5}^-1*(3+2*(cos9,72+(2+ln2,71)^3)) -> -{-5}^-1*(3+2*(cos9,72+{3}^3)) * |_________| * __ * -{-5}^-1*(3+2*(cos9,72+{3}^3)) -> -{-5}^-1*(3+2*26) * |_____________| * __ * -{-5}^-1*(3+2*26) -> -{-5}^-1*55 * |______| */ regEx = new Regex(@"([a-z]*)\(([^\(\)]+)\)(\^|!?)", RegexOptions.IgnoreCase); Match m = regEx.Match(Expression); while (m.Success) { if (m.Groups[3].Value.Length > 0) Expression = Expression.Replace(m.Value, "{" + m.Groups[1].Value + this.Solve(m.Groups[2].Value) + "}" + m.Groups[3].Value); else Expression = Expression.Replace(m.Value, m.Groups[1].Value + this.Solve(m.Groups[2].Value)); m = regEx.Match(Expression); } // // ---------- // - Step 5 - // ---------- // There are no more parentheses. Solve the expression and convert it to double. // __ // -{-5}^-1*55 => 11 // |_________| // this.Value = Convert.ToDouble(this.Solve(Expression)); return true; } catch { // Shit! return false; } } private string Solve(string Expression) { Regex regEx; Match m; // Solve AND regEx = new Regex(@"([\+-]?\d+,*\d*[eE][\+-]?\d+|[\-\+]?\d+,*\d*)([\/\*])(-?\d+,*\d*[eE][\+-]?\d+|-?\d+,*\d*)"); m = regEx.Match(Expression, 0); while (m.Success) { double result; //switch( m.Groups[2].Value ) //{ // case "*" : result = Convert.ToDouble(Convert.ToInt32(m.Groups[1].Value) & Convert.ToInt32(m.Groups[3].Value)); if (m.Index == 0) Expression = regEx.Replace(Expression, result.ToString(), 1); else Expression = Expression.Replace(m.Value, "+" + result); m = regEx.Match(Expression); // continue; //} } // Solve XOR. regEx = new Regex(@"([\+-]?\d+,*\d*[eE][\+-]?\d+|[\+-]?\d+,*\d*)([\+-])(-?\d+,*\d*[eE][\+-]?\d+|-?\d+,*\d*)"); m = regEx.Match(Expression, 0); while (m.Success) { double result; //switch( m.Groups[2].Value ) //{ // case "+" : result = result = Convert.ToDouble(Convert.ToInt32(m.Groups[1].Value) ^ Convert.ToInt32(m.Groups[3].Value)); if (m.Index == 0) Expression = regEx.Replace(Expression, result.ToString(), 1); else Expression = regEx.Replace(Expression, "+" + result, 1); m = regEx.Match(Expression); // continue; //} } //if( Expression.StartsWith( "--" ) ) Expression = Expression.Substring(2); return Expression; } } }
41.391534
201
0.339384
[ "Apache-2.0" ]
CrypToolProject/CrypTool-2
CrypPlugins/BooleanFunctionParser/MathParser.cs
7,825
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the pinpoint-2016-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Pinpoint.Model { /// <summary> /// Specifies the settings for an SMS activity in a journey. This type of activity sends /// a text message to participants. /// </summary> public partial class SMSMessageActivity { private JourneySMSMessage _messageConfig; private string _nextActivity; private string _templateName; private string _templateVersion; /// <summary> /// Gets and sets the property MessageConfig. /// <para> /// Specifies the sender ID and message type for an SMS message that's sent to participants /// in a journey. /// </para> /// </summary> public JourneySMSMessage MessageConfig { get { return this._messageConfig; } set { this._messageConfig = value; } } // Check to see if MessageConfig property is set internal bool IsSetMessageConfig() { return this._messageConfig != null; } /// <summary> /// Gets and sets the property NextActivity. /// <para> /// The unique identifier for the next activity to perform, after the message is sent. /// </para> /// </summary> public string NextActivity { get { return this._nextActivity; } set { this._nextActivity = value; } } // Check to see if NextActivity property is set internal bool IsSetNextActivity() { return this._nextActivity != null; } /// <summary> /// Gets and sets the property TemplateName. /// <para> /// The name of the SMS message template to use for the message. If specified, this value /// must match the name of an existing message template. /// </para> /// </summary> public string TemplateName { get { return this._templateName; } set { this._templateName = value; } } // Check to see if TemplateName property is set internal bool IsSetTemplateName() { return this._templateName != null; } /// <summary> /// Gets and sets the property TemplateVersion. /// <para> /// The unique identifier for the version of the SMS template to use for the message. /// If specified, this value must match the identifier for an existing template version. /// To retrieve a list of versions and version identifiers for a template, use the <link /// linkend="templates-template-name-template-type-versions">Template Versions</link> /// resource. /// </para> /// /// <para> /// If you don't specify a value for this property, Amazon Pinpoint uses the <i>active /// version</i> of the template. The <i>active version</i> is typically the version of /// a template that's been most recently reviewed and approved for use, depending on your /// workflow. It isn't necessarily the latest version of a template. /// </para> /// </summary> public string TemplateVersion { get { return this._templateVersion; } set { this._templateVersion = value; } } // Check to see if TemplateVersion property is set internal bool IsSetTemplateVersion() { return this._templateVersion != null; } } }
35.1875
107
0.595249
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/Pinpoint/Generated/Model/SMSMessageActivity.cs
4,504
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 Microsoft.Templates.Core.Locations; namespace Microsoft.UI.Test.ProjectConfigurationTests { public sealed class UITestsTemplatesSource : LocalTemplatesSource { public UITestsTemplatesSource() : base(null) { } public override string Id => "UITest" + GetAgentName(); public override string GetContentRootFolder() { var dir = System.IO.Path.GetDirectoryName(System.Environment.CurrentDirectory); dir = System.IO.Path.Combine(dir, @"..\..\SharedFunctionality.UI.Tests\TestData\Templates\test"); return dir; } } }
31
110
0.64977
[ "MIT" ]
Microsoft/WindowsTemplateStudio
code/test/SharedFunctionality.UI.Tests/ProjectConfigurationTests/UiTestsTemplatesSource.cs
843
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Collections.Generic; using System.Linq; using UnityEngine; namespace HoloToolkit.Unity { /// <summary> /// A collection of useful extension methods for Unity's Vector structs. /// </summary> public static class VectorExtensions { public static Vector2 Mul(this Vector2 value, Vector2 scale) { return new Vector2(value.x * scale.x, value.y * scale.y); } public static Vector2 Div(this Vector2 value, Vector2 scale) { return new Vector2(value.x / scale.x, value.y / scale.y); } public static Vector3 Mul(this Vector3 value, Vector3 scale) { return new Vector3(value.x * scale.x, value.y * scale.y, value.z * scale.z); } public static Vector3 Div(this Vector3 value, Vector3 scale) { return new Vector3(value.x / scale.x, value.y / scale.y, value.z / scale.z); } public static Vector3 RotateAround(this Vector3 point, Vector3 pivot, Quaternion rotation) { return rotation * (point - pivot) + pivot; } public static Vector3 RotateAround(this Vector3 point, Vector3 pivot, Vector3 eulerAngles) { return RotateAround(point, pivot, Quaternion.Euler(eulerAngles)); } public static Vector3 TransformPoint(this Vector3 point, Vector3 translation, Quaternion rotation, Vector3 lossyScale) { return rotation * Vector3.Scale(lossyScale, point) + translation; } public static Vector3 InverseTransformPoint(this Vector3 point, Vector3 translation, Quaternion rotation, Vector3 lossyScale) { var scaleInv = new Vector3(1 / lossyScale.x, 1 / lossyScale.y, 1 / lossyScale.z); return Vector3.Scale(scaleInv, (Quaternion.Inverse(rotation) * (point - translation))); } public static Vector2 Average(this IEnumerable<Vector2> vectors) { float x = 0f; float y = 0f; int count = 0; foreach (var pos in vectors) { x += pos.x; y += pos.y; count++; } return new Vector2(x / count, y / count); } public static Vector3 Average(this IEnumerable<Vector3> vectors) { float x = 0f; float y = 0f; float z = 0f; int count = 0; foreach (var pos in vectors) { x += pos.x; y += pos.y; z += pos.z; count++; } return new Vector3(x / count, y / count, z / count); } public static Vector2 Average(this ICollection<Vector2> vectors) { int count = vectors.Count; if (count == 0) { return Vector2.zero; } float x = 0f; float y = 0f; foreach (var pos in vectors) { x += pos.x; y += pos.y; } return new Vector2(x / count, y / count); } public static Vector3 Average(this ICollection<Vector3> vectors) { int count = vectors.Count; if (count == 0) { return Vector3.zero; } float x = 0f; float y = 0f; float z = 0f; foreach (var pos in vectors) { x += pos.x; y += pos.y; z += pos.z; } return new Vector3(x / count, y / count, z / count); } public static Vector2 Median(this IEnumerable<Vector2> vectors) { int count = vectors.Count(); if (count == 0) { return Vector2.zero; } return vectors.OrderBy(v => v.sqrMagnitude).ElementAt(count / 2); } public static Vector3 Median(this IEnumerable<Vector3> vectors) { int count = vectors.Count(); if (count == 0) { return Vector3.zero; } return vectors.OrderBy(v => v.sqrMagnitude).ElementAt(count / 2); } public static Vector2 Median(this ICollection<Vector2> vectors) { int count = vectors.Count; if (count == 0) { return Vector2.zero; } return vectors.OrderBy(v => v.sqrMagnitude).ElementAt(count / 2); } public static Vector3 Median(this ICollection<Vector3> vectors) { int count = vectors.Count; if (count == 0) { return Vector3.zero; } return vectors.OrderBy(v => v.sqrMagnitude).ElementAt(count / 2); } } }
31.005917
134
0.494084
[ "MIT" ]
4dpocket/Unitytest1
DesignLabs_Unity/Assets/HoloToolkit/Utilities/Scripts/Extensions/VectorExtensions.cs
5,242
C#
// <auto-generated /> using System; using ConsoleApp1; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace ConsoleApp1.Migrations { [DbContext(typeof(DataStore))] [Migration("20201104173716_Init")] partial class Init { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.9"); modelBuilder.Entity("ConsoleApp1.Student", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Address") .HasColumnType("TEXT"); b.Property<int>("ClassId") .HasColumnType("INTEGER"); b.Property<DateTime>("CreateTime") .HasColumnType("TEXT"); b.Property<string>("Name") .HasColumnType("TEXT"); b.Property<int>("SeatId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.ToTable("Students"); }); #pragma warning restore 612, 618 } } }
29.26
75
0.534518
[ "MIT" ]
HekunX/EazyPageQuery
example/ConsoleApp1/ConsoleApp1/Migrations/20201104173716_Init.Designer.cs
1,465
C#
// Copyright © 2014 Rick Beerendonk. All Rights Reserved. // // This code is a C# port of the Java version created and maintained by Cognitect, therefore // // Copyright © 2014 Cognitect. 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 Beerendonk.Transit.Impl.ReadHandlers { internal class KeywordReadHandler : IReadHandler { public object FromRepresentation(object representation) { return TransitFactory.Keyword((string)representation); } } }
37
92
0.726834
[ "Apache-2.0" ]
NForza/transit-csharp
src/Transit/Impl/ReadHandlers/KeywordReadHandler.cs
1,040
C#
using AntDesign.TestApp.Client.Data; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AntDesign.TestApp.Server.Controllers { [Authorize] [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] _summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet] public IEnumerable<WeatherForecast> Get() { var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = _summaries[rng.Next(_summaries.Length)] }) .ToArray(); } } }
29.162791
110
0.619617
[ "MIT" ]
1051324354/ant-design-blazor
tests/AntDesign.TestApp/Server/Controllers/WeatherForecastController.cs
1,256
C#
using System.Collections.Generic; using System.IO; using DataTools.SqlBulkData.Columns; using DataTools.SqlBulkData.PersistedModel; using DataTools.SqlBulkData.Serialisation; namespace DataTools.SqlBulkData { public class NullFieldMap { private readonly BitSetPacker packer; private readonly byte[] buffer; public NullFieldMap(IColumnSerialiser[] columns) { var nullableColumns = new List<int>(); for (var i = 0; i < columns.Length; i++) { if (columns[i].Flags.IsNullable()) nullableColumns.Add(i); } packer = new BitSetPacker(nullableColumns.ToArray()); NullFields = new bool[columns.Length]; buffer = new byte[packer.PackedByteCount]; } public bool[] NullFields { get; } public void Read(Stream stream) { Serialiser.ReadFixedLengthBytes(stream, buffer); packer.Unpack(buffer, NullFields); } public void Write(Stream stream) { packer.Pack(NullFields, buffer); Serialiser.WriteFixedLengthBytes(stream, buffer); } } }
29.731707
75
0.590648
[ "MIT" ]
alex-davidson/DataTools
DataTools.SqlBulkData/NullFieldMap.cs
1,221
C#
namespace ImageManipulator { partial class HistogramForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea(); System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend(); System.Windows.Forms.DataVisualization.Charting.Series series1 = new System.Windows.Forms.DataVisualization.Charting.Series(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.chart1 = new System.Windows.Forms.DataVisualization.Charting.Chart(); this.tableLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.chart1)).BeginInit(); this.SuspendLayout(); // // tableLayoutPanel1 // this.tableLayoutPanel1.ColumnCount = 1; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.Controls.Add(this.chart1, 0, 0); this.tableLayoutPanel1.Location = new System.Drawing.Point(12, 12); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 1; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(1175, 627); this.tableLayoutPanel1.TabIndex = 0; // // chart1 // this.chart1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); chartArea1.Name = "ChartArea1"; this.chart1.ChartAreas.Add(chartArea1); legend1.Name = "Legend1"; this.chart1.Legends.Add(legend1); this.chart1.Location = new System.Drawing.Point(10, 10); this.chart1.Margin = new System.Windows.Forms.Padding(10); this.chart1.Name = "chart1"; series1.ChartArea = "ChartArea1"; series1.Legend = "Legend1"; series1.Name = "ImageHistogram"; this.chart1.Series.Add(series1); this.chart1.Size = new System.Drawing.Size(1155, 607); this.chart1.TabIndex = 0; this.chart1.Text = "chart1"; this.chart1.Resize += new System.EventHandler(this.chart1_Resize); // // HistogramForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1199, 651); this.Controls.Add(this.tableLayoutPanel1); this.Name = "HistogramForm"; this.Text = "HistogramForm"; this.Load += new System.EventHandler(this.HistogramForm_Load); this.tableLayoutPanel1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.chart1)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.DataVisualization.Charting.Chart chart1; } }
48.967742
157
0.632631
[ "MIT" ]
IordanisKostelidis/ImageManipulator
ImageManipulator/HistogramForm.Designer.cs
4,556
C#
using System.Text.Json.Serialization; namespace Essensoft.AspNetCore.Payment.Alipay.Response { /// <summary> /// AlipayBusinessOrderCancelResponse. /// </summary> public class AlipayBusinessOrderCancelResponse : AlipayResponse { /// <summary> /// 商户外部订单号 /// </summary> [JsonPropertyName("merchant_order_no")] public string MerchantOrderNo { get; set; } /// <summary> /// 支付宝订单号 /// </summary> [JsonPropertyName("order_no")] public string OrderNo { get; set; } } }
24.869565
67
0.597902
[ "MIT" ]
LuohuaRain/payment
src/Essensoft.AspNetCore.Payment.Alipay/Response/AlipayBusinessOrderCancelResponse.cs
600
C#
/******************************************************************************* * Copyright 2012-2019 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. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.ChimeSDKIdentity; using Amazon.ChimeSDKIdentity.Model; namespace Amazon.PowerShell.Cmdlets.CHMID { /// <summary> /// Demotes an <code>AppInstanceAdmin</code> to an <code>AppInstanceUser</code>. This /// action does not delete the user. /// </summary> [Cmdlet("Remove", "CHMIDAppInstanceAdmin", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.High)] [OutputType("None")] [AWSCmdlet("Calls the Amazon Chime SDK Identity DeleteAppInstanceAdmin API operation.", Operation = new[] {"DeleteAppInstanceAdmin"}, SelectReturnType = typeof(Amazon.ChimeSDKIdentity.Model.DeleteAppInstanceAdminResponse))] [AWSCmdletOutput("None or Amazon.ChimeSDKIdentity.Model.DeleteAppInstanceAdminResponse", "This cmdlet does not generate any output." + "The service response (type Amazon.ChimeSDKIdentity.Model.DeleteAppInstanceAdminResponse) can be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class RemoveCHMIDAppInstanceAdminCmdlet : AmazonChimeSDKIdentityClientCmdlet, IExecutor { #region Parameter AppInstanceAdminArn /// <summary> /// <para> /// <para>The ARN of the <code>AppInstance</code>'s administrator.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] #else [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String AppInstanceAdminArn { get; set; } #endregion #region Parameter AppInstanceArn /// <summary> /// <para> /// <para>The ARN of the <code>AppInstance</code>.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String AppInstanceArn { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The cmdlet doesn't have a return value by default. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.ChimeSDKIdentity.Model.DeleteAppInstanceAdminResponse). /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "*"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the AppInstanceArn parameter. /// The -PassThru parameter is deprecated, use -Select '^AppInstanceArn' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^AppInstanceArn' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter Force /// <summary> /// This parameter overrides confirmation prompts to force /// the cmdlet to continue its operation. This parameter should always /// be used with caution. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter Force { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.AppInstanceAdminArn), MyInvocation.BoundParameters); if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Remove-CHMIDAppInstanceAdmin (DeleteAppInstanceAdmin)")) { return; } var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.ChimeSDKIdentity.Model.DeleteAppInstanceAdminResponse, RemoveCHMIDAppInstanceAdminCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.AppInstanceArn; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.AppInstanceAdminArn = this.AppInstanceAdminArn; #if MODULAR if (this.AppInstanceAdminArn == null && ParameterWasBound(nameof(this.AppInstanceAdminArn))) { WriteWarning("You are passing $null as a value for parameter AppInstanceAdminArn which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif context.AppInstanceArn = this.AppInstanceArn; #if MODULAR if (this.AppInstanceArn == null && ParameterWasBound(nameof(this.AppInstanceArn))) { WriteWarning("You are passing $null as a value for parameter AppInstanceArn which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.ChimeSDKIdentity.Model.DeleteAppInstanceAdminRequest(); if (cmdletContext.AppInstanceAdminArn != null) { request.AppInstanceAdminArn = cmdletContext.AppInstanceAdminArn; } if (cmdletContext.AppInstanceArn != null) { request.AppInstanceArn = cmdletContext.AppInstanceArn; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.ChimeSDKIdentity.Model.DeleteAppInstanceAdminResponse CallAWSServiceOperation(IAmazonChimeSDKIdentity client, Amazon.ChimeSDKIdentity.Model.DeleteAppInstanceAdminRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Chime SDK Identity", "DeleteAppInstanceAdmin"); try { #if DESKTOP return client.DeleteAppInstanceAdmin(request); #elif CORECLR return client.DeleteAppInstanceAdminAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public System.String AppInstanceAdminArn { get; set; } public System.String AppInstanceArn { get; set; } public System.Func<Amazon.ChimeSDKIdentity.Model.DeleteAppInstanceAdminResponse, RemoveCHMIDAppInstanceAdminCmdlet, object> Select { get; set; } = (response, cmdlet) => null; } } }
46.383673
290
0.623636
[ "Apache-2.0" ]
aws/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/ChimeSDKIdentity/Basic/Remove-CHMIDAppInstanceAdmin-Cmdlet.cs
11,364
C#
using UnityEngine; public class Sense : MonoBehaviour { public bool enableDebug = true; public Aspect.AspectTypes aspectName = Aspect.AspectTypes.ENEMY; public float detectionRate = 1.0f; protected float elapsedTime = 0.0f; protected virtual void Initialize() {} protected virtual void UpdateSense() {} // Start is called before the first frame update void Start() { elapsedTime = 0.0f; Initialize(); } // Update is called once per frame void Update() { UpdateSense(); } }
21.576923
68
0.639929
[ "MIT" ]
StanHaakman/unity-tutorial
Assets/Scripts/Sense.cs
561
C#
using System; using System.Net.Http; using System.Web.OData.Formatter.Serialization; using Bit.Core.Contracts; using Bit.Owin.Contracts; using Microsoft.OData; using Microsoft.OData.Edm; using Microsoft.Owin; namespace Bit.OData.Serialization { public class DefaultODataPrimitiveSerializer : ODataPrimitiveSerializer { public override ODataPrimitiveValue CreateODataPrimitiveValue(object graph, IEdmPrimitiveTypeReference primitiveType, ODataSerializerContext writeContext) { ODataPrimitiveValue result = base.CreateODataPrimitiveValue(graph, primitiveType, writeContext); if (result?.Value is DateTimeOffset date) { IDependencyResolver dependencyResolver = writeContext.Request.GetOwinContext() .GetDependencyResolver(); ITimeZoneManager timeZoneManager = dependencyResolver.Resolve<ITimeZoneManager>(); result = new ODataPrimitiveValue(timeZoneManager.MapFromServerToClient(date)); } return result; } } }
34.5
108
0.696558
[ "MIT" ]
moshtaba/bit-framework
src/Server/Bit.OData/Serialization/DefaultODataPrimitiveSerializer.cs
1,106
C#
using System; using Xunit; using Sample.MaxSubarray; namespace Sample.Tests{ public class UnitTest_MaxSubarray{ [Theory] [InlineData(new int[]{-2,1,-3,4,-1,2,1,-5,4},6)] [InlineData(new int[]{5,4,-1,7,8},23)] public void checkResult(int[] nums,int expected){ Assert.Equal(expected,maxSubarray.naive(nums)); } } }
24.933333
59
0.606952
[ "MIT" ]
zcemycl/algoTest
cs/sample/Sample.Tests/MaxSubarray/testMaxSubarray.cs
374
C#
#region License // /* // * ###### // * ###### // * ############ ####( ###### #####. ###### ############ ############ // * ############# #####( ###### #####. ###### ############# ############# // * ###### #####( ###### #####. ###### ##### ###### ##### ###### // * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### // * ###### ###### #####( ###### #####. ###### ##### ##### ###### // * ############# ############# ############# ############# ##### ###### // * ############ ############ ############# ############ ##### ###### // * ###### // * ############# // * ############ // * // * Adyen Dotnet API Library // * // * Copyright (c) 2019 Adyen B.V. // * This file is open source and available under the MIT license. // * See the LICENSE file for more info. // */ #endregion namespace Adyen.Model.Nexo { /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class LogoutRequest { /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] [System.ComponentModel.DefaultValueAttribute(false)] public bool? MaintenanceAllowed; } }
39.051282
79
0.328956
[ "MIT" ]
AlexandrosMor/adyen-dotnet-api-library
Adyen/Model/Nexo/LogoutRequest.cs
1,525
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.CodeAnalysis.Sarif; namespace Microsoft.CodeAnalysis.IL { internal static class ErrorRules { public static ReportingDescriptor InvalidPE = new ReportingDescriptor() { Id = "BA1001", Name = nameof(InvalidPE), FullDescription = new MultiformatMessageString { Text = DriverResources.InvalidPE_Description } }; } }
31.666667
108
0.666667
[ "MIT" ]
Bhaskers-Blu-Org2/binskim
src/BinSkim.Driver/ErrorRules.cs
555
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.Infrastructure.DependencyResolution { using System.Collections.Concurrent; using System.Collections.Generic; using System.Data.Entity.Core.Common; using System.Data.Entity.Infrastructure.Interception; using System.Data.Entity.Internal; using System.Data.Entity.Utilities; using System.Globalization; using System.Linq; using System.Reflection; // <summary> // Resolves dependencies from a config file. // </summary> internal class AppConfigDependencyResolver : IDbDependencyResolver { private readonly AppConfig _appConfig; private readonly InternalConfiguration _internalConfiguration; private readonly ConcurrentDictionary<Tuple<Type, object>, Func<object>> _serviceFactories = new ConcurrentDictionary<Tuple<Type, object>, Func<object>>(); private readonly ConcurrentDictionary<Tuple<Type, object>, IEnumerable<Func<object>>> _servicesFactories = new ConcurrentDictionary<Tuple<Type, object>, IEnumerable<Func<object>>>(); private readonly Dictionary<string, DbProviderServices> _providerFactories = new Dictionary<string, DbProviderServices>(); private bool _providersRegistered; private readonly ProviderServicesFactory _providerServicesFactory; // <summary> // For testing. // </summary> public AppConfigDependencyResolver() { } public AppConfigDependencyResolver( AppConfig appConfig, InternalConfiguration internalConfiguration, ProviderServicesFactory providerServicesFactory = null) { DebugCheck.NotNull(appConfig); _appConfig = appConfig; _internalConfiguration = internalConfiguration; _providerServicesFactory = providerServicesFactory ?? new ProviderServicesFactory(); } public virtual object GetService(Type type, object key) { return _serviceFactories.GetOrAdd( Tuple.Create(type, key), t => GetServiceFactory(type, key as string))(); } public IEnumerable<object> GetServices(Type type, object key) { return _servicesFactories.GetOrAdd( Tuple.Create(type, key), t => GetServicesFactory(type, key)).Select(f => f()).Where(s => s != null).ToList(); } public virtual IEnumerable<Func<object>> GetServicesFactory(Type type, object key) { if (type == typeof(IDbInterceptor)) { return _appConfig.Interceptors.Select(i => (Func<object>)(() => i)).ToList(); } return new List<Func<object>> { GetServiceFactory(type, key as string) }; } public virtual Func<object> GetServiceFactory(Type type, string name) { if (!_providersRegistered) { lock (_providerFactories) { if (!_providersRegistered) { RegisterDbProviderServices(); _providersRegistered = true; } } } if (!string.IsNullOrWhiteSpace(name)) { if (type == typeof(DbProviderServices)) { DbProviderServices providerFactory; _providerFactories.TryGetValue(name, out providerFactory); return () => providerFactory; } } if (type == typeof(IDbConnectionFactory)) { // This is convoluted to avoid breaking changes from EF5. The behavior is: // 1. If the app has already set the Database.DefaultConnectionFactory property, then // whatever it is set to should be returned. // 2. If not, but an connection factory was set in app.config, then set the // DefaultConnectionFactory property to the one from the app.config so that in // the future it will always be used, unless... // 3. The app later changes the DefaultConnectionFactory property in which case // the later one will be used instead of the one from app.config // Note that this means that the app.config and DefaultConnectionFactory will override // any other resolver in the chain (since this class is at the top of the chain) // unless IDbConfiguration was used to add an overriding resolver. if (!Database.DefaultConnectionFactoryChanged) { var connectionFactory = _appConfig.TryGetDefaultConnectionFactory(); if (connectionFactory != null) { #pragma warning disable 612,618 Database.DefaultConnectionFactory = connectionFactory; #pragma warning restore 612,618 } } return () => Database.DefaultConnectionFactoryChanged ? Database.SetDefaultConnectionFactory : null; } var contextType = type.TryGetElementType(typeof(IDatabaseInitializer<>)); if (contextType != null) { var initializer = _appConfig.Initializers.TryGetInitializer(contextType); return () => initializer; } return () => null; } private void RegisterDbProviderServices() { var providers = _appConfig.DbProviderServices; if (providers.All(p => p.InvariantName != "System.Data.SqlClient")) { // If no SQL Server provider is registered, then make sure the SQL Server provider is available // by convention (if it can be loaded) as it would have been in previous versions of EF. RegisterSqlServerProvider(); } providers.Each( p => { _providerFactories[p.InvariantName] = p.ProviderServices; _internalConfiguration.AddDefaultResolver(p.ProviderServices); }); } private void RegisterSqlServerProvider() { var providerTypeName = string.Format( CultureInfo.InvariantCulture, "System.Data.Entity.SqlServer.SqlProviderServices, Z.EntityFramework.Classic.SqlServer, Version={0}, Culture=neutral, PublicKeyToken=afc61983f100d280", new AssemblyName(typeof(DbContext).Assembly().FullName).Version); var provider = _providerServicesFactory.TryGetInstance(providerTypeName); if (provider != null) { // This provider goes just above the root resolver so that any other provider registered in code // still takes precedence, including any additional services registered by that provider. _internalConfiguration.SetDefaultProviderServices(provider, "System.Data.SqlClient"); } } } }
41.463277
171
0.59831
[ "Apache-2.0" ]
Lempireqc/EntityFramework-Classic
src/Shared/EntityFramework/Infrastructure/DependencyResolution/AppConfigDependencyResolver.cs
7,339
C#
using System; using System.Xml.Serialization; namespace Aop.Api.Domain { /// <summary> /// AlipayOpenServicemarketOrderItemCompleteModel Data Structure. /// </summary> [Serializable] public class AlipayOpenServicemarketOrderItemCompleteModel : AopObject { /// <summary> /// 订购服务插件订单号 /// </summary> [XmlElement("commodity_order_id")] public string CommodityOrderId { get; set; } /// <summary> /// 订购插件选择的某一店铺ID /// </summary> [XmlElement("shop_id")] public string ShopId { get; set; } } }
23.96
74
0.602671
[ "MIT" ]
BJDIIL/DiiL
Sdk/AlipaySdk/Domain/AlipayOpenServicemarketOrderItemCompleteModel.cs
639
C#
using System; using JetBrains.Annotations; namespace BuildNotifications.PluginInterfaces.SourceControl { /// <summary> /// Contains information about a branch. /// </summary> [PublicAPI] public interface IBranch : IEquatable<IBranch> { /// <summary> /// Name that can be used when displaying this branch. /// </summary> string DisplayName { get; } /// <summary> /// The name of the branch. /// </summary> string FullName { get; } /// <summary> /// Indicates whether this branch is a real branch (false) or one that was /// created during/for a pull request (true); /// </summary> bool IsPullRequest { get; } } }
26.678571
82
0.576975
[ "MIT" ]
TheSylence/BuildNotifications
Plugins/BuildNotifications.PluginInterfaces/SourceControl/IBranch.cs
749
C#
//Copyright 2014 Esri // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License.using System; using ArcGIS.Desktop.Framework.Contracts; using ArcGIS.Desktop.Internal.Mapping; namespace ProSDKSamples.FixedZoom { /// <summary> /// The button shows zoom-out functionality by manipulating the camera. /// In 2D view mode we are changing the scale property whereas in 3D the z-value /// of the observer (eye). /// </summary> internal class FixedZoomOut : Button { private static readonly double MaximumScale = 1000000000.0; private static readonly double MaximumElevation = MaximumScale; protected override void OnClick() { Camera camera = ProSDKSampleModule.ActiveMapView.Camera; if (ProSDKSampleModule.ActiveMapView.Is2D) { double scale = camera.Scale * 1.25; camera.Scale = scale < MaximumScale ? scale : MaximumScale; } else { double z = camera.EyeXYZ.Z*1.25; camera.EyeXYZ.Z = z < MaximumScale ? z : MaximumScale; } ProSDKSampleModule.ActiveMapView.Camera = camera; } } }
38.272727
84
0.665677
[ "Apache-2.0" ]
Esri/arcgis-pro-samples-beta
Beta5/FixedZoom/FixedZoomOut.cs
1,686
C#
// $Id: EditMenu.cs 1766 2008-09-14 16:54:14Z lining $ using System; using System.Diagnostics; using System.Threading; using System.Windows.Forms; using UW.ClassroomPresenter.Model; using UW.ClassroomPresenter.Model.Undo; using UW.ClassroomPresenter.Model.Presentation; using UW.ClassroomPresenter.Viewer.Slides; namespace UW.ClassroomPresenter.Viewer.Menus { public class EditMenu : MenuItem { public EditMenu(ControlEventQueue dispatcher, PresenterModel model) { this.Text = Strings.Edit; this.MenuItems.Add(new UndoMenuItem(dispatcher, model)); this.MenuItems.Add(new RedoMenuItem(dispatcher, model)); } private class UndoMenuItem : MenuItem, DeckTraversalModelAdapter.IAdaptee { protected readonly PresenterModel m_Model; private readonly EventQueue m_EventQueue; private bool m_Disposed; protected object[] m_Actors; private readonly WorkspaceModelAdapter m_WorkspaceModelAdapter; public UndoMenuItem(ControlEventQueue dispatcher, PresenterModel model) { this.m_Model = model; this.m_EventQueue = dispatcher; this.Text = Strings.Undo; this.Shortcut = Shortcut.CtrlZ; this.ShowShortcut = true; this.m_Model.Undo.Update += new EventHandler(this.HandleUndoableChanged); this.m_WorkspaceModelAdapter = new WorkspaceModelAdapter(dispatcher, this, this.m_Model); } protected override void Dispose(bool disposing) { if(this.m_Disposed) return; try { if(disposing) { this.m_Model.Undo.Update -= new EventHandler(this.HandleUndoableChanged); this.m_WorkspaceModelAdapter.Dispose(); } } finally { base.Dispose(disposing); } this.m_Disposed = true; } protected override void OnClick(EventArgs e) { base.OnClick(e); this.OnClickImpl(); } protected virtual void OnClickImpl() { using(Synchronizer.Lock(this.m_Model.Undo.SyncRoot)) { if(this.m_Model.Undo.IsUndoable(this.m_Actors)) this.m_Model.Undo.UndoOne(this.m_Actors); } } private void HandleUndoableChanged(object sender, EventArgs e) { this.m_EventQueue.Post(new EventQueue.EventDelegate(this.HandleUndoStackChanged)); } protected virtual void HandleUndoStackChanged() { using(Synchronizer.Lock(this.m_Model.Undo.SyncRoot)) { this.Enabled = this.m_Model.Undo.IsUndoable(this.m_Actors); } } SlideModel DeckTraversalModelAdapter.IAdaptee.Slide { set { using(Synchronizer.Lock(this.m_Model.Undo.SyncRoot)) { this.m_Actors = new object[] { value }; this.HandleUndoableChanged(this, EventArgs.Empty); } } } //Unused IAdaptee member System.Drawing.Color DeckTraversalModelAdapter.IAdaptee.DefaultDeckBGColor { set {} } UW.ClassroomPresenter.Model.Background.BackgroundTemplate DeckTraversalModelAdapter.IAdaptee.DefaultDeckBGTemplate { set { } } } private class RedoMenuItem : UndoMenuItem { public RedoMenuItem(ControlEventQueue dispatcher, PresenterModel model) : base(dispatcher, model) { this.Text = Strings.Redo; this.Shortcut = Shortcut.CtrlY; this.ShowShortcut = true; } protected override void OnClickImpl() { using(Synchronizer.Lock(this.m_Model.Undo.SyncRoot)) { if(this.m_Model.Undo.IsRedoable(this.m_Actors)) this.m_Model.Undo.RedoOne(this.m_Actors); } } protected override void HandleUndoStackChanged() { using(Synchronizer.Lock(this.m_Model.Undo.SyncRoot)) { this.Enabled = this.m_Model.Undo.IsRedoable(this.m_Actors); } } } } }
39.111111
129
0.56097
[ "Apache-2.0" ]
ClassroomPresenter/CP3
UW.ClassroomPresenter/Viewer/Menus/EditMenu.cs
4,576
C#
using RabbitMQ.Client.Framing.Impl; namespace RabbitMQ.Client.Impl { ///<summary>Normal ISession implementation used during normal channel operation.</summary> public class Session : SessionBase { private readonly CommandAssembler _assembler; public Session(Connection connection, int channelNumber) : base(connection, channelNumber) { _assembler = new CommandAssembler(connection.Protocol); } public override void HandleFrame(InboundFrame frame) { using Command cmd = _assembler.HandleFrame(frame); if (cmd != null) { OnCommandReceived(cmd); } } } }
27.461538
94
0.616246
[ "MIT" ]
houseofcat/RabbitMQ.Core
v6.0.0/RabbitMQ.Client/Impl/Session.cs
714
C#
// -------------------------------------------------------------------------------------------- // Version: MPL 1.1/GPL 2.0/LGPL 2.1 // // The contents of this file are subject to the Mozilla Public License Version // 1.1 (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.mozilla.org/MPL/ // // Software distributed under the License is distributed on an "AS IS" basis, // WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License // for the specific language governing rights and limitations under the // License. // // <remarks> // Generated by IDLImporter from file nsIDOMMessageEvent.idl // // You should use these interfaces when you access the COM objects defined in the mentioned // IDL/IDH file. // </remarks> // -------------------------------------------------------------------------------------------- namespace Gecko { using System; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Runtime.CompilerServices; /// <summary> /// The nsIDOMMessageEvent interface is used for server-sent events and for /// cross-domain messaging. /// /// For more information on this interface, please see /// http://www.whatwg.org/specs/web-apps/current-work/#messageevent /// </summary> [ComImport()] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("4408a2f5-614f-40a3-8786-e16bd3f74e32")] internal interface nsIDOMMessageEvent : nsIDOMEvent { /// <summary> /// The name of the event (case-insensitive). The name must be an XML /// name. /// </summary> [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] new void GetTypeAttribute([MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = "Gecko.CustomMarshalers.AStringMarshaler")] nsAStringBase aType); /// <summary> /// Used to indicate the EventTarget to which the event was originally /// dispatched. /// </summary> [return: MarshalAs(UnmanagedType.Interface)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] new nsIDOMEventTarget GetTargetAttribute(); /// <summary> /// Used to indicate the EventTarget whose EventListeners are currently /// being processed. This is particularly useful during capturing and /// bubbling. /// </summary> [return: MarshalAs(UnmanagedType.Interface)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] new nsIDOMEventTarget GetCurrentTargetAttribute(); /// <summary> /// Used to indicate which phase of event flow is currently being /// evaluated. /// </summary> [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] new ushort GetEventPhaseAttribute(); /// <summary> /// Used to indicate whether or not an event is a bubbling event. If the /// event can bubble the value is true, else the value is false. /// </summary> [return: MarshalAs(UnmanagedType.U1)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] new bool GetBubblesAttribute(); /// <summary> /// Used to indicate whether or not an event can have its default action /// prevented. If the default action can be prevented the value is true, /// else the value is false. /// </summary> [return: MarshalAs(UnmanagedType.U1)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] new bool GetCancelableAttribute(); /// <summary> /// Used to specify the time (in milliseconds relative to the epoch) at /// which the event was created. Due to the fact that some systems may /// not provide this information the value of timeStamp may be not /// available for all events. When not available, a value of 0 will be /// returned. Examples of epoch time are the time of the system start or /// 0:0:0 UTC 1st January 1970. /// </summary> [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] new long GetTimeStampAttribute(); /// <summary> /// The stopPropagation method is used prevent further propagation of an /// event during event flow. If this method is called by any /// EventListener the event will cease propagating through the tree. The /// event will complete dispatch to all listeners on the current /// EventTarget before event flow stops. This method may be used during /// any stage of event flow. /// </summary> [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] new void StopPropagation(); /// <summary> /// If an event is cancelable, the preventDefault method is used to /// signify that the event is to be canceled, meaning any default action /// normally taken by the implementation as a result of the event will /// not occur. If, during any stage of event flow, the preventDefault /// method is called the event is canceled. Any default action associated /// with the event will not occur. Calling this method for a /// non-cancelable event has no effect. Once preventDefault has been /// called it will remain in effect throughout the remainder of the /// event's propagation. This method may be used during any stage of /// event flow. /// </summary> [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] new void PreventDefault(); /// <summary> /// The initEvent method is used to initialize the value of an Event /// created through the DocumentEvent interface. This method may only be /// called before the Event has been dispatched via the dispatchEvent /// method, though it may be called multiple times during that phase if /// necessary. If called multiple times the final invocation takes /// precedence. If called from a subclass of Event interface only the /// values specified in the initEvent method are modified, all other /// attributes are left unchanged. /// /// @param eventTypeArg Specifies the event type. This type may be /// any event type currently defined in this /// specification or a new event type.. The string /// must be an XML name. /// Any new event type must not begin with any /// upper, lower, or mixed case version of the /// string "DOM". This prefix is reserved for /// future DOM event sets. It is also strongly /// recommended that third parties adding their /// own events use their own prefix to avoid /// confusion and lessen the probability of /// conflicts with other new events. /// @param canBubbleArg Specifies whether or not the event can bubble. /// @param cancelableArg Specifies whether or not the event's default /// action can be prevented. /// </summary> [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] new void InitEvent([MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = "Gecko.CustomMarshalers.AStringMarshaler")] nsAStringBase eventTypeArg, [MarshalAs(UnmanagedType.U1)] bool canBubbleArg, [MarshalAs(UnmanagedType.U1)] bool cancelableArg); /// <summary> /// Used to indicate whether preventDefault() has been called for this event. /// </summary> [return: MarshalAs(UnmanagedType.U1)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] new bool GetDefaultPreventedAttribute(); /// <summary> /// Prevents other event listeners from being triggered and, /// unlike Event.stopPropagation() its effect is immediate. /// </summary> [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] new void StopImmediatePropagation(); /// <summary> ///The original target of the event, before any retargetings. </summary> [return: MarshalAs(UnmanagedType.Interface)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] new nsIDOMEventTarget GetOriginalTargetAttribute(); /// <summary> /// The explicit original target of the event. If the event was retargeted /// for some reason other than an anonymous boundary crossing, this will be set /// to the target before the retargeting occurs. For example, mouse events /// are retargeted to their parent node when they happen over text nodes (bug /// 185889), and in that case .target will show the parent and /// .explicitOriginalTarget will show the text node. /// .explicitOriginalTarget differs from .originalTarget in that it will never /// contain anonymous content. /// </summary> [return: MarshalAs(UnmanagedType.Interface)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] new nsIDOMEventTarget GetExplicitOriginalTargetAttribute(); /// <summary> /// @deprecated Use nsIDOMEvent::defaultPrevented. /// To be removed in bug 691151. /// </summary> [return: MarshalAs(UnmanagedType.U1)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] new bool GetPreventDefault(); [return: MarshalAs(UnmanagedType.U1)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] new bool GetIsTrustedAttribute(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] new void DuplicatePrivateData(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] new void SetTarget([MarshalAs(UnmanagedType.Interface)] nsIDOMEventTarget aTarget); [return: MarshalAs(UnmanagedType.U1)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] new bool IsDispatchStopped(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] new System.IntPtr GetInternalNSEvent(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] new void SetTrusted([MarshalAs(UnmanagedType.U1)] bool aTrusted); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] new void Serialize(System.IntPtr aMsg, [MarshalAs(UnmanagedType.U1)] bool aSerializeInterfaceType); [return: MarshalAs(UnmanagedType.U1)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] new bool Deserialize(System.IntPtr aMsg, ref System.IntPtr aIter); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] new void SetOwner(nsIDOMEventTarget aOwner); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] new System.IntPtr InternalDOMEvent(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] new void StopCrossProcessForwarding(); /// <summary> /// Custom string data associated with this event. /// </summary> [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] Gecko.JsVal GetDataAttribute(System.IntPtr jsContext); /// <summary> /// The origin of the site from which this event originated, which is the /// scheme, ":", and if the URI has a host, "//" followed by the /// host, and if the port is not the default for the given scheme, /// ":" followed by that port. This value does not have a trailing slash. /// </summary> [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetOriginAttribute([MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = "Gecko.CustomMarshalers.AStringMarshaler")] nsAStringBase aOrigin); /// <summary> /// The last event ID string of the event source, for server-sent DOM events; this /// value is the empty string for cross-origin messaging. /// </summary> [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetLastEventIdAttribute([MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = "Gecko.CustomMarshalers.AStringMarshaler")] nsAStringBase aLastEventId); /// <summary> /// The window which originated this event. /// </summary> [return: MarshalAs(UnmanagedType.Interface)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] nsIDOMWindow GetSourceAttribute(); /// <summary> /// Initializes this event with the given data, in a manner analogous to /// the similarly-named method on the nsIDOMEvent interface, also setting the /// data, origin, source, and lastEventId attributes of this appropriately. /// </summary> [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void InitMessageEvent([MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = "Gecko.CustomMarshalers.AStringMarshaler")] nsAStringBase aType, [MarshalAs(UnmanagedType.U1)] bool aCanBubble, [MarshalAs(UnmanagedType.U1)] bool aCancelable, ref Gecko.JsVal aData, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = "Gecko.CustomMarshalers.AStringMarshaler")] nsAStringBase aOrigin, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = "Gecko.CustomMarshalers.AStringMarshaler")] nsAStringBase aLastEventId, [MarshalAs(UnmanagedType.Interface)] nsIDOMWindow aSource); } }
50.643382
573
0.710345
[ "MIT" ]
haga-rak/Freezer
Freezer/GeckoFX/__Core/Generated/nsIDOMMessageEvent.cs
13,775
C#
using Prism.Ioc; using Prism.Ninject; using System.Configuration; using System.Windows; using Tanka.GraphQL.Sample.Chat.Client.Shared; using Tanka.GraphQL.Sample.Chat.Client.Shared.Services; using Tanka.GraphQL.Sample.Chat.Client.Wpf.Services; using Tanka.GraphQL.Sample.Chat.Client.Wpf.Views; namespace Tanka.GraphQL.Sample.Chat.Client.Wpf { public partial class App : PrismApplication { protected override Window CreateShell() { var shell = Container.Resolve<MainWindow>(); if (shell.DataContext != null && shell.DataContext is IAsyncInitializer) { (shell.DataContext as IAsyncInitializer).InitializeAsync(ConfigurationManager.AppSettings["Tanka:SignalRHubUrl"]); } return shell; } protected override void RegisterTypes(IContainerRegistry containerRegistry) { containerRegistry.RegisterSingleton<IAuthenticationService, AuthenticationService>(); containerRegistry.RegisterSingleton<IDispatcherContext, WpfDispatcherContext>(); containerRegistry.RegisterSingleton<IChatService, ChatService>(); } protected override void ConfigureServiceLocator() { base.ConfigureServiceLocator(); } } }
34.210526
130
0.693077
[ "Apache-2.0" ]
anttikajanus/tanka-graphql-net-client
sample/tanka-graphql-sample-chat-wpf/App.xaml.cs
1,302
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace IdentityEmails.Examples.WebApp.Areas.Identity.Pages.Account { [AllowAnonymous] public class ExternalLoginModel : PageModel { private readonly SignInManager<IdentityUser> _signInManager; private readonly IdentityEmailUserManager<IdentityUser> _userManager; private readonly ILogger<ExternalLoginModel> _logger; public ExternalLoginModel( SignInManager<IdentityUser> signInManager, IdentityEmailUserManager<IdentityUser> userManager, ILogger<ExternalLoginModel> logger) { _signInManager = signInManager; _userManager = userManager; _logger = logger; } [BindProperty] public InputModel Input { get; set; } public string LoginProvider { get; set; } public string ReturnUrl { get; set; } [TempData] public string ErrorMessage { get; set; } public class InputModel { [Required] [EmailAddress] public string Email { get; set; } } public IActionResult OnGetAsync() { return RedirectToPage("./Login"); } public IActionResult OnPost(string provider, string returnUrl = null) { // Request a redirect to the external login provider. var redirectUrl = Url.Page("./ExternalLogin", pageHandler: "Callback", values: new { returnUrl }); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl); return new ChallengeResult(provider, properties); } public async Task<IActionResult> OnGetCallbackAsync(string returnUrl = null, string remoteError = null) { returnUrl = returnUrl ?? Url.Content("~/"); if (remoteError != null) { ErrorMessage = $"Error from external provider: {remoteError}"; return RedirectToPage("./Login", new {ReturnUrl = returnUrl }); } var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { ErrorMessage = "Error loading external login information."; return RedirectToPage("./Login", new { ReturnUrl = returnUrl }); } // Sign in the user with this external login provider if the user already has a login. var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor : true); if (result.Succeeded) { _logger.LogInformation("{Name} logged in with {LoginProvider} provider.", info.Principal.Identity.Name, info.LoginProvider); return LocalRedirect(returnUrl); } if (result.IsLockedOut) { return RedirectToPage("./Lockout"); } else { // If the user does not have an account, then ask the user to create an account. ReturnUrl = returnUrl; LoginProvider = info.LoginProvider; if (info.Principal.HasClaim(c => c.Type == ClaimTypes.Email)) { Input = new InputModel { Email = info.Principal.FindFirstValue(ClaimTypes.Email) }; } return Page(); } } public async Task<IActionResult> OnPostConfirmationAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { ErrorMessage = "Error loading external login information during confirmation."; return RedirectToPage("./Login", new { ReturnUrl = returnUrl }); } if (ModelState.IsValid) { var user = new IdentityUser { UserName = Input.Email, Email = Input.Email }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { var email = info.Principal.Claims.FindEmail(); result = await _userManager.AddLoginAsync(user, info, email); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider); return LocalRedirect(returnUrl); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } LoginProvider = info.LoginProvider; ReturnUrl = returnUrl; return Page(); } } }
38.825175
154
0.580512
[ "MIT" ]
Logwise/IdentityEmails
Examples/IdentityEmails.Examples.WebApp/Areas/Identity/Pages/Account/ExternalLogin.cshtml.cs
5,554
C#
using UnityEngine; using System.Collections; public class GameManager : MonoBehaviour { public Transform platformGenerator; private Vector3 platformStartPoint; public PlayerController player; private Vector3 playerStartPoint; private PlatformDestroyer[] platformArr; private ScoreManager scoreManager; public DeathMenu deathScreen; void Start () { platformStartPoint = platformGenerator.position; playerStartPoint = player.transform.position; scoreManager = FindObjectOfType<ScoreManager>(); } public void RestartGame() { //StartCoroutine("RestartGameCoroutine"); scoreManager.scoreIncreasing = false; player.gameObject.SetActive(false); deathScreen.gameObject.SetActive(true); } public void Reset() { deathScreen.gameObject.SetActive(false); scoreManager.scoreIncreasing = false; player.gameObject.SetActive(false); platformArr = FindObjectsOfType<PlatformDestroyer>(); for (int i = 0; i < platformArr.Length; ++i) { platformArr[i].gameObject.SetActive(false); } player.transform.position = playerStartPoint; platformGenerator.position = platformStartPoint; player.gameObject.SetActive(true); scoreManager.scoreCounter = 0; scoreManager.scoreIncreasing = true; } }
22.725806
61
0.678495
[ "MIT" ]
mmacken42/MM_Jump
MM_Jump - Unity Project Files/Assets/Scripts/GameManager.cs
1,411
C#
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // package aes -- go2cs converted at 2020 October 09 04:53:48 UTC // import "crypto/aes" ==> using aes = go.crypto.aes_package // Original source: C:\Go\src\crypto\aes\ctr_s390x.go using cipher = go.crypto.cipher_package; using subtle = go.crypto.@internal.subtle_package; using binary = go.encoding.binary_package; using static go.builtin; namespace go { namespace crypto { public static partial class aes_package { // Assert that aesCipherAsm implements the ctrAble interface. private static ctrAble _ = (aesCipherAsm.val)(null); // xorBytes xors the contents of a and b and places the resulting values into // dst. If a and b are not the same length then the number of bytes processed // will be equal to the length of shorter of the two. Returns the number // of bytes processed. //go:noescape private static long xorBytes(slice<byte> dst, slice<byte> a, slice<byte> b) ; // streamBufferSize is the number of bytes of encrypted counter values to cache. private static readonly long streamBufferSize = (long)32L * BlockSize; private partial struct aesctr { public ptr<aesCipherAsm> block; // block cipher public array<ulong> ctr; // next value of the counter (big endian) public slice<byte> buffer; // buffer for the encrypted counter values public array<byte> storage; // array backing buffer slice } // NewCTR returns a Stream which encrypts/decrypts using the AES block // cipher in counter mode. The length of iv must be the same as BlockSize. private static cipher.Stream NewCTR(this ptr<aesCipherAsm> _addr_c, slice<byte> iv) => func((_, panic, __) => { ref aesCipherAsm c = ref _addr_c.val; if (len(iv) != BlockSize) {>>MARKER:FUNCTION_xorBytes_BLOCK_PREFIX<< panic("cipher.NewCTR: IV length must equal block size"); } ref aesctr ac = ref heap(out ptr<aesctr> _addr_ac); ac.block = c; ac.ctr[0L] = binary.BigEndian.Uint64(iv[0L..]); // high bits ac.ctr[1L] = binary.BigEndian.Uint64(iv[8L..]); // low bits ac.buffer = ac.storage[..0L]; return _addr_ac; }); private static void refill(this ptr<aesctr> _addr_c) { ref aesctr c = ref _addr_c.val; // Fill up the buffer with an incrementing count. c.buffer = c.storage[..streamBufferSize]; var c0 = c.ctr[0L]; var c1 = c.ctr[1L]; { long i = 0L; while (i < streamBufferSize) { binary.BigEndian.PutUint64(c.buffer[i + 0L..], c0); binary.BigEndian.PutUint64(c.buffer[i + 8L..], c1); // Increment in big endian: c0 is high, c1 is low. c1++; if (c1 == 0L) { // add carry c0++; i += 16L; } } } c.ctr[0L] = c0; c.ctr[1L] = c1; // Encrypt the buffer using AES in ECB mode. cryptBlocks(c.block.function, _addr_c.block.key[0L], _addr_c.buffer[0L], _addr_c.buffer[0L], streamBufferSize); } private static void XORKeyStream(this ptr<aesctr> _addr_c, slice<byte> dst, slice<byte> src) => func((_, panic, __) => { ref aesctr c = ref _addr_c.val; if (len(dst) < len(src)) { panic("crypto/cipher: output smaller than input"); } if (subtle.InexactOverlap(dst[..len(src)], src)) { panic("crypto/cipher: invalid buffer overlap"); } while (len(src) > 0L) { if (len(c.buffer) == 0L) { c.refill(); } var n = xorBytes(dst, src, c.buffer); c.buffer = c.buffer[n..]; src = src[n..]; dst = dst[n..]; } }); } }}
34.155039
126
0.537449
[ "MIT" ]
GridProtectionAlliance/go2cs
src/go-src-converted/crypto/aes/ctr_s390x.cs
4,406
C#
using System; using System.IO; using System.Linq; using FluentAssertions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.KeyPerFile; using Moq; using NUnit.Framework; namespace VH.Core.Configuration.UnitTests.TheIConfigurationBuilderExtensions { public class when_given_valid_path_string { public DirectoryInfo GenerateTempFolder() { var path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } return new DirectoryInfo(path); } [Test] public void should_not_throw_any_exceptions() { // arrange var tempFolderInfo = GenerateTempFolder(); var configBuilder = new Mock<IConfigurationBuilder>(); // act var action = new Action(() => { configBuilder.Object.AddAksKeyVaultSecretProvider(tempFolderInfo.FullName); }); // assert action.Should().NotThrow(); } [TestCase(0)] [TestCase(1)] [TestCase(2)] [TestCase(10)] public void should_add_key_per_file_for_each_file_in_folder(int numberOfFiles) { // arrange var tempFolderInfo = GenerateTempFolder(); for (var i = 0; i < numberOfFiles; i++) { var key = $"secret key {i:D2}"; var value = $"secret value {i:D2}"; var filePath = Path.Combine(tempFolderInfo.FullName, key); File.WriteAllText(filePath, value); } // act var configRoot = new ConfigurationBuilder() .AddAksKeyVaultSecretProvider(tempFolderInfo.FullName) .Build(); // assert configRoot.Providers.Count().Should().Be(1); var keyPerFileConfigurationProvider = configRoot.Providers.First(); keyPerFileConfigurationProvider.Should().BeOfType<KeyPerFileConfigurationProvider>(); for (var i = 0; i < numberOfFiles; i++) { keyPerFileConfigurationProvider.TryGet($"secret key {i:D2}", out var value); value.Should().Be($"secret value {i:D2}"); } } } }
30.679487
97
0.568742
[ "MIT" ]
hmcts/vh-common
VH.Core.Configuration.UnitTests/TheIConfigurationBuilderExtensions/when_given_valid_path_string.cs
2,393
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NLog; namespace UnderTheCursorTranslatorLibrary { public abstract class InputHook { Logger Logger; public InputCombination InputCombination { get; protected set; } public ProcessFunction ImageProcessFunction { get; protected set; } public InputHook(InputCombination inputCombination, ProcessFunction imageProcessFunction) { Logger = LogManager.GetCurrentClassLogger(); InputCombination = inputCombination; ImageProcessFunction = imageProcessFunction; } protected abstract bool CheckCombination(); protected void ImageProcessFunctionAsync() { var func = new ProcessFunction(ImageProcessFunction); func.BeginInvoke(null, null); Logger.Trace("Image Processing Function has been invoked"); } } }
20.333333
91
0.761124
[ "Apache-2.0" ]
KvanTTT/Draft-Projects
UnderTheCursorTranslator/UnderTheCursorTranslatorLibrary/InputHooking/InputHook.cs
856
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 states-2016-11-23.normal.json service model. */ using System; using System.IO; using System.Linq; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using Amazon.StepFunctions; using Amazon.StepFunctions.Model; using Amazon.StepFunctions.Model.Internal.MarshallTransformations; using Amazon.Runtime.Internal.Transform; using ServiceClientGenerator; using AWSSDK_DotNet35.UnitTests.TestTools; namespace AWSSDK_DotNet35.UnitTests.Marshalling { [TestClass] public class StepFunctionsMarshallingTests { static readonly ServiceModel service_model = Utils.LoadServiceModel("states"); [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void CreateActivityMarshallTest() { var request = InstantiateClassGenerator.Execute<CreateActivityRequest>(); var marshaller = new CreateActivityRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreateActivityRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("CreateActivity").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = CreateActivityResponseUnmarshaller.Instance.Unmarshall(context) as CreateActivityResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void CreateActivity_ActivityLimitExceededExceptionMarshallTest() { var operation = service_model.FindOperation("CreateActivity"); var request = InstantiateClassGenerator.Execute<CreateActivityRequest>(); var marshaller = new CreateActivityRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreateActivityRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("ActivityLimitExceededException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","ActivityLimitExceededException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = CreateActivityResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void CreateActivity_InvalidNameExceptionMarshallTest() { var operation = service_model.FindOperation("CreateActivity"); var request = InstantiateClassGenerator.Execute<CreateActivityRequest>(); var marshaller = new CreateActivityRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreateActivityRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidNameException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidNameException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = CreateActivityResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void CreateActivity_TooManyTagsExceptionMarshallTest() { var operation = service_model.FindOperation("CreateActivity"); var request = InstantiateClassGenerator.Execute<CreateActivityRequest>(); var marshaller = new CreateActivityRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreateActivityRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("TooManyTagsException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","TooManyTagsException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = CreateActivityResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void CreateStateMachineMarshallTest() { var request = InstantiateClassGenerator.Execute<CreateStateMachineRequest>(); var marshaller = new CreateStateMachineRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreateStateMachineRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("CreateStateMachine").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = CreateStateMachineResponseUnmarshaller.Instance.Unmarshall(context) as CreateStateMachineResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void CreateStateMachine_InvalidArnExceptionMarshallTest() { var operation = service_model.FindOperation("CreateStateMachine"); var request = InstantiateClassGenerator.Execute<CreateStateMachineRequest>(); var marshaller = new CreateStateMachineRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreateStateMachineRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidArnException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidArnException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = CreateStateMachineResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void CreateStateMachine_InvalidDefinitionExceptionMarshallTest() { var operation = service_model.FindOperation("CreateStateMachine"); var request = InstantiateClassGenerator.Execute<CreateStateMachineRequest>(); var marshaller = new CreateStateMachineRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreateStateMachineRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidDefinitionException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidDefinitionException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = CreateStateMachineResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void CreateStateMachine_InvalidLoggingConfigurationExceptionMarshallTest() { var operation = service_model.FindOperation("CreateStateMachine"); var request = InstantiateClassGenerator.Execute<CreateStateMachineRequest>(); var marshaller = new CreateStateMachineRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreateStateMachineRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidLoggingConfigurationException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidLoggingConfigurationException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = CreateStateMachineResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void CreateStateMachine_InvalidNameExceptionMarshallTest() { var operation = service_model.FindOperation("CreateStateMachine"); var request = InstantiateClassGenerator.Execute<CreateStateMachineRequest>(); var marshaller = new CreateStateMachineRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreateStateMachineRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidNameException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidNameException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = CreateStateMachineResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void CreateStateMachine_InvalidTracingConfigurationExceptionMarshallTest() { var operation = service_model.FindOperation("CreateStateMachine"); var request = InstantiateClassGenerator.Execute<CreateStateMachineRequest>(); var marshaller = new CreateStateMachineRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreateStateMachineRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidTracingConfigurationException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidTracingConfigurationException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = CreateStateMachineResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void CreateStateMachine_StateMachineAlreadyExistsExceptionMarshallTest() { var operation = service_model.FindOperation("CreateStateMachine"); var request = InstantiateClassGenerator.Execute<CreateStateMachineRequest>(); var marshaller = new CreateStateMachineRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreateStateMachineRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("StateMachineAlreadyExistsException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","StateMachineAlreadyExistsException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = CreateStateMachineResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void CreateStateMachine_StateMachineDeletingExceptionMarshallTest() { var operation = service_model.FindOperation("CreateStateMachine"); var request = InstantiateClassGenerator.Execute<CreateStateMachineRequest>(); var marshaller = new CreateStateMachineRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreateStateMachineRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("StateMachineDeletingException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","StateMachineDeletingException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = CreateStateMachineResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void CreateStateMachine_StateMachineLimitExceededExceptionMarshallTest() { var operation = service_model.FindOperation("CreateStateMachine"); var request = InstantiateClassGenerator.Execute<CreateStateMachineRequest>(); var marshaller = new CreateStateMachineRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreateStateMachineRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("StateMachineLimitExceededException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","StateMachineLimitExceededException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = CreateStateMachineResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void CreateStateMachine_StateMachineTypeNotSupportedExceptionMarshallTest() { var operation = service_model.FindOperation("CreateStateMachine"); var request = InstantiateClassGenerator.Execute<CreateStateMachineRequest>(); var marshaller = new CreateStateMachineRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreateStateMachineRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("StateMachineTypeNotSupportedException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","StateMachineTypeNotSupportedException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = CreateStateMachineResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void CreateStateMachine_TooManyTagsExceptionMarshallTest() { var operation = service_model.FindOperation("CreateStateMachine"); var request = InstantiateClassGenerator.Execute<CreateStateMachineRequest>(); var marshaller = new CreateStateMachineRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<CreateStateMachineRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("TooManyTagsException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","TooManyTagsException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = CreateStateMachineResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void DeleteActivityMarshallTest() { var request = InstantiateClassGenerator.Execute<DeleteActivityRequest>(); var marshaller = new DeleteActivityRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DeleteActivityRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DeleteActivity").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DeleteActivityResponseUnmarshaller.Instance.Unmarshall(context) as DeleteActivityResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void DeleteActivity_InvalidArnExceptionMarshallTest() { var operation = service_model.FindOperation("DeleteActivity"); var request = InstantiateClassGenerator.Execute<DeleteActivityRequest>(); var marshaller = new DeleteActivityRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DeleteActivityRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidArnException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidArnException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = DeleteActivityResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void DeleteStateMachineMarshallTest() { var request = InstantiateClassGenerator.Execute<DeleteStateMachineRequest>(); var marshaller = new DeleteStateMachineRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DeleteStateMachineRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DeleteStateMachine").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DeleteStateMachineResponseUnmarshaller.Instance.Unmarshall(context) as DeleteStateMachineResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void DeleteStateMachine_InvalidArnExceptionMarshallTest() { var operation = service_model.FindOperation("DeleteStateMachine"); var request = InstantiateClassGenerator.Execute<DeleteStateMachineRequest>(); var marshaller = new DeleteStateMachineRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DeleteStateMachineRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidArnException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidArnException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = DeleteStateMachineResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void DescribeActivityMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeActivityRequest>(); var marshaller = new DescribeActivityRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeActivityRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeActivity").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeActivityResponseUnmarshaller.Instance.Unmarshall(context) as DescribeActivityResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void DescribeActivity_ActivityDoesNotExistExceptionMarshallTest() { var operation = service_model.FindOperation("DescribeActivity"); var request = InstantiateClassGenerator.Execute<DescribeActivityRequest>(); var marshaller = new DescribeActivityRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeActivityRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("ActivityDoesNotExistException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","ActivityDoesNotExistException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = DescribeActivityResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void DescribeActivity_InvalidArnExceptionMarshallTest() { var operation = service_model.FindOperation("DescribeActivity"); var request = InstantiateClassGenerator.Execute<DescribeActivityRequest>(); var marshaller = new DescribeActivityRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeActivityRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidArnException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidArnException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = DescribeActivityResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void DescribeExecutionMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeExecutionRequest>(); var marshaller = new DescribeExecutionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeExecutionRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeExecution").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeExecutionResponseUnmarshaller.Instance.Unmarshall(context) as DescribeExecutionResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void DescribeExecution_ExecutionDoesNotExistExceptionMarshallTest() { var operation = service_model.FindOperation("DescribeExecution"); var request = InstantiateClassGenerator.Execute<DescribeExecutionRequest>(); var marshaller = new DescribeExecutionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeExecutionRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("ExecutionDoesNotExistException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","ExecutionDoesNotExistException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = DescribeExecutionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void DescribeExecution_InvalidArnExceptionMarshallTest() { var operation = service_model.FindOperation("DescribeExecution"); var request = InstantiateClassGenerator.Execute<DescribeExecutionRequest>(); var marshaller = new DescribeExecutionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeExecutionRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidArnException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidArnException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = DescribeExecutionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void DescribeStateMachineMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeStateMachineRequest>(); var marshaller = new DescribeStateMachineRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeStateMachineRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeStateMachine").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeStateMachineResponseUnmarshaller.Instance.Unmarshall(context) as DescribeStateMachineResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void DescribeStateMachine_InvalidArnExceptionMarshallTest() { var operation = service_model.FindOperation("DescribeStateMachine"); var request = InstantiateClassGenerator.Execute<DescribeStateMachineRequest>(); var marshaller = new DescribeStateMachineRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeStateMachineRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidArnException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidArnException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = DescribeStateMachineResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void DescribeStateMachine_StateMachineDoesNotExistExceptionMarshallTest() { var operation = service_model.FindOperation("DescribeStateMachine"); var request = InstantiateClassGenerator.Execute<DescribeStateMachineRequest>(); var marshaller = new DescribeStateMachineRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeStateMachineRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("StateMachineDoesNotExistException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","StateMachineDoesNotExistException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = DescribeStateMachineResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void DescribeStateMachineForExecutionMarshallTest() { var request = InstantiateClassGenerator.Execute<DescribeStateMachineForExecutionRequest>(); var marshaller = new DescribeStateMachineForExecutionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeStateMachineForExecutionRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeStateMachineForExecution").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = DescribeStateMachineForExecutionResponseUnmarshaller.Instance.Unmarshall(context) as DescribeStateMachineForExecutionResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void DescribeStateMachineForExecution_ExecutionDoesNotExistExceptionMarshallTest() { var operation = service_model.FindOperation("DescribeStateMachineForExecution"); var request = InstantiateClassGenerator.Execute<DescribeStateMachineForExecutionRequest>(); var marshaller = new DescribeStateMachineForExecutionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeStateMachineForExecutionRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("ExecutionDoesNotExistException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","ExecutionDoesNotExistException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = DescribeStateMachineForExecutionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void DescribeStateMachineForExecution_InvalidArnExceptionMarshallTest() { var operation = service_model.FindOperation("DescribeStateMachineForExecution"); var request = InstantiateClassGenerator.Execute<DescribeStateMachineForExecutionRequest>(); var marshaller = new DescribeStateMachineForExecutionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<DescribeStateMachineForExecutionRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidArnException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidArnException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = DescribeStateMachineForExecutionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void GetActivityTaskMarshallTest() { var request = InstantiateClassGenerator.Execute<GetActivityTaskRequest>(); var marshaller = new GetActivityTaskRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<GetActivityTaskRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("GetActivityTask").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = GetActivityTaskResponseUnmarshaller.Instance.Unmarshall(context) as GetActivityTaskResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void GetActivityTask_ActivityDoesNotExistExceptionMarshallTest() { var operation = service_model.FindOperation("GetActivityTask"); var request = InstantiateClassGenerator.Execute<GetActivityTaskRequest>(); var marshaller = new GetActivityTaskRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<GetActivityTaskRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("ActivityDoesNotExistException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","ActivityDoesNotExistException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = GetActivityTaskResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void GetActivityTask_ActivityWorkerLimitExceededExceptionMarshallTest() { var operation = service_model.FindOperation("GetActivityTask"); var request = InstantiateClassGenerator.Execute<GetActivityTaskRequest>(); var marshaller = new GetActivityTaskRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<GetActivityTaskRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("ActivityWorkerLimitExceededException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","ActivityWorkerLimitExceededException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = GetActivityTaskResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void GetActivityTask_InvalidArnExceptionMarshallTest() { var operation = service_model.FindOperation("GetActivityTask"); var request = InstantiateClassGenerator.Execute<GetActivityTaskRequest>(); var marshaller = new GetActivityTaskRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<GetActivityTaskRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidArnException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidArnException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = GetActivityTaskResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void GetExecutionHistoryMarshallTest() { var request = InstantiateClassGenerator.Execute<GetExecutionHistoryRequest>(); var marshaller = new GetExecutionHistoryRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<GetExecutionHistoryRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("GetExecutionHistory").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = GetExecutionHistoryResponseUnmarshaller.Instance.Unmarshall(context) as GetExecutionHistoryResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void GetExecutionHistory_ExecutionDoesNotExistExceptionMarshallTest() { var operation = service_model.FindOperation("GetExecutionHistory"); var request = InstantiateClassGenerator.Execute<GetExecutionHistoryRequest>(); var marshaller = new GetExecutionHistoryRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<GetExecutionHistoryRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("ExecutionDoesNotExistException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","ExecutionDoesNotExistException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = GetExecutionHistoryResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void GetExecutionHistory_InvalidArnExceptionMarshallTest() { var operation = service_model.FindOperation("GetExecutionHistory"); var request = InstantiateClassGenerator.Execute<GetExecutionHistoryRequest>(); var marshaller = new GetExecutionHistoryRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<GetExecutionHistoryRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidArnException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidArnException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = GetExecutionHistoryResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void GetExecutionHistory_InvalidTokenExceptionMarshallTest() { var operation = service_model.FindOperation("GetExecutionHistory"); var request = InstantiateClassGenerator.Execute<GetExecutionHistoryRequest>(); var marshaller = new GetExecutionHistoryRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<GetExecutionHistoryRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidTokenException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidTokenException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = GetExecutionHistoryResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void ListActivitiesMarshallTest() { var request = InstantiateClassGenerator.Execute<ListActivitiesRequest>(); var marshaller = new ListActivitiesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ListActivitiesRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ListActivities").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = ListActivitiesResponseUnmarshaller.Instance.Unmarshall(context) as ListActivitiesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void ListActivities_InvalidTokenExceptionMarshallTest() { var operation = service_model.FindOperation("ListActivities"); var request = InstantiateClassGenerator.Execute<ListActivitiesRequest>(); var marshaller = new ListActivitiesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ListActivitiesRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidTokenException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidTokenException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = ListActivitiesResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void ListExecutionsMarshallTest() { var request = InstantiateClassGenerator.Execute<ListExecutionsRequest>(); var marshaller = new ListExecutionsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ListExecutionsRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ListExecutions").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = ListExecutionsResponseUnmarshaller.Instance.Unmarshall(context) as ListExecutionsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void ListExecutions_InvalidArnExceptionMarshallTest() { var operation = service_model.FindOperation("ListExecutions"); var request = InstantiateClassGenerator.Execute<ListExecutionsRequest>(); var marshaller = new ListExecutionsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ListExecutionsRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidArnException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidArnException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = ListExecutionsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void ListExecutions_InvalidTokenExceptionMarshallTest() { var operation = service_model.FindOperation("ListExecutions"); var request = InstantiateClassGenerator.Execute<ListExecutionsRequest>(); var marshaller = new ListExecutionsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ListExecutionsRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidTokenException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidTokenException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = ListExecutionsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void ListExecutions_StateMachineDoesNotExistExceptionMarshallTest() { var operation = service_model.FindOperation("ListExecutions"); var request = InstantiateClassGenerator.Execute<ListExecutionsRequest>(); var marshaller = new ListExecutionsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ListExecutionsRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("StateMachineDoesNotExistException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","StateMachineDoesNotExistException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = ListExecutionsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void ListExecutions_StateMachineTypeNotSupportedExceptionMarshallTest() { var operation = service_model.FindOperation("ListExecutions"); var request = InstantiateClassGenerator.Execute<ListExecutionsRequest>(); var marshaller = new ListExecutionsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ListExecutionsRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("StateMachineTypeNotSupportedException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","StateMachineTypeNotSupportedException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = ListExecutionsResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void ListStateMachinesMarshallTest() { var request = InstantiateClassGenerator.Execute<ListStateMachinesRequest>(); var marshaller = new ListStateMachinesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ListStateMachinesRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ListStateMachines").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = ListStateMachinesResponseUnmarshaller.Instance.Unmarshall(context) as ListStateMachinesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void ListStateMachines_InvalidTokenExceptionMarshallTest() { var operation = service_model.FindOperation("ListStateMachines"); var request = InstantiateClassGenerator.Execute<ListStateMachinesRequest>(); var marshaller = new ListStateMachinesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ListStateMachinesRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidTokenException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidTokenException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = ListStateMachinesResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void ListTagsForResourceMarshallTest() { var request = InstantiateClassGenerator.Execute<ListTagsForResourceRequest>(); var marshaller = new ListTagsForResourceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ListTagsForResourceRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ListTagsForResource").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = ListTagsForResourceResponseUnmarshaller.Instance.Unmarshall(context) as ListTagsForResourceResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void ListTagsForResource_InvalidArnExceptionMarshallTest() { var operation = service_model.FindOperation("ListTagsForResource"); var request = InstantiateClassGenerator.Execute<ListTagsForResourceRequest>(); var marshaller = new ListTagsForResourceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ListTagsForResourceRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidArnException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidArnException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = ListTagsForResourceResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void ListTagsForResource_ResourceNotFoundExceptionMarshallTest() { var operation = service_model.FindOperation("ListTagsForResource"); var request = InstantiateClassGenerator.Execute<ListTagsForResourceRequest>(); var marshaller = new ListTagsForResourceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<ListTagsForResourceRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("ResourceNotFoundException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","ResourceNotFoundException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = ListTagsForResourceResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void SendTaskFailureMarshallTest() { var request = InstantiateClassGenerator.Execute<SendTaskFailureRequest>(); var marshaller = new SendTaskFailureRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<SendTaskFailureRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("SendTaskFailure").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = SendTaskFailureResponseUnmarshaller.Instance.Unmarshall(context) as SendTaskFailureResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void SendTaskFailure_InvalidTokenExceptionMarshallTest() { var operation = service_model.FindOperation("SendTaskFailure"); var request = InstantiateClassGenerator.Execute<SendTaskFailureRequest>(); var marshaller = new SendTaskFailureRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<SendTaskFailureRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidTokenException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidTokenException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = SendTaskFailureResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void SendTaskFailure_TaskDoesNotExistExceptionMarshallTest() { var operation = service_model.FindOperation("SendTaskFailure"); var request = InstantiateClassGenerator.Execute<SendTaskFailureRequest>(); var marshaller = new SendTaskFailureRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<SendTaskFailureRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("TaskDoesNotExistException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","TaskDoesNotExistException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = SendTaskFailureResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void SendTaskFailure_TaskTimedOutExceptionMarshallTest() { var operation = service_model.FindOperation("SendTaskFailure"); var request = InstantiateClassGenerator.Execute<SendTaskFailureRequest>(); var marshaller = new SendTaskFailureRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<SendTaskFailureRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("TaskTimedOutException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","TaskTimedOutException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = SendTaskFailureResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void SendTaskHeartbeatMarshallTest() { var request = InstantiateClassGenerator.Execute<SendTaskHeartbeatRequest>(); var marshaller = new SendTaskHeartbeatRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<SendTaskHeartbeatRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("SendTaskHeartbeat").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = SendTaskHeartbeatResponseUnmarshaller.Instance.Unmarshall(context) as SendTaskHeartbeatResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void SendTaskHeartbeat_InvalidTokenExceptionMarshallTest() { var operation = service_model.FindOperation("SendTaskHeartbeat"); var request = InstantiateClassGenerator.Execute<SendTaskHeartbeatRequest>(); var marshaller = new SendTaskHeartbeatRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<SendTaskHeartbeatRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidTokenException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidTokenException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = SendTaskHeartbeatResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void SendTaskHeartbeat_TaskDoesNotExistExceptionMarshallTest() { var operation = service_model.FindOperation("SendTaskHeartbeat"); var request = InstantiateClassGenerator.Execute<SendTaskHeartbeatRequest>(); var marshaller = new SendTaskHeartbeatRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<SendTaskHeartbeatRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("TaskDoesNotExistException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","TaskDoesNotExistException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = SendTaskHeartbeatResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void SendTaskHeartbeat_TaskTimedOutExceptionMarshallTest() { var operation = service_model.FindOperation("SendTaskHeartbeat"); var request = InstantiateClassGenerator.Execute<SendTaskHeartbeatRequest>(); var marshaller = new SendTaskHeartbeatRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<SendTaskHeartbeatRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("TaskTimedOutException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","TaskTimedOutException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = SendTaskHeartbeatResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void SendTaskSuccessMarshallTest() { var request = InstantiateClassGenerator.Execute<SendTaskSuccessRequest>(); var marshaller = new SendTaskSuccessRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<SendTaskSuccessRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("SendTaskSuccess").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = SendTaskSuccessResponseUnmarshaller.Instance.Unmarshall(context) as SendTaskSuccessResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void SendTaskSuccess_InvalidOutputExceptionMarshallTest() { var operation = service_model.FindOperation("SendTaskSuccess"); var request = InstantiateClassGenerator.Execute<SendTaskSuccessRequest>(); var marshaller = new SendTaskSuccessRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<SendTaskSuccessRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidOutputException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidOutputException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = SendTaskSuccessResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void SendTaskSuccess_InvalidTokenExceptionMarshallTest() { var operation = service_model.FindOperation("SendTaskSuccess"); var request = InstantiateClassGenerator.Execute<SendTaskSuccessRequest>(); var marshaller = new SendTaskSuccessRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<SendTaskSuccessRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidTokenException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidTokenException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = SendTaskSuccessResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void SendTaskSuccess_TaskDoesNotExistExceptionMarshallTest() { var operation = service_model.FindOperation("SendTaskSuccess"); var request = InstantiateClassGenerator.Execute<SendTaskSuccessRequest>(); var marshaller = new SendTaskSuccessRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<SendTaskSuccessRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("TaskDoesNotExistException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","TaskDoesNotExistException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = SendTaskSuccessResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void SendTaskSuccess_TaskTimedOutExceptionMarshallTest() { var operation = service_model.FindOperation("SendTaskSuccess"); var request = InstantiateClassGenerator.Execute<SendTaskSuccessRequest>(); var marshaller = new SendTaskSuccessRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<SendTaskSuccessRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("TaskTimedOutException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","TaskTimedOutException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = SendTaskSuccessResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void StartExecutionMarshallTest() { var request = InstantiateClassGenerator.Execute<StartExecutionRequest>(); var marshaller = new StartExecutionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<StartExecutionRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("StartExecution").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = StartExecutionResponseUnmarshaller.Instance.Unmarshall(context) as StartExecutionResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void StartExecution_ExecutionAlreadyExistsExceptionMarshallTest() { var operation = service_model.FindOperation("StartExecution"); var request = InstantiateClassGenerator.Execute<StartExecutionRequest>(); var marshaller = new StartExecutionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<StartExecutionRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("ExecutionAlreadyExistsException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","ExecutionAlreadyExistsException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = StartExecutionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void StartExecution_ExecutionLimitExceededExceptionMarshallTest() { var operation = service_model.FindOperation("StartExecution"); var request = InstantiateClassGenerator.Execute<StartExecutionRequest>(); var marshaller = new StartExecutionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<StartExecutionRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("ExecutionLimitExceededException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","ExecutionLimitExceededException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = StartExecutionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void StartExecution_InvalidArnExceptionMarshallTest() { var operation = service_model.FindOperation("StartExecution"); var request = InstantiateClassGenerator.Execute<StartExecutionRequest>(); var marshaller = new StartExecutionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<StartExecutionRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidArnException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidArnException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = StartExecutionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void StartExecution_InvalidExecutionInputExceptionMarshallTest() { var operation = service_model.FindOperation("StartExecution"); var request = InstantiateClassGenerator.Execute<StartExecutionRequest>(); var marshaller = new StartExecutionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<StartExecutionRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidExecutionInputException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidExecutionInputException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = StartExecutionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void StartExecution_InvalidNameExceptionMarshallTest() { var operation = service_model.FindOperation("StartExecution"); var request = InstantiateClassGenerator.Execute<StartExecutionRequest>(); var marshaller = new StartExecutionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<StartExecutionRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidNameException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidNameException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = StartExecutionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void StartExecution_StateMachineDeletingExceptionMarshallTest() { var operation = service_model.FindOperation("StartExecution"); var request = InstantiateClassGenerator.Execute<StartExecutionRequest>(); var marshaller = new StartExecutionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<StartExecutionRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("StateMachineDeletingException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","StateMachineDeletingException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = StartExecutionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void StartExecution_StateMachineDoesNotExistExceptionMarshallTest() { var operation = service_model.FindOperation("StartExecution"); var request = InstantiateClassGenerator.Execute<StartExecutionRequest>(); var marshaller = new StartExecutionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<StartExecutionRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("StateMachineDoesNotExistException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","StateMachineDoesNotExistException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = StartExecutionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void StartSyncExecutionMarshallTest() { var request = InstantiateClassGenerator.Execute<StartSyncExecutionRequest>(); var marshaller = new StartSyncExecutionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<StartSyncExecutionRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("StartSyncExecution").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = StartSyncExecutionResponseUnmarshaller.Instance.Unmarshall(context) as StartSyncExecutionResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void StartSyncExecution_InvalidArnExceptionMarshallTest() { var operation = service_model.FindOperation("StartSyncExecution"); var request = InstantiateClassGenerator.Execute<StartSyncExecutionRequest>(); var marshaller = new StartSyncExecutionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<StartSyncExecutionRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidArnException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidArnException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = StartSyncExecutionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void StartSyncExecution_InvalidExecutionInputExceptionMarshallTest() { var operation = service_model.FindOperation("StartSyncExecution"); var request = InstantiateClassGenerator.Execute<StartSyncExecutionRequest>(); var marshaller = new StartSyncExecutionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<StartSyncExecutionRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidExecutionInputException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidExecutionInputException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = StartSyncExecutionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void StartSyncExecution_InvalidNameExceptionMarshallTest() { var operation = service_model.FindOperation("StartSyncExecution"); var request = InstantiateClassGenerator.Execute<StartSyncExecutionRequest>(); var marshaller = new StartSyncExecutionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<StartSyncExecutionRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidNameException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidNameException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = StartSyncExecutionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void StartSyncExecution_StateMachineDeletingExceptionMarshallTest() { var operation = service_model.FindOperation("StartSyncExecution"); var request = InstantiateClassGenerator.Execute<StartSyncExecutionRequest>(); var marshaller = new StartSyncExecutionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<StartSyncExecutionRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("StateMachineDeletingException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","StateMachineDeletingException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = StartSyncExecutionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void StartSyncExecution_StateMachineDoesNotExistExceptionMarshallTest() { var operation = service_model.FindOperation("StartSyncExecution"); var request = InstantiateClassGenerator.Execute<StartSyncExecutionRequest>(); var marshaller = new StartSyncExecutionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<StartSyncExecutionRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("StateMachineDoesNotExistException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","StateMachineDoesNotExistException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = StartSyncExecutionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void StartSyncExecution_StateMachineTypeNotSupportedExceptionMarshallTest() { var operation = service_model.FindOperation("StartSyncExecution"); var request = InstantiateClassGenerator.Execute<StartSyncExecutionRequest>(); var marshaller = new StartSyncExecutionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<StartSyncExecutionRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("StateMachineTypeNotSupportedException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","StateMachineTypeNotSupportedException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = StartSyncExecutionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void StopExecutionMarshallTest() { var request = InstantiateClassGenerator.Execute<StopExecutionRequest>(); var marshaller = new StopExecutionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<StopExecutionRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("StopExecution").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = StopExecutionResponseUnmarshaller.Instance.Unmarshall(context) as StopExecutionResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void StopExecution_ExecutionDoesNotExistExceptionMarshallTest() { var operation = service_model.FindOperation("StopExecution"); var request = InstantiateClassGenerator.Execute<StopExecutionRequest>(); var marshaller = new StopExecutionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<StopExecutionRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("ExecutionDoesNotExistException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","ExecutionDoesNotExistException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = StopExecutionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void StopExecution_InvalidArnExceptionMarshallTest() { var operation = service_model.FindOperation("StopExecution"); var request = InstantiateClassGenerator.Execute<StopExecutionRequest>(); var marshaller = new StopExecutionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<StopExecutionRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidArnException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidArnException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = StopExecutionResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void TagResourceMarshallTest() { var request = InstantiateClassGenerator.Execute<TagResourceRequest>(); var marshaller = new TagResourceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<TagResourceRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("TagResource").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = TagResourceResponseUnmarshaller.Instance.Unmarshall(context) as TagResourceResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void TagResource_InvalidArnExceptionMarshallTest() { var operation = service_model.FindOperation("TagResource"); var request = InstantiateClassGenerator.Execute<TagResourceRequest>(); var marshaller = new TagResourceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<TagResourceRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidArnException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidArnException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = TagResourceResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void TagResource_ResourceNotFoundExceptionMarshallTest() { var operation = service_model.FindOperation("TagResource"); var request = InstantiateClassGenerator.Execute<TagResourceRequest>(); var marshaller = new TagResourceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<TagResourceRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("ResourceNotFoundException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","ResourceNotFoundException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = TagResourceResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void TagResource_TooManyTagsExceptionMarshallTest() { var operation = service_model.FindOperation("TagResource"); var request = InstantiateClassGenerator.Execute<TagResourceRequest>(); var marshaller = new TagResourceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<TagResourceRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("TooManyTagsException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","TooManyTagsException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = TagResourceResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void UntagResourceMarshallTest() { var request = InstantiateClassGenerator.Execute<UntagResourceRequest>(); var marshaller = new UntagResourceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<UntagResourceRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("UntagResource").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = UntagResourceResponseUnmarshaller.Instance.Unmarshall(context) as UntagResourceResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void UntagResource_InvalidArnExceptionMarshallTest() { var operation = service_model.FindOperation("UntagResource"); var request = InstantiateClassGenerator.Execute<UntagResourceRequest>(); var marshaller = new UntagResourceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<UntagResourceRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidArnException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidArnException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = UntagResourceResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void UntagResource_ResourceNotFoundExceptionMarshallTest() { var operation = service_model.FindOperation("UntagResource"); var request = InstantiateClassGenerator.Execute<UntagResourceRequest>(); var marshaller = new UntagResourceRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<UntagResourceRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("ResourceNotFoundException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","ResourceNotFoundException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = UntagResourceResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void UpdateStateMachineMarshallTest() { var request = InstantiateClassGenerator.Execute<UpdateStateMachineRequest>(); var marshaller = new UpdateStateMachineRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<UpdateStateMachineRequest>(request,jsonRequest); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("UpdateStateMachine").ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()); UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse); var response = UpdateStateMachineResponseUnmarshaller.Instance.Unmarshall(context) as UpdateStateMachineResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void UpdateStateMachine_InvalidArnExceptionMarshallTest() { var operation = service_model.FindOperation("UpdateStateMachine"); var request = InstantiateClassGenerator.Execute<UpdateStateMachineRequest>(); var marshaller = new UpdateStateMachineRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<UpdateStateMachineRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidArnException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidArnException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = UpdateStateMachineResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void UpdateStateMachine_InvalidDefinitionExceptionMarshallTest() { var operation = service_model.FindOperation("UpdateStateMachine"); var request = InstantiateClassGenerator.Execute<UpdateStateMachineRequest>(); var marshaller = new UpdateStateMachineRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<UpdateStateMachineRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidDefinitionException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidDefinitionException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = UpdateStateMachineResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void UpdateStateMachine_InvalidLoggingConfigurationExceptionMarshallTest() { var operation = service_model.FindOperation("UpdateStateMachine"); var request = InstantiateClassGenerator.Execute<UpdateStateMachineRequest>(); var marshaller = new UpdateStateMachineRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<UpdateStateMachineRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidLoggingConfigurationException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidLoggingConfigurationException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = UpdateStateMachineResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void UpdateStateMachine_InvalidTracingConfigurationExceptionMarshallTest() { var operation = service_model.FindOperation("UpdateStateMachine"); var request = InstantiateClassGenerator.Execute<UpdateStateMachineRequest>(); var marshaller = new UpdateStateMachineRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<UpdateStateMachineRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("InvalidTracingConfigurationException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","InvalidTracingConfigurationException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = UpdateStateMachineResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void UpdateStateMachine_MissingRequiredParameterExceptionMarshallTest() { var operation = service_model.FindOperation("UpdateStateMachine"); var request = InstantiateClassGenerator.Execute<UpdateStateMachineRequest>(); var marshaller = new UpdateStateMachineRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<UpdateStateMachineRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("MissingRequiredParameterException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","MissingRequiredParameterException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = UpdateStateMachineResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void UpdateStateMachine_StateMachineDeletingExceptionMarshallTest() { var operation = service_model.FindOperation("UpdateStateMachine"); var request = InstantiateClassGenerator.Execute<UpdateStateMachineRequest>(); var marshaller = new UpdateStateMachineRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<UpdateStateMachineRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("StateMachineDeletingException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","StateMachineDeletingException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = UpdateStateMachineResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Json")] [TestCategory("StepFunctions")] public void UpdateStateMachine_StateMachineDoesNotExistExceptionMarshallTest() { var operation = service_model.FindOperation("UpdateStateMachine"); var request = InstantiateClassGenerator.Execute<UpdateStateMachineRequest>(); var marshaller = new UpdateStateMachineRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content); Comparer.CompareObjectToJson<UpdateStateMachineRequest>(request,jsonRequest); var exception = operation.Exceptions.First(e => e.Name.Equals("StateMachineDoesNotExistException")); var jsonResponse = new JsonSampleGenerator(service_model, exception).Execute(); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"}, {"x-amzn-ErrorType","StateMachineDoesNotExistException"}, {"Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString()} } }; var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), true, webResponse, true); var response = UpdateStateMachineResponseUnmarshaller.Instance.UnmarshallException(context, null, System.Net.HttpStatusCode.OK); InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } } }
51.601913
163
0.652556
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/test/Services/StepFunctions/UnitTests/Generated/Marshalling/StepFunctionsMarshallingTests.cs
156,457
C#
// cs3005-8.cs: Identifier `II.Foo()' differing only in case is not CLS-compliant // Line: 9 // Compiler options: -warnaserror using System; [assembly:CLSCompliant(true)] public interface II { int Foo(); int foo { get; } }
20.083333
81
0.655602
[ "MIT" ]
zlxy/Genesis-3D
Engine/extlibs/IosLibs/mono-2.6.7/mcs/errors/cs3005-8.cs
241
C#
using System; using System.Text; using Application.Common.Interfaces; using Infrastructure.Identity; using Infrastructure.Persistence; using Infrastructure.Services; using Infrastructure.Services.Handlers; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Tokens; namespace Infrastructure { public static class DependencyInjection { public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)//, IWebHostEnvironment environment) { if (configuration.GetValue<bool>("UseInMemoryDatabase")) { services.AddDbContext<ApplicationDbContext>(options => options.UseInMemoryDatabase("WebMotorsDb")); } else { services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer( configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName))); } services.AddScoped<IApplicationDbContext>(provider => provider.GetService<ApplicationDbContext>()); services.AddDefaultIdentity<ApplicationUser>() .AddRoles<IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>(); services.AddIdentityServer() .AddApiAuthorization<ApplicationUser, ApplicationDbContext>(); services.AddHttpClient("webmotors-api", c => { c.BaseAddress = new Uri(configuration.GetSection("WebMotorsApi:Url").Value); c.DefaultRequestHeaders.Add(configuration.GetSection("WebMotorsApi:Key:Key").Value, configuration.GetSection("WebMotorsApi:Key:Value").Value); c.DefaultRequestHeaders.Add(configuration.GetSection("WebMotorsApi:Host:Key").Value, configuration.GetSection("WebMotorsApi:Host:Value").Value); }); services.AddTransient<IHttpClientHandler, HttpClientHandler>(); services.AddTransient<IDateTime, DateTimeService>(); services.AddTransient<IIdentityService, IdentityService>(); services.AddTransient<IWebmotorsService, WebMotorsService>(); services.AddTransient<ITokenService, TokenService>(); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.SaveToken = true; options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuer = true, ValidateAudience = true, ValidAudience = configuration["JWT:ValidAudience"], ValidIssuer = configuration["JWT:ValidIssuer"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JWT:Secret"])) }; }) .AddIdentityServerJwt(); return services; } } }
43.705882
160
0.641454
[ "MIT" ]
ntitsolutins01/TesteWebMotors
src/Common/Infrastructure/DependencyInjection.cs
3,717
C#