content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FakeGravity : MonoBehaviour { private Rigidbody rb; private void Awake() { rb = GetComponent<Rigidbody>(); } private void Update() { FakeGrav(); } private void FakeGrav() { rb.velocity += Vector3.down; } }
12.166667
42
0.613699
[ "Apache-2.0" ]
bruno-pLima/PandoraPlayers
Controllers/FakeGravity.cs
367
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; using Yandex.Maps.StaticAPI; using Yandex.Maps.StaticAPI.PT; namespace YandexMapsStaticApiTest.PT { [TestFixture] class FlagTest { double lat = 53.1565165498; double lon = 93.5611612361; [Test] public void PtFlagGetPartUrlDefault() { Flag Flag = new Flag(lat, lon); string result = $"{Flag.Lon.ToString().Replace(',', '.')}" + $",{Flag.Lat.ToString().Replace(',', '.')}," + $"flag"; Assert.AreEqual(result, Flag.GetPartUrl()); } } }
22.870968
72
0.586742
[ "Apache-2.0" ]
RakEG/Yandex.Maps.StaticAPI
Tests/Yandex.Maps.StaticAPITest/PT/FlagTest.cs
711
C#
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. using BenchmarkDotNet.Attributes; using SixLabors.ImageSharp.Formats.Jpeg.Components.Decoder.ColorConverters; namespace SixLabors.ImageSharp.Benchmarks.Codecs.Jpeg { [Config(typeof(Config.ShortMultiFramework))] public class CmykColorConversion : ColorConversionBenchmark { public CmykColorConversion() : base(4) { } [Benchmark(Baseline = true)] public void Scalar() { var values = new JpegColorConverter.ComponentValues(this.Input, 0); new JpegColorConverter.FromCmykBasic(8).ConvertToRgbInplace(values); } [Benchmark] public void SimdVector8() { var values = new JpegColorConverter.ComponentValues(this.Input, 0); new JpegColorConverter.FromCmykVector8(8).ConvertToRgbInplace(values); } [Benchmark] public void SimdVectorAvx2() { var values = new JpegColorConverter.ComponentValues(this.Input, 0); new JpegColorConverter.FromCmykAvx2(8).ConvertToRgbInplace(values); } } }
28.119048
82
0.651143
[ "Apache-2.0" ]
SixLabors/ImageSharp
tests/ImageSharp.Benchmarks/Codecs/Jpeg/CmykColorConversion.cs
1,181
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("KeesTalksTech Utility Pack")] [assembly: AssemblyDescription("Utility package with useful and less useful buidling blocks.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("KeesTalksTech")] [assembly: AssemblyProduct("Utility Pack")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("b4831004-64d0-4137-b289-70cec983a035")] // 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("0.3.*")] [assembly: AssemblyFileVersion("1.0.0.0")]
40.055556
95
0.74896
[ "MIT" ]
KeesCBakker/KeesTalksTech-Utility-Pack
KeesTalksTech-Utility-Pack/KeesTalksTech.Utilities/Properties/AssemblyInfo.cs
1,445
C#
using System.Collections.Generic; using System.Dynamic; namespace Dorkari.Helpers.Core.Utilities { public class DynamicHelper { public static ExpandoObject CreateExpando(IEnumerable<KeyValuePair<string, object>> propertyValues) { IDictionary<string, object> dynamicObject = new ExpandoObject(); foreach (var item in propertyValues) { dynamicObject[item.Key] = item.Value; } return (ExpandoObject)dynamicObject; } } }
27.947368
107
0.634652
[ "Apache-2.0" ]
chakrabar/Dorkari
Dorkari.Helpers.Core/Utilities/DynamicHelper.cs
533
C#
using System; using NetOffice; using NetOffice.Attributes; namespace NetOffice.WordApi.Enums { /// <summary> /// SupportByVersion Word 12, 14, 15, 16 /// </summary> ///<remarks> MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff191740.aspx </remarks> [SupportByVersion("Word", 12,14,15,16)] [EntityType(EntityType.IsEnum)] public enum WdCellColor { /// <summary> /// SupportByVersion Word 12, 14, 15, 16 /// </summary> /// <remarks>-1</remarks> [SupportByVersion("Word", 12,14,15,16)] wdCellColorByAuthor = -1, /// <summary> /// SupportByVersion Word 12, 14, 15, 16 /// </summary> /// <remarks>0</remarks> [SupportByVersion("Word", 12,14,15,16)] wdCellColorNoHighlight = 0, /// <summary> /// SupportByVersion Word 12, 14, 15, 16 /// </summary> /// <remarks>1</remarks> [SupportByVersion("Word", 12,14,15,16)] wdCellColorPink = 1, /// <summary> /// SupportByVersion Word 12, 14, 15, 16 /// </summary> /// <remarks>2</remarks> [SupportByVersion("Word", 12,14,15,16)] wdCellColorLightBlue = 2, /// <summary> /// SupportByVersion Word 12, 14, 15, 16 /// </summary> /// <remarks>3</remarks> [SupportByVersion("Word", 12,14,15,16)] wdCellColorLightYellow = 3, /// <summary> /// SupportByVersion Word 12, 14, 15, 16 /// </summary> /// <remarks>4</remarks> [SupportByVersion("Word", 12,14,15,16)] wdCellColorLightPurple = 4, /// <summary> /// SupportByVersion Word 12, 14, 15, 16 /// </summary> /// <remarks>5</remarks> [SupportByVersion("Word", 12,14,15,16)] wdCellColorLightOrange = 5, /// <summary> /// SupportByVersion Word 12, 14, 15, 16 /// </summary> /// <remarks>6</remarks> [SupportByVersion("Word", 12,14,15,16)] wdCellColorLightGreen = 6, /// <summary> /// SupportByVersion Word 12, 14, 15, 16 /// </summary> /// <remarks>7</remarks> [SupportByVersion("Word", 12,14,15,16)] wdCellColorLightGray = 7 } }
26.246753
119
0.615042
[ "MIT" ]
DominikPalo/NetOffice
Source/Word/Enums/WdCellColor.cs
2,023
C#
namespace MyFitnessApp.Web.Controllers { using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using MyFitnessApp.Services.Data.Exercise; using MyFitnessApp.Web.Filters; using MyFitnessApp.Web.ViewModels.Exercises; [Authorize] [TypeFilter(typeof(RestrictBannedUsersAttribute))] [TypeFilter(typeof(RestrictUsersWithoutProfileAttribute))] public class ExercisesController : Controller { private readonly IExercisesService exercisesService; public ExercisesController(IExercisesService exercisesService) { this.exercisesService = exercisesService; } [HttpGet] public IActionResult Create() { var viewModel = new CreateExerciseInputModel(); viewModel.Categories = this.exercisesService.GetExerciseCategories(); viewModel.Equipments = this.exercisesService.GetExerciseEquipments(); return this.View(viewModel); } [HttpPost] public async Task<IActionResult> Create(CreateExerciseInputModel model) { if (!this.ModelState.IsValid) { model.Categories = this.exercisesService.GetExerciseCategories(); model.Equipments = this.exercisesService.GetExerciseEquipments(); return this.View(model); } var userId = this.User.GetId(); await this.exercisesService.CreateExcerciseAsync(model, userId); this.TempData["Message"] = "Exercise created successfully."; return this.RedirectToAction("All", "Exercises"); } [HttpGet] public IActionResult All(int id = 1) { const int itemsPerPage = 6; var view = new AllExercisesViewModel { PageNumber = id, Exercises = this.exercisesService.GetAllExercises(id, itemsPerPage), ItemsCount = this.exercisesService.GetCounts(), ItemsPerPage = itemsPerPage, }; return this.View(view); } [HttpGet] public IActionResult Add(int id) { var viewNodel = this.exercisesService.GetExerciseById(id); return this.View(viewNodel); } [HttpPost] public async Task<IActionResult> Add(AddExerciseInputModel model, int id) { if (!this.ModelState.IsValid) { var viewNodel = this.exercisesService.GetExerciseById(id); return this.View(viewNodel); } var userId = this.User.GetId(); await this.exercisesService.AddExerciseToUserAsync(model, userId); var dayOfWeek = model.WeekDay.ToString(); this.TempData["Message"] = "Exercise added to my diary."; return this.RedirectToAction(dayOfWeek, "ExerciseDiary"); } [HttpGet] public IActionResult Categories() { return this.View(); } [HttpPost] public async Task<IActionResult> Remove(int id, string day) { var userId = this.User.GetId(); await this.exercisesService.RemoveExerciseAsync(userId, id); return this.Redirect($"/ExerciseDiary/{day}"); } } }
31.607477
84
0.602898
[ "MIT" ]
GeorgiGradev/MyFitnessApp
MyFitnessApp/Web/MyFitnessApp.Web/Controllers/ExercisesController.cs
3,384
C#
// #define USING_HASH_SET // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: SortedSet ** ** Purpose: A generic sorted set. ** ** Date: August 15, 2008 ** ===========================================================*/ namespace ME.ECS.Collections { using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.Serialization; using System.Collections; using System.Collections.Generic; unsafe internal class BitHelper { // should not be serialized private const byte MarkedBitFlag = 1; private const byte IntSize = 32; // m_length of underlying int array (not logical bit array) private int m_length; // ptr to stack alloc'd array of ints [System.Security.SecurityCritical] private int* m_arrayPtr; // array of ints private int[] m_array; // whether to operate on stack alloc'd or heap alloc'd array private bool useStackAlloc; /// <summary> /// Instantiates a BitHelper with a heap alloc'd array of ints /// </summary> /// <param name="bitArray">int array to hold bits</param> /// <param name="length">length of int array</param> // <SecurityKernel Critical="True" Ring="0"> // <UsesUnsafeCode Name="Field: m_arrayPtr" /> // <UsesUnsafeCode Name="Parameter bitArrayPtr of type: Int32*" /> // </SecurityKernel> [System.Security.SecurityCritical] internal BitHelper(int* bitArrayPtr, int length) { this.m_arrayPtr = bitArrayPtr; this.m_length = length; useStackAlloc = true; } /// <summary> /// Instantiates a BitHelper with a heap alloc'd array of ints /// </summary> /// <param name="bitArray">int array to hold bits</param> /// <param name="length">length of int array</param> internal BitHelper(int[] bitArray, int length) { this.m_array = bitArray; this.m_length = length; } /// <summary> /// Mark bit at specified position /// </summary> /// <param name="bitPosition"></param> // <SecurityKernel Critical="True" Ring="0"> // <UsesUnsafeCode Name="Field: m_arrayPtr" /> // </SecurityKernel> [System.Security.SecurityCritical] internal unsafe void MarkBit(int bitPosition) { if (useStackAlloc) { int bitArrayIndex = bitPosition / IntSize; if (bitArrayIndex < m_length && bitArrayIndex >= 0) { m_arrayPtr[bitArrayIndex] |= (MarkedBitFlag << (bitPosition % IntSize)); } } else { int bitArrayIndex = bitPosition / IntSize; if (bitArrayIndex < m_length && bitArrayIndex >= 0) { m_array[bitArrayIndex] |= (MarkedBitFlag << (bitPosition % IntSize)); } } } /// <summary> /// Is bit at specified position marked? /// </summary> /// <param name="bitPosition"></param> /// <returns></returns> // <SecurityKernel Critical="True" Ring="0"> // <UsesUnsafeCode Name="Field: m_arrayPtr" /> // </SecurityKernel> [System.Security.SecurityCritical] internal unsafe bool IsMarked(int bitPosition) { if (useStackAlloc) { int bitArrayIndex = bitPosition / IntSize; if (bitArrayIndex < m_length && bitArrayIndex >= 0) { return ((m_arrayPtr[bitArrayIndex] & (MarkedBitFlag << (bitPosition % IntSize))) != 0); } return false; } else { int bitArrayIndex = bitPosition / IntSize; if (bitArrayIndex < m_length && bitArrayIndex >= 0) { return ((m_array[bitArrayIndex] & (MarkedBitFlag << (bitPosition % IntSize))) != 0); } return false; } } /// <summary> /// How many ints must be allocated to represent n bits. Returns (n+31)/32, but /// avoids overflow /// </summary> /// <param name="n"></param> /// <returns></returns> internal static int ToIntArrayLength(int n) { return n > 0 ? ((n - 1) / IntSize + 1) : 0; } } // // A binary search tree is a red-black tree if it satisfies the following red-black properties: // 1. Every node is either red or black // 2. Every leaf (nil node) is black // 3. If a node is red, then both its children are black // 4. Every simple path from a node to a descendant leaf contains the same number of black nodes // // The basic idea of red-black tree is to represent 2-3-4 trees as standard BSTs but to add one extra bit of information // per node to encode 3-nodes and 4-nodes. // 4-nodes will be represented as: B // R R // 3 -node will be represented as: B or B // R B B R // // For a detailed description of the algorithm, take a look at "Algorithms" by Robert Sedgewick. // internal delegate bool TreeWalkPredicate<T>(SortedSetCopyable<T>.Node node); internal enum TreeRotation { LeftRotation = 1, RightRotation = 2, RightLeftRotation = 3, LeftRightRotation = 4, } [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "by design name choice")] [DebuggerDisplay("Count = {Count}")] #if ECS_COMPILE_IL2CPP_OPTIONS [Unity.IL2CPP.CompilerServices.Il2CppSetOptionAttribute(Unity.IL2CPP.CompilerServices.Option.NullChecks, false)] [Unity.IL2CPP.CompilerServices.Il2CppSetOptionAttribute(Unity.IL2CPP.CompilerServices.Option.ArrayBoundsChecks, false)] [Unity.IL2CPP.CompilerServices.Il2CppSetOptionAttribute(Unity.IL2CPP.CompilerServices.Option.DivideByZeroChecks, false)] #endif #if !FEATURE_NETCORE [Serializable] public class SortedSetCopyable<T> : ISet<T>, ICollection<T>, ICollection, ISerializable, IDeserializationCallback, IPoolableRecycle { #else public class SortedSetCopyable<T> : ISet<T>, ICollection<T>, ICollection { #endif //!FEATURE_NETCORE #region local variables/constants Node root; IComparer<T> comparer; int count; int version; private Object _syncRoot; private const String ComparerName = "Comparer"; private const String CountName = "Count"; private const String ItemsName = "Items"; private const String VersionName = "Version"; //needed for enumerator private const String TreeName = "Tree"; private const String NodeValueName = "Item"; private const String EnumStartName = "EnumStarted"; private const String ReverseName = "Reverse"; private const String EnumVersionName = "EnumVersion"; #if !FEATURE_NETCORE //needed for TreeSubset private const String minName = "Min"; private const String maxName = "Max"; private const String lBoundActiveName = "lBoundActive"; private const String uBoundActiveName = "uBoundActive"; private SerializationInfo siInfo; //A temporary variable which we need during deserialization. #endif internal const int StackAllocThreshold = 100; #endregion public void OnRecycle() { this.count = default; this.version = default; this._syncRoot = default; this.RecycleNodes(ref this.root); } public void CopyFrom(SortedSetCopyable<T> other) { this.RecycleNodes(ref root); // these are explicit type checks in the mould of HashSet. It would have worked better // with something like an ISorted<T> (we could make this work for SortedList.Keys etc) SortedSetCopyable<T> baseSortedSet = other as SortedSetCopyable<T>; //SortedSetCopyable<T> baseTreeSubSet = other as TreeSubSet; //if (baseSortedSet != null && baseTreeSubSet == null && AreComparersEqual(this, baseSortedSet)) { //breadth first traversal to recreate nodes if (baseSortedSet.Count == 0) { count = 0; version = 0; root = null; return; } //pre order way to replicate nodes Stack<Node> theirStack = PoolStack<SortedSetCopyable<T>.Node>.Spawn(2 * log2(baseSortedSet.Count) + 2); Stack<Node> myStack = PoolStack<SortedSetCopyable<T>.Node>.Spawn(2 * log2(baseSortedSet.Count) + 2); Node theirCurrent = baseSortedSet.root; Node myCurrent = (theirCurrent != null ? new SortedSetCopyable<T>.Node(theirCurrent.Item, theirCurrent.IsRed) : null); root = myCurrent; while (theirCurrent != null) { theirStack.Push(theirCurrent); myStack.Push(myCurrent); myCurrent.Left = (theirCurrent.Left != null ? SortedSetCopyable<T>.Node.Spawn(theirCurrent.Left.Item, theirCurrent.Left.IsRed) : null); theirCurrent = theirCurrent.Left; myCurrent = myCurrent.Left; } while (theirStack.Count != 0) { theirCurrent = theirStack.Pop(); myCurrent = myStack.Pop(); Node theirRight = theirCurrent.Right; Node myRight = null; if (theirRight != null) { myRight = SortedSetCopyable<T>.Node.Spawn(theirRight.Item, theirRight.IsRed); } myCurrent.Right = myRight; while (theirRight != null) { theirStack.Push(theirRight); myStack.Push(myRight); myRight.Left = (theirRight.Left != null ? SortedSetCopyable<T>.Node.Spawn(theirRight.Left.Item, theirRight.Left.IsRed) : null); theirRight = theirRight.Left; myRight = myRight.Left; } } PoolStack<SortedSetCopyable<T>.Node>.Recycle(ref myStack); PoolStack<SortedSetCopyable<T>.Node>.Recycle(ref theirStack); count = baseSortedSet.count; version = 0; //} //this.RecycleNodes(ref this.root); //this.CopyNodes(ref this.root, other.root); this.count = other.count; this.version = other.version; this._syncRoot = other._syncRoot; } private void RecycleNodes(ref Node node) { if (node == null) return; var current = node.Left; while (current != null) { var next = current.Left; PoolClass<Node>.Recycle(ref current); current = next; } current = node.Right; while (current != null) { var next = current.Right; PoolClass<Node>.Recycle(ref current); current = next; } PoolClass<Node>.Recycle(ref node); } /*private void CopyNodes(ref Node root, Node otherRoot) { if (otherRoot == null) { root = null; return; } root = PoolClass<Node>.Spawn(); root.Item = otherRoot.Item; root.IsRed = otherRoot.IsRed; var current = otherRoot.Left; var rootNode = root; while (current != null) { var next = current.Left; { var node = PoolClass<Node>.Spawn(); node.Item = current.Item; node.IsRed = current.IsRed; rootNode.Left = node; rootNode = node; } current = next; } current = otherRoot.Right; rootNode = root; while (current != null) { var next = current.Right; { var node = PoolClass<Node>.Spawn(); node.Item = current.Item; node.IsRed = current.IsRed; rootNode.Right = node; rootNode = node; } current = next; } }*/ #region Constructors public SortedSetCopyable() { this.comparer = Comparer<T>.Default; } public SortedSetCopyable(IComparer<T> comparer) { if (comparer == null) { this.comparer = Comparer<T>.Default; } else { this.comparer = comparer; } } public SortedSetCopyable(IEnumerable<T> collection) : this(collection, Comparer<T>.Default) { } public SortedSetCopyable(IEnumerable<T> collection, IComparer<T> comparer) : this(comparer) { if (collection == null) { throw new ArgumentNullException("collection"); } // these are explicit type checks in the mould of HashSet. It would have worked better // with something like an ISorted<T> (we could make this work for SortedList.Keys etc) SortedSetCopyable<T> baseSortedSet = collection as SortedSetCopyable<T>; SortedSetCopyable<T> baseTreeSubSet = collection as TreeSubSet; if (baseSortedSet != null && baseTreeSubSet == null && AreComparersEqual(this, baseSortedSet)) { //breadth first traversal to recreate nodes if (baseSortedSet.Count == 0) { count = 0; version = 0; root = null; return; } //pre order way to replicate nodes Stack<Node> theirStack = new Stack<SortedSetCopyable<T>.Node>(2 * log2(baseSortedSet.Count) + 2); Stack<Node> myStack = new Stack<SortedSetCopyable<T>.Node>(2 * log2(baseSortedSet.Count) + 2); Node theirCurrent = baseSortedSet.root; Node myCurrent = (theirCurrent != null ? new SortedSetCopyable<T>.Node(theirCurrent.Item, theirCurrent.IsRed) : null); root = myCurrent; while (theirCurrent != null) { theirStack.Push(theirCurrent); myStack.Push(myCurrent); myCurrent.Left = (theirCurrent.Left != null ? new SortedSetCopyable<T>.Node(theirCurrent.Left.Item, theirCurrent.Left.IsRed) : null); theirCurrent = theirCurrent.Left; myCurrent = myCurrent.Left; } while (theirStack.Count != 0) { theirCurrent = theirStack.Pop(); myCurrent = myStack.Pop(); Node theirRight = theirCurrent.Right; Node myRight = null; if (theirRight != null) { myRight = new SortedSetCopyable<T>.Node(theirRight.Item, theirRight.IsRed); } myCurrent.Right = myRight; while (theirRight != null) { theirStack.Push(theirRight); myStack.Push(myRight); myRight.Left = (theirRight.Left != null ? new SortedSetCopyable<T>.Node(theirRight.Left.Item, theirRight.Left.IsRed) : null); theirRight = theirRight.Left; myRight = myRight.Left; } } count = baseSortedSet.count; version = 0; } else { //As it stands, you're doing an NlogN sort of the collection List<T> els = new List<T>(collection); els.Sort(this.comparer); for (int i = 1; i < els.Count; i++) { if (comparer.Compare(els[i], els[i - 1]) == 0) { els.RemoveAt(i); i--; } } root = ConstructRootFromSortedArray(els.ToArray(), 0, els.Count - 1, null); count = els.Count; version = 0; } } #if !FEATURE_NETCORE protected SortedSetCopyable(SerializationInfo info, StreamingContext context) { siInfo = info; } #endif #endregion #region Bulk Operation Helpers private void AddAllElements(IEnumerable<T> collection) { foreach (T item in collection) { if (!this.Contains(item)) Add(item); } } private void RemoveAllElements(IEnumerable<T> collection) { T min = this.Min; T max = this.Max; foreach (T item in collection) { if (!(comparer.Compare(item, min) < 0 || comparer.Compare(item, max) > 0) && this.Contains(item)) this.Remove(item); } } private bool ContainsAllElements(IEnumerable<T> collection) { foreach (T item in collection) { if (!this.Contains(item)) { return false; } } return true; } // // Do a in order walk on tree and calls the delegate for each node. // If the action delegate returns false, stop the walk. // // Return true if the entire tree has been walked. // Otherwise returns false. // internal bool InOrderTreeWalk(TreeWalkPredicate<T> action) { return InOrderTreeWalk(action, false); } // Allows for the change in traversal direction. Reverse visits nodes in descending order internal virtual bool InOrderTreeWalk(TreeWalkPredicate<T> action, bool reverse) { if (root == null) { return true; } // The maximum height of a red-black tree is 2*lg(n+1). // See page 264 of "Introduction to algorithms" by Thomas H. Cormen // note: this should be logbase2, but since the stack grows itself, we // don't want the extra cost Stack<Node> stack = new Stack<Node>(2 * (int)(SortedSetCopyable<T>.log2(Count + 1))); Node current = root; while (current != null) { stack.Push(current); current = (reverse ? current.Right : current.Left); } while (stack.Count != 0) { current = stack.Pop(); if (!action(current)) { return false; } Node node = (reverse ? current.Left : current.Right); while (node != null) { stack.Push(node); node = (reverse ? node.Right : node.Left); } } return true; } // // Do a left to right breadth first walk on tree and // calls the delegate for each node. // If the action delegate returns false, stop the walk. // // Return true if the entire tree has been walked. // Otherwise returns false. // internal virtual bool BreadthFirstTreeWalk(TreeWalkPredicate<T> action) { if (root == null) { return true; } List<Node> processQueue = new List<Node>(); processQueue.Add(root); Node current; while (processQueue.Count != 0) { current = processQueue[0]; processQueue.RemoveAt(0); if (!action(current)) { return false; } if (current.Left != null) { processQueue.Add(current.Left); } if (current.Right != null) { processQueue.Add(current.Right); } } return true; } #endregion #region Properties public int Count { get { VersionCheck(); return count; } } public IComparer<T> Comparer { get { return comparer; } } bool ICollection<T>.IsReadOnly { get { return false; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (_syncRoot == null) { System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null); } return _syncRoot; } } #endregion #region Subclass helpers //virtual function for subclass that needs to update count internal virtual void VersionCheck() { } //virtual function for subclass that needs to do range checks internal virtual bool IsWithinRange(T item) { return true; } #endregion #region ICollection<T> Members /// <summary> /// Add the value ITEM to the tree, returns true if added, false if duplicate /// </summary> /// <param name="item">item to be added</param> public bool Add(T item) { return AddIfNotPresent(item); } void ICollection<T>.Add(T item) { AddIfNotPresent(item); } /// <summary> /// Adds ITEM to the tree if not already present. Returns TRUE if value was successfully added /// or FALSE if it is a duplicate /// </summary> internal virtual bool AddIfNotPresent(T item) { if (root == null) { // empty tree root = Node.Spawn(item, false); count = 1; version++; return true; } // // Search for a node at bottom to insert the new node. // If we can guanratee the node we found is not a 4-node, it would be easy to do insertion. // We split 4-nodes along the search path. // Node current = root; Node parent = null; Node grandParent = null; Node greatGrandParent = null; //even if we don't actually add to the set, we may be altering its structure (by doing rotations //and such). so update version to disable any enumerators/subsets working on it version++; int order = 0; while (current != null) { order = comparer.Compare(item, current.Item); if (order == 0) { // We could have changed root node to red during the search process. // We need to set it to black before we return. root.IsRed = false; return false; } // split a 4-node into two 2-nodes if (Is4Node(current)) { Split4Node(current); // We could have introduced two consecutive red nodes after split. Fix that by rotation. if (IsRed(parent)) { InsertionBalance(current, ref parent, grandParent, greatGrandParent); } } greatGrandParent = grandParent; grandParent = parent; parent = current; current = (order < 0) ? current.Left : current.Right; } Debug.Assert(parent != null, "Parent node cannot be null here!"); // ready to insert the new node Node node = Node.Spawn(item); if (order > 0) { parent.Right = node; } else { parent.Left = node; } // the new node will be red, so we will need to adjust the colors if parent node is also red if (parent.IsRed) { InsertionBalance(node, ref parent, grandParent, greatGrandParent); } // Root node is always black root.IsRed = false; ++count; return true; } /// <summary> /// Remove the T ITEM from this SortedSet. Returns true if successfully removed. /// </summary> /// <param name="item"></param> /// <returns></returns> public bool Remove(T item) { return this.DoRemove(item); // hack so it can be made non-virtual } internal virtual bool DoRemove(T item) { if (root == null) { return false; } // Search for a node and then find its succesor. // Then copy the item from the succesor to the matching node and delete the successor. // If a node doesn't have a successor, we can replace it with its left child (if not empty.) // or delete the matching node. // // In top-down implementation, it is important to make sure the node to be deleted is not a 2-node. // Following code will make sure the node on the path is not a 2 Node. //even if we don't actually remove from the set, we may be altering its structure (by doing rotations //and such). so update version to disable any enumerators/subsets working on it version++; Node current = root; Node parent = null; Node grandParent = null; Node match = null; Node parentOfMatch = null; bool foundMatch = false; while (current != null) { if (Is2Node(current)) { // fix up 2-Node if (parent == null) { // current is root. Mark it as red current.IsRed = true; } else { Node sibling = GetSibling(current, parent); if (sibling.IsRed) { // If parent is a 3-node, flip the orientation of the red link. // We can acheive this by a single rotation // This case is converted to one of other cased below. Debug.Assert(!parent.IsRed, "parent must be a black node!"); if (parent.Right == sibling) { RotateLeft(parent); } else { RotateRight(parent); } parent.IsRed = true; sibling.IsRed = false; // parent's color // sibling becomes child of grandParent or root after rotation. Update link from grandParent or root ReplaceChildOfNodeOrRoot(grandParent, parent, sibling); // sibling will become grandParent of current node grandParent = sibling; if (parent == match) { parentOfMatch = sibling; } // update sibling, this is necessary for following processing sibling = (parent.Left == current) ? parent.Right : parent.Left; } Debug.Assert(sibling != null && sibling.IsRed == false, "sibling must not be null and it must be black!"); if (Is2Node(sibling)) { Merge2Nodes(parent, current, sibling); } else { // current is a 2-node and sibling is either a 3-node or a 4-node. // We can change the color of current to red by some rotation. TreeRotation rotation = RotationNeeded(parent, current, sibling); Node newGrandParent = null; switch (rotation) { case TreeRotation.RightRotation: Debug.Assert(parent.Left == sibling, "sibling must be left child of parent!"); Debug.Assert(sibling.Left.IsRed, "Left child of sibling must be red!"); sibling.Left.IsRed = false; newGrandParent = RotateRight(parent); break; case TreeRotation.LeftRotation: Debug.Assert(parent.Right == sibling, "sibling must be left child of parent!"); Debug.Assert(sibling.Right.IsRed, "Right child of sibling must be red!"); sibling.Right.IsRed = false; newGrandParent = RotateLeft(parent); break; case TreeRotation.RightLeftRotation: Debug.Assert(parent.Right == sibling, "sibling must be left child of parent!"); Debug.Assert(sibling.Left.IsRed, "Left child of sibling must be red!"); newGrandParent = RotateRightLeft(parent); break; case TreeRotation.LeftRightRotation: Debug.Assert(parent.Left == sibling, "sibling must be left child of parent!"); Debug.Assert(sibling.Right.IsRed, "Right child of sibling must be red!"); newGrandParent = RotateLeftRight(parent); break; } newGrandParent.IsRed = parent.IsRed; parent.IsRed = false; current.IsRed = true; ReplaceChildOfNodeOrRoot(grandParent, parent, newGrandParent); if (parent == match) { parentOfMatch = newGrandParent; } grandParent = newGrandParent; } } } // we don't need to compare any more once we found the match int order = foundMatch ? -1 : comparer.Compare(item, current.Item); if (order == 0) { // save the matching node foundMatch = true; match = current; parentOfMatch = parent; } grandParent = parent; parent = current; if (order < 0) { current = current.Left; } else { current = current.Right; // continue the search in right sub tree after we find a match } } // move successor to the matching node position and replace links if (match != null) { ReplaceNode(match, parentOfMatch, parent, grandParent); --count; } if (root != null) { root.IsRed = false; } return foundMatch; } public virtual void Clear() { PoolClass<Node>.Recycle(ref root); root = null; count = 0; ++version; } public virtual bool Contains(T item) { return FindNode(item) != null; } public void CopyTo(T[] array) { CopyTo(array, 0, Count); } public void CopyTo(T[] array, int index) { CopyTo(array, index, Count); } public void CopyTo(T[] array, int index, int count) { // will array, starting at arrayIndex, be able to hold elements? Note: not // checking arrayIndex >= array.Length (consistency with list of allowing // count of 0; subsequent check takes care of the rest) //upper bound count += index; Stack<Node> stack = PoolStack<Node>.Spawn(2 * (int)(SortedSetCopyable<T>.log2(Count + 1))); Node current = root; while (current != null) { stack.Push(current); current = current.Left; } while (stack.Count != 0) { current = stack.Pop(); if (index >= count) { return; } array[index++] = current.Item; Node node = current.Right; while (node != null) { stack.Push(node); node = node.Left; } } PoolStack<Node>.Recycle(ref stack); /*InOrderTreeWalk(delegate(Node node) { if (index >= count) { return false; } else { array[index++] = node.Item; return true; } });*/ } void ICollection.CopyTo(Array array, int index) { T[] tarray = array as T[]; if (tarray != null) { CopyTo(tarray, index); } else { object[] objects = array as object[]; InOrderTreeWalk(delegate(Node node) { objects[index++] = node.Item; return true; }); } } #endregion #region IEnumerable<T> members public Enumerator GetEnumerator() { return new Enumerator(this); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(this); } #endregion #region Tree Specific Operations private static Node GetSibling(Node node, Node parent) { if (parent.Left == node) { return parent.Right; } return parent.Left; } // After calling InsertionBalance, we need to make sure current and parent up-to-date. // It doesn't matter if we keep grandParent and greatGrantParent up-to-date // because we won't need to split again in the next node. // By the time we need to split again, everything will be correctly set. // private void InsertionBalance(Node current, ref Node parent, Node grandParent, Node greatGrandParent) { Debug.Assert(grandParent != null, "Grand parent cannot be null here!"); bool parentIsOnRight = (grandParent.Right == parent); bool currentIsOnRight = (parent.Right == current); Node newChildOfGreatGrandParent; if (parentIsOnRight == currentIsOnRight) { // same orientation, single rotation newChildOfGreatGrandParent = currentIsOnRight ? RotateLeft(grandParent) : RotateRight(grandParent); } else { // different orientaton, double rotation newChildOfGreatGrandParent = currentIsOnRight ? RotateLeftRight(grandParent) : RotateRightLeft(grandParent); // current node now becomes the child of greatgrandparent parent = greatGrandParent; } // grand parent will become a child of either parent of current. grandParent.IsRed = true; newChildOfGreatGrandParent.IsRed = false; ReplaceChildOfNodeOrRoot(greatGrandParent, grandParent, newChildOfGreatGrandParent); } private static bool Is2Node(Node node) { Debug.Assert(node != null, "node cannot be null!"); return IsBlack(node) && IsNullOrBlack(node.Left) && IsNullOrBlack(node.Right); } private static bool Is4Node(Node node) { return IsRed(node.Left) && IsRed(node.Right); } private static bool IsBlack(Node node) { return (node != null && !node.IsRed); } private static bool IsNullOrBlack(Node node) { return (node == null || !node.IsRed); } private static bool IsRed(Node node) { return (node != null && node.IsRed); } private static void Merge2Nodes(Node parent, Node child1, Node child2) { Debug.Assert(IsRed(parent), "parent must be be red"); // combing two 2-nodes into a 4-node parent.IsRed = false; child1.IsRed = true; child2.IsRed = true; } // Replace the child of a parent node. // If the parent node is null, replace the root. private void ReplaceChildOfNodeOrRoot(Node parent, Node child, Node newChild) { if (parent != null) { if (parent.Left == child) { parent.Left = newChild; } else { parent.Right = newChild; } } else { root = newChild; } } // Replace the matching node with its succesor. private void ReplaceNode(Node match, Node parentOfMatch, Node succesor, Node parentOfSuccesor) { if (succesor == match) { // this node has no successor, should only happen if right child of matching node is null. Debug.Assert(match.Right == null, "Right child must be null!"); succesor = match.Left; } else { Debug.Assert(parentOfSuccesor != null, "parent of successor cannot be null!"); Debug.Assert(succesor.Left == null, "Left child of succesor must be null!"); Debug.Assert((succesor.Right == null && succesor.IsRed) || (succesor.Right.IsRed && !succesor.IsRed), "Succesor must be in valid state"); if (succesor.Right != null) { succesor.Right.IsRed = false; } if (parentOfSuccesor != match) { // detach succesor from its parent and set its right child parentOfSuccesor.Left = succesor.Right; succesor.Right = match.Right; } succesor.Left = match.Left; } if (succesor != null) { succesor.IsRed = match.IsRed; } ReplaceChildOfNodeOrRoot(parentOfMatch, match, succesor); } internal virtual Node FindNode(T item) { Node current = root; while (current != null) { int order = comparer.Compare(item, current.Item); if (order == 0) { return current; } else { current = (order < 0) ? current.Left : current.Right; } } return null; } //used for bithelpers. Note that this implementation is completely different //from the Subset's. The two should not be mixed. This indexes as if the tree were an array. //http://en.wikipedia.org/wiki/Binary_Tree#Methods_for_storing_binary_trees internal virtual int InternalIndexOf(T item) { Node current = root; int count = 0; while (current != null) { int order = comparer.Compare(item, current.Item); if (order == 0) { return count; } else { current = (order < 0) ? current.Left : current.Right; count = (order < 0) ? (2 * count + 1) : (2 * count + 2); } } return -1; } internal Node FindRange(T from, T to) { return FindRange(from, to, true, true); } internal Node FindRange(T from, T to, bool lowerBoundActive, bool upperBoundActive) { Node current = root; while (current != null) { if (lowerBoundActive && comparer.Compare(from, current.Item) > 0) { current = current.Right; } else { if (upperBoundActive && comparer.Compare(to, current.Item) < 0) { current = current.Left; } else { return current; } } } return null; } internal void UpdateVersion() { ++version; } private static Node RotateLeft(Node node) { Node x = node.Right; node.Right = x.Left; x.Left = node; return x; } private static Node RotateLeftRight(Node node) { Node child = node.Left; Node grandChild = child.Right; node.Left = grandChild.Right; grandChild.Right = node; child.Right = grandChild.Left; grandChild.Left = child; return grandChild; } private static Node RotateRight(Node node) { Node x = node.Left; node.Left = x.Right; x.Right = node; return x; } private static Node RotateRightLeft(Node node) { Node child = node.Right; Node grandChild = child.Left; node.Right = grandChild.Left; grandChild.Left = node; child.Left = grandChild.Right; grandChild.Right = child; return grandChild; } /// <summary> /// Testing counter that can track rotations /// </summary> private static TreeRotation RotationNeeded(Node parent, Node current, Node sibling) { Debug.Assert(IsRed(sibling.Left) || IsRed(sibling.Right), "sibling must have at least one red child"); if (IsRed(sibling.Left)) { if (parent.Left == current) { return TreeRotation.RightLeftRotation; } return TreeRotation.RightRotation; } else { if (parent.Left == current) { return TreeRotation.LeftRotation; } return TreeRotation.LeftRightRotation; } } /// <summary> /// Used for deep equality of SortedSet testing /// </summary> /// <returns></returns> public static IEqualityComparer<SortedSetCopyable<T>> CreateSetComparer() { return new SortedSetEqualityComparer<T>(); } /// <summary> /// Create a new set comparer for this set, where this set's members' equality is defined by the /// memberEqualityComparer. Note that this equality comparer's definition of equality must be the /// same as this set's Comparer's definition of equality /// </summary> public static IEqualityComparer<SortedSetCopyable<T>> CreateSetComparer(IEqualityComparer<T> memberEqualityComparer) { return new SortedSetEqualityComparer<T>(memberEqualityComparer); } /// <summary> /// Decides whether these sets are the same, given the comparer. If the EC's are the same, we can /// just use SetEquals, but if they aren't then we have to manually check with the given comparer /// </summary> internal static bool SortedSetEquals(SortedSetCopyable<T> set1, SortedSetCopyable<T> set2, IComparer<T> comparer) { // handle null cases first if (set1 == null) { return (set2 == null); } else if (set2 == null) { // set1 != null return false; } if (AreComparersEqual(set1, set2)) { if (set1.Count != set2.Count) return false; return set1.SetEquals(set2); } else { bool found = false; foreach (T item1 in set1) { found = false; foreach (T item2 in set2) { if (comparer.Compare(item1, item2) == 0) { found = true; break; } } if (!found) return false; } return true; } } //This is a little frustrating because we can't support more sorted structures private static bool AreComparersEqual(SortedSetCopyable<T> set1, SortedSetCopyable<T> set2) { return set1.Comparer.Equals(set2.Comparer); } private static void Split4Node(Node node) { node.IsRed = true; node.Left.IsRed = false; node.Right.IsRed = false; } /// <summary> /// Copies this to an array. Used for DebugView /// </summary> /// <returns></returns> internal T[] ToArray() { T[] newArray = new T[Count]; CopyTo(newArray); return newArray; } #endregion #region ISet Members /// <summary> /// Transform this set into its union with the IEnumerable OTHER ///Attempts to insert each element and rejects it if it exists. /// NOTE: The caller object is important as UnionWith uses the Comparator ///associated with THIS to check equality /// Throws ArgumentNullException if OTHER is null /// </summary> /// <param name="other"></param> public void UnionWith(IEnumerable<T> other) { if (other == null) { throw new ArgumentNullException("other"); } SortedSetCopyable<T> s = other as SortedSetCopyable<T>; TreeSubSet t = this as TreeSubSet; if (t != null) VersionCheck(); if (s != null && t == null && this.count == 0) { SortedSetCopyable<T> dummy = new SortedSetCopyable<T>(s, this.comparer); this.root = dummy.root; this.count = dummy.count; this.version++; return; } if (s != null && t == null && AreComparersEqual(this, s) && (s.Count > this.Count / 2)) { //this actually hurts if N is much greater than M the /2 is arbitrary //first do a merge sort to an array. T[] merged = new T[s.Count + this.Count]; int c = 0; Enumerator mine = this.GetEnumerator(); Enumerator theirs = s.GetEnumerator(); bool mineEnded = !mine.MoveNext(), theirsEnded = !theirs.MoveNext(); while (!mineEnded && !theirsEnded) { int comp = Comparer.Compare(mine.Current, theirs.Current); if (comp < 0) { merged[c++] = mine.Current; mineEnded = !mine.MoveNext(); } else if (comp == 0) { merged[c++] = theirs.Current; mineEnded = !mine.MoveNext(); theirsEnded = !theirs.MoveNext(); } else { merged[c++] = theirs.Current; theirsEnded = !theirs.MoveNext(); } } if (!mineEnded || !theirsEnded) { Enumerator remaining = (mineEnded ? theirs : mine); do { merged[c++] = remaining.Current; } while (remaining.MoveNext()); } //now merged has all c elements //safe to gc the root, we have all the elements root = null; root = SortedSetCopyable<T>.ConstructRootFromSortedArray(merged, 0, c - 1, null); count = c; version++; } else { AddAllElements(other); } } private static Node ConstructRootFromSortedArray(T[] arr, int startIndex, int endIndex, Node redNode) { //what does this do? //you're given a sorted array... say 1 2 3 4 5 6 //2 cases: // If there are odd # of elements, pick the middle element (in this case 4), and compute // its left and right branches // If there are even # of elements, pick the left middle element, save the right middle element // and call the function on the rest // 1 2 3 4 5 6 -> pick 3, save 4 and call the fn on 1,2 and 5,6 // now add 4 as a red node to the lowest element on the right branch // 3 3 // 1 5 -> 1 5 // 2 6 2 4 6 // As we're adding to the leftmost of the right branch, nesting will not hurt the red-black properties // Leaf nodes are red if they have no sibling (if there are 2 nodes or if a node trickles // down to the bottom //the iterative way to do this ends up wasting more space than it saves in stack frames (at //least in what i tried) //so we're doing this recursively //base cases are described below int size = endIndex - startIndex + 1; if (size == 0) { return null; } Node root = null; if (size == 1) { root = Node.Spawn(arr[startIndex], false); if (redNode != null) { root.Left = redNode; } } else if (size == 2) { root = Node.Spawn(arr[startIndex], false); root.Right = Node.Spawn(arr[endIndex], false); root.Right.IsRed = true; if (redNode != null) { root.Left = redNode; } } else if (size == 3) { root = Node.Spawn(arr[startIndex + 1], false); root.Left = Node.Spawn(arr[startIndex], false); root.Right = Node.Spawn(arr[endIndex], false); if (redNode != null) { root.Left.Left = redNode; } } else { int midpt = ((startIndex + endIndex) / 2); root = Node.Spawn(arr[midpt], false); root.Left = ConstructRootFromSortedArray(arr, startIndex, midpt - 1, redNode); if (size % 2 == 0) { root.Right = ConstructRootFromSortedArray(arr, midpt + 2, endIndex, Node.Spawn(arr[midpt + 1], true)); } else { root.Right = ConstructRootFromSortedArray(arr, midpt + 1, endIndex, null); } } return root; } /// <summary> /// Transform this set into its intersection with the IEnumerable OTHER /// NOTE: The caller object is important as IntersectionWith uses the /// comparator associated with THIS to check equality /// Throws ArgumentNullException if OTHER is null /// </summary> /// <param name="other"></param> public virtual void IntersectWith(IEnumerable<T> other) { if (other == null) { throw new ArgumentNullException("other"); } if (Count == 0) return; //HashSet<T> optimizations can't be done until equality comparers and comparers are related //Technically, this would work as well with an ISorted<T> SortedSetCopyable<T> s = other as SortedSetCopyable<T>; TreeSubSet t = this as TreeSubSet; if (t != null) VersionCheck(); //only let this happen if i am also a SortedSet, not a SubSet if (s != null && t == null && AreComparersEqual(this, s)) { //first do a merge sort to an array. T[] merged = new T[this.Count]; int c = 0; Enumerator mine = this.GetEnumerator(); Enumerator theirs = s.GetEnumerator(); bool mineEnded = !mine.MoveNext(), theirsEnded = !theirs.MoveNext(); T max = Max; T min = Min; while (!mineEnded && !theirsEnded && Comparer.Compare(theirs.Current, max) <= 0) { int comp = Comparer.Compare(mine.Current, theirs.Current); if (comp < 0) { mineEnded = !mine.MoveNext(); } else if (comp == 0) { merged[c++] = theirs.Current; mineEnded = !mine.MoveNext(); theirsEnded = !theirs.MoveNext(); } else { theirsEnded = !theirs.MoveNext(); } } //now merged has all c elements //safe to gc the root, we have all the elements root = null; root = SortedSetCopyable<T>.ConstructRootFromSortedArray(merged, 0, c - 1, null); count = c; version++; } else { IntersectWithEnumerable(other); } } internal virtual void IntersectWithEnumerable(IEnumerable<T> other) { // List<T> toSave = new List<T>(this.Count); foreach (T item in other) { if (this.Contains(item)) { toSave.Add(item); this.Remove(item); } } this.Clear(); AddAllElements(toSave); } /// <summary> /// Transform this set into its complement with the IEnumerable OTHER /// NOTE: The caller object is important as ExceptWith uses the /// comparator associated with THIS to check equality /// Throws ArgumentNullException if OTHER is null /// </summary> /// <param name="other"></param> public void ExceptWith(IEnumerable<T> other) { if (other == null) { throw new ArgumentNullException("other"); } if (count == 0) return; if (other == this) { this.Clear(); return; } SortedSetCopyable<T> asSorted = other as SortedSetCopyable<T>; if (asSorted != null && AreComparersEqual(this, asSorted)) { //outside range, no point doing anything if (!(comparer.Compare(asSorted.Max, this.Min) < 0 || comparer.Compare(asSorted.Min, this.Max) > 0)) { T min = this.Min; T max = this.Max; foreach (T item in other) { if (comparer.Compare(item, min) < 0) continue; if (comparer.Compare(item, max) > 0) break; Remove(item); } } } else { RemoveAllElements(other); } } /// <summary> /// Transform this set so it contains elements in THIS or OTHER but not both /// NOTE: The caller object is important as SymmetricExceptWith uses the /// comparator associated with THIS to check equality /// Throws ArgumentNullException if OTHER is null /// </summary> /// <param name="other"></param> public void SymmetricExceptWith(IEnumerable<T> other) { if (other == null) { throw new ArgumentNullException("other"); } if (this.Count == 0) { this.UnionWith(other); return; } if (other == this) { this.Clear(); return; } SortedSetCopyable<T> asSorted = other as SortedSetCopyable<T>; #if USING_HASH_SET HashSet<T> asHash = other as HashSet<T>; #endif if (asSorted != null && AreComparersEqual(this, asSorted)) { SymmetricExceptWithSameEC(asSorted); } #if USING_HASH_SET else if (asHash != null && this.comparer.Equals(Comparer<T>.Default) && asHash.Comparer.Equals(EqualityComparer<T>.Default)) { SymmetricExceptWithSameEC(asHash); } #endif else { //need perf improvement on this T[] elements = (new List<T>(other)).ToArray(); Array.Sort(elements, this.Comparer); SymmetricExceptWithSameEC(elements); } } //OTHER must be a set internal void SymmetricExceptWithSameEC(ISet<T> other) { foreach (T item in other) { //yes, it is classier to say //if (!this.Remove(item))this.Add(item); //but this ends up saving on rotations if (this.Contains(item)) { this.Remove(item); } else { this.Add(item); } } } //OTHER must be a sorted array internal void SymmetricExceptWithSameEC(T[] other) { if (other.Length == 0) { return; } T last = other[0]; for (int i = 0; i < other.Length; i++) { while (i < other.Length && i != 0 && comparer.Compare(other[i], last) == 0) i++; if (i >= other.Length) break; if (this.Contains(other[i])) { this.Remove(other[i]); } else { this.Add(other[i]); } last = other[i]; } } /// <summary> /// Checks whether this Tree is a subset of the IEnumerable other /// </summary> /// <param name="other"></param> /// <returns></returns> [System.Security.SecuritySafeCritical] public bool IsSubsetOf(IEnumerable<T> other) { if (other == null) { throw new ArgumentNullException("other"); } if (Count == 0) return true; SortedSetCopyable<T> asSorted = other as SortedSetCopyable<T>; if (asSorted != null && AreComparersEqual(this, asSorted)) { if (this.Count > asSorted.Count) return false; return IsSubsetOfSortedSetWithSameEC(asSorted); } else { //worst case: mark every element in my set and see if i've counted all //O(MlogN) ElementCount result = CheckUniqueAndUnfoundElements(other, false); return (result.uniqueCount == Count && result.unfoundCount >= 0); } } private bool IsSubsetOfSortedSetWithSameEC(SortedSetCopyable<T> asSorted) { SortedSetCopyable<T> prunedOther = asSorted.GetViewBetween(this.Min, this.Max); foreach (T item in this) { if (!prunedOther.Contains(item)) return false; } return true; } /// <summary> /// Checks whether this Tree is a proper subset of the IEnumerable other /// </summary> /// <param name="other"></param> /// <returns></returns> [System.Security.SecuritySafeCritical] public bool IsProperSubsetOf(IEnumerable<T> other) { if (other == null) { throw new ArgumentNullException("other"); } if ((other as ICollection) != null) { if (Count == 0) return (other as ICollection).Count > 0; } #if USING_HASH_SET //do it one way for HashSets HashSet<T> asHash = other as HashSet<T>; if (asHash != null && comparer.Equals(Comparer<T>.Default) && asHash.Comparer.Equals(EqualityComparer<T>.Default)) { return asHash.IsProperSupersetOf(this); } #endif //another for sorted sets with the same comparer SortedSetCopyable<T> asSorted = other as SortedSetCopyable<T>; if (asSorted != null && AreComparersEqual(this, asSorted)) { if (this.Count >= asSorted.Count) return false; return IsSubsetOfSortedSetWithSameEC(asSorted); } //worst case: mark every element in my set and see if i've counted all //O(MlogN). ElementCount result = CheckUniqueAndUnfoundElements(other, false); return (result.uniqueCount == Count && result.unfoundCount > 0); } /// <summary> /// Checks whether this Tree is a super set of the IEnumerable other /// </summary> /// <param name="other"></param> /// <returns></returns> public bool IsSupersetOf(IEnumerable<T> other) { if (other == null) { throw new ArgumentNullException("other"); } if ((other as ICollection) != null && (other as ICollection).Count == 0) return true; //do it one way for HashSets #if USING_HASH_SET HashSet<T> asHash = other as HashSet<T>; if (asHash != null && comparer.Equals(Comparer<T>.Default) && asHash.Comparer.Equals(EqualityComparer<T>.Default)) { return asHash.IsSubsetOf(this); } #endif //another for sorted sets with the same comparer SortedSetCopyable<T> asSorted = other as SortedSetCopyable<T>; if (asSorted != null && AreComparersEqual(this, asSorted)) { if (this.Count < asSorted.Count) return false; SortedSetCopyable<T> pruned = GetViewBetween(asSorted.Min, asSorted.Max); foreach (T item in asSorted) { if (!pruned.Contains(item)) return false; } return true; } //and a third for everything else return ContainsAllElements(other); } /// <summary> /// Checks whether this Tree is a proper super set of the IEnumerable other /// </summary> /// <param name="other"></param> /// <returns></returns> [System.Security.SecuritySafeCritical] public bool IsProperSupersetOf(IEnumerable<T> other) { if (other == null) { throw new ArgumentNullException("other"); } if (Count == 0) return false; if ((other as ICollection) != null && (other as ICollection).Count == 0) return true; #if USING_HASH_SET //do it one way for HashSets HashSet<T> asHash = other as HashSet<T>; if (asHash != null && comparer.Equals(Comparer<T>.Default) && asHash.Comparer.Equals(EqualityComparer<T>.Default)) { return asHash.IsProperSubsetOf(this); } #endif //another way for sorted sets SortedSetCopyable<T> asSorted = other as SortedSetCopyable<T>; if (asSorted != null && AreComparersEqual(asSorted, this)) { if (asSorted.Count >= this.Count) return false; SortedSetCopyable<T> pruned = GetViewBetween(asSorted.Min, asSorted.Max); foreach (T item in asSorted) { if (!pruned.Contains(item)) return false; } return true; } //worst case: mark every element in my set and see if i've counted all //O(MlogN) //slight optimization, put it into a HashSet and then check can do it in O(N+M) //but slower in better cases + wastes space ElementCount result = CheckUniqueAndUnfoundElements(other, true); return (result.uniqueCount < Count && result.unfoundCount == 0); } /// <summary> /// Checks whether this Tree has all elements in common with IEnumerable other /// </summary> /// <param name="other"></param> /// <returns></returns> [System.Security.SecuritySafeCritical] public bool SetEquals(IEnumerable<T> other) { if (other == null) { throw new ArgumentNullException("other"); } #if USING_HASH_SET HashSet<T> asHash = other as HashSet<T>; if (asHash != null && comparer.Equals(Comparer<T>.Default) && asHash.Comparer.Equals(EqualityComparer<T>.Default)) { return asHash.SetEquals(this); } #endif SortedSetCopyable<T> asSorted = other as SortedSetCopyable<T>; if (asSorted != null && AreComparersEqual(this, asSorted)) { IEnumerator<T> mine = this.GetEnumerator(); IEnumerator<T> theirs = asSorted.GetEnumerator(); bool mineEnded = !mine.MoveNext(); bool theirsEnded = !theirs.MoveNext(); while (!mineEnded && !theirsEnded) { if (Comparer.Compare(mine.Current, theirs.Current) != 0) { return false; } mineEnded = !mine.MoveNext(); theirsEnded = !theirs.MoveNext(); } return mineEnded && theirsEnded; } //worst case: mark every element in my set and see if i've counted all //O(N) by size of other ElementCount result = CheckUniqueAndUnfoundElements(other, true); return (result.uniqueCount == Count && result.unfoundCount == 0); } /// <summary> /// Checks whether this Tree has any elements in common with IEnumerable other /// </summary> /// <param name="other"></param> /// <returns></returns> public bool Overlaps(IEnumerable<T> other) { if (other == null) { throw new ArgumentNullException("other"); } if (this.Count == 0) return false; if ((other as ICollection<T> != null) && (other as ICollection<T>).Count == 0) return false; SortedSetCopyable<T> asSorted = other as SortedSetCopyable<T>; if (asSorted != null && AreComparersEqual(this, asSorted) && (comparer.Compare(Min, asSorted.Max) > 0 || comparer.Compare(Max, asSorted.Min) < 0)) { return false; } #if USING_HASH_SET HashSet<T> asHash = other as HashSet<T>; if (asHash != null && comparer.Equals(Comparer<T>.Default) && asHash.Comparer.Equals(EqualityComparer<T>.Default)) { return asHash.Overlaps(this); } #endif foreach (T item in other) { if (this.Contains(item)) { return true; } } return false; } /// <summary> /// This works similar to HashSet's CheckUniqueAndUnfound (description below), except that the bit /// array maps differently than in the HashSet. We can only use this for the bulk boolean checks. /// /// Determines counts that can be used to determine equality, subset, and superset. This /// is only used when other is an IEnumerable and not a HashSet. If other is a HashSet /// these properties can be checked faster without use of marking because we can assume /// other has no duplicates. /// /// The following count checks are performed by callers: /// 1. Equals: checks if unfoundCount = 0 and uniqueFoundCount = Count; i.e. everything /// in other is in this and everything in this is in other /// 2. Subset: checks if unfoundCount >= 0 and uniqueFoundCount = Count; i.e. other may /// have elements not in this and everything in this is in other /// 3. Proper subset: checks if unfoundCount > 0 and uniqueFoundCount = Count; i.e /// other must have at least one element not in this and everything in this is in other /// 4. Proper superset: checks if unfound count = 0 and uniqueFoundCount strictly less /// than Count; i.e. everything in other was in this and this had at least one element /// not contained in other. /// /// An earlier implementation used delegates to perform these checks rather than returning /// an ElementCount struct; however this was changed due to the perf overhead of delegates. /// </summary> /// <param name="other"></param> /// <param name="returnIfUnfound">Allows us to finish faster for equals and proper superset /// because unfoundCount must be 0.</param> /// <returns></returns> // <SecurityKernel Critical="True" Ring="0"> // <UsesUnsafeCode Name="Local bitArrayPtr of type: Int32*" /> // <ReferencesCritical Name="Method: BitHelper..ctor(System.Int32*,System.Int32)" Ring="1" /> // <ReferencesCritical Name="Method: BitHelper.IsMarked(System.Int32):System.Boolean" Ring="1" /> // <ReferencesCritical Name="Method: BitHelper.MarkBit(System.Int32):System.Void" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] private unsafe ElementCount CheckUniqueAndUnfoundElements(IEnumerable<T> other, bool returnIfUnfound) { ElementCount result; // need special case in case this has no elements. if (Count == 0) { int numElementsInOther = 0; foreach (T item in other) { numElementsInOther++; // break right away, all we want to know is whether other has 0 or 1 elements break; } result.uniqueCount = 0; result.unfoundCount = numElementsInOther; return result; } int originalLastIndex = Count; int intArrayLength = BitHelper.ToIntArrayLength(originalLastIndex); BitHelper bitHelper; if (intArrayLength <= StackAllocThreshold) { int* bitArrayPtr = stackalloc int[intArrayLength]; bitHelper = new BitHelper(bitArrayPtr, intArrayLength); } else { int[] bitArray = new int[intArrayLength]; bitHelper = new BitHelper(bitArray, intArrayLength); } // count of items in other not found in this int unfoundCount = 0; // count of unique items in other found in this int uniqueFoundCount = 0; foreach (T item in other) { int index = InternalIndexOf(item); if (index >= 0) { if (!bitHelper.IsMarked(index)) { // item hasn't been seen yet bitHelper.MarkBit(index); uniqueFoundCount++; } } else { unfoundCount++; if (returnIfUnfound) { break; } } } result.uniqueCount = uniqueFoundCount; result.unfoundCount = unfoundCount; return result; } public int RemoveWhere(Predicate<T> match) { if (match == null) { throw new ArgumentNullException("match"); } List<T> matches = new List<T>(this.Count); BreadthFirstTreeWalk(delegate(Node n) { if (match(n.Item)) { matches.Add(n.Item); } return true; }); // reverse breadth first to (try to) incur low cost int actuallyRemoved = 0; for (int i = matches.Count - 1; i >= 0; i--) { if (this.Remove(matches[i])) { actuallyRemoved++; } } return actuallyRemoved; } #endregion #region ISorted Members public T Min { get { T ret = default(T); InOrderTreeWalk(delegate(SortedSetCopyable<T>.Node n) { ret = n.Item; return false; }); return ret; } } public T Max { get { T ret = default(T); InOrderTreeWalk(delegate(SortedSetCopyable<T>.Node n) { ret = n.Item; return false; }, true); return ret; } } public IEnumerable<T> Reverse() { Enumerator e = new Enumerator(this, true); while (e.MoveNext()) { yield return e.Current; } } /// <summary> /// Returns a subset of this tree ranging from values lBound to uBound /// Any changes made to the subset reflect in the actual tree /// </summary> /// <param name="lowVestalue">Lowest Value allowed in the subset</param> /// <param name="highestValue">Highest Value allowed in the subset</param> public virtual SortedSetCopyable<T> GetViewBetween(T lowerValue, T upperValue) { if (Comparer.Compare(lowerValue, upperValue) > 0) { throw new ArgumentException("lowerBound is greater than upperBound"); } return new TreeSubSet(this, lowerValue, upperValue, true, true); } #if DEBUG /// <summary> /// debug status to be checked whenever any operation is called /// </summary> /// <returns></returns> internal virtual bool versionUpToDate() { return true; } #endif /// <summary> /// This class represents a subset view into the tree. Any changes to this view /// are reflected in the actual tree. Uses the Comparator of the underlying tree. /// </summary> /// <typeparam name="T"></typeparam> #if !FEATURE_NETCORE [Serializable] internal sealed class TreeSubSet : SortedSetCopyable<T>, ISerializable, IDeserializationCallback { #else internal sealed class TreeSubSet : SortedSetCopyable<T> { #endif SortedSetCopyable<T> underlying; T min, max; //these exist for unbounded collections //for instance, you could allow this subset to be defined for i>10. The set will throw if //anything <=10 is added, but there is no upperbound. These features Head(), Tail(), were punted //in the spec, and are not available, but the framework is there to make them available at some point. bool lBoundActive, uBoundActive; //used to see if the count is out of date #if DEBUG internal override bool versionUpToDate() { return (this.version == underlying.version); } #endif public TreeSubSet(SortedSetCopyable<T> Underlying, T Min, T Max, bool lowerBoundActive, bool upperBoundActive) : base(Underlying.Comparer) { underlying = Underlying; min = Min; max = Max; lBoundActive = lowerBoundActive; uBoundActive = upperBoundActive; root = underlying.FindRange(min, max, lBoundActive, uBoundActive); // root is first element within range count = 0; version = -1; VersionCheckImpl(); } #if !FEATURE_NETCORE /// <summary> /// For serialization and deserialization /// </summary> private TreeSubSet() { comparer = null; } [SuppressMessage("Microsoft.Usage", "CA2236:CallBaseClassMethodsOnISerializableTypes", Justification = "special case TreeSubSet serialization")] private TreeSubSet(SerializationInfo info, StreamingContext context) { siInfo = info; OnDeserializationImpl(info); } #endif // !FEATURE_NETCORE /// <summary> /// Additions to this tree need to be added to the underlying tree as well /// </summary> internal override bool AddIfNotPresent(T item) { bool ret = underlying.AddIfNotPresent(item); VersionCheck(); #if DEBUG Debug.Assert(this.versionUpToDate() && this.root == this.underlying.FindRange(min, max)); #endif return ret; } public override bool Contains(T item) { VersionCheck(); #if DEBUG Debug.Assert(this.versionUpToDate() && this.root == this.underlying.FindRange(min, max)); #endif return base.Contains(item); } internal override bool DoRemove(T item) { // todo: uppercase this and others if (!IsWithinRange(item)) { return false; } bool ret = underlying.Remove(item); VersionCheck(); #if DEBUG Debug.Assert(this.versionUpToDate() && this.root == this.underlying.FindRange(min, max)); #endif return ret; } public override void Clear() { if (count == 0) { return; } List<T> toRemove = new List<T>(); BreadthFirstTreeWalk(delegate(Node n) { toRemove.Add(n.Item); return true; }); while (toRemove.Count != 0) { underlying.Remove(toRemove[toRemove.Count - 1]); toRemove.RemoveAt(toRemove.Count - 1); } root = null; count = 0; version = underlying.version; } internal override bool IsWithinRange(T item) { int comp = (lBoundActive ? Comparer.Compare(min, item) : -1); if (comp > 0) { return false; } comp = (uBoundActive ? Comparer.Compare(max, item) : 1); if (comp < 0) { return false; } return true; } internal override bool InOrderTreeWalk(TreeWalkPredicate<T> action, Boolean reverse) { VersionCheck(); if (root == null) { return true; } // The maximum height of a red-black tree is 2*lg(n+1). // See page 264 of "Introduction to algorithms" by Thomas H. Cormen Stack<Node> stack = new Stack<Node>(2 * (int)SortedSetCopyable<T>.log2(count + 1)); //this is not exactly right if count is out of date, but the stack can grow Node current = root; while (current != null) { if (IsWithinRange(current.Item)) { stack.Push(current); current = (reverse ? current.Right : current.Left); } else if (lBoundActive && Comparer.Compare(min, current.Item) > 0) { current = current.Right; } else { current = current.Left; } } while (stack.Count != 0) { current = stack.Pop(); if (!action(current)) { return false; } Node node = (reverse ? current.Left : current.Right); while (node != null) { if (IsWithinRange(node.Item)) { stack.Push(node); node = (reverse ? node.Right : node.Left); } else if (lBoundActive && Comparer.Compare(min, node.Item) > 0) { node = node.Right; } else { node = node.Left; } } } return true; } internal override bool BreadthFirstTreeWalk(TreeWalkPredicate<T> action) { VersionCheck(); if (root == null) { return true; } List<Node> processQueue = new List<Node>(); processQueue.Add(root); Node current; while (processQueue.Count != 0) { current = processQueue[0]; processQueue.RemoveAt(0); if (IsWithinRange(current.Item) && !action(current)) { return false; } if (current.Left != null && (!lBoundActive || Comparer.Compare(min, current.Item) < 0)) { processQueue.Add(current.Left); } if (current.Right != null && (!uBoundActive || Comparer.Compare(max, current.Item) > 0)) { processQueue.Add(current.Right); } } return true; } internal override SortedSetCopyable<T>.Node FindNode(T item) { if (!IsWithinRange(item)) { return null; } VersionCheck(); #if DEBUG Debug.Assert(this.versionUpToDate() && this.root == this.underlying.FindRange(min, max)); #endif return base.FindNode(item); } //this does indexing in an inefficient way compared to the actual sortedset, but it saves a //lot of space internal override int InternalIndexOf(T item) { int count = -1; foreach (T i in this) { count++; if (Comparer.Compare(item, i) == 0) return count; } #if DEBUG Debug.Assert(this.versionUpToDate() && this.root == this.underlying.FindRange(min, max)); #endif return -1; } /// <summary> /// checks whether this subset is out of date. updates if necessary. /// </summary> internal override void VersionCheck() { VersionCheckImpl(); } private void VersionCheckImpl() { Debug.Assert(underlying != null, "Underlying set no longer exists"); if (this.version != underlying.version) { this.root = underlying.FindRange(min, max, lBoundActive, uBoundActive); this.version = underlying.version; count = 0; InOrderTreeWalk(delegate(Node n) { count++; return true; }); } } //This passes functionality down to the underlying tree, clipping edges if necessary //There's nothing gained by having a nested subset. May as well draw it from the base //Cannot increase the bounds of the subset, can only decrease it public override SortedSetCopyable<T> GetViewBetween(T lowerValue, T upperValue) { if (lBoundActive && Comparer.Compare(min, lowerValue) > 0) { //lBound = min; throw new ArgumentOutOfRangeException("lowerValue"); } if (uBoundActive && Comparer.Compare(max, upperValue) < 0) { //uBound = max; throw new ArgumentOutOfRangeException("upperValue"); } TreeSubSet ret = (TreeSubSet)underlying.GetViewBetween(lowerValue, upperValue); return ret; } internal override void IntersectWithEnumerable(IEnumerable<T> other) { List<T> toSave = new List<T>(this.Count); foreach (T item in other) { if (this.Contains(item)) { toSave.Add(item); this.Remove(item); } } this.Clear(); this.AddAllElements(toSave); #if DEBUG Debug.Assert(this.versionUpToDate() && this.root == this.underlying.FindRange(min, max)); #endif } #if !FEATURE_NETCORE void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { GetObjectData(info, context); } protected override void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue(maxName, max, typeof(T)); info.AddValue(minName, min, typeof(T)); info.AddValue(lBoundActiveName, lBoundActive); info.AddValue(uBoundActiveName, uBoundActive); base.GetObjectData(info, context); } void IDeserializationCallback.OnDeserialization(Object sender) { //don't do anything here as its already been done by the constructor //OnDeserialization(sender); } protected override void OnDeserialization(Object sender) { OnDeserializationImpl(sender); } private void OnDeserializationImpl(Object sender) { comparer = (IComparer<T>)siInfo.GetValue(ComparerName, typeof(IComparer<T>)); int savedCount = siInfo.GetInt32(CountName); max = (T)siInfo.GetValue(maxName, typeof(T)); min = (T)siInfo.GetValue(minName, typeof(T)); lBoundActive = siInfo.GetBoolean(lBoundActiveName); uBoundActive = siInfo.GetBoolean(uBoundActiveName); underlying = new SortedSetCopyable<T>(); if (savedCount != 0) { T[] items = (T[])siInfo.GetValue(ItemsName, typeof(T[])); for (int i = 0; i < items.Length; i++) { underlying.Add(items[i]); } } underlying.version = siInfo.GetInt32(VersionName); count = underlying.count; version = underlying.version - 1; VersionCheck(); //this should update the count to be right and update root to be right siInfo = null; } #endif // !FEATURE_NETCORE } #endregion #region Serialization methods #if !FEATURE_NETCORE // LinkDemand here is unnecessary as this is a methodimpl and linkdemand from the interface should suffice void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { GetObjectData(info, context); } protected virtual void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue(CountName, count); //This is the length of the bucket array. info.AddValue(ComparerName, comparer, typeof(IComparer<T>)); info.AddValue(VersionName, version); if (root != null) { T[] items = new T[Count]; CopyTo(items, 0); info.AddValue(ItemsName, items, typeof(T[])); } } void IDeserializationCallback.OnDeserialization(Object sender) { OnDeserialization(sender); } protected virtual void OnDeserialization(Object sender) { if (comparer != null) { return; //Somebody had a dependency on this class and fixed us up before the ObjectManager got to it. } comparer = (IComparer<T>)siInfo.GetValue(ComparerName, typeof(IComparer<T>)); int savedCount = siInfo.GetInt32(CountName); if (savedCount != 0) { T[] items = (T[])siInfo.GetValue(ItemsName, typeof(T[])); for (int i = 0; i < items.Length; i++) { Add(items[i]); } } version = siInfo.GetInt32(VersionName); siInfo = null; } #endif //!FEATURE_NETCORE #endregion #region Helper Classes internal class Node : IPoolableRecycle { public bool IsRed; public T Item; public Node Left; public Node Right; public static Node Spawn(T item) { var instance = PoolClass<Node>.Spawn(); instance.Item = item; instance.IsRed = true; return instance; } public static Node Spawn(T item, bool isRed) { var instance = PoolClass<Node>.Spawn(); instance.Item = item; instance.IsRed = isRed; return instance; } public void OnRecycle() { this.IsRed = default; this.Item = default; this.Left = default; this.Right = default; } public Node() {} public Node(T item) { // The default color will be red, we never need to create a black node directly. this.Item = item; IsRed = true; } public Node(T item, bool isRed) { // The default color will be red, we never need to create a black node directly. this.Item = item; this.IsRed = isRed; } } [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")] #if !FEATURE_NETCORE [Serializable] public struct Enumerator : IEnumerator<T>, IEnumerator, ISerializable, IDeserializationCallback { #else public struct Enumerator : IEnumerator<T>, IEnumerator { #endif private SortedSetCopyable<T> tree; private int version; private Stack<SortedSetCopyable<T>.Node> stack; private SortedSetCopyable<T>.Node current; static SortedSetCopyable<T>.Node dummyNode = new SortedSetCopyable<T>.Node(default(T)); private bool reverse; #if !FEATURE_NETCORE private SerializationInfo siInfo; #endif internal Enumerator(SortedSetCopyable<T> set) { tree = set; //this is a hack to make sure that the underlying subset has not been changed since // tree.VersionCheck(); version = tree.version; // 2lg(n + 1) is the maximum height stack = PoolStack<SortedSetCopyable<T>.Node>.Spawn(2 * (int)SortedSetCopyable<T>.log2(set.Count + 1)); current = null; reverse = false; #if !FEATURE_NETCORE siInfo = null; #endif Intialize(); } internal Enumerator(SortedSetCopyable<T> set, bool reverse) { tree = set; //this is a hack to make sure that the underlying subset has not been changed since // tree.VersionCheck(); version = tree.version; // 2lg(n + 1) is the maximum height stack = PoolStack<SortedSetCopyable<T>.Node>.Spawn(2 * (int)SortedSetCopyable<T>.log2(set.Count + 1)); current = null; this.reverse = reverse; #if !FEATURE_NETCORE siInfo = null; #endif Intialize(); } #if !FEATURE_NETCORE private Enumerator(SerializationInfo info, StreamingContext context) { tree = null; version = -1; current = null; reverse = false; stack = null; this.siInfo = info; } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { GetObjectData(info, context); } private void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue(TreeName, tree, typeof(SortedSetCopyable<T>)); info.AddValue(EnumVersionName, version); info.AddValue(ReverseName, reverse); info.AddValue(EnumStartName, !NotStartedOrEnded); info.AddValue(NodeValueName, (current == null ? dummyNode.Item : current.Item), typeof(T)); } void IDeserializationCallback.OnDeserialization(Object sender) { OnDeserialization(sender); } private void OnDeserialization(Object sender) { tree = (SortedSetCopyable<T>)siInfo.GetValue(TreeName, typeof(SortedSetCopyable<T>)); version = siInfo.GetInt32(EnumVersionName); reverse = siInfo.GetBoolean(ReverseName); bool EnumStarted = siInfo.GetBoolean(EnumStartName); stack = new Stack<SortedSetCopyable<T>.Node>(2 * (int)SortedSetCopyable<T>.log2(tree.Count + 1)); current = null; if (EnumStarted) { T item = (T)siInfo.GetValue(NodeValueName, typeof(T)); Intialize(); //go until it reaches the value we want while (this.MoveNext()) { if (tree.Comparer.Compare(this.Current, item) == 0) break; } } } #endif //!FEATURE_NETCORE private void Intialize() { current = null; SortedSetCopyable<T>.Node node = tree.root; Node next = null, other = null; while (node != null) { next = (reverse ? node.Right : node.Left); other = (reverse ? node.Left : node.Right); if (tree.IsWithinRange(node.Item)) { stack.Push(node); node = next; } else if (next == null || !tree.IsWithinRange(next.Item)) { node = other; } else { node = next; } } } public bool MoveNext() { //this is a hack to make sure that the underlying subset has not been changed since // tree.VersionCheck(); if (stack.Count == 0) { current = null; return false; } current = stack.Pop(); SortedSetCopyable<T>.Node node = (reverse ? current.Left : current.Right); Node next = null, other = null; while (node != null) { next = (reverse ? node.Right : node.Left); other = (reverse ? node.Left : node.Right); if (tree.IsWithinRange(node.Item)) { stack.Push(node); node = next; } else if (other == null || !tree.IsWithinRange(other.Item)) { node = next; } else { node = other; } } return true; } public void Dispose() { PoolStack<Node>.Recycle(ref stack); } public T Current { get { if (current != null) { return current.Item; } return default(T); } } object IEnumerator.Current { get { return current.Item; } } internal bool NotStartedOrEnded { get { return current == null; } } internal void Reset() { stack.Clear(); Intialize(); } void IEnumerator.Reset() { Reset(); } } internal struct ElementCount { internal int uniqueCount; internal int unfoundCount; } #endregion #region misc /// <summary> /// Searches the set for a given value and returns the equal value it finds, if any. /// </summary> /// <param name="equalValue">The value to search for.</param> /// <param name="actualValue">The value from the set that the search found, or the default value of <typeparamref name="T"/> when the search yielded no match.</param> /// <returns>A value indicating whether the search was successful.</returns> /// <remarks> /// This can be useful when you want to reuse a previously stored reference instead of /// a newly constructed one (so that more sharing of references can occur) or to look up /// a value that has more complete data than the value you currently have, although their /// comparer functions indicate they are equal. /// </remarks> public bool TryGetValue(T equalValue, out T actualValue) { Node node = FindNode(equalValue); if (node != null) { actualValue = node.Item; return true; } actualValue = default(T); return false; } // used for set checking operations (using enumerables) that rely on counting private static int log2(int value) { //Contract.Requires(value>0) int c = 0; while (value > 0) { c++; value >>= 1; } return c; } #endregion } /// <summary> /// A class that generates an IEqualityComparer for this SortedSet. Requires that the definition of /// equality defined by the IComparer for this SortedSet be consistent with the default IEqualityComparer /// for the type T. If not, such an IEqualityComparer should be provided through the constructor. /// </summary> internal class SortedSetEqualityComparer<T> : IEqualityComparer<SortedSetCopyable<T>> { private IComparer<T> comparer; private IEqualityComparer<T> e_comparer; public SortedSetEqualityComparer() : this(null, null) { } public SortedSetEqualityComparer(IComparer<T> comparer) : this(comparer, null) { } public SortedSetEqualityComparer(IEqualityComparer<T> memberEqualityComparer) : this(null, memberEqualityComparer) { } /// <summary> /// Create a new SetEqualityComparer, given a comparer for member order and another for member equality (these /// must be consistent in their definition of equality) /// </summary> public SortedSetEqualityComparer(IComparer<T> comparer, IEqualityComparer<T> memberEqualityComparer) { if (comparer == null) this.comparer = Comparer<T>.Default; else this.comparer = comparer; if (memberEqualityComparer == null) e_comparer = EqualityComparer<T>.Default; else e_comparer = memberEqualityComparer; } // using comparer to keep equals properties in tact; don't want to choose one of the comparers public bool Equals(SortedSetCopyable<T> x, SortedSetCopyable<T> y) { return SortedSetCopyable<T>.SortedSetEquals(x, y, comparer); } //IMPORTANT: this part uses the fact that GetHashCode() is consistent with the notion of equality in //the set public int GetHashCode(SortedSetCopyable<T> obj) { int hashCode = 0; if (obj != null) { foreach (T t in obj) { hashCode = hashCode ^ (e_comparer.GetHashCode(t) & 0x7FFFFFFF); } } // else returns hashcode of 0 for null HashSets return hashCode; } // Equals method for the comparer itself. public override bool Equals(Object obj) { SortedSetEqualityComparer<T> comparer = obj as SortedSetEqualityComparer<T>; if (comparer == null) { return false; } return (this.comparer == comparer.comparer); } public override int GetHashCode() { return comparer.GetHashCode() ^ e_comparer.GetHashCode(); } } }
39.409903
176
0.492239
[ "MIT" ]
Comelyes/ECSExample
Assets/ECS/ECS/Core/Collections/SortedSetCopyable.cs
105,857
C#
using RepoDb.Attributes; using RepoDb.Exceptions; using RepoDb.Extensions; using System; using System.Collections.Concurrent; using System.Linq.Expressions; using System.Reflection; namespace RepoDb { /// <summary> /// A class that is being used to map a class into its equivalent database object (ie: Table, View) column. This is an alternative class to <see cref="MapAttribute"/> object for property mapping. /// </summary> public static class PropertyMapper { #region Privates private static readonly ConcurrentDictionary<int, string> maps = new ConcurrentDictionary<int, string>(); #endregion #region Methods /* * Add */ /// <summary> /// Adds a mapping between a class property and a database column (via expression). /// </summary> /// <typeparam name="TEntity">The type of the data entity.</typeparam> /// <param name="expression">The expression to be parsed.</param> /// <param name="columnName">The name of the database column.</param> public static void Add<TEntity>(Expression<Func<TEntity, object>> expression, string columnName) where TEntity : class => Add<TEntity>(expression, columnName, false); /// <summary> /// Adds a mapping between a class property and a database column (via expression). /// </summary> /// <typeparam name="TEntity">The type of the data entity.</typeparam> /// <param name="expression">The expression to be parsed.</param> /// <param name="columnName">The name of the database column.</param> /// <param name="force">A value that indicates whether to force the mapping. If one is already exists, then it will be overwritten.</param> public static void Add<TEntity>(Expression<Func<TEntity, object>> expression, string columnName, bool force) where TEntity : class => Add<TEntity>(ExpressionExtension.GetProperty<TEntity>(expression), columnName, force); /// <summary> /// Adds a mapping between a class property and a database column (via property name). /// </summary> /// <typeparam name="TEntity">The target .NET CLR type.</typeparam> /// <param name="propertyName">The name of the class property to be mapped.</param> /// <param name="columnName">The name of the database column.</param> public static void Add<TEntity>(string propertyName, string columnName) where TEntity : class => Add<TEntity>(propertyName, columnName, false); /// <summary> /// Adds a mapping between a class property and a database column (via property name). /// </summary> /// <typeparam name="TEntity">The target .NET CLR type.</typeparam> /// <param name="propertyName">The name of the class property to be mapped.</param> /// <param name="columnName">The name of the class property to be mapped.</param> /// <param name="force">A value that indicates whether to force the mapping. If one is already exists, then it will be overwritten.</param> public static void Add<TEntity>(string propertyName, string columnName, bool force) where TEntity : class { // Validates ThrowNullReferenceException(propertyName, "PropertyName"); // Get the property var property = TypeExtension.GetProperty<TEntity>(propertyName); if (property == null) { throw new PropertyNotFoundException($"Property '{propertyName}' is not found at type '{typeof(TEntity).FullName}'."); } // Add to the mapping Add<TEntity>(property, columnName, force); } /// <summary> /// Adds a mapping between a class property and a database column (via <see cref="Field"/> object). /// </summary> /// <typeparam name="TEntity">The target .NET CLR type.</typeparam> /// <param name="field">The instance of <see cref="Field"/> object to be mapped.</param> /// <param name="columnName">The name of the database column.</param> public static void Add<TEntity>(Field field, string columnName) where TEntity : class => Add<TEntity>(field, columnName, false); /// <summary> /// Adds a mapping between a class property and a database column (via <see cref="Field"/> object). /// </summary> /// <typeparam name="TEntity">The target .NET CLR type.</typeparam> /// <param name="field">The instance of <see cref="Field"/> object to be mapped.</param> /// <param name="columnName">The name of the database column.</param> /// <param name="force">A value that indicates whether to force the mapping. If one is already exists, then it will be overwritten.</param> public static void Add<TEntity>(Field field, string columnName, bool force) where TEntity : class { // Validates ThrowNullReferenceException(field, "Field"); // Get the property var property = TypeExtension.GetProperty<TEntity>(field.Name); if (property == null) { throw new PropertyNotFoundException($"Property '{field.Name}' is not found at type '{typeof(TEntity).FullName}'."); } // Add to the mapping Add<TEntity>(property, columnName, force); } /// <summary> /// Adds a mapping between a <see cref="PropertyInfo"/> object and the database column. /// </summary> /// <typeparam name="TEntity">The target .NET CLR type.</typeparam> /// <param name="propertyInfo">The instance of <see cref="PropertyInfo"/> to be mapped.</param> /// <param name="columnName">The name of the database column.</param> internal static void Add<TEntity>(PropertyInfo propertyInfo, string columnName) where TEntity : class => Add<TEntity>(propertyInfo, columnName, false); /// <summary> /// Adds a mapping between a <see cref="PropertyInfo"/> object and the database column. /// </summary> /// <typeparam name="TEntity">The target .NET CLR type.</typeparam> /// <param name="propertyInfo">The instance of <see cref="PropertyInfo"/> to be mapped.</param> /// <param name="columnName">The name of the database column.</param> /// <param name="force">A value that indicates whether to force the mapping. If one is already exists, then it will be overwritten.</param> internal static void Add<TEntity>(PropertyInfo propertyInfo, string columnName, bool force) where TEntity : class { // Validate ThrowNullReferenceException(propertyInfo, "PropertyInfo"); ValidateTargetColumnName(columnName); // Variables var key = GenerateHashCode(typeof(TEntity), propertyInfo); // Try get the cache if (maps.TryGetValue(key, out var value)) { if (force) { // Update the existing one maps.TryUpdate(key, columnName, value); } else { // Throws an exception throw new MappingExistsException($"A property mapping to '{propertyInfo.DeclaringType.FullName}.{propertyInfo.Name}' already exists."); } } else { // Add the mapping maps.TryAdd(key, columnName); } } /* * Get */ /// <summary> /// Gets the mapped database column of the property (via expression). /// </summary> /// <typeparam name="TEntity">The type of the data entity.</typeparam> /// <param name="expression">The expression to be parsed.</param> /// <returns>The mapped name of the property.</returns> public static string Get<TEntity>(Expression<Func<TEntity, object>> expression) where TEntity : class => Get<TEntity>(ExpressionExtension.GetProperty<TEntity>(expression)); /// <summary> /// Gets the mapped database column of the property (via property name). /// </summary> /// <typeparam name="TEntity">The target .NET CLR type.</typeparam> /// <param name="propertyName">The name of the property.</param> /// <returns>The mapped name of the property.</returns> public static string Get<TEntity>(string propertyName) where TEntity : class => Get<TEntity>(TypeExtension.GetProperty<TEntity>(propertyName)); /// <summary> /// Gets the mapped database column of the property (via <see cref="Field"/> object). /// </summary> /// <typeparam name="TEntity">The target .NET CLR type.</typeparam> /// <param name="field">The instance of <see cref="Field"/> object.</param> /// <returns>The mapped name of the property.</returns> public static string Get<TEntity>(Field field) where TEntity : class => Get<TEntity>(TypeExtension.GetProperty<TEntity>(field.Name)); /// <summary> /// Gets the mapped database column of the <see cref="PropertyInfo"/> object. /// </summary> /// <typeparam name="TEntity">The target .NET CLR type.</typeparam> /// <param name="propertyInfo">The instance of <see cref="PropertyInfo"/>.</param> /// <returns>The mapped name of the property.</returns> internal static string Get<TEntity>(PropertyInfo propertyInfo) where TEntity : class => Get(typeof(TEntity), propertyInfo); /// <summary> /// Gets the mapped database column of the <see cref="PropertyInfo"/> object. /// </summary> /// <param name="propertyInfo">The instance of <see cref="PropertyInfo"/>.</param> /// <returns>The mapped name of the property.</returns> internal static string Get(PropertyInfo propertyInfo) => Get(propertyInfo.DeclaringType, propertyInfo); /// <summary> /// Gets the mapped database column of the <see cref="PropertyInfo"/> object. /// </summary> /// <param name="entityType">The target .NET CLR type.</param> /// <param name="propertyInfo">The instance of <see cref="PropertyInfo"/>.</param> /// <returns>The mapped name of the property.</returns> internal static string Get(Type entityType, PropertyInfo propertyInfo) { // Validate ThrowNullReferenceException(propertyInfo, "PropertyInfo"); // Variables var key = GenerateHashCode(entityType, propertyInfo); // Try get the value maps.TryGetValue(key, out var value); // Return the value return value; } /* * Remove */ /// <summary> /// Removes the mapped database column from a property (via expression). /// </summary> /// <typeparam name="TEntity">The type of the data entity.</typeparam> /// <param name="expression">The expression to be parsed.</param> public static void Remove<TEntity>(Expression<Func<TEntity, object>> expression) where TEntity : class => Remove<TEntity>(ExpressionExtension.GetProperty<TEntity>(expression)); /// <summary> /// Removes the mapping between the class property and database column (via property name). /// </summary> /// <typeparam name="TEntity">The target .NET CLR type.</typeparam> /// <param name="propertyName">The name of the property.</param> public static void Remove<TEntity>(string propertyName) where TEntity : class => Remove<TEntity>(TypeExtension.GetProperty<TEntity>(propertyName)); /// <summary> /// Removes the mapping between the class property and database column (via <see cref="Field"/> object). /// </summary> /// <typeparam name="TEntity">The target .NET CLR type.</typeparam> /// <param name="field">The instance of <see cref="Field"/> object.</param> public static void Remove<TEntity>(Field field) where TEntity : class => Remove<TEntity>(TypeExtension.GetProperty<TEntity>(field.Name)); /// <summary> /// Removes the mapped database column from a <see cref="PropertyInfo"/> object. /// </summary> /// <typeparam name="TEntity">The target .NET CLR type.</typeparam> /// <param name="propertyInfo">The instance of <see cref="PropertyInfo"/>.</param> internal static void Remove<TEntity>(PropertyInfo propertyInfo) where TEntity : class { // Validate ThrowNullReferenceException(propertyInfo, "PropertyInfo"); // Variables var key = GenerateHashCode(typeof(TEntity), propertyInfo); var value = (string)null; // Try get the value maps.TryRemove(key, out value); } /* * Clear */ /// <summary> /// Clears all the existing cached property mapped names. /// </summary> public static void Clear() => maps.Clear(); #endregion #region Helpers /// <summary> /// Generates a hashcode for caching. /// </summary> /// <param name="entityType">The type of the data entity.</param> /// <param name="propertyInfo">The instance of <see cref="PropertyInfo"/>.</param> /// <returns>The generated hashcode.</returns> private static int GenerateHashCode(Type entityType, PropertyInfo propertyInfo) => TypeExtension.GenerateHashCode(entityType, propertyInfo); /// <summary> /// Validates the value of the target column name. /// </summary> /// <param name="columnName">The column name to be validated.</param> private static void ValidateTargetColumnName(string columnName) { if (string.IsNullOrWhiteSpace(columnName)) { throw new NullReferenceException("The target column name cannot be null or empty."); } } /// <summary> /// Validates the target object presence. /// </summary> /// <typeparam name="T">The type of the object.</typeparam> /// <param name="obj">The object to be checked.</param> /// <param name="argument">The name of the argument.</param> private static void ThrowNullReferenceException<T>(T obj, string argument) { if (obj == null) { throw new NullReferenceException($"The argument '{argument}' cannot be null."); } } #endregion } }
42.859551
199
0.591427
[ "Apache-2.0" ]
VincenzoCarlino/RepoDB
RepoDb.Core/RepoDb/Mappers/PropertyMapper.cs
15,260
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Baseline; using Marten.Util; namespace Marten.Events.Projections { public class Aggregator<T>: IAggregator<T> where T : class, new() { public static readonly string ApplyMethod = "Apply"; protected readonly IDictionary<Type, object> Aggregations = new Dictionary<Type, object>(); public Aggregator() : this(typeof(T).GetMethods().Where(x => x.Name == ApplyMethod && x.GetParameters().Length == 1)) { } protected Aggregator(IEnumerable<MethodInfo> overrideMethodLookup) { Alias = typeof(T).Name.ToTableAlias(); overrideMethodLookup .Each(method => { object step = null; var eventType = method.GetParameters().Single<ParameterInfo>().ParameterType; if (eventType.Closes(typeof(Event<>))) { eventType = eventType.GetGenericArguments().Single(); step = typeof(EventAggregationStep<,>) .CloseAndBuildAs<object>(method, typeof(T), eventType); } else { step = typeof(AggregationStep<,>) .CloseAndBuildAs<object>(method, typeof(T), eventType); } Aggregations.Add(eventType, step); }); } public Type AggregateType => typeof(T); public string Alias { get; protected set; } public T Build(IEnumerable<IEvent> events, IDocumentSession session) { return Build(events, session, new T()); } public T Build(IEnumerable<IEvent> events, IDocumentSession session, T state) { events.Each(x => x.Apply(state, this)); return state; } public Type[] EventTypes => Aggregations.Keys.ToArray(); public Aggregator<T> Add<TEvent>(IAggregation<T, TEvent> aggregation) { if (Aggregations.ContainsKey(typeof(TEvent))) { Aggregations[typeof(TEvent)] = aggregation; } else { Aggregations.Add(typeof(TEvent), aggregation); } return this; } public Aggregator<T> Add<TEvent>(Action<T, TEvent> application) { return Add(new AggregationStep<T, TEvent>(application)); } public IAggregation<T, TEvent> AggregatorFor<TEvent>() { return Aggregations.ContainsKey(typeof(TEvent)) ? Aggregations[typeof(TEvent)].As<IAggregation<T, TEvent>>() : null; } public bool AppliesTo(EventStream stream) { return stream.Events.Any(x => Aggregations.ContainsKey(x.Data.GetType())); } } }
31.808511
125
0.53913
[ "MIT" ]
gravypower/marten
src/Marten/Events/Projections/Aggregator.cs
2,990
C#
using MasterDevs.ChromeDevTools; using Newtonsoft.Json; using System.Collections.Generic; namespace MasterDevs.ChromeDevTools.Protocol.iOS.OverlayTypes { /// <summary> /// Data required to highlight multiple quads. /// </summary> [SupportedBy("iOS")] public class FragmentHighlightData { /// <summary> /// Gets or sets Quads for which the highlight should be applied. /// </summary> public Point[][] Quads { get; set; } /// <summary> /// Gets or sets ContentColor /// </summary> public string ContentColor { get; set; } /// <summary> /// Gets or sets ContentOutlineColor /// </summary> public string ContentOutlineColor { get; set; } /// <summary> /// Gets or sets PaddingColor /// </summary> public string PaddingColor { get; set; } /// <summary> /// Gets or sets BorderColor /// </summary> public string BorderColor { get; set; } /// <summary> /// Gets or sets MarginColor /// </summary> public string MarginColor { get; set; } /// <summary> /// Gets or sets RegionClippingArea /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public Point[] RegionClippingArea { get; set; } } }
26.681818
67
0.667802
[ "MIT" ]
Digitalbil/ChromeDevTools
source/ChromeDevTools/Protocol/iOS/OverlayTypes/FragmentHighlightData.cs
1,174
C#
using System.Linq; using System.Threading.Tasks; using Certes.Acme; using Certes.Acme.Resource; namespace Certes { /// <summary> /// Extension methods for <see cref="IAuthorizationContext"/>. /// </summary> public static class IAuthorizationContextExtensions { /// <summary> /// Gets the HTTP challenge. /// </summary> /// <param name="authorizationContext">The authorization context.</param> /// <returns>The HTTP challenge, <c>null</c> if no HTTP challenge available.</returns> public static Task<IChallengeContext> Http(this IAuthorizationContext authorizationContext) => authorizationContext.Challenge(ChallengeTypes.Http01); /// <summary> /// Gets the DNS challenge. /// </summary> /// <param name="authorizationContext">The authorization context.</param> /// <returns>The DNS challenge, <c>null</c> if no DNS challenge available.</returns> public static Task<IChallengeContext> Dns(this IAuthorizationContext authorizationContext) => authorizationContext.Challenge(ChallengeTypes.Dns01); /// <summary> /// Gets the TLS ALPN challenge. /// </summary> /// <param name="authorizationContext">The authorization context.</param> /// <returns>The TLS ALPN challenge, <c>null</c> if no TLS ALPN challenge available.</returns> public static Task<IChallengeContext> TlsAlpn(this IAuthorizationContext authorizationContext) => authorizationContext.Challenge(ChallengeTypes.TlsAlpn01); /// <summary> /// Gets a challenge by type. /// </summary> /// <param name="authorizationContext">The authorization context.</param> /// <param name="type">The challenge type.</param> /// <returns>The challenge, <c>null</c> if no challenge found.</returns> public static async Task<IChallengeContext> Challenge(this IAuthorizationContext authorizationContext, string type) { var challenges = await authorizationContext.Challenges(); return challenges.FirstOrDefault(c => c.Type == type); } } }
43.6
123
0.655505
[ "MIT" ]
AMEST/certes
src/Certes/Extensions/IAuthorizationContextExtensions.cs
2,182
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("Topologify")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Topologify")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("a41a89c0-9c13-4950-8c89-a80b4f7fcec0")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.648649
84
0.744436
[ "MIT" ]
CNA-Bld/EOPlugin-Topologify
Topologify/Properties/AssemblyInfo.cs
1,396
C#
using BillsPaymentSystem.Core.IO.Contracts; using System; namespace BillsPaymentSystem.Core.IO { public class ConsoleWriter : IWriter { public void WriteLine(string text) { Console.WriteLine(text); } } }
18.142857
44
0.637795
[ "MIT" ]
bobo4aces/07.SoftUni-CSharpDBFundamentals
02. Databases Advanced - Entity Framework - 06. Advanced Relations/BillsPaymentSystem/BillsPaymentSystem.Core/IO/ConsoleWriter.cs
256
C#
// ************************************************************************** //Start Finance - An to manage your personal finances. //Copyright(C) 2016 Jijo Bose //Start Finance 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 3 of the License, or //(at your option) any later version. //Start Finance is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the //GNU General Public License for more details. //You should have received a copy of the GNU General Public License //along with Start Finance.If not, see<http://www.gnu.org/licenses/>. // *************************************************************************** using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SQLite.Net.Attributes; namespace StartFinance.Models { public class Assets { [PrimaryKey,AutoIncrement] public int ID { get; set; } [Unique, NotNull] public string AssetName { get; set; } [NotNull] public double AssetValue { get; set; } } }
32.756098
79
0.618764
[ "MIT" ]
001084786/Screenshots
Start-Finance-master/InstaRichie/Models/Assets.cs
1,345
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.AspNetCore.Http.Metadata; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.Http.HttpResults; /// <summary> /// An <see cref="IResult"/> that on execution will write an object to the response /// with status code Created (201) and Location header. /// Targets a registered route. /// </summary> public sealed class CreatedAtRoute : IResult, IEndpointMetadataProvider { /// <summary> /// Initializes a new instance of the <see cref="CreatedAtRoute"/> class with the values /// provided. /// </summary> /// <param name="routeValues">The route data to use for generating the URL.</param> internal CreatedAtRoute(object? routeValues) : this(routeName: null, routeValues: routeValues) { } /// <summary> /// Initializes a new instance of the <see cref="CreatedAtRoute"/> class with the values /// provided. /// </summary> /// <param name="routeName">The name of the route to use for generating the URL.</param> /// <param name="routeValues">The route data to use for generating the URL.</param> internal CreatedAtRoute( string? routeName, object? routeValues) { RouteName = routeName; RouteValues = new RouteValueDictionary(routeValues); } /// <summary> /// Gets the name of the route to use for generating the URL. /// </summary> public string? RouteName { get; } /// <summary> /// Gets the route data to use for generating the URL. /// </summary> public RouteValueDictionary RouteValues { get; } /// <summary> /// Gets the HTTP status code: <see cref="StatusCodes.Status201Created"/> /// </summary> public int StatusCode => StatusCodes.Status201Created; /// <inheritdoc/> public Task ExecuteAsync(HttpContext httpContext) { ArgumentNullException.ThrowIfNull(httpContext); var linkGenerator = httpContext.RequestServices.GetRequiredService<LinkGenerator>(); var url = linkGenerator.GetUriByRouteValues( httpContext, RouteName, RouteValues, fragment: FragmentString.Empty); if (string.IsNullOrEmpty(url)) { throw new InvalidOperationException("No route matches the supplied values."); } // Creating the logger with a string to preserve the category after the refactoring. var loggerFactory = httpContext.RequestServices.GetRequiredService<ILoggerFactory>(); var logger = loggerFactory.CreateLogger("Microsoft.AspNetCore.Http.Result.CreatedAtRouteResult"); httpContext.Response.Headers.Location = url; HttpResultsHelper.Log.WritingResultAsStatusCode(logger, StatusCode); httpContext.Response.StatusCode = StatusCode; return Task.CompletedTask; } /// <inheritdoc/> static void IEndpointMetadataProvider.PopulateMetadata(EndpointMetadataContext context) { ArgumentNullException.ThrowIfNull(context); context.EndpointMetadata.Add(new ProducesResponseTypeMetadata(StatusCodes.Status201Created)); } }
35.393617
105
0.689811
[ "MIT" ]
Akarachudra/kontur-aspnetcore-fork
src/Http/Http.Results/src/CreatedAtRoute.cs
3,327
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace RestaurantBooking.Responses.Cancel { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class CancelStrings { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal CancelStrings() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("RestaurantBooking.Responses.Cancel.CancelStrings", typeof(CancelStrings).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Ok, let&apos;s start over.. /// </summary> public static string CANCEL_CONFIRMED { get { return ResourceManager.GetString("CANCEL_CONFIRMED", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Ok, let&apos;s keep going.. /// </summary> public static string CANCEL_DENIED { get { return ResourceManager.GetString("CANCEL_DENIED", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Are you sure you want to cancel?. /// </summary> public static string CANCEL_PROMPT { get { return ResourceManager.GetString("CANCEL_PROMPT", resourceCulture); } } } }
41.208791
197
0.593067
[ "MIT" ]
3ve4me/botframework-solutions
skills/src/csharp/experimental/restaurantbooking/Responses/Cancel/CancelStrings.Designer.cs
3,752
C#
//********************************* bs::framework - Copyright 2018-2019 Marko Pintera ************************************// //*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********// using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace bs { /** @addtogroup Rendering * @{ */ /// <summary> /// Contains mesh vertex and index data used for initializing, updating and reading mesh data from Mesh. /// </summary> [ShowInInspector] public partial class MeshData : ScriptObject { private MeshData(bool __dummy0) { } protected MeshData() { } public MeshData(int numVertices, int numIndices, VertexLayout layout, IndexType indexType = IndexType.Index32) { Internal_create(this, numVertices, numIndices, layout, indexType); } /// <summary>An array of all vertex positions. Only valid if the vertex layout contains vertex positions.</summary> [ShowInInspector] [NativeWrapper] public Vector3[] Positions { get { return Internal_getPositions(mCachedPtr); } set { Internal_setPositions(mCachedPtr, value); } } /// <summary>An array of all vertex normals. Only valid if the vertex layout contains vertex normals.</summary> [ShowInInspector] [NativeWrapper] public Vector3[] Normals { get { return Internal_getNormals(mCachedPtr); } set { Internal_setNormals(mCachedPtr, value); } } /// <summary>An array of all vertex tangents. Only valid if the vertex layout contains vertex tangents.</summary> [ShowInInspector] [NativeWrapper] public Vector4[] Tangents { get { return Internal_getTangents(mCachedPtr); } set { Internal_setTangents(mCachedPtr, value); } } /// <summary>An array of all vertex colors. Only valid if the vertex layout contains vertex colors.</summary> [ShowInInspector] [NativeWrapper] public Color[] Colors { get { return Internal_getColors(mCachedPtr); } set { Internal_setColors(mCachedPtr, value); } } /// <summary> /// An array of all vertex texture coordinates in the UV0 channel. Only valid if the vertex layout contains UV0 /// coordinates. /// </summary> [ShowInInspector] [NativeWrapper] public Vector2[] UV0 { get { return Internal_getUV0(mCachedPtr); } set { Internal_setUV0(mCachedPtr, value); } } /// <summary> /// An array of all vertex texture coordinates in the UV1 channel. Only valid if the vertex layout contains UV1 /// coordinates. /// </summary> [ShowInInspector] [NativeWrapper] public Vector2[] UV1 { get { return Internal_getUV1(mCachedPtr); } set { Internal_setUV1(mCachedPtr, value); } } /// <summary>An array of all vertex bone weights. Only valid if the vertex layout contains bone weights.</summary> [ShowInInspector] [NativeWrapper] public BoneWeight[] BoneWeights { get { return Internal_getBoneWeights(mCachedPtr); } set { Internal_setBoneWeights(mCachedPtr, value); } } /// <summary>An array of all indices.</summary> [ShowInInspector] [NativeWrapper] public int[] Indices { get { return Internal_getIndices(mCachedPtr); } set { Internal_setIndices(mCachedPtr, value); } } /// <summary>Returns the number of vertices contained in the mesh.</summary> [NativeWrapper] public int VertexCount { get { return Internal_getVertexCount(mCachedPtr); } } /// <summary>Returns the number of indices contained in the mesh.</summary> [NativeWrapper] public int IndexCount { get { return Internal_getIndexCount(mCachedPtr); } } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_create(MeshData managedInstance, int numVertices, int numIndices, VertexLayout layout, IndexType indexType); [MethodImpl(MethodImplOptions.InternalCall)] private static extern Vector3[] Internal_getPositions(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setPositions(IntPtr thisPtr, Vector3[] value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern Vector3[] Internal_getNormals(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setNormals(IntPtr thisPtr, Vector3[] value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern Vector4[] Internal_getTangents(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setTangents(IntPtr thisPtr, Vector4[] value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern Color[] Internal_getColors(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setColors(IntPtr thisPtr, Color[] value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern Vector2[] Internal_getUV0(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setUV0(IntPtr thisPtr, Vector2[] value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern Vector2[] Internal_getUV1(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setUV1(IntPtr thisPtr, Vector2[] value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern BoneWeight[] Internal_getBoneWeights(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setBoneWeights(IntPtr thisPtr, BoneWeight[] value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern int[] Internal_getIndices(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_setIndices(IntPtr thisPtr, int[] value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern int Internal_getVertexCount(IntPtr thisPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern int Internal_getIndexCount(IntPtr thisPtr); } /** @} */ }
37.291925
146
0.744337
[ "MIT" ]
InsaneZeroGame/bsf
Source/Scripting/bsfSharp/Generated/RendererMeshData.generated.cs
6,004
C#
namespace Pulse.Common.Model.AgentScheduling.Abstract { // level 1: class activity public class AbstractAgentActivity { public string Name { set; get; } public string ActivityType { set; get; } public override string ToString() { return Name; } } }
22.714286
54
0.59434
[ "MIT" ]
vladkar/pulse-project-open
Pulse.Common/Model/AgentScheduling/Abstract/AbstractAgentActivity.cs
320
C#
// Copyright (c) 2008-2021, Hazelcast, Inc. 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. // <auto-generated> // This code was generated by a tool. // Hazelcast Client Protocol Code Generator // https://github.com/hazelcast/hazelcast-client-protocol // Change to this file will be lost if the code is regenerated. // </auto-generated> #pragma warning disable IDE0051 // Remove unused private members // ReSharper disable UnusedMember.Local // ReSharper disable RedundantUsingDirective // ReSharper disable CheckNamespace using System; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Hazelcast.Protocol.BuiltInCodecs; using Hazelcast.Protocol.CustomCodecs; using Hazelcast.Core; using Hazelcast.Messaging; using Hazelcast.Clustering; using Hazelcast.Serialization; using Microsoft.Extensions.Logging; namespace Hazelcast.Protocol.Codecs { /// <summary> /// Queries the map based on the specified predicate and returns the keys of matching entries. Specified predicate /// runs on all members in parallel. The collection is NOT backed by the map, so changes to the map are NOT reflected /// in the collection, and vice-versa. This method is always executed by a distributed query, so it may throw a /// QueryResultSizeExceededException if query result size limit is configured. ///</summary> #if SERVER_CODEC internal static class MapKeySetWithPagingPredicateServerCodec #else internal static class MapKeySetWithPagingPredicateCodec #endif { public const int RequestMessageType = 78848; // 0x013400 public const int ResponseMessageType = 78849; // 0x013401 private const int RequestInitialFrameSize = Messaging.FrameFields.Offset.PartitionId + BytesExtensions.SizeOfInt; private const int ResponseInitialFrameSize = Messaging.FrameFields.Offset.ResponseBackupAcks + BytesExtensions.SizeOfByte; #if SERVER_CODEC public sealed class RequestParameters { /// <summary> /// name of map ///</summary> public string Name { get; set; } /// <summary> /// specified query criteria. ///</summary> public Hazelcast.Protocol.Models.PagingPredicateHolder Predicate { get; set; } } #endif public static ClientMessage EncodeRequest(string name, Hazelcast.Protocol.Models.PagingPredicateHolder predicate) { var clientMessage = new ClientMessage { IsRetryable = true, OperationName = "Map.KeySetWithPagingPredicate" }; var initialFrame = new Frame(new byte[RequestInitialFrameSize], (FrameFlags) ClientMessageFlags.Unfragmented); initialFrame.Bytes.WriteIntL(Messaging.FrameFields.Offset.MessageType, RequestMessageType); initialFrame.Bytes.WriteIntL(Messaging.FrameFields.Offset.PartitionId, -1); clientMessage.Append(initialFrame); StringCodec.Encode(clientMessage, name); PagingPredicateHolderCodec.Encode(clientMessage, predicate); return clientMessage; } #if SERVER_CODEC public static RequestParameters DecodeRequest(ClientMessage clientMessage) { using var iterator = clientMessage.GetEnumerator(); var request = new RequestParameters(); iterator.Take(); // empty initial frame request.Name = StringCodec.Decode(iterator); request.Predicate = PagingPredicateHolderCodec.Decode(iterator); return request; } #endif public sealed class ResponseParameters { /// <summary> /// result keys for the query. ///</summary> public IList<IData> Response { get; set; } /// <summary> /// The updated anchor list. ///</summary> public Hazelcast.Protocol.Models.AnchorDataListHolder AnchorDataList { get; set; } } #if SERVER_CODEC public static ClientMessage EncodeResponse(ICollection<IData> response, Hazelcast.Protocol.Models.AnchorDataListHolder anchorDataList) { var clientMessage = new ClientMessage(); var initialFrame = new Frame(new byte[ResponseInitialFrameSize], (FrameFlags) ClientMessageFlags.Unfragmented); initialFrame.Bytes.WriteIntL(Messaging.FrameFields.Offset.MessageType, ResponseMessageType); clientMessage.Append(initialFrame); ListMultiFrameCodec.Encode(clientMessage, response, DataCodec.Encode); AnchorDataListHolderCodec.Encode(clientMessage, anchorDataList); return clientMessage; } #endif public static ResponseParameters DecodeResponse(ClientMessage clientMessage) { using var iterator = clientMessage.GetEnumerator(); var response = new ResponseParameters(); iterator.Take(); // empty initial frame response.Response = ListMultiFrameCodec.Decode(iterator, DataCodec.Decode); response.AnchorDataList = AnchorDataListHolderCodec.Decode(iterator); return response; } } }
40.843972
142
0.690571
[ "Apache-2.0" ]
alexb5dh/hazelcast-csharp-client
src/Hazelcast.Net/Protocol/Codecs/MapKeySetWithPagingPredicateCodec.cs
5,759
C#
using Nixi.Injections; using UnityEngine.UI; namespace ScriptExample.Audio { public sealed class AudioControllerWithInactive : MonoBehaviourInjectable { [NixInjectComponentFromChildren("SliderMusic", false)] public Slider musicSlider; [NixInjectComponentFromChildren("SliderSpatialisation", false)] public Slider spatialisationSlider; } }
27.5
77
0.745455
[ "MIT" ]
f-antoine/Nixi
Assets/ScriptExample/Audio/AudioControllerWithInactive.cs
387
C#
#pragma checksum "D:\CodingWork\Projects\NongMinGoProject\SimplCommerce\src\Modules\SimplCommerce.Module.NongMinGo\_Imports.razor" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "8a9804a1188708b018e9b38ddba736987a0bb5d8" // <auto-generated/> #pragma warning disable 1591 #pragma warning disable 0414 #pragma warning disable 0649 #pragma warning disable 0169 namespace SimplCommerce.Module.NongMinGo { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; #line 1 "D:\CodingWork\Projects\NongMinGoProject\SimplCommerce\src\Modules\SimplCommerce.Module.NongMinGo\_Imports.razor" using Microsoft.AspNetCore.Components.Web; #line default #line hidden public class _Imports : System.Object { #pragma warning disable 1998 protected void Execute() { } #pragma warning restore 1998 } } #pragma warning restore 1591
31.419355
214
0.759754
[ "Apache-2.0" ]
Coopathon2019/03_NongMinGo
src/Modules/SimplCommerce.Module.NongMinGo/obj/Debug/netstandard2.0/RazorDeclaration/_Imports.razor.g.cs
974
C#
using Avalonia.Controls; using Avalonia.Markup.Xaml; namespace Modern.Vice.PdbMonitor.Views { public class ProjectExplorer : UserControl { public ProjectExplorer() { InitializeComponent(); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } } }
18.473684
46
0.60114
[ "MIT" ]
MihaMarkic/modern-vice-pdb-monitor
source/Modern.Vice.PdbMonitor/Modern.Vice.PdbMonitor/Views/ProjectExplorer.axaml.cs
351
C#
// GBEmmy // Copyright (C) 2014 Tim Potze // // 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 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. // // For more information, please refer to <http://unlicense.org> namespace GBEmmy.Processor.Opcode.Operation { internal class XorOperation : IOperation { public bool Call(Z80 cpu, Operand operand1, Operand operand2, byte embedded) { cpu.ResetFlags(); cpu.ToggleFlag(Flags.Zero, (cpu.Register.A ^= cpu.GetByte(operand1)) == 0); return true; } } }
35.769231
87
0.689247
[ "Unlicense" ]
ikkentim/GBEmmy
src/GBEmmyOld/Processor/Opcode/Operation/XorOperation.cs
932
C#
using System; using System.Threading.Tasks; using Foundation; using NomadCode.UIExtensions; using Xamarin.Cognitive.Face.Model; using Xamarin.Cognitive.Face.Shared; using Xamarin.Cognitive.Face.Shared.Extensions; namespace Xamarin.Cognitive.Face.Sample.iOS { public partial class FaceViewController : BaseViewController { class Segues { public const string Verification = "Verification"; } public FaceViewController (IntPtr handle) : base (handle) { } partial void VerificationAction (NSObject sender) { ChooseVerify ().Forget (); } async Task ChooseVerify () { var verificationType = await this.ShowActionSheet ("Please Choose", "Choose verification type", ("Face and Face", VerificationType.FaceAndFace), ("Face and Person", VerificationType.FaceAndPerson)); if (verificationType == VerificationType.None) { return; } FaceState.Current.Verification.Type = verificationType; PerformSegue (Segues.Verification, this); } } }
22.108696
98
0.721731
[ "MIT" ]
colbylwilliams/Cognitive-Face-Xamarin
Xamarin.Cognitive.Face/Xamarin.Cognitive.Face.Sample/Xamarin.Cognitive.Face.Sample.iOS/View/FaceViewController.cs
1,019
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.IO { /// <devdoc> /// Provides data for the <see cref='System.IO.FileSystemWatcher.Renamed'/> event. /// </devdoc> public class RenamedEventArgs : FileSystemEventArgs { private readonly string? _oldName; private readonly string _oldFullPath; /// <devdoc> /// Initializes a new instance of the <see cref='System.IO.RenamedEventArgs'/> class. /// </devdoc> public RenamedEventArgs(WatcherChangeTypes changeType, string directory, string? name, string? oldName) : base(changeType, directory, name) { _oldName = oldName; _oldFullPath = Combine(Path.GetFullPath(directory), oldName); } /// <devdoc> /// Gets the previous fully qualified path of the affected file or directory. /// </devdoc> public string OldFullPath { get { return _oldFullPath; } } /// <devdoc> /// Gets the old name of the affected file or directory. /// </devdoc> public string? OldName { get { return _oldName; } } } }
29.340426
111
0.5562
[ "MIT" ]
goelanurag/runtime
src/libraries/System.IO.FileSystem.Watcher/src/System/IO/RenamedEventArgs.cs
1,379
C#
using System.Windows; using System.Windows.Controls; namespace Lol.Settings.InGame.UI.Units { public class Items : Control { #region DefaultStyleKey static Items() { DefaultStyleKeyProperty.OverrideMetadata(typeof(Items), new FrameworkPropertyMetadata(typeof(Items))); } #endregion } }
20.764706
114
0.651558
[ "MIT" ]
devncore-james/wpf-leagueoflegends
src/Lol.Settings.InGame/UI/Units/HotKey/Items.cs
355
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BookShopSystem.Models { /// <summary> /// 会员 /// </summary> public class MemberEntity { /// <summary> /// 用户编号 /// </summary> public long UserId { get; set; } /// <summary> /// 帐号 /// </summary> public string Account { get; set; } /// <summary> /// 职业 /// </summary> public long ProfessionId { get; set; } } }
18.666667
46
0.514286
[ "Apache-2.0" ]
a156845044/BookShopSystem
BookShopSystem.Models/MemberEntity.cs
582
C#
using System.Linq; using UnityEditor; using UnityEngine; namespace Zios.Unity.Editor.ImportSettings{ using Zios.Extensions; using Zios.Unity.Editor.Extensions; public class ImportSettings : AssetPostprocessor{ public void OnPreprocessModel(){ ModelImporter importer = (ModelImporter)assetImporter; if(importer.assetPath.ContainsAny(".fbx")){ importer.globalScale = 1.0f; } if(importer.importMaterials){ importer.meshCompression = ModelImporterMeshCompression.Off; importer.optimizeMesh = true; importer.importMaterials = false; importer.importTangents = ModelImporterTangents.None; importer.animationCompression = ModelImporterAnimationCompression.Off; importer.animationType = ModelImporterAnimationType.None; importer.generateAnimations = ModelImporterGenerateAnimations.None; } if(importer.assetPath.ContainsAny("@","Shared","Animation","Actions") && importer.animationType != ModelImporterAnimationType.Legacy){ importer.animationType = ModelImporterAnimationType.Legacy; importer.generateAnimations = ModelImporterGenerateAnimations.GenerateAnimations; importer.animationCompression = ModelImporterAnimationCompression.Off; importer.animationPositionError = 0; importer.animationWrapMode = WrapMode.ClampForever; importer.importAnimation = true; } } public void OnPreprocessTexture(){ TextureImporter importer = (TextureImporter)assetImporter; string assetName = importer.assetPath.Split("/").Last(); importer.npotScale = assetName.Contains(".exr") ? TextureImporterNPOTScale.ToNearest : TextureImporterNPOTScale.None; if(assetName.ContainsAny("Index","Outline","Shading","Interface")){ importer.wrapMode = TextureWrapMode.Clamp; importer.mipmapEnabled = false; //if(assetName.ContainsAny("Outline","Shading","Interface")){importer.SetTextureFormat(TextureImporterFormat.BC7);} if(assetName.ContainsAny("Index")){importer.SetTextureFormat(TextureImporterFormat.BC5);} //if(assetName.ContainsAny("Outline","Interface")){importer.filterMode = FilterMode.Trilinear;} if(assetName.ContainsAny("Index","Shading")){importer.filterMode = FilterMode.Point;} } } } }
48.666667
137
0.776712
[ "MIT" ]
z3nth10n/unity-themes
Codebase/Editor/@Unity/Editor/Systems/Import Settings/ImportSettings.cs
2,190
C#
namespace HallOfBeorn.Models { public enum StatType { Sphere, IsUnique, Threat_Cost, Resource_Cost, Willpower, Attack, Defense, Hit_Points, Threat, Engagement_Cost, Quest_Points, Stage_Number, Stage_Letter, Opposite_Stage_Letter, Victory_Points, Max_Per_Deck, Pass_Value, Eye_Icon, Siege_Points, Has_Horizontal_Art, Direction, Errata, } }
18.206897
30
0.532197
[ "MIT" ]
danpoage/hall-of-beorn
v2/src/HallOfBeorn/Models/StatType.cs
530
C#
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using vtortola.Redis; using Moq; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; namespace UnitTest.RedisClient.Api { [TestClass] public class RedisChannelTests { ProcedureCollection _procedures; Mock<ICommandConnection> _multiplex; Mock<IConnectionProvider<ICommandConnection>> _pool; Mock<IConnectionProvider<ISubscriptionConnection>> _subscriber; RedisChannel _channel; [TestInitialize] public void Init() { _procedures = ProcedureCollection.Empty; _multiplex = new Mock<ICommandConnection>(); _multiplex.Setup(x => x.ConnectAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult<Object>(null)); _pool = new Mock<IConnectionProvider<ICommandConnection>>(); _pool.Setup(x => x.ConnectAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult<Object>(null)); _subscriber = new Mock<IConnectionProvider<ISubscriptionConnection>>(); _subscriber.Setup(x => x.ConnectAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult<Object>(null)); _channel = new RedisChannel(new ExecutionPlanner(_procedures), _procedures, _multiplex.Object, _subscriber.Object, _pool.Object); } private Mock<ICommandConnection> MultiplexSetup() { _multiplex.Setup(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>())).Verifiable(); _multiplex.Setup(x => x.Dispose()).Throws(new Exception("Do not dispose multiplexed connections.")); _pool.Setup(x => x.Provide()).Throws(new Exception("Exclusive pool should not be used.")); return _multiplex; } private Mock<ICommandConnection> ExclusivePoolSetup() { var connection = new Mock<ICommandConnection>(); connection.Setup(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>())) .Callback((ExecutionToken t, CancellationToken c) => t.SetCompleted()) .Verifiable(); connection.Setup(x => x.Dispose()).Verifiable(); _pool.Setup(x => x.Provide()).Returns(connection.Object); _multiplex.Setup(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>())).Throws(new Exception()); return connection; } [TestMethod] public void RunWholeTransactionMultiplexed() { var connection = MultiplexSetup(); _channel.ExecuteAsync(@" MULTI INCR X EXEC"); connection.Verify(); } [TestMethod] public void RunWholeDiscardedTransactionMultiplexed() { var connection = MultiplexSetup(); _channel.ExecuteAsync(@" MULTI INCR X DISCARD"); connection.Verify(); } [TestMethod] public void RunWholeWatchedTransactionMultiplexed() { var connection = MultiplexSetup(); _channel.ExecuteAsync(@" WATCH whatever MULTI INCR X EXEC"); connection.Verify(); } [TestMethod] public void RunWholeDiscardedWathedTransactionMultiplexed() { var connection = MultiplexSetup(); _channel.ExecuteAsync(@" WATCH whatever MULTI INCR X DISCARD"); connection.Verify(); } [TestMethod] public void RunWholeUnWatchedTransactionMultiplexed() { var connection = MultiplexSetup(); _channel.ExecuteAsync(@" WATCH whatever INCR X UNWATCH"); connection.Verify(); } [TestMethod] public void ReusesStandaloneConnectionOnMulti() { var connection = ExclusivePoolSetup(); _channel.Execute(@" MULTI INCR X"); _channel.Execute(@" INCR X"); _channel.Execute(@" INCR X EXEC"); connection.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(3)); connection.Verify(x => x.Dispose(), Times.Once); } [TestMethod] public void ReusesStandaloneConnectionOnOpenWatch() { var connection = ExclusivePoolSetup(); _channel.Execute(@" WATCH INCR X"); _channel.Execute(@" INCR X"); _channel.Execute(@" INCR X UNWATCH"); connection.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(3)); connection.Verify(x => x.Dispose(), Times.Once); } [TestMethod] public void StandaloneConnectionForBlocking() { var connection = ExclusivePoolSetup(); _channel.Execute(@"BRPOP X"); connection.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(1)); connection.Verify(x => x.Dispose(), Times.Once); } [TestMethod] public void SwitchesBetweenConnections() { var standalone = new Mock<ICommandConnection>(); standalone.Setup(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>())) .Callback((ExecutionToken t, CancellationToken c) => t.SetCompleted()) .Verifiable(); standalone.Setup(x => x.Dispose()).Verifiable(); _pool.Setup(x => x.Provide()).Returns(standalone.Object); _multiplex.Setup(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>())) .Callback((ExecutionToken t, CancellationToken c) => t.SetCompleted()) .Verifiable(); _multiplex.Setup(x => x.Dispose()).Throws(new Exception("Do not dispose multiplexed connections.")); _channel.Execute(@" INCR X"); standalone.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(0)); _multiplex.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(1)); _channel.Execute(@" WATCH X GET X"); standalone.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(1)); _multiplex.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(1)); _channel.ExecuteAsync(@" MULTI INCR X EXEC"); standalone.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(2)); _multiplex.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(1)); standalone.Verify(x => x.Dispose(), Times.Once); _channel.Execute(@" INCR X"); standalone.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(2)); _multiplex.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(2)); } [TestMethod] public void SwitchesBetweenConnectionsEvenWithUnwatch() { var standalone = new Mock<ICommandConnection>(); standalone.Setup(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>())) .Callback((ExecutionToken t, CancellationToken c) => t.SetCompleted()) .Verifiable(); standalone.Setup(x => x.Dispose()).Verifiable(); _pool.Setup(x => x.Provide()).Returns(standalone.Object); _multiplex.Setup(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>())) .Callback((ExecutionToken t, CancellationToken c) => t.SetCompleted()) .Verifiable(); _multiplex.Setup(x => x.Dispose()).Throws(new Exception("Do not dispose multiplexed connections.")); _channel.Execute(@" INCR X"); standalone.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(0)); _multiplex.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(1)); _channel.Execute(@" WATCH X GET X"); standalone.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(1)); _multiplex.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(1)); _channel.ExecuteAsync(@" MULTI INCR X"); standalone.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(2)); _multiplex.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(1)); _channel.Execute(@" UNWATCH"); standalone.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(3)); _multiplex.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(1)); _channel.Execute(@" INCR X EXEC"); standalone.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(4)); _multiplex.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(1)); standalone.Verify(x => x.Dispose(), Times.Once); _channel.Execute(@" INCR X"); standalone.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(4)); _multiplex.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(2)); } [TestMethod] public void SwitchesBetweenConnectionsWithBlocking() { var standalone = new Mock<ICommandConnection>(); standalone.Setup(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>())) .Callback((ExecutionToken t, CancellationToken c) => t.SetCompleted()) .Verifiable(); standalone.Setup(x => x.Dispose()).Verifiable(); _pool.Setup(x => x.Provide()).Returns(standalone.Object); _multiplex.Setup(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>())) .Callback((ExecutionToken t, CancellationToken c) => t.SetCompleted()) .Verifiable(); _multiplex.Setup(x => x.Dispose()).Throws(new Exception("Do not dispose multiplexed connections.")); _channel.Execute(@"INCR X"); standalone.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(0)); _multiplex.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(1)); _channel.Execute(@"BLPOP X"); standalone.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(1)); _multiplex.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(1)); standalone.Verify(x => x.Dispose(), Times.Once); _channel.Execute(@"INCR X"); standalone.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(1)); _multiplex.Verify(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>()), Times.Exactly(2)); } [TestMethod] public void FixUnfinishedTransaction() { var connection = ExclusivePoolSetup(); var tokens = new List<ExecutionToken>(); connection.Setup(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>())) .Callback((ExecutionToken token, CancellationToken cancel) => { tokens.Add(token); }); _channel.ExecuteAsync(@" MULTI INCR X"); _channel.Dispose(); Assert.AreEqual(2, tokens.Count); Assert.IsInstanceOfType(tokens[1].CommandOperation, typeof(DiscardTransactionOperation)); } [TestMethod] public void FixUnfinishedWatch() { var connection = ExclusivePoolSetup(); var tokens = new List<ExecutionToken>(); connection.Setup(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>())) .Callback((ExecutionToken token, CancellationToken cancel) => { tokens.Add(token); }); _channel.ExecuteAsync(@" WATCH INCR X"); _channel.Dispose(); Assert.AreEqual(2, tokens.Count); Assert.IsInstanceOfType(tokens[1].CommandOperation, typeof(UnwatchOperation)); } [TestMethod] public void FixUnfinishedWatchAndTransaction() { var connection = ExclusivePoolSetup(); var tokens = new List<ExecutionToken>(); connection.Setup(x => x.Execute(It.IsAny<ExecutionToken>(), It.IsAny<CancellationToken>())) .Callback((ExecutionToken token, CancellationToken cancel) => { tokens.Add(token); }); _channel.ExecuteAsync(@" WATCH"); _channel.ExecuteAsync(@" MULTI INCR X"); _channel.Dispose(); Assert.AreEqual(3, tokens.Count); Assert.IsInstanceOfType(tokens[2].CommandOperation, typeof(DiscardTransactionOperation)); } } }
40.446524
141
0.555629
[ "MIT" ]
vtortola/RedisClient
Tests/UnitTest.RedisClient/Api/RedisChannelTests.cs
15,129
C#
using AutoUpdaterDotNET; using StatisticsAnalysisTool.Properties; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Threading; using System.Windows; namespace StatisticsAnalysisTool.Common { public static class Utilities { public static string DateFormat(string format, double hourModify) { if (string.IsNullOrWhiteSpace(format)) return new DateTime(1, 1, 1).ToString(CultureInfo.InvariantCulture); try { var value = DateTime.Parse(format, LanguageController.CurrentCultureInfo); value = value.AddHours(hourModify); return value.ToString(new CultureInfo(LanguageController.CurrentCultureInfo.TextInfo.CultureName)); } catch (FormatException ex) { Debug.Print(ex.ToString()); return new DateTime(0).ToString(CultureInfo.InvariantCulture); } } public static string DateFormat(DateTime format, double hourModify) => DateFormat(format.ToString(CultureInfo.InvariantCulture), hourModify); public static bool IsDateTimeOutdated(string format, double hourModify) { if (string.IsNullOrWhiteSpace(format)) return true; if (!DateTime.TryParse(format, out DateTime dateTime)) return true; return IsDateTimeOutdated(dateTime, hourModify); } public static bool IsDateTimeOutdated(DateTime dateTime, double hourModify) { dateTime = dateTime.AddHours(hourModify); return dateTime < DateTime.Now.ToUniversalTime(); } public static long MapUlongToLong(ulong ulongValue) => Convert.ToInt64(ulongValue); public static void AddRange<T>(this ConcurrentBag<T> @this, IEnumerable<T> toAdd) { foreach (var element in toAdd) { @this.Add(element); } } public static void AutoUpdate() { AutoUpdater.Start(Settings.Default.AutoUpdateConfigUrl); AutoUpdater.DownloadPath = Environment.CurrentDirectory; AutoUpdater.RunUpdateAsAdmin = false; AutoUpdater.ApplicationExitEvent += AutoUpdater_ApplicationExitEvent; } private static void AutoUpdater_ApplicationExitEvent() { Thread.Sleep(5000); Application.Current.Shutdown(); } public static bool IsWindowOpen<T>(string name = "") where T : Window { return string.IsNullOrEmpty(name) ? Application.Current.Windows.OfType<T>().Any() : Application.Current.Windows.OfType<T>().Any(w => w.Name.Equals(name)); } } }
34.488095
149
0.627891
[ "MIT" ]
sh4mzz/AlbionOnline-StatisticsAnalysis
StatisticsAnalysisTool/StatisticsAnalysisTool/Common/Utilities.cs
2,899
C#
using System.Collections.Generic; using GigHub.Core.Models; namespace GigHub.Core.Repositories { public interface IFollowingRepository { IEnumerable<Following> GetFollowingsByUserId(string userId); Following GetFollowing(string userId, string artistId); } }
26.090909
68
0.752613
[ "MIT" ]
HalfBlood-Prince/GigHub
GigHub/Core/Repositories/IFollowingRepository.cs
289
C#
#if USE_UNI_LUA using LuaAPI = UniLua.Lua; using RealStatePtr = UniLua.ILuaState; using LuaCSFunction = UniLua.CSharpFunctionDelegate; #else using LuaAPI = XLua.LuaDLL.Lua; using RealStatePtr = System.IntPtr; using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; #endif using XLua; using System.Collections.Generic; namespace XLua.CSObjectWrap { using Utils = XLua.Utils; public class XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapPathfindingEnumFlagAttributeWrapWrapWrapWrapWrap { public static void __Register(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.Type type = typeof(XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapPathfindingEnumFlagAttributeWrapWrapWrapWrap); Utils.BeginObjectRegister(type, L, translator, 0, 0, 0, 0); Utils.EndObjectRegister(type, L, translator, null, null, null, null, null); Utils.BeginClassRegister(type, L, __CreateInstance, 2, 0, 0); Utils.RegisterFunc(L, Utils.CLS_IDX, "__Register", _m___Register_xlua_st_); Utils.EndClassRegister(type, L, translator); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int __CreateInstance(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); if(LuaAPI.lua_gettop(L) == 1) { XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapPathfindingEnumFlagAttributeWrapWrapWrapWrap gen_ret = new XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapPathfindingEnumFlagAttributeWrapWrapWrapWrap(); translator.Push(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapPathfindingEnumFlagAttributeWrapWrapWrapWrap constructor!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m___Register_xlua_st_(RealStatePtr L) { try { { System.IntPtr _L = LuaAPI.lua_touserdata(L, 1); XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapPathfindingEnumFlagAttributeWrapWrapWrapWrap.__Register( _L ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } } }
27.336364
243
0.617226
[ "MIT" ]
zxsean/DCET
Unity/Assets/Model/XLua/Gen/XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapPathfindingEnumFlagAttributeWrapWrapWrapWrapWrap.cs
3,009
C#
namespace ASP.NET_MVC_Forum.Validation.Contracts { using ASP.NET_MVC_Forum.Domain.Entities; using System.Threading.Tasks; public interface ICommentReportValidationService { public Task ValidateExistsAsync(int reportId); public void ValidateNotNull(CommentReport report); public void ValidateStatus(string status); } }
22.9375
58
0.735695
[ "MIT" ]
donchodonev/ASP.NET-MVC-Blog
ASP.NET-MVC-Forum/ASP.NET-MVC-Forum.Validation.Contracts/ICommentReportValidationService.cs
369
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Stocky.WinForm.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Stocky.WinForm.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
38.680556
180
0.603232
[ "Apache-2.0" ]
ssnaik84/Lean
Stocky.WinForm/Properties/Resources.Designer.cs
2,787
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.Text; using System.Threading; using System.Globalization; using System.Threading.Tasks; using System.Runtime.CompilerServices; using System.Buffers; namespace System.IO { // This abstract base class represents a writer that can write a sequential // stream of characters. A subclass must minimally implement the // Write(char) method. // // This class is intended for character output, not bytes. // There are methods on the Stream class for writing bytes. public abstract partial class TextWriter : MarshalByRefObject, IDisposable { public static readonly TextWriter Null = new NullTextWriter(); // We don't want to allocate on every TextWriter creation, so cache the char array. private static readonly char[] s_coreNewLine = Environment.NewLine.ToCharArray(); /// <summary> /// This is the 'NewLine' property expressed as a char[]. /// It is exposed to subclasses as a protected field for read-only /// purposes. You should only modify it by using the 'NewLine' property. /// In particular you should never modify the elements of the array /// as they are shared among many instances of TextWriter. /// </summary> protected char[] CoreNewLine = s_coreNewLine; private string CoreNewLineStr = Environment.NewLine; // Can be null - if so, ask for the Thread's CurrentCulture every time. private IFormatProvider _internalFormatProvider; protected TextWriter() { _internalFormatProvider = null; // Ask for CurrentCulture all the time. } protected TextWriter(IFormatProvider formatProvider) { _internalFormatProvider = formatProvider; } public virtual IFormatProvider FormatProvider { get { if (_internalFormatProvider == null) { return CultureInfo.CurrentCulture; } else { return _internalFormatProvider; } } } public virtual void Close() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } // Clears all buffers for this TextWriter and causes any buffered data to be // written to the underlying device. This default method is empty, but // descendant classes can override the method to provide the appropriate // functionality. public virtual void Flush() { } public abstract Encoding Encoding { get; } // Returns the line terminator string used by this TextWriter. The default line // terminator string is a carriage return followed by a line feed ("\r\n"). // // Sets the line terminator string for this TextWriter. The line terminator // string is written to the text stream whenever one of the // WriteLine methods are called. In order for text written by // the TextWriter to be readable by a TextReader, only one of the following line // terminator strings should be used: "\r", "\n", or "\r\n". // public virtual string NewLine { get { return CoreNewLineStr; } set { if (value == null) { value = Environment.NewLine; } CoreNewLineStr = value; CoreNewLine = value.ToCharArray(); } } // Writes a character to the text stream. This default method is empty, // but descendant classes can override the method to provide the // appropriate functionality. // public virtual void Write(char value) { } // Writes a character array to the text stream. This default method calls // Write(char) for each of the characters in the character array. // If the character array is null, nothing is written. // public virtual void Write(char[] buffer) { if (buffer != null) { Write(buffer, 0, buffer.Length); } } // Writes a range of a character array to the text stream. This method will // write count characters of data into this TextWriter from the // buffer character array starting at position index. // public virtual void Write(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } for (int i = 0; i < count; i++) Write(buffer[index + i]); } // Writes a span of characters to the text stream. // public virtual void Write(ReadOnlySpan<char> source) { char[] buffer = ArrayPool<char>.Shared.Rent(source.Length); try { source.CopyTo(new Span<char>(buffer)); Write(buffer, 0, source.Length); } finally { ArrayPool<char>.Shared.Return(buffer); } } // Writes the text representation of a boolean to the text stream. This // method outputs either Boolean.TrueString or Boolean.FalseString. // public virtual void Write(bool value) { Write(value ? "True" : "False"); } // Writes the text representation of an integer to the text stream. The // text representation of the given value is produced by calling the // Int32.ToString() method. // public virtual void Write(int value) { Write(value.ToString(FormatProvider)); } // Writes the text representation of an integer to the text stream. The // text representation of the given value is produced by calling the // UInt32.ToString() method. // [CLSCompliant(false)] public virtual void Write(uint value) { Write(value.ToString(FormatProvider)); } // Writes the text representation of a long to the text stream. The // text representation of the given value is produced by calling the // Int64.ToString() method. // public virtual void Write(long value) { Write(value.ToString(FormatProvider)); } // Writes the text representation of an unsigned long to the text // stream. The text representation of the given value is produced // by calling the UInt64.ToString() method. // [CLSCompliant(false)] public virtual void Write(ulong value) { Write(value.ToString(FormatProvider)); } // Writes the text representation of a float to the text stream. The // text representation of the given value is produced by calling the // Float.toString(float) method. // public virtual void Write(float value) { Write(value.ToString(FormatProvider)); } // Writes the text representation of a double to the text stream. The // text representation of the given value is produced by calling the // Double.toString(double) method. // public virtual void Write(double value) { Write(value.ToString(FormatProvider)); } public virtual void Write(decimal value) { Write(value.ToString(FormatProvider)); } // Writes a string to the text stream. If the given string is null, nothing // is written to the text stream. // public virtual void Write(string value) { if (value != null) { Write(value.ToCharArray()); } } // Writes the text representation of an object to the text stream. If the // given object is null, nothing is written to the text stream. // Otherwise, the object's ToString method is called to produce the // string representation, and the resulting string is then written to the // output stream. // public virtual void Write(object value) { if (value != null) { IFormattable f = value as IFormattable; if (f != null) { Write(f.ToString(null, FormatProvider)); } else Write(value.ToString()); } } // Writes out a formatted string. Uses the same semantics as // String.Format. // public virtual void Write(string format, object arg0) { Write(string.Format(FormatProvider, format, arg0)); } // Writes out a formatted string. Uses the same semantics as // String.Format. // public virtual void Write(string format, object arg0, object arg1) { Write(string.Format(FormatProvider, format, arg0, arg1)); } // Writes out a formatted string. Uses the same semantics as // String.Format. // public virtual void Write(string format, object arg0, object arg1, object arg2) { Write(string.Format(FormatProvider, format, arg0, arg1, arg2)); } // Writes out a formatted string. Uses the same semantics as // String.Format. // public virtual void Write(string format, params object[] arg) { Write(string.Format(FormatProvider, format, arg)); } // Writes a line terminator to the text stream. The default line terminator // is Environment.NewLine, but this value can be changed by setting the NewLine property. // public virtual void WriteLine() { Write(CoreNewLine); } // Writes a character followed by a line terminator to the text stream. // public virtual void WriteLine(char value) { Write(value); WriteLine(); } // Writes an array of characters followed by a line terminator to the text // stream. // public virtual void WriteLine(char[] buffer) { Write(buffer); WriteLine(); } // Writes a range of a character array followed by a line terminator to the // text stream. // public virtual void WriteLine(char[] buffer, int index, int count) { Write(buffer, index, count); WriteLine(); } public virtual void WriteLine(ReadOnlySpan<char> source) { char[] buffer = ArrayPool<char>.Shared.Rent(source.Length); try { source.CopyTo(new Span<char>(buffer)); WriteLine(buffer, 0, source.Length); } finally { ArrayPool<char>.Shared.Return(buffer); } } // Writes the text representation of a boolean followed by a line // terminator to the text stream. // public virtual void WriteLine(bool value) { Write(value); WriteLine(); } // Writes the text representation of an integer followed by a line // terminator to the text stream. // public virtual void WriteLine(int value) { Write(value); WriteLine(); } // Writes the text representation of an unsigned integer followed by // a line terminator to the text stream. // [CLSCompliant(false)] public virtual void WriteLine(uint value) { Write(value); WriteLine(); } // Writes the text representation of a long followed by a line terminator // to the text stream. // public virtual void WriteLine(long value) { Write(value); WriteLine(); } // Writes the text representation of an unsigned long followed by // a line terminator to the text stream. // [CLSCompliant(false)] public virtual void WriteLine(ulong value) { Write(value); WriteLine(); } // Writes the text representation of a float followed by a line terminator // to the text stream. // public virtual void WriteLine(float value) { Write(value); WriteLine(); } // Writes the text representation of a double followed by a line terminator // to the text stream. // public virtual void WriteLine(double value) { Write(value); WriteLine(); } public virtual void WriteLine(decimal value) { Write(value); WriteLine(); } // Writes a string followed by a line terminator to the text stream. // public virtual void WriteLine(string value) { if (value != null) { Write(value); } Write(CoreNewLineStr); } // Writes the text representation of an object followed by a line // terminator to the text stream. // public virtual void WriteLine(object value) { if (value == null) { WriteLine(); } else { // Call WriteLine(value.ToString), not Write(Object), WriteLine(). // This makes calls to WriteLine(Object) atomic. IFormattable f = value as IFormattable; if (f != null) { WriteLine(f.ToString(null, FormatProvider)); } else { WriteLine(value.ToString()); } } } // Writes out a formatted string and a new line. Uses the same // semantics as String.Format. // public virtual void WriteLine(string format, object arg0) { WriteLine(string.Format(FormatProvider, format, arg0)); } // Writes out a formatted string and a new line. Uses the same // semantics as String.Format. // public virtual void WriteLine(string format, object arg0, object arg1) { WriteLine(string.Format(FormatProvider, format, arg0, arg1)); } // Writes out a formatted string and a new line. Uses the same // semantics as String.Format. // public virtual void WriteLine(string format, object arg0, object arg1, object arg2) { WriteLine(string.Format(FormatProvider, format, arg0, arg1, arg2)); } // Writes out a formatted string and a new line. Uses the same // semantics as String.Format. // public virtual void WriteLine(string format, params object[] arg) { WriteLine(string.Format(FormatProvider, format, arg)); } #region Task based Async APIs public virtual Task WriteAsync(char value) { var tuple = new Tuple<TextWriter, char>(this, value); return Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, char>)state; t.Item1.Write(t.Item2); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } public virtual Task WriteAsync(string value) { var tuple = new Tuple<TextWriter, string>(this, value); return Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, string>)state; t.Item1.Write(t.Item2); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } public Task WriteAsync(char[] buffer) { if (buffer == null) { return Task.CompletedTask; } return WriteAsync(buffer, 0, buffer.Length); } public virtual Task WriteAsync(char[] buffer, int index, int count) { var tuple = new Tuple<TextWriter, char[], int, int>(this, buffer, index, count); return Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, char[], int, int>)state; t.Item1.Write(t.Item2, t.Item3, t.Item4); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } public virtual Task WriteAsync(ReadOnlyMemory<char> source, CancellationToken cancellationToken = default(CancellationToken)) => source.DangerousTryGetArray(out ArraySegment<char> array) ? WriteAsync(array.Array, array.Offset, array.Count) : Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, ReadOnlyMemory<char>>)state; t.Item1.Write(t.Item2.Span); }, Tuple.Create(this, source), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); public virtual Task WriteLineAsync(char value) { var tuple = new Tuple<TextWriter, char>(this, value); return Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, char>)state; t.Item1.WriteLine(t.Item2); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } public virtual Task WriteLineAsync(string value) { var tuple = new Tuple<TextWriter, string>(this, value); return Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, string>)state; t.Item1.WriteLine(t.Item2); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } public Task WriteLineAsync(char[] buffer) { if (buffer == null) { return WriteLineAsync(); } return WriteLineAsync(buffer, 0, buffer.Length); } public virtual Task WriteLineAsync(char[] buffer, int index, int count) { var tuple = new Tuple<TextWriter, char[], int, int>(this, buffer, index, count); return Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, char[], int, int>)state; t.Item1.WriteLine(t.Item2, t.Item3, t.Item4); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } public virtual Task WriteLineAsync(ReadOnlyMemory<char> source, CancellationToken cancellationToken = default(CancellationToken)) => source.DangerousTryGetArray(out ArraySegment<char> array) ? WriteLineAsync(array.Array, array.Offset, array.Count) : Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, ReadOnlyMemory<char>>)state; t.Item1.WriteLine(t.Item2.Span); }, Tuple.Create(this, source), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); public virtual Task WriteLineAsync() { return WriteAsync(CoreNewLine); } public virtual Task FlushAsync() { return Task.Factory.StartNew(state => { ((TextWriter)state).Flush(); }, this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } #endregion private sealed class NullTextWriter : TextWriter { internal NullTextWriter() : base(CultureInfo.InvariantCulture) { } public override Encoding Encoding { get { return Encoding.Unicode; } } public override void Write(char[] buffer, int index, int count) { } public override void Write(string value) { } // Not strictly necessary, but for perf reasons public override void WriteLine() { } // Not strictly necessary, but for perf reasons public override void WriteLine(string value) { } public override void WriteLine(object value) { } public override void Write(char value) { } } public static TextWriter Synchronized(TextWriter writer) { if (writer == null) throw new ArgumentNullException(nameof(writer)); return writer is SyncTextWriter ? writer : new SyncTextWriter(writer); } internal sealed class SyncTextWriter : TextWriter, IDisposable { private readonly TextWriter _out; internal SyncTextWriter(TextWriter t) : base(t.FormatProvider) { _out = t; } public override Encoding Encoding => _out.Encoding; public override IFormatProvider FormatProvider => _out.FormatProvider; public override string NewLine { [MethodImpl(MethodImplOptions.Synchronized)] get { return _out.NewLine; } [MethodImpl(MethodImplOptions.Synchronized)] set { _out.NewLine = value; } } [MethodImpl(MethodImplOptions.Synchronized)] public override void Close() => _out.Close(); [MethodImpl(MethodImplOptions.Synchronized)] protected override void Dispose(bool disposing) { // Explicitly pick up a potentially methodimpl'ed Dispose if (disposing) ((IDisposable)_out).Dispose(); } [MethodImpl(MethodImplOptions.Synchronized)] public override void Flush() => _out.Flush(); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(char value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(char[] buffer) => _out.Write(buffer); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(char[] buffer, int index, int count) => _out.Write(buffer, index, count); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(bool value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(int value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(uint value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(long value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(ulong value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(float value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(double value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(Decimal value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(string value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(object value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(string format, object arg0) => _out.Write(format, arg0); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(string format, object arg0, object arg1) => _out.Write(format, arg0, arg1); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(string format, object arg0, object arg1, object arg2) => _out.Write(format, arg0, arg1, arg2); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(string format, object[] arg) => _out.Write(format, arg); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine() => _out.WriteLine(); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(char value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(decimal value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(char[] buffer) => _out.WriteLine(buffer); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(char[] buffer, int index, int count) => _out.WriteLine(buffer, index, count); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(bool value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(int value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(uint value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(long value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(ulong value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(float value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(double value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(string value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(object value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(string format, object arg0) => _out.WriteLine(format, arg0); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(string format, object arg0, object arg1) => _out.WriteLine(format, arg0, arg1); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(string format, object arg0, object arg1, object arg2) => _out.WriteLine(format, arg0, arg1, arg2); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(string format, object[] arg) => _out.WriteLine(format, arg); // // On SyncTextWriter all APIs should run synchronously, even the async ones. // [MethodImpl(MethodImplOptions.Synchronized)] public override Task WriteAsync(char value) { Write(value); return Task.CompletedTask; } [MethodImpl(MethodImplOptions.Synchronized)] public override Task WriteAsync(string value) { Write(value); return Task.CompletedTask; } [MethodImpl(MethodImplOptions.Synchronized)] public override Task WriteAsync(char[] buffer, int index, int count) { Write(buffer, index, count); return Task.CompletedTask; } [MethodImpl(MethodImplOptions.Synchronized)] public override Task WriteLineAsync(char value) { WriteLine(value); return Task.CompletedTask; } [MethodImpl(MethodImplOptions.Synchronized)] public override Task WriteLineAsync(string value) { WriteLine(value); return Task.CompletedTask; } [MethodImpl(MethodImplOptions.Synchronized)] public override Task WriteLineAsync(char[] buffer, int index, int count) { WriteLine(buffer, index, count); return Task.CompletedTask; } [MethodImpl(MethodImplOptions.Synchronized)] public override Task FlushAsync() { Flush(); return Task.CompletedTask; } } } }
35.175317
141
0.569859
[ "MIT" ]
ArthurBrussee/corefx
src/System.Runtime.Extensions/src/System/IO/TextWriter.cs
30,497
C#
#nullable enable using NUnit.Framework; using System; using static PrimeFuncPack.UnitTest.TestData; namespace PrimeFuncPack.Primitives.Tests { partial class StringsTests { [Test] public void ToStringOrEmpty_Ref_SourceIsNull_ExpectEmpty() { ToStringStubRefType? source = null; var actual = Strings.ToStringOrEmpty(source); Assert.IsEmpty(actual); } [Test] public void ToStringOrEmpty_Ref_SourceToStringIsNull_ExpectEmpty() { ToStringStubRefType? source = new(null); var actual = Strings.ToStringOrEmpty(source); Assert.IsEmpty(actual); } [Test] [TestCase(EmptyString)] [TestCase(WhiteSpaceString)] [TestCase(TabString)] [TestCase(SomeString)] public void ToStringOrEmpty_Ref_SourceToStringIsNotNull_ExpectActualToStringValue( string sourceToStringValue) { ToStringStubRefType? source = new(sourceToStringValue); var actual = Strings.ToStringOrEmpty(source); Assert.AreEqual(sourceToStringValue, actual); } } }
26.75
90
0.638063
[ "MIT" ]
pfpack/pfpack-primitives
src/primitives/Primitives.Tests/Strings.Tests/ToStringOrEmpty_Ref.cs
1,179
C#
#pragma warning disable CS1591 using Newtonsoft.Json; namespace Discord.API { internal class Sticker { [JsonProperty("id")] public ulong Id { get; set; } [JsonProperty("pack_id")] public ulong PackId { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("description")] public string Desription { get; set; } [JsonProperty("tags")] public Optional<string> Tags { get; set; } [JsonProperty("type")] public StickerType Type { get; set; } [JsonProperty("format_type")] public StickerFormatType FormatType { get; set; } [JsonProperty("available")] public bool? Available { get; set; } [JsonProperty("guild_id")] public Optional<ulong> GuildId { get; set; } [JsonProperty("user")] public Optional<User> User { get; set; } [JsonProperty("sort_value")] public int? SortValue { get; set; } } }
31.40625
57
0.58408
[ "MIT" ]
killerfrienddk/Discord.Net-Labs
src/Discord.Net.Rest/API/Common/Sticker.cs
1,005
C#
// T4 code generation is enabled for model 'C:\2019-09-c-sharp-labs\labs\Just_Do_It_12_Rabbit_Explosion\Model1.edmx'. // To enable legacy code generation, change the value of the 'Code Generation Strategy' designer // property to 'Legacy ObjectContext'. This property is available in the Properties Window when the model // is open in the designer. // If no context and entity classes have been generated, it may be because you created an empty model but // have not yet chosen which version of Entity Framework to use. To generate a context class and entity // classes for your model, open the model in the designer, right-click on the designer surface, and // select 'Update Model from Database...', 'Generate Database from Model...', or 'Add Code Generation // Item...'.
77.6
119
0.765464
[ "MIT" ]
Ryan-Paul-Burdus/2019-09-c-sharp-labs
labs/Just_Do_It_12_Rabbit_Explosion/Model1.Designer.cs
778
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace ZibicoCMS.WebUI { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); } } }
21.526316
60
0.689487
[ "MIT" ]
onursteknik/ZibicoCMS
ZibicoCMS.WebUI/Global.asax.cs
411
C#
namespace D365FOSecurityConverter.Models { public enum LayerType { Role = 1, Duty = 2, Privilege = 3 } public enum ProcessingDirection { Child = 0, Parent = 1 } }
14.3125
41
0.519651
[ "MIT" ]
ameyer505/D365FOSecurityConverter
D365FOSecurityConverter/Models/Enums.cs
231
C#
namespace PartlyRebuildIdentity.Models.Interfaces { public interface IClaim<TUser> : IInCovariant<TUser> { TUser UserId { get; } } }
21.857143
56
0.673203
[ "MIT" ]
kraskoo/PartlyRebuildMicrosoftIdentityUser
PartlyRebuildIdentity.Models/Interfaces/IClaim.cs
155
C#
using System; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Threading.Tasks; using System.Windows.Threading; using Apteco.Diagnostics.UI.Annotations; namespace Apteco.Diagnostics.UI.Utils { public class ViewModelBase: INotifyPropertyChanged { #region events public event PropertyChangedEventHandler PropertyChanged; #endregion #region protected methods protected void RunOnUIThread(Action method) { if (Dispatcher.CurrentDispatcher.CheckAccess()) method(); else Dispatcher.CurrentDispatcher.BeginInvoke(method); } #endregion #region event handlers [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion } }
19.847826
91
0.733844
[ "Apache-2.0" ]
Apteco/process-diagnostics
Apteco.Diagnostics.UI/Utils/ViewModelBase.cs
915
C#
using System.IO; #if UNITY_EDITOR using UnityEditor; #endif public static class Utility { public static void CreateDirectoryRecursive(string path) { #if UNITY_EDITOR path = path.TrimEnd('/'); var currentPath = ""; foreach (var name in path.Split(new char[] { '/' })) { if (!AssetDatabase.IsValidFolder(currentPath + '/' + name)) { AssetDatabase.CreateFolder(currentPath, name); } if (currentPath == string.Empty) { currentPath += name; } else { currentPath += '/' + name; } } #endif } public static string GetDirectoryName(string filePath) { return Path.GetDirectoryName(filePath).Replace('\\', '/'); } public static string AssetPathToLoadDirectory(string assetPath) { assetPath = assetPath.Remove(0, assetPath.IndexOf("Resources/") + "Resources/".Length); return assetPath.Remove(assetPath.Length - ".asset".Length); } }
26.365854
95
0.555967
[ "Apache-2.0" ]
StoneDot/UnitySync-Unity
Assets/UnitySync/Scripts/Utility.cs
1,083
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; namespace DbContextScope.Demo.Repositories { public interface IReadonlyRepository<T> { T Get(Expression<Func<T, bool>> predicate); Task<T> GetAsync(Expression<Func<T, bool>> predicate); List<T> GetWithInclude(params Expression<Func<T, object>>[] includeProperties); Task<List<T>> GetWithIncludeAsync(params Expression<Func<T, object>>[] includeProperties); List<T> GetWithInclude(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] includeProperties); Task<List<T>> GetWithIncludeAsync(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] includeProperties); IQueryable<T> GetAll(); IQueryable<T> GetAll(Expression<Func<T, bool>> predicate); } }
32.214286
135
0.710643
[ "MIT" ]
sapphirenk/DbContextScope
Demo/Repositories/IReadonlyRepository.cs
904
C#
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. using UnrealBuildTool; public class ProfilingBlocks : ModuleRules { public ProfilingBlocks(ReadOnlyTargetRules Target) : base(Target) { PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs; PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "HeadMountedDisplay" }); } }
27.357143
124
0.767624
[ "MIT" ]
ADMTec/UE4-Cpp-Tutorials
Profiling_Code/Source/ProfilingBlocks/ProfilingBlocks.Build.cs
383
C#
//namespace Morsley.UK.People.Messaging; //// Listens //public class Subscriber //{ //}
12.25
42
0.622449
[ "MIT" ]
john-morsley/Users
src/Infrastructure/Morsley.UK.People.Messaging/Subscriber.cs
100
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.Mariadb.V20170312.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class ModifyBackupTimeRequest : AbstractModel { /// <summary> /// 实例ID,形如:tdsql-ow728lmc,可以通过 DescribeDBInstances 查询实例详情获得。 /// </summary> [JsonProperty("InstanceId")] public string InstanceId{ get; set; } /// <summary> /// 每天备份执行的区间的开始时间,格式 mm:ss,形如 22:00 /// </summary> [JsonProperty("StartBackupTime")] public string StartBackupTime{ get; set; } /// <summary> /// 每天备份执行的区间的结束时间,格式 mm:ss,形如 23:59 /// </summary> [JsonProperty("EndBackupTime")] public string EndBackupTime{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> internal override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "InstanceId", this.InstanceId); this.SetParamSimple(map, prefix + "StartBackupTime", this.StartBackupTime); this.SetParamSimple(map, prefix + "EndBackupTime", this.EndBackupTime); } } }
32.62069
87
0.645349
[ "Apache-2.0" ]
ImEdisonJiang/tencentcloud-sdk-dotnet
TencentCloud/Mariadb/V20170312/Models/ModifyBackupTimeRequest.cs
2,012
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers.Common; using CSSyntax = Microsoft.CodeAnalysis.CSharp.Syntax; using VBSyntax = Microsoft.CodeAnalysis.VisualBasic.Syntax; namespace Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers { [ApplicableComponents(ProjectComponents.AspNetCore)] [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class HttpContextCurrentAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = "UA0005"; private const string Category = "Upgrade"; private const string TargetTypeSimpleName = "HttpContext"; private const string TargetMember = "Current"; private const string TargetPropertySymbolName = "Microsoft.AspNetCore.Mvc.ControllerBase.HttpContext"; private static readonly string[] TargetTypeSymbolNames = new[] { "System.Web.HttpContext", "Microsoft.AspNetCore.Http.HttpContext" }; private static readonly LocalizableString Title = new LocalizableResourceString(nameof(Resources.HttpContextCurrentTitle), Resources.ResourceManager, typeof(Resources)); private static readonly LocalizableString MessageFormat = new LocalizableResourceString(nameof(Resources.HttpContextCurrentMessageFormat), Resources.ResourceManager, typeof(Resources)); private static readonly LocalizableString Description = new LocalizableResourceString(nameof(Resources.HttpContextCurrentDescription), Resources.ResourceManager, typeof(Resources)); private static readonly DiagnosticDescriptor Rule = new(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { if (context is null) { throw new ArgumentNullException(nameof(context)); } context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); context.RegisterSimpleMemberAccessExpression(AnalyzeMemberAccessExpressionsCsharp, AnalyzeMemberAccessExpressionsVb); } private void AnalyzeMemberAccessExpressionsCsharp(SyntaxNodeAnalysisContext context) { var memberAccessExpression = (CSSyntax.MemberAccessExpressionSyntax)context.Node; // If the accessed member isn't named "Current" bail out if (!TargetMember.Equals(memberAccessExpression.Name.Identifier.ValueText, StringComparison.Ordinal)) { return; } // If the call is to a method called Current then bail out since they're // not using the HttpContext.Current property if (memberAccessExpression.Parent is CSSyntax.InvocationExpressionSyntax) { return; } // Get the identifier accessed var accessedIdentifier = memberAccessExpression.Expression switch { CSSyntax.IdentifierNameSyntax i => i, CSSyntax.MemberAccessExpressionSyntax m => m.DescendantNodes().OfType<CSSyntax.IdentifierNameSyntax>().LastOrDefault(), _ => null }; AnalyzeMemberAccessExpressions(context, memberAccessExpression, accessedIdentifier, accessedIdentifier?.Identifier.ValueText); } private void AnalyzeMemberAccessExpressionsVb(SyntaxNodeAnalysisContext context) { var memberAccessExpression = (VBSyntax.MemberAccessExpressionSyntax)context.Node; // If the accessed member isn't named "Current" bail out if (!TargetMember.Equals(memberAccessExpression.Name.Identifier.ValueText, StringComparison.Ordinal)) { return; } // If the call is to a method called Current then bail out since they're // not using the HttpContext.Current property if (memberAccessExpression.Parent is VBSyntax.InvocationExpressionSyntax) { return; } // Get the identifier accessed var accessedIdentifier = memberAccessExpression.Expression switch { VBSyntax.IdentifierNameSyntax i => i, VBSyntax.MemberAccessExpressionSyntax m => m.DescendantNodes().OfType<VBSyntax.IdentifierNameSyntax>().LastOrDefault(), _ => null }; AnalyzeMemberAccessExpressions(context, memberAccessExpression, accessedIdentifier, accessedIdentifier?.Identifier.ValueText); } private static void AnalyzeMemberAccessExpressions(SyntaxNodeAnalysisContext context, SyntaxNode memberAccessExpression, SyntaxNode? accessedIdentifier, string? identifierValue) { // Return if the accessed identifier wasn't from a simple member access expression or identifier, or if it doesn't match HttpContext if (accessedIdentifier is null || !TargetTypeSimpleName.Equals(identifierValue, StringComparison.Ordinal)) { return; } if (!TryMatchSymbol(context, accessedIdentifier)) { return; } var diagnostic = Diagnostic.Create(Rule, memberAccessExpression.GetLocation()); context.ReportDiagnostic(diagnostic); } /// <summary> /// Attempts to match against an identifier's symbol against ASP.NET's HttpContext. /// If a symbol is resolved, it must match System.Web.HttpContext or /// Microsoft.AspNetCore.Http.HttpContext exactly. /// </summary> /// <param name="context">The analysis context.</param> /// <param name="accessedIdentifier">The accessedIdentifier that was found.</param> /// <returns>Returns true if the identifier's symbol matches ASP.NET's HttpContext or if no symbol was found.</returns> private static bool TryMatchSymbol(SyntaxNodeAnalysisContext context, SyntaxNode accessedIdentifier) { // If the accessed identifier resolves to a type symbol other than System.Web.HttpContext or // Microsoft.AspNetCore.Http.HttpContext, then bail out since it means the user is calling // some other similarly named API. This allows diagnostics on Microsoft.AspNetCore.Http.HttpContext // in addition to System.Web.HttpContext since ASP.NET Core's HttpContext doesn't have a Current // property so any attempt to access such a property probably indicates a partially upgraded // call site that needs remedied. var accessedSymbol = context.SemanticModel.GetSymbolInfo(accessedIdentifier).Symbol; if (accessedSymbol is INamedTypeSymbol symbol) { if (!TargetTypeSymbolNames.Any(name => symbol.ToDisplayString(NullableFlowState.NotNull).Equals(name, StringComparison.Ordinal))) { return false; } } else if (accessedSymbol is IPropertySymbol propSymbol) { // If the HttpContext reference occurs inside a controller, HttpContext.Current can look // like a reference to the ControllerBase.HttpContext property. However, these should still // be flagged because .Current won't exist in ASP.NET Core. Therefore, bail out for // property symbols only if they are not ControllerBase.HttpContext. if (!TargetPropertySymbolName.Equals(propSymbol.ToDisplayString(), StringComparison.Ordinal)) { return false; } } else if (accessedSymbol != null) { // If the accessed identifier resolves to a symbol other than a type or property symbol, bail out // since it's not a reference to System.Web.HttpContext return false; } return true; } } }
50.85119
193
0.678684
[ "MIT" ]
Leosamus/upgrade-assistant
src/extensions/default/analyzers/Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers/HttpContextCurrentAnalyzer.cs
8,545
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("XlFormulas")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("XlFormulas")] [assembly: AssemblyCopyright("Copyright © Microsoft 2012")] [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("7befd179-a193-4590-b174-85e8261f94af")] // 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")]
39.621622
86
0.719645
[ "MIT" ]
jdm7dv/financial
windows/CsForFinancialMarkets/CsForFinancialMarkets/UtilityClassLibrary/Automation Add-In XlFormulas/Properties/AssemblyInfo.cs
1,469
C#
namespace DailyCodingProblem; /// <summary> /// A Cartesian tree with sequence S is a binary tree defined by the following two properties: /// It is heap-ordered, so that each parent value is strictly less than that of its children. /// An in-order traversal of the tree produces nodes with values that correspond exactly to S. /// For example, given the sequence[3, 2, 6, 1, 9], the resulting Cartesian tree would be: /// 1 /// / \ /// 2 9 /// / \ /// 3 6 /// Given a sequence S, construct the corresponding Cartesian tree. /// </summary> public class D01048 { // 1. 用单调栈维护最右链 // 2. 每次插入当前的i,在单调栈中不停弹出栈顶,直到栈顶fa满足val[fa]<val[i],则最后一次弹出的就是j // 3. 将i作为fa的右儿子,j作为i的左儿子 // 4. 如果没有找到右链上的节点,那么i就是新根,把原来的树当成i的左儿子 public static void Exection() { var nums = new int[] { 3, 2, 6, 1, 9 }; var stack = new Stack<Tree>(); Tree? node = null; Tree newNode; Tree? last = null; var n = nums.Length; for (int i = 0; i < n; i++) { newNode = new Tree(i, nums[i]); while (stack.Any()) { node = stack.Peek(); //直到栈顶的元素的Value大于当前结点的Value if (node.Value > newNode.Value) { //将原来的右子链挂载到newNode的左子树 if (node.Right != null) { node.Right.Parent = newNode; newNode.Left = node.Right; } //将新插入的节点插入,作为右链的最后 node.Right = newNode; newNode.Parent = node; break; } last = stack.Pop(); } // 如果当前节点把栈全部弹空了,就要把原先的根节点作为当前节点的左子节点 if (!stack.Any() && last != null) { newNode.Left = last; last.Parent = newNode; } stack.Push(newNode); } while (stack.Any()) { node = stack.Pop(); } Display(node); } private static void Display(Tree? node) { if (node == null) { return; } Display(node.Left); Console.Write(node.Value + " ,"); Display(node.Right); } public class Tree { public Tree(int index, int value) { Index = index; Value = value; } public int Value { get; set; } public int Index { get; set; } public Tree Left { get; set; } public Tree Right { get; set; } public Tree Parent { get; set; } } } // for(int i=1;i<=n;i++) // { // int j = 0; // while(v.size() && a[v.back()]>a[i]) // { // j=v.back(); // v.pop_back(); // } // if (!v.size()) // root = i; // else // rs[v.back()] = i; // ls[i] = j; // v.push_back(i); // }
27.036697
94
0.45945
[ "Apache-2.0" ]
futugyou/CodeFragments
Algorithm/DailyCodingProblem/D01048.cs
3,289
C#
namespace Panda.ViewModels.Users { public class LoginInputModel { public string Username { get; set; } public string Password { get; set; } } }
19.222222
44
0.618497
[ "MIT" ]
tonchevaAleksandra/C-Sharp-Web-Development-SoftUni-Problems
C# Web Basic/SUS September 2020 Session/Panda/ViewModels/Users/LoginInputModel.cs
175
C#
 using UnityEngine; using UnityEngine.UI; namespace BeatSaberMarkupLanguage.Tags { class PrimaryButtonTag : ButtonTag { public override string[] Aliases => new[] { "primary-button", "action-button" }; public override string PrefabButton => "PlayButton"; public override GameObject CreateObject(Transform parent) { return base.CreateObject(parent).AddComponent<LayoutElement>().gameObject; } } }
25.666667
88
0.67316
[ "MIT" ]
Futuremappermydud/BeatSaberMarkupLanguage
BeatSaberMarkupLanguage/Tags/PrimaryButtonTag.cs
464
C#
namespace TwitchIrcHub; public static class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } private static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); }
25.714286
91
0.680556
[ "MIT" ]
icecreamdatabase/TwitchIrcHub
TwitchIrcHub/Program.cs
360
C#
using NHapi.Base.Parser; using NHapi.Base; using NHapi.Base.Log; using System; using System.Collections.Generic; using NHapi.Model.V251.Segment; using NHapi.Model.V251.Datatype; using NHapi.Base.Model; namespace NHapi.Model.V251.Group { ///<summary> ///Represents the ORM_O01_PATIENT_VISIT Group. A Group is an ordered collection of message /// segments that can repeat together or be optionally in/excluded together. /// This Group contains the following elements: ///<ol> ///<li>0: PV1 (Patient Visit) </li> ///<li>1: PV2 (Patient Visit - Additional Information) optional </li> ///</ol> ///</summary> [Serializable] public class ORM_O01_PATIENT_VISIT : AbstractGroup { ///<summary> /// Creates a new ORM_O01_PATIENT_VISIT Group. ///</summary> public ORM_O01_PATIENT_VISIT(IGroup parent, IModelClassFactory factory) : base(parent, factory){ try { this.add(typeof(PV1), true, false); this.add(typeof(PV2), false, false); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating ORM_O01_PATIENT_VISIT - this is probably a bug in the source code generator.", e); } } ///<summary> /// Returns PV1 (Patient Visit) - creates it if necessary ///</summary> public PV1 PV1 { get{ PV1 ret = null; try { ret = (PV1)this.GetStructure("PV1"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns PV2 (Patient Visit - Additional Information) - creates it if necessary ///</summary> public PV2 PV2 { get{ PV2 ret = null; try { ret = (PV2)this.GetStructure("PV2"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } } }
29.885714
159
0.68738
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
AMCN41R/nHapi
src/NHapi.Model.V251/Group/ORM_O01_PATIENT_VISIT.cs
2,092
C#
namespace AlfredoRevillaWebshop.Services.Models { public class GetProductsServiceModel { public int MaxRecords { get; set; } public int StartIndex { get; set; } } }
24.125
48
0.663212
[ "MIT" ]
alfredorevilla/webshop
src/AlfredoRevillaWebshop/Services/Models/GetProductsServiceModel.cs
195
C#
using System; using Content.Shared.GameObjects.Components.Power; using Content.Shared.Utility; using SS14.Server.GameObjects; using SS14.Shared.GameObjects; namespace Content.Server.GameObjects.Components.Power { /// <summary> /// Handles the "user-facing" side of the actual SMES object. /// This is operations that are specific to the SMES, like UI and visuals. /// Code interfacing with the powernet is handled in <see cref="PowerStorageComponent" />. /// </summary> public class SmesComponent : Component { public override string Name => "Smes"; PowerStorageComponent Storage; AppearanceComponent Appearance; int LastChargeLevel = 0; ChargeState LastChargeState; public override void Initialize() { base.Initialize(); Storage = Owner.GetComponent<PowerStorageComponent>(); Appearance = Owner.GetComponent<AppearanceComponent>(); } public void OnUpdate() { var newLevel = CalcChargeLevel(); if (newLevel != LastChargeLevel) { LastChargeLevel = newLevel; Appearance.SetData(SmesVisuals.LastChargeLevel, newLevel); } var newState = Storage.GetChargeState(); if (newState != LastChargeState) { LastChargeState = newState; Appearance.SetData(SmesVisuals.LastChargeState, newState); } } int CalcChargeLevel() { return ContentHelpers.RoundToLevels(Storage.Charge, Storage.Capacity, 6); } } }
30.759259
98
0.610476
[ "MIT" ]
praisenarsie/space-station-14-content
Content.Server/GameObjects/Components/Power/SmesComponent.cs
1,663
C#
using System.Collections.Generic; using System.Threading.Tasks; using MeetingApp.Data.Models; using Microsoft.Azure.Cosmos.Table; namespace MeetingApp.Data.Repositories.Notes { /// <summary> /// Interface for table operations for Notes table /// </summary> public interface INotesRepository { /// <summary> /// Store or update notes in table storage. /// </summary> /// <param name="entity">Represents notes entity used for storage and retrieval.</param> /// <returns><see cref="Task"/> that represents notes entity is saved or updated.</returns> Task<TableResult> StoreOrUpdateQuestionEntityAsync(NotesEntity entity); /// <summary> /// Get notes from table storage. /// </summary> /// <returns><see cref="Task"/> Already saved entity detail.</returns> Task<IEnumerable<NotesEntity>> GetNotes(string email); } }
34.333333
99
0.656958
[ "MIT" ]
AbhijeetThakur-msft/Microsoft-Teams-Samples
samples/meeting-recruitment-app/csharp/MeetingApp/Data/Repositories/Notes/INotesRepository.cs
929
C#
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Collections.Generic; using System.Windows; using System.Diagnostics; using System.Windows.Controls; using ICSharpCode.WpfDesign.Extensions; using ICSharpCode.WpfDesign.Designer.Controls; namespace ICSharpCode.WpfDesign.Designer.Extensions { /// <summary> /// Provides <see cref="IPlacementBehavior"/> behavior for <see cref="Grid"/>. /// </summary> [ExtensionFor(typeof(Grid), OverrideExtension=typeof(DefaultPlacementBehavior))] public sealed class GridPlacementSupport : SnaplinePlacementBehavior { Grid grid; private bool enteredIntoNewContainer; protected override void OnInitialized() { base.OnInitialized(); grid = (Grid)this.ExtendedItem.Component; } double GetColumnOffset(int index) { // when the grid has no columns, we still need to return 0 for index=0 and grid.Width for index=1 if (index == 0) return 0; else if (index < grid.ColumnDefinitions.Count) return grid.ColumnDefinitions[index].Offset; else return grid.ActualWidth; } double GetRowOffset(int index) { if (index == 0) return 0; else if (index < grid.RowDefinitions.Count) return grid.RowDefinitions[index].Offset; else return grid.ActualHeight; } const double epsilon = 0.00000001; int GetColumnIndex(double x) { if (grid.ColumnDefinitions.Count == 0) return 0; for (int i = 1; i < grid.ColumnDefinitions.Count; i++) { if (x < grid.ColumnDefinitions[i].Offset - epsilon) return i - 1; } return grid.ColumnDefinitions.Count - 1; } int GetRowIndex(double y) { if (grid.RowDefinitions.Count == 0) return 0; for (int i = 1; i < grid.RowDefinitions.Count; i++) { if (y < grid.RowDefinitions[i].Offset - epsilon) return i - 1; } return grid.RowDefinitions.Count - 1; } int GetEndColumnIndex(double x) { if (grid.ColumnDefinitions.Count == 0) return 0; for (int i = 1; i < grid.ColumnDefinitions.Count; i++) { if (x <= grid.ColumnDefinitions[i].Offset + epsilon) return i - 1; } return grid.ColumnDefinitions.Count - 1; } int GetEndRowIndex(double y) { if (grid.RowDefinitions.Count == 0) return 0; for (int i = 1; i < grid.RowDefinitions.Count; i++) { if (y <= grid.RowDefinitions[i].Offset + epsilon) return i - 1; } return grid.RowDefinitions.Count - 1; } protected override void AddContainerSnaplines(Rect containerRect, List<SnaplinePlacementBehavior.Snapline> horizontalMap, List<SnaplinePlacementBehavior.Snapline> verticalMap) { var grid = (Grid)ExtendedItem.View; double offset = 0; foreach (RowDefinition r in grid.RowDefinitions) { offset += r.ActualHeight; horizontalMap.Add(new Snapline() { RequireOverlap = false, Offset = offset, Start = offset, End = containerRect.Right }); if (SnaplineMargin > 0) { horizontalMap.Add(new Snapline() { RequireOverlap = false, Offset = offset - SnaplineMargin, Start = offset, End = containerRect.Right }); horizontalMap.Add(new Snapline() { RequireOverlap = false, Offset = offset + SnaplineMargin, Start = offset, End = containerRect.Right }); } } offset = 0; foreach (ColumnDefinition c in grid.ColumnDefinitions) { offset += c.ActualWidth; verticalMap.Add(new Snapline() { RequireOverlap = false, Offset = offset, Start = containerRect.Top, End = containerRect.Bottom }); if (SnaplineMargin > 0) { verticalMap.Add(new Snapline() { RequireOverlap = false, Offset = offset - SnaplineMargin, Start = containerRect.Top, End = containerRect.Bottom }); verticalMap.Add(new Snapline() { RequireOverlap = false, Offset = offset + SnaplineMargin, Start = containerRect.Top, End = containerRect.Bottom }); } } } static void SetColumn(DesignItem item, int column, int columnSpan) { Debug.Assert(item != null && column >= 0 && columnSpan > 0); item.Properties.GetAttachedProperty(Grid.ColumnProperty).SetValue(column); if (columnSpan == 1) { item.Properties.GetAttachedProperty(Grid.ColumnSpanProperty).Reset(); } else { item.Properties.GetAttachedProperty(Grid.ColumnSpanProperty).SetValue(columnSpan); } } static void SetRow(DesignItem item, int row, int rowSpan) { Debug.Assert(item != null && row >= 0 && rowSpan > 0); item.Properties.GetAttachedProperty(Grid.RowProperty).SetValue(row); if (rowSpan == 1) { item.Properties.GetAttachedProperty(Grid.RowSpanProperty).Reset(); } else { item.Properties.GetAttachedProperty(Grid.RowSpanProperty).SetValue(rowSpan); } } static HorizontalAlignment SuggestHorizontalAlignment(Rect itemBounds, Rect availableSpaceRect) { bool isLeft = itemBounds.Left < availableSpaceRect.Left + availableSpaceRect.Width / 4; bool isRight = itemBounds.Right > availableSpaceRect.Right - availableSpaceRect.Width / 4; if (isLeft && isRight) return HorizontalAlignment.Stretch; else if (isRight) return HorizontalAlignment.Right; else return HorizontalAlignment.Left; } static VerticalAlignment SuggestVerticalAlignment(Rect itemBounds, Rect availableSpaceRect) { bool isTop = itemBounds.Top < availableSpaceRect.Top + availableSpaceRect.Height / 4; bool isBottom = itemBounds.Bottom > availableSpaceRect.Bottom - availableSpaceRect.Height / 4; if (isTop && isBottom) return VerticalAlignment.Stretch; else if (isBottom) return VerticalAlignment.Bottom; else return VerticalAlignment.Top; } public override void EnterContainer(PlacementOperation operation) { enteredIntoNewContainer=true; grid.UpdateLayout(); base.EnterContainer(operation); if (operation.Type == PlacementType.PasteItem) { foreach (PlacementInformation info in operation.PlacedItems) { var margin = (Thickness)info.Item.Properties.GetProperty(FrameworkElement.MarginProperty).ValueOnInstance; var horizontalAlignment = (HorizontalAlignment)info.Item.Properties.GetProperty(FrameworkElement.HorizontalAlignmentProperty).ValueOnInstance; var verticalAlignment = (VerticalAlignment)info.Item.Properties.GetProperty(FrameworkElement.VerticalAlignmentProperty).ValueOnInstance; if (horizontalAlignment == HorizontalAlignment.Left) margin.Left += PlacementOperation.PasteOffset; else if (horizontalAlignment == HorizontalAlignment.Right) margin.Right -= PlacementOperation.PasteOffset; if (verticalAlignment == VerticalAlignment.Top) margin.Top += PlacementOperation.PasteOffset; else if (verticalAlignment == VerticalAlignment.Bottom) margin.Bottom -= PlacementOperation.PasteOffset; info.Item.Properties.GetProperty(FrameworkElement.MarginProperty).SetValue(margin); } } } GrayOutDesignerExceptActiveArea grayOut; public override void EndPlacement(PlacementOperation operation) { GrayOutDesignerExceptActiveArea.Stop(ref grayOut); enteredIntoNewContainer=false; base.EndPlacement(operation); } public override void SetPosition(PlacementInformation info) { base.SetPosition(info); int leftColumnIndex = GetColumnIndex(info.Bounds.Left); int rightColumnIndex = GetEndColumnIndex(info.Bounds.Right); if (rightColumnIndex < leftColumnIndex) rightColumnIndex = leftColumnIndex; SetColumn(info.Item, leftColumnIndex, rightColumnIndex - leftColumnIndex + 1); int topRowIndex = GetRowIndex(info.Bounds.Top); int bottomRowIndex = GetEndRowIndex(info.Bounds.Bottom); if (bottomRowIndex < topRowIndex) bottomRowIndex = topRowIndex; SetRow(info.Item, topRowIndex, bottomRowIndex - topRowIndex + 1); Rect availableSpaceRect = new Rect( new Point(GetColumnOffset(leftColumnIndex), GetRowOffset(topRowIndex)), new Point(GetColumnOffset(rightColumnIndex + 1), GetRowOffset(bottomRowIndex + 1)) ); if (info.Item == Services.Selection.PrimarySelection) { // only for primary selection: if (grayOut != null) { grayOut.AnimateActiveAreaRectTo(availableSpaceRect); } else { GrayOutDesignerExceptActiveArea.Start(ref grayOut, this.Services, this.ExtendedItem.View, availableSpaceRect); } } HorizontalAlignment ha = (HorizontalAlignment)info.Item.Properties[FrameworkElement.HorizontalAlignmentProperty].ValueOnInstance; VerticalAlignment va = (VerticalAlignment)info.Item.Properties[FrameworkElement.VerticalAlignmentProperty].ValueOnInstance; if(enteredIntoNewContainer){ ha = SuggestHorizontalAlignment(info.Bounds, availableSpaceRect); va = SuggestVerticalAlignment(info.Bounds, availableSpaceRect); } info.Item.Properties[FrameworkElement.HorizontalAlignmentProperty].SetValue(ha); info.Item.Properties[FrameworkElement.VerticalAlignmentProperty].SetValue(va); Thickness margin = new Thickness(0, 0, 0, 0); if (ha == HorizontalAlignment.Left || ha == HorizontalAlignment.Stretch) margin.Left = info.Bounds.Left - GetColumnOffset(leftColumnIndex); if (va == VerticalAlignment.Top || va == VerticalAlignment.Stretch) margin.Top = info.Bounds.Top - GetRowOffset(topRowIndex); if (ha == HorizontalAlignment.Right || ha == HorizontalAlignment.Stretch) margin.Right = GetColumnOffset(rightColumnIndex + 1) - info.Bounds.Right; if (va == VerticalAlignment.Bottom || va == VerticalAlignment.Stretch) margin.Bottom = GetRowOffset(bottomRowIndex + 1) - info.Bounds.Bottom; info.Item.Properties[FrameworkElement.MarginProperty].SetValue(margin); if (ha == HorizontalAlignment.Stretch) info.Item.Properties[FrameworkElement.WidthProperty].Reset(); //else // info.Item.Properties[FrameworkElement.WidthProperty].SetValue(info.Bounds.Width); if (va == VerticalAlignment.Stretch) info.Item.Properties[FrameworkElement.HeightProperty].Reset(); //else // info.Item.Properties[FrameworkElement.HeightProperty].SetValue(info.Bounds.Height); } public override void LeaveContainer(PlacementOperation operation) { GrayOutDesignerExceptActiveArea.Stop(ref grayOut); base.LeaveContainer(operation); foreach (PlacementInformation info in operation.PlacedItems) { if (info.Item.ComponentType == typeof(ColumnDefinition)) { // TODO: combine the width of the deleted column with the previous column this.ExtendedItem.Properties["ColumnDefinitions"].CollectionElements.Remove(info.Item); } else if (info.Item.ComponentType == typeof(RowDefinition)) { this.ExtendedItem.Properties["RowDefinitions"].CollectionElements.Remove(info.Item); } else { info.Item.Properties.GetAttachedProperty(Grid.RowProperty).Reset(); info.Item.Properties.GetAttachedProperty(Grid.ColumnProperty).Reset(); info.Item.Properties.GetAttachedProperty(Grid.RowSpanProperty).Reset(); info.Item.Properties.GetAttachedProperty(Grid.ColumnSpanProperty).Reset(); HorizontalAlignment ha = (HorizontalAlignment)info.Item.Properties[FrameworkElement.HorizontalAlignmentProperty].ValueOnInstance; VerticalAlignment va = (VerticalAlignment)info.Item.Properties[FrameworkElement.VerticalAlignmentProperty].ValueOnInstance; if (ha == HorizontalAlignment.Stretch) info.Item.Properties[FrameworkElement.WidthProperty].SetValue(info.Bounds.Width); if (va == VerticalAlignment.Stretch) info.Item.Properties[FrameworkElement.HeightProperty].SetValue(info.Bounds.Height); } } } } }
41.444079
177
0.734979
[ "MIT" ]
CudoXY/CMPILER_UI-Designer
WpfDesign.Designer/Project/Extensions/GridPlacementSupport.cs
12,601
C#
using Microsoft.EntityFrameworkCore; namespace ctorx.Core.Data { public class DefaultUnitOfWorkFactory<TDbContext> : IUnitOfWorkFactory<TDbContext> where TDbContext : DbContext { readonly TDbContext DbContext; /// <summary> /// ctor the Mighty /// </summary> public DefaultUnitOfWorkFactory(TDbContext dbContext) { this.DbContext = dbContext; } /// <summary> /// Makes a new unit of work /// </summary> public IUnitOfWork<TDbContext> NewUnitOfWork() { return new UnitOfWork<TDbContext>(this.DbContext); } } }
26.08
115
0.601227
[ "MIT" ]
ctorx/ctorx.Core.Data
src/DefaultUnitOfWorkFactory.cs
654
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using Bing.Admin.Commons.Domain.Models; using Bing.Admin.Commons.Domain.Repositories; using Bing.Admin.Data; using Bing.Admin.Service.Abstractions; namespace Bing.Admin.Service.Implements { /// <summary> /// 测试服务 /// </summary> public class TestService : Bing.Application.Services.AppServiceBase, ITestService { /// <summary> /// 工作单元 /// </summary> protected IAdminUnitOfWork UnitOfWork { get; set; } /// <summary> /// 文件仓储 /// </summary> protected IFileRepository FileRepository { get; set; } /// <summary> /// 初始化一个<see cref="TestService"/>类型的实例 /// </summary> /// <param name="unitOfWork">工作单元</param> /// <param name="fileRepository">文件仓储</param> public TestService(IAdminUnitOfWork unitOfWork, IFileRepository fileRepository) { UnitOfWork = unitOfWork; FileRepository = fileRepository; } /// <summary> /// 批量插入文件 /// </summary> public async Task BatchInsertFileAsync(long qty) { var list = new List<File>(); for (var i = 0; i < qty; i++) { var item = new File { Name = $"批量生成-{DateTime.Now:yyyyMMddHHmmss}-{i}", Size = i * 100, ExtName = ".txt", Address = "Test", Creator = "系统初始化", CreatorId = Guid.Empty, CreationTime = DateTime.Now, }; item.Init(); list.Add(item); } await FileRepository.AddAsync(list); await UnitOfWork.CommitAsync(); } /// <summary> /// 测试参数空异常 /// </summary> public Task TestArgumentNullAsync(List<string> list) { list.ForEach(Console.WriteLine); return Task.CompletedTask; } } }
28.148649
87
0.513682
[ "MIT" ]
bing-framework/Bing.NetCode
modules/admin/src/Bing.Admin.Service/Implements/TestService.cs
2,189
C#
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; namespace Avalonia.Input { /// <summary> /// Defines a keyboard input combination. /// </summary> public sealed class KeyGesture : IEquatable<KeyGesture> { private static readonly Dictionary<string, Key> s_keySynonyms = new Dictionary<string, Key> { { "+", Key.OemPlus }, { "-", Key.OemMinus }, { ".", Key.OemPeriod }, { ",", Key.OemComma } }; [Obsolete("Use constructor taking KeyModifiers")] public KeyGesture(Key key, InputModifiers modifiers) { Key = key; KeyModifiers = (KeyModifiers)(((int)modifiers) & 0xf); } public KeyGesture(Key key, KeyModifiers modifiers = KeyModifiers.None) { Key = key; KeyModifiers = modifiers; } public bool Equals(KeyGesture other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Key == other.Key && KeyModifiers == other.KeyModifiers; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj is KeyGesture && Equals((KeyGesture)obj); } public override int GetHashCode() { unchecked { return ((int)Key * 397) ^ (int)KeyModifiers; } } public static bool operator ==(KeyGesture left, KeyGesture right) { return Equals(left, right); } public static bool operator !=(KeyGesture left, KeyGesture right) { return !Equals(left, right); } public Key Key { get; } [Obsolete("Use KeyModifiers")] public InputModifiers Modifiers => (InputModifiers)KeyModifiers; public KeyModifiers KeyModifiers { get; } public static KeyGesture Parse(string gesture) { // string.Split can't be used here because "Ctrl++" is a perfectly valid key gesture var key = Key.None; var keyModifiers = KeyModifiers.None; var cstart = 0; for (var c = 0; c <= gesture.Length; c++) { var ch = c == gesture.Length ? '\0' : gesture[c]; bool isLast = c == gesture.Length; if (isLast || (ch == '+' && cstart != c)) { var partSpan = gesture.AsSpan(cstart, c - cstart).Trim(); if (isLast) { key = ParseKey(partSpan.ToString()); } else { keyModifiers |= ParseModifier(partSpan); } cstart = c + 1; } } return new KeyGesture(key, keyModifiers); } public override string ToString() { var parts = new List<string>(); foreach (var flag in Enum.GetValues(typeof(KeyModifiers)).Cast<KeyModifiers>()) { if (KeyModifiers.HasFlag(flag) && flag != KeyModifiers.None) { parts.Add(flag.ToString()); } } parts.Add(Key.ToString()); return string.Join(" + ", parts); } public bool Matches(KeyEventArgs keyEvent) => ResolveNumPadOperationKey(keyEvent.Key) == Key && keyEvent.KeyModifiers == KeyModifiers; // TODO: Move that to external key parser private static Key ParseKey(string key) { if (s_keySynonyms.TryGetValue(key.ToLower(), out Key rv)) return rv; return (Key)Enum.Parse(typeof(Key), key, true); } private static KeyModifiers ParseModifier(ReadOnlySpan<char> modifier) { if (modifier.Equals("ctrl".AsSpan(), StringComparison.OrdinalIgnoreCase)) { return KeyModifiers.Control; } if (modifier.Equals("cmd".AsSpan(), StringComparison.OrdinalIgnoreCase)) { return KeyModifiers.Meta; } return (KeyModifiers)Enum.Parse(typeof(KeyModifiers), modifier.ToString(), true); } private Key ResolveNumPadOperationKey(Key key) { switch (key) { case Key.Add: return Key.OemPlus; case Key.Subtract: return Key.OemMinus; case Key.Decimal: return Key.OemPeriod; default: return key; } } } }
29.904762
142
0.515924
[ "MIT" ]
Artentus/Avalonia
src/Avalonia.Input/KeyGesture.cs
5,024
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.SecurityInsights.Outputs { [OutputType] public sealed class TimelineErrorResponseResult { /// <summary> /// the error message /// </summary> public readonly string ErrorMessage; /// <summary> /// the query kind /// </summary> public readonly string Kind; /// <summary> /// the query id /// </summary> public readonly string? QueryId; [OutputConstructor] private TimelineErrorResponseResult( string errorMessage, string kind, string? queryId) { ErrorMessage = errorMessage; Kind = kind; QueryId = queryId; } } }
24.627907
81
0.593012
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/SecurityInsights/Outputs/TimelineErrorResponseResult.cs
1,059
C#
// Automatically generated by xdrgen // DO NOT EDIT or your changes may be overwritten using System; namespace stellar_dotnet_sdk.xdr { // === xdr source ============================================================ // struct StellarValue // { // Hash txSetHash; // transaction set to apply to previous ledger // uint64 closeTime; // network close time // // // upgrades to apply to the previous ledger (usually empty) // // this is a vector of encoded 'LedgerUpgrade' so that nodes can drop // // unknown steps during consensus if needed. // // see notes below on 'LedgerUpgrade' for more detail // // max size is dictated by number of upgrade types (+ room for future) // UpgradeType upgrades<6>; // // // reserved for future use // union switch (int v) // { // case 0: // void; // } // ext; // }; // =========================================================================== public class StellarValue { public StellarValue() { } public Hash TxSetHash { get; set; } public Uint64 CloseTime { get; set; } public UpgradeType[] Upgrades { get; set; } public StellarValueExt Ext { get; set; } public static void Encode(XdrDataOutputStream stream, StellarValue encodedStellarValue) { Hash.Encode(stream, encodedStellarValue.TxSetHash); Uint64.Encode(stream, encodedStellarValue.CloseTime); int upgradessize = encodedStellarValue.Upgrades.Length; stream.WriteInt(upgradessize); for (int i = 0; i < upgradessize; i++) { UpgradeType.Encode(stream, encodedStellarValue.Upgrades[i]); } StellarValueExt.Encode(stream, encodedStellarValue.Ext); } public static StellarValue Decode(XdrDataInputStream stream) { StellarValue decodedStellarValue = new StellarValue(); decodedStellarValue.TxSetHash = Hash.Decode(stream); decodedStellarValue.CloseTime = Uint64.Decode(stream); int upgradessize = stream.ReadInt(); decodedStellarValue.Upgrades = new UpgradeType[upgradessize]; for (int i = 0; i < upgradessize; i++) { decodedStellarValue.Upgrades[i] = UpgradeType.Decode(stream); } decodedStellarValue.Ext = StellarValueExt.Decode(stream); return decodedStellarValue; } public class StellarValueExt { public StellarValueExt() { } public int Discriminant { get; set; } = new int(); public static void Encode(XdrDataOutputStream stream, StellarValueExt encodedStellarValueExt) { stream.WriteInt((int)encodedStellarValueExt.Discriminant); switch (encodedStellarValueExt.Discriminant) { case 0: break; } } public static StellarValueExt Decode(XdrDataInputStream stream) { StellarValueExt decodedStellarValueExt = new StellarValueExt(); int discriminant = stream.ReadInt(); decodedStellarValueExt.Discriminant = discriminant; switch (decodedStellarValueExt.Discriminant) { case 0: break; } return decodedStellarValueExt; } } } }
38
106
0.530612
[ "Apache-2.0" ]
alphapoint/dotnet-stellar-sdk
stellar-dotnet-sdk/xdr/generated/StellarValue.cs
3,724
C#
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; // 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("WoopsaAds")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("WoopsaAds")] [assembly: AssemblyCopyright("Copyright © Microsoft 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // 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")]
43.12963
98
0.704594
[ "MIT" ]
BiancoRoyal/Woopsa
Sources/BeckhoffAds/WoopsaAds/Properties/AssemblyInfo.cs
2,332
C#
//------------------------------------------------------------------------------ // <auto-generated> // 這個程式碼是由範本產生。 // // 對這個檔案進行手動變更可能導致您的應用程式產生未預期的行為。 // 如果重新產生程式碼,將會覆寫對這個檔案的手動變更。 // </auto-generated> //------------------------------------------------------------------------------ namespace _02.EntityFramework.Models { using System; using System.Collections.Generic; public partial class Shipper { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Shipper() { this.Orders = new HashSet<Orders>(); } public int ShipperID { get; set; } public string CompanyName { get; set; } public string Phone { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Orders> Orders { get; set; } } }
32.225806
128
0.54955
[ "MIT" ]
Kodofish-Learning/MVC_Course
MVC_Course/02.EntityFramework/Models/Shipper.cs
1,133
C#
using System; using System.IO; using Common.Extensions; using Common.Logging; using Microsoft.Extensions.Logging; namespace Common { public static class NuGetHelper { private static readonly ILogger Log = LogManager.GetLogger(typeof(NuGetHelper)); public static string GetNugetPackageVersion(string packageName, string nugetRunCommand, bool preRelease) { var shellRunner = new ShellRunner(); ConsoleWriter.WriteProgressWithoutSave("Get package version for " + packageName); shellRunner.Run($"{nugetRunCommand} list {packageName} -NonInteractive" + (preRelease ? " -PreRelease" : "")); foreach (var line in shellRunner.Output.Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries)) { var lineTokens = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (lineTokens.Length == 2 && lineTokens[0].Equals(packageName, StringComparison.InvariantCultureIgnoreCase)) { var msg = $"Got package version: {lineTokens[1]} for {packageName}"; Log.LogInformation(msg); ConsoleWriter.WriteInfo(msg); return lineTokens[1]; } } var message = $"not found package version for package {packageName}. nuget output: " + shellRunner.Output + shellRunner.Errors; Log.LogDebug(message); ConsoleWriter.WriteWarning(message); return null; } public static string GetNugetRunCommand() { var nuGetPath = GetNuGetPath(); if (nuGetPath == null) return null; var nugetCommand = $"\"{nuGetPath}\""; if (Helper.OsIsUnix()) nugetCommand = $"mono {nugetCommand}"; return nugetCommand; } private static string GetNuGetPath() { var nuget = Path.Combine(Helper.GetCementInstallDirectory(), "dotnet", "NuGet.exe"); if (!File.Exists(nuget)) { Log.LogError($"NuGet.exe not found in {nuget}"); return null; } Log.LogDebug($"NuGet.exe found in {nuget}"); return nuget; } } }
38.274194
140
0.562579
[ "MIT" ]
Dimutrulkin/cement
Common/NuGetHelper.cs
2,373
C#
using System; namespace Indice.Hosting { /// <summary> /// Contains metadata about a job to execute. /// </summary> internal class DequeueJobSettings { /// <summary> /// Creates a new instance of <see cref="DequeueJobSettings"/>. /// </summary> /// <param name="jobHandlerType">The CLR type of the job's handler.</param> /// <param name="workItemType">The CLR type of the job's work item.</param> /// <param name="jobName">The name of the job.</param> /// <param name="pollingInterval">The time interval between two attempts to dequeue new items. In milliseconds</param> /// <param name="backoffThreshold">The maximum time interval between two attempts to dequeue new items. In milliseconds</param> /// <param name="cleanUpInterval">Cleanup up the queue every interval secconds</param> /// <param name="cleanUpBatchSize">Cleanup every items.</param> /// <param name="instanceCount">Number of concurrent instances</param> public DequeueJobSettings(Type jobHandlerType, Type workItemType, string jobName, int pollingInterval, int backoffThreshold, int cleanUpInterval, int cleanUpBatchSize, int instanceCount) { JobHandlerType = jobHandlerType; WorkItemType = workItemType; Name = jobName; PollingInterval = pollingInterval; MaxPollingInterval = backoffThreshold; CleanupInterval = cleanUpInterval; CleanupBatchSize = cleanUpBatchSize; InstanceCount = instanceCount; } /// <summary> /// The CLR type of the job's handler. /// </summary> public Type JobHandlerType { get; } /// <summary> /// The CLR type of the job's work item. /// </summary> public Type WorkItemType { get; } /// <summary> /// The name of the job. /// </summary> public string Name { get; set; } /// <summary> /// The time interval between two attempts to dequeue new items. Mesured in millisecconds /// </summary> public int PollingInterval { get; set; } = 300; /// <summary> /// The maximum time interval between two attempts to dequeue new items. Mesured in millisecconds /// </summary> public int MaxPollingInterval { get; set; } = 5000; /// <summary> /// The concurrent instance count. /// </summary> public int InstanceCount { get; set; } = 10; /// <summary> /// Cleanup interval in secconds /// </summary> public int CleanupInterval { get; set; } = 3600; /// <summary> /// Cleanup batch size /// </summary> public int CleanupBatchSize { get; set; } = 100; } }
42.666667
196
0.601207
[ "MIT" ]
ChristosAsvestopoulos/Indice.AspNet
src/Indice.Hosting/Tasks/DequeueJobSettings.cs
2,818
C#
//------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.42000 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ using NMF.Collections.Generic; using NMF.Collections.ObjectModel; using NMF.Expressions; using NMF.Expressions.Linq; using NMF.Models; using NMF.Models.Collections; using NMF.Models.Expressions; using NMF.Models.Meta; using NMF.Models.Repository; using NMF.Serialization; using NMF.Utilities; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Linq; using TTC2017.SmartGrids.CIM.IEC61968.Assets; using TTC2017.SmartGrids.CIM.IEC61968.Common; using TTC2017.SmartGrids.CIM.IEC61968.Work; using TTC2017.SmartGrids.CIM.IEC61970.Core; using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfAssets; using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfCommon; using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfERPSupport; using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfGMLSupport; using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfLocations; using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfOperations; using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfTypeAsset; namespace TTC2017.SmartGrids.CIM.IEC61970.Informative.InfWork { public class ConditionFactorDesignLocationsCollection : ObservableOppositeOrderedSet<IConditionFactor, IDesignLocation> { public ConditionFactorDesignLocationsCollection(IConditionFactor parent) : base(parent) { } private void OnItemDeleted(object sender, System.EventArgs e) { this.Remove(((IDesignLocation)(sender))); } protected override void SetOpposite(IDesignLocation item, IConditionFactor parent) { if ((parent != null)) { item.Deleted += this.OnItemDeleted; item.ConditionFactors.Add(parent); } else { item.Deleted -= this.OnItemDeleted; item.ConditionFactors.Remove(this.Parent); } } } }
33.608108
123
0.670688
[ "MIT" ]
georghinkel/ttc2017smartGrids
generator/Schema/IEC61970/Informative/InfWork/ConditionFactorDesignLocationsCollection.cs
2,489
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Language_Internals { class Program { static void Main() { foreach ( var x in new[] { 2, 3, 5, 7 } ) { new Thread(() => Console.WriteLine(x)).Start(); } Console.Read(); } } }
19.285714
63
0.567901
[ "MIT" ]
MuilaerteJunior/Training
C#/LearningProjects/Language_Internals/foreach.cs
407
C#
namespace GreenDoorProject.Services.Statistics { using GreenDoorProject.Services.Statistics.Models; public interface IStatisticsService { StatisticsServiceModel Total(); } }
20.4
54
0.72549
[ "MIT" ]
ChrisIvanov/ASP.NET-Core-MVC-Green-Door-Project
GreenDoorProject/Services/Statistics/IStatisticsService.cs
206
C#
using Microsoft.ApplicationInsights.DataContracts; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.Extensions.Options; using Microsoft.Net.Http.Headers; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Sockets; using System.Security.Principal; using System.Threading; using System.Threading.Tasks; namespace OAKProxy.Proxy { public class ProxyMiddleware { private readonly IHttpClientFactory _clientFactory; private readonly IClaimsProviderProvider _claimsProviders; public ProxyMiddleware(RequestDelegate next, IHttpClientFactory clientFactory, IClaimsProviderProvider claimsProviders) { _clientFactory = clientFactory; _claimsProviders = claimsProviders; } public async Task Invoke(HttpContext context, IProxyApplicationService applicationService) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var application = applicationService.GetActiveApplication(); var claimsTransforms = _claimsProviders[application.Name]; foreach (var claimsTransform in claimsTransforms) { await claimsTransform.UpdateAsync(context.AuthenticationTicket()); } var client = _clientFactory.CreateClient(application.Name); using (var requestMessage = CreateHttpRequestMessageFromIncomingRequest(context)) { try { using (var responseMessage = await client.SendAsync(requestMessage, context.RequestAborted)) { await CopyProxiedMessageToResponseAsync(context.Response, responseMessage, context.RequestAborted); } } catch (AuthenticatorException e) { context.Response.StatusCode = 403; context.SetErrorDetail(e.Code, e.Message); } catch (HttpRequestException e) { if (e.InnerException is SocketException se && se.SocketErrorCode == SocketError.TimedOut) { context.Response.StatusCode = 504; context.SetErrorDetail(Errors.Code.NoResponse, "The downstream server did not respond."); } else { throw; } } var telemetry = context.Features.Get<RequestTelemetry>(); string authenticatorUser = AuthenticatorHandler.GetAuthenticatorProvidedUser(requestMessage); if (telemetry != null && authenticatorUser != null) { telemetry.Context.User.AccountId = authenticatorUser; } } } private static readonly Uri cookieUri = new Uri("http://localhost/"); private static HttpRequestMessage CreateHttpRequestMessageFromIncomingRequest(HttpContext context) { var request = context.Request; var requestMessage = new HttpRequestMessage(); AuthenticatorHandler.RelateIncomingRequestToMessage(context, requestMessage); var requestMethod = request.Method; if (!HttpMethods.IsGet(requestMethod) && !HttpMethods.IsHead(requestMethod) && !HttpMethods.IsDelete(requestMethod) && !HttpMethods.IsTrace(requestMethod)) { var streamContent = new StreamContent(request.Body); requestMessage.Content = streamContent; } bool needToStripCookie = context.Request.Cookies?.Any(c => c.Key.StartsWith(ProxyAuthComponents.CookiePrefix)) ?? false; foreach (var header in request.Headers) { if (header.Key.Equals(HeaderNames.Host, StringComparison.InvariantCultureIgnoreCase) || header.Key.Equals(HeaderNames.Authorization, StringComparison.InvariantCultureIgnoreCase) || (needToStripCookie && header.Key.Equals(HeaderNames.Cookie, StringComparison.InvariantCultureIgnoreCase)) || header.Key.StartsWith("X-Forwarded-", StringComparison.InvariantCultureIgnoreCase) || header.Key.StartsWith("X-Original-", StringComparison.InvariantCultureIgnoreCase)) continue; if (!requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray()) && requestMessage.Content != null) { requestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray()); } } if (needToStripCookie) { var cookies = CreateCookieHeaderValue(request.Cookies.Where(c => !c.Key.StartsWith(ProxyAuthComponents.CookiePrefix))); if (cookies != null) { requestMessage.Headers.Add(HeaderNames.Cookie, cookies); } } var uri = new Uri(UriHelper.BuildRelative(null, request.Path, request.QueryString), UriKind.Relative); requestMessage.RequestUri = uri; requestMessage.Method = new HttpMethod(request.Method); requestMessage.Headers.TryAddWithoutValidation(ForwardedHeadersDefaults.XForwardedHostHeaderName, context.Request.Host.ToUriComponent()); requestMessage.Headers.TryAddWithoutValidation(ForwardedHeadersDefaults.XForwardedProtoHeaderName, context.Request.Scheme); requestMessage.Headers.TryAddWithoutValidation(ForwardedHeadersDefaults.XForwardedForHeaderName, context.Connection.RemoteIpAddress.ToString()); return requestMessage; } private static string CreateCookieHeaderValue(IEnumerable<KeyValuePair<string,string>> cookies) { var container = new CookieContainer(); foreach (var cookie in cookies) { container.Add(cookieUri, new Cookie(cookie.Key, cookie.Value)); } return container.Count > 0 ? container.GetCookieHeader(cookieUri) : null; } private static async Task CopyProxiedMessageToResponseAsync(HttpResponse response, HttpResponseMessage responseMessage, CancellationToken token) { const int StreamCopyBufferSize = 131072; if (responseMessage == null) { throw new ArgumentNullException(nameof(responseMessage)); } response.StatusCode = (int)responseMessage.StatusCode; foreach (var header in responseMessage.Headers) { response.Headers[header.Key] = header.Value.ToArray(); } foreach (var header in responseMessage.Content.Headers) { response.Headers[header.Key] = header.Value.ToArray(); } // SendAsync removes chunking from the response. This removes the header so it doesn't expect a chunked response. response.Headers.Remove("transfer-encoding"); using (var responseStream = await responseMessage.Content.ReadAsStreamAsync()) { await responseStream.CopyToAsync(response.Body, StreamCopyBufferSize, token); } } } }
43.129944
156
0.623526
[ "MIT" ]
wpbrown/oakproxy
src/OAKProxy/Proxy/ProxyMiddleware.cs
7,636
C#
// <copyright file="UserScenarios.cs" company="Okta, Inc"> // Copyright (c) 2014 - present Okta, Inc. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. // </copyright> using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using FluentAssertions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Polly; using Xunit; namespace Okta.Sdk.IntegrationTests { [Collection(nameof(UserScenarios))] public class UserScenarios { [Fact] public async Task ListUsers() { var client = TestClient.Create(); var guid = Guid.NewGuid(); var profile = new UserProfile { FirstName = "John", LastName = "List-Users", Email = $"john-list-users-dotnet-sdk-{guid}@example.com", Login = $"john-list-users-dotnet-sdk-{guid}@example.com", ["nickName"] = $"johny-list-users-{guid}", }; var createdUser = await client.Users.CreateUserAsync(new CreateUserWithPasswordOptions { Profile = profile, Password = "Abcd1234", }); // this delay and the below retry policy are to handle: // https://developer.okta.com/docs/api/resources/users.html#list-users-with-search // "Queries data from a replicated store, so changes aren’t always immediately available in search results." await Task.Delay(3000); try { async Task UserShouldExist() { var foundUsers = await client.Users .ListUsers(search: $"profile.nickName eq \"{createdUser.Profile.GetProperty<string>("nickName")}\"") .ToArrayAsync(); foundUsers.Length.Should().Be(1); foundUsers.Single().Id.Should().Be(createdUser.Id); } var policy = Polly.Policy .Handle<Exception>() .WaitAndRetryAsync(4, attemptNumber => TimeSpan.FromSeconds(Math.Pow(5, attemptNumber - 1))); await policy.ExecuteAsync(UserShouldExist); } finally { await createdUser.DeactivateAsync(); await createdUser.DeactivateOrDeleteAsync(); } } [Fact] public async Task GetUser() { var client = TestClient.Create(); var guid = Guid.NewGuid(); // Create a user var createdUser = await client.Users.CreateUserAsync(new CreateUserWithPasswordOptions { Profile = new UserProfile { FirstName = "John", LastName = "Get-User", Email = $"john-get-user-dotnet-sdk-{guid}@example.com", Login = $"john-get-user-dotnet-sdk-{guid}@example.com", }, Password = "Abcd1234", Activate = false, }); try { // Retrieve by ID var retrievedById = await client.Users.GetUserAsync(createdUser.Id); retrievedById.Profile.FirstName.Should().Be("John"); retrievedById.Profile.LastName.Should().Be("Get-User"); // Retrieve by login var retrievedByLogin = await client.Users.GetUserAsync(createdUser.Profile.Login); retrievedByLogin.Profile.FirstName.Should().Be("John"); retrievedByLogin.Profile.LastName.Should().Be("Get-User"); } finally { // Remove the user await createdUser.DeactivateAsync(); await createdUser.DeactivateOrDeleteAsync(); } // Getting by ID should result in 404 error await Assert.ThrowsAsync<OktaApiException>( () => client.Users.GetUserAsync(createdUser.Id)); } [Fact] public async Task CreateUserWithPasswordImportInlineHookOptions() { var client = TestClient.Create(); var guid = Guid.NewGuid(); // Create a user var createdUser = await client.Users.CreateUserAsync(new CreateUserWithPasswordImportInlineHookOptions { Profile = new UserProfile { FirstName = "John", LastName = "CreateUserWithPasswordImportInlineHookOptions", Email = $"john-create-user-inline-hooks-pass-dotnet-sdk-{guid}@example.com", Login = $"john-create-user-inline-hooks-pass-dotnet-sdk-{guid}@example.com", }, Activate = false, }); try { // Retrieve by ID var userRetrievedById = await client.Users.GetUserAsync(createdUser.Id); userRetrievedById.Profile.FirstName.Should().Be("John"); userRetrievedById.Profile.LastName.Should().Be("CreateUserWithPasswordImportInlineHookOptions"); userRetrievedById.Credentials.Provider.Type.Should().Be(AuthenticationProviderType.Import); userRetrievedById.Credentials.Provider.Name.Should().Be("IMPORT"); } finally { // Remove the user await createdUser.DeactivateAsync(); await createdUser.DeactivateOrDeleteAsync(); } // Getting by ID should result in 404 error await Assert.ThrowsAsync<OktaApiException>( () => client.Users.GetUserAsync(createdUser.Id)); } [Fact] public async Task CreateUserWithImportedHashedPassword() { var client = TestClient.Create(); var guid = Guid.NewGuid(); var userLastName = nameof(CreateUserWithImportedHashedPassword); var userMail = $"{userLastName.ToLower()}-{guid}@example.com"; // Create a user var createdUser = await client.Users.CreateUserAsync(new CreateUserWithImportedHashedPasswordOptions { Profile = new UserProfile { FirstName = "John", LastName = userLastName, Email = userMail, Login = userMail, }, PasswordCredentialHash = new PasswordCredentialHash { Algorithm = PasswordCredentialHashAlgorithm.Bcrypt, WorkFactor = 10, Salt = "rwh3vH166HCH/NT9XV5FYu", Value = "qaMqvAPULkbiQzkTCWo5XDcvzpk8Tna", }, Activate = true, }); try { // Retrieve by ID var userRetrievedById = await client.Users.GetUserAsync(createdUser.Id); userRetrievedById.Profile.FirstName.Should().Be("John"); userRetrievedById.Profile.LastName.Should().Be(userLastName); userRetrievedById.Credentials.Provider.Type.Should().Be(AuthenticationProviderType.Import); userRetrievedById.Credentials.Provider.Name.Should().Be("IMPORT"); } finally { // Remove the user await createdUser.DeactivateAsync(); await createdUser.DeactivateOrDeleteAsync(); } // Getting by ID should result in 404 error await Assert.ThrowsAsync<OktaApiException>( () => client.Users.GetUserAsync(createdUser.Id)); } [Fact] public async Task ActivateUser() { var client = TestClient.Create(); var guid = Guid.NewGuid(); // Create a user var createdUser = await client.Users.CreateUserAsync(new CreateUserWithPasswordOptions { Profile = new UserProfile { FirstName = "John", LastName = "Activate", Email = $"john-activate-dotnet-sdk-{guid}@example.com", Login = $"john-activate-dotnet-sdk-{guid}@example.com", }, Password = "Abcd1234", Activate = false, }); try { // Activate the user await createdUser.ActivateAsync(sendEmail: false); // Verify user exists in list of active users var activeUsers = await client.Users.ListUsers(filter: "status eq \"ACTIVE\"").ToArrayAsync(); activeUsers.Should().Contain(u => u.Id == createdUser.Id); } finally { // Remove the user await createdUser.DeactivateAsync(); await createdUser.DeactivateOrDeleteAsync(); } } [Theory] [InlineData("Batman")] [InlineData("")] public async Task UpdateUserProfile(string nickName) { var client = TestClient.Create(); var guid = Guid.NewGuid(); // Create a user var createdUser = await client.Users.CreateUserAsync(new CreateUserWithPasswordOptions { Profile = new UserProfile { FirstName = "John", LastName = "Profile-Update", Email = $"john-profile-update-dotnet-sdk-{guid}@example.com", Login = $"john-profile-update-dotnet-sdk-{guid}@example.com", }, Password = "Abcd1234", Activate = false, }); try { // Update profile createdUser.Profile["nickName"] = nickName; var updatedUser = await createdUser.UpdateAsync(); var retrievedUpdatedUser = await client.Users.GetUserAsync(createdUser.Id); updatedUser.Profile.GetProperty<string>("nickName").Should().Be(nickName); retrievedUpdatedUser.Profile.GetProperty<string>("nickName").Should().Be(nickName); } finally { // Deactivate + delete await createdUser.DeactivateAsync(); await createdUser.DeactivateOrDeleteAsync(); } } [Fact] public async Task UpdateUserProfileWithDynamicObject() { var client = TestClient.Create(); var guid = Guid.NewGuid(); // Create a user var createdUser = await client.Users.CreateUserAsync(new CreateUserWithPasswordOptions { Profile = new UserProfile { FirstName = "John", LastName = "Dynamic Profile", Email = $"john-dynamic-profile-dotnet-sdk-{guid}@example.com", Login = $"john-dynamic-profile-dotnet-sdk-{guid}@example.com", }, Password = "Abcd1234", Activate = false, }); try { var titleObject = new { prop1 = "prop1", prop2 = new List<string> { "item1", "item2", "item3" }, prop3 = new { name = "ObjectSample" }, prop4 = 4, }; createdUser.Profile["title"] = JsonConvert.SerializeObject(titleObject); var updatedUser = await createdUser.UpdateAsync(); var retrievedUpdatedUser = await client.Users.GetUserAsync(createdUser.Id); var retrievedTitleStr = retrievedUpdatedUser.Profile.GetProperty<string>("title"); dynamic retrievedTitle = JsonConvert.DeserializeObject(retrievedTitleStr); ((string)retrievedTitle.prop1).Should().Be("prop1"); ((JArray)retrievedTitle.prop2).Should().HaveCount(3); ((string)retrievedTitle.prop3.name).Should().Be("ObjectSample"); ((int)retrievedTitle.prop4).Should().Be(4); } finally { // Deactivate + delete await createdUser.DeactivateAsync(); await createdUser.DeactivateOrDeleteAsync(); } } [Fact] public async Task GetResetPasswordUrl() { var client = TestClient.Create(); var guid = Guid.NewGuid(); var createdUser = await client.Users.CreateUserAsync(new CreateUserWithPasswordOptions { Profile = new UserProfile { FirstName = "John", LastName = "Get-Reset-Password-URL", Email = $"john-get-reset-password-url-dotnet-sdk-{guid}@example.com", Login = $"john-get-reset-password-url-dotnet-sdk-{guid}@example.com", }, Password = "Abcd1234", Activate = true, }); try { var resetPasswordToken = await createdUser.ResetPasswordAsync(sendEmail: false); resetPasswordToken.ResetPasswordUrl.Should().NotBeNullOrEmpty(); } finally { // Deactivate + delete await createdUser.DeactivateAsync(); await createdUser.DeactivateOrDeleteAsync(); } } [Fact] public async Task SuspendUser() { var client = TestClient.Create(); var guid = Guid.NewGuid(); // Create a user var createdUser = await client.Users.CreateUserAsync(new CreateUserWithPasswordOptions { Profile = new UserProfile { FirstName = "John", LastName = "Suspend", Email = $"john-suspend-dotnet-sdk-{guid}@example.com", Login = $"john-suspend-dotnet-sdk-{guid}@example.com", }, Password = "Abcd1234", Activate = true, }); try { await createdUser.SuspendAsync(); var suspendedUsers = await client.Users.ListUsers(filter: "status eq \"SUSPENDED\"").ToArrayAsync(); suspendedUsers.Should().Contain(u => u.Id == createdUser.Id); await createdUser.UnsuspendAsync(); var activeUsers = await client.Users.ListUsers(filter: "status eq \"ACTIVE\"").ToArrayAsync(); activeUsers.Should().Contain(u => u.Id == createdUser.Id); } finally { await createdUser.DeactivateAsync(); await createdUser.DeactivateOrDeleteAsync(); } } [Fact] public async Task ChangeUserPassword() { var client = TestClient.Create(); var guid = Guid.NewGuid(); var createdUser = await client.Users.CreateUserAsync(new CreateUserWithPasswordOptions { Profile = new UserProfile { FirstName = "John", LastName = "Change-User-Password", Email = $"john-change-user-password-dotnet-sdk-{guid}@example.com", Login = $"john-change-user-password-dotnet-sdk-{guid}@example.com", }, Password = "Abcd1234", Activate = true, }); try { await Task.Delay(1000); // just to make sure the date is later await createdUser.ChangePasswordAsync(new ChangePasswordOptions { CurrentPassword = "Abcd1234", NewPassword = "1234Abcd", }); var updatedUser = await client.Users.GetUserAsync(createdUser.Id); updatedUser.PasswordChanged.Value.Should().BeAfter(createdUser.PasswordChanged.Value); } finally { // Deactivate + delete await createdUser.DeactivateAsync(); await createdUser.DeactivateOrDeleteAsync(); } } [Fact] public async Task ExpireUserPassword() { var client = TestClient.Create(); var guid = Guid.NewGuid(); // Create a user var createdUser = await client.Users.CreateUserAsync(new CreateUserWithPasswordOptions { Profile = new UserProfile { FirstName = "John", LastName = "Expire-Password", Email = $"john-expire-password-dotnet-sdk-{guid}@example.com", Login = $"john-expire-password-dotnet-sdk-{guid}@example.com", }, Password = "Abcd1234", Activate = true, }); try { // Expire the user password var user = await createdUser.ExpirePasswordAsync(); user.Id.Should().Be(createdUser.Id); } finally { // Remove the user await createdUser.DeactivateAsync(); await createdUser.DeactivateOrDeleteAsync(); } } [Fact] public async Task ChangeUserRecoveryQuestion() { var client = TestClient.Create(); var guid = Guid.NewGuid(); // Create a user var createdUser = await client.Users.CreateUserAsync(new CreateUserWithPasswordOptions { Profile = new UserProfile { FirstName = "John", LastName = "Change-Recovery-Question", Email = $"john-change-recover-question-dotnet-sdk-{guid}@example.com", Login = $"john-change-recover-question-dotnet-sdk-{guid}@example.com", }, Password = "Abcd1234", Activate = true, }); try { // Update the user's recovery question await createdUser.ChangeRecoveryQuestionAsync(new ChangeRecoveryQuestionOptions { CurrentPassword = "Abcd1234", RecoveryQuestion = "Answer to life, the universe, & everything", RecoveryAnswer = "42 of course", }); } finally { // Remove the user await createdUser.DeactivateAsync(); await createdUser.DeactivateOrDeleteAsync(); } } [Fact] public async Task CreateUserWithProvider() { var client = TestClient.Create(); var guid = Guid.NewGuid(); // Create a user var createdUser = await client.Users.CreateUserAsync(new CreateUserWithProviderOptions { Profile = new UserProfile { FirstName = "Joanna", LastName = "CreatedWithProvider", Email = $"joanna-create-with-provider-dotnet-sdk-{guid}@example.com", Login = $"joanna-create-with-provider-dotnet-sdk-{guid}@example.com", }, ProviderType = AuthenticationProviderType.Federation, ProviderName = "FEDERATION", }); try { // Retrieve by ID var retrievedById = await client.Users.GetUserAsync(createdUser.Id); retrievedById.Profile.LastName.Should().Be("CreatedWithProvider"); retrievedById.Credentials.Provider.Type.Should().Be(AuthenticationProviderType.Federation); retrievedById.Credentials.Provider.Name.Should().Be("FEDERATION"); } finally { // Remove the user await createdUser.DeactivateAsync(); await createdUser.DeactivateOrDeleteAsync(); } // Getting by ID should result in 404 error await Assert.ThrowsAsync<OktaApiException>( () => client.Users.GetUserAsync(createdUser.Id)); } [Fact] public async Task AssignRoleToUser() { var client = TestClient.Create(); var guid = Guid.NewGuid(); var createdUser = await client.Users.CreateUserAsync(new CreateUserWithPasswordOptions { Profile = new UserProfile { FirstName = "John", LastName = $"{nameof(AssignRoleToUser)}", Email = $"john-{nameof(AssignRoleToUser)}-dotnet-sdk-{guid}@example.com", Login = $"john-{nameof(AssignRoleToUser)}-dotnet-sdk-{guid}@example.com", }, Password = "Abcd1234", Activate = true, }); try { await createdUser.AssignRoleAsync( new AssignRoleRequest() { Type = RoleType.SuperAdmin, }); var roles = await createdUser.Roles.ToListAsync(); roles.FirstOrDefault(x => x.Type == RoleType.SuperAdmin).Should().NotBeNull(); } finally { // Remove the user await createdUser.DeactivateAsync(); await createdUser.DeactivateOrDeleteAsync(); } } [Fact] public async Task ListRoles() { var client = TestClient.Create(); var guid = Guid.NewGuid(); var createdUser = await client.Users.CreateUserAsync(new CreateUserWithPasswordOptions { Profile = new UserProfile { FirstName = "John", LastName = $"{nameof(ListRoles)}", Email = $"john-{nameof(ListRoles)}-dotnet-sdk-{guid}@example.com", Login = $"john-{nameof(ListRoles)}-dotnet-sdk-{guid}@example.com", }, Password = "Abcd1234", Activate = true, }); try { await createdUser.AssignRoleAsync( new AssignRoleRequest() { Type = RoleType.SuperAdmin, }); await createdUser.AssignRoleAsync( new AssignRoleRequest() { Type = RoleType.AppAdmin, }); await createdUser.AssignRoleAsync( new AssignRoleRequest() { Type = RoleType.OrgAdmin, }); var roles = await createdUser.Roles.ToListAsync(); roles.Count.Should().Be(3); roles.FirstOrDefault(x => x.Type == RoleType.SuperAdmin).Should().NotBeNull(); roles.FirstOrDefault(x => x.Type == RoleType.AppAdmin).Should().NotBeNull(); roles.FirstOrDefault(x => x.Type == RoleType.OrgAdmin).Should().NotBeNull(); } finally { // Remove the user await createdUser.DeactivateAsync(); await createdUser.DeactivateOrDeleteAsync(); } } [Fact] public async Task RemoveRole() { var client = TestClient.Create(); var guid = Guid.NewGuid(); var createdUser = await client.Users.CreateUserAsync(new CreateUserWithPasswordOptions { Profile = new UserProfile { FirstName = "John", LastName = $"{nameof(RemoveRole)}", Email = $"john-{nameof(RemoveRole)}-dotnet-sdk-{guid}@example.com", Login = $"john-{nameof(RemoveRole)}-dotnet-sdk-{guid}@example.com", }, Password = "Abcd1234", Activate = true, }); try { await createdUser.AssignRoleAsync( new AssignRoleRequest() { Type = RoleType.SuperAdmin, }); await createdUser.AssignRoleAsync( new AssignRoleRequest() { Type = RoleType.OrgAdmin, }); Thread.Sleep(2000); var roles = await createdUser.Roles.ToListAsync(); roles.Count.Should().Be(2); var role1 = roles.FirstOrDefault(x => x.Type == RoleType.SuperAdmin); var role2 = roles.FirstOrDefault(x => x.Type == RoleType.OrgAdmin); await createdUser.RemoveRoleAsync(role1.Id); await createdUser.RemoveRoleAsync(role2.Id); roles = await createdUser.Roles.ToListAsync(); roles.Count.Should().Be(0); } finally { // Remove the user await createdUser.DeactivateAsync(); await createdUser.DeactivateOrDeleteAsync(); } } [Fact] public async Task ListGroupTargetsForRole() { var client = TestClient.Create(); var guid = Guid.NewGuid(); var createdUser = await client.Users.CreateUserAsync(new CreateUserWithPasswordOptions { Profile = new UserProfile { FirstName = "John", LastName = $"{nameof(ListGroupTargetsForRole)}", Email = $"john-{nameof(ListGroupTargetsForRole)}-dotnet-sdk-{guid}@example.com", Login = $"john-{nameof(ListGroupTargetsForRole)}-dotnet-sdk-{guid}@example.com", }, Password = "Abcd1234", Activate = true, }); var createdGroup = await client.Groups.CreateGroupAsync(new CreateGroupOptions { Name = $"dotnet-sdk:{nameof(ListGroupTargetsForRole)}-{guid}", Description = $"dotnet-sdk:{nameof(ListGroupTargetsForRole)}-{guid}", }); try { var role = await createdUser.AssignRoleAsync( new AssignRoleRequest { Type = RoleType.UserAdmin, }); await createdUser.AddGroupTargetAsync(role.Id, createdGroup.Id); var retrievedGroupsForRole = await createdUser.ListGroupTargets(role.Id).ToListAsync(); retrievedGroupsForRole.Should().Contain(x => x.Id == createdGroup.Id); } finally { // Remove the user await createdUser.DeactivateAsync(); await createdUser.DeactivateOrDeleteAsync(); await createdGroup.DeleteAsync(); } } [Fact] public async Task RemoveGroupTargetFromRole() { var client = TestClient.Create(); var guid = Guid.NewGuid(); var createdUser = await client.Users.CreateUserAsync(new CreateUserWithPasswordOptions { Profile = new UserProfile { FirstName = "John", LastName = $"{nameof(RemoveGroupTargetFromRole)}", Email = $"john-{nameof(RemoveGroupTargetFromRole)}-dotnet-sdk-{guid}@example.com", Login = $"john-{nameof(RemoveGroupTargetFromRole)}-dotnet-sdk-{guid}@example.com", }, Password = "Abcd1234", Activate = true, }); var createdGroup1 = await client.Groups.CreateGroupAsync(new CreateGroupOptions { Name = $"dotnet-sdk:{nameof(RemoveGroupTargetFromRole)}1-{guid}", Description = $"dotnet-sdk:{nameof(RemoveGroupTargetFromRole)}1-{guid}", }); var createdGroup2 = await client.Groups.CreateGroupAsync(new CreateGroupOptions { Name = $"dotnet-sdk:{nameof(RemoveGroupTargetFromRole)}2-{guid}", Description = $"dotnet-sdk:{nameof(RemoveGroupTargetFromRole)}2-{guid}", }); try { var role = await createdUser.AssignRoleAsync( new AssignRoleRequest { Type = RoleType.UserAdmin, }); // Need 2 groups, because if you remove the last one it throws an (expected) exception. await createdUser.AddGroupTargetAsync(role.Id, createdGroup1.Id); await createdUser.AddGroupTargetAsync(role.Id, createdGroup2.Id); var retrievedGroupsForRole = await createdUser.ListGroupTargets(role.Id).ToListAsync(); retrievedGroupsForRole.Should().Contain(x => x.Id == createdGroup1.Id); retrievedGroupsForRole.Should().Contain(x => x.Id == createdGroup2.Id); await createdUser.RemoveGroupTargetAsync(role.Id, createdGroup1.Id); retrievedGroupsForRole = await createdUser.ListGroupTargets(role.Id).ToListAsync(); retrievedGroupsForRole.Should().NotContain(x => x.Id == createdGroup1.Id); } finally { // Remove the user await createdUser.DeactivateAsync(); await createdUser.DeactivateOrDeleteAsync(); await createdGroup1.DeleteAsync(); await createdGroup2.DeleteAsync(); } } [Fact] public async Task ForgotPasswordGenerateOneTimeToken() { var client = TestClient.Create(); var guid = Guid.NewGuid(); var createdUser = await client.Users.CreateUserAsync(new CreateUserWithPasswordOptions { Profile = new UserProfile { FirstName = "John", LastName = $"{nameof(ForgotPasswordGenerateOneTimeToken)}", Email = $"{nameof(ForgotPasswordGenerateOneTimeToken)}-dotnet-sdk-{guid}@example.com", Login = $"{nameof(ForgotPasswordGenerateOneTimeToken)}-dotnet-sdk-{guid}@example.com", }, RecoveryQuestion = "Answer to life, the universe, & everything", RecoveryAnswer = "42 of course", Password = "Abcd1234", Activate = true, }); Thread.Sleep(5000); // allow for user replication prior to read attempt try { var policy = Polly.Policy .Handle<Exception>() .WaitAndRetryAsync(4, attemptNumber => TimeSpan.FromSeconds(Math.Pow(5, attemptNumber - 1))) .ExecuteAsync(async () => { var forgotPasswordResponse = await createdUser.ForgotPasswordGenerateOneTimeTokenAsync(false); forgotPasswordResponse.Should().NotBeNull(); forgotPasswordResponse.ResetPasswordUrl.Should().NotBeNullOrEmpty(); }); } finally { await createdUser.DeactivateAsync(); await createdUser.DeactivateOrDeleteAsync(); } } [Fact] public async Task ForgotPasswordSetNewPassword() { var client = TestClient.Create(); var guid = Guid.NewGuid(); var createdUser = await client.Users.CreateUserAsync(new CreateUserWithPasswordOptions { Profile = new UserProfile { FirstName = "John", LastName = $"{nameof(ForgotPasswordSetNewPassword)}", Email = $"{nameof(ForgotPasswordSetNewPassword)}-dotnet-sdk-{guid}@example.com", Login = $"{nameof(ForgotPasswordSetNewPassword)}-dotnet-sdk-{guid}@example.com", }, RecoveryQuestion = "Answer to life, the universe, & everything", RecoveryAnswer = "42 of course", Password = "Abcd1234", Activate = true, }); Thread.Sleep(3000); // allow for user replication prior to read attempt try { var forgotPasswordResponse = await createdUser.ForgotPasswordSetNewPasswordAsync( new UserCredentials { Password = new PasswordCredential { Value = "NewPassword1!", }, RecoveryQuestion = new RecoveryQuestionCredential { Question = "Answer to life, the universe, & everything", Answer = "42 of course", }, }); forgotPasswordResponse.Should().NotBeNull(); } finally { await createdUser.DeactivateAsync(); await createdUser.DeactivateOrDeleteAsync(); } } [Fact] public async Task ExpirePasswordAndGetTemporaryPassword() { var client = TestClient.Create(); var guid = Guid.NewGuid(); var createdUser = await client.Users.CreateUserAsync(new CreateUserWithPasswordOptions { Profile = new UserProfile { FirstName = "John", LastName = $"{nameof(ExpirePasswordAndGetTemporaryPassword)}", Email = $"{nameof(ExpirePasswordAndGetTemporaryPassword)}-dotnet-sdk-{guid}@example.com", Login = $"{nameof(ExpirePasswordAndGetTemporaryPassword)}-dotnet-sdk-{guid}@example.com", }, RecoveryQuestion = "Answer to life, the universe, & everything", RecoveryAnswer = "42 of course", Password = "Abcd1234", Activate = true, }); Thread.Sleep(3000); // allow for user replication prior to read attempt try { var tempPassword = await createdUser.ExpirePasswordAndGetTemporaryPasswordAsync(); tempPassword.Should().NotBeNull(); tempPassword.Password.Should().NotBeNullOrEmpty(); } finally { await createdUser.DeactivateAsync(); await createdUser.DeactivateOrDeleteAsync(); } } [Fact] public async Task GetLinkedObjectForUser() { var client = TestClient.Create(); var randomString = TestClient.RandomString(6); // use of guid results in field values that are too long var primaryRelationshipName = $"dotnet_sdk_{nameof(GetLinkedObjectForUser)}_primary_{randomString}"; var associatedRelationshipName = $"dotnet_sdk_{nameof(GetLinkedObjectForUser)}_associated_{randomString}"; var createdPrimaryUser = await client.Users.CreateUserAsync( new CreateUserWithPasswordOptions { Profile = new UserProfile { FirstName = "John-Primary", LastName = $"{nameof(GetLinkedObjectForUser)}", Email = $"{nameof(GetLinkedObjectForUser)}-primary-dotnet-sdk-{randomString}@example.com", Login = $"{nameof(GetLinkedObjectForUser)}-primary-dotnet-sdk-{randomString}@example.com", }, RecoveryQuestion = "Answer to life, the universe, & everything", RecoveryAnswer = "42 of course", Password = "Abcd1234", Activate = true, }); var createdAssociatedUser = await client.Users.CreateUserAsync( new CreateUserWithPasswordOptions { Profile = new UserProfile { FirstName = "David-Associated", LastName = $"{nameof(GetLinkedObjectForUser)}", Email = $"{nameof(GetLinkedObjectForUser)}-associated-dotnet-sdk-{randomString}@example.com", Login = $"{nameof(GetLinkedObjectForUser)}-associated-dotnet-sdk-{randomString}@example.com", }, RecoveryQuestion = "Answer to life, the universe, & everything", RecoveryAnswer = "42 of course", Password = "Abcd1234", Activate = true, }); var createdLinkedObjectDefinition = await client.LinkedObjects.AddLinkedObjectDefinitionAsync( new LinkedObject { Primary = new LinkedObjectDetails { Name = primaryRelationshipName, Title = "Primary", Description = "Primary link property", Type = "USER", }, Associated = new LinkedObjectDetails { Name = associatedRelationshipName, Title = "Associated", Description = "Associated link property", Type = "USER", }, }); Thread.Sleep(3000); // allow for user replication prior to read attempt try { await createdAssociatedUser.SetLinkedObjectAsync(primaryRelationshipName, createdPrimaryUser.Id); var links = await createdAssociatedUser.GetLinkedObjects(primaryRelationshipName).ToListAsync(); links.Should().NotBeNull(); links.Count.Should().Be(1); } finally { await createdPrimaryUser.DeactivateAsync(); await createdPrimaryUser.DeactivateOrDeleteAsync(); await createdAssociatedUser.DeactivateAsync(); await createdAssociatedUser.DeactivateOrDeleteAsync(); await client.LinkedObjects.DeleteLinkedObjectDefinitionAsync(primaryRelationshipName); } } [Fact] public async Task RemoveLinkedObjectForUser() { var client = TestClient.Create(); var randomString = TestClient.RandomString(6); // use of guid results in field values that are too long var primaryRelationshipName = $"dotnet_sdk_{nameof(RemoveLinkedObjectForUser)}_primary_{randomString}"; var associatedRelationshipName = $"dotnet_sdk_{nameof(RemoveLinkedObjectForUser)}_associated_{randomString}"; var createdPrimaryUser = await client.Users.CreateUserAsync( new CreateUserWithPasswordOptions { Profile = new UserProfile { FirstName = "John-Primary", LastName = $"{nameof(RemoveLinkedObjectForUser)}", Email = $"{nameof(RemoveLinkedObjectForUser)}-primary-dotnet-sdk-{randomString}@example.com", Login = $"{nameof(RemoveLinkedObjectForUser)}-primary-dotnet-sdk-{randomString}@example.com", }, RecoveryQuestion = "Answer to life, the universe, & everything", RecoveryAnswer = "42 of course", Password = "Abcd1234", Activate = true, }); var createdAssociatedUser = await client.Users.CreateUserAsync( new CreateUserWithPasswordOptions { Profile = new UserProfile { FirstName = "David-Associated", LastName = $"{nameof(RemoveLinkedObjectForUser)}", Email = $"{nameof(RemoveLinkedObjectForUser)}-associated-dotnet-sdk-{randomString}@example.com", Login = $"{nameof(RemoveLinkedObjectForUser)}-associated-dotnet-sdk-{randomString}@example.com", }, RecoveryQuestion = "Answer to life, the universe, & everything", RecoveryAnswer = "42 of course", Password = "Abcd1234", Activate = true, }); var createdLinkedObjectDefinition = await client.LinkedObjects.AddLinkedObjectDefinitionAsync( new LinkedObject { Primary = new LinkedObjectDetails { Name = primaryRelationshipName, Title = "Primary", Description = "Primary link property", Type = "USER", }, Associated = new LinkedObjectDetails { Name = associatedRelationshipName, Title = "Associated", Description = "Associated link property", Type = "USER", }, }); Thread.Sleep(3000); // allow for user replication prior to read attempt try { await createdAssociatedUser.SetLinkedObjectAsync(primaryRelationshipName, createdPrimaryUser.Id); var links = await createdAssociatedUser.GetLinkedObjects(primaryRelationshipName).ToListAsync(); links.Should().NotBeNull(); links.Count.Should().Be(1); await createdAssociatedUser.RemoveLinkedObjectAsync(primaryRelationshipName); links = await createdAssociatedUser.GetLinkedObjects(primaryRelationshipName).ToListAsync(); links.Should().NotBeNull(); links.Count.Should().Be(0); } finally { await createdPrimaryUser.DeactivateAsync(); await createdPrimaryUser.DeactivateOrDeleteAsync(); await createdAssociatedUser.DeactivateAsync(); await createdAssociatedUser.DeactivateOrDeleteAsync(); await client.LinkedObjects.DeleteLinkedObjectDefinitionAsync(primaryRelationshipName); } } [Fact] public async Task ListAssignedRolesForUser() { var client = TestClient.Create(); var guid = Guid.NewGuid(); var createdUser = await client.Users.CreateUserAsync( new CreateUserWithPasswordOptions { Profile = new UserProfile { FirstName = "John", LastName = $"{nameof(ListAssignedRolesForUser)}", Email = $"{nameof(ListAssignedRolesForUser)}-dotnet-sdk-{guid}@example.com", Login = $"{nameof(ListAssignedRolesForUser)}-dotnet-sdk-{guid}@example.com", }, RecoveryQuestion = "Answer to life, the universe, & everything", RecoveryAnswer = "42 of course", Password = "Abcd1234", Activate = true, }); Thread.Sleep(3000); // allow for user replication prior to read attempt try { var assignedRoles = await createdUser.ListAssignedRoles().ToListAsync(); assignedRoles.Should().NotBeNull(); assignedRoles.Count.Should().Be(0); await createdUser.AssignRoleAsync( new AssignRoleRequest { Type = RoleType.OrgAdmin, }); assignedRoles = await createdUser.ListAssignedRoles().ToListAsync(); assignedRoles.Should().NotBeNull(); assignedRoles.Count.Should().Be(1); assignedRoles[0].Type.Should().Be(RoleType.OrgAdmin); } finally { await createdUser.DeactivateAsync(); await createdUser.DeactivateOrDeleteAsync(); } } } }
39.652136
124
0.511796
[ "Apache-2.0" ]
Christian-Oleson/okta-sdk-dotnet
src/Okta.Sdk.IntegrationTests/UserScenarios.cs
45,485
C#
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Raven.Client.Documents; using Raven.Client.Documents.Linq; using Raven.Client.Documents.Session; using static Marketplace.Contracts.ClassifiedAds; namespace Marketplace.Modules.ClassifiedAds { public class ClassifiedAdsQueryService { Func<IAsyncDocumentSession> GetSession { get; } public ClassifiedAdsQueryService(Func<IAsyncDocumentSession> getSession) => GetSession = getSession; public async Task<V1.GetAvailableAds.Result> GetAvailableAds( V1.GetAvailableAds query, CancellationToken cancellationToken) { using (var session = GetSession()) { if (query.Page <= 0) query.Page = 1; if (query.PageSize <= 0) query.PageSize = 10; var result = await session.Query<Projections.AvailableClassifiedAdsProjection.AvailableClassifiedAd>() .Where(x => x.PublishedAt != null) .OrderByDescending(x => x.PublishedAt) .Statistics(out var statistics) .Skip((query.Page - 1) * query.PageSize) .Take(query.PageSize) .Select(x => new V1.GetAvailableAds.Result.Item { ClassifiedAdId = x.ClassifiedAdId, Title = x.Title, Text = x.Text, Price = x.Price, Owner = x.Owner, PublishedAt = x.PublishedAt.Value }) .ToListAsync(cancellationToken); return new V1.GetAvailableAds.Result { Page = query.Page, PageSize = query.PageSize, TotalItems = statistics.TotalResults - statistics.SkippedResults, TotalPages = (int) Math.Ceiling((double) statistics.TotalResults / query.PageSize), Items = result.ToArray() }; } } } }
37.928571
118
0.550377
[ "Apache-2.0" ]
UbiquitousAS/WorkshopEventSourcing
src/Marketplace/Modules/ClassifiedAds/ClassifiedAdsQueryService.cs
2,124
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 finspace-data-2020-07-13.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.FinSpaceData.Model { /// <summary> /// Container for the parameters to the ListPermissionGroups operation. /// Lists all available permission groups in FinSpace. /// </summary> public partial class ListPermissionGroupsRequest : AmazonFinSpaceDataRequest { private int? _maxResults; private string _nextToken; /// <summary> /// Gets and sets the property MaxResults. /// <para> /// The maximum number of results per page. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=100)] public int MaxResults { get { return this._maxResults.GetValueOrDefault(); } set { this._maxResults = value; } } // Check to see if MaxResults property is set internal bool IsSetMaxResults() { return this._maxResults.HasValue; } /// <summary> /// Gets and sets the property NextToken. /// <para> /// A token that indicates where a results page should begin. /// </para> /// </summary> public string NextToken { get { return this._nextToken; } set { this._nextToken = value; } } // Check to see if NextToken property is set internal bool IsSetNextToken() { return this._nextToken != null; } } }
29.871795
111
0.629185
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/FinSpaceData/Generated/Model/ListPermissionGroupsRequest.cs
2,330
C#
// SPDX-FileCopyrightText: 2021 TillW <https://www.github.com/x789/> // SPDX-License-Identifier: MIT using System; using System.Linq; using Xunit; namespace ValueArrays.Tests; public sealed class Examples { private record Line(ValueArray<string> points) { } [Fact] public void Usage() { var array = new ValueArray<string>(new[] { "one", "two", "three" }); var copy = new ValueArray<string>(array.ToArray()); var other = new ValueArray<string>(new[] { "two", "one", "three" }); // Equality is determined based on the items... Assert.True(array.Equals(copy)); // ...and the order. Assert.False(array.Equals(other)); // Like equality, the hash-code of a value-array is determined based on its content. Assert.True(array.GetHashCode() == copy.GetHashCode()); Assert.False(array.GetHashCode() == other.GetHashCode()); // The equality-operators are overloaded and work as expected. Assert.True(array == copy); Assert.True(array != other); // Value-arrays are enumerable... foreach (var item in array) Console.WriteLine(item); // prints "one", "two", "three" // ... and therefore support LINQ. Assert.True(array.Where(x => x == "two").Any()); // They have an indexer... Console.WriteLine(array[2]); // prints "three" // ...and a 'Length' property. for (var i = 0; i < array.Length; i++) Console.WriteLine(array[i]); // prints "one", "two", "three" // Value-arrays are immutable. The indexer is read-only... //array[1] = "foo"; // triggers CS0200 "indexer is read only" // ...and changing the original data has no side-effects. var data = new[] { 1, 2, 3 }; var va = new ValueArray<int>(data); data[1] = 4; Assert.True(va[1] == 2); // They can safely be used to model value-objects as records, since they fit into the built-in Equals() and GetHashCode(). var line1 = new Line(array); var line2 = new Line(copy); Assert.True(line1.Equals(line2)); Assert.True(line1 == line2); Assert.True(line1.GetHashCode() == line2.GetHashCode()); } }
35.28125
130
0.593003
[ "MIT" ]
x789/ValueArrays
ValueArrays.Tests/Examples.cs
2,260
C#
using Newtonsoft.Json; namespace Bleatingsheep.Osu.ApiV2 { internal class TokenResponse { [JsonProperty("token_type")] public string TokenType { get; set; } [JsonProperty("expires_in")] public int ExpiresInSeconds { get; set; } [JsonProperty("access_token")] public string AccessToken { get; set; } [JsonProperty("refresh_token")] public string RefreshToken { get; set; } } }
22.85
49
0.623632
[ "Unlicense" ]
bltsheep/Bleatingsheep.Osu.ApiV2
Bleatingsheep.Osu.ApiV2/TokenResponse.cs
459
C#
using System.IO; using System.ComponentModel; using RageAudioTool.IO; namespace RageAudioTool.Rage_Wrappers.DatFile { public class audParameterTransformSound : audSoundBase { public audParameterTransformData[] UnkArrayData { get; set; } public override byte[] Serialize() { var bytes = base.Serialize(); using (MemoryStream stream = new MemoryStream()) { using (IOBinaryWriter writer = new IOBinaryWriter(stream)) { writer.Write(bytes); writer.Write(AudioTracks[0]); writer.Write(UnkArrayData.Length); for (int i = 0; i < UnkArrayData.Length; i++) { writer.Write(UnkArrayData[i].ParameterHash.HashKey); writer.Write(UnkArrayData[i].UnkFloat); writer.Write(UnkArrayData[i].UnkFloat1); if (UnkArrayData[i].NestedData != null) { writer.Write(UnkArrayData[i].NestedData.Length); for (int x = 0; x < UnkArrayData[i].NestedData.Length; x++) { writer.Write(UnkArrayData[i].NestedData[x].UnkFloat); writer.Write(UnkArrayData[i].NestedData[x].UnkInt); writer.Write(UnkArrayData[i].NestedData[x].ParameterHash.HashKey); writer.Write(UnkArrayData[i].NestedData[x].UnkFloat1); writer.Write(UnkArrayData[i].NestedData[x].UnkFloat2); writer.Write(UnkArrayData[i].NestedData[x].NestedItems.Length); for (int y = 0; y < UnkArrayData[i].NestedData[x].NestedItems.Length; y++) { writer.Write(UnkArrayData[i].NestedData[x].NestedItems[y].First); writer.Write(UnkArrayData[i].NestedData[x].NestedItems[y].Second); } } } } } return stream.ToArray(); } } public override int Deserialize(byte[] data) { var bytesRead = base.Deserialize(data); using (BinaryReader reader = new BinaryReader(new MemoryStream(data, bytesRead, data.Length - bytesRead))) { AudioTracks.Add(new audHashString(parent, reader.ReadUInt32()), bytesRead + ((int)reader.BaseStream.Position - 4)); //0x0-0x4 var itemCount = reader.ReadInt32(); //0x4-0x8 UnkArrayData = new audParameterTransformData[itemCount]; for (int i = 0; i < itemCount; i++) { UnkArrayData[i] = new audParameterTransformData { ParameterHash = new audHashString(parent, reader.ReadUInt32()), UnkFloat = reader.ReadSingle(), UnkFloat1 = reader.ReadSingle() }; var nestedItemCount = reader.ReadInt32(); UnkArrayData[i].NestedData = new audParameterTransformDataNested[nestedItemCount]; for (int x = 0; x < nestedItemCount; x++) { UnkArrayData[i].NestedData[x] = new audParameterTransformDataNested { UnkFloat = reader.ReadSingle(), UnkInt = reader.ReadInt32(), ParameterHash = new audHashString(parent, reader.ReadUInt32()), UnkFloat1 = reader.ReadSingle(), UnkFloat2 = reader.ReadSingle() }; var pairItemCount = reader.ReadInt32(); UnkArrayData[i].NestedData[x].NestedItems = new Pair<float, float>[pairItemCount]; for (int y = 0; y < pairItemCount; y++) { UnkArrayData[i].NestedData[x].NestedItems[y] = new Pair<float, float>(reader.ReadSingle(), reader.ReadSingle()); } } } return (int)reader.BaseStream.Position; } } public override string ToString() { return "";//BitConverter.ToString(Data).Replace("-", ""); } public audParameterTransformSound(RageDataFile parent, string str) : base(parent, str) { } public audParameterTransformSound(RageDataFile parent, uint hashName) : base(parent, hashName) { } public audParameterTransformSound() { } } [TypeConverter(typeof(ExpandableObjectConverter))] public class audParameterTransformData { public audHashString ParameterHash { get; set; } //0x0-0x4 public float UnkFloat { get; set; } //0x4-0x8 public float UnkFloat1 { get; set; } //0x8-0xC public audParameterTransformDataNested[] NestedData { get; set; } //0x10.. } public class audParameterTransformDataNested { public float UnkFloat { get; set; } //0x0-0x4 public int UnkInt { get; set; } //0x4 public audHashString ParameterHash { get; set; } //0x8-0xC public float UnkFloat1 { get; set; } //0xC public float UnkFloat2 { get; set; } //0x10-0x14 public Pair<float, float>[] NestedItems { get; set; } //0x18-... } }
36.478261
118
0.493274
[ "MIT" ]
CamxxCore/RageAudioTool
RageAudioTool/Rage Wrappers/DatFile/Types/Metadata/dat54/audParameterTransformSound.cs
5,875
C#
/* * Copyright (c) 2014, Furore (info@furore.com) and contributors * See the file CONTRIBUTORS for details. * * This file is licensed under the BSD 3-Clause license * available at https://raw.githubusercontent.com/ewoutkramer/fhir-net-api/master/LICENSE */ using Hl7.Fhir.Model; using Hl7.Fhir.Rest; using Hl7.Fhir.Serialization; using Hl7.Fhir.Support; using Hl7.Fhir.Utility; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; namespace Hl7.Fhir.Rest { public partial class FhirClient : IFhirClient { private Requester _requester; /// <summary> /// Creates a new client using a default endpoint /// If the endpoint does not end with a slash (/), it will be added. /// </summary> /// <param name="endpoint"> /// The URL of the server to connect to.<br/> /// If the trailing '/' is not present, then it will be appended automatically /// </param> /// <param name="verifyFhirVersion"> /// If parameter is set to true the first time a request is made to the server a /// conformance check will be made to check that the FHIR versions are compatible. /// When they are not compatible, a FhirException will be thrown. /// </param> public FhirClient(Uri endpoint, bool verifyFhirVersion = false) { if (endpoint == null) throw new ArgumentNullException("endpoint"); if (!endpoint.OriginalString.EndsWith("/")) endpoint = new Uri(endpoint.OriginalString + "/"); if (!endpoint.IsAbsoluteUri) throw new ArgumentException("endpoint", "Endpoint must be absolute"); Endpoint = endpoint; _requester = new Requester(Endpoint) { BeforeRequest = this.BeforeRequest, AfterResponse = this.AfterResponse }; VerifyFhirVersion = verifyFhirVersion; } /// <summary> /// Creates a new client using a default endpoint /// If the endpoint does not end with a slash (/), it will be added. /// </summary> /// <param name="endpoint"> /// The URL of the server to connect to.<br/> /// If the trailing '/' is not present, then it will be appended automatically /// </param> /// <param name="verifyFhirVersion"> /// If parameter is set to true the first time a request is made to the server a /// conformance check will be made to check that the FHIR versions are compatible. /// When they are not compatible, a FhirException will be thrown. /// </param> public FhirClient(string endpoint, bool verifyFhirVersion = false) : this(new Uri(endpoint), verifyFhirVersion) { } #region << Client Communication Defaults (PreferredFormat, UseFormatParam, Timeout, ReturnFullResource) >> public bool VerifyFhirVersion { get; set; } /// <summary> /// The preferred format of the content to be used when communicating with the FHIR server (XML or JSON) /// </summary> public ResourceFormat PreferredFormat { get { return _requester.PreferredFormat; } set { _requester.PreferredFormat = value; } } /// <summary> /// When passing the content preference, use the _format parameter instead of the request header /// </summary> public bool UseFormatParam { get { return _requester.UseFormatParameter; } set { _requester.UseFormatParameter = value; } } /// <summary> /// The timeout (in milliseconds) to be used when making calls to the FHIR server /// </summary> public int Timeout { get { return _requester.Timeout; } set { _requester.Timeout = value; } } //private bool _returnFullResource = false; /// <summary> /// Should calls to Create, Update and transaction operations return the whole updated content? /// </summary> /// <remarks>Refer to specification section 2.1.0.5 (Managing Return Content)</remarks> public bool ReturnFullResource { get => _requester.Prefer == Prefer.ReturnRepresentation; set => _requester.Prefer = value ? Prefer.ReturnRepresentation : Prefer.ReturnMinimal; } #if NET_COMPRESSION /// <summary> /// This will do 2 things: /// 1. Add the header Accept-Encoding: gzip, deflate /// 2. decompress any responses that have Content-Encoding: gzip (or deflate) /// </summary> public bool PreferCompressedResponses { get { return _requester.PreferCompressedResponses; } set { _requester.PreferCompressedResponses = value; } } /// <summary> /// Compress any Request bodies /// (warning, if a server does not handle compressed requests you will get a 415 response) /// </summary> public bool CompressRequestBody { get { return _requester.CompressRequestBody; } set { _requester.CompressRequestBody = value; } } #endif /// <summary> /// The last transaction result that was executed on this connection to the FHIR server /// </summary> public Bundle.ResponseComponent LastResult => _requester.LastResult?.Response; public ParserSettings ParserSettings { get { return _requester.ParserSettings; } set { _requester.ParserSettings = value; } } public byte[] LastBody => LastResult?.GetBody(); public string LastBodyAsText => LastResult?.GetBodyAsText(); public Resource LastBodyAsResource => _requester.LastResult?.Resource; /// <summary> /// Returns the HttpWebRequest as it was last constructed to execute a call on the FhirClient /// </summary> public HttpWebRequest LastRequest { get { return _requester.LastRequest; } } /// <summary> /// Returns the HttpWebResponse as it was last received during a call on the FhirClient /// </summary> /// <remarks>Note that the FhirClient will have read the body data from the HttpWebResponse, so this is /// no longer available. Use LastBody, LastBodyAsText and LastBodyAsResource to get access to the received body (if any)</remarks> public HttpWebResponse LastResponse { get { return _requester.LastResponse; } } /// <summary> /// The default endpoint for use with operations that use discrete id/version parameters /// instead of explicit uri endpoints. This will always have a trailing "/" /// </summary> public Uri Endpoint { get; private set; } #endregion #region Read /// <summary> /// Fetches a typed resource from a FHIR resource endpoint. /// </summary> /// <param name="location">The url of the Resource to fetch. This can be a Resource id url or a version-specific /// Resource url.</param> /// <param name="ifNoneMatch">The (weak) ETag to use in a conditional read. Optional.</param> /// <param name="ifModifiedSince">Last modified since date in a conditional read. Optional. (refer to spec 2.1.0.5) If this is used, the client will throw an exception you need</param> /// <typeparam name="TResource">The type of resource to read. Resource or DomainResource is allowed if exact type is unknown</typeparam> /// <returns> /// The requested resource. This operation will throw an exception /// if the resource has been deleted or does not exist. /// The specified may be relative or absolute, if it is an absolute /// url, it must reference an address within the endpoint. /// </returns> /// <remarks>Since ResourceLocation is a subclass of Uri, you may pass in ResourceLocations too.</remarks> /// <exception cref="FhirOperationException">This will occur if conditional request returns a status 304 and optionally an OperationOutcome</exception> public Task<TResource> ReadAsync<TResource>(Uri location, string ifNoneMatch=null, DateTimeOffset? ifModifiedSince=null) where TResource : Resource { if (location == null) throw Error.ArgumentNull(nameof(location)); var id = verifyResourceIdentity(location, needId: true, needVid: false); Bundle tx; if (!id.HasVersion) { var ri = new TransactionBuilder(Endpoint).Read(id.ResourceType, id.Id, ifNoneMatch, ifModifiedSince); tx = ri.ToBundle(); } else { tx = new TransactionBuilder(Endpoint).VRead(id.ResourceType, id.Id, id.VersionId).ToBundle(); } return executeAsync<TResource>(tx, HttpStatusCode.OK); } /// <summary> /// Fetches a typed resource from a FHIR resource endpoint. /// </summary> /// <param name="location">The url of the Resource to fetch. This can be a Resource id url or a version-specific /// Resource url.</param> /// <param name="ifNoneMatch">The (weak) ETag to use in a conditional read. Optional.</param> /// <param name="ifModifiedSince">Last modified since date in a conditional read. Optional. (refer to spec 2.1.0.5) If this is used, the client will throw an exception you need</param> /// <typeparam name="TResource">The type of resource to read. Resource or DomainResource is allowed if exact type is unknown</typeparam> /// <returns> /// The requested resource. This operation will throw an exception /// if the resource has been deleted or does not exist. /// The specified may be relative or absolute, if it is an absolute /// url, it must reference an address within the endpoint. /// </returns> /// <remarks>Since ResourceLocation is a subclass of Uri, you may pass in ResourceLocations too.</remarks> /// <exception cref="FhirOperationException">This will occur if conditional request returns a status 304 and optionally an OperationOutcome</exception> public TResource Read<TResource>(Uri location, string ifNoneMatch = null, DateTimeOffset? ifModifiedSince = null) where TResource : Resource { return ReadAsync<TResource>(location, ifNoneMatch, ifModifiedSince).WaitResult(); } /// <summary> /// Fetches a typed resource from a FHIR resource endpoint. /// </summary> /// <param name="location">The url of the Resource to fetch as a string. This can be a Resource id url or a version-specific /// Resource url.</param> /// <param name="ifNoneMatch">The (weak) ETag to use in a conditional read. Optional.</param> /// <param name="ifModifiedSince">Last modified since date in a conditional read. Optional.</param> /// <typeparam name="TResource">The type of resource to read. Resource or DomainResource is allowed if exact type is unknown</typeparam> /// <returns>The requested resource</returns> /// <remarks>This operation will throw an exception /// if the resource has been deleted or does not exist. The specified may be relative or absolute, if it is an absolute /// url, it must reference an address within the endpoint.</remarks> public Task<TResource> ReadAsync<TResource>(string location, string ifNoneMatch = null, DateTimeOffset? ifModifiedSince = null) where TResource : Resource { return ReadAsync<TResource>(new Uri(location, UriKind.RelativeOrAbsolute), ifNoneMatch, ifModifiedSince); } /// <summary> /// Fetches a typed resource from a FHIR resource endpoint. /// </summary> /// <param name="location">The url of the Resource to fetch as a string. This can be a Resource id url or a version-specific /// Resource url.</param> /// <param name="ifNoneMatch">The (weak) ETag to use in a conditional read. Optional.</param> /// <param name="ifModifiedSince">Last modified since date in a conditional read. Optional.</param> /// <typeparam name="TResource">The type of resource to read. Resource or DomainResource is allowed if exact type is unknown</typeparam> /// <returns>The requested resource</returns> /// <remarks>This operation will throw an exception /// if the resource has been deleted or does not exist. The specified may be relative or absolute, if it is an absolute /// url, it must reference an address within the endpoint.</remarks> public TResource Read<TResource>(string location, string ifNoneMatch = null, DateTimeOffset? ifModifiedSince = null) where TResource : Resource { return ReadAsync<TResource>(location, ifNoneMatch, ifModifiedSince).WaitResult(); } #endregion #region Refresh /// <summary> /// Refreshes the data in the resource passed as an argument by re-reading it from the server /// </summary> /// <typeparam name="TResource"></typeparam> /// <param name="current">The resource for which you want to get the most recent version.</param> /// <returns>A new instance of the resource, containing the most up-to-date data</returns> /// <remarks>This function will not overwrite the argument with new data, rather it will return a new instance /// which will have the newest data, leaving the argument intact.</remarks> public Task<TResource> RefreshAsync<TResource>(TResource current) where TResource : Resource { if (current == null) throw Error.ArgumentNull(nameof(current)); return ReadAsync<TResource>(ResourceIdentity.Build(current.TypeName, current.Id)); } /// <summary> /// Refreshes the data in the resource passed as an argument by re-reading it from the server /// </summary> /// <typeparam name="TResource"></typeparam> /// <param name="current">The resource for which you want to get the most recent version.</param> /// <returns>A new instance of the resource, containing the most up-to-date data</returns> /// <remarks>This function will not overwrite the argument with new data, rather it will return a new instance /// which will have the newest data, leaving the argument intact.</remarks> public TResource Refresh<TResource>(TResource current) where TResource : Resource { return RefreshAsync<TResource>(current).WaitResult(); } #endregion #region Update /// <summary> /// Update (or create) a resource /// </summary> /// <param name="resource">The resource to update</param> /// <param name="versionAware">If true, asks the server to verify we are updating the latest version</param> /// <typeparam name="TResource">The type of resource that is being updated</typeparam> /// <returns>The body of the updated resource, unless ReturnFullResource is set to "false"</returns> /// <remarks>Throws an exception when the update failed, in particular when an update conflict is detected and the server returns a HTTP 409. /// If the resource does not yet exist - and the server allows client-assigned id's - a new resource with the given id will be /// created.</remarks> public Task<TResource> UpdateAsync<TResource>(TResource resource, bool versionAware=false) where TResource : Resource { if (resource == null) throw Error.ArgumentNull(nameof(resource)); if (resource.Id == null) throw Error.Argument(nameof(resource), "Resource needs a non-null Id to send the update to"); var upd = new TransactionBuilder(Endpoint); if (versionAware && resource.HasVersionId) upd.Update(resource.Id, resource, versionId: resource.VersionId); else upd.Update(resource.Id, resource); return internalUpdateAsync<TResource>(resource, upd.ToBundle()); } /// <summary> /// Update (or create) a resource /// </summary> /// <param name="resource">The resource to update</param> /// <param name="versionAware">If true, asks the server to verify we are updating the latest version</param> /// <typeparam name="TResource">The type of resource that is being updated</typeparam> /// <returns>The body of the updated resource, unless ReturnFullResource is set to "false"</returns> /// <remarks>Throws an exception when the update failed, in particular when an update conflict is detected and the server returns a HTTP 409. /// If the resource does not yet exist - and the server allows client-assigned id's - a new resource with the given id will be /// created.</remarks> public TResource Update<TResource>(TResource resource, bool versionAware = false) where TResource : Resource { return UpdateAsync<TResource>(resource, versionAware).WaitResult(); } /// <summary> /// Conditionally update (or create) a resource /// </summary> /// <param name="resource">The resource to update</param> /// <param name="condition">Criteria used to locate the resource to update</param> /// <param name="versionAware">If true, asks the server to verify we are updating the latest version</param> /// <typeparam name="TResource">The type of resource that is being updated</typeparam> /// <returns>The body of the updated resource, unless ReturnFullResource is set to "false"</returns> /// <remarks>Throws an exception when the update failed, in particular when an update conflict is detected and the server returns a HTTP 409. /// If the criteria passed in condition do not match a resource a new resource with a server assigned id will be created.</remarks> public Task<TResource> UpdateAsync<TResource>(TResource resource, SearchParams condition, bool versionAware = false) where TResource : Resource { if (resource == null) throw Error.ArgumentNull(nameof(resource)); if (condition == null) throw Error.ArgumentNull(nameof(condition)); var upd = new TransactionBuilder(Endpoint); if (versionAware && resource.HasVersionId) upd.Update(condition, resource, versionId: resource.VersionId); else upd.Update(condition, resource); return internalUpdateAsync(resource, upd.ToBundle()); } /// <summary> /// Conditionally update (or create) a resource /// </summary> /// <param name="resource">The resource to update</param> /// <param name="condition">Criteria used to locate the resource to update</param> /// <param name="versionAware">If true, asks the server to verify we are updating the latest version</param> /// <typeparam name="TResource">The type of resource that is being updated</typeparam> /// <returns>The body of the updated resource, unless ReturnFullResource is set to "false"</returns> /// <remarks>Throws an exception when the update failed, in particular when an update conflict is detected and the server returns a HTTP 409. /// If the criteria passed in condition do not match a resource a new resource with a server assigned id will be created.</remarks> public TResource Update<TResource>(TResource resource, SearchParams condition, bool versionAware = false) where TResource : Resource { return UpdateAsync(resource, condition, versionAware).WaitResult(); } private Task<TResource> internalUpdateAsync<TResource>(TResource resource, Bundle tx) where TResource : Resource { resource.ResourceBase = Endpoint; // This might be an update of a resource that doesn't yet exist, so accept a status Created too return executeAsync<TResource>(tx, new[] { HttpStatusCode.Created, HttpStatusCode.OK }); } private TResource internalUpdate<TResource>(TResource resource, Bundle tx) where TResource : Resource { return internalUpdateAsync(resource, tx).WaitResult(); } #endregion #region Delete /// <summary> /// Delete a resource at the given endpoint. /// </summary> /// <param name="location">endpoint of the resource to delete</param> /// <returns>Throws an exception when the delete failed, though this might /// just mean the server returned 404 (the resource didn't exist before) or 410 (the resource was /// already deleted).</returns> public async Task DeleteAsync(Uri location) { if (location == null) throw Error.ArgumentNull(nameof(location)); var id = verifyResourceIdentity(location, needId: true, needVid: false); var tx = new TransactionBuilder(Endpoint).Delete(id.ResourceType, id.Id).ToBundle(); await executeAsync<Resource>(tx, new[] { HttpStatusCode.OK, HttpStatusCode.NoContent }).ConfigureAwait(false); } /// <summary> /// Delete a resource at the given endpoint. /// </summary> /// <param name="location">endpoint of the resource to delete</param> /// <returns>Throws an exception when the delete failed, though this might /// just mean the server returned 404 (the resource didn't exist before) or 410 (the resource was /// already deleted).</returns> public void Delete(Uri location) { DeleteAsync(location).WaitNoResult(); } /// <summary> /// Delete a resource at the given endpoint. /// </summary> /// <param name="location">endpoint of the resource to delete</param> /// <returns>Throws an exception when the delete failed, though this might /// just mean the server returned 404 (the resource didn't exist before) or 410 (the resource was /// already deleted).</returns> public Task DeleteAsync(string location) { return DeleteAsync(new Uri(location, UriKind.Relative)); } /// <summary> /// Delete a resource at the given endpoint. /// </summary> /// <param name="location">endpoint of the resource to delete</param> /// <returns>Throws an exception when the delete failed, though this might /// just mean the server returned 404 (the resource didn't exist before) or 410 (the resource was /// already deleted).</returns> public void Delete(string location) { DeleteAsync(location).WaitNoResult(); } /// <summary> /// Delete a resource /// </summary> /// <param name="resource">The resource to delete</param> public async Task DeleteAsync(Resource resource) { if (resource == null) throw Error.ArgumentNull(nameof(resource)); if (resource.Id == null) throw Error.Argument(nameof(resource), "Entry must have an id"); await DeleteAsync(resource.ResourceIdentity(Endpoint).WithoutVersion()).ConfigureAwait(false); } /// <summary> /// Delete a resource /// </summary> /// <param name="resource">The resource to delete</param> public void Delete(Resource resource) { DeleteAsync(resource).WaitNoResult(); } /// <summary> /// Conditionally delete a resource /// </summary> /// <param name="resourceType">The type of resource to delete</param> /// <param name="condition">Criteria to use to match the resource to delete.</param> public async Task DeleteAsync(string resourceType, SearchParams condition) { if (resourceType == null) throw Error.ArgumentNull(nameof(resourceType)); if (condition == null) throw Error.ArgumentNull(nameof(condition)); var tx = new TransactionBuilder(Endpoint).Delete(resourceType, condition).ToBundle(); await executeAsync<Resource>(tx,new[]{ HttpStatusCode.OK, HttpStatusCode.NoContent}).ConfigureAwait(false); } /// <summary> /// Conditionally delete a resource /// </summary> /// <param name="resourceType">The type of resource to delete</param> /// <param name="condition">Criteria to use to match the resource to delete.</param> public void Delete(string resourceType, SearchParams condition) { DeleteAsync(resourceType, condition).WaitNoResult(); } #endregion #region Create /// <summary> /// Create a resource on a FHIR endpoint /// </summary> /// <param name="resource">The resource instance to create</param> /// <returns>The resource as created on the server, or an exception if the create failed.</returns> /// <typeparam name="TResource">The type of resource to create</typeparam> public Task<TResource> CreateAsync<TResource>(TResource resource) where TResource : Resource { if (resource == null) throw Error.ArgumentNull(nameof(resource)); var tx = new TransactionBuilder(Endpoint).Create(resource).ToBundle(); return executeAsync<TResource>(tx,new[] { HttpStatusCode.Created, HttpStatusCode.OK }); } /// <summary> /// Create a resource on a FHIR endpoint /// </summary> /// <param name="resource">The resource instance to create</param> /// <returns>The resource as created on the server, or an exception if the create failed.</returns> /// <typeparam name="TResource">The type of resource to create</typeparam> public TResource Create<TResource>(TResource resource) where TResource : Resource { return CreateAsync(resource).WaitResult(); } /// <summary> /// Conditionally Create a resource on a FHIR endpoint /// </summary> /// <param name="resource">The resource instance to create</param> /// <param name="condition">The criteria</param> /// <returns>The resource as created on the server, or an exception if the create failed.</returns> /// <typeparam name="TResource">The type of resource to create</typeparam> public Task<TResource> CreateAsync<TResource>(TResource resource, SearchParams condition) where TResource : Resource { if (resource == null) throw Error.ArgumentNull(nameof(resource)); if (condition == null) throw Error.ArgumentNull(nameof(condition)); var tx = new TransactionBuilder(Endpoint).Create(resource,condition).ToBundle(); return executeAsync<TResource>(tx, new[] { HttpStatusCode.Created, HttpStatusCode.OK }); } public TResource Create<TResource>(TResource resource, SearchParams condition) where TResource : Resource { return CreateAsync(resource, condition).WaitResult(); } #endregion #region Conformance /// <summary> /// Get a conformance statement for the system /// </summary> /// <returns>A Conformance resource. Throws an exception if the operation failed.</returns> public Task<Conformance> ConformanceAsync(SummaryType? summary = null) { var tx = new TransactionBuilder(Endpoint).Conformance(summary).ToBundle(); return executeAsync<Conformance>(tx, HttpStatusCode.OK); } public Conformance Conformance(SummaryType? summary = null) { return ConformanceAsync(summary).WaitResult(); } #endregion #region History /// <summary> /// Retrieve the version history for a specific resource type /// </summary> /// <param name="resourceType">The type of Resource to get the history for</param> /// <param name="since">Optional. Returns only changes after the given date</param> /// <param name="pageSize">Optional. Asks server to limit the number of entries per page returned</param> /// <param name="summary">Optional. Asks the server to only provide the fields defined for the summary</param> /// <returns>A bundle with the history for the indicated instance, may contain both /// ResourceEntries and DeletedEntries.</returns> public Task<Bundle> TypeHistoryAsync(string resourceType, DateTimeOffset? since = null, int? pageSize = null, SummaryType summary = SummaryType.False) { return internalHistoryAsync(resourceType, null, since, pageSize, summary); } /// <summary> /// Retrieve the version history for a specific resource type /// </summary> /// <param name="resourceType">The type of Resource to get the history for</param> /// <param name="since">Optional. Returns only changes after the given date</param> /// <param name="pageSize">Optional. Asks server to limit the number of entries per page returned</param> /// <param name="summary">Optional. Asks the server to only provide the fields defined for the summary</param> /// <returns>A bundle with the history for the indicated instance, may contain both /// ResourceEntries and DeletedEntries.</returns> public Bundle TypeHistory(string resourceType, DateTimeOffset? since = null, int? pageSize = null, SummaryType summary = SummaryType.False) { return TypeHistoryAsync(resourceType, since, pageSize, summary).WaitResult(); } /// <summary> /// Retrieve the version history for a specific resource type /// </summary> /// <param name="since">Optional. Returns only changes after the given date</param> /// <param name="pageSize">Optional. Asks server to limit the number of entries per page returned</param> /// <param name="summary">Optional. Asks the server to only provide the fields defined for the summary</param> /// <typeparam name="TResource">The type of Resource to get the history for</typeparam> /// <returns>A bundle with the history for the indicated instance, may contain both /// ResourceEntries and DeletedEntries.</returns> public Task<Bundle> TypeHistoryAsync<TResource>(DateTimeOffset? since = null, int? pageSize = null, SummaryType summary = SummaryType.False) where TResource : Resource, new() { string collection = typeof(TResource).GetCollectionName(); return internalHistoryAsync(collection, null, since, pageSize, summary); } /// <summary> /// Retrieve the version history for a specific resource type /// </summary> /// <param name="since">Optional. Returns only changes after the given date</param> /// <param name="pageSize">Optional. Asks server to limit the number of entries per page returned</param> /// <param name="summary">Optional. Asks the server to only provide the fields defined for the summary</param> /// <typeparam name="TResource">The type of Resource to get the history for</typeparam> /// <returns>A bundle with the history for the indicated instance, may contain both /// ResourceEntries and DeletedEntries.</returns> public Bundle TypeHistory<TResource>(DateTimeOffset? since = null, int? pageSize = null, SummaryType summary = SummaryType.False) where TResource : Resource, new() { return TypeHistoryAsync<TResource>(since, pageSize, summary).WaitResult(); } /// <summary> /// Retrieve the version history for a resource at a given location /// </summary> /// <param name="location">The address of the resource to get the history for</param> /// <param name="since">Optional. Returns only changes after the given date</param> /// <param name="pageSize">Optional. Asks server to limit the number of entries per page returned</param> /// <param name="summary">Optional. Asks the server to only provide the fields defined for the summary</param> /// <returns>A bundle with the history for the indicated instance, may contain both /// ResourceEntries and DeletedEntries.</returns> public Task<Bundle> HistoryAsync(Uri location, DateTimeOffset? since = null, int? pageSize = null, SummaryType summary = SummaryType.False) { if (location == null) throw Error.ArgumentNull(nameof(location)); var id = verifyResourceIdentity(location, needId: true, needVid: false); return internalHistoryAsync(id.ResourceType, id.Id, since, pageSize, summary); } /// <summary> /// Retrieve the version history for a resource at a given location /// </summary> /// <param name="location">The address of the resource to get the history for</param> /// <param name="since">Optional. Returns only changes after the given date</param> /// <param name="pageSize">Optional. Asks server to limit the number of entries per page returned</param> /// <param name="summary">Optional. Asks the server to only provide the fields defined for the summary</param> /// <returns>A bundle with the history for the indicated instance, may contain both /// ResourceEntries and DeletedEntries.</returns> public Bundle History(Uri location, DateTimeOffset? since = null, int? pageSize = null, SummaryType summary = SummaryType.False) { return HistoryAsync(location, since, pageSize, summary).WaitResult(); } /// <summary> /// Retrieve the version history for a resource at a given location /// </summary> /// <param name="location">The address of the resource to get the history for</param> /// <param name="since">Optional. Returns only changes after the given date</param> /// <param name="pageSize">Optional. Asks server to limit the number of entries per page returned</param> /// <param name="summary">Optional. Asks the server to only provide the fields defined for the summary</param> /// <returns>A bundle with the history for the indicated instance, may contain both /// ResourceEntries and DeletedEntries.</returns> public Task<Bundle> HistoryAsync(string location, DateTimeOffset? since = null, int? pageSize = null, SummaryType summary = SummaryType.False) { return HistoryAsync(new Uri(location, UriKind.Relative), since, pageSize, summary); } /// <summary> /// Retrieve the version history for a resource at a given location /// </summary> /// <param name="location">The address of the resource to get the history for</param> /// <param name="since">Optional. Returns only changes after the given date</param> /// <param name="pageSize">Optional. Asks server to limit the number of entries per page returned</param> /// <param name="summary">Optional. Asks the server to only provide the fields defined for the summary</param> /// <returns>A bundle with the history for the indicated instance, may contain both /// ResourceEntries and DeletedEntries.</returns> public Bundle History(string location, DateTimeOffset? since = null, int? pageSize = null, SummaryType summary = SummaryType.False) { return HistoryAsync(location, since, pageSize, summary).WaitResult(); } /// <summary> /// Retrieve the full version history of the server /// </summary> /// <param name="since">Optional. Returns only changes after the given date</param> /// <param name="pageSize">Optional. Asks server to limit the number of entries per page returned</param> /// <param name="summary">Indicates whether the returned resources should just contain the minimal set of elements</param> /// <returns>A bundle with the history for the indicated instance, may contain both /// ResourceEntries and DeletedEntries.</returns> public Task<Bundle> WholeSystemHistoryAsync(DateTimeOffset? since = null, int? pageSize = null, SummaryType summary = SummaryType.False) { return internalHistoryAsync(null, null, since, pageSize, summary); } /// <summary> /// Retrieve the full version history of the server /// </summary> /// <param name="since">Optional. Returns only changes after the given date</param> /// <param name="pageSize">Optional. Asks server to limit the number of entries per page returned</param> /// <param name="summary">Indicates whether the returned resources should just contain the minimal set of elements</param> /// <returns>A bundle with the history for the indicated instance, may contain both /// ResourceEntries and DeletedEntries.</returns> public Bundle WholeSystemHistory(DateTimeOffset? since = null, int? pageSize = null, SummaryType summary = SummaryType.False) { return WholeSystemHistoryAsync(since, pageSize, summary).WaitResult(); } private Task<Bundle> internalHistoryAsync(string resourceType = null, string id = null, DateTimeOffset? since = null, int? pageSize = null, SummaryType summary = SummaryType.False) { TransactionBuilder history; if(resourceType == null) history = new TransactionBuilder(Endpoint).ServerHistory(summary,pageSize,since); else if(id == null) history = new TransactionBuilder(Endpoint).CollectionHistory(resourceType, summary,pageSize,since); else history = new TransactionBuilder(Endpoint).ResourceHistory(resourceType,id, summary,pageSize,since); return executeAsync<Bundle>(history.ToBundle(), HttpStatusCode.OK); } private Bundle internalHistory(string resourceType = null, string id = null, DateTimeOffset? since = null, int? pageSize = null, SummaryType summary = SummaryType.False) { return internalHistoryAsync(resourceType, id, since, pageSize, summary).WaitResult(); } #endregion #region Transaction /// <summary> /// Send a set of creates, updates and deletes to the server to be processed in one transaction /// </summary> /// <param name="bundle">The bundled creates, updates and deleted</param> /// <returns>A bundle as returned by the server after it has processed the transaction, or null /// if an error occurred.</returns> public Task<Bundle> TransactionAsync(Bundle bundle) { if (bundle == null) throw new ArgumentNullException(nameof(bundle)); var tx = new TransactionBuilder(Endpoint).Transaction(bundle).ToBundle(); return executeAsync<Bundle>(tx, HttpStatusCode.OK); } /// <summary> /// Send a set of creates, updates and deletes to the server to be processed in one transaction /// </summary> /// <param name="bundle">The bundled creates, updates and deleted</param> /// <returns>A bundle as returned by the server after it has processed the transaction, or null /// if an error occurred.</returns> public Bundle Transaction(Bundle bundle) { return TransactionAsync(bundle).WaitResult(); } #endregion #region Operation public Task<Resource> WholeSystemOperationAsync(string operationName, Parameters parameters = null, bool useGet = false) { if (operationName == null) throw Error.ArgumentNull(nameof(operationName)); return internalOperationAsync(operationName, parameters: parameters, useGet: useGet); } public Resource WholeSystemOperation(string operationName, Parameters parameters = null, bool useGet = false) { return WholeSystemOperationAsync(operationName, parameters, useGet).WaitResult(); } public Task<Resource> TypeOperationAsync<TResource>(string operationName, Parameters parameters = null, bool useGet = false) where TResource : Resource { if (operationName == null) throw Error.ArgumentNull(nameof(operationName)); // [WMR 20160421] GetResourceNameForType is obsolete // var typeName = ModelInfo.GetResourceNameForType(typeof(TResource)); var typeName = ModelInfo.GetFhirTypeNameForType(typeof(TResource)); return TypeOperationAsync(operationName, typeName, parameters, useGet: useGet); } public Resource TypeOperation<TResource>(string operationName, Parameters parameters = null, bool useGet = false) where TResource : Resource { return TypeOperationAsync<TResource>(operationName, parameters, useGet).WaitResult(); } public Task<Resource> TypeOperationAsync(string operationName, string typeName, Parameters parameters = null, bool useGet = false) { if (operationName == null) throw Error.ArgumentNull(nameof(operationName)); if (typeName == null) throw Error.ArgumentNull(nameof(typeName)); return internalOperationAsync(operationName, typeName, parameters: parameters, useGet: useGet); } public Resource TypeOperation(string operationName, string typeName, Parameters parameters = null, bool useGet = false) { return TypeOperationAsync(operationName, typeName, parameters, useGet).WaitResult(); } public Task<Resource> InstanceOperationAsync(Uri location, string operationName, Parameters parameters = null, bool useGet = false) { if (location == null) throw Error.ArgumentNull(nameof(location)); if (operationName == null) throw Error.ArgumentNull(nameof(operationName)); var id = verifyResourceIdentity(location, needId: true, needVid: false); return internalOperationAsync(operationName, id.ResourceType, id.Id, id.VersionId, parameters, useGet); } public Resource InstanceOperation(Uri location, string operationName, Parameters parameters = null, bool useGet = false) { return InstanceOperationAsync(location, operationName, parameters, useGet).WaitResult(); } public Task<Resource> OperationAsync(Uri location, string operationName, Parameters parameters = null, bool useGet = false) { if (location == null) throw Error.ArgumentNull(nameof(location)); if (operationName == null) throw Error.ArgumentNull(nameof(operationName)); var tx = new TransactionBuilder(Endpoint).EndpointOperation(new RestUrl(location), operationName, parameters, useGet).ToBundle(); return executeAsync<Resource>(tx, HttpStatusCode.OK); } public Resource Operation(Uri location, string operationName, Parameters parameters = null, bool useGet = false) { return OperationAsync(location, operationName, parameters, useGet).WaitResult(); } public Task<Resource> OperationAsync(Uri operation, Parameters parameters = null, bool useGet = false) { if (operation == null) throw Error.ArgumentNull(nameof(operation)); var tx = new TransactionBuilder(Endpoint).EndpointOperation(new RestUrl(operation), parameters, useGet).ToBundle(); return executeAsync<Resource>(tx, HttpStatusCode.OK); } public Resource Operation(Uri operation, Parameters parameters = null, bool useGet = false) { return OperationAsync(operation, parameters, useGet).WaitResult(); } private Task<Resource> internalOperationAsync(string operationName, string type = null, string id = null, string vid = null, Parameters parameters = null, bool useGet = false) { // Brian: Not sure why we would create this parameters object as empty. // I would imagine that a null parameters object is different to an empty one? // EK: What else could we do? POST an empty body? We cannot use GET unless the caller indicates this is an // idempotent call.... // MV: (related to issue #419): we only provide an empty parameter when we are not performing a GET operation. In r4 it will be allowed // to provide an empty body in POST operations. In that case the line of code can be deleted. if (parameters == null && !useGet) parameters = new Parameters(); Bundle tx; if (type == null) tx = new TransactionBuilder(Endpoint).ServerOperation(operationName, parameters, useGet).ToBundle(); else if (id == null) tx = new TransactionBuilder(Endpoint).TypeOperation(type, operationName, parameters, useGet).ToBundle(); else tx = new TransactionBuilder(Endpoint).ResourceOperation(type, id, vid, operationName, parameters, useGet).ToBundle(); return executeAsync<Resource>(tx, HttpStatusCode.OK); } private Resource internalOperation(string operationName, string type = null, string id = null, string vid = null, Parameters parameters = null, bool useGet = false) { return internalOperationAsync(operationName, type, id, vid, parameters, useGet).WaitResult(); } #endregion #region Get /// <summary> /// Invoke a general GET on the server. If the operation fails, then this method will throw an exception /// </summary> /// <param name="url">A relative or absolute url. If the url is absolute, it has to be located within the endpoint of the client.</param> /// <returns>A resource that is the outcome of the operation. The type depends on the definition of the operation at the given url</returns> /// <remarks>parameters to the method are simple, and are in the URL, and this is a GET operation</remarks> public Resource Get(Uri url) { return GetAsync(url).WaitResult(); } /// <summary> /// Invoke a general GET on the server. If the operation fails, then this method will throw an exception /// </summary> /// <param name="url">A relative or absolute url. If the url is absolute, it has to be located within the endpoint of the client.</param> /// <returns>A resource that is the outcome of the operation. The type depends on the definition of the operation at the given url</returns> /// <remarks>parameters to the method are simple, and are in the URL, and this is a GET operation</remarks> public async Task<Resource> GetAsync(Uri url) { if (url == null) throw Error.ArgumentNull(nameof(url)); var tx = new TransactionBuilder(Endpoint).Get(url).ToBundle(); return await executeAsync<Resource>(tx, HttpStatusCode.OK).ConfigureAwait(false); } /// <summary> /// Invoke a general GET on the server. If the operation fails, then this method will throw an exception /// </summary> /// <param name="url">A relative or absolute url. If the url is absolute, it has to be located within the endpoint of the client.</param> /// <returns>A resource that is the outcome of the operation. The type depends on the definition of the operation at the given url</returns> /// <remarks>parameters to the method are simple, and are in the URL, and this is a GET operation</remarks> public Resource Get(string url) { return GetAsync(url).WaitResult(); } /// <summary> /// Invoke a general GET on the server. If the operation fails, then this method will throw an exception /// </summary> /// <param name="url">A relative or absolute url. If the url is absolute, it has to be located within the endpoint of the client.</param> /// <returns>A resource that is the outcome of the operation. The type depends on the definition of the operation at the given url</returns> /// <remarks>parameters to the method are simple, and are in the URL, and this is a GET operation</remarks> public Task<Resource> GetAsync(string url) { if (url == null) throw Error.ArgumentNull(nameof(url)); return GetAsync(new Uri(url, UriKind.RelativeOrAbsolute)); } #endregion private ResourceIdentity verifyResourceIdentity(Uri location, bool needId, bool needVid) { var result = new ResourceIdentity(location); if (result.ResourceType == null) throw Error.Argument(nameof(location), "Must be a FHIR REST url containing the resource type in its path"); if (needId && result.Id == null) throw Error.Argument(nameof(location), "Must be a FHIR REST url containing the logical id in its path"); if (needVid && !result.HasVersion) throw Error.Argument(nameof(location), "Must be a FHIR REST url containing the version id in its path"); return result; } // TODO: Depending on type of response, update identity & always update lastupdated? private void updateIdentity(Resource resource, ResourceIdentity identity) { if (resource.Meta == null) resource.Meta = new Meta(); if (resource.Id == null) { resource.Id = identity.Id; resource.VersionId = identity.VersionId; } } private void setResourceBase(Resource resource, string baseUri) { resource.ResourceBase = new Uri(baseUri); if (resource is Bundle) { var bundle = resource as Bundle; foreach (var entry in bundle.Entry.Where(e => e.Resource != null)) entry.Resource.ResourceBase = new Uri(baseUri, UriKind.RelativeOrAbsolute); } } /// <summary> /// Called just before the Http call is done /// </summary> public event EventHandler<BeforeRequestEventArgs> OnBeforeRequest; /// <summary> /// Called just after the response was received /// </summary> public event EventHandler<AfterResponseEventArgs> OnAfterResponse; /// <summary> /// Inspect or modify the HttpWebRequest just before the FhirClient issues a call to the server /// </summary> /// <param name="rawRequest">The request as it is about to be sent to the server</param> /// <param name="body">The data in the body of the request as it is about to be sent to the server</param> protected virtual void BeforeRequest(HttpWebRequest rawRequest, byte[] body) { // Default implementation: call event OnBeforeRequest?.Invoke(this, new BeforeRequestEventArgs(rawRequest, body)); } /// <summary> /// Inspect the HttpWebResponse as it came back from the server /// </summary> /// <remarks>You cannot read the body from the HttpWebResponse, since it has /// already been read by the framework. Use the body parameter instead.</remarks> protected virtual void AfterResponse(HttpWebResponse webResponse, byte[] body) { // Default implementation: call event OnAfterResponse?.Invoke(this, new AfterResponseEventArgs(webResponse, body)); } // Original private TResource execute<TResource>(Bundle tx, HttpStatusCode expect) where TResource : Resource { return executeAsync<TResource>(tx, new[] { expect }).WaitResult(); } public Task<TResource> executeAsync<TResource>(Bundle tx, HttpStatusCode expect) where TResource : Resource { return executeAsync<TResource>(tx, new[] { expect }); } // Original private TResource execute<TResource>(Bundle tx, IEnumerable<HttpStatusCode> expect) where TResource : Resource { return executeAsync<TResource>(tx, expect).WaitResult(); } private async Task<TResource> executeAsync<TResource>(Bundle tx, IEnumerable<HttpStatusCode> expect) where TResource : Resource { verifyServerVersion(); var request = tx.Entry[0]; var response = await _requester.ExecuteAsync(request).ConfigureAwait(false); if (!expect.Select(sc => ((int)sc).ToString()).Contains(response.Response.Status)) { Enum.TryParse<HttpStatusCode>(response.Response.Status, out HttpStatusCode code); throw new FhirOperationException("Operation concluded successfully, but the return status {0} was unexpected".FormatWith(response.Response.Status), code); } Resource result; // Special feature: if ReturnFullResource was requested (using the Prefer header), but the server did not return the resource // (or it returned an OperationOutcome) - explicitly go out to the server to get the resource and return it. // This behavior is only valid for PUT and POST requests, where the server may device whether or not to return the full body of the alterend resource. var noRealBody = response.Resource == null || (response.Resource is OperationOutcome && string.IsNullOrEmpty(response.Resource.Id)); if (noRealBody && isPostOrPut(request) && ReturnFullResource && response.Response.Location != null && new ResourceIdentity(response.Response.Location).IsRestResourceIdentity()) // Check that it isn't an operation too { result = await GetAsync(response.Response.Location).ConfigureAwait(false); } else result = response.Resource; if (result == null) return null; // We have a success code (2xx), we have a body, but the body may not be of the type we expect. if (!(result is TResource)) { // If this is an operationoutcome, that may still be allright. Keep the OperationOutcome in // the LastResult, and return null as the result. Otherwise, throw. if (result is OperationOutcome) return null; var message = String.Format("Operation {0} on {1} expected a body of type {2} but a {3} was returned", response.Request.Method, response.Request.Url, typeof(TResource).Name, result.GetType().Name); throw new FhirOperationException(message, _requester.LastResponse.StatusCode); } else return result as TResource; } private bool isPostOrPut(Bundle.EntryComponent interaction) { var method = interaction.Request.Method; return method == Bundle.HTTPVerb.POST || method == Bundle.HTTPVerb.PUT; } private bool versionChecked = false; private void verifyServerVersion() { if (!VerifyFhirVersion) return; if (versionChecked) return; versionChecked = true; // So we can now start calling Conformance() without getting into a loop Conformance conf = null; try { conf = Conformance(); } catch (FormatException) { // Mmmm...cannot even read the body. Probably not so good. throw Error.NotSupported("Cannot read the conformance statement of the server to verify FHIR version compatibility"); } if (!conf.FhirVersion.StartsWith(ModelInfo.Version)) { throw Error.NotSupported("This client support FHIR version {0}, but the server uses version {1}".FormatWith(ModelInfo.Version, conf.FhirVersion)); } } } public class BeforeRequestEventArgs : EventArgs { public BeforeRequestEventArgs(HttpWebRequest rawRequest, byte[] body) { this.RawRequest = rawRequest; this.Body = body; } public HttpWebRequest RawRequest { get; internal set; } public byte[] Body { get; internal set; } } public class AfterResponseEventArgs : EventArgs { public AfterResponseEventArgs(HttpWebResponse webResponse, byte[] body) { this.RawResponse = webResponse; this.Body = body; } public HttpWebResponse RawResponse { get; internal set; } public byte[] Body { get; internal set; } } }
51.098404
192
0.641632
[ "BSD-3-Clause" ]
Kno2/fhir-net-api
src/Hl7.Fhir.Core/Rest/FhirClient.cs
57,641
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.IO; using Microsoft.Extensions.CommandLineUtils; namespace Microsoft.AspNetCore.Blazor.Build.Cli.Commands { internal class BuildIndexHtmlCommand { public static void Command(CommandLineApplication command) { var clientPage = command.Option("--html-page", "Path to the HTML Page containing the Blazor bootstrap script tag.", CommandOptionType.SingleValue); var referencesFile = command.Option("--references", "The path to a file that lists the paths to given referenced dll files", CommandOptionType.SingleValue); var embeddedResourcesFile = command.Option("--embedded-resources", "The path to a file that lists the paths of .NET assemblies that may contain embedded resources (typically, referenced assemblies in their pre-linked states)", CommandOptionType.SingleValue); var outputPath = command.Option("--output", "Path to the output file", CommandOptionType.SingleValue); var mainAssemblyPath = command.Argument("assembly", "Path to the assembly containing the entry point of the application."); var linkerEnabledFlag = command.Option("--linker-enabled", "If set, specifies that the application is being built with linking enabled.", CommandOptionType.NoValue); command.OnExecute(() => { if (string.IsNullOrEmpty(mainAssemblyPath.Value) || !clientPage.HasValue() || !outputPath.HasValue()) { command.ShowHelp(command.Name); return 1; } try { var referencesSources = referencesFile.HasValue() ? File.ReadAllLines(referencesFile.Value()) : Array.Empty<string>(); var embeddedResourcesSources = embeddedResourcesFile.HasValue() ? File.ReadAllLines(embeddedResourcesFile.Value()) : Array.Empty<string>(); IndexHtmlWriter.UpdateIndex( clientPage.Value(), mainAssemblyPath.Value, referencesSources, embeddedResourcesSources, linkerEnabledFlag.HasValue(), outputPath.Value()); return 0; } catch (Exception ex) { Console.WriteLine($"ERROR: {ex.Message}"); Console.WriteLine(ex.StackTrace); return 1; } }); } } }
40.226667
175
0.548558
[ "Apache-2.0" ]
RemiBou/Blazor
src/Microsoft.AspNetCore.Blazor.Build/Cli/Commands/BuildIndexHtmlCommand.cs
3,019
C#
using Cake.Core; using Cake.Frosting; using Dalion.WebAppTemplate.Build.Configuration; namespace Dalion.WebAppTemplate.Build { public class Context : FrostingContext { public Context(ICakeContext context) : base(context) { App = new AppProperties(context); } public AppProperties App { get; } } }
26.307692
62
0.684211
[ "MIT" ]
DavidLievrouw/DalionWebAppTemplate
src/Build/Context.cs
342
C#
using Android.App; using Android.Content; using Android.Content.PM; using Android.OS; namespace VerifyTaxiApp.Droid { [Activity(Label = "@string/app_name", Theme = "@style/MyTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { protected override async void OnCreate(Bundle bundle) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(bundle); // Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity = this; // await CrossMedia.Current.Initialize(); global::Xamarin.Forms.Forms.Init(this, bundle); LoadApplication(new App()); } //public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults) //{ // PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults); //} } }
34.787879
166
0.690767
[ "MIT" ]
ignatandrei/IsThisTaxiLegal
applications/VerifyTaxiApp/VerifyTaxiApp/VerifyTaxiApp.Android/MainActivity.cs
1,150
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.Contracts; namespace System.Globalization { //////////////////////////////////////////////////////////////////////////// // // Notes about JapaneseLunisolarCalendar // //////////////////////////////////////////////////////////////////////////// /* ** Calendar support range: ** Calendar Minimum Maximum ** ========== ========== ========== ** Gregorian 1960/01/28 2050/01/22 ** JapaneseLunisolar 1960/01/01 2049/12/29 */ public class JapaneseLunisolarCalendar : EastAsianLunisolarCalendar { // // The era value for the current era. // public const int JapaneseEra = 1; internal GregorianCalendarHelper helper; internal const int MIN_LUNISOLAR_YEAR = 1960; internal const int MAX_LUNISOLAR_YEAR = 2049; internal const int MIN_GREGORIAN_YEAR = 1960; internal const int MIN_GREGORIAN_MONTH = 1; internal const int MIN_GREGORIAN_DAY = 28; internal const int MAX_GREGORIAN_YEAR = 2050; internal const int MAX_GREGORIAN_MONTH = 1; internal const int MAX_GREGORIAN_DAY = 22; internal static DateTime minDate = new DateTime(MIN_GREGORIAN_YEAR, MIN_GREGORIAN_MONTH, MIN_GREGORIAN_DAY); internal static DateTime maxDate = new DateTime((new DateTime(MAX_GREGORIAN_YEAR, MAX_GREGORIAN_MONTH, MAX_GREGORIAN_DAY, 23, 59, 59, 999)).Ticks + 9999); public override DateTime MinSupportedDateTime { get { return (minDate); } } public override DateTime MaxSupportedDateTime { get { return (maxDate); } } protected override int DaysInYearBeforeMinSupportedYear { get { // 1959 from ChineseLunisolarCalendar return 354; } } static readonly int[,] yinfo = { /*Y LM Lmon Lday DaysPerMonth D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 #Days 1960 */ { 6 , 1 , 28 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 29 384 1961 */{ 0 , 2 , 15 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355 1962 */{ 0 , 2 , 5 , 19808 },/* 29 30 29 29 30 30 29 30 29 30 30 29 0 354 1963 */{ 4 , 1 , 25 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384 1964 */{ 0 , 2 , 13 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355 1965 */{ 0 , 2 , 2 , 21104 },/* 29 30 29 30 29 29 30 29 29 30 30 30 0 354 1966 */{ 3 , 1 , 22 , 26928 },/* 29 30 30 29 30 29 29 30 29 29 30 30 29 383 1967 */{ 0 , 2 , 9 , 55632 },/* 30 30 29 30 30 29 29 30 29 30 29 30 0 355 1968 */{ 7 , 1 , 30 , 27304 },/* 29 30 30 29 30 29 30 29 30 29 30 29 30 384 1969 */{ 0 , 2 , 17 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354 1970 */{ 0 , 2 , 6 , 39632 },/* 30 29 29 30 30 29 30 29 30 30 29 30 0 355 1971 */{ 5 , 1 , 27 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 1972 */{ 0 , 2 , 15 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354 1973 */{ 0 , 2 , 3 , 42208 },/* 30 29 30 29 29 30 29 29 30 30 30 29 0 354 1974 */{ 4 , 1 , 23 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384 1975 */{ 0 , 2 , 11 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 1976 */{ 8 , 1 , 31 , 54600 },/* 30 30 29 30 29 30 29 30 29 30 29 29 30 384 1977 */{ 0 , 2 , 18 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354 1978 */{ 0 , 2 , 7 , 54944 },/* 30 30 29 30 29 30 30 29 30 29 30 29 0 355 1979 */{ 6 , 1 , 28 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384 1980 */{ 0 , 2 , 16 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355 1981 */{ 0 , 2 , 5 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354 1982 */{ 4 , 1 , 25 , 42200 },/* 30 29 30 29 29 30 29 29 30 30 29 30 30 384 1983 */{ 0 , 2 , 13 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 1984 */{ 10 , 2 , 2 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384 1985 */{ 0 , 2 , 20 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354 1986 */{ 0 , 2 , 9 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354 1987 */{ 6 , 1 , 29 , 46504 },/* 30 29 30 30 29 30 29 30 30 29 30 29 30 385 1988 */{ 0 , 2 , 18 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354 1989 */{ 0 , 2 , 6 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355 1990 */{ 5 , 1 , 27 , 18872 },/* 29 30 29 29 30 29 29 30 30 29 30 30 30 384 1991 */{ 0 , 2 , 15 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354 1992 */{ 0 , 2 , 4 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354 1993 */{ 3 , 1 , 23 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 29 383 1994 */{ 0 , 2 , 10 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355 1995 */{ 8 , 1 , 31 , 27976 },/* 29 30 30 29 30 30 29 30 29 30 29 29 30 384 1996 */{ 0 , 2 , 19 , 23248 },/* 29 30 29 30 30 29 30 29 30 30 29 30 0 355 1997 */{ 0 , 2 , 8 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354 1998 */{ 5 , 1 , 28 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 29 384 1999 */{ 0 , 2 , 16 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354 2000 */{ 0 , 2 , 5 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354 2001 */{ 4 , 1 , 24 , 58536 },/* 30 30 30 29 29 30 29 29 30 29 30 29 30 384 2002 */{ 0 , 2 , 12 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354 2003 */{ 0 , 2 , 1 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 0 355 2004 */{ 2 , 1 , 22 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384 2005 */{ 0 , 2 , 9 , 22208 },/* 29 30 29 30 29 30 30 29 30 30 29 29 0 354 2006 */{ 7 , 1 , 29 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385 2007 */{ 0 , 2 , 18 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354 2008 */{ 0 , 2 , 7 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354 2009 */{ 5 , 1 , 26 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384 2010 */{ 0 , 2 , 14 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354 2011 */{ 0 , 2 , 3 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354 2012 */{ 3 , 1 , 23 , 47696 },/* 30 29 30 30 30 29 30 29 29 30 29 30 29 384 2013 */{ 0 , 2 , 10 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355 2014 */{ 9 , 1 , 31 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384 2015 */{ 0 , 2 , 19 , 19360 },/* 29 30 29 29 30 29 30 30 30 29 30 29 0 354 2016 */{ 0 , 2 , 8 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355 2017 */{ 5 , 1 , 28 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384 2018 */{ 0 , 2 , 16 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354 2019 */{ 0 , 2 , 5 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354 2020 */{ 4 , 1 , 25 , 46248 },/* 30 29 30 30 29 30 29 29 30 29 30 29 30 384 2021 */{ 0 , 2 , 12 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354 2022 */{ 0 , 2 , 1 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355 2023 */{ 2 , 1 , 22 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384 2024 */{ 0 , 2 , 10 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354 2025 */{ 6 , 1 , 29 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384 2026 */{ 0 , 2 , 17 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355 2027 */{ 0 , 2 , 7 , 21104 },/* 29 30 29 30 29 29 30 29 29 30 30 30 0 354 2028 */{ 5 , 1 , 27 , 26928 },/* 29 30 30 29 30 29 29 30 29 29 30 30 29 383 2029 */{ 0 , 2 , 13 , 55600 },/* 30 30 29 30 30 29 29 30 29 29 30 30 0 355 2030 */{ 0 , 2 , 3 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354 2031 */{ 3 , 1 , 23 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 29 384 2032 */{ 0 , 2 , 11 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355 2033 */{ 11 , 1 , 31 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 2034 */{ 0 , 2 , 19 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354 2035 */{ 0 , 2 , 8 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354 2036 */{ 6 , 1 , 28 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384 2037 */{ 0 , 2 , 15 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 2038 */{ 0 , 2 , 4 , 54560 },/* 30 30 29 30 29 30 29 30 29 29 30 29 0 354 2039 */{ 5 , 1 , 24 , 55968 },/* 30 30 29 30 30 29 30 29 30 29 30 29 29 384 2040 */{ 0 , 2 , 12 , 46752 },/* 30 29 30 30 29 30 30 29 30 29 30 29 0 355 2041 */{ 0 , 2 , 1 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355 2042 */{ 2 , 1 , 22 , 19160 },/* 29 30 29 29 30 29 30 29 30 30 29 30 30 384 2043 */{ 0 , 2 , 10 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354 2044 */{ 7 , 1 , 30 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384 2045 */{ 0 , 2 , 17 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 2046 */{ 0 , 2 , 6 , 45648 },/* 30 29 30 30 29 29 30 29 29 30 29 30 0 354 2047 */{ 5 , 1 , 26 , 46376 },/* 30 29 30 30 29 30 29 30 29 29 30 29 30 384 2048 */{ 0 , 2 , 14 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354 2049 */{ 0 , 2 , 2 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 0 355 */ }; internal override int MinCalendarYear { get { return (MIN_LUNISOLAR_YEAR); } } internal override int MaxCalendarYear { get { return (MAX_LUNISOLAR_YEAR); } } internal override DateTime MinDate { get { return (minDate); } } internal override DateTime MaxDate { get { return (maxDate); } } internal override EraInfo[] CalEraInfo { get { return (JapaneseCalendar.GetEraInfo()); } } internal override int GetYearInfo(int LunarYear, int Index) { if ((LunarYear < MIN_LUNISOLAR_YEAR) || (LunarYear > MAX_LUNISOLAR_YEAR)) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, MIN_LUNISOLAR_YEAR, MAX_LUNISOLAR_YEAR)); } Contract.EndContractBlock(); return yinfo[LunarYear - MIN_LUNISOLAR_YEAR, Index]; } internal override int GetYear(int year, DateTime time) { return helper.GetYear(year, time); } internal override int GetGregorianYear(int year, int era) { return helper.GetGregorianYear(year, era); } // Trim off the eras that are before our date range private static EraInfo[] TrimEras(EraInfo[] baseEras) { EraInfo[] newEras = new EraInfo[baseEras.Length]; int newIndex = 0; // Eras have most recent first, so start with that for (int i = 0; i < baseEras.Length; i++) { // If this one's minimum year is bigger than our maximum year // then we can't use it. if (baseEras[i].yearOffset + baseEras[i].minEraYear >= MAX_LUNISOLAR_YEAR) { // skip this one. continue; } // If this one's maximum era is less than our minimum era // then we've gotten too low in the era #s, so we're done if (baseEras[i].yearOffset + baseEras[i].maxEraYear < MIN_LUNISOLAR_YEAR) { break; } // Wasn't too large or too small, can use this one newEras[newIndex] = baseEras[i]; newIndex++; } // If we didn't copy any then something was wrong, just return base if (newIndex == 0) return baseEras; // Resize the output array Array.Resize(ref newEras, newIndex); return newEras; } // Construct an instance of JapaneseLunisolar calendar. public JapaneseLunisolarCalendar() { helper = new GregorianCalendarHelper(this, TrimEras(JapaneseCalendar.GetEraInfo())); } public override int GetEra(DateTime time) { return (helper.GetEra(time)); } internal override CalendarId BaseCalendarID { get { return (CalendarId.JAPAN); } } internal override CalendarId ID { get { return (CalendarId.JAPANESELUNISOLAR); } } public override int[] Eras { get { return (helper.Eras); } } } }
62.446945
162
0.351063
[ "MIT" ]
Rayislandstyle/dotnet-coreclr
src/mscorlib/corefx/System/Globalization/JapaneseLunisolarCalendar.cs
19,421
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 { /// <summary> /// A factory for creating derived <see cref="DbContext" /> instances. Implement this /// interface to enable design-time services for context types that do not have a /// public default constructor. /// At design-time, derived <see cref="DbContext" /> instances can be created in order to enable specific /// design-time experiences such as model rendering, DDL generation etc. To enable design-time instantiation /// for derived <see cref="DbContext" /> types that do not have a public, default constructor, implement /// this interface. Design-time services will auto-discover implementations of this interface that are in the /// same assembly as the derived <see cref="DbContext" /> type. /// </summary> /// <typeparam name="TContext"> </typeparam> public interface IDbContextFactory<out TContext> where TContext : DbContext { /// <summary> /// Creates a new instance of a derived <see cref="DbContext" /> type. /// </summary> /// <returns> An instance of TContext </returns> TContext Create(); } }
52.461538
134
0.655425
[ "Apache-2.0" ]
TerraVenil/entityframework
src/EntityFramework/Infrastructure/IDbContextFactory.cs
1,366
C#
using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; using AssetBundles; #if UNITY_EDITOR using UnityEditor; #endif namespace UAsset { [System.Serializable] public class Bundle { public string name; public string[] assets; public int version; public bool update { get; set; } public Hash128 hash { get; set; } public Bundle () { update = false; version = 0; } } public class BundleVersion { public string bundle; public Hash128 hash; public int version; public override string ToString () { return string.Format ("{0}:{1}:{2}", bundle, hash, version); } } public class AssetManifest : ScriptableObject, ISerializationCallbackReceiver { #region ISerializationCallbackReceiver implementation public void OnBeforeSerialize () { List<Bundle> list = new List<Bundle> (); foreach (var item in map) { Bundle bundle = new Bundle (); bundle.name = item.Key; bundle.assets = item.Value.assets; list.Add (bundle); } bundles = list.ToArray (); } public void OnAfterDeserialize () { map.Clear (); paths.Clear (); for (int i = 0; i < bundles.Length; i++) { var bundle = bundles [i]; map [bundle.name] = bundle; for (int j = 0; j < bundle.assets.Length; j++) { var assetPath = bundle.assets [j]; paths [assetPath] = bundle.name; } } } #endregion [SerializeField] Bundle[] bundles = new Bundle[0]; public Bundle[] Bundles { get { return bundles; } } Dictionary<string, string> paths = new Dictionary<string, string> (); Dictionary<string, Bundle> map = new Dictionary<string, Bundle> (); public string GetAssetBundleName (string assetPath) { string assetBundleName = null; if (!paths.TryGetValue (assetPath, out assetBundleName)) { Debug.LogError ("failed to GetAssetBundleName: " + assetPath); } return assetBundleName; } public const string ASSETBUNDLE_NAME = "assetmanifest"; public const string ASSET_NAME = "AssetManifest.asset"; static AssetManifest instance = null; public static AssetManifest Instance { get { #if UNITY_EDITOR if (instance == null) { instance = AssetDatabase.LoadAssetAtPath<AssetManifest> (EXPORT_PATH + ASSET_NAME); if (instance == null) { instance = CreateInstance<AssetManifest> (); AssetDatabase.CreateAsset (instance, EXPORT_PATH + ASSET_NAME); var importer = AssetImporter.GetAtPath (EXPORT_PATH + ASSET_NAME); if (importer != null) { importer.assetBundleName = ASSETBUNDLE_NAME; } } } #endif return instance; } } static Dictionary<string, bool> bundleStates = new Dictionary<string, bool> (); public static IEnumerator Initialize () { AssetBundleManager.SetDevelopmentAssetBundleServer (); var oper = AssetBundleManager.Initialize (); if (oper != null) { yield return oper; var req = AssetBundleManager.LoadAssetAsync (ASSETBUNDLE_NAME, ASSET_NAME, typeof(AssetManifest)); if (req != null) { yield return req; instance = req.GetAsset<AssetManifest> (); } } } public static string[] GetNewBundles (AssetBundleManifest remote, AssetBundleManifest local) { List<string> newBundles = new List<string> (); if (remote != null) { var localBundles = local.GetAllAssetBundles (); var remoteBundles = remote.GetAllAssetBundles (); foreach (var item in remoteBundles) { bool versionChanged = true; if (System.Array.Exists<string> (localBundles, o => { return o.Equals (item); })) { if (remote.GetAssetBundleHash (item).Equals (local.GetAssetBundleHash (item))) { versionChanged = false; } } if (versionChanged) { newBundles.Add (item); } } } return newBundles.ToArray (); } // static string AssetBundles_AssetBundleManager_overrideBaseDownloadingURL (string bundleName) // { // if (instance.map [bundleName].update) { // return System.IO.Path.Combine (Application.streamingAssetsPath, bundleName); // } // return AssetBundleManager.BaseDownloadingURL + bundleName; // } #if UNITY_EDITOR const string EXPORT_PATH = "Assets/"; static public string CreateAssetBundleDirectory () { // Choose the output path according to the build target. string outputPath = Path.Combine (Utility.AssetBundlesOutputPath, Utility.GetPlatformName ()); if (!Directory.Exists (outputPath)) Directory.CreateDirectory (outputPath); return outputPath; } public static AssetBundleManifest BuildAssetBundles () { // Choose the output path according to the build target. string outputPath = CreateAssetBundleDirectory (); var options = BuildAssetBundleOptions.None; bool shouldCheckODR = EditorUserBuildSettings.activeBuildTarget == BuildTarget.iOS; #if UNITY_TVOS shouldCheckODR |= EditorUserBuildSettings.activeBuildTarget == BuildTarget.tvOS; #endif if (shouldCheckODR) { #if ENABLE_IOS_ON_DEMAND_RESOURCES if (PlayerSettings.iOS.useOnDemandResources) options |= BuildAssetBundleOptions.UncompressedAssetBundle; #endif #if ENABLE_IOS_APP_SLICING options |= BuildAssetBundleOptions.UncompressedAssetBundle; #endif } return BuildPipeline.BuildAssetBundles (outputPath, options, EditorUserBuildSettings.activeBuildTarget); } static string versionsFilePath { get { return string.Format ("{0}/version.txt", CreateAssetBundleDirectory ()); } } static void LoadVersions (Dictionary<string, BundleVersion> versions) { if (File.Exists (versionsFilePath)) { TextReader reader = new StreamReader (versionsFilePath); if (reader != null) { string line = null; while ((line = reader.ReadLine ()) != null) { string[] fields = line.Split (':'); BundleVersion v = new BundleVersion (); v.bundle = fields [0]; v.hash = Hash128.Parse (fields [1]); v.version = int.Parse (fields [2]); versions [v.bundle] = v; } reader.Close (); } } } static void SaveVersions (Dictionary<string, BundleVersion> versions) { TextWriter writer = new StreamWriter (versionsFilePath); if (writer != null) { foreach (var item in versions) { writer.WriteLine (item.Value.ToString ()); } writer.Close (); } EditorUtility.OpenWithDefaultApp (versionsFilePath); } public void Build () { var time = System.DateTime.Now.TimeOfDay.TotalSeconds; AssetDatabase.RemoveUnusedAssetBundleNames (); var allAssetBundleNames = AssetDatabase.GetAllAssetBundleNames (); for (int i = 0; i < allAssetBundleNames.Length; i++) { var item = allAssetBundleNames [i]; if (System.IO.Directory.Exists (item)) { Debug.LogError (item + " Is Directory."); } } AssetDatabase.RemoveUnusedAssetBundleNames (); allAssetBundleNames = AssetDatabase.GetAllAssetBundleNames (); if (allAssetBundleNames.Length > 0) { bundles = new Bundle[allAssetBundleNames.Length]; map.Clear (); for (int i = 0; i < allAssetBundleNames.Length; i++) { var item = allAssetBundleNames [i]; bundles [i] = new Bundle (); bundles [i].name = item; bundles [i].assets = AssetDatabase.GetAssetPathsFromAssetBundle (item); map [item] = bundles [i]; } EditorUtility.SetDirty (this); } var importer = AssetImporter.GetAtPath (EXPORT_PATH + ASSET_NAME); if (importer != null) { importer.assetBundleName = ASSETBUNDLE_NAME; } var elasped = System.DateTime.Now.TimeOfDay.TotalSeconds - time; Dictionary<string, BundleVersion> versions = new Dictionary<string, BundleVersion> (); LoadVersions (versions); var assetBundleManifest = BuildAssetBundles (); if (assetBundleManifest != null) { foreach (var item in allAssetBundleNames) { var hash = assetBundleManifest.GetAssetBundleHash (item); BundleVersion version = null; if (!versions.TryGetValue (item, out version)) { version = new BundleVersion (); version.bundle = item; version.hash = hash; version.version = 1; versions [item] = version; } else { if (!version.hash.Equals (hash)) { version.hash = hash; version.version++; } } } Debug.Log ("assetBundleManifest.GetHashCode: " + assetBundleManifest.GetHashCode ()); } SaveVersions (versions); Debug.Log ("[AssetManifest] Build with " + elasped + " seconds."); } #endif } }
28.609428
117
0.676474
[ "Apache-2.0" ]
CorianderLi/AssetManager
Assets/AssetManager/AssetManifest.cs
8,497
C#
using Newtonsoft.Json; namespace Grasews.API.Models { /// <summary> /// /// </summary> public class GraphJson_ApiRequestCreateModel { /// <summary> /// /// </summary> [JsonProperty("service_name", NullValueHandling = NullValueHandling.Ignore)] public string ServiceName { get; set; } /// <summary> /// /// </summary> [JsonProperty("xml", NullValueHandling = NullValueHandling.Ignore)] public string Xml { get; set; } } }
23.954545
84
0.563567
[ "MIT" ]
mlcalache/grasews
Grasews.Models/GraphJson_ApiRequestCreateModel.cs
529
C#
using System; namespace Aut.Lab.lab09 { class lab09Application { public void Run() { Console.Write("Enter 2 point : "); string twopoint = Console.ReadLine(); string[] arrpoint = twopoint.Split('|'); Point p1 = new Point(arrpoint[0]); Point p2 = new Point(arrpoint[1]); Line l1 = new Line(p1,p2); string cmd = ""; while(cmd != "exist") { Console.Write("Please enter command : "); string command = Console.ReadLine(); string[]splitcmd = command.Split(' '); cmd = splitcmd[0]; if(cmd.Equals("length")) { double length = l1.Length(); Console.WriteLine("Length = {0}",length); } else if(cmd.Equals("slope")) { double slope = l1.Slope(); if(slope == -0) { Console.WriteLine("Slope = 0"); } else { Console.WriteLine("Slope = {0}",slope); } } else if(cmd.Equals("exit")) { return; } else if(cmd.Equals("showc")) { double length = l1.Length(); double slope = l1.Slope(); l1.ShowC(slope); } else if(cmd.Equals("show")) { double length = l1.Length(); double slope = l1.Slope(); Console.WriteLine("Length = {0}",length); if(slope == -0) { Console.WriteLine("Slope = 0"); } else { Console.WriteLine("Slope = {0}",slope); } l1.ShowC(slope); } } } } }
31.788732
79
0.330527
[ "MIT" ]
pjamenaja/tutorials
Learning/Aut/Lab/Lab09/Lab09Application.cs
2,257
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Localization; using OrchardCore.DisplayManagement; using OrchardCore.DisplayManagement.Descriptors; using OrchardCore.DisplayManagement.Implementation; using OrchardCore.DisplayManagement.Shapes; namespace OrchardCore.Navigation { public class PagerShapesTableProvider : IShapeTableProvider { private readonly IStringLocalizer S; public PagerShapesTableProvider(IStringLocalizer<PagerShapes> localizer) { S = localizer; } public void Discover(ShapeTableBuilder builder) { builder.Describe("Pager") .OnCreated(created => { dynamic pager = created.Shape; // Intializes the common properties of a Pager shape // such that views can safely add values to them. pager.ItemClasses = new List<string>(); pager.ItemAttributes = new Dictionary<string, string>(); }) .OnDisplaying(displaying => { dynamic pager = displaying.Shape; string pagerId = pager.PagerId; if (!String.IsNullOrEmpty(pagerId)) { displaying.Shape.Metadata.Alternates.Add("Pager__" + EncodeAlternateElement(pagerId)); } }); builder.Describe("PagerSlim") .OnCreated(created => { dynamic pager = created.Shape; // Intializes the common properties of a Pager shape // such that views can safely add values to them. pager.ItemClasses = new List<string>(); pager.ItemAttributes = new Dictionary<string, string>(); }); builder.Describe("Pager_Gap") .OnDisplaying(displaying => { dynamic shape = displaying.Shape; var pager = shape.Pager; string pagerId = pager.PagerId; if (!String.IsNullOrEmpty(pagerId)) { pager.Metadata.Alternates.Add("Pager_Gap__" + EncodeAlternateElement(pagerId)); } }); builder.Describe("Pager_First") .OnDisplaying(displaying => { dynamic shape = displaying.Shape; var pager = shape.Pager; string pagerId = pager.PagerId; if (!String.IsNullOrEmpty(pagerId)) { displaying.Shape.Metadata.Alternates.Add("Pager_First__" + EncodeAlternateElement(pagerId)); } }); builder.Describe("Pager_Previous") .OnDisplaying(displaying => { dynamic shape = displaying.Shape; var pager = shape.Pager; string pagerId = pager.PagerId; if (!String.IsNullOrEmpty(pagerId)) { displaying.Shape.Metadata.Alternates.Add("Pager_Previous__" + EncodeAlternateElement(pagerId)); } }); builder.Describe("Pager_Next") .OnDisplaying(displaying => { dynamic shape = displaying.Shape; var pager = shape.Pager; string pagerId = pager.PagerId; if (!String.IsNullOrEmpty(pagerId)) { displaying.Shape.Metadata.Alternates.Add("Pager_Next__" + EncodeAlternateElement(pagerId)); } }); builder.Describe("Pager_Last") .OnDisplaying(displaying => { dynamic shape = displaying.Shape; var pager = shape.Pager; string pagerId = pager.PagerId; if (!String.IsNullOrEmpty(pagerId)) { displaying.Shape.Metadata.Alternates.Add("Pager_Last__" + EncodeAlternateElement(pagerId)); } }); builder.Describe("Pager_CurrentPage") .OnDisplaying(displaying => { dynamic shape = displaying.Shape; var pager = shape.Pager; string pagerId = pager.PagerId; if (!String.IsNullOrEmpty(pagerId)) { displaying.Shape.Metadata.Alternates.Add("Pager_CurrentPage__" + EncodeAlternateElement(pagerId)); } }); builder.Describe("Pager_Links") .OnDisplaying(displaying => { dynamic pager = displaying.Shape; string pagerId = pager.PagerId; if (!String.IsNullOrEmpty(pagerId)) { displaying.Shape.Metadata.Alternates.Add("Pager_Links__" + EncodeAlternateElement(pagerId)); } }); } private string EncodeAlternateElement(string alternateElement) { return alternateElement.Replace("-", "__").Replace('.', '_'); } } public class PagerShapes : IShapeAttributeProvider { private readonly IStringLocalizer S; public PagerShapes(IStringLocalizer<PagerShapes> localizer) { S = localizer; } [Shape] public async Task<IHtmlContent> Pager_Links(dynamic Shape, dynamic DisplayAsync, dynamic New, IHtmlHelper Html, DisplayContext DisplayContext, int Page, int PageSize, double TotalItemCount, int? Quantity, object FirstText, object PreviousText, object NextText, object LastText, object GapText, string PagerId, bool ShowNext, string Tag, string ItemTag, IDictionary<string, string> Attributes, IDictionary<string, string> ItemAttributes // parameter omitted to workaround an issue where a NullRef is thrown // when an anonymous object is bound to an object shape parameter /*object RouteValues*/) { Shape.Tag = Tag; Shape.ItemTag = ItemTag; Shape.Attributes = Attributes; Shape.ItemAttributes = ItemAttributes; var currentPage = Page; if (currentPage < 1) currentPage = 1; var pageSize = PageSize; var numberOfPagesToShow = Quantity ?? 0; if (Quantity == null || Quantity < 0) numberOfPagesToShow = 7; var totalPageCount = pageSize > 0 ? (int)Math.Ceiling(TotalItemCount / pageSize) : 1; // return shape early if pager is not needed. if (totalPageCount < 2) { Shape.Metadata.Type = "List"; return await DisplayAsync(Shape); } var firstText = FirstText ?? S["<<"]; var previousText = PreviousText ?? S["<"]; var nextText = NextText ?? S[">"]; var lastText = LastText ?? S[">>"]; var gapText = GapText ?? S["..."]; var httpContextAccessor = DisplayContext.ServiceProvider.GetService<IHttpContextAccessor>(); var httpContext = httpContextAccessor.HttpContext; var routeData = new RouteValueDictionary(Html.ViewContext.RouteData.Values); if (httpContext != null) { var queryString = httpContext.Request.Query; if (queryString != null) { foreach (var key in from string key in queryString.Keys where key != null && !routeData.ContainsKey(key) let value = queryString[key] select key) { routeData[key] = queryString[key]; } } } // specific cross-requests route data can be passed to the shape directly (e.g., OrchardCore.Users) var shapeRoute = (object)((dynamic)Shape).RouteData; if (shapeRoute != null) { var shapeRouteData = shapeRoute as RouteValueDictionary; if (shapeRouteData == null) { var route = shapeRoute as RouteData; if (route != null) { shapeRouteData = new RouteValueDictionary(route.Values); } } if (shapeRouteData != null) { foreach (var rd in shapeRouteData) { routeData[rd.Key] = rd.Value; } } } int firstPage = Math.Max(1, Page - (numberOfPagesToShow / 2)); int lastPage = Math.Min(totalPageCount, Page + (int)(numberOfPagesToShow / 2)); var pageKey = String.IsNullOrEmpty(PagerId) ? "page" : PagerId; Shape.Classes.Add("pager"); Shape.Metadata.Alternates.Clear(); Shape.Metadata.Type = "List"; // first and previous pages if ((Page > 1) && (routeData.ContainsKey(pageKey))) { routeData.Remove(pageKey); // to keep from having "page=1" in the query string } // first Shape.Add(await New.Pager_First(Value: firstText, RouteValues: new RouteValueDictionary(routeData), Pager: Shape, Disabled: Page < 2)); // previous if ((Page > 1) && (currentPage > 2)) { // also to keep from having "page=1" in the query string routeData[pageKey] = currentPage - 1; } Shape.Add(await New.Pager_Previous(Value: previousText, RouteValues: new RouteValueDictionary(routeData), Pager: Shape, Disabled: Page < 2)); // gap at the beginning of the pager if (firstPage > 1 && numberOfPagesToShow > 0) { Shape.Add(await New.Pager_Gap(Value: gapText, Pager: Shape)); } // page numbers if (numberOfPagesToShow > 0 && lastPage > 1) { for (var p = firstPage; p <= lastPage; p++) { if (p == currentPage) { routeData[pageKey] = currentPage; Shape.Add(await New.Pager_CurrentPage(Value: p, RouteValues: new RouteValueDictionary(routeData), Pager: Shape)); } else { if (p == 1) routeData.Remove(pageKey); else routeData[pageKey] = p; Shape.Add(await New.Pager_Link(Value: p, RouteValues: new RouteValueDictionary(routeData), Pager: Shape)); } } } // gap at the end of the pager if (lastPage < totalPageCount && numberOfPagesToShow > 0) { Shape.Add(await New.Pager_Gap(Value: gapText, Pager: Shape)); } // Next routeData[pageKey] = Page + 1; Shape.Add(await New.Pager_Next(Value: nextText, RouteValues: new RouteValueDictionary(routeData), Pager: Shape, Disabled: Page >= totalPageCount && !ShowNext)); // Last routeData[pageKey] = totalPageCount; Shape.Add(await New.Pager_Last(Value: lastText, RouteValues: new RouteValueDictionary(routeData), Pager: Shape, Disabled: Page >= totalPageCount)); return await DisplayAsync(Shape); } [Shape] public Task<IHtmlContent> Pager(Shape Shape, dynamic DisplayAsync) { Shape.Metadata.Alternates.Clear(); Shape.Metadata.Type = "Pager_Links"; return DisplayAsync(Shape); } [Shape] public async Task<IHtmlContent> PagerSlim(dynamic Shape, dynamic DisplayAsync, dynamic New, IHtmlHelper Html, string Id, object PreviousText, object NextText, string PreviousClass, string NextClass, string Tag, string ItemTag, IDictionary<string, string> Attributes, IDictionary<string, string> ItemAttributes, Dictionary<string, object> UrlParams) { Shape.Classes.Add("pager"); Shape.Metadata.Alternates.Clear(); Shape.Metadata.Type = "List"; Shape.Id = Id; Shape.Tag = Tag; Shape.ItemTag = ItemTag; Shape.Attributes = Attributes; Shape.ItemAttributes = ItemAttributes; var previousText = PreviousText ?? S["<"]; var nextText = NextText ?? S[">"]; var routeData = new RouteValueDictionary(Html.ViewContext.RouteData.Values); // Allows to pass custom url params to PagerSlim if (UrlParams != null) { foreach (var item in UrlParams) { routeData.Add(item.Key, item.Value); } } string after = Shape.After; string before = Shape.Before; if (before != null) { var beforeRouteData = new RouteValueDictionary(routeData); beforeRouteData["before"] = (string)Shape.Before; Shape.Add(await New.Pager_Previous(Value: previousText, RouteValues: beforeRouteData, Pager: Shape)); Shape.FirstClass = PreviousClass; } if (after != null) { var afterRouteData = new RouteValueDictionary(routeData); afterRouteData["after"] = (string)Shape.After; Shape.Add(await New.Pager_Next(Value: nextText, RouteValues: afterRouteData, Pager: Shape)); Shape.LastClass = NextClass; } return await DisplayAsync(Shape); } [Shape] public Task<IHtmlContent> Pager_First(Shape Shape, dynamic DisplayAsync) { Shape.Metadata.Alternates.Clear(); Shape.Metadata.Type = "Pager_Link"; return DisplayAsync(Shape); } [Shape] public Task<IHtmlContent> Pager_Previous(Shape Shape, dynamic DisplayAsync) { Shape.Metadata.Alternates.Clear(); Shape.Metadata.Type = "Pager_Link"; return DisplayAsync(Shape); } [Shape] public Task<IHtmlContent> Pager_CurrentPage(Shape Shape, dynamic DisplayAsync) { Shape.Metadata.Alternates.Clear(); Shape.Metadata.Type = "Pager_Link"; ((dynamic)Shape).Tag.AddCssClass("active"); return DisplayAsync(Shape); } [Shape] public Task<IHtmlContent> Pager_Next(Shape Shape, dynamic DisplayAsync) { Shape.Metadata.Alternates.Clear(); Shape.Metadata.Type = "Pager_Link"; return DisplayAsync(Shape); } [Shape] public Task<IHtmlContent> Pager_Last(Shape Shape, dynamic DisplayAsync) { Shape.Metadata.Alternates.Clear(); Shape.Metadata.Type = "Pager_Link"; return DisplayAsync(Shape); } [Shape] public Task<IHtmlContent> Pager_Link(IHtmlHelper Html, Shape Shape, dynamic DisplayAsync, object Value) { Shape.Metadata.Alternates.Clear(); Shape.Metadata.Type = "ActionLink"; return DisplayAsync(Shape); } [Shape] public IHtmlContent ActionLink(IUrlHelper Url, Shape Shape, object Value, bool Disabled = false) { if (Disabled) { TagBuilder parentLiTag = (TagBuilder)((dynamic)Shape).Tag; parentLiTag.AddCssClass("disabled"); } var RouteValues = (object)((dynamic)Shape).RouteValues; RouteValueDictionary rvd; if (RouteValues == null) { rvd = new RouteValueDictionary(); } else { rvd = RouteValues as RouteValueDictionary ?? new RouteValueDictionary(RouteValues); } var action = Url.Action((string)rvd["action"], (string)rvd["controller"], rvd); IEnumerable<string> classes = Shape.Classes; IDictionary<string, string> attributes = Shape.Attributes; attributes["href"] = action; string id = Shape.Id; var tag = Shape.GetTagBuilder("a", id, classes, attributes); tag.InnerHtml.AppendHtml(CoerceHtmlString(Value)); return tag; } [Shape] public Task<IHtmlContent> Pager_Gap(Shape Shape, dynamic DisplayAsync) { Shape.Metadata.Alternates.Clear(); Shape.Metadata.Type = "Pager_Link"; ((dynamic)Shape).Tag.AddCssClass("disabled"); return DisplayAsync(Shape); } private IHtmlContent CoerceHtmlString(object value) { if (value == null) { return null; } if (value is IHtmlContent result) { return result; } return new StringHtmlContent(value.ToString()); } } }
36.649299
172
0.524442
[ "BSD-3-Clause" ]
Stoyanov8/OrchardCore
src/OrchardCore.Modules/OrchardCore.Navigation/PagerShapes.cs
18,288
C#
/**************************************************************************** * NVorbis * * Copyright (C) 2014, Andrew Ward <afward@gmail.com> * * * * See COPYING for license terms (Ms-PL). * * * ***************************************************************************/ using System; namespace RhythmCodex.Plugin.NVorbis.Lib { /// <summary> /// Event data for when a new logical stream is found in a container. /// </summary> [Serializable] public class NewStreamEventArgs : EventArgs { /// <summary> /// Creates a new instance of <see cref="NewStreamEventArgs"/> with the specified <see cref="IPacketProvider"/>. /// </summary> /// <param name="packetProvider">An <see cref="IPacketProvider"/> instance.</param> public NewStreamEventArgs(IPacketProvider packetProvider) { PacketProvider = packetProvider ?? throw new ArgumentNullException(nameof(packetProvider)); } /// <summary> /// Gets new the <see cref="IPacketProvider"/> instance. /// </summary> public IPacketProvider PacketProvider { get; } /// <summary> /// Gets or sets whether to ignore the logical stream associated with the packet provider. /// </summary> public bool IgnoreStream { get; set; } } }
41.128205
120
0.455736
[ "MIT" ]
SaxxonPike/RhythmCodex
Source/RhythmCodex.Plugin.NVorbis/Lib/NewStreamEventArgs.cs
1,606
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using System.Threading.Tasks; using ComponentModelValidationException = System.ComponentModel.DataAnnotations.ValidationException; using FluentValidationException = FluentValidation.ValidationException; namespace NightLib.Web.Filters { public class ValidationExceptionFilterAttribute : ExceptionFilterAttribute { public override Task OnExceptionAsync(ExceptionContext context) { switch (context.Exception) { case FluentValidationException exception: HandleFluentValidationException(exception, context); break; case ComponentModelValidationException exception: HandleComponentModelValidationException(exception, context); break; default: break; } return Task.CompletedTask; } public void HandleFluentValidationException(FluentValidationException exception, ExceptionContext context) { foreach (var error in exception.Errors) { context.ModelState.AddModelError(error.PropertyName, error.ErrorMessage); } var details = new ValidationProblemDetails(context.ModelState); context.Result = new BadRequestObjectResult(details); context.ExceptionHandled = true; } public void HandleComponentModelValidationException(ComponentModelValidationException exception, ExceptionContext context) { foreach (var key in exception.ValidationResult.MemberNames) { context.ModelState.TryAddModelException(key, exception); } var details = new ValidationProblemDetails(context.ModelState); context.Result = new BadRequestObjectResult(details); context.ExceptionHandled = true; } } }
36.254545
130
0.656469
[ "MIT" ]
vantm/nightlib
src/NightLib.Web/Filters/ValidationExceptionFilterAttribute.cs
1,994
C#
namespace ArmChair.Commands { //TODO: remove attributes which tie this class to newtonsoft //http://stackoverflow.com/a/26307686/47642 using System.Collections.Generic; using Newtonsoft.Json; /// <summary> /// a mongo query request. /// </summary> public class MongoQueryRequest { /// <summary> /// JSON object describing criteria used to select documents. More information provided in the section on selector syntax. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Include)] public IDictionary<string, object> Selector { get; set; } /// <summary> /// Maximum number of results returned. Default is 25. Optional /// </summary> public long? Limit { get; set; } /// <summary> /// Skip the first ‘n’ results, where ‘n’ is the value specified. Optional /// </summary> public long? Skip { get; set; } /// <summary> /// list of fields to return. /// </summary> public IList<string> Fields { get; set; } /// <summary> /// apply sorting to the query, plesae ensure there is an index which can be used. /// </summary> public IList<IDictionary<string, Order>> Sort { get; set; } } }
33.461538
130
0.596935
[ "Apache-2.0" ]
dbones-labs/arm-chair
src/ArmChair.Core/Commands/MongoQueryRequest.cs
1,315
C#
using MicrosoftStore.Responses; namespace MicrosoftStore.Models { public class RatingSummary : Payload { public double AverageRating { get; set; } public int ReviewCount { get; set; } public int Star1Count { get; set; } public int Star2Count { get; set; } public int Star3Count { get; set; } public int Star4Count { get; set; } public int Star5Count { get; set; } public int Star1ReviewCount { get; set; } public int Star2ReviewCount { get; set; } public int Star3ReviewCount { get; set; } public int Star4ReviewCount { get; set; } public int Star5ReviewCount { get; set; } public Review MostCriticalReview { get; set; } public Review MostFavorableReview { get; set; } } }
34.73913
55
0.623279
[ "MIT" ]
mediaexplorer74/MicroStore
MicrosoftStore/Models/RatingSummary.cs
801
C#
using System; using System.Collections.Generic; using System.Linq; using DatenMeister.Core.EMOF.Interface.Common; using DatenMeister.Core.EMOF.Interface.Identifiers; using DatenMeister.Core.EMOF.Interface.Reflection; using DatenMeister.Core.Functions.Queries; using DatenMeister.Core.Models.EMOF; using DatenMeister.Core.Runtime.Workspaces; namespace DatenMeister.Extent.Manager.Extents { /// <summary> /// Helper function for extents /// </summary> public class ExtentFunctions { /// <summary> /// Stores the workspace logic /// </summary> private readonly IWorkspaceLogic _workspaceLogic; /// <summary> /// Initializes a new instance of the ExtentFunctions class. /// </summary> /// <param name="workspaceLogic"></param> public ExtentFunctions(IWorkspaceLogic workspaceLogic) { _workspaceLogic = workspaceLogic; } /// <summary> /// Gets an enumeration of creatable types for a given extent. /// It navigates to the meta extent and looks for all classes /// </summary> /// <param name="collection">The reflectivecollection into which a new instance shall be created</param> /// <returns>Enumeration of types</returns> public CreateableTypeResult GetCreatableTypes(IReflectiveCollection collection) => GetCreatableTypes(((IHasExtent) collection)?.Extent ?? throw new InvalidOperationException("No extent")); /// <summary> /// Gets an enumeration of creatable types for a given extent. /// It navigates to the meta extent and looks for all classes /// </summary> /// <param name="element">The reflectivecollection into which a new instance shall be created</param> /// <returns>Enumeration of types</returns> public CreateableTypeResult GetCreatableTypes(IElement element) => GetCreatableTypes(((IHasExtent) element)?.Extent ?? throw new InvalidOperationException("No extent")); /// <summary> /// Gets an enumeration of creatable types for a given extent. /// It navigates to the meta extent and looks for all classes /// </summary> /// <param name="extent">The extent into which a new instance shall be created</param> /// <returns>Enumeration of types</returns> public CreateableTypeResult GetCreatableTypes(IExtent extent) { var dataLayer = _workspaceLogic.GetWorkspaceOfExtent(extent); if (dataLayer == null) { throw new InvalidOperationException("Datalayer is not found"); } var typeLayer = dataLayer.MetaWorkspaces.FirstOrDefault() ?? _workspaceLogic.GetTypesWorkspace(); var classType = _UML.TheOne.StructuredClassifiers.__Class; if (classType == null) { // We did not find the corresponding class type return new CreateableTypeResult { MetaLayer = typeLayer, CreatableTypes = new IElement[] { } }; } return new CreateableTypeResult { MetaLayer = typeLayer, CreatableTypes = _workspaceLogic.GetExtentsForWorkspace(typeLayer!) .SelectMany(x => x.elements().GetAllDescendants().WhenMetaClassIs(classType)) .Cast<IElement>() .ToList() }; } public class CreateableTypeResult { public Workspace? MetaLayer { get; set; } public IList<IElement>? CreatableTypes { get; set; } } } }
39.652632
117
0.612689
[ "MIT" ]
mbrenn/datenmeister-new
src/DatenMeister.Extent.Manager/Extents/ExtentFunctions.cs
3,769
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Kubeleans.KubernetesApi.Models { using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// SubjectAccessReviewSpec is a description of the access request. /// Exactly one of ResourceAuthorizationAttributes and /// NonResourceAuthorizationAttributes must be set /// </summary> public partial class Iok8sapiauthorizationv1SubjectAccessReviewSpec { /// <summary> /// Initializes a new instance of the /// Iok8sapiauthorizationv1SubjectAccessReviewSpec class. /// </summary> public Iok8sapiauthorizationv1SubjectAccessReviewSpec() { CustomInit(); } /// <summary> /// Initializes a new instance of the /// Iok8sapiauthorizationv1SubjectAccessReviewSpec class. /// </summary> /// <param name="extra">Extra corresponds to the user.Info.GetExtra() /// method from the authenticator. Since that is input to the /// authorizer it needs a reflection here.</param> /// <param name="groups">Groups is the groups you're testing /// for.</param> /// <param name="nonResourceAttributes">NonResourceAttributes describes /// information for a non-resource access request</param> /// <param name="resourceAttributes">ResourceAuthorizationAttributes /// describes information for a resource access request</param> /// <param name="uid">UID information about the requesting /// user.</param> /// <param name="user">User is the user you're testing for. If you /// specify "User" but not "Groups", then is it interpreted as "What if /// User were not a member of any groups</param> public Iok8sapiauthorizationv1SubjectAccessReviewSpec(IDictionary<string, IList<string>> extra = default(IDictionary<string, IList<string>>), IList<string> groups = default(IList<string>), Iok8sapiauthorizationv1NonResourceAttributes nonResourceAttributes = default(Iok8sapiauthorizationv1NonResourceAttributes), Iok8sapiauthorizationv1ResourceAttributes resourceAttributes = default(Iok8sapiauthorizationv1ResourceAttributes), string uid = default(string), string user = default(string)) { Extra = extra; Groups = groups; NonResourceAttributes = nonResourceAttributes; ResourceAttributes = resourceAttributes; Uid = uid; User = user; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets extra corresponds to the user.Info.GetExtra() method /// from the authenticator. Since that is input to the authorizer it /// needs a reflection here. /// </summary> [JsonProperty(PropertyName = "extra")] public IDictionary<string, IList<string>> Extra { get; set; } /// <summary> /// Gets or sets groups is the groups you're testing for. /// </summary> [JsonProperty(PropertyName = "groups")] public IList<string> Groups { get; set; } /// <summary> /// Gets or sets nonResourceAttributes describes information for a /// non-resource access request /// </summary> [JsonProperty(PropertyName = "nonResourceAttributes")] public Iok8sapiauthorizationv1NonResourceAttributes NonResourceAttributes { get; set; } /// <summary> /// Gets or sets resourceAuthorizationAttributes describes information /// for a resource access request /// </summary> [JsonProperty(PropertyName = "resourceAttributes")] public Iok8sapiauthorizationv1ResourceAttributes ResourceAttributes { get; set; } /// <summary> /// Gets or sets UID information about the requesting user. /// </summary> [JsonProperty(PropertyName = "uid")] public string Uid { get; set; } /// <summary> /// Gets or sets user is the user you're testing for. If you specify /// "User" but not "Groups", then is it interpreted as "What if User /// were not a member of any groups /// </summary> [JsonProperty(PropertyName = "user")] public string User { get; set; } } }
43.083333
496
0.647969
[ "MIT" ]
attilah/Kubeleans
src/KubernetesAPI.Reference/Models/Iok8sapiauthorizationv1SubjectAccessReviewSpec.cs
4,653
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DontDestroyOnLoad : MonoBehaviour { private void Awake() { transform.SetParent(null); Object.DontDestroyOnLoad(gameObject); } }
17.928571
46
0.713147
[ "MIT" ]
Miami-StevenR/Week8
Week 8/Assets/LavelManagement/Scripts/Utilities/DontDestroyOnLoad.cs
253
C#
// Licensed under the MIT License. // Copyright (c) Microsoft Corporation. All rights reserved. using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.Bot.Schema; using Microsoft.Recognizers.Text; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; namespace Microsoft.Bot.Builder.Dialogs.Adaptive.Recognizers { /// <summary> /// TextEntityRecognizer - base class for Text.Recogizers from the text recognizer library. /// </summary> public abstract class TextEntityRecognizer : EntityRecognizer { private static JsonSerializer serializer = new JsonSerializer() { ContractResolver = new CamelCasePropertyNamesContractResolver() }; /// <summary> /// Initializes a new instance of the <see cref="TextEntityRecognizer"/> class. /// </summary> /// <param name="callerPath">Optional, source file full path.</param> /// <param name="callerLine">Optional, line number in source file.</param> [JsonConstructor] public TextEntityRecognizer([CallerFilePath] string callerPath = "", [CallerLineNumber] int callerLine = 0) : base(callerPath, callerLine) { } /// <summary> /// Recognizes entities from an <see cref="Entity"/> list. /// </summary> /// <param name="dialogContext">The <see cref="DialogContext"/> for the current turn of conversation.</param> /// <param name="text">Text to recognize.</param> /// <param name="locale">Locale to use.</param> /// <param name="entities">The enumerated <see cref="Entity"/> to be recognized.</param> /// <param name="cancellationToken">Optional, the <see cref="CancellationToken"/> from the task.</param> /// <returns>Recognized <see cref="Entity"/> list.</returns> public override Task<IEnumerable<Entity>> RecognizeEntitiesAsync(DialogContext dialogContext, string text, string locale, IEnumerable<Entity> entities, CancellationToken cancellationToken = default) { List<Entity> newEntities = new List<Entity>(); var culture = Culture.MapToNearestLanguage(locale ?? string.Empty); // look for text entities to recognize foreach (var entity in entities.Where(e => e.Type == TextEntity.TypeName).Select(e => e as TextEntity ?? e.GetAs<TextEntity>())) { var results = Recognize(entity.Text, culture); foreach (var result in results) { var newEntity = JObject.FromObject(result, serializer).ToObject<Entity>(); newEntity.Type = result.TypeName; newEntity.Properties.Remove("TypeName"); newEntities.Add(newEntity); } } return Task.FromResult<IEnumerable<Entity>>(newEntities); } /// <summary> /// Text recognizing implementation. /// </summary> /// <param name="text">Text to recognize.</param> /// <param name="culture"><see cref="Culture"/> to use.</param> /// <returns>The recognized <see cref="ModelResult"/> list.</returns> protected abstract List<ModelResult> Recognize(string text, string culture); } }
45.72973
206
0.642139
[ "MIT" ]
SundaresanSivakumar/botbuilder-dotnet
libraries/Microsoft.Bot.Builder.Dialogs.Adaptive/Recognizers/EntityRecognizers/TextEntityRecognizer.cs
3,386
C#
using JSLTSharp.JsonTransforms.Abstractions; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; namespace JSLTSharp.JsonTransforms.EmbededFunctions.ConditionalOperations { public class IfNotEmptyConditionalKeyOperation : IJsonTransformConditionalCustomOperation { public string OperationName => "ifnotempty"; public bool Apply(JToken dataSource, JToken objectToApplyTo, IList<string> parameters) { if (parameters.Count != 1) throw new InvalidOperationException($"You must provide only one parameter for function {OperationName}"); return Exists(dataSource, objectToApplyTo, parameters); } protected bool Exists(JToken dataSource, JToken token, IList<string> parameters) { if (parameters[0].StartsWith("$")) { var existsTokenSearch = dataSource.SelectToken(parameters[0]); if (existsTokenSearch is null) { return false; } if (existsTokenSearch.Type == JTokenType.Object || existsTokenSearch.Type == JTokenType.Array) return existsTokenSearch.Children().Any(); else return existsTokenSearch.Type != JTokenType.Null; } else return !string.IsNullOrWhiteSpace(parameters[0]); } } }
36.35
121
0.624484
[ "MIT" ]
mathieumack/JSLTSharp
src/JSLTSharp/JsonTransforms/EmbededFunctions/ConditionalOperations/IfNotEmptyConditionalKeyOperation.cs
1,456
C#
namespace CodeBase.Off.Website.Models { using System.ComponentModel; using System.ComponentModel.DataAnnotations; using CodeBase.Off.Website.Properties; using DataAnnotationsExtensions; public sealed class SocialNetworkGridModel { public string Slug { get; set; } [DisplayName(@"نام")] public string Name { get; set; } [DisplayName(@"آدرس")] public string Url { get; set; } [DisplayName(@"فعال؟")] public string IsActive { get; set; } [DisplayName(@"ترتیب نمایش")] public int Order { get; set; } [DisplayName(@"تعداد کلیک")] public int ClickCount { get; set; } } }
25.333333
48
0.615497
[ "MIT" ]
m-sadegh-sh/CodeBase
src/Off/CodeBase.Off.Website/Models/SocialNetworkGridModel.cs
717
C#
using System.Text.RegularExpressions; using SkbKontur.Cassandra.DistributedTaskQueue.Monitoring.Api; using SkbKontur.Cassandra.TimeBasedUuid; using SkbKontur.TypeScript.ContractGenerator; using SkbKontur.TypeScript.ContractGenerator.Abstractions; using SkbKontur.TypeScript.ContractGenerator.CodeDom; using SkbKontur.TypeScript.ContractGenerator.Internals; using SkbKontur.TypeScript.ContractGenerator.TypeBuilders; namespace SkbKontur.Cassandra.DistributedTaskQueue.Monitoring.TestService.TypeScriptConfiguration { public class RtqMonitoringCustomTypeGenerator : ICustomTypeGenerator { public string GetTypeLocation(ITypeInfo type) { if (InternalApiTypeBuildingContext.Accept(type)) return InternalApiTypeBuildingContext.GetApiName(type); return type.IsGenericType ? new Regex("`.*$").Replace(type.Name, "") : type.Name; } public ITypeBuildingContext ResolveType(string initialUnitPath, ITypeGenerator typeGenerator, ITypeInfo type, ITypeScriptUnitFactory unitFactory) { if (type.Equals(TypeInfo.From<TimeGuid>())) return TypeBuilding.RedirectToType("TimeGuid", @"..\DataTypes\TimeGuid", type); if (type.Equals(TypeInfo.From<Timestamp>())) return TypeBuilding.RedirectToType("Timestamp", @"..\DataTypes\Timestamp", type); if (type.Equals(TypeInfo.From<TimestampRange>())) return TypeBuilding.RedirectToType("DateTimeRange", @"..\DataTypes\DateTimeRange", type); if (type.Equals(TypeInfo.From<long>())) return new TypeRedirectBuildingContext(TypeInfo.From<long>(), new TypeScriptBuildInType("string")); if (InternalApiTypeBuildingContext.Accept(type)) return new InternalApiTypeBuildingContext(unitFactory.GetOrCreateTypeUnit(initialUnitPath), type); return null; } public TypeScriptTypeMemberDeclaration ResolveProperty(TypeScriptUnit unit, ITypeGenerator typeGenerator, ITypeInfo type, IPropertyInfo property) { return null; } } }
50.595238
153
0.72
[ "MIT" ]
skbkontur/cassandra-distributed-task-queue
Cassandra.DistributedTaskQueue.Monitoring.TestService/TypeScriptConfiguration/RtqMonitoringCustomTypeGenerator.cs
2,127
C#