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 ForEvolve.DependencyInjection; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using System; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Microsoft.Extensions.DependencyInjection { public static class ForEvolveDependencyInjectionModulesStartupExtensions { /// <summary> /// Create an <see cref="IScanningContext"/>, scan specified assemblies, /// and initialized the modules that were found. /// </summary> /// <param name="services">The service collection to add dependency to.</param> /// <param name="assemblies">The assemblies to scan for modules.</param> /// <returns>The <see cref="IServiceCollection"/>.</returns> public static IServiceCollection AddDependencyInjectionModules(this IServiceCollection services, params Assembly[] assemblies) { services.AddDependencyInjectionModules(initialize: true, assemblies); return services; } /// <summary> /// Create an <see cref="IScanningContext"/>, scan specified assemblies, /// and optionaly initialized the modules that were found. /// </summary> /// <param name="services">The service collection to add dependency to.</param> /// <param name="initialize"> /// When true, call the <see cref="IScanningContext.Initialize"/> method of /// the <see cref="IScanningContext"/> after scanning the assemblies. /// </param> /// <param name="assemblies">The assemblies to scan for modules.</param> /// <returns>The created <see cref="IScanningContext"/>.</returns> public static IScanningContext AddDependencyInjectionModules(this IServiceCollection services, bool initialize, params Assembly[] assemblies) { var context = new ScanningContext(services); if (assemblies != null) { context.ScanAssemblies(assemblies); } if (initialize) { context.Initialize(); } return context; } /// <summary> /// Register the specified <see cref="IConfiguration"/>, used during modules instantiation. /// </summary> /// <param name="scanningContext">The scanning context to add <see cref="IConfiguration"/> to.</param> /// <param name="configuration">The <see cref="IConfiguration"/> to add.</param> /// <returns>The <paramref name="scanningContext"/>.</returns> public static IScanningContext UseConfiguration(this IScanningContext scanningContext, IConfiguration configuration) { return scanningContext .ConfigureServices(services => services.TryAddSingleton(configuration)) ; } /// <summary> /// Scan the specified assemblies and registers all <see cref="IDependencyInjectionModule"/> /// implementations that are found with the <see cref="IScanningContext"/>. /// /// This method can be called multiple times. /// </summary> /// <param name="scanningContext">The <see cref="IScanningContext"/> to registers modules against.</param> /// <param name="assemblies">The assemblies to scan for.</param> /// <returns>The <paramref name="scanningContext"/>.</returns> public static IScanningContext ScanAssemblies(this IScanningContext scanningContext, params Assembly[] assemblies) { foreach (var assembly in assemblies) { if (assembly.IsDynamic) { continue; // throw an exception? log an error/warning? } var modulesTypeInfo = assembly .DefinedTypes .Where(t => t.IsClass && !t.IsAbstract) .KeepOnlyDependencyInjectionModules(); ; scanningContext.Register(modulesTypeInfo); } return scanningContext; } /// <summary> /// Create a <see cref="IScanningContext"/> ready to scan for DI modules. /// </summary> /// <param name="services">The service collection to add dependency to.</param> /// <returns>The newly created <see cref="IScanningContext"/>.</returns> [Obsolete("Use AddDependencyInjectionModules(...) instead. This should be removed in v3.0.", false)] public static IScanningContext ScanForDIModules(this IServiceCollection services) { return services.AddDependencyInjectionModules(initialize: false); } /// <summary> /// Scan the assembly containing <typeparamref name="T"/> /// and initialize all DI modules found, registering dependencies /// with the <see cref="IServiceCollection"/> specified during the /// <see cref="IScanningContext"/> creation. /// </summary> /// <typeparam name="T">The type in an assembly to scan.</typeparam> /// <param name="scanningContext">The <see cref="IScanningContext"/> to initialize.</param> /// <returns>The <paramref name="scanningContext"/>.</returns> [Obsolete("Use AddDependencyInjectionModules(...) or ScanAssemblies(...) instead. This should be removed in v3.0.", false)] public static IScanningContext FromAssemblyOf<T>(this IScanningContext scanningContext) { var assemblyToScan = typeof(T).Assembly; return scanningContext.ScanAssemblies(assemblyToScan); } /// <summary> /// Register the specified <see cref="IConfiguration"/>, used during DI module instantiation. /// </summary> /// <param name="scanningContext">The scanning context to add <see cref="IConfiguration"/> to.</param> /// <param name="configuration">The <see cref="IConfiguration"/> to add.</param> /// <returns>The <paramref name="scanningContext"/>.</returns> [Obsolete("Use UseConfiguration(...) instead. This should be removed in v3.0.", false)] public static IScanningContext WithConfiguration(this IScanningContext scanningContext, IConfiguration configuration) { return scanningContext.UseConfiguration(configuration); } } }
48.43609
149
0.633654
[ "MIT" ]
ForEvolve/ForEvolve.DependencyInjection
src/ForEvolve.DependencyInjection.Modules/StartupExtensions.cs
6,444
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // System.Net.ChunkedInputStream // // Authors: // Gonzalo Paniagua Javier (gonzalo@novell.com) // // Copyright (c) 2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System.IO; using System.Runtime.InteropServices; namespace System.Net { internal sealed class ChunkedInputStream : HttpRequestStream { private ChunkStream _decoder; private readonly HttpListenerContext _context; private bool _no_more_data; private sealed class ReadBufferState { public byte[] Buffer; public int Offset; public int Count; public int InitialCount; public HttpStreamAsyncResult Ares; public ReadBufferState(byte[] buffer, int offset, int count, HttpStreamAsyncResult ares) { Buffer = buffer; Offset = offset; Count = count; InitialCount = count; Ares = ares; } } public ChunkedInputStream(HttpListenerContext context, Stream stream, byte[] buffer, int offset, int length) : base(stream, buffer, offset, length) { _context = context; WebHeaderCollection coll = (WebHeaderCollection)context.Request.Headers; _decoder = new ChunkStream(coll); } public ChunkStream Decoder { get { return _decoder; } set { _decoder = value; } } protected override int ReadCore(byte[] buffer, int offset, int count) { IAsyncResult ares = BeginReadCore(buffer, offset, count, null, null); return EndRead(ares); } protected override IAsyncResult BeginReadCore(byte[] buffer, int offset, int size, AsyncCallback? cback, object? state) { HttpStreamAsyncResult ares = new HttpStreamAsyncResult(this); ares._callback = cback; ares._state = state; if (_no_more_data || size == 0 || _closed) { ares.Complete(); return ares; } int nread = _decoder.Read(buffer, offset, size); offset += nread; size -= nread; if (size == 0) { // got all we wanted, no need to bother the decoder yet ares._count = nread; ares.Complete(); return ares; } if (!_decoder.WantMore) { _no_more_data = nread == 0; ares._count = nread; ares.Complete(); return ares; } ares._buffer = new byte[8192]; ares._offset = 0; ares._count = 8192; ReadBufferState rb = new ReadBufferState(buffer, offset, size, ares); rb.InitialCount += nread; base.BeginReadCore(ares._buffer, ares._offset, ares._count, OnRead, rb); return ares; } private void OnRead(IAsyncResult base_ares) { ReadBufferState rb = (ReadBufferState)base_ares.AsyncState!; HttpStreamAsyncResult ares = rb.Ares; try { int nread = base.EndRead(base_ares); if (nread == 0) { _no_more_data = true; ares._count = rb.InitialCount - rb.Count; ares.Complete(); return; } _decoder.Write(ares._buffer!, ares._offset, nread); nread = _decoder.Read(rb.Buffer, rb.Offset, rb.Count); rb.Offset += nread; rb.Count -= nread; if (rb.Count == 0 || !_decoder.WantMore) { _no_more_data = !_decoder.WantMore && nread == 0; ares._count = rb.InitialCount - rb.Count; ares.Complete(); return; } ares._offset = 0; ares._count = Math.Min(8192, _decoder.ChunkLeft + 6); base.BeginReadCore(ares._buffer!, ares._offset, ares._count, OnRead, rb); } catch (Exception e) { _context.Connection.SendError(e.Message, 400); ares.Complete(e); } } public override int EndRead(IAsyncResult asyncResult) { ArgumentNullException.ThrowIfNull(asyncResult); HttpStreamAsyncResult? ares = asyncResult as HttpStreamAsyncResult; if (ares == null || !ReferenceEquals(this, ares._parent)) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } if (ares._endCalled) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, nameof(EndRead))); } ares._endCalled = true; if (!asyncResult.IsCompleted) asyncResult.AsyncWaitHandle.WaitOne(); if (ares._error != null) throw new HttpListenerException((int)HttpStatusCode.BadRequest, SR.Format(SR.net_io_operation_aborted, ares._error.Message)); return ares._count; } } }
36.983051
141
0.570272
[ "MIT" ]
Ali-YousefiTelori/runtime
src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkedInputStream.cs
6,546
C#
/* The MIT License (MIT) Copyright (c) 2016 Maksim Volkau 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 AddOrUpdateServiceFactory all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace DryIoc { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Runtime.CompilerServices; // for aggressive inlining hints /// <summary>Methods to work with immutable arrays, and general array sugar.</summary> public static class ArrayTools { /// <summary>Returns true if array is null or have no items.</summary> <typeparam name="T">Type of array item.</typeparam> /// <param name="source">Source array to check.</param> <returns>True if null or has no items, false otherwise.</returns> public static bool IsNullOrEmpty<T>(this T[] source) { return source == null || source.Length == 0; } /// <summary>Returns empty array instead of null, or source array otherwise.</summary> <typeparam name="T">Type of array item.</typeparam> /// <param name="source">Source array.</param> <returns>Empty array or source.</returns> public static T[] EmptyIfNull<T>(this T[] source) { return source ?? Empty<T>(); } /// <summary>Returns source enumerable if it is array, otherwise converts source to array.</summary> /// <typeparam name="T">Array item type.</typeparam> /// <param name="source">Source enumerable.</param> /// <returns>Source enumerable or its array copy.</returns> public static T[] ToArrayOrSelf<T>(this IEnumerable<T> source) { return source is T[] ? (T[])source : source.ToArray(); } /// <summary>Returns new array consisting from all items from source array then all items from added array. /// If source is null or empty, then added array will be returned. /// If added is null or empty, then source will be returned.</summary> /// <typeparam name="T">Array item type.</typeparam> /// <param name="source">Array with leading items.</param> /// <param name="added">Array with following items.</param> /// <returns>New array with items of source and added arrays.</returns> public static T[] Append<T>(this T[] source, params T[] added) { if (added == null || added.Length == 0) return source; if (source == null || source.Length == 0) return added; var result = new T[source.Length + added.Length]; Array.Copy(source, 0, result, 0, source.Length); if (added.Length == 1) result[source.Length] = added[0]; else Array.Copy(added, 0, result, source.Length, added.Length); return result; } /// <summary>Returns new array with <paramref name="value"/> appended, /// or <paramref name="value"/> at <paramref name="index"/>, if specified. /// If source array could be null or empty, then single value item array will be created despite any index.</summary> /// <typeparam name="T">Array item type.</typeparam> /// <param name="source">Array to append value to.</param> /// <param name="value">Value to append.</param> /// <param name="index">(optional) Index of value to update.</param> /// <returns>New array with appended or updated value.</returns> public static T[] AppendOrUpdate<T>(this T[] source, T value, int index = -1) { if (source == null || source.Length == 0) return new[] { value }; var sourceLength = source.Length; index = index < 0 ? sourceLength : index; var result = new T[index < sourceLength ? sourceLength : sourceLength + 1]; Array.Copy(source, result, sourceLength); result[index] = value; return result; } /// <summary>Calls predicate on each item in <paramref name="source"/> array until predicate returns true, /// then method will return this item index, or if predicate returns false for each item, method will return -1.</summary> /// <typeparam name="T">Type of array items.</typeparam> /// <param name="source">Source array: if null or empty, then method will return -1.</param> /// <param name="predicate">Delegate to evaluate on each array item until delegate returns true.</param> /// <returns>Index of item for which predicate returns true, or -1 otherwise.</returns> public static int IndexOf<T>(this T[] source, Func<T, bool> predicate) { if (source != null && source.Length != 0) for (var i = 0; i < source.Length; ++i) if (predicate(source[i])) return i; return -1; } /// <summary>Looks up for item in source array equal to provided value, and returns its index, or -1 if not found.</summary> /// <typeparam name="T">Type of array items.</typeparam> /// <param name="source">Source array: if null or empty, then method will return -1.</param> /// <param name="value">Value to look up.</param> /// <returns>Index of item equal to value, or -1 item is not found.</returns> public static int IndexOf<T>(this T[] source, T value) { if (source != null && source.Length != 0) for (var i = 0; i < source.Length; ++i) { var item = source[i]; if (ReferenceEquals(item, value) || Equals(item, value)) return i; } return -1; } /// <summary>Produces new array without item at specified <paramref name="index"/>. /// Will return <paramref name="source"/> array if index is out of bounds, or source is null/empty.</summary> /// <typeparam name="T">Type of array item.</typeparam> /// <param name="source">Input array.</param> <param name="index">Index if item to remove.</param> /// <returns>New array with removed item at index, or input source array if index is not in array.</returns> public static T[] RemoveAt<T>(this T[] source, int index) { if (source == null || source.Length == 0 || index < 0 || index >= source.Length) return source; if (index == 0 && source.Length == 1) return new T[0]; var result = new T[source.Length - 1]; if (index != 0) Array.Copy(source, 0, result, 0, index); if (index != result.Length) Array.Copy(source, index + 1, result, index, result.Length - index); return result; } /// <summary>Looks for item in array using equality comparison, and returns new array with found item remove, or original array if not item found.</summary> /// <typeparam name="T">Type of array item.</typeparam> /// <param name="source">Input array.</param> <param name="value">Value to find and remove.</param> /// <returns>New array with value removed or original array if value is not found.</returns> public static T[] Remove<T>(this T[] source, T value) { return source.RemoveAt(source.IndexOf(value)); } /// <summary>Returns singleton empty array of provided type.</summary> /// <typeparam name="T">Array item type.</typeparam> <returns>Empty array.</returns> public static T[] Empty<T>() { return EmptyArray<T>.Value; } private static class EmptyArray<T> { public static readonly T[] Value = new T[0]; } } /// <summary>Wrapper that provides optimistic-concurrency Swap operation implemented using <see cref="Ref.Swap{T}"/>.</summary> /// <typeparam name="T">Type of object to wrap.</typeparam> public sealed class Ref<T> where T : class { /// <summary>Gets the wrapped value.</summary> public T Value { get { return _value; } } /// <summary>Creates ref to object, optionally with initial value provided.</summary> /// <param name="initialValue">(optional) Initial value.</param> public Ref(T initialValue = default(T)) { _value = initialValue; } /// <summary>Exchanges currently hold object with <paramref name="getNewValue"/> - see <see cref="Ref.Swap{T}"/> for details.</summary> /// <param name="getNewValue">Delegate to produce new object value from current one passed as parameter.</param> /// <returns>Returns old object value the same way as <see cref="Interlocked.Exchange(ref int,int)"/></returns> /// <remarks>Important: <paramref name="getNewValue"/> May be called multiple times to retry update with value concurrently changed by other code.</remarks> public T Swap(Func<T, T> getNewValue) { return Ref.Swap(ref _value, getNewValue); } /// <summary>Just sets new value ignoring any intermingled changes.</summary> /// <param name="newValue"></param> <returns>old value</returns> public T Swap(T newValue) { return Interlocked.Exchange(ref _value, newValue); } /// <summary>Compares current Referred value with <paramref name="currentValue"/> and if equal replaces current with <paramref name="newValue"/></summary> /// <param name="currentValue"></param> <param name="newValue"></param> /// <returns>True if current value was replaced with new value, and false if current value is outdated (already changed by other party).</returns> /// <example><c>[!CDATA[ /// var value = SomeRef.Value; /// if (!SomeRef.TrySwapIfStillCurrent(value, Update(value)) /// SomeRef.Swap(v => Update(v)); // fallback to normal Swap with delegate allocation /// ]]</c></example> public bool TrySwapIfStillCurrent(T currentValue, T newValue) { return Interlocked.CompareExchange(ref _value, newValue, currentValue) == currentValue; } private T _value; } /// <summary>Provides optimistic-concurrency consistent <see cref="Swap{T}"/> operation.</summary> public static class Ref { /// <summary>Factory for <see cref="Ref{T}"/> with type of value inference.</summary> /// <typeparam name="T">Type of value to wrap.</typeparam> /// <param name="value">Initial value to wrap.</param> /// <returns>New ref.</returns> public static Ref<T> Of<T>(T value) where T : class { return new Ref<T>(value); } /// <summary>Creates new ref to the value of original ref.</summary> <typeparam name="T">Ref value type.</typeparam> /// <param name="original">Original ref.</param> <returns>New ref to original value.</returns> public static Ref<T> NewRef<T>(this Ref<T> original) where T : class { return Of(original.Value); } /// <summary>First, it evaluates new value using <paramref name="getNewValue"/> function. /// Second, it checks that original value is not changed. /// If it is changed it will retry first step, otherwise it assigns new value and returns original (the one used for <paramref name="getNewValue"/>).</summary> /// <typeparam name="T">Type of value to swap.</typeparam> /// <param name="value">Reference to change to new value</param> /// <param name="getNewValue">Delegate to get value from old one.</param> /// <returns>Old/original value. By analogy with <see cref="Interlocked.Exchange(ref int,int)"/>.</returns> /// <remarks>Important: <paramref name="getNewValue"/> May be called multiple times to retry update with value concurrently changed by other code.</remarks> public static T Swap<T>(ref T value, Func<T, T> getNewValue) where T : class { var retryCount = 0; while (true) { var oldValue = value; var newValue = getNewValue(oldValue); if (Interlocked.CompareExchange(ref value, newValue, oldValue) == oldValue) return oldValue; if (++retryCount > RETRY_COUNT_UNTIL_THROW) throw new InvalidOperationException(_errorRetryCountExceeded); } } private const int RETRY_COUNT_UNTIL_THROW = 50; private static readonly string _errorRetryCountExceeded = "Ref retried to Update for " + RETRY_COUNT_UNTIL_THROW + " times But there is always someone else intervened."; } /// <summary>Immutable Key-Value pair. It is reference type (could be check for null), /// which is different from System value type <see cref="KeyValuePair{TKey,TValue}"/>. /// In addition provides <see cref="Equals"/> and <see cref="GetHashCode"/> implementations.</summary> /// <typeparam name="K">Type of Key.</typeparam><typeparam name="V">Type of Value.</typeparam> public class KV<K, V> { /// <summary>Key.</summary> public readonly K Key; /// <summary>Value.</summary> public readonly V Value; /// <summary>Creates Key-Value object by providing key and value. Does Not check either one for null.</summary> /// <param name="key">key.</param><param name="value">value.</param> public KV(K key, V value) { Key = key; Value = value; } /// <summary>Creates nice string view.</summary><returns>String representation.</returns> public override string ToString() { var s = new StringBuilder('{'); if (Key != null) s.Append(Key); s.Append(','); if (Value != null) s.Append(Value); s.Append('}'); return s.ToString(); } /// <summary>Returns true if both key and value are equal to corresponding key-value of other object.</summary> /// <param name="obj">Object to check equality with.</param> <returns>True if equal.</returns> public override bool Equals(object obj) { var other = obj as KV<K, V>; return other != null && (ReferenceEquals(other.Key, Key) || Equals(other.Key, Key)) && (ReferenceEquals(other.Value, Value) || Equals(other.Value, Value)); } /// <summary>Combines key and value hash code. R# generated default implementation.</summary> /// <returns>Combined hash code for key-value.</returns> public override int GetHashCode() { unchecked { return ((object)Key == null ? 0 : Key.GetHashCode() * 397) ^ ((object)Value == null ? 0 : Value.GetHashCode()); } } } /// <summary>Helpers for <see cref="KV{K,V}"/>.</summary> public static class KV { /// <summary>Creates the key value pair.</summary> /// <typeparam name="K">Key type</typeparam> <typeparam name="V">Value type</typeparam> /// <param name="key">Key</param> <param name="value">Value</param> <returns>New pair.</returns> [MethodImpl((MethodImplOptions)256)] // AggressiveInlining public static KV<K, V> Of<K, V>(K key, V value) { return new KV<K, V>(key, value); } /// <summary>Creates the new pair with new key and old value.</summary> /// <typeparam name="K">Key type</typeparam> <typeparam name="V">Value type</typeparam> /// <param name="source">Source value</param> <param name="key">New key</param> <returns>New pair</returns> [MethodImpl((MethodImplOptions)256)] // AggressiveInlining public static KV<K, V> WithKey<K, V>(this KV<K, V> source, K key) { return new KV<K, V>(key, source.Value); } /// <summary>Creates the new pair with old key and new value.</summary> /// <typeparam name="K">Key type</typeparam> <typeparam name="V">Value type</typeparam> /// <param name="source">Source value</param> <param name="value">New value.</param> <returns>New pair</returns> [MethodImpl((MethodImplOptions)256)] // AggressiveInlining public static KV<K, V> WithValue<K, V>(this KV<K, V> source, V value) { return new KV<K, V>(source.Key, value); } } /// <summary>Delegate for changing value from old one to some new based on provided new value.</summary> /// <typeparam name="V">Type of values.</typeparam> /// <param name="oldValue">Existing value.</param> /// <param name="newValue">New value passed to Update.. method.</param> /// <returns>Changed value.</returns> public delegate V Update<V>(V oldValue, V newValue); // todo: V3: Rename to ImTree /// <summary>Simple immutable AVL tree with integer keys and object values.</summary> public sealed class ImTreeMapIntToObj { /// <summary>Empty tree to start with.</summary> public static readonly ImTreeMapIntToObj Empty = new ImTreeMapIntToObj(); /// <summary>Key.</summary> public readonly int Key; /// <summary>Value.</summary> public readonly object Value; /// <summary>Left sub-tree/branch, or empty.</summary> public readonly ImTreeMapIntToObj Left; /// <summary>Right sub-tree/branch, or empty.</summary> public readonly ImTreeMapIntToObj Right; /// <summary>Height of longest sub-tree/branch plus 1. It is 0 for empty tree, and 1 for single node tree.</summary> public readonly int Height; /// <summary>Returns true is tree is empty.</summary> public bool IsEmpty { get { return Height == 0; } } /// <summary>Returns new tree with added or updated value for specified key.</summary> /// <param name="key"></param> <param name="value"></param> /// <returns>New tree.</returns> public ImTreeMapIntToObj AddOrUpdate(int key, object value) { return AddOrUpdate(key, value, false, null); } /// <summary>Delegate to calculate new value from and old and a new value.</summary> /// <param name="oldValue">Old</param> <param name="newValue">New</param> <returns>Calculated result.</returns> public delegate object UpdateValue(object oldValue, object newValue); /// <summary>Returns new tree with added or updated value for specified key.</summary> /// <param name="key">Key</param> <param name="value">Value</param> /// <param name="updateValue">(optional) Delegate to calculate new value from and old and a new value.</param> /// <returns>New tree.</returns> public ImTreeMapIntToObj AddOrUpdate(int key, object value, UpdateValue updateValue) { return AddOrUpdate(key, value, false, updateValue); } /// <summary>Returns new tree with updated value for the key, Or the same tree if key was not found.</summary> /// <param name="key"></param> <param name="value"></param> /// <returns>New tree if key is found, or the same tree otherwise.</returns> public ImTreeMapIntToObj Update(int key, object value) { return AddOrUpdate(key, value, true, null); } /// <summary>Get value for found key or null otherwise.</summary> /// <param name="key"></param> <returns>Found value or null.</returns> public object GetValueOrDefault(int key) { var tree = this; while (tree.Height != 0 && tree.Key != key) tree = key < tree.Key ? tree.Left : tree.Right; return tree.Height != 0 ? tree.Value : null; } /// <summary>Returns all sub-trees enumerated from left to right.</summary> /// <returns>Enumerated sub-trees or empty if tree is empty.</returns> public IEnumerable<ImTreeMapIntToObj> Enumerate() { if (Height == 0) yield break; var parents = new ImTreeMapIntToObj[Height]; var tree = this; var parentCount = -1; while (tree.Height != 0 || parentCount != -1) { if (tree.Height != 0) { parents[++parentCount] = tree; tree = tree.Left; } else { tree = parents[parentCount--]; yield return tree; tree = tree.Right; } } } #region Implementation private ImTreeMapIntToObj() { } private ImTreeMapIntToObj(int key, object value, ImTreeMapIntToObj left, ImTreeMapIntToObj right) { Key = key; Value = value; Left = left; Right = right; Height = 1 + (left.Height > right.Height ? left.Height : right.Height); } private ImTreeMapIntToObj AddOrUpdate(int key, object value, bool updateOnly, UpdateValue update) { return Height == 0 ? // tree is empty (updateOnly ? this : new ImTreeMapIntToObj(key, value, Empty, Empty)) : (key == Key ? // actual update new ImTreeMapIntToObj(key, update == null ? value : update(Value, value), Left, Right) : (key < Key // try update on left or right sub-tree ? With(Left.AddOrUpdate(key, value, updateOnly, update), Right) : With(Left, Right.AddOrUpdate(key, value, updateOnly, update))).KeepBalanced()); } private ImTreeMapIntToObj KeepBalanced() { var delta = Left.Height - Right.Height; return delta >= 2 ? With(Left.Right.Height - Left.Left.Height == 1 ? Left.RotateLeft() : Left, Right).RotateRight() : (delta <= -2 ? With(Left, Right.Left.Height - Right.Right.Height == 1 ? Right.RotateRight() : Right).RotateLeft() : this); } private ImTreeMapIntToObj RotateRight() { return Left.With(Left.Left, With(Left.Right, Right)); } private ImTreeMapIntToObj RotateLeft() { return Right.With(With(Left, Right.Left), Right.Right); } private ImTreeMapIntToObj With(ImTreeMapIntToObj left, ImTreeMapIntToObj right) { return left == Left && right == Right ? this : new ImTreeMapIntToObj(Key, Value, left, right); } #endregion } // todo: V3: Rename to ImHashTree /// <summary>Immutable http://en.wikipedia.org/wiki/AVL_tree where actual node key is hash code of <typeparamref name="K"/>.</summary> public sealed class ImTreeMap<K, V> { /// <summary>Empty tree to start with.</summary> public static readonly ImTreeMap<K, V> Empty = new ImTreeMap<K, V>(); /// <summary>Key of type K that should support <see cref="object.Equals(object)"/> and <see cref="object.GetHashCode"/>.</summary> public readonly K Key; /// <summary>Value of any type V.</summary> public readonly V Value; /// <summary>Calculated key hash.</summary> public readonly int Hash; /// <summary>In case of <see cref="Hash"/> conflicts for different keys contains conflicted keys with their values.</summary> public readonly KV<K, V>[] Conflicts; /// <summary>Left sub-tree/branch, or empty.</summary> public readonly ImTreeMap<K, V> Left; /// <summary>Right sub-tree/branch, or empty.</summary> public readonly ImTreeMap<K, V> Right; /// <summary>Height of longest sub-tree/branch plus 1. It is 0 for empty tree, and 1 for single node tree.</summary> public readonly int Height; /// <summary>Returns true if tree is empty.</summary> public bool IsEmpty { get { return Height == 0; } } /// <summary>Returns new tree with added key-value. If value with the same key is exist, then /// if <paramref name="update"/> is not specified: then existing value will be replaced by <paramref name="value"/>; /// if <paramref name="update"/> is specified: then update delegate will decide what value to keep.</summary> /// <param name="key">Key to add.</param><param name="value">Value to add.</param> /// <param name="update">(optional) Delegate to decide what value to keep: old or new one.</param> /// <returns>New tree with added or updated key-value.</returns> public ImTreeMap<K, V> AddOrUpdate(K key, V value, Update<V> update = null) { return AddOrUpdate(key.GetHashCode(), key, value, update, updateOnly: false); } /// <summary>Looks for <paramref name="key"/> and replaces its value with new <paramref name="value"/>, or /// runs custom update handler (<paramref name="update"/>) with old and new value to get the updated result.</summary> /// <param name="key">Key to look for.</param> /// <param name="value">New value to replace key value with.</param> /// <param name="update">(optional) Delegate for custom update logic, it gets old and new <paramref name="value"/> /// as inputs and should return updated value as output.</param> /// <returns>New tree with updated value or the SAME tree if no key found.</returns> public ImTreeMap<K, V> Update(K key, V value, Update<V> update = null) { return AddOrUpdate(key.GetHashCode(), key, value, update, updateOnly: true); } /// <summary>Looks for key in a tree and returns the key value if found, or <paramref name="defaultValue"/> otherwise.</summary> /// <param name="key">Key to look for.</param> <param name="defaultValue">(optional) Value to return if key is not found.</param> /// <returns>Found value or <paramref name="defaultValue"/>.</returns> public V GetValueOrDefault(K key, V defaultValue = default(V)) { var t = this; var hash = key.GetHashCode(); while (t.Height != 0 && t.Hash != hash) t = hash < t.Hash ? t.Left : t.Right; return t.Height != 0 && (ReferenceEquals(key, t.Key) || key.Equals(t.Key)) ? t.Value : t.GetConflictedValueOrDefault(key, defaultValue); } /// <summary>Depth-first in-order traversal as described in http://en.wikipedia.org/wiki/Tree_traversal /// The only difference is using fixed size array instead of stack for speed-up (~20% faster than stack).</summary> /// <returns>Sequence of enumerated key value pairs.</returns> public IEnumerable<KV<K, V>> Enumerate() { if (Height == 0) yield break; var parents = new ImTreeMap<K, V>[Height]; var tree = this; var parentCount = -1; while (tree.Height != 0 || parentCount != -1) { if (tree.Height != 0) { parents[++parentCount] = tree; tree = tree.Left; } else { tree = parents[parentCount--]; yield return new KV<K, V>(tree.Key, tree.Value); if (tree.Conflicts != null) for (var i = 0; i < tree.Conflicts.Length; i++) yield return tree.Conflicts[i]; tree = tree.Right; } } } #region Implementation private ImTreeMap() { } private ImTreeMap(int hash, K key, V value, KV<K, V>[] conficts, ImTreeMap<K, V> left, ImTreeMap<K, V> right) { Hash = hash; Key = key; Value = value; Conflicts = conficts; Left = left; Right = right; Height = 1 + (left.Height > right.Height ? left.Height : right.Height); } private ImTreeMap<K, V> AddOrUpdate(int hash, K key, V value, Update<V> update, bool updateOnly) { return Height == 0 ? (updateOnly ? this : new ImTreeMap<K, V>(hash, key, value, null, Empty, Empty)) : (hash == Hash ? UpdateValueAndResolveConflicts(key, value, update, updateOnly) : (hash < Hash ? With(Left.AddOrUpdate(hash, key, value, update, updateOnly), Right) : With(Left, Right.AddOrUpdate(hash, key, value, update, updateOnly))).KeepBalanced()); } private ImTreeMap<K, V> UpdateValueAndResolveConflicts(K key, V value, Update<V> update, bool updateOnly) { if (ReferenceEquals(Key, key) || Key.Equals(key)) return new ImTreeMap<K, V>(Hash, key, update == null ? value : update(Value, value), Conflicts, Left, Right); if (Conflicts == null) // add only if updateOnly is false. return updateOnly ? this : new ImTreeMap<K, V>(Hash, Key, Value, new[] { new KV<K, V>(key, value) }, Left, Right); var found = Conflicts.Length - 1; while (found >= 0 && !Equals(Conflicts[found].Key, Key)) --found; if (found == -1) { if (updateOnly) return this; var newConflicts = new KV<K, V>[Conflicts.Length + 1]; Array.Copy(Conflicts, 0, newConflicts, 0, Conflicts.Length); newConflicts[Conflicts.Length] = new KV<K, V>(key, value); return new ImTreeMap<K, V>(Hash, Key, Value, newConflicts, Left, Right); } var conflicts = new KV<K, V>[Conflicts.Length]; Array.Copy(Conflicts, 0, conflicts, 0, Conflicts.Length); conflicts[found] = new KV<K, V>(key, update == null ? value : update(Conflicts[found].Value, value)); return new ImTreeMap<K, V>(Hash, Key, Value, conflicts, Left, Right); } private V GetConflictedValueOrDefault(K key, V defaultValue) { if (Conflicts != null) for (var i = 0; i < Conflicts.Length; i++) if (Equals(Conflicts[i].Key, key)) return Conflicts[i].Value; return defaultValue; } private ImTreeMap<K, V> KeepBalanced() { var delta = Left.Height - Right.Height; return delta >= 2 ? With(Left.Right.Height - Left.Left.Height == 1 ? Left.RotateLeft() : Left, Right).RotateRight() : (delta <= -2 ? With(Left, Right.Left.Height - Right.Right.Height == 1 ? Right.RotateRight() : Right).RotateLeft() : this); } private ImTreeMap<K, V> RotateRight() { return Left.With(Left.Left, With(Left.Right, Right)); } private ImTreeMap<K, V> RotateLeft() { return Right.With(With(Left, Right.Left), Right.Right); } private ImTreeMap<K, V> With(ImTreeMap<K, V> left, ImTreeMap<K, V> right) { return left == Left && right == Right ? this : new ImTreeMap<K, V>(Hash, Key, Value, Conflicts, left, right); } #endregion } }
47.528467
167
0.589612
[ "MIT" ]
MovGP0/Calculator
Calculator/DryIoc/ImTools.cs
32,557
C#
using LiteDB; namespace merlin.classes { public class ApiKey { public string Service { get; set; } public string Key { get; set; } [BsonId] public int Id { get; set; } } }
18.083333
43
0.548387
[ "MIT" ]
jakedacatman/merlin
src/classes/misc/apikey.cs
219
C#
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using System; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using AdventureWorks.Common; using Windows.Media.SpeechRecognition; using System.Linq; using Windows.Storage; using System.Collections.Generic; namespace AdventureWorks { /// <summary> /// Provides application-specific behavior to supplement the default Application class. Contains initialization of the /// NavigationService, and handles Activation via methods other than normal user interaction (For example, voice commands/Cortana /// or URI invoking) /// </summary> sealed partial class App : Application { /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += OnSuspending; } /// <summary> /// Navigation service, provides a decoupled way to trigger the UI Frame /// to transition between views. /// </summary> public static NavigationService NavigationService { get; private set; } private RootFrameNavigationHelper rootFrameNavigationHelper; /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to respond to voice commands, or /// URI invoked. This also installs the voice commands into cortana. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected async override void OnLaunched(LaunchActivatedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); App.NavigationService = new NavigationService(rootFrame); // Use the RootFrameNavigationHelper to respond to keyboard and mouse shortcuts. this.rootFrameNavigationHelper = new RootFrameNavigationHelper(rootFrame); rootFrame.NavigationFailed += OnNavigationFailed; // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // Determine if we're being activated normally, or with arguments from Cortana. if (string.IsNullOrEmpty(e.Arguments)) { // Launching normally. rootFrame.Navigate(typeof(View.TripListView), ""); } else { // Launching with arguments. We assume, for now, that this is likely // to be in the form of "destination=<location>" from activation via Cortana. rootFrame.Navigate(typeof(View.TripDetails), e.Arguments); } } // Ensure the current window is active Window.Current.Activate(); try { // Install the main VCD. Since there's no simple way to test that the VCD has been imported, or that it's your most recent // version, it's not unreasonable to do this upon app load. StorageFile vcdStorageFile = await Package.Current.InstalledLocation.GetFileAsync(@"AdventureWorksCommands.xml"); await Windows.ApplicationModel.VoiceCommands.VoiceCommandDefinitionManager.InstallCommandDefinitionsFromStorageFileAsync(vcdStorageFile); // Update phrase list. ViewModel.ViewModelLocator locator = App.Current.Resources["ViewModelLocator"] as ViewModel.ViewModelLocator; if(locator != null) { await locator.TripViewModel.UpdateDestinationPhraseList(); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Installing Voice Commands Failed: " + ex.ToString()); } } /// <summary> /// Invoked when Navigation to a certain page fails /// </summary> /// <param name="sender">The Frame which failed navigation</param> /// <param name="e">Details about the navigation failure</param> void OnNavigationFailed(object sender, NavigationFailedEventArgs e) { throw new Exception("Failed to load Page " + e.SourcePageType.FullName); } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); deferral.Complete(); } /// <summary> /// OnActivated is the entry point for an application when it is launched via /// means other normal user interaction. This includes Voice Commands, URI activation, /// being used as a share target from another app, etc. Here, we're going to handle the /// Voice Command activation from Cortana. /// /// Note: Be aware that an older VCD could still be in place for your application if you /// modify it and update your app via the store. You should be aware that you could get /// activations that include commands in older versions of your VCD, and you should try /// to handle them gracefully. /// </summary> /// <param name="args">Details about the activation method, including the activation /// phrase (for voice commands) and the semantic interpretation, parameters, etc.</param> protected override void OnActivated(IActivatedEventArgs args) { base.OnActivated(args); Type navigationToPageType; ViewModel.TripVoiceCommand? navigationCommand = null; // If the app was launched via a Voice Command, this corresponds to the "show trip to <location>" command. // Protocol activation occurs when a tile is clicked within Cortana (via the background task) if (args.Kind == ActivationKind.VoiceCommand) { // The arguments can represent many different activation types. Cast it so we can get the // parameters we care about out. var commandArgs = args as VoiceCommandActivatedEventArgs; Windows.Media.SpeechRecognition.SpeechRecognitionResult speechRecognitionResult = commandArgs.Result; // Get the name of the voice command and the text spoken. See AdventureWorksCommands.xml for // the <Command> tags this can be filled with. string voiceCommandName = speechRecognitionResult.RulePath[0]; string textSpoken = speechRecognitionResult.Text; // The commandMode is either "voice" or "text", and it indictes how the voice command // was entered by the user. // Apps should respect "text" mode by providing feedback in silent form. string commandMode = this.SemanticInterpretation("commandMode", speechRecognitionResult); switch (voiceCommandName) { case "showTripToDestination": // Access the value of the {destination} phrase in the voice command string destination = this.SemanticInterpretation("destination", speechRecognitionResult); // Create a navigation command object to pass to the page. Any object can be passed in, // here we're using a simple struct. navigationCommand = new ViewModel.TripVoiceCommand( voiceCommandName, commandMode, textSpoken, destination); // Set the page to navigate to for this voice command. navigationToPageType = typeof(View.TripDetails); break; default: // If we can't determine what page to launch, go to the default entry point. navigationToPageType = typeof(View.TripListView); break; } } else if (args.Kind == ActivationKind.Protocol) { // Extract the launch context. In this case, we're just using the destination from the phrase set (passed // along in the background task inside Cortana), which makes no attempt to be unique. A unique id or // identifier is ideal for more complex scenarios. We let the destination page check if the // destination trip still exists, and navigate back to the trip list if it doesn't. var commandArgs = args as ProtocolActivatedEventArgs; Windows.Foundation.WwwFormUrlDecoder decoder = new Windows.Foundation.WwwFormUrlDecoder(commandArgs.Uri.Query); var destination = decoder.GetFirstValueByName("LaunchContext"); navigationCommand = new ViewModel.TripVoiceCommand( "protocolLaunch", "text", "destination", destination); navigationToPageType = typeof(View.TripDetails); } else { // If we were launched via any other mechanism, fall back to the main page view. // Otherwise, we'll hang at a splash screen. navigationToPageType = typeof(View.TripListView); } // Re"peat the same basic initialization as OnLaunched() above, taking into account whether // or not the app is already active. Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); App.NavigationService = new NavigationService(rootFrame); rootFrame.NavigationFailed += OnNavigationFailed; // Place the frame in the current Window Window.Current.Content = rootFrame; } // Since we're expecting to always show a details page, navigate even if // a content frame is in place (unlike OnLaunched). // Navigate to either the main trip list page, or if a valid voice command // was provided, to the details page for that trip. rootFrame.Navigate(navigationToPageType, navigationCommand); // Ensure the current window is active Window.Current.Activate(); } /// <summary> /// Returns the semantic interpretation of a speech result. Returns null if there is no interpretation for /// that key. /// </summary> /// <param name="interpretationKey">The interpretation key.</param> /// <param name="speechRecognitionResult">The result to get an interpretation from.</param> /// <returns></returns> private string SemanticInterpretation(string interpretationKey, SpeechRecognitionResult speechRecognitionResult) { return speechRecognitionResult.SemanticInterpretation.Properties[interpretationKey].FirstOrDefault(); } } }
49.325926
154
0.589653
[ "MIT" ]
544146/Windows-universal-samples
Samples/CortanaVoiceCommand/cs/AdventureWorks/App.xaml.cs
13,051
C#
using System; using System.Collections.Generic; public class JournalsConversation : List<JournalsConversationContent> { }
17.714286
69
0.822581
[ "Apache-2.0" ]
Shadowrabbit/BigBiaDecompilation
Source/Assembly-CSharp/JournalsConversation.cs
126
C#
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Blog.Repository { public class DbInitializer : CreateDatabaseIfNotExists<EntityContext> { } }
17.4
73
0.770115
[ "MIT" ]
Balabili/MyBlog
Blog.Repository/DbInitializer.cs
263
C#
/* * Copyright 2018 JDCLOUD.COM * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http:#www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Live-Video * 直播管理API * * OpenAPI spec version: v1 * Contact: * * NOTE: This class is auto generated by the jdcloud code generator program. */ using System; using System.Collections.Generic; using System.Text; using JDCloudSDK.Core.Service; namespace JDCloudSDK.Live.Apis { /// <summary> /// 删除域名级别水印模板配置 /// /// - 删除域名级别水印模板配置,重新推流后生效 /// /// /// </summary> public class DeleteLiveStreamDomainWatermarkResult : JdcloudResult { } }
25.511628
76
0.689152
[ "Apache-2.0" ]
jdcloud-api/jdcloud-sdk-net
sdk/src/Service/Live/Apis/DeleteLiveStreamDomainWatermarkResult.cs
1,167
C#
//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.42000 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ namespace App.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.8.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
35.888889
151
0.560372
[ "Unlicense" ]
XavierMoon/DFAssist_CN
App/Properties/Settings.Designer.cs
1,077
C#
using System; using System.Diagnostics; using System.Runtime.InteropServices; using GitSync.git; using LibGit2Sharp; using LibGit2Sharp.Handlers; namespace GitSync { static class CommandProcessor { public static StageResponse GitAddAll(Repository repository) { try { Commands.Stage(repository, "*"); return new StageResponse(true); } catch (Exception e) { return new StageResponse(false, e); } } public static StageResponse GitCommit(Repository repository, GitUser user, string message) { try { var author = new Signature(user.UserName, user.Email, DateTime.Now); repository.Commit(message, author, author); return new StageResponse(true); } catch (Exception e) { return new StageResponse(false, e); } } public static StageResponse GitPull(Repository repository, GitUser user) { try { Commands.Pull ( repository, new Signature(new Identity(user.UserName, user.Email), DateTimeOffset.Now), new PullOptions() { FetchOptions = new FetchOptions() { CredentialsProvider = new CredentialsHandler((url, usernameFromUrl, types) => new UsernamePasswordCredentials() { Username = user.UserName, Password = user.Password } ) } } ); return new StageResponse(true); } catch (Exception e) { return new StageResponse(false, e); } } public static StageResponse GitPush(Repository repository, GitUser user) { try { repository.Network.Push ( repository.Branches["master"], new PushOptions() { CredentialsProvider = new CredentialsHandler((url, usernameFromUrl, types) => new UsernamePasswordCredentials() { Username = user.UserName, Password = user.Password } ) } ); return new StageResponse(true); } catch (Exception e) { return new StageResponse(false, e); } } } }
31.1875
105
0.42485
[ "MIT" ]
RafaelSantosBraz/AutoSyncRepositories-Git
GitSync/GitSync/git/CommandProcessor.cs
2,996
C#
/* * Morgan Stanley makes this available to you under the Apache License, * Version 2.0 (the "License"). You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0. * * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. Unless required by applicable law or agreed * to in writing, software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions * and limitations under the License. */ using DotNetPlease.Utilities; using System; namespace DotNetPlease.Services.Reporting.Abstractions { public class NullReporter : IReporter { private NullReporter() { } public static readonly NullReporter Singleton = new NullReporter(); public IDisposable BeginScope(string scope) { return new NullDisposable(); } public void Message(string message, MessageType type = MessageType.Information) { } } }
31.027027
87
0.700348
[ "Apache-2.0" ]
BalassaMarton/dotnet-please
DotNetPlease/Services/Reporting/Abstractions/NullReporter.cs
1,150
C#
using System; namespace Passion.Outbox.Publisher.Settings { public class ProcessSettings : IProcessSettings { public string ExecutionLimit { get; set; } public string ExecutionTryCount { get; set; } public int GetExecutionLimit() { return Convert.ToInt32(this.ExecutionLimit); } } }
23.333333
56
0.637143
[ "MIT" ]
oktydag/passion
src/Passion.Outbox.Publisher/Settings/ProcessSettings.cs
352
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; using System.Reflection; using System.Threading.Tasks; using System.Windows.Forms; namespace PeerReview { partial class AboutBox : Form { public AboutBox() { InitializeComponent(); this.Text = String.Format("About {0}", AssemblyTitle); this.labelProductName.Text = AssemblyProduct; this.labelVersion.Text = String.Format("Version {0}", AssemblyVersion); this.labelCopyright.Text = AssemblyCopyright; this.labelCompanyName.Text = AssemblyCompany; this.textBoxDescription.Text = AssemblyDescription; } #region Assembly Attribute Accessors public string AssemblyTitle { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false); if (attributes.Length > 0) { AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0]; if (titleAttribute.Title != "") { return titleAttribute.Title; } } return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase); } } public string AssemblyVersion { get { return Assembly.GetExecutingAssembly().GetName().Version.ToString(); } } public string AssemblyDescription { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false); if (attributes.Length == 0) { return ""; } return ((AssemblyDescriptionAttribute)attributes[0]).Description; } } public string AssemblyProduct { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false); if (attributes.Length == 0) { return ""; } return ((AssemblyProductAttribute)attributes[0]).Product; } } public string AssemblyCopyright { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false); if (attributes.Length == 0) { return ""; } return ((AssemblyCopyrightAttribute)attributes[0]).Copyright; } } public string AssemblyCompany { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false); if (attributes.Length == 0) { return ""; } return ((AssemblyCompanyAttribute)attributes[0]).Company; } } #endregion } }
24.018868
123
0.704242
[ "MIT" ]
cvelten/RadOnc_PeerReview
PeerReviewList/AboutBox.cs
2,548
C#
// // - TokeniserState.BogusCommentState.cs - // // Copyright 2012 Carbonfrost Systems, Inc. (http://carbonfrost.com) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // The MIT License // // Copyright (c) 2009, 2010, 2011, 2012 Jonathan Hedley <jonathan@hedley.net> // // 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; namespace Carbonfrost.Commons.Html.Parser { partial class TokeniserState { class BogusCommentState : TokeniserState { public override void Read(Tokeniser t, CharacterReader r) { // TODO: handle bogus comment starting from eof. when does that trigger? // rewind to capture char that lead us here r.Unconsume(); Token.Comment comment = new Token.Comment(); comment.data.Append(r.ConsumeTo('>')); comment.IsBogus = true; // TODO: replace nullChar with replaceChar t.Emit(comment); t.AdvanceTransition(Data); } } } }
38.567164
88
0.696981
[ "Apache-2.0" ]
Carbonfrost/f-html
dotnet/src/Carbonfrost.Commons.Html/Src/Carbonfrost/Commons/Html/Parser/TokeniserState.BogusCommentState.cs
2,584
C#
// Copyright © 2010-2017 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; namespace CefSharp { /// <summary> /// Event arguments to the FrameLoadEnd event handler set up in IWebBrowser. /// </summary> public class FrameLoadEndEventArgs : EventArgs { /// <summary> /// Creates a new FrameLoadEnd event args /// </summary> /// <param name="browser">browser</param> /// <param name="frame">frame</param> /// <param name="httpStatusCode">http statusCode</param> public FrameLoadEndEventArgs(IBrowser browser, IFrame frame, int httpStatusCode) { Browser = browser; Frame = frame; if (frame.IsValid) { Url = frame.Url; } HttpStatusCode = httpStatusCode; } /// <summary> /// The browser that contains the frame that finished loading. /// </summary> public IBrowser Browser { get; private set; } /// <summary> /// The frame that finished loading. /// </summary> public IFrame Frame { get; private set; } /// <summary> /// The URL that was loaded. /// </summary> public string Url { get; private set; } /// <summary> /// Http Status Code /// </summary> public int HttpStatusCode { get; set; } } }
29.365385
100
0.554028
[ "BSD-3-Clause" ]
intuiface/CefSharp
CefSharp/Event/FrameLoadEndEventArgs.cs
1,530
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Configuration; using System.Data.SqlClient; namespace DatasetsAndLinq { public partial class StudentsByCourseForm : Form { private SqlConnection sqlConn = new SqlConnection(Properties.Settings.Default.connection); public StudentsByCourseForm() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { SqlCommand command = new SqlCommand("Select distinct major from student", sqlConn); sqlConn.Open(); SqlDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { cmb_type.Items.Add(reader.GetString(0)); } } command.Dispose(); reader.Close(); sqlConn.Close(); } private void cmb_type_SelectedValueChanged(object sender, EventArgs e) { lbx_students.Items.Clear(); string majorString = cmb_type.Text.Trim(); string sql = "Select studentid, stuname from student where major = '" + majorString + "'"; SqlCommand command = new SqlCommand(sql, sqlConn); sqlConn.Open(); SqlDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { lbx_students.Items.Add(reader.GetInt32(0) + " - " + reader.GetString(1)); } } command.Dispose(); reader.Close(); sqlConn.Close(); } private void lbx_students_SelectedValueChanged(object sender, EventArgs e) { string[] values = lbx_students.SelectedItem.ToString().Split(new[] { " - " }, StringSplitOptions.None); DisplayStudentMarksForm studentMarksForm = new DisplayStudentMarksForm(Convert.ToInt32(values[0]), values[1]); this.Hide(); studentMarksForm.ShowDialog(); this.Show(); } } }
32.097222
122
0.577672
[ "MIT" ]
Iqrahaq/CSharp
kf7014/week9/DatasetsAndLinq/StudentsByCourseForm.cs
2,313
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class GameManager : MonoBehaviour { public GameObject[] spawners; private int level = 0; private int currentScene = 0; private int zombieCount = 0; private int zombieLimit = 10; public GameObject player; public GameObject weapon; public GameObject hudCanvas; private Scene scene; void Start() { PrepareSpawners(); } void Awake() { SceneManager.sceneLoaded -= OnSceneLoaded; SceneManager.sceneLoaded += OnSceneLoaded; DontDestroyOnLoad(player.gameObject); DontDestroyOnLoad(weapon.gameObject); DontDestroyOnLoad(hudCanvas.gameObject); DontDestroyOnLoad(gameObject); scene = SceneManager.GetActiveScene(); } void OnSceneLoaded(Scene scene, LoadSceneMode mode) { if(!string.Equals(scene.path, this.scene.path)){ level++; PrepareSpawners(); } } void PrepareSpawners() { spawners = GameObject.FindGameObjectsWithTag("Spawner"); if(spawners.Length > 0) { int rnd = Random.Range(0, spawners.Length); spawners[rnd].GetComponent<SpawnerScript>().SetGateway(true); // Weapon Upgrade testing if(Random.Range(0, 5) == 3) { int randTemp = Random.Range(0, spawners.Length); spawners[randTemp].GetComponent<SpawnerScript>().SetWeapon(true); } foreach (GameObject spawner in spawners) { spawner.GetComponent<SpawnerScript>().SetHealth(level + Random.Range(3, 6)); } } } public void SetZombieCount(int amount) { zombieCount += amount; } public int GetZombieCount() { return zombieCount; } public int GetZombieLimit() { return zombieLimit; } public void LoadLevel() { zombieCount = 0; if (SceneManager.GetActiveScene().buildIndex != 7) { currentScene = 1; } else { currentScene = -1; } SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + currentScene); } public int GetLevel() { return level; } }
24.326531
92
0.588926
[ "Unlicense" ]
rudranshg/Mystic-Dungeon
Assets/Scripts/GameManager.cs
2,386
C#
namespace Replikit.Abstractions.Common.Models; public sealed record AdapterIdentifier(string Type, Identifier BotId) { public static implicit operator string(AdapterIdentifier identifier) => identifier.ToString(); public override string ToString() => $"{Type}:{BotId}"; }
31.444444
98
0.766784
[ "MIT" ]
Replikit/Replikit
src/core/Replikit.Abstractions/src/Common/Models/AdapterIdentifier.cs
285
C#
/* The MIT License (MIT) Copyright (c) 2015 Abdelkarim Sellamna 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.Windows; using System.Windows.Controls; namespace DropShadowChrome.Lib.Controls.Primitives { /// <summary> /// A custom panel that will arrange all of its children in the same /// space. /// </summary> public class SingleCellGrid : Panel { protected override Size MeasureOverride(Size availableSize) { var desiredWidth = 0.0; var desiredHeight = 0.0; foreach (UIElement child in this.InternalChildren) { child.Measure(availableSize); var desiredSize = child.DesiredSize; if (desiredSize.Width > desiredWidth) { desiredWidth = desiredSize.Width; } if (desiredSize.Height > desiredHeight) { desiredHeight = desiredSize.Height; } } return new Size(desiredWidth, desiredHeight); } protected override Size ArrangeOverride(Size finalSize) { var rect = new Rect(finalSize); foreach (UIElement child in this.InternalChildren) { child.Arrange(rect); } return finalSize; } } }
33.871429
78
0.655841
[ "MIT" ]
abdelkarim/DropShadowChrome
DropShadowChrome/DropShadowChrome.Lib/Controls/Primitives/SingleCellGrid.cs
2,373
C#
using System; using System.Data; using System.Configuration; using System.Threading; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Collections.Generic; using Umbraco.Core; using Umbraco.Core.Logging; using Umbraco.Web; using umbraco.interfaces; using umbraco.BusinessLogic.Utils; using umbraco.BusinessLogic; using umbraco.BasePages; namespace umbraco.cms.presentation.Trees { /// <summary> /// A collection of TreeDefinitions found in any loaded assembly. /// </summary> public class TreeDefinitionCollection : List<TreeDefinition> { //create singleton private static readonly TreeDefinitionCollection instance = new TreeDefinitionCollection(); private static readonly object Locker = new object(); private static volatile bool _ensureTrees = false; public static TreeDefinitionCollection Instance { get { instance.EnsureTreesRegistered(); return instance; } } /// <summary> /// Find the TreeDefinition object based on the ITree /// </summary> /// <param name="tree"></param> /// <returns></returns> public TreeDefinition FindTree(ITree tree) { EnsureTreesRegistered(); var foundTree = this.Find( t => t.TreeType == tree.GetType() ); if (foundTree != null) return foundTree; return null; } /// <summary> /// Finds the TreeDefinition with the generic type specified /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public TreeDefinition FindTree<T>() where T : ITree { EnsureTreesRegistered(); var foundTree = this.Find( delegate(TreeDefinition t) { // zb-00002 #29929 : use IsAssignableFrom instead of Equal, otherwise you can't override build-in // trees because for ex. PermissionEditor.aspx.cs OnInit calls FindTree<loadContent>() return typeof(T).IsAssignableFrom(t.TreeType); } ); if (foundTree != null) return foundTree; return null; } /// <summary> /// Return the TreeDefinition object based on the tree alias and application it belongs to /// </summary> /// <param name="alias"></param> /// <returns></returns> public TreeDefinition FindTree(string alias) { EnsureTreesRegistered(); var foundTree = this.Find( t => t.Tree.Alias.ToLower() == alias.ToLower() ); if (foundTree != null) return foundTree; return null; } /// <summary> /// Return a list of TreeDefinition's with the appAlias specified /// </summary> /// <param name="appAlias"></param> /// <returns></returns> public List<TreeDefinition> FindTrees(string appAlias) { EnsureTreesRegistered(); return this.FindAll( tree => (tree.App != null && tree.App.alias.ToLower() == appAlias.ToLower()) ); } /// <summary> /// Return a list of TreeDefinition's with the appAlias specified /// </summary> /// <param name="appAlias"></param> /// <returns></returns> public List<TreeDefinition> FindActiveTrees(string appAlias) { EnsureTreesRegistered(); return this.FindAll( tree => (tree.App != null && tree.App.alias.ToLower() == appAlias.ToLower() && tree.Tree.Initialize) ); } public void ReRegisterTrees() { //clears the trees/flag so that they are lazily refreshed on next access lock (Locker) { this.Clear(); _ensureTrees = false; } } /// <summary> /// Finds all instances of ITree in loaded assemblies, then finds their associated ApplicationTree and Application objects /// and stores them together in a TreeDefinition class and adds the definition to our list. /// This will also store an instance of each tree object in the TreeDefinition class which should be /// used when referencing all tree classes. /// </summary> private void EnsureTreesRegistered() { if (_ensureTrees == false) { lock (Locker) { if (_ensureTrees == false) { var foundITrees = PluginManager.Current.ResolveTrees(); var objTrees = ApplicationTree.getAll(); var appTrees = new List<ApplicationTree>(); appTrees.AddRange(objTrees); var apps = Application.getAll(); foreach (var type in foundITrees) { //find the Application tree's who's combination of assembly name and tree type is equal to //the Type that was found's full name. //Since a tree can exist in multiple applications we'll need to register them all. //The logic of this has changed in 6.0: http://issues.umbraco.org/issue/U4-1360 // we will support the old legacy way but the normal way is to match on assembly qualified names var appTreesForType = appTrees.FindAll( tree => { //match the type on assembly qualified name if the assembly attribute is empty or if the // tree type contains a comma (meaning it is assembly qualified) if (tree.AssemblyName.IsNullOrWhiteSpace() || tree.Type.Contains(",")) { return tree.GetRuntimeType() == type; } //otherwise match using legacy match rules return (string.Format("{0}.{1}", tree.AssemblyName, tree.Type).InvariantEquals(type.FullName)); } ); foreach (var appTree in appTreesForType) { //find the Application object whos name is the same as our appTree ApplicationAlias var app = apps.Find( a => (a.alias == appTree.ApplicationAlias) ); var def = new TreeDefinition(type, appTree, app); this.Add(def); } } //sort our trees with the sort order definition this.Sort((t1, t2) => t1.Tree.SortOrder.CompareTo(t2.Tree.SortOrder)); _ensureTrees = true; } } } } } }
36.561321
132
0.498774
[ "MIT" ]
Hendy/Umbraco-CMS
src/Umbraco.Web/umbraco.presentation/umbraco/Trees/TreeDefinitionCollection.cs
7,751
C#
// Copyright (c) MOSA Project. Licensed under the New BSD License. using Mosa.Compiler.Common; using Mosa.Compiler.Framework; using Mosa.Compiler.Linker; using Mosa.Compiler.Linker.Elf32; using Mosa.Compiler.Linker.PE; using Mosa.Compiler.Trace.BuiltIn; using Mosa.Utility.Aot; using NDesk.Options; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Mosa.Tool.Compiler { /// <summary> /// Class containing the Compiler. /// </summary> public class Compiler { #region Data protected MosaCompiler compiler = new MosaCompiler(); /// <summary> /// Holds a list of input files. /// </summary> private List<FileInfo> inputFiles; /// <summary> /// Determines if the file is executable. /// </summary> private bool isExecutable; /// <summary> /// Holds a reference to the OptionSet used for option parsing. /// </summary> private OptionSet optionSet; private readonly int majorVersion = 1; private readonly int minorVersion = 4; private readonly string codeName = "Neptune"; /// <summary> /// A string holding a simple usage description. /// </summary> private readonly string usageString; #endregion Data #region Constructors /// <summary> /// Initializes a new instance of the Compiler class. /// </summary> public Compiler() { compiler.CompilerFactory = delegate { return new AotCompiler(); }; usageString = "Usage: mosacl -o outputfile --Architecture=[x86|avr32] --format=[ELF32|ELF64|PE] {--boot=[mb0.7]} {additional options} inputfiles"; optionSet = new OptionSet(); inputFiles = new List<FileInfo>(); #region Setup general options optionSet.Add( "local|version", "Display version information.", delegate (string v) { if (v != null) { // only show header and exit Environment.Exit(0); } }); optionSet.Add( "h|?|help", "Display the full set of available options.", delegate (string v) { if (v != null) { this.ShowHelp(); Environment.Exit(0); } }); // default option handler for input files optionSet.Add( "<>", "Input files.", delegate (string v) { if (!File.Exists(v)) { throw new OptionException(String.Format("Input file or option '{0}' doesn't exist.", v), String.Empty); } FileInfo file = new FileInfo(v); if (file.Extension.ToLower() == ".exe") { if (isExecutable) { // there are more than one exe files in the list throw new OptionException("Multiple executables aren't allowed.", String.Empty); } isExecutable = true; } inputFiles.Add(file); }); #endregion Setup general options #region Setup options optionSet.Add( "b|boot=", "Specify the bootable format of the produced binary [{mb0.7}].", delegate (string format) { compiler.CompilerOptions.BootStageFactory = GetBootStageFactory(format); } ); optionSet.Add( "a|Architecture=", "Select one of the MOSA architectures to compile for [{x86|ARMv6}].", delegate (string arch) { compiler.CompilerOptions.Architecture = SelectArchitecture(arch); } ); optionSet.Add( "f|format=", "Select the format of the binary file to create [{ELF32|ELF64|PE}].", delegate (string format) { compiler.CompilerOptions.LinkerFactory = GetLinkerFactory(format); if (compiler.CompilerOptions.LinkerFactory == null) throw new OptionException("Invalid value Linker format: " + format, "format"); } ); optionSet.Add( "o|out=", "The name of the output {file}.", delegate (string file) { compiler.CompilerOptions.OutputFile = file; } ); optionSet.Add( "map=", "Generate a map {file} of the produced binary.", delegate (string file) { compiler.CompilerOptions.MapFile = file; } ); optionSet.Add( @"sa|enable-static-alloc", @"Performs static allocations at compile time.", enable => compiler.CompilerOptions.EnableStaticAllocations = enable != null ); optionSet.Add( @"ssa|enable-single-static-assignment-form", @"Performs single static assignments at compile time.", enable => compiler.CompilerOptions.EnableSSA = enable != null ); optionSet.Add( @"optimize|enable-optimizations|ssa-optimize", @"Performs single static assignments optimizations.", enable => compiler.CompilerOptions.EnableOptimizations = enable != null ); optionSet.Add( @"promote-variables|enable-variable-promotion", @"Enables variable promotion optimization.", enable => compiler.CompilerOptions.EnableVariablePromotion = enable != null ); optionSet.Add( "base-address=", "Specify the {base address}.", delegate (string v) { uint val; if (uint.TryParse(v, out val)) { compiler.CompilerOptions.BaseAddress = val; } else { throw new OptionException("Invalid value for base address: " + v, "base-address"); } } ); #endregion Setup options } #endregion Constructors #region Public Methods /// <summary> /// Runs the command line parser and the compilation process. /// </summary> /// <param name="args">The command line arguments.</param> public void Run(string[] args) { // always print header with version information Console.WriteLine("MOSA AOT Compiler, Version {0}.{1} '{2}'", majorVersion, minorVersion, codeName); Console.WriteLine("Copyright 2015 by the MOSA Project. Licensed under the New BSD License."); Console.WriteLine("Copyright 2008 by Novell. NDesk.Options is released under the MIT/X11 license."); Console.WriteLine(); Console.WriteLine("Parsing options..."); try { if (args == null || args.Length == 0) { // no arguments are specified ShowShortHelp(); return; } optionSet.Parse(args); if (inputFiles.Count == 0) { throw new OptionException("No input file(s) specified.", String.Empty); } // Process boot format: // Boot format only matters if it's an executable // Process this only now, because input files must be known if (!isExecutable && compiler.CompilerOptions.BootStageFactory != null) { Console.WriteLine("Warning: Ignoring boot format, because target is not an executable."); Console.WriteLine(); } // Check for missing options if (compiler.CompilerOptions.LinkerFactory == null) { throw new OptionException("No binary format specified.", "format"); } if (String.IsNullOrEmpty(compiler.CompilerOptions.OutputFile)) { throw new OptionException("No output file specified.", "o"); } if (compiler.CompilerOptions.Architecture == null) { throw new OptionException("No Architecture specified.", "Architecture"); } } catch (OptionException e) { ShowError(e.Message); return; } Console.WriteLine(this.ToString()); Console.WriteLine("Compiling ..."); DateTime start = DateTime.Now; try { Compile(); } catch (CompilerException ce) { this.ShowError(ce.Message); } DateTime end = DateTime.Now; TimeSpan time = end - start; Console.WriteLine(); Console.WriteLine("Compilation time: " + time); } /// <summary> /// Returns a string representation of the current options. /// </summary> /// <returns>A string containing the options.</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append(" > Output file: ").AppendLine(compiler.CompilerOptions.OutputFile); sb.Append(" > Input file(s): ").AppendLine(String.Join(", ", new List<string>(GetInputFileNames()).ToArray())); sb.Append(" > Architecture: ").AppendLine(compiler.CompilerOptions.Architecture.GetType().FullName); sb.Append(" > Binary format: ").AppendLine(compiler.CompilerOptions.LinkerFactory().GetType().FullName); sb.Append(" > Boot format: ").AppendLine((compiler.CompilerOptions.BootStageFactory == null) ? "None" : ((IPipelineStage)compiler.CompilerOptions.BootStageFactory()).Name); sb.Append(" > Is executable: ").AppendLine(isExecutable.ToString()); return sb.ToString(); } #endregion Public Methods #region Private Methods private void Compile() { compiler.CompilerTrace.TraceListener = new ConsoleEventListener(); compiler.Load(inputFiles); compiler.Execute(Environment.ProcessorCount); } /// <summary> /// Gets a list of input file names. /// </summary> private IEnumerable<string> GetInputFileNames() { foreach (FileInfo file in inputFiles) yield return file.FullName; } /// <summary> /// Shows an error and a short information text. /// </summary> /// <param name="message">The error message to show.</param> private void ShowError(string message) { Console.WriteLine(usageString); Console.WriteLine(); Console.Write("Error: "); Console.WriteLine(message); Console.WriteLine(); Console.WriteLine("Execute 'mosacl --help' for more information."); Console.WriteLine(); } /// <summary> /// Shows a short help text pointing to the '--help' option. /// </summary> private void ShowShortHelp() { Console.WriteLine(usageString); Console.WriteLine(); Console.WriteLine("Execute 'mosacl --help' for more information."); } /// <summary> /// Shows the full help containing descriptions for all possible options. /// </summary> private void ShowHelp() { Console.WriteLine(usageString); Console.WriteLine(); Console.WriteLine("Options:"); this.optionSet.WriteOptionDescriptions(Console.Out); } #endregion Private Methods #region Internal Methods /// <summary> /// Selects the architecture. /// </summary> /// <param name="architecture">The architecture.</param> /// <returns></returns> private static BaseArchitecture SelectArchitecture(string architecture) { switch (architecture.ToLower()) { case "x86": return Mosa.Platform.x86.Architecture.CreateArchitecture(Mosa.Platform.x86.ArchitectureFeatureFlags.AutoDetect); default: throw new NotImplementCompilerException(String.Format("Unknown or unsupported Architecture {0}.", architecture)); } } private static Func<ICompilerStage> GetBootStageFactory(string format) { switch (format.ToLower()) { case "multibootHeader-0.7": case "mb0.7": return delegate { return new Mosa.Platform.x86.Stages.Multiboot0695Stage(); }; default: throw new NotImplementCompilerException(String.Format("Unknown or unsupported boot format {0}.", format)); } } private static Func<BaseLinker> GetLinkerFactory(string format) { switch (format.ToLower()) { case "pe": return delegate { return new PELinker(); }; case "elf": return delegate { return new Elf32(); }; case "elf32": return delegate { return new Elf32(); }; //case "elf64": return delegate { return new Elf64Linker(); }; default: return null; } } #endregion Internal Methods } }
26.65625
175
0.665344
[ "BSD-3-Clause" ]
Kintaro/MOSA-Project
Source/Mosa.Tool.Compiler/Compiler.cs
11,089
C#
using NiVek.Common.Comms; using NiVek.Common.Models; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace NiVek.FlightControls.Views { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MicroConfig : NiVekPage { MicroConfiguration _configuration; public MicroConfig() { this.InitializeComponent(); } protected async override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); _configuration = await Drone.GetAsync<MicroConfiguration>(NiVek.Common.Comms.Common.ModuleTypes.GPIO, NiVek.Common.Modules.GPIOModule.CMD_ReadAllPIDConstants, IncomingMessage.MicroConfig); PitchPID.DataContext = _configuration.PIDPitch; RollPID.DataContext = _configuration.PIDRoll; YawPID.DataContext = _configuration.PIDYaw; AltitudePID.DataContext = _configuration.PIDAlt; StablePID.DataContext = _configuration.PIDStable; } protected override void SetConnectionStatus(NiVek.Common.Comms.Common.ConnectionStates status) { } } }
32.056604
200
0.712184
[ "MIT" ]
bytemaster-0xff/DroneTek
NiVek/Software/GroundStation/FlightControls/Views/MicroConfig.xaml.cs
1,701
C#
using System; using System.Collections.Generic; namespace wR.Core.Domain { /// <summary> /// A row containing potential translation of a word or sentence between different /// languages /// </summary> public class TranslationRow : BaseEntity { public string English { get; set; } public string German { get; set; } public string French { get; set; } public string Polish { get; set; } public string Spanish { get; set; } public string Italian { get; set; } public ICollection<GuessAttempt> GuessAttempts { get; set; } public string GetTranslationByLanguageCode(string code) { switch (code) { case "EN": return English; case "DE": return German; case "FR": return French; case "PL": return Polish; case "ES": return Spanish; default: throw new ArgumentException($"Could not find Key: {code}"); } } } }
23.039216
86
0.497021
[ "MIT" ]
piotr-mamenas/personal-tools
tools/word-repeater/wR.Core/Domain/TranslationRow.cs
1,177
C#
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using PathFinder.sdk.Actors; using PathFinder.sdk.Host.PathServices; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Text; using Toolbox.Actor.Host; using Toolbox.Tools; namespace PathFinder.sdk.Services { public static class PathFinderServiceExtensions { public static IActorHost AddPathServiceActors(this IActorHost actorHost, IServiceProvider serviceProvider) { actorHost.VerifyNotNull(nameof(actorHost)); serviceProvider.VerifyNotNull(nameof(serviceProvider)); actorHost .Register<ILinkRecordActor>(() => serviceProvider.GetRequiredService<ILinkRecordActor>()) .Register<IMetadataRecordActor>(() => serviceProvider.GetRequiredService<IMetadataRecordActor>()); return actorHost; } public static IServiceCollection AddPathServiceActorHost(this IServiceCollection services, int capacity = 10000) { services.VerifyNotNull(nameof(services)); services.AddSingleton<IActorHost>(x => { ILoggerFactory loggerFactory = x.GetRequiredService<ILoggerFactory>(); IActorHost host = new ActorHost(capacity, loggerFactory); host.AddPathServiceActors(x); return host; }); return services; } public static IServiceCollection AddPathServices(this IServiceCollection services) { services.VerifyNotNull(nameof(services)); services.AddSingleton<ILinkPathService, LinkPathService>(); services.AddSingleton<IMetadataPathService, MetadataPathService>(); services.AddTransient<ILinkRecordActor, LinkRecordActor>(); services.AddTransient<IMetadataRecordActor, MetadataRecordActor>(); return services; } } }
33.661017
120
0.683787
[ "MIT" ]
khooversoft/PathFinder
Src/PathFinder.sdk/Services/PathFinderServiceExtensions.cs
1,988
C#
/*---------------------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v.2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. ----------------------------------------------------------*/ using ScriptEngine.Machine; using ScriptEngine.Machine.Contexts; namespace ScriptEngine.HostedScript.Library.Json { [SystemEnum("ФорматДатыJSON", "JSONDateFormat")] public class JSONDateFormatEnum : EnumerationContext { private JSONDateFormatEnum(TypeDescriptor typeRepresentation, TypeDescriptor valuesType) : base(typeRepresentation, valuesType) { } [EnumValue("ISO")] public EnumerationValue ISO { get { return this["ISO"]; } } [EnumValue("JavaScript")] public EnumerationValue JavaScript { get { return this["JavaScript"]; } } [EnumValue("Microsoft")] public EnumerationValue Microsoft { get { return this["Microsoft"]; } } public static JSONDateFormatEnum CreateInstance() { return EnumContextHelper.CreateEnumInstance<JSONDateFormatEnum>((t, v) => new JSONDateFormatEnum(t, v)); } } }
26.454545
116
0.528522
[ "MPL-2.0" ]
240596448/OneScript
src/ScriptEngine.HostedScript/Library/Json/JSONDateFormatEnum.cs
1,467
C#
using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System; using Algenta.Colectica.Model; using Algenta.Colectica.Model.Utility; using Algenta.Colectica.Model.Repository; using Algenta.Colectica.Model.Ddi; using Algenta.Colectica.Model.Ddi.Serialization; namespace CMIE.ControllerSystem.Actions { class LinkChild : IAction { private string _parentId; private string _childId; public LinkChild(string parentId, string childId) { _parentId = parentId; _childId = childId; } public override void Validate() { } public bool Evaluate(RepositoryClientBase client) { var parentPeices = _parentId.Split(':'); if (parentPeices.Length != 2) { throw new Exception("Parent identifier is wrong for link:'" + _parentId + "'"); } var childPeices = _childId.Split(':'); if (childPeices.Length != 2) { throw new Exception("Parent identifier is wrong for link:'" + _childId + "'"); } var parentIdentifier = Guid.Parse(parentPeices[1]); var childIdentifier = Guid.Parse(childPeices[1]); var parentTriples = client.GetVersions(parentIdentifier, parentPeices[0]); var childTriples = client.GetVersions(childIdentifier, childPeices[0]); var latestParent = client.GetItem(parentTriples.First()); var latestChild = client.GetItem(childTriples.First()); var map = new Dictionary<long, long>(); foreach (var parentTriple in parentTriples) { var parent = client.GetItem(parentTriple); foreach (var parentChild in parent.GetChildren()) { var childFound = childTriples.FirstOrDefault(x => x == parentChild.CompositeId); if (childFound != default(IdentifierTriple)) { map[parent.CompositeId.Version] = childFound.Version; break; } } } System.Console.WriteLine( "Parent: {0}", latestParent.GetType().GetProperty("DisplayLabel").GetValue(latestParent, null) ); System.Console.WriteLine( "Child: {0}", latestChild.GetType().GetProperty("DisplayLabel").GetValue(latestChild, null) ); System.Console.WriteLine("Parent Child"); var good = true; long max = 0, min = 999999999; if (map.Values.Any()) { max = map.Values.Max(); min = map.Values.Min(); } foreach (var childVersion in childTriples.Select(x => x.Version).Where(x => x > max)) { System.Console.WriteLine(" {0,-3}", childVersion); good = false; } foreach (var parentTriple in parentTriples) { if (map.Any(x => x.Key == parentTriple.Version)) { System.Console.WriteLine("{0,6} -> {1,-3}", parentTriple.Version, map[parentTriple.Version]); } else { System.Console.WriteLine("{0,6}", parentTriple.Version); } } return good; } public override IEnumerable<IVersionable> Build(Repository repository) { var parent = repository.GetLatestItem(_parentId); var child = repository.GetLatestItem(_childId); var oldChild = parent.GetChildren().FirstOrDefault( x => x.AgencyId == child.AgencyId && x.Identifier == child.Identifier ); if (oldChild == default(IVersionable)) { parent.AddChild(child); } else { parent.ReplaceChild(oldChild.CompositeId, child); } return new List<IVersionable> { parent }; } } }
34.966942
113
0.528008
[ "MIT" ]
CLOSER-Cohorts/CMIE
CMIE/ControllerSystem/Actions/LinkChild.cs
4,233
C#
using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using OrchardCore.DisplayManagement.Entities; using OrchardCore.DisplayManagement.Handlers; using OrchardCore.DisplayManagement.Views; using OrchardCore.Environment.Shell; using OrchardCore.Google.Analytics.Settings; using OrchardCore.Google.Analytics.ViewModels; using OrchardCore.Settings; namespace OrchardCore.Google.Analytics.Drivers { public class GoogleAnalyticsSettingsDisplayDriver : SectionDisplayDriver<ISite, GoogleAnalyticsSettings> { private readonly IAuthorizationService _authorizationService; private readonly IHttpContextAccessor _httpContextAccessor; private readonly IShellHost _shellHost; private readonly ShellSettings _shellSettings; public GoogleAnalyticsSettingsDisplayDriver( IAuthorizationService authorizationService, IHttpContextAccessor httpContextAccessor, IShellHost shellHost, ShellSettings shellSettings) { _authorizationService = authorizationService; _httpContextAccessor = httpContextAccessor; _shellHost = shellHost; _shellSettings = shellSettings; } public override async Task<IDisplayResult> EditAsync(GoogleAnalyticsSettings settings, BuildEditorContext context) { var user = _httpContextAccessor.HttpContext?.User; if (user == null || !await _authorizationService.AuthorizeAsync(user, Permissions.ManageGoogleAnalytics)) { return null; } return Initialize<GoogleAnalyticsSettingsViewModel>("GoogleAnalyticsSettings_Edit", model => { model.TrackingID = settings.TrackingID; }).Location("Content:5").OnGroup(GoogleConstants.Features.GoogleAnalytics); } public override async Task<IDisplayResult> UpdateAsync(GoogleAnalyticsSettings settings, BuildEditorContext context) { if (context.GroupId == GoogleConstants.Features.GoogleAnalytics) { var user = _httpContextAccessor.HttpContext?.User; if (user == null || !await _authorizationService.AuthorizeAsync(user, Permissions.ManageGoogleAnalytics)) { return null; } var model = new GoogleAnalyticsSettingsViewModel(); await context.Updater.TryUpdateModelAsync(model, Prefix); if (context.Updater.ModelState.IsValid) { settings.TrackingID = model.TrackingID; } } return await EditAsync(settings, context); } } }
40.144928
124
0.674729
[ "BSD-3-Clause" ]
Craige/OrchardCore
src/OrchardCore.Modules/OrchardCore.Google/Analytics/Drivers/GoogleAnalyticsSettingsDisplayDriver.cs
2,770
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201 { using Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.PowerShell; /// <summary>StaticSitesWorkflowPreviewRequest resource specific properties</summary> [System.ComponentModel.TypeConverter(typeof(StaticSitesWorkflowPreviewRequestPropertiesTypeConverter))] public partial class StaticSitesWorkflowPreviewRequestProperties { /// <summary> /// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the /// object before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); /// <summary> /// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); /// <summary> /// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); /// <summary> /// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.StaticSitesWorkflowPreviewRequestProperties" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestProperties" /// />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) { return new StaticSitesWorkflowPreviewRequestProperties(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.StaticSitesWorkflowPreviewRequestProperties" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestProperties" /// />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) { return new StaticSitesWorkflowPreviewRequestProperties(content); } /// <summary> /// Creates a new instance of <see cref="StaticSitesWorkflowPreviewRequestProperties" />, deserializing the content from a /// json string. /// </summary> /// <param name="jsonText">a string containing a JSON serialized instance of this model.</param> /// <returns>an instance of the <see cref="className" /> model class.</returns> public static Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.Json.JsonNode.Parse(jsonText)); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.StaticSitesWorkflowPreviewRequestProperties" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> internal StaticSitesWorkflowPreviewRequestProperties(global::System.Collections.IDictionary content) { bool returnNow = false; BeforeDeserializeDictionary(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildProperty = (Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSiteBuildProperties) content.GetValueForProperty("BuildProperty",((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildProperty, Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.StaticSiteBuildPropertiesTypeConverter.ConvertFrom); ((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).RepositoryUrl = (string) content.GetValueForProperty("RepositoryUrl",((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).RepositoryUrl, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).Branch = (string) content.GetValueForProperty("Branch",((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).Branch, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertyAppLocation = (string) content.GetValueForProperty("BuildPropertyAppLocation",((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertyAppLocation, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertyApiLocation = (string) content.GetValueForProperty("BuildPropertyApiLocation",((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertyApiLocation, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertyAppArtifactLocation = (string) content.GetValueForProperty("BuildPropertyAppArtifactLocation",((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertyAppArtifactLocation, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertyOutputLocation = (string) content.GetValueForProperty("BuildPropertyOutputLocation",((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertyOutputLocation, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertyAppBuildCommand = (string) content.GetValueForProperty("BuildPropertyAppBuildCommand",((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertyAppBuildCommand, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertyApiBuildCommand = (string) content.GetValueForProperty("BuildPropertyApiBuildCommand",((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertyApiBuildCommand, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertySkipGithubActionWorkflowGeneration = (bool?) content.GetValueForProperty("BuildPropertySkipGithubActionWorkflowGeneration",((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertySkipGithubActionWorkflowGeneration, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); ((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertyGithubActionSecretNameOverride = (string) content.GetValueForProperty("BuildPropertyGithubActionSecretNameOverride",((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertyGithubActionSecretNameOverride, global::System.Convert.ToString); AfterDeserializeDictionary(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.StaticSitesWorkflowPreviewRequestProperties" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> internal StaticSitesWorkflowPreviewRequestProperties(global::System.Management.Automation.PSObject content) { bool returnNow = false; BeforeDeserializePSObject(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildProperty = (Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSiteBuildProperties) content.GetValueForProperty("BuildProperty",((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildProperty, Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.StaticSiteBuildPropertiesTypeConverter.ConvertFrom); ((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).RepositoryUrl = (string) content.GetValueForProperty("RepositoryUrl",((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).RepositoryUrl, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).Branch = (string) content.GetValueForProperty("Branch",((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).Branch, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertyAppLocation = (string) content.GetValueForProperty("BuildPropertyAppLocation",((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertyAppLocation, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertyApiLocation = (string) content.GetValueForProperty("BuildPropertyApiLocation",((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertyApiLocation, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertyAppArtifactLocation = (string) content.GetValueForProperty("BuildPropertyAppArtifactLocation",((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertyAppArtifactLocation, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertyOutputLocation = (string) content.GetValueForProperty("BuildPropertyOutputLocation",((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertyOutputLocation, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertyAppBuildCommand = (string) content.GetValueForProperty("BuildPropertyAppBuildCommand",((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertyAppBuildCommand, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertyApiBuildCommand = (string) content.GetValueForProperty("BuildPropertyApiBuildCommand",((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertyApiBuildCommand, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertySkipGithubActionWorkflowGeneration = (bool?) content.GetValueForProperty("BuildPropertySkipGithubActionWorkflowGeneration",((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertySkipGithubActionWorkflowGeneration, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); ((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertyGithubActionSecretNameOverride = (string) content.GetValueForProperty("BuildPropertyGithubActionSecretNameOverride",((Microsoft.Azure.PowerShell.Cmdlets.Websites.Models.Api20201201.IStaticSitesWorkflowPreviewRequestPropertiesInternal)this).BuildPropertyGithubActionSecretNameOverride, global::System.Convert.ToString); AfterDeserializePSObject(content); } /// <summary>Serializes this instance to a json string.</summary> /// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns> public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Websites.Runtime.SerializationMode.IncludeAll)?.ToString(); } /// StaticSitesWorkflowPreviewRequest resource specific properties [System.ComponentModel.TypeConverter(typeof(StaticSitesWorkflowPreviewRequestPropertiesTypeConverter))] public partial interface IStaticSitesWorkflowPreviewRequestProperties { } }
113.896104
543
0.785063
[ "MIT" ]
Amrinder-Singh29/azure-powershell
src/Websites/Websites.Autorest/generated/api/Models/Api20201201/StaticSitesWorkflowPreviewRequestProperties.PowerShell.cs
17,387
C#
using System; using NUnit.Framework; using PeanutButter.RandomGenerators; using PeanutButter.TempDb.LocalDb; namespace PeanutButter.TestUtils.Entity.Tests { [TestFixture] public class TestDbSchemaImporter { private TempDBLocalDb _migratedDb; [OneTimeSetUp] public void TestFixtureSetUp() { _migratedDb = CreateMigratedDb(); } [OneTimeTearDown] public void TestFixtureTearDown() { _migratedDb.Dispose(); } private TempDBLocalDb CreateMigratedDb() { var db = CreateTempDb(); var migrator = Create(db.ConnectionString); migrator.MigrateToLatest(); return db; } [Test] public void CleanCommentsFrom_GivenStringWithoutComments_ShouldReturnIt() { //---------------Set up test pack------------------- var sut = Create(); var input = "create table foo (id int primary key identity);"; //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- var result = sut.CleanCommentsFrom(input); //---------------Test Result ----------------------- Assert.AreEqual(input, result); } [Test] public void CleanCommentsFrom_GivenStringWithSingleLineComment_ShouldRemoveIt() { //---------------Set up test pack------------------- var sut = Create(); var expected = "create table foo (id int primary key identity);"; var input = string.Join("\r\n", "-- this is a single line comment", expected); //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- var result = sut.CleanCommentsFrom(input); //---------------Test Result ----------------------- Assert.AreEqual(expected, result); } [Test] public void CleanCommentsFrom_GivenStringWithMultilineComment_ShouldRemoveIt() { //---------------Set up test pack------------------- var sut = Create(); var expected = "create table foo (id int primary key identity);"; var input = string.Join("\r\n", "/* this is the start of a multiline comment", "and here is some more comment */", expected); //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- var result = sut.CleanCommentsFrom(input); //---------------Test Result ----------------------- Assert.AreEqual(expected, result); } [Test] public void MigrateToLatest_ShouldNotThrow() { using (var db = CreateTempDb()) { //---------------Set up test pack------------------- var migrator = new DbSchemaImporter(db.ConnectionString, TestResources.dbscript); //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- migrator.MigrateToLatest(); //---------------Test Result ----------------------- } } [Test] public void MakeATempDb() { //---------------Set up test pack------------------- var db = CreateTempDb(); var migrator = new DbSchemaImporter(db.ConnectionString, TestResources.dbscript); migrator.MigrateToLatest(); Console.WriteLine(db.DatabasePath); //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- //---------------Test Result ----------------------- } [TestCase("COMBlockList")] [TestCase("COMBlockListReason")] [TestCase("COMMessagePlatformOption")] [TestCase("COMMessageRequestLog")] [TestCase("COMNotificationCustomer")] [TestCase("COMNotificationCustomerHistory")] [TestCase("COMNotificationMember")] [TestCase("COMNotificationMemberHistory")] [TestCase("COMNotificationRestriction")] [TestCase("COMPromotionCustomer")] [TestCase("COMPromotionCustomerHistory")] [TestCase("COMPromotionMember")] [TestCase("COMPromotionMemberHistory")] [TestCase("COMProtocol")] [TestCase("COMProtocolOption")] [TestCase("COMSubscriptionOption")] public void ShouldHaveTableAfterMigration_(string tableName) { //---------------Set up test pack------------------- using (var connection = _migratedDb.OpenConnection()) { //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- using (var cmd = connection.CreateCommand()) { cmd.CommandText = "select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = '" + tableName + "';"; using (var reader = cmd.ExecuteReader()) { Assert.IsTrue(reader.Read()); } } //---------------Test Result ----------------------- } } [Test] public void SplitPartsOutOf_GivenStringWithNo_GO_ShouldReturnIt() { //---------------Set up test pack------------------- var sut = Create(); var input = RandomValueGen.GetRandomString(); //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- var result = sut.SplitPartsOutOf(input); //---------------Test Result ----------------------- Assert.IsNotNull(result); Assert.AreEqual(1, result.Length); Assert.AreEqual(input, result[0]); } [Test] public void SplitPartsOutOf_GivenStringWithA_GO_ShouldReturnTheParts() { //---------------Set up test pack------------------- var sut = Create(); var first = RandomValueGen.GetRandomString(); var second = RandomValueGen.GetRandomString(); var input = first + "\r\nGO\r\n" + second; //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- var result = sut.SplitPartsOutOf(input); //---------------Test Result ----------------------- Assert.IsNotNull(result); Assert.AreEqual(2, result.Length); Assert.AreEqual(first, result[0]); Assert.AreEqual(second, result[1]); } private DbSchemaImporter Create(string connectionString = null, string schema = null) { return new DbSchemaImporter(connectionString ?? RandomValueGen.GetRandomString(1), schema ?? TestResources.dbscript); } private static TempDBLocalDb CreateTempDb() { return new TempDBLocalDb(); } } }
36.980392
138
0.451617
[ "BSD-3-Clause" ]
Geosong/PeanutButter
source/TestUtils/PeanutButter.TestUtils.Entity.Tests/TestDbSchemaImporter.cs
7,544
C#
using System; public class PrintingDrink { public static void Main() { //Input string profession = Console.ReadLine(); //Logic string drink = string.Empty; switch (profession) { case "Athlete": drink = "Water"; break; case "Businessman": case "Businesswoman": drink = "Coffee"; break; case "SoftUni Student": drink = "Beer"; break; default: drink = "Tea"; break; } //Logic Console.WriteLine(drink); } }
20.575758
47
0.421208
[ "MIT" ]
AJMitev/CSharp-Programming-Fundamentals
01.Conditional Statements and Loops/Problem 1. Choose a Drink/PrintingDrink.cs
681
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace OrderServiceMassTransit.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet] public IEnumerable<WeatherForecast> Get() { var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); } } }
28.875
110
0.604329
[ "MIT" ]
farzin2171/WT.RabbitMQSamples
RabbitMQ_Samples/OrderServiceMassTransit/Controllers/WeatherForecastController.cs
1,157
C#
// Copyright (c) 2019 Lykke Corp. // See the LICENSE file in the project root for more information. using Lykke.SettingsReader.Attributes; namespace MarginTrading.AssetService.Core.Settings { public class PlatformSettings { [Optional] public string PlatformMarketId { get; set; } = "PlatformScheduleMarketId"; } }
26.384615
82
0.720117
[ "MIT-0" ]
LykkeBusiness/MarginTrading.AssetService
src/MarginTrading.AssetService.Core/Settings/PlatformSettings.cs
343
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 sso-admin-2020-07-20.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.SSOAdmin.Model { /// <summary> /// This is the response object from the DeleteInstanceAccessControlAttributeConfiguration operation. /// </summary> public partial class DeleteInstanceAccessControlAttributeConfigurationResponse : AmazonWebServiceResponse { } }
32.131579
110
0.725635
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/SSOAdmin/Generated/Model/DeleteInstanceAccessControlAttributeConfigurationResponse.cs
1,221
C#
using System; using MikhailKhalizev.Processor.x86.BinToCSharp; namespace MikhailKhalizev.Max.Program { public partial class RawProgram { [MethodInfo("0x100d_5094-44b9eb0e")] public void Method_100d_5094() { ii(0x100d_5094, 1); push(ebx); /* push ebx */ ii(0x100d_5095, 1); push(ecx); /* push ecx */ ii(0x100d_5096, 1); push(edx); /* push edx */ ii(0x100d_5097, 1); push(esi); /* push esi */ ii(0x100d_5098, 1); push(edi); /* push edi */ ii(0x100d_5099, 1); push(ebp); /* push ebp */ ii(0x100d_509a, 2); mov(ebp, esp); /* mov ebp, esp */ ii(0x100d_509c, 6); sub(esp, 4); /* sub esp, 0x4 */ ii(0x100d_50a2, 4); mov(memb[ss, ebp - 4], 1); /* mov byte [ebp-0x4], 0x1 */ ii(0x100d_50a6, 3); mov(al, memb[ss, ebp - 4]); /* mov al, [ebp-0x4] */ ii(0x100d_50a9, 2); mov(esp, ebp); /* mov esp, ebp */ ii(0x100d_50ab, 1); pop(ebp); /* pop ebp */ ii(0x100d_50ac, 1); pop(edi); /* pop edi */ ii(0x100d_50ad, 1); pop(esi); /* pop esi */ ii(0x100d_50ae, 1); pop(edx); /* pop edx */ ii(0x100d_50af, 1); pop(ecx); /* pop ecx */ ii(0x100d_50b0, 1); pop(ebx); /* pop ebx */ ii(0x100d_50b1, 1); ret(); /* ret */ } } }
58.1875
101
0.37218
[ "Apache-2.0" ]
mikhail-khalizev/max
source/MikhailKhalizev.Max/source/Program/Auto/z-100d-5094.cs
1,862
C#
// // System.Threading.AsyncFlowControl.cs // // Author: // Sebastien Pouliot <sebastien@ximian.com> // // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Globalization; using System.Runtime.InteropServices; using System.Security; namespace System.Threading { internal enum AsyncFlowControlType { None, Execution, Security } public struct AsyncFlowControl : IDisposable { private Thread _t; private AsyncFlowControlType _type; internal AsyncFlowControl (Thread t, AsyncFlowControlType type) { _t = t; _type = type; } public void Undo () { if (_t == null) { throw new InvalidOperationException (Locale.GetText ( "Can only be called once.")); } switch (_type) { case AsyncFlowControlType.Execution: ExecutionContext.RestoreFlow (); break; case AsyncFlowControlType.Security: SecurityContext.RestoreFlow (); break; } _t = null; } #if NET_4_0 || MOBILE public void Dispose () #else void IDisposable.Dispose () #endif { if (_t != null) { Undo (); _t = null; _type = AsyncFlowControlType.None; } } public override int GetHashCode () { return(base.GetHashCode ()); } public override bool Equals (object obj) { if (!(obj is AsyncFlowControl)) { return(false); } return(obj.Equals (this)); } public bool Equals (AsyncFlowControl obj) { if (this._t == obj._t && this._type == obj._type) { return(true); } else { return(false); } } public static bool operator == (AsyncFlowControl a, AsyncFlowControl b) { return a.Equals (b); } public static bool operator != (AsyncFlowControl a, AsyncFlowControl b) { return !a.Equals (b); } } }
24.387931
73
0.692471
[ "Apache-2.0" ]
CRivlaldo/mono
mcs/class/corlib/System.Threading/AsyncFlowControl.cs
2,829
C#
using System.Collections.Generic; using System.Collections.ObjectModel; namespace SaleIt.Controllers.Resources { public class MakeResource : KeyValuePairResource { public ICollection<KeyValuePairResource> Models { get; set; } public MakeResource() { Models = new Collection<KeyValuePairResource>(); } } }
25.785714
69
0.68144
[ "MIT" ]
ritwickdey/Sale-It
Controllers/Resources/MakeResource.cs
361
C#
using DN.WebApi.Application.Abstractions.Services.Identity; using DN.WebApi.Infrastructure.SwaggerFilters; using DN.WebApi.Shared.DTOs.Identity.Requests; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Swashbuckle.AspNetCore.Annotations; using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; namespace DN.WebApi.Bootstrapper.Controllers.Identity { [ApiController] [Route("api/[controller]")] public sealed class TokensController : ControllerBase { private readonly ITokenService _tokenService; public TokensController(ITokenService tokenService) { _tokenService = tokenService; } [HttpPost] [AllowAnonymous] [SwaggerHeader("tenant", "Input your tenant Id to access this API", "", true)] [SwaggerOperation(Summary = "Submit Credentials with Tenant Key to generate valid Access Token.")] public async Task<IActionResult> GetTokenAsync(TokenRequest request, [FromHeader(Name = "tenant")][Required] string tenant = null) { var token = await _tokenService.GetTokenAsync(request, GenerateIPAddress()); return Ok(token); } [HttpPost("refresh")] [AllowAnonymous] [SwaggerHeader("tenant", "Input your tenant Id to access this API", "", true)] public async Task<ActionResult> RefreshAsync(RefreshTokenRequest request, [FromHeader(Name = "tenant")][Required] string tenant = null) { var response = await _tokenService.RefreshTokenAsync(request, GenerateIPAddress()); return Ok(response); } private string GenerateIPAddress() { if (Request.Headers.ContainsKey("X-Forwarded-For")) { return Request.Headers["X-Forwarded-For"]; } else { return HttpContext.Connection.RemoteIpAddress?.MapToIPv4().ToString(); } } } }
37.074074
143
0.658342
[ "MIT" ]
MohAshour/m.a
src/Bootstrapper/Controllers/Identity/TokensController.cs
2,002
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("MediumTrust")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("GemBox Ltd.")] [assembly: AssemblyProduct("MediumTrust")] [assembly: AssemblyCopyright("Copyright © GemBox Ltd.")] [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("46ddde6e-a2a6-4769-bc35-36fab66ffdd7")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.083333
84
0.749818
[ "MIT" ]
GemBox-d-o-o/GemBox.Spreadsheet.Examples
C#/Platforms/GridView in ASP.NET Web Forms/Properties/AssemblyInfo.cs
1,372
C#
 #if NET20 #region License, Terms and Author(s) // // LINQBridge // Copyright (c) 2007-9 Atif Aziz, Joseph Albahari. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // This library is free software; you can redistribute it and/or modify it // under the terms of the New BSD License, a copy of which should have // been delivered along with this distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #endregion using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using Medivh.Json.Serialization; namespace Medivh.Json.Utilities.LinqBridge { /// <summary> /// Provides a set of static (Shared in Visual Basic) methods for /// querying objects that implement <see cref="IEnumerable{T}" />. /// </summary> internal static partial class Enumerable { /// <summary> /// Returns the input typed as <see cref="IEnumerable{T}"/>. /// </summary> public static IEnumerable<TSource> AsEnumerable<TSource>(IEnumerable<TSource> source) { return source; } /// <summary> /// Returns an empty <see cref="IEnumerable{T}"/> that has the /// specified type argument. /// </summary> public static IEnumerable<TResult> Empty<TResult>() { return Sequence<TResult>.Empty; } /// <summary> /// Converts the elements of an <see cref="IEnumerable"/> to the /// specified type. /// </summary> public static IEnumerable<TResult> Cast<TResult>( this IEnumerable source) { CheckNotNull(source, "source"); return CastYield<TResult>(source); } private static IEnumerable<TResult> CastYield<TResult>( IEnumerable source) { foreach (var item in source) yield return (TResult) item; } /// <summary> /// Filters the elements of an <see cref="IEnumerable"/> based on a specified type. /// </summary> public static IEnumerable<TResult> OfType<TResult>( this IEnumerable source) { CheckNotNull(source, "source"); return OfTypeYield<TResult>(source); } private static IEnumerable<TResult> OfTypeYield<TResult>( IEnumerable source) { foreach (var item in source) if (item is TResult) yield return (TResult) item; } /// <summary> /// Generates a sequence of integral numbers within a specified range. /// </summary> /// <param name="start">The value of the first integer in the sequence.</param> /// <param name="count">The number of sequential integers to generate.</param> public static IEnumerable<int> Range(int start, int count) { if (count < 0) throw new ArgumentOutOfRangeException("count", count, null); var end = (long) start + count; if (end - 1 >= int.MaxValue) throw new ArgumentOutOfRangeException("count", count, null); return RangeYield(start, end); } private static IEnumerable<int> RangeYield(int start, long end) { for (var i = start; i < end; i++) yield return i; } /// <summary> /// Generates a sequence that contains one repeated value. /// </summary> public static IEnumerable<TResult> Repeat<TResult>(TResult element, int count) { if (count < 0) throw new ArgumentOutOfRangeException("count", count, null); return RepeatYield(element, count); } private static IEnumerable<TResult> RepeatYield<TResult>(TResult element, int count) { for (var i = 0; i < count; i++) yield return element; } /// <summary> /// Filters a sequence of values based on a predicate. /// </summary> public static IEnumerable<TSource> Where<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate) { CheckNotNull(predicate, "predicate"); return source.Where((item, i) => predicate(item)); } /// <summary> /// Filters a sequence of values based on a predicate. /// Each element's index is used in the logic of the predicate function. /// </summary> public static IEnumerable<TSource> Where<TSource>( this IEnumerable<TSource> source, Func<TSource, int, bool> predicate) { CheckNotNull(source, "source"); CheckNotNull(predicate, "predicate"); return WhereYield(source, predicate); } private static IEnumerable<TSource> WhereYield<TSource>( IEnumerable<TSource> source, Func<TSource, int, bool> predicate) { var i = 0; foreach (var item in source) if (predicate(item, i++)) yield return item; } /// <summary> /// Projects each element of a sequence into a new form. /// </summary> public static IEnumerable<TResult> Select<TSource, TResult>( this IEnumerable<TSource> source, Func<TSource, TResult> selector) { CheckNotNull(selector, "selector"); return source.Select((item, i) => selector(item)); } /// <summary> /// Projects each element of a sequence into a new form by /// incorporating the element's index. /// </summary> public static IEnumerable<TResult> Select<TSource, TResult>( this IEnumerable<TSource> source, Func<TSource, int, TResult> selector) { CheckNotNull(source, "source"); CheckNotNull(selector, "selector"); return SelectYield(source, selector); } private static IEnumerable<TResult> SelectYield<TSource, TResult>( IEnumerable<TSource> source, Func<TSource, int, TResult> selector) { var i = 0; foreach (var item in source) yield return selector(item, i++); } /// <summary> /// Projects each element of a sequence to an <see cref="IEnumerable{T}" /> /// and flattens the resulting sequences into one sequence. /// </summary> public static IEnumerable<TResult> SelectMany<TSource, TResult>( this IEnumerable<TSource> source, Func<TSource, IEnumerable<TResult>> selector) { CheckNotNull(selector, "selector"); return source.SelectMany((item, i) => selector(item)); } /// <summary> /// Projects each element of a sequence to an <see cref="IEnumerable{T}" />, /// and flattens the resulting sequences into one sequence. The /// index of each source element is used in the projected form of /// that element. /// </summary> public static IEnumerable<TResult> SelectMany<TSource, TResult>( this IEnumerable<TSource> source, Func<TSource, int, IEnumerable<TResult>> selector) { CheckNotNull(selector, "selector"); return source.SelectMany(selector, (item, subitem) => subitem); } /// <summary> /// Projects each element of a sequence to an <see cref="IEnumerable{T}" />, /// flattens the resulting sequences into one sequence, and invokes /// a result selector function on each element therein. /// </summary> public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>( this IEnumerable<TSource> source, Func<TSource, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector) { CheckNotNull(collectionSelector, "collectionSelector"); return source.SelectMany((item, i) => collectionSelector(item), resultSelector); } /// <summary> /// Projects each element of a sequence to an <see cref="IEnumerable{T}" />, /// flattens the resulting sequences into one sequence, and invokes /// a result selector function on each element therein. The index of /// each source element is used in the intermediate projected form /// of that element. /// </summary> public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>( this IEnumerable<TSource> source, Func<TSource, int, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector) { CheckNotNull(source, "source"); CheckNotNull(collectionSelector, "collectionSelector"); CheckNotNull(resultSelector, "resultSelector"); return SelectManyYield(source, collectionSelector, resultSelector); } private static IEnumerable<TResult> SelectManyYield<TSource, TCollection, TResult>( this IEnumerable<TSource> source, Func<TSource, int, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector) { var i = 0; foreach (var item in source) foreach (var subitem in collectionSelector(item, i++)) yield return resultSelector(item, subitem); } /// <summary> /// Returns elements from a sequence as long as a specified condition is true. /// </summary> public static IEnumerable<TSource> TakeWhile<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate) { CheckNotNull(predicate, "predicate"); return source.TakeWhile((item, i) => predicate(item)); } /// <summary> /// Returns elements from a sequence as long as a specified condition is true. /// The element's index is used in the logic of the predicate function. /// </summary> public static IEnumerable<TSource> TakeWhile<TSource>( this IEnumerable<TSource> source, Func<TSource, int, bool> predicate) { CheckNotNull(source, "source"); CheckNotNull(predicate, "predicate"); return TakeWhileYield(source, predicate); } private static IEnumerable<TSource> TakeWhileYield<TSource>( this IEnumerable<TSource> source, Func<TSource, int, bool> predicate) { var i = 0; foreach (var item in source) if (predicate(item, i++)) yield return item; else break; } private static class Futures<T> { public static readonly Func<T> Default = () => default(T); public static readonly Func<T> Undefined = () => { throw new InvalidOperationException(); }; } /// <summary> /// Base implementation of First operator. /// </summary> private static TSource FirstImpl<TSource>( this IEnumerable<TSource> source, Func<TSource> empty) { CheckNotNull(source, "source"); Debug.Assert(empty != null); var list = source as IList<TSource>; // optimized case for lists if (list != null) return list.Count > 0 ? list[0] : empty(); using (var e = source.GetEnumerator()) // fallback for enumeration return e.MoveNext() ? e.Current : empty(); } /// <summary> /// Returns the first element of a sequence. /// </summary> public static TSource First<TSource>( this IEnumerable<TSource> source) { return source.FirstImpl(Futures<TSource>.Undefined); } /// <summary> /// Returns the first element in a sequence that satisfies a specified condition. /// </summary> public static TSource First<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate) { return First(source.Where(predicate)); } /// <summary> /// Returns the first element of a sequence, or a default value if /// the sequence contains no elements. /// </summary> public static TSource FirstOrDefault<TSource>( this IEnumerable<TSource> source) { return source.FirstImpl(Futures<TSource>.Default); } /// <summary> /// Returns the first element of the sequence that satisfies a /// condition or a default value if no such element is found. /// </summary> public static TSource FirstOrDefault<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate) { return FirstOrDefault(source.Where(predicate)); } /// <summary> /// Base implementation of Last operator. /// </summary> private static TSource LastImpl<TSource>( this IEnumerable<TSource> source, Func<TSource> empty) { CheckNotNull(source, "source"); var list = source as IList<TSource>; // optimized case for lists if (list != null) return list.Count > 0 ? list[list.Count - 1] : empty(); using (var e = source.GetEnumerator()) { if (!e.MoveNext()) return empty(); var last = e.Current; while (e.MoveNext()) last = e.Current; return last; } } /// <summary> /// Returns the last element of a sequence. /// </summary> public static TSource Last<TSource>( this IEnumerable<TSource> source) { return source.LastImpl(Futures<TSource>.Undefined); } /// <summary> /// Returns the last element of a sequence that satisfies a /// specified condition. /// </summary> public static TSource Last<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate) { return Last(source.Where(predicate)); } /// <summary> /// Returns the last element of a sequence, or a default value if /// the sequence contains no elements. /// </summary> public static TSource LastOrDefault<TSource>( this IEnumerable<TSource> source) { return source.LastImpl(Futures<TSource>.Default); } /// <summary> /// Returns the last element of a sequence that satisfies a /// condition or a default value if no such element is found. /// </summary> public static TSource LastOrDefault<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate) { return LastOrDefault(source.Where(predicate)); } /// <summary> /// Base implementation of Single operator. /// </summary> private static TSource SingleImpl<TSource>( this IEnumerable<TSource> source, Func<TSource> empty) { CheckNotNull(source, "source"); using (var e = source.GetEnumerator()) { if (e.MoveNext()) { var single = e.Current; if (!e.MoveNext()) return single; throw new InvalidOperationException(); } return empty(); } } /// <summary> /// Returns the only element of a sequence, and throws an exception /// if there is not exactly one element in the sequence. /// </summary> public static TSource Single<TSource>( this IEnumerable<TSource> source) { return source.SingleImpl(Futures<TSource>.Undefined); } /// <summary> /// Returns the only element of a sequence that satisfies a /// specified condition, and throws an exception if more than one /// such element exists. /// </summary> public static TSource Single<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate) { return Single(source.Where(predicate)); } /// <summary> /// Returns the only element of a sequence, or a default value if /// the sequence is empty; this method throws an exception if there /// is more than one element in the sequence. /// </summary> public static TSource SingleOrDefault<TSource>( this IEnumerable<TSource> source) { return source.SingleImpl(Futures<TSource>.Default); } /// <summary> /// Returns the only element of a sequence that satisfies a /// specified condition or a default value if no such element /// exists; this method throws an exception if more than one element /// satisfies the condition. /// </summary> public static TSource SingleOrDefault<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate) { return SingleOrDefault(source.Where(predicate)); } /// <summary> /// Returns the element at a specified index in a sequence. /// </summary> public static TSource ElementAt<TSource>( this IEnumerable<TSource> source, int index) { CheckNotNull(source, "source"); if (index < 0) throw new ArgumentOutOfRangeException("index", index, null); var list = source as IList<TSource>; if (list != null) return list[index]; try { return source.SkipWhile((item, i) => i < index).First(); } catch (InvalidOperationException) // if thrown by First { throw new ArgumentOutOfRangeException("index", index, null); } } /// <summary> /// Returns the element at a specified index in a sequence or a /// default value if the index is out of range. /// </summary> public static TSource ElementAtOrDefault<TSource>( this IEnumerable<TSource> source, int index) { CheckNotNull(source, "source"); if (index < 0) return default(TSource); var list = source as IList<TSource>; if (list != null) return index < list.Count ? list[index] : default(TSource); return source.SkipWhile((item, i) => i < index).FirstOrDefault(); } /// <summary> /// Inverts the order of the elements in a sequence. /// </summary> public static IEnumerable<TSource> Reverse<TSource>( this IEnumerable<TSource> source) { CheckNotNull(source, "source"); return ReverseYield(source); } private static IEnumerable<TSource> ReverseYield<TSource>(IEnumerable<TSource> source) { var stack = new Stack<TSource>(); foreach (var item in source) stack.Push(item); foreach (var item in stack) yield return item; } /// <summary> /// Returns a specified number of contiguous elements from the start /// of a sequence. /// </summary> public static IEnumerable<TSource> Take<TSource>( this IEnumerable<TSource> source, int count) { return source.Where((item, i) => i < count); } /// <summary> /// Bypasses a specified number of elements in a sequence and then /// returns the remaining elements. /// </summary> public static IEnumerable<TSource> Skip<TSource>( this IEnumerable<TSource> source, int count) { return source.Where((item, i) => i >= count); } /// <summary> /// Bypasses elements in a sequence as long as a specified condition /// is true and then returns the remaining elements. /// </summary> public static IEnumerable<TSource> SkipWhile<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate) { CheckNotNull(predicate, "predicate"); return source.SkipWhile((item, i) => predicate(item)); } /// <summary> /// Bypasses elements in a sequence as long as a specified condition /// is true and then returns the remaining elements. The element's /// index is used in the logic of the predicate function. /// </summary> public static IEnumerable<TSource> SkipWhile<TSource>( this IEnumerable<TSource> source, Func<TSource, int, bool> predicate) { CheckNotNull(source, "source"); CheckNotNull(predicate, "predicate"); return SkipWhileYield(source, predicate); } private static IEnumerable<TSource> SkipWhileYield<TSource>( IEnumerable<TSource> source, Func<TSource, int, bool> predicate) { using (var e = source.GetEnumerator()) { for (var i = 0;; i++) { if (!e.MoveNext()) yield break; if (!predicate(e.Current, i)) break; } do { yield return e.Current; } while (e.MoveNext()); } } /// <summary> /// Returns the number of elements in a sequence. /// </summary> public static int Count<TSource>( this IEnumerable<TSource> source) { CheckNotNull(source, "source"); var collection = source as ICollection; return collection != null ? collection.Count : source.Aggregate(0, (count, item) => checked(count + 1)); } /// <summary> /// Returns a number that represents how many elements in the /// specified sequence satisfy a condition. /// </summary> public static int Count<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate) { return Count(source.Where(predicate)); } /// <summary> /// Returns an <see cref="Int64"/> that represents the total number /// of elements in a sequence. /// </summary> public static long LongCount<TSource>( this IEnumerable<TSource> source) { CheckNotNull(source, "source"); var array = source as Array; return array != null ? array.LongLength : source.Aggregate(0L, (count, item) => count + 1); } /// <summary> /// Returns an <see cref="Int64"/> that represents how many elements /// in a sequence satisfy a condition. /// </summary> public static long LongCount<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate) { return LongCount(source.Where(predicate)); } /// <summary> /// Concatenates two sequences. /// </summary> public static IEnumerable<TSource> Concat<TSource>( this IEnumerable<TSource> first, IEnumerable<TSource> second) { CheckNotNull(first, "first"); CheckNotNull(second, "second"); return ConcatYield(first, second); } private static IEnumerable<TSource> ConcatYield<TSource>( IEnumerable<TSource> first, IEnumerable<TSource> second) { foreach (var item in first) yield return item; foreach (var item in second) yield return item; } /// <summary> /// Creates a <see cref="List{T}"/> from an <see cref="IEnumerable{T}"/>. /// </summary> public static List<TSource> ToList<TSource>( this IEnumerable<TSource> source) { CheckNotNull(source, "source"); return new List<TSource>(source); } /// <summary> /// Creates an array from an <see cref="IEnumerable{T}"/>. /// </summary> public static TSource[] ToArray<TSource>( this IEnumerable<TSource> source) { return source.ToList().ToArray(); } /// <summary> /// Returns distinct elements from a sequence by using the default /// equality comparer to compare values. /// </summary> public static IEnumerable<TSource> Distinct<TSource>( this IEnumerable<TSource> source) { return Distinct(source, /* comparer */ null); } /// <summary> /// Returns distinct elements from a sequence by using a specified /// <see cref="IEqualityComparer{T}"/> to compare values. /// </summary> public static IEnumerable<TSource> Distinct<TSource>( this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer) { CheckNotNull(source, "source"); return DistinctYield(source, comparer); } private static IEnumerable<TSource> DistinctYield<TSource>( IEnumerable<TSource> source, IEqualityComparer<TSource> comparer) { var set = new Dictionary<TSource, object>(comparer); var gotNull = false; foreach (var item in source) { if (item == null) { if (gotNull) continue; gotNull = true; } else { if (set.ContainsKey(item)) continue; set.Add(item, null); } yield return item; } } /// <summary> /// Creates a <see cref="Lookup{TKey,TElement}" /> from an /// <see cref="IEnumerable{T}" /> according to a specified key /// selector function. /// </summary> public static ILookup<TKey, TSource> ToLookup<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { return ToLookup(source, keySelector, e => e, /* comparer */ null); } /// <summary> /// Creates a <see cref="Lookup{TKey,TElement}" /> from an /// <see cref="IEnumerable{T}" /> according to a specified key /// selector function and a key comparer. /// </summary> public static ILookup<TKey, TSource> ToLookup<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer) { return ToLookup(source, keySelector, e => e, comparer); } /// <summary> /// Creates a <see cref="Lookup{TKey,TElement}" /> from an /// <see cref="IEnumerable{T}" /> according to specified key /// and element selector functions. /// </summary> public static ILookup<TKey, TElement> ToLookup<TSource, TKey, TElement>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector) { return ToLookup(source, keySelector, elementSelector, /* comparer */ null); } /// <summary> /// Creates a <see cref="Lookup{TKey,TElement}" /> from an /// <see cref="IEnumerable{T}" /> according to a specified key /// selector function, a comparer and an element selector function. /// </summary> public static ILookup<TKey, TElement> ToLookup<TSource, TKey, TElement>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer) { CheckNotNull(source, "source"); CheckNotNull(keySelector, "keySelector"); CheckNotNull(elementSelector, "elementSelector"); var lookup = new Lookup<TKey, TElement>(comparer); foreach (var item in source) { var key = keySelector(item); var grouping = (Grouping<TKey, TElement>) lookup.Find(key); if (grouping == null) { grouping = new Grouping<TKey, TElement>(key); lookup.Add(grouping); } grouping.Add(elementSelector(item)); } return lookup; } /// <summary> /// Groups the elements of a sequence according to a specified key /// selector function. /// </summary> public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { return GroupBy(source, keySelector, /* comparer */ null); } /// <summary> /// Groups the elements of a sequence according to a specified key /// selector function and compares the keys by using a specified /// comparer. /// </summary> public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer) { return GroupBy(source, keySelector, e => e, comparer); } /// <summary> /// Groups the elements of a sequence according to a specified key /// selector function and projects the elements for each group by /// using a specified function. /// </summary> public static IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector) { return GroupBy(source, keySelector, elementSelector, /* comparer */ null); } /// <summary> /// Groups the elements of a sequence according to a specified key /// selector function and creates a result value from each group and /// its key. /// </summary> public static IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer) { CheckNotNull(source, "source"); CheckNotNull(keySelector, "keySelector"); CheckNotNull(elementSelector, "elementSelector"); return ToLookup(source, keySelector, elementSelector, comparer); } /// <summary> /// Groups the elements of a sequence according to a key selector /// function. The keys are compared by using a comparer and each /// group's elements are projected by using a specified function. /// </summary> public static IEnumerable<TResult> GroupBy<TSource, TKey, TResult>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TKey, IEnumerable<TSource>, TResult> resultSelector) { return GroupBy(source, keySelector, resultSelector, /* comparer */ null); } /// <summary> /// Groups the elements of a sequence according to a specified key /// selector function and creates a result value from each group and /// its key. The elements of each group are projected by using a /// specified function. /// </summary> public static IEnumerable<TResult> GroupBy<TSource, TKey, TResult>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TKey, IEnumerable<TSource>, TResult> resultSelector, IEqualityComparer<TKey> comparer) { CheckNotNull(source, "source"); CheckNotNull(keySelector, "keySelector"); CheckNotNull(resultSelector, "resultSelector"); return ToLookup(source, keySelector, comparer).Select(g => resultSelector(g.Key, g)); } /// <summary> /// Groups the elements of a sequence according to a specified key /// selector function and creates a result value from each group and /// its key. The keys are compared by using a specified comparer. /// </summary> public static IEnumerable<TResult> GroupBy<TSource, TKey, TElement, TResult>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, Func<TKey, IEnumerable<TElement>, TResult> resultSelector) { return GroupBy(source, keySelector, elementSelector, resultSelector, /* comparer */ null); } /// <summary> /// Groups the elements of a sequence according to a specified key /// selector function and creates a result value from each group and /// its key. Key values are compared by using a specified comparer, /// and the elements of each group are projected by using a /// specified function. /// </summary> public static IEnumerable<TResult> GroupBy<TSource, TKey, TElement, TResult>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, Func<TKey, IEnumerable<TElement>, TResult> resultSelector, IEqualityComparer<TKey> comparer) { CheckNotNull(source, "source"); CheckNotNull(keySelector, "keySelector"); CheckNotNull(elementSelector, "elementSelector"); CheckNotNull(resultSelector, "resultSelector"); return ToLookup(source, keySelector, elementSelector, comparer) .Select(g => resultSelector(g.Key, g)); } /// <summary> /// Applies an accumulator function over a sequence. /// </summary> public static TSource Aggregate<TSource>( this IEnumerable<TSource> source, Func<TSource, TSource, TSource> func) { CheckNotNull(source, "source"); CheckNotNull(func, "func"); using (var e = source.GetEnumerator()) { if (!e.MoveNext()) throw new InvalidOperationException(); return e.Renumerable().Skip(1).Aggregate(e.Current, func); } } /// <summary> /// Applies an accumulator function over a sequence. The specified /// seed value is used as the initial accumulator value. /// </summary> public static TAccumulate Aggregate<TSource, TAccumulate>( this IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func) { return Aggregate(source, seed, func, r => r); } /// <summary> /// Applies an accumulator function over a sequence. The specified /// seed value is used as the initial accumulator value, and the /// specified function is used to select the result value. /// </summary> public static TResult Aggregate<TSource, TAccumulate, TResult>( this IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func, Func<TAccumulate, TResult> resultSelector) { CheckNotNull(source, "source"); CheckNotNull(func, "func"); CheckNotNull(resultSelector, "resultSelector"); var result = seed; foreach (var item in source) result = func(result, item); return resultSelector(result); } /// <summary> /// Produces the set union of two sequences by using the default /// equality comparer. /// </summary> public static IEnumerable<TSource> Union<TSource>( this IEnumerable<TSource> first, IEnumerable<TSource> second) { return Union(first, second, /* comparer */ null); } /// <summary> /// Produces the set union of two sequences by using a specified /// <see cref="IEqualityComparer{T}" />. /// </summary> public static IEnumerable<TSource> Union<TSource>( this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer) { return first.Concat(second).Distinct(comparer); } /// <summary> /// Returns the elements of the specified sequence or the type /// parameter's default value in a singleton collection if the /// sequence is empty. /// </summary> public static IEnumerable<TSource> DefaultIfEmpty<TSource>( this IEnumerable<TSource> source) { return source.DefaultIfEmpty(default(TSource)); } /// <summary> /// Returns the elements of the specified sequence or the specified /// value in a singleton collection if the sequence is empty. /// </summary> public static IEnumerable<TSource> DefaultIfEmpty<TSource>( this IEnumerable<TSource> source, TSource defaultValue) { CheckNotNull(source, "source"); return DefaultIfEmptyYield(source, defaultValue); } private static IEnumerable<TSource> DefaultIfEmptyYield<TSource>( IEnumerable<TSource> source, TSource defaultValue) { using (var e = source.GetEnumerator()) { if (!e.MoveNext()) yield return defaultValue; else do { yield return e.Current; } while (e.MoveNext()); } } /// <summary> /// Determines whether all elements of a sequence satisfy a condition. /// </summary> public static bool All<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate) { CheckNotNull(source, "source"); CheckNotNull(predicate, "predicate"); foreach (var item in source) if (!predicate(item)) return false; return true; } /// <summary> /// Determines whether a sequence contains any elements. /// </summary> public static bool Any<TSource>( this IEnumerable<TSource> source) { CheckNotNull(source, "source"); using (var e = source.GetEnumerator()) return e.MoveNext(); } /// <summary> /// Determines whether any element of a sequence satisfies a /// condition. /// </summary> public static bool Any<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate) { return source.Where(predicate).Any(); } /// <summary> /// Determines whether a sequence contains a specified element by /// using the default equality comparer. /// </summary> public static bool Contains<TSource>( this IEnumerable<TSource> source, TSource value) { return source.Contains(value, /* comparer */ null); } /// <summary> /// Determines whether a sequence contains a specified element by /// using a specified <see cref="IEqualityComparer{T}" />. /// </summary> public static bool Contains<TSource>( this IEnumerable<TSource> source, TSource value, IEqualityComparer<TSource> comparer) { CheckNotNull(source, "source"); if (comparer == null) { var collection = source as ICollection<TSource>; if (collection != null) return collection.Contains(value); } comparer = comparer ?? EqualityComparer<TSource>.Default; return source.Any(item => comparer.Equals(item, value)); } /// <summary> /// Determines whether two sequences are equal by comparing the /// elements by using the default equality comparer for their type. /// </summary> public static bool SequenceEqual<TSource>( this IEnumerable<TSource> first, IEnumerable<TSource> second) { return first.SequenceEqual(second, /* comparer */ null); } /// <summary> /// Determines whether two sequences are equal by comparing their /// elements by using a specified <see cref="IEqualityComparer{T}" />. /// </summary> public static bool SequenceEqual<TSource>( this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer) { CheckNotNull(first, "frist"); CheckNotNull(second, "second"); comparer = comparer ?? EqualityComparer<TSource>.Default; using (IEnumerator<TSource> lhs = first.GetEnumerator(), rhs = second.GetEnumerator()) { do { if (!lhs.MoveNext()) return !rhs.MoveNext(); if (!rhs.MoveNext()) return false; } while (comparer.Equals(lhs.Current, rhs.Current)); } return false; } /// <summary> /// Base implementation for Min/Max operator. /// </summary> private static TSource MinMaxImpl<TSource>( this IEnumerable<TSource> source, Func<TSource, TSource, bool> lesser) { CheckNotNull(source, "source"); Debug.Assert(lesser != null); return source.Aggregate((a, item) => lesser(a, item) ? a : item); } /// <summary> /// Base implementation for Min/Max operator for nullable types. /// </summary> private static TSource? MinMaxImpl<TSource>( this IEnumerable<TSource?> source, TSource? seed, Func<TSource?, TSource?, bool> lesser) where TSource : struct { CheckNotNull(source, "source"); Debug.Assert(lesser != null); return source.Aggregate(seed, (a, item) => lesser(a, item) ? a : item); // == MinMaxImpl(Repeat<TSource?>(null, 1).Concat(source), lesser); } /// <summary> /// Returns the minimum value in a generic sequence. /// </summary> public static TSource Min<TSource>( this IEnumerable<TSource> source) { var comparer = Comparer<TSource>.Default; return source.MinMaxImpl((x, y) => comparer.Compare(x, y) < 0); } /// <summary> /// Invokes a transform function on each element of a generic /// sequence and returns the minimum resulting value. /// </summary> public static TResult Min<TSource, TResult>( this IEnumerable<TSource> source, Func<TSource, TResult> selector) { return source.Select(selector).Min(); } /// <summary> /// Returns the maximum value in a generic sequence. /// </summary> public static TSource Max<TSource>( this IEnumerable<TSource> source) { var comparer = Comparer<TSource>.Default; return source.MinMaxImpl((x, y) => comparer.Compare(x, y) > 0); } /// <summary> /// Invokes a transform function on each element of a generic /// sequence and returns the maximum resulting value. /// </summary> public static TResult Max<TSource, TResult>( this IEnumerable<TSource> source, Func<TSource, TResult> selector) { return source.Select(selector).Max(); } /// <summary> /// Makes an enumerator seen as enumerable once more. /// </summary> /// <remarks> /// The supplied enumerator must have been started. The first element /// returned is the element the enumerator was on when passed in. /// DO NOT use this method if the caller must be a generator. It is /// mostly safe among aggregate operations. /// </remarks> private static IEnumerable<T> Renumerable<T>(this IEnumerator<T> e) { Debug.Assert(e != null); do { yield return e.Current; } while (e.MoveNext()); } /// <summary> /// Sorts the elements of a sequence in ascending order according to a key. /// </summary> public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { return source.OrderBy(keySelector, /* comparer */ null); } /// <summary> /// Sorts the elements of a sequence in ascending order by using a /// specified comparer. /// </summary> public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer) { CheckNotNull(source, "source"); CheckNotNull(keySelector, "keySelector"); return new OrderedEnumerable<TSource, TKey>(source, keySelector, comparer, /* descending */ false); } /// <summary> /// Sorts the elements of a sequence in descending order according to a key. /// </summary> public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { return source.OrderByDescending(keySelector, /* comparer */ null); } /// <summary> /// Sorts the elements of a sequence in descending order by using a /// specified comparer. /// </summary> public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer) { CheckNotNull(source, "source"); CheckNotNull(source, "keySelector"); return new OrderedEnumerable<TSource, TKey>(source, keySelector, comparer, /* descending */ true); } /// <summary> /// Performs a subsequent ordering of the elements in a sequence in /// ascending order according to a key. /// </summary> public static IOrderedEnumerable<TSource> ThenBy<TSource, TKey>( this IOrderedEnumerable<TSource> source, Func<TSource, TKey> keySelector) { return source.ThenBy(keySelector, /* comparer */ null); } /// <summary> /// Performs a subsequent ordering of the elements in a sequence in /// ascending order by using a specified comparer. /// </summary> public static IOrderedEnumerable<TSource> ThenBy<TSource, TKey>( this IOrderedEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer) { CheckNotNull(source, "source"); return source.CreateOrderedEnumerable(keySelector, comparer, /* descending */ false); } /// <summary> /// Performs a subsequent ordering of the elements in a sequence in /// descending order, according to a key. /// </summary> public static IOrderedEnumerable<TSource> ThenByDescending<TSource, TKey>( this IOrderedEnumerable<TSource> source, Func<TSource, TKey> keySelector) { return source.ThenByDescending(keySelector, /* comparer */ null); } /// <summary> /// Performs a subsequent ordering of the elements in a sequence in /// descending order by using a specified comparer. /// </summary> public static IOrderedEnumerable<TSource> ThenByDescending<TSource, TKey>( this IOrderedEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer) { CheckNotNull(source, "source"); return source.CreateOrderedEnumerable(keySelector, comparer, /* descending */ true); } /// <summary> /// Base implementation for Intersect and Except operators. /// </summary> private static IEnumerable<TSource> IntersectExceptImpl<TSource>( this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer, bool flag) { CheckNotNull(first, "first"); CheckNotNull(second, "second"); var keys = new List<TSource>(); var flags = new Dictionary<TSource, bool>(comparer); foreach (var item in first.Where(k => !flags.ContainsKey(k))) { flags.Add(item, !flag); keys.Add(item); } foreach (var item in second.Where(flags.ContainsKey)) flags[item] = flag; // // As per docs, "the marked elements are yielded in the order in // which they were collected. // return keys.Where(item => flags[item]); } /// <summary> /// Produces the set intersection of two sequences by using the /// default equality comparer to compare values. /// </summary> public static IEnumerable<TSource> Intersect<TSource>( this IEnumerable<TSource> first, IEnumerable<TSource> second) { return first.Intersect(second, /* comparer */ null); } /// <summary> /// Produces the set intersection of two sequences by using the /// specified <see cref="IEqualityComparer{T}" /> to compare values. /// </summary> public static IEnumerable<TSource> Intersect<TSource>( this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer) { return IntersectExceptImpl(first, second, comparer, /* flag */ true); } /// <summary> /// Produces the set difference of two sequences by using the /// default equality comparer to compare values. /// </summary> public static IEnumerable<TSource> Except<TSource>( this IEnumerable<TSource> first, IEnumerable<TSource> second) { return first.Except(second, /* comparer */ null); } /// <summary> /// Produces the set difference of two sequences by using the /// specified <see cref="IEqualityComparer{T}" /> to compare values. /// </summary> public static IEnumerable<TSource> Except<TSource>( this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer) { return IntersectExceptImpl(first, second, comparer, /* flag */ false); } /// <summary> /// Creates a <see cref="Dictionary{TKey,TValue}" /> from an /// <see cref="IEnumerable{T}" /> according to a specified key /// selector function. /// </summary> public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { return source.ToDictionary(keySelector, /* comparer */ null); } /// <summary> /// Creates a <see cref="Dictionary{TKey,TValue}" /> from an /// <see cref="IEnumerable{T}" /> according to a specified key /// selector function and key comparer. /// </summary> public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer) { return source.ToDictionary(keySelector, e => e); } /// <summary> /// Creates a <see cref="Dictionary{TKey,TValue}" /> from an /// <see cref="IEnumerable{T}" /> according to specified key /// selector and element selector functions. /// </summary> public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector) { return source.ToDictionary(keySelector, elementSelector, /* comparer */ null); } /// <summary> /// Creates a <see cref="Dictionary{TKey,TValue}" /> from an /// <see cref="IEnumerable{T}" /> according to a specified key /// selector function, a comparer, and an element selector function. /// </summary> public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer) { CheckNotNull(source, "source"); CheckNotNull(keySelector, "keySelector"); CheckNotNull(elementSelector, "elementSelector"); var dict = new Dictionary<TKey, TElement>(comparer); foreach (var item in source) { // // ToDictionary is meant to throw ArgumentNullException if // keySelector produces a key that is null and // Argument exception if keySelector produces duplicate keys // for two elements. Incidentally, the doucmentation for // IDictionary<TKey, TValue>.Add says that the Add method // throws the same exceptions under the same circumstances // so we don't need to do any additional checking or work // here and let the Add implementation do all the heavy // lifting. // dict.Add(keySelector(item), elementSelector(item)); } return dict; } /// <summary> /// Correlates the elements of two sequences based on matching keys. /// The default equality comparer is used to compare keys. /// </summary> public static IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>( this IEnumerable<TOuter> outer, IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, TInner, TResult> resultSelector) { return outer.Join(inner, outerKeySelector, innerKeySelector, resultSelector, /* comparer */ null); } /// <summary> /// Correlates the elements of two sequences based on matching keys. /// The default equality comparer is used to compare keys. A /// specified <see cref="IEqualityComparer{T}" /> is used to compare keys. /// </summary> public static IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>( this IEnumerable<TOuter> outer, IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, TInner, TResult> resultSelector, IEqualityComparer<TKey> comparer) { CheckNotNull(outer, "outer"); CheckNotNull(inner, "inner"); CheckNotNull(outerKeySelector, "outerKeySelector"); CheckNotNull(innerKeySelector, "innerKeySelector"); CheckNotNull(resultSelector, "resultSelector"); var lookup = inner.ToLookup(innerKeySelector, comparer); return from o in outer from i in lookup[outerKeySelector(o)] select resultSelector(o, i); } /// <summary> /// Correlates the elements of two sequences based on equality of /// keys and groups the results. The default equality comparer is /// used to compare keys. /// </summary> public static IEnumerable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>( this IEnumerable<TOuter> outer, IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, IEnumerable<TInner>, TResult> resultSelector) { return outer.GroupJoin(inner, outerKeySelector, innerKeySelector, resultSelector, /* comparer */ null); } /// <summary> /// Correlates the elements of two sequences based on equality of /// keys and groups the results. The default equality comparer is /// used to compare keys. A specified <see cref="IEqualityComparer{T}" /> /// is used to compare keys. /// </summary> public static IEnumerable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>( this IEnumerable<TOuter> outer, IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, IEnumerable<TInner>, TResult> resultSelector, IEqualityComparer<TKey> comparer) { CheckNotNull(outer, "outer"); CheckNotNull(inner, "inner"); CheckNotNull(outerKeySelector, "outerKeySelector"); CheckNotNull(innerKeySelector, "innerKeySelector"); CheckNotNull(resultSelector, "resultSelector"); var lookup = inner.ToLookup(innerKeySelector, comparer); return outer.Select(o => resultSelector(o, lookup[outerKeySelector(o)])); } [DebuggerStepThrough] private static void CheckNotNull<T>(T value, string name) where T : class { if (value == null) throw new ArgumentNullException(name); } private static class Sequence<T> { public static readonly IEnumerable<T> Empty = new T[0]; } private sealed class Grouping<K, V> : List<V>, IGrouping<K, V> { internal Grouping(K key) { Key = key; } public K Key { get; private set; } } } internal partial class Enumerable { /// <summary> /// Computes the sum of a sequence of nullable <see cref="System.Int32" /> values. /// </summary> public static int Sum( this IEnumerable<int> source) { CheckNotNull(source, "source"); int sum = 0; foreach (var num in source) sum = checked(sum + num); return sum; } /// <summary> /// Computes the sum of a sequence of nullable <see cref="System.Int32" /> /// values that are obtained by invoking a transform function on /// each element of the input sequence. /// </summary> public static int Sum<TSource>( this IEnumerable<TSource> source, Func<TSource, int> selector) { return source.Select(selector).Sum(); } /// <summary> /// Computes the average of a sequence of nullable <see cref="System.Int32" /> values. /// </summary> public static double Average( this IEnumerable<int> source) { CheckNotNull(source, "source"); long sum = 0; long count = 0; foreach (var num in source) checked { sum += (int) num; count++; } if (count == 0) throw new InvalidOperationException(); return (double) sum/count; } /// <summary> /// Computes the average of a sequence of nullable <see cref="System.Int32" /> values /// that are obtained by invoking a transform function on each /// element of the input sequence. /// </summary> public static double Average<TSource>( this IEnumerable<TSource> source, Func<TSource, int> selector) { return source.Select(selector).Average(); } /// <summary> /// Computes the sum of a sequence of <see cref="System.Int32" /> values. /// </summary> public static int? Sum( this IEnumerable<int?> source) { CheckNotNull(source, "source"); int sum = 0; foreach (var num in source) sum = checked(sum + (num ?? 0)); return sum; } /// <summary> /// Computes the sum of a sequence of <see cref="System.Int32" /> /// values that are obtained by invoking a transform function on /// each element of the input sequence. /// </summary> public static int? Sum<TSource>( this IEnumerable<TSource> source, Func<TSource, int?> selector) { return source.Select(selector).Sum(); } /// <summary> /// Computes the average of a sequence of <see cref="System.Int32" /> values. /// </summary> public static double? Average( this IEnumerable<int?> source) { CheckNotNull(source, "source"); long sum = 0; long count = 0; foreach (var num in source.Where(n => n != null)) checked { sum += (int) num; count++; } if (count == 0) return null; return (double?) sum/count; } /// <summary> /// Computes the average of a sequence of <see cref="System.Int32" /> values /// that are obtained by invoking a transform function on each /// element of the input sequence. /// </summary> public static double? Average<TSource>( this IEnumerable<TSource> source, Func<TSource, int?> selector) { return source.Select(selector).Average(); } /// <summary> /// Returns the minimum value in a sequence of nullable /// <see cref="System.Int32" /> values. /// </summary> public static int? Min( this IEnumerable<int?> source) { CheckNotNull(source, "source"); return MinMaxImpl(source.Where(x => x != null), null, (min, x) => min < x); } /// <summary> /// Invokes a transform function on each element of a sequence and /// returns the minimum nullable <see cref="System.Int32" /> value. /// </summary> public static int? Min<TSource>( this IEnumerable<TSource> source, Func<TSource, int?> selector) { return source.Select(selector).Min(); } /// <summary> /// Returns the maximum value in a sequence of nullable /// <see cref="System.Int32" /> values. /// </summary> public static int? Max( this IEnumerable<int?> source) { CheckNotNull(source, "source"); return MinMaxImpl(source.Where(x => x != null), null, (max, x) => x == null || (max != null && x.Value < max.Value)); } /// <summary> /// Invokes a transform function on each element of a sequence and /// returns the maximum nullable <see cref="System.Int32" /> value. /// </summary> public static int? Max<TSource>( this IEnumerable<TSource> source, Func<TSource, int?> selector) { return source.Select(selector).Max(); } /// <summary> /// Computes the sum of a sequence of nullable <see cref="System.Int64" /> values. /// </summary> public static long Sum( this IEnumerable<long> source) { CheckNotNull(source, "source"); long sum = 0; foreach (var num in source) sum = checked(sum + num); return sum; } /// <summary> /// Computes the sum of a sequence of nullable <see cref="System.Int64" /> /// values that are obtained by invoking a transform function on /// each element of the input sequence. /// </summary> public static long Sum<TSource>( this IEnumerable<TSource> source, Func<TSource, long> selector) { return source.Select(selector).Sum(); } /// <summary> /// Computes the average of a sequence of nullable <see cref="System.Int64" /> values. /// </summary> public static double Average( this IEnumerable<long> source) { CheckNotNull(source, "source"); long sum = 0; long count = 0; foreach (var num in source) checked { sum += (long) num; count++; } if (count == 0) throw new InvalidOperationException(); return (double) sum/count; } /// <summary> /// Computes the average of a sequence of nullable <see cref="System.Int64" /> values /// that are obtained by invoking a transform function on each /// element of the input sequence. /// </summary> public static double Average<TSource>( this IEnumerable<TSource> source, Func<TSource, long> selector) { return source.Select(selector).Average(); } /// <summary> /// Computes the sum of a sequence of <see cref="System.Int64" /> values. /// </summary> public static long? Sum( this IEnumerable<long?> source) { CheckNotNull(source, "source"); long sum = 0; foreach (var num in source) sum = checked(sum + (num ?? 0)); return sum; } /// <summary> /// Computes the sum of a sequence of <see cref="System.Int64" /> /// values that are obtained by invoking a transform function on /// each element of the input sequence. /// </summary> public static long? Sum<TSource>( this IEnumerable<TSource> source, Func<TSource, long?> selector) { return source.Select(selector).Sum(); } /// <summary> /// Computes the average of a sequence of <see cref="System.Int64" /> values. /// </summary> public static double? Average( this IEnumerable<long?> source) { CheckNotNull(source, "source"); long sum = 0; long count = 0; foreach (var num in source.Where(n => n != null)) checked { sum += (long) num; count++; } if (count == 0) return null; return (double?) sum/count; } /// <summary> /// Computes the average of a sequence of <see cref="System.Int64" /> values /// that are obtained by invoking a transform function on each /// element of the input sequence. /// </summary> public static double? Average<TSource>( this IEnumerable<TSource> source, Func<TSource, long?> selector) { return source.Select(selector).Average(); } /// <summary> /// Returns the minimum value in a sequence of nullable /// <see cref="System.Int64" /> values. /// </summary> public static long? Min( this IEnumerable<long?> source) { CheckNotNull(source, "source"); return MinMaxImpl(source.Where(x => x != null), null, (min, x) => min < x); } /// <summary> /// Invokes a transform function on each element of a sequence and /// returns the minimum nullable <see cref="System.Int64" /> value. /// </summary> public static long? Min<TSource>( this IEnumerable<TSource> source, Func<TSource, long?> selector) { return source.Select(selector).Min(); } /// <summary> /// Returns the maximum value in a sequence of nullable /// <see cref="System.Int64" /> values. /// </summary> public static long? Max( this IEnumerable<long?> source) { CheckNotNull(source, "source"); return MinMaxImpl(source.Where(x => x != null), null, (max, x) => x == null || (max != null && x.Value < max.Value)); } /// <summary> /// Invokes a transform function on each element of a sequence and /// returns the maximum nullable <see cref="System.Int64" /> value. /// </summary> public static long? Max<TSource>( this IEnumerable<TSource> source, Func<TSource, long?> selector) { return source.Select(selector).Max(); } /// <summary> /// Computes the sum of a sequence of nullable <see cref="System.Single" /> values. /// </summary> public static float Sum( this IEnumerable<float> source) { CheckNotNull(source, "source"); float sum = 0; foreach (var num in source) sum = checked(sum + num); return sum; } /// <summary> /// Computes the sum of a sequence of nullable <see cref="System.Single" /> /// values that are obtained by invoking a transform function on /// each element of the input sequence. /// </summary> public static float Sum<TSource>( this IEnumerable<TSource> source, Func<TSource, float> selector) { return source.Select(selector).Sum(); } /// <summary> /// Computes the average of a sequence of nullable <see cref="System.Single" /> values. /// </summary> public static float Average( this IEnumerable<float> source) { CheckNotNull(source, "source"); float sum = 0; long count = 0; foreach (var num in source) checked { sum += (float) num; count++; } if (count == 0) throw new InvalidOperationException(); return (float) sum/count; } /// <summary> /// Computes the average of a sequence of nullable <see cref="System.Single" /> values /// that are obtained by invoking a transform function on each /// element of the input sequence. /// </summary> public static float Average<TSource>( this IEnumerable<TSource> source, Func<TSource, float> selector) { return source.Select(selector).Average(); } /// <summary> /// Computes the sum of a sequence of <see cref="System.Single" /> values. /// </summary> public static float? Sum( this IEnumerable<float?> source) { CheckNotNull(source, "source"); float sum = 0; foreach (var num in source) sum = checked(sum + (num ?? 0)); return sum; } /// <summary> /// Computes the sum of a sequence of <see cref="System.Single" /> /// values that are obtained by invoking a transform function on /// each element of the input sequence. /// </summary> public static float? Sum<TSource>( this IEnumerable<TSource> source, Func<TSource, float?> selector) { return source.Select(selector).Sum(); } /// <summary> /// Computes the average of a sequence of <see cref="System.Single" /> values. /// </summary> public static float? Average( this IEnumerable<float?> source) { CheckNotNull(source, "source"); float sum = 0; long count = 0; foreach (var num in source.Where(n => n != null)) checked { sum += (float) num; count++; } if (count == 0) return null; return (float?) sum/count; } /// <summary> /// Computes the average of a sequence of <see cref="System.Single" /> values /// that are obtained by invoking a transform function on each /// element of the input sequence. /// </summary> public static float? Average<TSource>( this IEnumerable<TSource> source, Func<TSource, float?> selector) { return source.Select(selector).Average(); } /// <summary> /// Returns the minimum value in a sequence of nullable /// <see cref="System.Single" /> values. /// </summary> public static float? Min( this IEnumerable<float?> source) { CheckNotNull(source, "source"); return MinMaxImpl(source.Where(x => x != null), null, (min, x) => min < x); } /// <summary> /// Invokes a transform function on each element of a sequence and /// returns the minimum nullable <see cref="System.Single" /> value. /// </summary> public static float? Min<TSource>( this IEnumerable<TSource> source, Func<TSource, float?> selector) { return source.Select(selector).Min(); } /// <summary> /// Returns the maximum value in a sequence of nullable /// <see cref="System.Single" /> values. /// </summary> public static float? Max( this IEnumerable<float?> source) { CheckNotNull(source, "source"); return MinMaxImpl(source.Where(x => x != null), null, (max, x) => x == null || (max != null && x.Value < max.Value)); } /// <summary> /// Invokes a transform function on each element of a sequence and /// returns the maximum nullable <see cref="System.Single" /> value. /// </summary> public static float? Max<TSource>( this IEnumerable<TSource> source, Func<TSource, float?> selector) { return source.Select(selector).Max(); } /// <summary> /// Computes the sum of a sequence of nullable <see cref="System.Double" /> values. /// </summary> public static double Sum( this IEnumerable<double> source) { CheckNotNull(source, "source"); double sum = 0; foreach (var num in source) sum = checked(sum + num); return sum; } /// <summary> /// Computes the sum of a sequence of nullable <see cref="System.Double" /> /// values that are obtained by invoking a transform function on /// each element of the input sequence. /// </summary> public static double Sum<TSource>( this IEnumerable<TSource> source, Func<TSource, double> selector) { return source.Select(selector).Sum(); } /// <summary> /// Computes the average of a sequence of nullable <see cref="System.Double" /> values. /// </summary> public static double Average( this IEnumerable<double> source) { CheckNotNull(source, "source"); double sum = 0; long count = 0; foreach (var num in source) checked { sum += (double) num; count++; } if (count == 0) throw new InvalidOperationException(); return (double) sum/count; } /// <summary> /// Computes the average of a sequence of nullable <see cref="System.Double" /> values /// that are obtained by invoking a transform function on each /// element of the input sequence. /// </summary> public static double Average<TSource>( this IEnumerable<TSource> source, Func<TSource, double> selector) { return source.Select(selector).Average(); } /// <summary> /// Computes the sum of a sequence of <see cref="System.Double" /> values. /// </summary> public static double? Sum( this IEnumerable<double?> source) { CheckNotNull(source, "source"); double sum = 0; foreach (var num in source) sum = checked(sum + (num ?? 0)); return sum; } /// <summary> /// Computes the sum of a sequence of <see cref="System.Double" /> /// values that are obtained by invoking a transform function on /// each element of the input sequence. /// </summary> public static double? Sum<TSource>( this IEnumerable<TSource> source, Func<TSource, double?> selector) { return source.Select(selector).Sum(); } /// <summary> /// Computes the average of a sequence of <see cref="System.Double" /> values. /// </summary> public static double? Average( this IEnumerable<double?> source) { CheckNotNull(source, "source"); double sum = 0; long count = 0; foreach (var num in source.Where(n => n != null)) checked { sum += (double) num; count++; } if (count == 0) return null; return (double?) sum/count; } /// <summary> /// Computes the average of a sequence of <see cref="System.Double" /> values /// that are obtained by invoking a transform function on each /// element of the input sequence. /// </summary> public static double? Average<TSource>( this IEnumerable<TSource> source, Func<TSource, double?> selector) { return source.Select(selector).Average(); } /// <summary> /// Returns the minimum value in a sequence of nullable /// <see cref="System.Double" /> values. /// </summary> public static double? Min( this IEnumerable<double?> source) { CheckNotNull(source, "source"); return MinMaxImpl(source.Where(x => x != null), null, (min, x) => min < x); } /// <summary> /// Invokes a transform function on each element of a sequence and /// returns the minimum nullable <see cref="System.Double" /> value. /// </summary> public static double? Min<TSource>( this IEnumerable<TSource> source, Func<TSource, double?> selector) { return source.Select(selector).Min(); } /// <summary> /// Returns the maximum value in a sequence of nullable /// <see cref="System.Double" /> values. /// </summary> public static double? Max( this IEnumerable<double?> source) { CheckNotNull(source, "source"); return MinMaxImpl(source.Where(x => x != null), null, (max, x) => x == null || (max != null && x.Value < max.Value)); } /// <summary> /// Invokes a transform function on each element of a sequence and /// returns the maximum nullable <see cref="System.Double" /> value. /// </summary> public static double? Max<TSource>( this IEnumerable<TSource> source, Func<TSource, double?> selector) { return source.Select(selector).Max(); } /// <summary> /// Computes the sum of a sequence of nullable <see cref="System.Decimal" /> values. /// </summary> public static decimal Sum( this IEnumerable<decimal> source) { CheckNotNull(source, "source"); decimal sum = 0; foreach (var num in source) sum = checked(sum + num); return sum; } /// <summary> /// Computes the sum of a sequence of nullable <see cref="System.Decimal" /> /// values that are obtained by invoking a transform function on /// each element of the input sequence. /// </summary> public static decimal Sum<TSource>( this IEnumerable<TSource> source, Func<TSource, decimal> selector) { return source.Select(selector).Sum(); } /// <summary> /// Computes the average of a sequence of nullable <see cref="System.Decimal" /> values. /// </summary> public static decimal Average( this IEnumerable<decimal> source) { CheckNotNull(source, "source"); decimal sum = 0; long count = 0; foreach (var num in source) checked { sum += (decimal) num; count++; } if (count == 0) throw new InvalidOperationException(); return (decimal) sum/count; } /// <summary> /// Computes the average of a sequence of nullable <see cref="System.Decimal" /> values /// that are obtained by invoking a transform function on each /// element of the input sequence. /// </summary> public static decimal Average<TSource>( this IEnumerable<TSource> source, Func<TSource, decimal> selector) { return source.Select(selector).Average(); } /// <summary> /// Computes the sum of a sequence of <see cref="System.Decimal" /> values. /// </summary> public static decimal? Sum( this IEnumerable<decimal?> source) { CheckNotNull(source, "source"); decimal sum = 0; foreach (var num in source) sum = checked(sum + (num ?? 0)); return sum; } /// <summary> /// Computes the sum of a sequence of <see cref="System.Decimal" /> /// values that are obtained by invoking a transform function on /// each element of the input sequence. /// </summary> public static decimal? Sum<TSource>( this IEnumerable<TSource> source, Func<TSource, decimal?> selector) { return source.Select(selector).Sum(); } /// <summary> /// Computes the average of a sequence of <see cref="System.Decimal" /> values. /// </summary> public static decimal? Average( this IEnumerable<decimal?> source) { CheckNotNull(source, "source"); decimal sum = 0; long count = 0; foreach (var num in source.Where(n => n != null)) checked { sum += (decimal) num; count++; } if (count == 0) return null; return (decimal?) sum/count; } /// <summary> /// Computes the average of a sequence of <see cref="System.Decimal" /> values /// that are obtained by invoking a transform function on each /// element of the input sequence. /// </summary> public static decimal? Average<TSource>( this IEnumerable<TSource> source, Func<TSource, decimal?> selector) { return source.Select(selector).Average(); } /// <summary> /// Returns the minimum value in a sequence of nullable /// <see cref="System.Decimal" /> values. /// </summary> public static decimal? Min( this IEnumerable<decimal?> source) { CheckNotNull(source, "source"); return MinMaxImpl(source.Where(x => x != null), null, (min, x) => min < x); } /// <summary> /// Invokes a transform function on each element of a sequence and /// returns the minimum nullable <see cref="System.Decimal" /> value. /// </summary> public static decimal? Min<TSource>( this IEnumerable<TSource> source, Func<TSource, decimal?> selector) { return source.Select(selector).Min(); } /// <summary> /// Returns the maximum value in a sequence of nullable /// <see cref="System.Decimal" /> values. /// </summary> public static decimal? Max( this IEnumerable<decimal?> source) { CheckNotNull(source, "source"); return MinMaxImpl(source.Where(x => x != null), null, (max, x) => x == null || (max != null && x.Value < max.Value)); } /// <summary> /// Invokes a transform function on each element of a sequence and /// returns the maximum nullable <see cref="System.Decimal" /> value. /// </summary> public static decimal? Max<TSource>( this IEnumerable<TSource> source, Func<TSource, decimal?> selector) { return source.Select(selector).Max(); } } /// <summary> /// Represents a collection of objects that have a common key. /// </summary> internal partial interface IGrouping<TKey, TElement> : IEnumerable<TElement> { /// <summary> /// Gets the key of the <see cref="IGrouping{TKey,TElement}" />. /// </summary> TKey Key { get; } } /// <summary> /// Defines an indexer, size property, and Boolean search method for /// data structures that map keys to <see cref="IEnumerable{T}"/> /// sequences of values. /// </summary> internal partial interface ILookup<TKey, TElement> : IEnumerable<IGrouping<TKey, TElement>> { bool Contains(TKey key); int Count { get; } IEnumerable<TElement> this[TKey key] { get; } } /// <summary> /// Represents a sorted sequence. /// </summary> internal partial interface IOrderedEnumerable<TElement> : IEnumerable<TElement> { /// <summary> /// Performs a subsequent ordering on the elements of an /// <see cref="IOrderedEnumerable{T}"/> according to a key. /// </summary> IOrderedEnumerable<TElement> CreateOrderedEnumerable<TKey>( Func<TElement, TKey> keySelector, IComparer<TKey> comparer, bool descending); } /// <summary> /// Represents a collection of keys each mapped to one or more values. /// </summary> internal sealed class Lookup<TKey, TElement> : ILookup<TKey, TElement> { private readonly Dictionary<TKey, IGrouping<TKey, TElement>> _map; internal Lookup(IEqualityComparer<TKey> comparer) { _map = new Dictionary<TKey, IGrouping<TKey, TElement>>(comparer); } internal void Add(IGrouping<TKey, TElement> item) { _map.Add(item.Key, item); } internal IEnumerable<TElement> Find(TKey key) { IGrouping<TKey, TElement> grouping; return _map.TryGetValue(key, out grouping) ? grouping : null; } /// <summary> /// Gets the number of key/value collection pairs in the <see cref="Lookup{TKey,TElement}" />. /// </summary> public int Count { get { return _map.Count; } } /// <summary> /// Gets the collection of values indexed by the specified key. /// </summary> public IEnumerable<TElement> this[TKey key] { get { IGrouping<TKey, TElement> result; return _map.TryGetValue(key, out result) ? result : Enumerable.Empty<TElement>(); } } /// <summary> /// Determines whether a specified key is in the <see cref="Lookup{TKey,TElement}" />. /// </summary> public bool Contains(TKey key) { return _map.ContainsKey(key); } /// <summary> /// Applies a transform function to each key and its associated /// values and returns the results. /// </summary> public IEnumerable<TResult> ApplyResultSelector<TResult>( Func<TKey, IEnumerable<TElement>, TResult> resultSelector) { if (resultSelector == null) throw new ArgumentNullException("resultSelector"); foreach (var pair in _map) yield return resultSelector(pair.Key, pair.Value); } /// <summary> /// Returns a generic enumerator that iterates through the <see cref="Lookup{TKey,TElement}" />. /// </summary> public IEnumerator<IGrouping<TKey, TElement>> GetEnumerator() { return _map.Values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal sealed class OrderedEnumerable<T, K> : IOrderedEnumerable<T> { private readonly IEnumerable<T> _source; private readonly List<Comparison<T>> _comparisons; public OrderedEnumerable(IEnumerable<T> source, Func<T, K> keySelector, IComparer<K> comparer, bool descending) : this(source, null, keySelector, comparer, descending) { } private OrderedEnumerable(IEnumerable<T> source, List<Comparison<T>> comparisons, Func<T, K> keySelector, IComparer<K> comparer, bool descending) { if (source == null) throw new ArgumentNullException("source"); if (keySelector == null) throw new ArgumentNullException("keySelector"); _source = source; comparer = comparer ?? Comparer<K>.Default; if (comparisons == null) comparisons = new List<Comparison<T>>( /* capacity */ 4); comparisons.Add((x, y) => (descending ? -1 : 1)*comparer.Compare(keySelector(x), keySelector(y))); _comparisons = comparisons; } public IOrderedEnumerable<T> CreateOrderedEnumerable<KK>( Func<T, KK> keySelector, IComparer<KK> comparer, bool descending) { return new OrderedEnumerable<T, KK>(_source, _comparisons, keySelector, comparer, descending); } public IEnumerator<T> GetEnumerator() { // // We sort using List<T>.Sort, but docs say that it performs an // unstable sort. LINQ, on the other hand, says OrderBy performs // a stable sort. So convert the source sequence into a sequence // of tuples where the second element tags the position of the // element from the source sequence (First). The position is // then used as a tie breaker when all keys compare equal, // thus making the sort stable. // var list = _source.Select(new Func<T, int, Tuple<T, int>>(TagPosition)).ToList(); list.Sort((x, y) => { // // Compare keys from left to right. // var comparisons = _comparisons; for (var i = 0; i < comparisons.Count; i++) { var result = comparisons[i](x.First, y.First); if (result != 0) return result; } // // All keys compared equal so now break the tie by their // position in the original sequence, making the sort stable. // return x.Second.CompareTo(y.Second); }); return list.Select(new Func<Tuple<T, int>, T>(GetFirst)).GetEnumerator(); } /// <remarks> /// See <a href="http://code.google.com/p/linqbridge/issues/detail?id=11">issue #11</a> /// for why this method is needed and cannot be expressed as a /// lambda at the call site. /// </remarks> private static Tuple<T, int> TagPosition(T e, int i) { return new Tuple<T, int>(e, i); } /// <remarks> /// See <a href="http://code.google.com/p/linqbridge/issues/detail?id=11">issue #11</a> /// for why this method is needed and cannot be expressed as a /// lambda at the call site. /// </remarks> private static T GetFirst(Tuple<T, int> pv) { return pv.First; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [Serializable] internal struct Tuple<TFirst, TSecond> : IEquatable<Tuple<TFirst, TSecond>> { public TFirst First { get; private set; } public TSecond Second { get; private set; } public Tuple(TFirst first, TSecond second) : this() { First = first; Second = second; } public override bool Equals(object obj) { return obj != null && obj is Tuple<TFirst, TSecond> && base.Equals((Tuple<TFirst, TSecond>) obj); } public bool Equals(Tuple<TFirst, TSecond> other) { return EqualityComparer<TFirst>.Default.Equals(other.First, First) && EqualityComparer<TSecond>.Default.Equals(other.Second, Second); } public override int GetHashCode() { var num = 0x7a2f0b42; num = (-1521134295*num) + EqualityComparer<TFirst>.Default.GetHashCode(First); return (-1521134295*num) + EqualityComparer<TSecond>.Default.GetHashCode(Second); } public override string ToString() { return string.Format(CultureInfo.InvariantCulture, @"{{ First = {0}, Second = {1} }}", First, Second); } } } namespace Medivh.Json.Serialization { #pragma warning disable 1591 public delegate TResult Func<TResult>(); public delegate TResult Func<T, TResult>(T a); public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2); public delegate TResult Func<T1, T2, T3, TResult>(T1 arg1, T2 arg2, T3 arg3); public delegate TResult Func<T1, T2, T3, T4, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4); public delegate void Action(); public delegate void Action<T1, T2>(T1 arg1, T2 arg2); public delegate void Action<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3); public delegate void Action<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4); #pragma warning restore 1591 } namespace System.Runtime.CompilerServices { /// <remarks> /// This attribute allows us to define extension methods without /// requiring .NET Framework 3.5. For more information, see the section, /// <a href="http://msdn.microsoft.com/en-us/magazine/cc163317.aspx#S7">Extension Methods in .NET Framework 2.0 Apps</a>, /// of <a href="http://msdn.microsoft.com/en-us/magazine/cc163317.aspx">Basic Instincts: Extension Methods</a> /// column in <a href="http://msdn.microsoft.com/msdnmag/">MSDN Magazine</a>, /// issue <a href="http://msdn.microsoft.com/en-us/magazine/cc135410.aspx">Nov 2007</a>. /// </remarks> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)] internal sealed class ExtensionAttribute : Attribute { } } #endif
29.158593
123
0.622127
[ "Apache-2.0" ]
larrymshi/medivh.client-csharp
src/Medivh/Json/Utilities/LinqBridge.cs
87,886
C#
// ReSharper disable once IdentifierTypo namespace Kingdom.Protobuf { /// <inheritdoc /> public class RangesReservedStatement : ReservedStatement<RangeDescriptor> { /// <inheritdoc /> protected override string RenderItem(RangeDescriptor item, IStringRenderingOptions options) => $"{item.ToDescriptorString(options)}"; } }
30.583333
99
0.694823
[ "Apache-2.0" ]
mwpowellhtx/Kingdom.Protobuf
src/Kingdom.Protobuf.Descriptors/Implementation/RangesReservedStatement.cs
369
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. // LICENSE: https://github.com/dotnet/wpf/blob/main/LICENSE.TXT // REF: https://github.com/dotnet/wpf/blob/v6.0.0-rtm.21523.1/src/Microsoft.DotNet.Wpf/src/Shared/MS/Internal/DoubleUtil.cs using System; using System.Windows; namespace WpfCoreTools { /// <summary> /// Provides "fuzzy" comparison functionality for doubles and some common double-based classes and structs. /// </summary> public static class MathUtils { /// <summary> /// The smallest <see cref="double"/> such that <b>1.0 + DOUBLE_EPSILON != 1.0</b>. /// </summary> /// <remarks> /// This value comes from <see langword="sdk\inc\crt\float.h"/>. /// </remarks> public const double DOUBLE_EPSILON = 2.2204460492503131e-016; /// <summary> /// Returns whether or not two <see cref="double"/> are close. /// </summary> /// <param name="value1">The first <see cref="double"/> to compare.</param> /// <param name="value2">The second <see cref="double"/> to compare.</param> /// <returns> /// <see langword="true"/> if the two <see cref="double"/> are close, otherwise <see langword="false"/>. /// </returns> /// <remarks> /// That is, whether or not they are within epsilon of each other. /// Note that this epsilon is proportional to the numbers themselves to that <see cref="AreClose(double, double)"/> /// survives scalar multiplication. /// There are plenty of ways for this to return <see langword="false"/> even for numbers which /// are theoretically identical, so no code calling this should fail to work if this returns <see langword="false"/>. /// <b>This should be used for optimizations only</b>. /// </remarks> public static bool AreClose(double value1, double value2) { if (value1 == value2) return true; double eps = (Math.Abs(value1) + Math.Abs(value2) + 10.0) * DOUBLE_EPSILON; double delta = value1 - value2; return (-eps < delta) && (eps > delta); } /// <summary> /// Returns whether or not the first <see cref="double"/> is less than the second <see cref="double"/>. /// </summary> /// <param name="value1">The first <see cref="double"/> to compare.</param> /// <param name="value2">The second <see cref="double"/> to compare.</param> /// <returns> /// <see langword="true"/> if the first <see cref="double"/> is less than the second <see cref="double"/>, /// otherwise <see langword="false"/>. /// bool - the result of the LessThan comparision. /// </returns> /// <remarks> /// That is, whether or not the first is strictly less than and not within epsilon of the other number. /// Note that this epsilon is proportional to the numbers themselves to that <see cref="AreClose(double, double)"/> /// survives scalar multiplication. /// There are plenty of ways for this to return <see langword="false"/> even for numbers which /// are theoretically identical, so no code calling this should fail to work if this returns <see langword="false"/>. /// <b>This should be used for optimizations only</b>. /// </remarks> public static bool LessThan(double value1, double value2) => (value1 < value2) && !AreClose(value1, value2); /// <summary> /// Returns whether or not the first <see cref="double"/> is greater than the second <see cref="double"/>. /// </summary> /// <param name="value1">The first <see cref="double"/> to compare.</param> /// <param name="value2">The second <see cref="double"/> to compare.</param> /// <returns> /// <see langword="true"/> if the first <see cref="double"/> is greater than the second <see cref="double"/>, /// otherwise <see langword="false"/>. /// </returns> /// <remarks> /// That is, whether or not the first is strictly greater than and not within epsilon of the other number. /// Note that this epsilon is proportional to the numbers themselves to that <see cref="AreClose(double, double)"/> /// survives scalar multiplication. /// There are plenty of ways for this to return <see langword="false"/> even for numbers which /// are theoretically identical, so no code calling this should fail to work if this returns <see langword="false"/>. /// <b>This should be used for optimizations only</b>. /// </remarks> public static bool GreaterThan(double value1, double value2) => (value1 > value2) && !AreClose(value1, value2); /// <summary> /// Returns whether or not the first <see cref="double"/> is less than or close to the second <see cref="double"/>. /// </summary> /// <param name="value1">The first <see cref="double"/> to compare.</param> /// <param name="value2">The second <see cref="double"/> to compare.</param> /// <returns> /// <see langword="true"/> if the first <see cref="double"/> is less than or close to the second <see cref="double"/>, /// otherwise <see langword="false"/>. /// </returns> /// <remarks> /// That is, whether or not the first is strictly less than or within epsilon of the other number. /// Note that this epsilon is proportional to the numbers themselves to that <see cref="AreClose(double, double)"/> /// survives scalar multiplication. /// There are plenty of ways for this to return <see langword="false"/> even for numbers which /// are theoretically identical, so no code calling this should fail to work if this returns <see langword="false"/>. /// <b>This should be used for optimizations only</b>. /// </remarks> public static bool LessThanOrClose(double value1, double value2) => (value1 < value2) || AreClose(value1, value2); /// <summary> /// Returns whether or not the first <see cref="double"/> is greater than or close to the second <see cref="double"/>. /// </summary> /// <param name="value1">The first <see cref="double"/> to compare.</param> /// <param name="value2">The second <see cref="double"/> to compare.</param> /// <returns> /// <see langword="true"/> if the first <see cref="double"/> is greater than or close to the second <see cref="double"/>, /// otherwise <see langword="false"/>. /// </returns> /// <remarks> /// That is, whether or not the first is strictly greater than or within epsilon of the other number. /// Note that this epsilon is proportional to the numbers themselves to that <see cref="AreClose(double, double)"/> /// survives scalar multiplication. /// There are plenty of ways for this to return <see langword="false"/> even for numbers which /// are theoretically identical, so no code calling this should fail to work if this returns <see langword="false"/>. /// <b>This should be used for optimizations only</b>. /// </remarks> public static bool GreaterThanOrClose(double value1, double value2) => (value1 > value2) || AreClose(value1, value2); /// <summary> /// Returns whether or not the <see cref="double"/> is close to 1. /// </summary> /// <param name="value">The <see cref="double"/> to compare to 1.</param> /// <returns> /// <see langword="true"/> the <see cref="double"/> is close to 1, otherwise <see langword="false"/>. /// </returns> public static bool IsOne(double value) => Math.Abs(value - 1.0) < 10.0 * DOUBLE_EPSILON; /// <summary> /// Returns whether or not the <see cref="double"/> is close to 0. /// </summary> /// <param name="value">The <see cref="double"/> to compare to 0.</param> /// <returns> /// <see langword="true"/> the <see cref="double"/> is close to 0, otherwise <see langword="false"/>. /// </returns> public static bool IsZero(double value) => Math.Abs(value) < 10.0 * DOUBLE_EPSILON; /// <summary> /// Returns whether or not the <see cref="double"/> is between 0 and 1. /// </summary> /// <param name="value">The <see cref="double"/> to check.</param> /// <returns> /// <see langword="true"/> the <see cref="double"/> is between 0 and 1, otherwise <see langword="false"/>. /// </returns> public static bool IsBetweenZeroAndOne(double value) => GreaterThanOrClose(value, 0) && LessThanOrClose(value, 1); /// <summary> /// Compares two <see cref="Point"/> for fuzzy equality. /// </summary> /// <param name='point1'>The first <see cref="Point"/> to compare.</param> /// <param name='point2'>The second <see cref="Point"/> to compare.</param> /// <returns> /// <see langword="true"/> if the two <see cref="Point"/> are equal, otherwise <see langword="false"/>. /// </returns> /// <remarks> /// This function helps compensate for the fact that <see cref="double"/> values can /// acquire error when operated upon. /// </remarks> public static bool AreClose(Point point1, Point point2) => AreClose(point1.X, point2.X) && AreClose(point1.Y, point2.Y); /// <summary> /// Compares two <see cref="Size"/> for fuzzy equality. /// </summary> /// <param name='size1'>The first <see cref="Size"/> to compare.</param> /// <param name='size2'>The second <see cref="Size"/> to compare.</param> /// <returns> /// <see langword="true"/> if the two <see cref="Size"/> are equal, otherwise <see langword="false"/>. /// </returns> /// <remarks> /// This function helps compensate for the fact that <see cref="double"/> values can /// acquire error when operated upon. /// </remarks> public static bool AreClose(Size size1, Size size2) => AreClose(size1.Width, size2.Width) && AreClose(size1.Height, size2.Height); /// <summary> /// Compares two <see cref="Vector"/> for fuzzy equality. /// </summary> /// <param name='vector1'>The first <see cref="Vector"/> to compare.</param> /// <param name='vector2'>The second <see cref="Vector"/> to compare.</param> /// <returns> /// <see langword="true"/> if the two <see cref="Vector"/> are equal, otherwise <see langword="false"/>. /// </returns> /// <remarks> /// This function helps compensate for the fact that <see cref="double"/> values can /// acquire error when operated upon. /// </remarks> public static bool AreClose(Vector vector1, Vector vector2) => AreClose(vector1.X, vector2.X) && AreClose(vector1.Y, vector2.Y); /// <summary> /// Compares two <see cref="Rect"/> for fuzzy equality. /// </summary> /// <param name='rect1'>The first <see cref="Rect"/> to compare.</param> /// <param name='rect2'>The second <see cref="Rect"/> to compare.</param> /// <returns> /// <see langword="true"/> if the two <see cref="Rect"/> are equal, otherwise <see langword="false"/>. /// </returns> /// <remarks> /// This function helps compensate for the fact that <see cref="double"/> values can /// acquire error when operated upon. /// </remarks> public static bool AreClose(Rect rect1, Rect rect2) => rect1.IsEmpty ? rect2.IsEmpty : (!rect2.IsEmpty) && AreClose(rect1.X, rect2.X) && AreClose(rect1.Y, rect2.Y) && AreClose(rect1.Height, rect2.Height) && AreClose(rect1.Width, rect2.Width); } }
56.616822
138
0.599208
[ "MIT" ]
devpelux/wpfcoretools
WpfCoreTools/MathUtils.cs
12,118
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.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net.Http.Headers; using System.Net.Quic; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Net.Http.QPack; using System.Runtime.ExceptionServices; namespace System.Net.Http { [SupportedOSPlatform("windows")] [SupportedOSPlatform("linux")] [SupportedOSPlatform("macos")] internal sealed class Http3RequestStream : IHttpHeadersHandler, IAsyncDisposable, IDisposable { private readonly HttpRequestMessage _request; private Http3Connection _connection; private long _streamId = -1; // A stream does not have an ID until the first I/O against it. This gets set almost immediately following construction. private QuicStream _stream; private ArrayBuffer _sendBuffer; private readonly ReadOnlyMemory<byte>[] _gatheredSendBuffer = new ReadOnlyMemory<byte>[2]; private ArrayBuffer _recvBuffer; private TaskCompletionSource<bool>? _expect100ContinueCompletionSource; // True indicates we should send content (e.g. received 100 Continue). private bool _disposed; private CancellationTokenSource? _goawayCancellationSource; private CancellationToken _goawayCancellationToken; private CancellationTokenSource? _sendContentCts; // Allocated when we receive a :status header. private HttpResponseMessage? _response; // Header decoding. private QPackDecoder _headerDecoder; private HeaderState _headerState; private long _headerBudgetRemaining; /// <summary>Reusable array used to get the values for each header being written to the wire.</summary> private string[] _headerValues = Array.Empty<string>(); /// <summary>Any trailing headers.</summary> private List<(HeaderDescriptor name, string value)>? _trailingHeaders; // When reading response content, keep track of the number of bytes left in the current data frame. private long _responseDataPayloadRemaining; // When our request content has a precomputed length, it is sent over a single DATA frame. // Keep track of how much is remaining in that frame. private long _requestContentLengthRemaining; // For the precomputed length case, we need to add the DATA framing for the first write only. private bool _singleDataFrameWritten; public long StreamId { get => Volatile.Read(ref _streamId); set => Volatile.Write(ref _streamId, value); } public Http3RequestStream(HttpRequestMessage request, Http3Connection connection, QuicStream stream) { _request = request; _connection = connection; _stream = stream; _sendBuffer = new ArrayBuffer(initialSize: 64, usePool: true); _recvBuffer = new ArrayBuffer(initialSize: 64, usePool: true); _headerBudgetRemaining = connection.Pool.Settings._maxResponseHeadersLength * 1024L; // _maxResponseHeadersLength is in KiB. _headerDecoder = new QPackDecoder(maxHeadersLength: (int)Math.Min(int.MaxValue, _headerBudgetRemaining)); _goawayCancellationSource = new CancellationTokenSource(); _goawayCancellationToken = _goawayCancellationSource.Token; } public void Dispose() { if (!_disposed) { _disposed = true; AbortStream(); _stream.Dispose(); DisposeSyncHelper(); } } public async ValueTask DisposeAsync() { if (!_disposed) { _disposed = true; AbortStream(); await _stream.DisposeAsync().ConfigureAwait(false); DisposeSyncHelper(); } } private void DisposeSyncHelper() { _connection.RemoveStream(_stream); _sendBuffer.Dispose(); _recvBuffer.Dispose(); // Dispose() might be called concurrently with GoAway(), we need to make sure to not Dispose/Cancel the CTS concurrently. Interlocked.Exchange(ref _goawayCancellationSource, null)?.Dispose(); } public void GoAway() { // Dispose() might be called concurrently with GoAway(), we need to make sure to not Dispose/Cancel the CTS concurrently. using CancellationTokenSource? cts = Interlocked.Exchange(ref _goawayCancellationSource, null); cts?.Cancel(); } public async Task<HttpResponseMessage> SendAsync(CancellationToken cancellationToken) { // If true, dispose the stream upon return. Will be set to false if we're duplex or returning content. bool disposeSelf = true; // Link the input token with _resetCancellationTokenSource, so cancellation will trigger on GoAway() or Abort(). using CancellationTokenSource requestCancellationSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _goawayCancellationToken); CancellationTokenRegistration sendContentCancellationRegistration = default; try { BufferHeaders(_request); // If using Expect 100 Continue, setup a TCS to wait to send content until we get a response. if (_request.HasHeaders && _request.Headers.ExpectContinue == true) { _expect100ContinueCompletionSource = new TaskCompletionSource<bool>(); } if (_expect100ContinueCompletionSource != null || _request.Content == null) { // Ideally, headers will be sent out in a gathered write inside of SendContentAsync(). // If we don't have content, or we are doing Expect 100 Continue, then we can't rely on // this and must send our headers immediately. // End the stream writing if there's no content to send, do it as part of the write so that the FIN flag isn't send in an empty QUIC frame. // Note that there's no need to call Shutdown separately since the FIN flag in the last write is the same thing. await FlushSendBufferAsync(endStream: _request.Content == null, requestCancellationSource.Token).ConfigureAwait(false); } Task sendContentTask; if (_request.Content != null) { // If using duplex content, the content will continue sending after this method completes. // So, only observe the cancellation token during this method. CancellationToken sendContentCancellationToken; if (requestCancellationSource.Token.CanBeCanceled) { _sendContentCts = new CancellationTokenSource(); sendContentCancellationToken = _sendContentCts.Token; sendContentCancellationRegistration = requestCancellationSource.Token.UnsafeRegister( static s => ((CancellationTokenSource)s!).Cancel(), _sendContentCts); } else { sendContentCancellationToken = default; } sendContentTask = SendContentAsync(_request.Content!, sendContentCancellationToken); } else { sendContentTask = Task.CompletedTask; } // In parallel, send content and read response. // Depending on Expect 100 Continue usage, one will depend on the other making progress. Task readResponseTask = ReadResponseAsync(requestCancellationSource.Token); bool sendContentObserved = false; // If we're not doing duplex, wait for content to finish sending here. // If we are doing duplex and have the unlikely event that it completes here, observe the result. // See Http2Connection.SendAsync for a full comment on this logic -- it is identical behavior. if (sendContentTask.IsCompleted || _request.Content?.AllowDuplex != true || await Task.WhenAny(sendContentTask, readResponseTask).ConfigureAwait(false) == sendContentTask || sendContentTask.IsCompleted) { try { await sendContentTask.ConfigureAwait(false); sendContentObserved = true; } catch { // Exceptions will be bubbled up from sendContentTask here, // which means the result of readResponseTask won't be observed directly: // Do a background await to log any exceptions. _connection.LogExceptions(readResponseTask); throw; } } else { // Duplex is being used, so we can't wait for content to finish sending. // Do a background await to log any exceptions. _connection.LogExceptions(sendContentTask); } // Wait for the response headers to be read. await readResponseTask.ConfigureAwait(false); // Now that we've received the response, we no longer need to observe GOAWAY. // Use an atomic exchange to avoid a race to Cancel()/Dispose(). Interlocked.Exchange(ref _goawayCancellationSource, null)?.Dispose(); Debug.Assert(_response != null && _response.Content != null); // Set our content stream. var responseContent = (HttpConnectionResponseContent)_response.Content; // If we have received Content-Length: 0 and have completed sending content (which may not be the case if duplex), // we can close our Http3RequestStream immediately and return a singleton empty content stream. Otherwise, we // need to return a Http3ReadStream which will be responsible for disposing the Http3RequestStream. bool useEmptyResponseContent = responseContent.Headers.ContentLength == 0 && sendContentObserved; if (useEmptyResponseContent) { // Drain the response frames to read any trailing headers. await DrainContentLength0Frames(requestCancellationSource.Token).ConfigureAwait(false); responseContent.SetStream(EmptyReadStream.Instance); } else { // A read stream is required to finish up the request. responseContent.SetStream(new Http3ReadStream(this)); } // Process any Set-Cookie headers. if (_connection.Pool.Settings._useCookies) { CookieHelper.ProcessReceivedCookies(_response, _connection.Pool.Settings._cookieContainer!); } // To avoid a circular reference (stream->response->content->stream), null out the stream's response. HttpResponseMessage response = _response; _response = null; // If we're 100% done with the stream, dispose. disposeSelf = useEmptyResponseContent; return response; } catch (QuicStreamAbortedException ex) when (ex.ErrorCode == (long)Http3ErrorCode.VersionFallback) { // The server is requesting us fall back to an older HTTP version. throw new HttpRequestException(SR.net_http_retry_on_older_version, ex, RequestRetryType.RetryOnLowerHttpVersion); } catch (QuicStreamAbortedException ex) when (ex.ErrorCode == (long)Http3ErrorCode.RequestRejected) { // The server is rejecting the request without processing it, retry it on a different connection. throw new HttpRequestException(SR.net_http_request_aborted, ex, RequestRetryType.RetryOnConnectionFailure); } catch (QuicStreamAbortedException ex) { // Our stream was reset. Exception? abortException = _connection.AbortException; throw new HttpRequestException(SR.net_http_client_execution_error, abortException ?? ex); } catch (QuicConnectionAbortedException ex) { // Our connection was reset. Start shutting down the connection. Exception abortException = _connection.Abort(ex); throw new HttpRequestException(SR.net_http_client_execution_error, abortException); } // It is possible for user's Content code to throw an unexpected OperationCanceledException. catch (OperationCanceledException ex) when (ex.CancellationToken == requestCancellationSource.Token || ex.CancellationToken == _sendContentCts?.Token) { // We're either observing GOAWAY, or the cancellationToken parameter has been canceled. if (cancellationToken.IsCancellationRequested) { _stream.AbortWrite((long)Http3ErrorCode.RequestCancelled); throw new OperationCanceledException(ex.Message, ex, cancellationToken); } else { Debug.Assert(_goawayCancellationToken.IsCancellationRequested == true); throw new HttpRequestException(SR.net_http_request_aborted, ex, RequestRetryType.RetryOnConnectionFailure); } } catch (Http3ConnectionException ex) { // A connection-level protocol error has occurred on our stream. _connection.Abort(ex); throw new HttpRequestException(SR.net_http_client_execution_error, ex); } catch (Exception ex) { _stream.AbortWrite((long)Http3ErrorCode.InternalError); if (ex is HttpRequestException) { throw; } throw new HttpRequestException(SR.net_http_client_execution_error, ex); } finally { sendContentCancellationRegistration.Dispose(); if (disposeSelf) { await DisposeAsync().ConfigureAwait(false); } } } /// <summary> /// Waits for the response headers to be read, and handles (Expect 100 etc.) informational statuses. /// </summary> private async Task ReadResponseAsync(CancellationToken cancellationToken) { Debug.Assert(_response == null); do { _headerState = HeaderState.StatusHeader; (Http3FrameType? frameType, long payloadLength) = await ReadFrameEnvelopeAsync(cancellationToken).ConfigureAwait(false); if (frameType != Http3FrameType.Headers) { if (NetEventSource.Log.IsEnabled()) { Trace($"Expected HEADERS as first response frame; received {frameType}."); } throw new HttpRequestException(SR.net_http_invalid_response); } await ReadHeadersAsync(payloadLength, cancellationToken).ConfigureAwait(false); Debug.Assert(_response != null); } while ((int)_response.StatusCode < 200); _headerState = HeaderState.TrailingHeaders; } private async Task SendContentAsync(HttpContent content, CancellationToken cancellationToken) { // If we're using Expect 100 Continue, wait to send content // until we get a response back or until our timeout elapses. if (_expect100ContinueCompletionSource != null) { Timer? timer = null; try { if (_connection.Pool.Settings._expect100ContinueTimeout != Timeout.InfiniteTimeSpan) { timer = new Timer(static o => ((Http3RequestStream)o!)._expect100ContinueCompletionSource!.TrySetResult(true), this, _connection.Pool.Settings._expect100ContinueTimeout, Timeout.InfiniteTimeSpan); } if (!await _expect100ContinueCompletionSource.Task.ConfigureAwait(false)) { // We received an error response code, so the body should not be sent. return; } } finally { if (timer != null) { await timer.DisposeAsync().ConfigureAwait(false); } } } // If we have a Content-Length, keep track of it so we don't over-send and so we can send in a single DATA frame. _requestContentLengthRemaining = content.Headers.ContentLength ?? -1; using (var writeStream = new Http3WriteStream(this)) { await content.CopyToAsync(writeStream, null, cancellationToken).ConfigureAwait(false); } // Set to 0 to recognize that the whole request body has been sent and therefore there's no need to abort write side in case of a premature disposal. _requestContentLengthRemaining = 0; if (_sendBuffer.ActiveLength != 0) { // Our initial send buffer, which has our headers, is normally sent out on the first write to the Http3WriteStream. // If we get here, it means the content didn't actually do any writing. Send out the headers now. // Also send the FIN flag, since this is the last write. No need to call Shutdown separately. await FlushSendBufferAsync(endStream: true, cancellationToken).ConfigureAwait(false); } else { _stream.Shutdown(); } } private async ValueTask WriteRequestContentAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken) { if (buffer.Length == 0) { return; } long remaining = _requestContentLengthRemaining; if (remaining != -1) { // This HttpContent had a precomputed length, and a DATA frame was written as part of the headers. We can write directly without framing. if (buffer.Length > _requestContentLengthRemaining) { string msg = SR.net_http_content_write_larger_than_content_length; throw new IOException(msg, new HttpRequestException(msg)); } _requestContentLengthRemaining -= buffer.Length; if (!_singleDataFrameWritten) { // Note we may not have sent headers yet; if so, _sendBuffer.ActiveLength will be > 0, and we will write them in a single write. // Because we have a Content-Length, we can write it in a single DATA frame. BufferFrameEnvelope(Http3FrameType.Data, remaining); _gatheredSendBuffer[0] = _sendBuffer.ActiveMemory; _gatheredSendBuffer[1] = buffer; await _stream.WriteAsync(_gatheredSendBuffer, cancellationToken).ConfigureAwait(false); _sendBuffer.Discard(_sendBuffer.ActiveLength); _singleDataFrameWritten = true; } else { // DATA frame already sent, send just the content buffer directly. await _stream.WriteAsync(buffer, cancellationToken).ConfigureAwait(false); } } else { // Variable-length content: write both a DATA frame and buffer. (and headers, which will still be in _sendBuffer if this is the first content write) // It's up to the HttpContent to give us sufficiently large writes to avoid excessively small DATA frames. BufferFrameEnvelope(Http3FrameType.Data, buffer.Length); _gatheredSendBuffer[0] = _sendBuffer.ActiveMemory; _gatheredSendBuffer[1] = buffer; await _stream.WriteAsync(_gatheredSendBuffer, cancellationToken).ConfigureAwait(false); _sendBuffer.Discard(_sendBuffer.ActiveLength); } } private async ValueTask FlushSendBufferAsync(bool endStream, CancellationToken cancellationToken) { await _stream.WriteAsync(_sendBuffer.ActiveMemory, endStream, cancellationToken).ConfigureAwait(false); _sendBuffer.Discard(_sendBuffer.ActiveLength); await _stream.FlushAsync(cancellationToken).ConfigureAwait(false); } private async ValueTask DrainContentLength0Frames(CancellationToken cancellationToken) { Http3FrameType? frameType; long payloadLength; while (true) { (frameType, payloadLength) = await ReadFrameEnvelopeAsync(cancellationToken).ConfigureAwait(false); switch (frameType) { case Http3FrameType.Headers: // Pick up any trailing headers. _trailingHeaders = new List<(HeaderDescriptor name, string value)>(); await ReadHeadersAsync(payloadLength, cancellationToken).ConfigureAwait(false); // Stop looping after a trailing header. // There may be extra frames after this one, but they would all be unknown extension // frames that can be safely ignored. Just stop reading here. // Note: this does leave us open to a bad server sending us an out of order DATA frame. goto case null; case null: // Done receiving: copy over trailing headers. CopyTrailersToResponseMessage(_response!); _responseDataPayloadRemaining = -1; // Set to -1 to indicate EOS. return; case Http3FrameType.Data: // The sum of data frames must equal content length. Because this method is only // called for a Content-Length of 0, anything other than 0 here would be an error. // Per spec, 0-length payload is allowed. if (payloadLength != 0) { if (NetEventSource.Log.IsEnabled()) { Trace("Response content exceeded Content-Length."); } throw new HttpRequestException(SR.net_http_invalid_response); } break; default: Debug.Fail($"Received unexpected frame type {frameType}."); return; } } } private void CopyTrailersToResponseMessage(HttpResponseMessage responseMessage) { if (_trailingHeaders?.Count > 0) { foreach ((HeaderDescriptor name, string value) in _trailingHeaders) { responseMessage.TrailingHeaders.TryAddWithoutValidation(name, value); } _trailingHeaders.Clear(); } } private void BufferHeaders(HttpRequestMessage request) { // Reserve space for the header frame envelope. // The envelope needs to be written after headers are serialized, as we need to know the payload length first. const int PreHeadersReserveSpace = Http3Frame.MaximumEncodedFrameEnvelopeLength; // This should be the first write to our buffer. The trick of reserving space won't otherwise work. Debug.Assert(_sendBuffer.ActiveLength == 0); // Reserve space for header frame envelope. _sendBuffer.Commit(PreHeadersReserveSpace); // Add header block prefix. We aren't using dynamic table, so these are simple zeroes. // https://tools.ietf.org/html/draft-ietf-quic-qpack-11#section-4.5.1 _sendBuffer.EnsureAvailableSpace(2); _sendBuffer.AvailableSpan[0] = 0x00; // required insert count. _sendBuffer.AvailableSpan[1] = 0x00; // s + delta base. _sendBuffer.Commit(2); HttpMethod normalizedMethod = HttpMethod.Normalize(request.Method); BufferBytes(normalizedMethod.Http3EncodedBytes); BufferIndexedHeader(H3StaticTable.SchemeHttps); if (request.HasHeaders && request.Headers.Host != null) { BufferLiteralHeaderWithStaticNameReference(H3StaticTable.Authority, request.Headers.Host); } else { BufferBytes(_connection.Pool._http3EncodedAuthorityHostHeader); } Debug.Assert(request.RequestUri != null); string pathAndQuery = request.RequestUri.PathAndQuery; if (pathAndQuery == "/") { BufferIndexedHeader(H3StaticTable.PathSlash); } else { BufferLiteralHeaderWithStaticNameReference(H3StaticTable.PathSlash, pathAndQuery); } // The only way to reach H3 is to upgrade via an Alt-Svc header, so we can encode Alt-Used for every connection. BufferBytes(_connection.AltUsedEncodedHeaderBytes); if (request.HasHeaders) { // H3 does not support Transfer-Encoding: chunked. if (request.HasHeaders && request.Headers.TransferEncodingChunked == true) { request.Headers.TransferEncodingChunked = false; } BufferHeaderCollection(request.Headers); } if (_connection.Pool.Settings._useCookies) { string cookiesFromContainer = _connection.Pool.Settings._cookieContainer!.GetCookieHeader(request.RequestUri); if (cookiesFromContainer != string.Empty) { Encoding? valueEncoding = _connection.Pool.Settings._requestHeaderEncodingSelector?.Invoke(HttpKnownHeaderNames.Cookie, request); BufferLiteralHeaderWithStaticNameReference(H3StaticTable.Cookie, cookiesFromContainer, valueEncoding); } } if (request.Content == null) { if (normalizedMethod.MustHaveRequestBody) { BufferIndexedHeader(H3StaticTable.ContentLength0); } } else { BufferHeaderCollection(request.Content.Headers); } // Determine our header envelope size. // The reserved space was the maximum required; discard what wasn't used. int headersLength = _sendBuffer.ActiveLength - PreHeadersReserveSpace; int headersLengthEncodedSize = VariableLengthIntegerHelper.GetByteCount(headersLength); _sendBuffer.Discard(PreHeadersReserveSpace - headersLengthEncodedSize - 1); // Encode header type in first byte, and payload length in subsequent bytes. _sendBuffer.ActiveSpan[0] = (byte)Http3FrameType.Headers; int actualHeadersLengthEncodedSize = VariableLengthIntegerHelper.WriteInteger(_sendBuffer.ActiveSpan.Slice(1, headersLengthEncodedSize), headersLength); Debug.Assert(actualHeadersLengthEncodedSize == headersLengthEncodedSize); } // TODO: special-case Content-Type for static table values values? private void BufferHeaderCollection(HttpHeaders headers) { if (headers.HeaderStore == null) { return; } HeaderEncodingSelector<HttpRequestMessage>? encodingSelector = _connection.Pool.Settings._requestHeaderEncodingSelector; foreach (KeyValuePair<HeaderDescriptor, object> header in headers.HeaderStore) { int headerValuesCount = HttpHeaders.GetStoreValuesIntoStringArray(header.Key, header.Value, ref _headerValues); Debug.Assert(headerValuesCount > 0, "No values for header??"); ReadOnlySpan<string> headerValues = _headerValues.AsSpan(0, headerValuesCount); Encoding? valueEncoding = encodingSelector?.Invoke(header.Key.Name, _request); KnownHeader? knownHeader = header.Key.KnownHeader; if (knownHeader != null) { // The Host header is not sent for HTTP/3 because we send the ":authority" pseudo-header instead // (see pseudo-header handling below in WriteHeaders). // The Connection, Upgrade and ProxyConnection headers are also not supported in HTTP/3. if (knownHeader != KnownHeaders.Host && knownHeader != KnownHeaders.Connection && knownHeader != KnownHeaders.Upgrade && knownHeader != KnownHeaders.ProxyConnection) { if (header.Key.KnownHeader == KnownHeaders.TE) { // HTTP/2 allows only 'trailers' TE header. rfc7540 8.1.2.2 // HTTP/3 does not mention this one way or another; assume it has the same rule. foreach (string value in headerValues) { if (string.Equals(value, "trailers", StringComparison.OrdinalIgnoreCase)) { BufferLiteralHeaderWithoutNameReference("TE", value, valueEncoding); break; } } continue; } // For all other known headers, send them via their pre-encoded name and the associated value. BufferBytes(knownHeader.Http3EncodedName); string? separator = null; if (headerValues.Length > 1) { HttpHeaderParser? parser = header.Key.Parser; if (parser != null && parser.SupportsMultipleValues) { separator = parser.Separator; } else { separator = HttpHeaderParser.DefaultSeparator; } } BufferLiteralHeaderValues(headerValues, separator, valueEncoding); } } else { // The header is not known: fall back to just encoding the header name and value(s). BufferLiteralHeaderWithoutNameReference(header.Key.Name, headerValues, HttpHeaderParser.DefaultSeparator, valueEncoding); } } } private void BufferIndexedHeader(int index) { int bytesWritten; while (!QPackEncoder.EncodeStaticIndexedHeaderField(index, _sendBuffer.AvailableSpan, out bytesWritten)) { _sendBuffer.Grow(); } _sendBuffer.Commit(bytesWritten); } private void BufferLiteralHeaderWithStaticNameReference(int nameIndex, string value, Encoding? valueEncoding = null) { int bytesWritten; while (!QPackEncoder.EncodeLiteralHeaderFieldWithStaticNameReference(nameIndex, value, valueEncoding, _sendBuffer.AvailableSpan, out bytesWritten)) { _sendBuffer.Grow(); } _sendBuffer.Commit(bytesWritten); } private void BufferLiteralHeaderWithoutNameReference(string name, ReadOnlySpan<string> values, string separator, Encoding? valueEncoding) { int bytesWritten; while (!QPackEncoder.EncodeLiteralHeaderFieldWithoutNameReference(name, values, separator, valueEncoding, _sendBuffer.AvailableSpan, out bytesWritten)) { _sendBuffer.Grow(); } _sendBuffer.Commit(bytesWritten); } private void BufferLiteralHeaderWithoutNameReference(string name, string value, Encoding? valueEncoding) { int bytesWritten; while (!QPackEncoder.EncodeLiteralHeaderFieldWithoutNameReference(name, value, valueEncoding, _sendBuffer.AvailableSpan, out bytesWritten)) { _sendBuffer.Grow(); } _sendBuffer.Commit(bytesWritten); } private void BufferLiteralHeaderValues(ReadOnlySpan<string> values, string? separator, Encoding? valueEncoding) { int bytesWritten; while (!QPackEncoder.EncodeValueString(values, separator, valueEncoding, _sendBuffer.AvailableSpan, out bytesWritten)) { _sendBuffer.Grow(); } _sendBuffer.Commit(bytesWritten); } private void BufferFrameEnvelope(Http3FrameType frameType, long payloadLength) { int bytesWritten; while (!Http3Frame.TryWriteFrameEnvelope(frameType, payloadLength, _sendBuffer.AvailableSpan, out bytesWritten)) { _sendBuffer.Grow(); } _sendBuffer.Commit(bytesWritten); } private void BufferBytes(ReadOnlySpan<byte> span) { _sendBuffer.EnsureAvailableSpace(span.Length); span.CopyTo(_sendBuffer.AvailableSpan); _sendBuffer.Commit(span.Length); } private async ValueTask<(Http3FrameType? frameType, long payloadLength)> ReadFrameEnvelopeAsync(CancellationToken cancellationToken) { long frameType, payloadLength; int bytesRead; while (true) { while (!Http3Frame.TryReadIntegerPair(_recvBuffer.ActiveSpan, out frameType, out payloadLength, out bytesRead)) { _recvBuffer.EnsureAvailableSpace(VariableLengthIntegerHelper.MaximumEncodedLength * 2); bytesRead = await _stream.ReadAsync(_recvBuffer.AvailableMemory, cancellationToken).ConfigureAwait(false); if (bytesRead != 0) { _recvBuffer.Commit(bytesRead); } else if (_recvBuffer.ActiveLength == 0) { // End of stream. return (null, 0); } else { // Our buffer has partial frame data in it but not enough to complete the read: bail out. throw new HttpRequestException(SR.net_http_invalid_response_premature_eof); } } _recvBuffer.Discard(bytesRead); if (NetEventSource.Log.IsEnabled()) { Trace($"Received frame {frameType} of length {payloadLength}."); } switch ((Http3FrameType)frameType) { case Http3FrameType.Headers: case Http3FrameType.Data: return ((Http3FrameType)frameType, payloadLength); case Http3FrameType.Settings: // These frames should only be received on a control stream, not a response stream. case Http3FrameType.GoAway: case Http3FrameType.MaxPushId: case Http3FrameType.ReservedHttp2Priority: // These frames are explicitly reserved and must never be sent. case Http3FrameType.ReservedHttp2Ping: case Http3FrameType.ReservedHttp2WindowUpdate: case Http3FrameType.ReservedHttp2Continuation: throw new Http3ConnectionException(Http3ErrorCode.UnexpectedFrame); case Http3FrameType.PushPromise: case Http3FrameType.CancelPush: // Because we haven't sent any MAX_PUSH_ID frames, any of these push-related // frames that the server sends will have an out-of-range push ID. throw new Http3ConnectionException(Http3ErrorCode.IdError); default: // Unknown frame types should be skipped. await SkipUnknownPayloadAsync(payloadLength, cancellationToken).ConfigureAwait(false); break; } } } private async ValueTask ReadHeadersAsync(long headersLength, CancellationToken cancellationToken) { // TODO: this header budget is sent as SETTINGS_MAX_HEADER_LIST_SIZE, so it should not use frame payload but rather 32 bytes + uncompressed size per entry. // https://tools.ietf.org/html/draft-ietf-quic-http-24#section-4.1.1 if (headersLength > _headerBudgetRemaining) { _stream.AbortWrite((long)Http3ErrorCode.ExcessiveLoad); throw new HttpRequestException(SR.Format(SR.net_http_response_headers_exceeded_length, _connection.Pool.Settings._maxResponseHeadersLength * 1024L)); } _headerBudgetRemaining -= headersLength; while (headersLength != 0) { if (_recvBuffer.ActiveLength == 0) { _recvBuffer.EnsureAvailableSpace(1); int bytesRead = await _stream.ReadAsync(_recvBuffer.AvailableMemory, cancellationToken).ConfigureAwait(false); if (bytesRead != 0) { _recvBuffer.Commit(bytesRead); } else { if (NetEventSource.Log.IsEnabled()) Trace($"Server closed response stream before entire header payload could be read. {headersLength:N0} bytes remaining."); throw new HttpRequestException(SR.net_http_invalid_response_premature_eof); } } int processLength = (int)Math.Min(headersLength, _recvBuffer.ActiveLength); _headerDecoder.Decode(_recvBuffer.ActiveSpan.Slice(0, processLength), this); _recvBuffer.Discard(processLength); headersLength -= processLength; } // Reset decoder state. Require because one decoder instance is reused to decode headers and trailers. _headerDecoder.Reset(); } private static ReadOnlySpan<byte> StatusHeaderNameBytes => new byte[] { (byte)'s', (byte)'t', (byte)'a', (byte)'t', (byte)'u', (byte)'s' }; void IHttpHeadersHandler.OnHeader(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value) { Debug.Assert(name.Length > 0); if (!HeaderDescriptor.TryGet(name, out HeaderDescriptor descriptor)) { // Invalid header name throw new HttpRequestException(SR.Format(SR.net_http_invalid_response_header_name, Encoding.ASCII.GetString(name))); } OnHeader(staticIndex: null, descriptor, staticValue: default, literalValue: value); } void IHttpHeadersHandler.OnStaticIndexedHeader(int index) { GetStaticQPackHeader(index, out HeaderDescriptor descriptor, out string? knownValue); OnHeader(index, descriptor, knownValue, literalValue: default); } void IHttpHeadersHandler.OnStaticIndexedHeader(int index, ReadOnlySpan<byte> value) { GetStaticQPackHeader(index, out HeaderDescriptor descriptor, knownValue: out _); OnHeader(index, descriptor, staticValue: null, literalValue: value); } private void GetStaticQPackHeader(int index, out HeaderDescriptor descriptor, out string? knownValue) { if (!HeaderDescriptor.TryGetStaticQPackHeader(index, out descriptor, out knownValue)) { if (NetEventSource.Log.IsEnabled()) Trace($"Response contains invalid static header index '{index}'."); throw new Http3ConnectionException(Http3ErrorCode.ProtocolError); } } /// <param name="staticIndex">The static index of the header, if any.</param> /// <param name="descriptor">A descriptor for either a known header or unknown header.</param> /// <param name="staticValue">The static indexed value, if any.</param> /// <param name="literalValue">The literal ASCII value, if any.</param> /// <remarks>One of <paramref name="staticValue"/> or <paramref name="literalValue"/> will be set.</remarks> private void OnHeader(int? staticIndex, HeaderDescriptor descriptor, string? staticValue, ReadOnlySpan<byte> literalValue) { if (descriptor.Name[0] == ':') { if (descriptor.KnownHeader != KnownHeaders.PseudoStatus) { if (NetEventSource.Log.IsEnabled()) Trace($"Received unknown pseudo-header '{descriptor.Name}'."); throw new Http3ConnectionException(Http3ErrorCode.ProtocolError); } if (_headerState != HeaderState.StatusHeader) { if (NetEventSource.Log.IsEnabled()) Trace("Received extra status header."); throw new Http3ConnectionException(Http3ErrorCode.ProtocolError); } int statusCode; if (staticValue != null) // Indexed Header Field -- both name and value are taken from the table { statusCode = staticIndex switch { H3StaticTable.Status103 => 103, H3StaticTable.Status200 => 200, H3StaticTable.Status304 => 304, H3StaticTable.Status404 => 404, H3StaticTable.Status503 => 503, H3StaticTable.Status100 => 100, H3StaticTable.Status204 => 204, H3StaticTable.Status206 => 206, H3StaticTable.Status302 => 302, H3StaticTable.Status400 => 400, H3StaticTable.Status403 => 403, H3StaticTable.Status421 => 421, H3StaticTable.Status425 => 425, H3StaticTable.Status500 => 500, // We should never get here, at least while we only use static table. But we can still parse staticValue. _ => ParseStatusCode(staticIndex, staticValue) }; int ParseStatusCode(int? index, string value) { string message = $"Unexpected QPACK table reference for Status code: index={index} value=\'{value}\'"; Debug.Fail(message); if (NetEventSource.Log.IsEnabled()) Trace(message); // TODO: The parsing is not optimal, but I don't expect this line to be executed at all for now. return HttpConnectionBase.ParseStatusCode(Encoding.ASCII.GetBytes(value)); } } else // Literal Header Field With Name Reference -- only name is taken from the table { statusCode = HttpConnectionBase.ParseStatusCode(literalValue); } _response = new HttpResponseMessage() { Version = HttpVersion.Version30, RequestMessage = _request, Content = new HttpConnectionResponseContent(), StatusCode = (HttpStatusCode)statusCode }; if (statusCode < 200) { // Informational responses should not contain headers -- skip them. _headerState = HeaderState.SkipExpect100Headers; if (_response.StatusCode == HttpStatusCode.Continue && _expect100ContinueCompletionSource != null) { _expect100ContinueCompletionSource.TrySetResult(true); } } else { _headerState = HeaderState.ResponseHeaders; if (_expect100ContinueCompletionSource != null) { // If the final status code is >= 300, skip sending the body. bool shouldSendBody = (statusCode < 300); if (NetEventSource.Log.IsEnabled()) Trace($"Expecting 100 Continue but received final status {statusCode}."); _expect100ContinueCompletionSource.TrySetResult(shouldSendBody); } } } else if (_headerState == HeaderState.SkipExpect100Headers) { // Ignore any headers that came as part of an informational (i.e. 100 Continue) response. return; } else { string? headerValue = staticValue; if (headerValue is null) { Encoding? encoding = _connection.Pool.Settings._responseHeaderEncodingSelector?.Invoke(descriptor.Name, _request); headerValue = _connection.GetResponseHeaderValueWithCaching(descriptor, literalValue, encoding); } switch (_headerState) { case HeaderState.StatusHeader: if (NetEventSource.Log.IsEnabled()) Trace($"Received headers without :status."); throw new Http3ConnectionException(Http3ErrorCode.ProtocolError); case HeaderState.ResponseHeaders when descriptor.HeaderType.HasFlag(HttpHeaderType.Content): _response!.Content!.Headers.TryAddWithoutValidation(descriptor, headerValue); break; case HeaderState.ResponseHeaders: _response!.Headers.TryAddWithoutValidation(descriptor.HeaderType.HasFlag(HttpHeaderType.Request) ? descriptor.AsCustomHeader() : descriptor, headerValue); break; case HeaderState.TrailingHeaders: _trailingHeaders!.Add((descriptor.HeaderType.HasFlag(HttpHeaderType.Request) ? descriptor.AsCustomHeader() : descriptor, headerValue)); break; default: Debug.Fail($"Unexpected {nameof(Http3RequestStream)}.{nameof(_headerState)} '{_headerState}'."); break; } } } void IHttpHeadersHandler.OnHeadersComplete(bool endStream) { Debug.Fail($"This has no use in HTTP/3 and should never be called by {nameof(QPackDecoder)}."); } private async ValueTask SkipUnknownPayloadAsync(long payloadLength, CancellationToken cancellationToken) { while (payloadLength != 0) { if (_recvBuffer.ActiveLength == 0) { _recvBuffer.EnsureAvailableSpace(1); int bytesRead = await _stream.ReadAsync(_recvBuffer.AvailableMemory, cancellationToken).ConfigureAwait(false); if (bytesRead != 0) { _recvBuffer.Commit(bytesRead); } else { // Our buffer has partial frame data in it but not enough to complete the read: bail out. throw new Http3ConnectionException(Http3ErrorCode.FrameError); } } long readLength = Math.Min(payloadLength, _recvBuffer.ActiveLength); _recvBuffer.Discard((int)readLength); payloadLength -= readLength; } } private int ReadResponseContent(HttpResponseMessage response, Span<byte> buffer) { // Response headers should be done reading by the time this is called. _response is nulled out as part of this. // Verify that this is being called in correct order. Debug.Assert(_response == null); try { int totalBytesRead = 0; while (buffer.Length != 0) { // Sync over async here -- QUIC implementation does it per-I/O already; this is at least more coarse-grained. if (_responseDataPayloadRemaining <= 0 && !ReadNextDataFrameAsync(response, CancellationToken.None).AsTask().GetAwaiter().GetResult()) { // End of stream. break; } if (_recvBuffer.ActiveLength != 0) { // Some of the payload is in our receive buffer, so copy it. int copyLen = (int)Math.Min(buffer.Length, Math.Min(_responseDataPayloadRemaining, _recvBuffer.ActiveLength)); _recvBuffer.ActiveSpan.Slice(0, copyLen).CopyTo(buffer); totalBytesRead += copyLen; _responseDataPayloadRemaining -= copyLen; _recvBuffer.Discard(copyLen); buffer = buffer.Slice(copyLen); // Stop, if we've reached the end of a data frame and start of the next data frame is not buffered yet // Waiting for the next data frame may cause a hang, e.g. in echo scenario // TODO: this is inefficient if data is already available in transport if (_responseDataPayloadRemaining == 0 && _recvBuffer.ActiveLength == 0) { break; } } else { // Receive buffer is empty -- bypass it and read directly into user's buffer. int copyLen = (int)Math.Min(buffer.Length, _responseDataPayloadRemaining); int bytesRead = _stream.Read(buffer.Slice(0, copyLen)); if (bytesRead == 0) { throw new HttpRequestException(SR.Format(SR.net_http_invalid_response_premature_eof_bytecount, _responseDataPayloadRemaining)); } totalBytesRead += bytesRead; _responseDataPayloadRemaining -= bytesRead; buffer = buffer.Slice(bytesRead); // Stop, even if we are in the middle of a data frame. Waiting for the next data may cause a hang // TODO: this is inefficient if data is already available in transport break; } } return totalBytesRead; } catch (Exception ex) { HandleReadResponseContentException(ex, CancellationToken.None); return 0; // never reached. } } private async ValueTask<int> ReadResponseContentAsync(HttpResponseMessage response, Memory<byte> buffer, CancellationToken cancellationToken) { // Response headers should be done reading by the time this is called. _response is nulled out as part of this. // Verify that this is being called in correct order. Debug.Assert(_response == null); try { int totalBytesRead = 0; while (buffer.Length != 0) { if (_responseDataPayloadRemaining <= 0 && !await ReadNextDataFrameAsync(response, cancellationToken).ConfigureAwait(false)) { // End of stream. break; } if (_recvBuffer.ActiveLength != 0) { // Some of the payload is in our receive buffer, so copy it. int copyLen = (int)Math.Min(buffer.Length, Math.Min(_responseDataPayloadRemaining, _recvBuffer.ActiveLength)); _recvBuffer.ActiveSpan.Slice(0, copyLen).CopyTo(buffer.Span); totalBytesRead += copyLen; _responseDataPayloadRemaining -= copyLen; _recvBuffer.Discard(copyLen); buffer = buffer.Slice(copyLen); // Stop, if we've reached the end of a data frame and start of the next data frame is not buffered yet // Waiting for the next data frame may cause a hang, e.g. in echo scenario // TODO: this is inefficient if data is already available in transport if (_responseDataPayloadRemaining == 0 && _recvBuffer.ActiveLength == 0) { break; } } else { // Receive buffer is empty -- bypass it and read directly into user's buffer. int copyLen = (int)Math.Min(buffer.Length, _responseDataPayloadRemaining); int bytesRead = await _stream.ReadAsync(buffer.Slice(0, copyLen), cancellationToken).ConfigureAwait(false); if (bytesRead == 0) { throw new HttpRequestException(SR.Format(SR.net_http_invalid_response_premature_eof_bytecount, _responseDataPayloadRemaining)); } totalBytesRead += bytesRead; _responseDataPayloadRemaining -= bytesRead; buffer = buffer.Slice(bytesRead); // Stop, even if we are in the middle of a data frame. Waiting for the next data may cause a hang // TODO: this is inefficient if data is already available in transport break; } } return totalBytesRead; } catch (Exception ex) { HandleReadResponseContentException(ex, cancellationToken); return 0; // never reached. } } private void HandleReadResponseContentException(Exception ex, CancellationToken cancellationToken) { switch (ex) { // Peer aborted the stream case QuicStreamAbortedException _: // User aborted the stream case QuicOperationAbortedException _: throw new IOException(SR.net_http_client_execution_error, new HttpRequestException(SR.net_http_client_execution_error, ex)); case QuicConnectionAbortedException _: // Our connection was reset. Start aborting the connection. Exception abortException = _connection.Abort(ex); throw new IOException(SR.net_http_client_execution_error, new HttpRequestException(SR.net_http_client_execution_error, abortException)); case Http3ConnectionException _: // A connection-level protocol error has occurred on our stream. _connection.Abort(ex); throw new IOException(SR.net_http_client_execution_error, new HttpRequestException(SR.net_http_client_execution_error, ex)); case OperationCanceledException oce when oce.CancellationToken == cancellationToken: _stream.AbortRead((long)Http3ErrorCode.RequestCancelled); ExceptionDispatchInfo.Throw(ex); // Rethrow. return; // Never reached. default: _stream.AbortRead((long)Http3ErrorCode.InternalError); throw new IOException(SR.net_http_client_execution_error, new HttpRequestException(SR.net_http_client_execution_error, ex)); } } private async ValueTask<bool> ReadNextDataFrameAsync(HttpResponseMessage response, CancellationToken cancellationToken) { if (_responseDataPayloadRemaining == -1) { // EOS -- this branch will only be taken if user calls Read again after EOS. return false; } Http3FrameType? frameType; long payloadLength; while (true) { (frameType, payloadLength) = await ReadFrameEnvelopeAsync(cancellationToken).ConfigureAwait(false); switch (frameType) { case Http3FrameType.Data: // Ignore DATA frames with 0 length. if (payloadLength == 0) { continue; } _responseDataPayloadRemaining = payloadLength; return true; case Http3FrameType.Headers: // Read any trailing headers. _trailingHeaders = new List<(HeaderDescriptor name, string value)>(); await ReadHeadersAsync(payloadLength, cancellationToken).ConfigureAwait(false); // There may be more frames after this one, but they would all be unknown extension // frames that we are allowed to skip. Just close the stream early. // Note: if a server sends additional HEADERS or DATA frames at this point, it // would be a connection error -- not draining the stream means we won't catch this. goto case null; case null: // End of stream. CopyTrailersToResponseMessage(response); _responseDataPayloadRemaining = -1; // Set to -1 to indicate EOS. return false; } } } public void Trace(string message, [CallerMemberName] string? memberName = null) => _connection.Trace(StreamId, message, memberName); private void AbortStream() { // If the request body isn't completed, cancel it now. if (_requestContentLengthRemaining != 0) // 0 is used for the end of content writing, -1 is used for unknown Content-Length { _stream.AbortWrite((long)Http3ErrorCode.RequestCancelled); } // If the response body isn't completed, cancel it now. if (_responseDataPayloadRemaining != -1) // -1 is used for EOF, 0 for consumed DATA frame payload before the next read { _stream.AbortRead((long)Http3ErrorCode.RequestCancelled); } } // TODO: it may be possible for Http3RequestStream to implement Stream directly and avoid this allocation. private sealed class Http3ReadStream : HttpBaseStream { private Http3RequestStream? _stream; private HttpResponseMessage? _response; public override bool CanRead => _stream != null; public override bool CanWrite => false; public Http3ReadStream(Http3RequestStream stream) { _stream = stream; _response = stream._response; } ~Http3ReadStream() { Dispose(false); } protected override void Dispose(bool disposing) { Http3RequestStream? stream = Interlocked.Exchange(ref _stream, null); if (stream is null) { return; } if (disposing) { // This will remove the stream from the connection properly. stream.Dispose(); } else { // We shouldn't be using a managed instance here, but don't have much choice -- we // need to remove the stream from the connection's GOAWAY collection and properly abort. stream.AbortStream(); stream._connection.RemoveStream(stream._stream); stream._connection = null!; } _response = null; base.Dispose(disposing); } public override async ValueTask DisposeAsync() { Http3RequestStream? stream = Interlocked.Exchange(ref _stream, null); if (stream is null) { return; } await stream.DisposeAsync().ConfigureAwait(false); _response = null; await base.DisposeAsync().ConfigureAwait(false); } public override int Read(Span<byte> buffer) { if (_stream == null) { throw new ObjectDisposedException(nameof(Http3RequestStream)); } Debug.Assert(_response != null); return _stream.ReadResponseContent(_response, buffer); } public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken) { if (_stream == null) { return ValueTask.FromException<int>(new ObjectDisposedException(nameof(Http3RequestStream))); } Debug.Assert(_response != null); return _stream.ReadResponseContentAsync(_response, buffer, cancellationToken); } public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken) { throw new NotSupportedException(); } } // TODO: it may be possible for Http3RequestStream to implement Stream directly and avoid this allocation. private sealed class Http3WriteStream : HttpBaseStream { private Http3RequestStream? _stream; public override bool CanRead => false; public override bool CanWrite => _stream != null; public Http3WriteStream(Http3RequestStream stream) { _stream = stream; } protected override void Dispose(bool disposing) { _stream = null; base.Dispose(disposing); } public override int Read(Span<byte> buffer) { throw new NotSupportedException(); } public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken) { throw new NotSupportedException(); } public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken) { if (_stream == null) { return ValueTask.FromException(new ObjectDisposedException(nameof(Http3WriteStream))); } return _stream.WriteRequestContentAsync(buffer, cancellationToken); } public override Task FlushAsync(CancellationToken cancellationToken) { if (_stream == null) { return Task.FromException(new ObjectDisposedException(nameof(Http3WriteStream))); } return _stream.FlushSendBufferAsync(endStream: false, cancellationToken).AsTask(); } } private enum HeaderState { StatusHeader, SkipExpect100Headers, ResponseHeaders, TrailingHeaders } } }
46.510549
185
0.56494
[ "MIT" ]
AlexRadch/runtime
src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http3RequestStream.cs
66,138
C#
using Autofac; using NUnit.Framework; using PGMS.Data.Services; using PGMS.DataProvider.EFCore.Installers; using PGMS.FakeImpl.DataProvider.Context; namespace PGMS.UnitTests.DataProvider.Installers { [TestFixture] public class ContextRegistrationFixture { [Test] public void Test() { var contextFactory = new FakeContextFactory(); contextFactory.InitContextUsage(false); var connectionString = "Fake"; var builder = new ContainerBuilder(); //Act DataProviderLayerInstaller.ConfigureServices(builder); DataProviderLayerInstaller.RegisterContext(builder, connectionString, contextFactory); var container = builder.Build(); //Assert Assert.That(container.Resolve<IUnitOfWorkProvider>(), Is.Not.Null); Assert.That(container.Resolve<IEntityRepository>(), Is.Not.Null); Assert.That(container.Resolve<IScopedEntityRepository>(), Is.Not.Null); } } }
30.588235
98
0.658654
[ "MIT" ]
danypellerin/CQSLight
src/PGMS.CQSLight/PGMS.UnitTests/DataProvider/Installers/ContextRegistrationFixture.cs
1,042
C#
using UnityEngine; using UnityEngine.UI; public class StartUI : MonoBehaviour { public Text gameTitleText; public Text madeByText; void Start() { bool isGameOver = PlayerPrefs.GetInt("GameOver") == 1 ? true : false; if (isGameOver) { gameTitleText.text = "Game Over!"; madeByText.text = "Try again?"; } } }
21.333333
77
0.585938
[ "MIT" ]
calemdar/Cut-It
Assets/Scripts/StartUI.cs
384
C#
using FinancialChartExplorer.Models; using Microsoft.AspNetCore.Mvc; namespace FinancialChartExplorer.Controllers { public partial class HomeController : Controller { public ActionResult Indicators() { var model = BoxData.GetDataFromJson(); return View(model); } } }
21.933333
52
0.659574
[ "MIT" ]
GrapeCity/ComponentOne-ASPNET-MVC-Samples
FinancialChartExplorer/FinancialChartExplorer/Controllers/Home/IndicatorsController.cs
331
C#
using System; using System.IO; using Microsoft.VisualStudio.TestTools.UnitTesting; using Stp7Toolbox; namespace UnitTest { [TestClass] public class UnitTest1 { [TestMethod] public void TestS7Time() { DateTime now = DateTime.Now; now = now.AddTicks(-(now.Ticks % 10000)); // Remove reslution lower than milliseconds DateTime time = PlcParser.timeFroms7time(PlcParser.s7timeFromDateTime(now)); Assert.AreEqual(now, time); DateTime exampleDate = new DateTime(2018, 3, 20, 9, 43, 10, 848); byte[] exampleDateHex = { 0x02, 0x15, 0xEB, 0x00, 0x30, 0xD1 }; PlcParser.parseS7Time(exampleDateHex, out DateTime outDate, out byte[] outByteMs, out byte[] outByteDays); Assert.AreEqual(BitConverter.ToString(outByteMs), BitConverter.ToString(exampleDateHex,0,4)); Assert.AreEqual(BitConverter.ToString(outByteDays), BitConverter.ToString(exampleDateHex, 4, 2)); Assert.AreEqual(exampleDate, outDate); byte[] outDateHex = PlcParser.s7timeFromDateTime(exampleDate); Assert.AreEqual(BitConverter.ToString(exampleDateHex), BitConverter.ToString(outDateHex)); } // This method accepts two strings the represent two files to // compare. A return value of 0 indicates that the contents of the files // are the same. A return value of any other value indicates that the // files are not the same. private bool FileCompare(string file1, string file2) { int file1byte; int file2byte; FileStream fs1; FileStream fs2; // Determine if the same file was referenced two times. if (file1 == file2) { // Return true to indicate that the files are the same. return true; } // Open the two files. fs1 = new FileStream(file1, FileMode.Open, FileAccess.Read); fs2 = new FileStream(file2, FileMode.Open, FileAccess.Read); // Check the file sizes. If they are not the same, the files // are not the same. if (fs1.Length != fs2.Length) { // Close the file fs1.Close(); fs2.Close(); // Return false to indicate files are different return false; } // Read and compare a byte from each file until either a // non-matching set of bytes is found or until the end of // file1 is reached. do { // Read one byte from each file. file1byte = fs1.ReadByte(); file2byte = fs2.ReadByte(); } while ((file1byte == file2byte) && (file1byte != -1)); // Close the files. fs1.Close(); fs2.Close(); // Return the success of the comparison. "file1byte" is // equal to "file2byte" at this point only if the files are // the same. return ((file1byte - file2byte) == 0); } } }
34.808511
109
0.554095
[ "MIT" ]
fleibede/Stp7Toolbox
UnitTest/UnitTest1.cs
3,274
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using SysHv.Server.DAL; namespace SysHv.Server.DAL.Migrations { [DbContext(typeof(ServerDbContext))] [Migration("20190507160927_MoveConfiguratiionToClientSensor")] partial class MoveConfiguratiionToClientSensor { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.2.4-servicing-10062") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Discriminator") .IsRequired(); b.Property<string>("Email") .HasMaxLength(256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasMaxLength(256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); b.HasDiscriminator<string>("Discriminator").HasValue("IdentityUser"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasMaxLength(128); b.Property<string>("ProviderKey") .HasMaxLength(128); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider") .HasMaxLength(128); b.Property<string>("Name") .HasMaxLength(128); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("SysHv.Server.DAL.Models.Client", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Description"); b.Property<string>("HardwareInfo"); b.Property<string>("Ip"); b.Property<string>("Name"); b.Property<string>("UserId"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("Clients"); }); modelBuilder.Entity("SysHv.Server.DAL.Models.ClientSensor", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("ClientId"); b.Property<float?>("CriticalValue"); b.Property<string>("Description"); b.Property<int>("Interval"); b.Property<float?>("MaxValue"); b.Property<float?>("MinValue"); b.Property<string>("Name"); b.Property<int>("SensorId"); b.HasKey("Id"); b.HasIndex("ClientId"); b.HasIndex("SensorId"); b.ToTable("ClientSensors"); }); modelBuilder.Entity("SysHv.Server.DAL.Models.Sensor", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Contract"); b.Property<string>("Description"); b.Property<bool>("IsNumeric"); b.Property<string>("Name"); b.Property<int>("OsType"); b.Property<string>("ReturnType"); b.HasKey("Id"); b.ToTable("Sensors"); }); modelBuilder.Entity("SysHv.Server.DAL.Models.SubSensor", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Description"); b.Property<bool>("IsNumeric"); b.Property<string>("Name"); b.Property<int>("SensorId"); b.HasKey("Id"); b.HasIndex("SensorId"); b.ToTable("SubSensors"); }); modelBuilder.Entity("SysHv.Server.DAL.Models.ApplicationUser", b => { b.HasBaseType("Microsoft.AspNetCore.Identity.IdentityUser"); b.Property<string>("CompanyName"); b.HasDiscriminator().HasValue("ApplicationUser"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("SysHv.Server.DAL.Models.Client", b => { b.HasOne("SysHv.Server.DAL.Models.ApplicationUser", "User") .WithMany("Clients") .HasForeignKey("UserId"); }); modelBuilder.Entity("SysHv.Server.DAL.Models.ClientSensor", b => { b.HasOne("SysHv.Server.DAL.Models.Client") .WithMany("ClientSensors") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("SysHv.Server.DAL.Models.Sensor", "Sensor") .WithMany("ClientSensors") .HasForeignKey("SensorId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("SysHv.Server.DAL.Models.SubSensor", b => { b.HasOne("SysHv.Server.DAL.Models.Sensor", "Sensor") .WithMany("SubSensors") .HasForeignKey("SensorId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
34.668435
125
0.478653
[ "MIT" ]
andrew-kulikov/sys-hv
SysHv/SysHv.Server.DAL/Migrations/20190507160927_MoveConfiguratiionToClientSensor.Designer.cs
13,072
C#
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System; using Microsoft.Data.SqlClient; using System.Globalization; using System.Text; using Microsoft.SqlServer.Management.Common; using SMO = Microsoft.SqlServer.Management.Smo; namespace Microsoft.SqlTools.ServiceLayer.Management { /// <summary> /// Internal reusable helpers /// </summary> internal class Utils { /// <summary> /// only static methods /// </summary> private Utils() { } /// <summary> /// returns all instances of the given custom attribute on a given object /// </summary> /// <param name="objectToGetAttributeFrom"></param> /// <param name="customAttribute"></param> /// <returns></returns> public static Attribute GetCustomAttribute(object objectToGetAttributeFrom, Type customAttribute) { //first, see if the object implemented this interface to override standard behavior System.Reflection.ICustomAttributeProvider attribProvider = objectToGetAttributeFrom as System.Reflection.ICustomAttributeProvider; if (attribProvider == null) { //if not, get it from its type attribProvider = (System.Reflection.ICustomAttributeProvider)objectToGetAttributeFrom.GetType(); } object[] attribs = attribProvider.GetCustomAttributes(customAttribute, true); if (attribs != null && attribs.Length > 0) { //NOTE: important that we'll always use the first one in collection. //Our implementation of ICustomAttributeProvider knows about that and //relies on this behavior return attribs[0] as Attribute; } return null; } /// <summary> /// called to create SqlConnectionInfo out of the given CDataContainer object /// </summary> /// <param name="dc"></param> /// <returns></returns> public static SqlConnectionInfo GetSqlConnectionInfoFromDataContainer(CDataContainer dc) { if (dc != null) { // we may have been given conneciton information by the object explorer. in which case there is no need // to build it ourselves. SqlConnectionInfo result = dc.ConnectionInfo as SqlConnectionInfo; if (result == null) { throw new InvalidOperationException(); } return result; } else { return null; } } public static int InitialTreeViewWidth { get { return 175; } } /// <summary> /// Try to set the CLR thread name. /// Will not throw if the name is already set. /// </summary> /// <param name="name"></param> public static void TrySetThreadName(String name) { try { System.Threading.Thread.CurrentThread.Name = name; } catch (InvalidOperationException) { } } public static bool IsKatmaiOrLater(int version) { return (10 <= version); } public static bool IsKjOrLater(ServerVersion version) { return (version.Major > 10 || (version.Major == 10 && version.Minor >= 50)); } public static bool IsSql11OrLater(ServerVersion version) { return IsSql11OrLater(version.Major); } public static bool IsSql11OrLater(int versionMajor) { return (versionMajor >= 11); } public static bool IsSql12OrLater(ServerVersion version) { return IsSql12OrLater(version.Major); } public static bool IsSql12OrLater(int versionMajor) { return (versionMajor >= 12); } public static bool IsSql13OrLater(ServerVersion version) { return IsSql13OrLater(version.Major); } public static bool IsSql13OrLater(int versionMajor) { return (versionMajor >= 13); } public static bool IsSql14OrLater(ServerVersion version) { return IsSql14OrLater(version.Major); } public static bool IsSql14OrLater(int versionMajor) { return (versionMajor >= 14); } /// <summary> /// Check if the version is SQL 2016 SP1 or later. /// </summary> /// <param name="version"></param> /// <returns>true if the version is SQL 2016 SP1 or later, false otherwise</returns> public static bool IsSql13SP1OrLater(Version version) { return (version >= new Version(13, 0, 3510)); } public static bool IsXTPSupportedOnServer(SMO.Server server) { bool isXTPSupported = false; if (server.ConnectionContext.ExecuteScalar("SELECT SERVERPROPERTY('IsXTPSupported')") != DBNull.Value) { isXTPSupported = server.IsXTPSupported; } return isXTPSupported; } /// <summary> /// Returns true if given database has memory optimized filegroup on given server. /// </summary> /// <param name="server"></param> /// <param name="dbName"></param> /// <returns></returns> public static bool HasMemoryOptimizedFileGroup(SMO.Server server, string dbName) { bool hasMemoryOptimizedFileGroup = false; if (server.ServerType != DatabaseEngineType.SqlAzureDatabase) { string query = string.Format(CultureInfo.InvariantCulture, "select top 1 1 from [{0}].sys.filegroups where type = 'FX'", CUtils.EscapeString(dbName, ']')); if (server.ConnectionContext.ExecuteScalar(query) != null) { hasMemoryOptimizedFileGroup = true; } } return hasMemoryOptimizedFileGroup; } public static bool IsPolybasedInstalledOnServer(SMO.Server server) { bool isPolybaseInstalled = false; if (server.IsSupportedProperty("IsPolyBaseInstalled")) { isPolybaseInstalled = server.IsPolyBaseInstalled; } return isPolybaseInstalled; } /// <summary> /// Returns true if current user has given permission on given server. /// </summary> /// <param name="server"></param> /// <param name="permissionName"></param> /// <returns></returns> public static bool HasPermissionOnServer(SMO.Server server, string permissionName) { return Convert.ToBoolean(server.ConnectionContext.ExecuteScalar( string.Format(CultureInfo.InvariantCulture, "SELECT HAS_PERMS_BY_NAME(null, null, '{0}');", permissionName))); } public static bool FilestreamEnabled(SMO.Server svr) { bool result = false; if (svr != null) { if (IsKatmaiOrLater(svr.Information.Version.Major) && svr.ServerType != DatabaseEngineType.SqlAzureDatabase) //Azure doesn't support filestream { if (svr.Configuration.FilestreamAccessLevel.RunValue != 0) { result = true; } } } return result; } public static bool IsYukonOrAbove(SMO.Server server) { return server.Version.Major >= 9; } public static bool IsBelowYukon(SMO.Server server) { return server.Version.Major < 9; } public static string MakeSqlBracket(string s) { return "[" + s.Replace("]", "]]") + "]"; } /// <summary> /// Some calendars, such as the UmAlQuraCalendar, support an upper date range that is earlier than MaxValue. /// In these cases, trying to access MaxValue in variable assignments or formatting and parsing operations can throw /// an ArgumentOutOfRangeException. Rather than retrieving the value of DateTime.MaxValue, you can retrieve the value /// of the specified culture's latest valid date value from the /// System.Globalization.CultureInfo.DateTimeFormat.Calendar.MaxSupportedDateTime property. /// http://msdn.microsoft.com/en-us/library/system.datetime.maxvalue(v=VS.90).aspx /// </summary> /// <returns></returns> public static DateTime GetMaxCultureDateTime() { CultureInfo currentCulture = System.Threading.Thread.CurrentThread.CurrentCulture; return currentCulture.DateTimeFormat.Calendar.MaxSupportedDateTime; } } /// <summary> /// Public reusable helpers /// </summary> public class SqlMgmtUtils { /// <summary> /// only static methods /// </summary> private SqlMgmtUtils() { } /// <summary> /// Returns whether the server is in AS Azure /// </summary> /// <param name="serverName"></param> /// <returns></returns> public static bool IsASAzure(string serverName) { return !string.IsNullOrEmpty(serverName) && serverName.StartsWith("asazure://", StringComparison.OrdinalIgnoreCase); } } /// <summary> /// Summary description for CUtils. /// </summary> internal class CUtils { private const int ObjectPermissionsDeniedErrorNumber = 229; private const int ColumnPermissionsDeniedErrorNumber = 230; public CUtils() { // // TODO: Add constructor logic here // } public static void UseMaster(SMO.Server server) { server.ConnectionContext.ExecuteNonQuery("use master"); } /// <summary> /// Get a SMO Server object that is connected to the connection /// </summary> /// <param name="ci">Conenction info</param> /// <returns>Smo Server object for the connection</returns> public static Microsoft.SqlServer.Management.Smo.Server GetSmoServer(IManagedConnection mc) { SqlOlapConnectionInfoBase ci = mc.Connection; if (ci == null) { throw new ArgumentNullException("ci"); } SMO.Server server = null; // see what type of connection we have been passed SqlConnectionInfoWithConnection ciWithCon = ci as SqlConnectionInfoWithConnection; if (ciWithCon != null) { server = new SMO.Server(ciWithCon.ServerConnection); } else { SqlConnectionInfo sqlCi = ci as SqlConnectionInfo; if (sqlCi != null) { server = new SMO.Server(new ServerConnection(sqlCi)); } } if (server == null) { throw new InvalidOperationException(); } return server; } public static int GetServerVersion(SMO.Server server) { return server.Information.Version.Major; } /// <summary> /// Determines the oldest date based on the type of time units and the number of time units /// </summary> /// <param name="numUnits"></param> /// <param name="typeUnits"></param> /// <returns></returns> public static DateTime GetOldestDate(int numUnits, TimeUnitType typeUnits) { DateTime result = DateTime.Now; switch (typeUnits) { case TimeUnitType.Week: { result = (DateTime.Now).AddDays(-1 * 7 * numUnits); break; } case TimeUnitType.Month: { result = (DateTime.Now).AddMonths(-1 * numUnits); break; } case TimeUnitType.Year: { result = (DateTime.Now).AddYears(-1 * numUnits); break; } default: { result = (DateTime.Now).AddDays(-1 * numUnits); break; } } return result; } public static string TokenizeXml(string s) { if (null == s) return String.Empty; System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (char c in s) { switch (c) { case '<': sb.Append("&lt;"); break; case '>': sb.Append("&gt;"); break; case '&': sb.Append("&amp;"); break; default: sb.Append(c); break; } } return sb.ToString(); } /// <summary> /// Tries to get the SqlException out of an Enumerator exception /// </summary> /// <param name="e"></param> /// <returns></returns> public static SqlException GetSqlException(Exception e) { SqlException sqlEx = null; Exception exception = e; while (exception != null) { sqlEx = exception as SqlException; if (null != sqlEx) { break; } exception = exception.InnerException; } return sqlEx; } /// <summary> /// computes the name of the machine based on server's name (as returned by smoServer.Name) /// </summary> /// <param name="sqlServerName">name of server ("",".","Server","Server\Instance",etc)</param> /// <returns>name of the machine hosting sql server instance</returns> public static string GetMachineName(string sqlServerName) { System.Diagnostics.Debug.Assert(sqlServerName != null); string machineName = sqlServerName; if (sqlServerName.Trim().Length != 0) { // [0] = machine, [1] = instance (if any) return sqlServerName.Split('\\')[0]; } else { // we have default instance of default machine return machineName; } } /// <summary> /// Determines if a SqlException is Permission denied exception /// </summary> /// <param name="sqlException"></param> /// <returns></returns> public static bool IsPermissionDeniedException(SqlException sqlException) { bool isPermDenied = false; if (null != sqlException.Errors) { foreach (SqlError sqlError in sqlException.Errors) { int errorNumber = GetSqlErrorNumber(sqlError); if ((ObjectPermissionsDeniedErrorNumber == errorNumber) || (ColumnPermissionsDeniedErrorNumber == errorNumber)) { isPermDenied = true; break; } } } return isPermDenied; } /// <summary> /// Returns the error number of a sql exeception /// </summary> /// <param name="sqlerror"></param> /// <returns></returns> public static int GetSqlErrorNumber(SqlError sqlerror) { return sqlerror.Number; } /// <summary> /// Function doubles up specified character in a string /// </summary> /// <param name="s"></param> /// <param name="cEsc"></param> /// <returns></returns> public static String EscapeString(string s, char cEsc) { if (string.IsNullOrWhiteSpace(s)) { return s; } StringBuilder sb = new StringBuilder(s.Length * 2); foreach (char c in s) { sb.Append(c); if (cEsc == c) sb.Append(c); } return sb.ToString(); } /// <summary> /// Function doubles up ']' character in a string /// </summary> /// <param name="s"></param> /// <returns></returns> public static String EscapeStringCBracket(string s) { return CUtils.EscapeString(s, ']'); } /// <summary> /// Function doubles up '\'' character in a string /// </summary> /// <param name="s"></param> /// <returns></returns> public static String EscapeStringSQuote(string s) { return CUtils.EscapeString(s, '\''); } /// <summary> /// Function removes doubled up specified character from a string /// </summary> /// <param name="s"></param> /// <param name="cEsc"></param> /// <returns></returns> public static String UnEscapeString(string s, char cEsc) { StringBuilder sb = new StringBuilder(s.Length); bool foundBefore = false; foreach (char c in s) { if (cEsc == c) // character to unescape { if (foundBefore) // skip second occurrence { foundBefore = false; } else // set the flag to skip next time around { sb.Append(c); foundBefore = true; } } else { sb.Append(c); foundBefore = false; } } return sb.ToString(); } /// <summary> /// Function removes doubled up ']' character from a string /// </summary> /// <param name="s"></param> /// <returns></returns> public static String UnEscapeStringCBracket(string s) { return CUtils.UnEscapeString(s, ']'); } /// <summary> /// Function removes doubled up '\'' character from a string /// </summary> /// <param name="s"></param> /// <returns></returns> public static String UnEscapeStringSQuote(string s) { return CUtils.UnEscapeString(s, '\''); } /// <summary> /// Get the windows login name with the domain portion in all-caps /// </summary> /// <param name="windowsLoginName">The windows login name</param> /// <returns>The windows login name with the domain portion in all-caps</returns> public static string CanonicalizeWindowsLoginName(string windowsLoginName) { string result; int lastBackslashIndex = windowsLoginName.LastIndexOf("\\", StringComparison.Ordinal); if (-1 != lastBackslashIndex) { string domainName = windowsLoginName.Substring(0, lastBackslashIndex).ToUpperInvariant(); string afterDomain = windowsLoginName.Substring(lastBackslashIndex); result = String.Concat(domainName, afterDomain); } else { result = windowsLoginName; } return result; } } /// <summary> /// Enum of time units types ( used in cleaning up history based on age ) /// </summary> internal enum TimeUnitType { Day, Week, Month, Year } /// <summary> /// Object used to populate default language in /// database and user dialogs. /// </summary> internal class LanguageDisplay { private SMO.Language language; public string LanguageAlias { get { return language.Alias; } } public SMO.Language Language { get { return language; } } public LanguageDisplay(SMO.Language language) { this.language = language; } public override string ToString() { return language.Alias; } } }
32.107303
143
0.508216
[ "MIT" ]
KevinRansom/sqltoolsservice
src/Microsoft.SqlTools.ServiceLayer/Management/Common/Utils.cs
21,546
C#
namespace Photon.Hive.Plugin { /// <summary> /// Internal plugin errors codes. /// </summary> public static class ErrorCodes { /// <summary> /// Indicates that a callback process method was not called. /// </summary> public const short MissingCallProcessing = 0; /// <summary> /// Indicates that an unhandled exception has occured. /// </summary> public const short UnhandledException = 1; /// <summary> /// Indicates that an exeption has occured in an asynchronous callback. /// </summary> public const short AsyncCallbackException = 2; /// <summary> /// Indicates that preconditions of SetProperties were not met. /// </summary> public const short SetPropertiesPreconditionsFail = 3; /// <summary> /// Indicates that CAS ("Check And Swap") failed when setting updated properties. /// </summary> public const short SetPropertiesCASFail = 4; /// <summary> /// Indicates that an exception has occurred when updating properties. /// </summary> public const short SetPropertiesException = 5; } }
35.588235
89
0.600826
[ "MIT" ]
LevchenkovHeyworks/Networking
Playground/.runtime/photon/src-server/HivePlugin/ErrorCodes.cs
1,212
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CoinMonitoringPortal.Data.Messages.Action { public class RegisterRequest { public string UserName { get; set; } public string Password { get; set; } public string Email { get; set; } } public class RegisterResponse { public bool Success { get; set; } public string Error { get; set; } } }
19.727273
51
0.728111
[ "MIT" ]
VytautasBoznis/CoinMonitoringPortal
CoinMonitoringPortal.Data/Messages/Action/Register.cs
436
C#
// <copyright file="CachedWrapperDelegateTests.cs" company="Datadog"> // Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. // This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. // </copyright> using System; using Confluent.Kafka; using Datadog.Trace.Agent; using Datadog.Trace.ClrProfiler.AutoInstrumentation.Kafka; using Datadog.Trace.Configuration; using Datadog.Trace.Sampling; using FluentAssertions; using Moq; using Xunit; namespace Datadog.Trace.ClrProfiler.Managed.Tests.AutoInstrumentation.Kafka { public class CachedWrapperDelegateTests { [Fact] public void CanCreateWrapperDelegate() { var wasOriginalInvoked = false; var testReport = new DeliveryReport<string, string>(); Action<DeliveryReport<string, string>> original = x => { wasOriginalInvoked = true; x.Should().BeSameAs(testReport); }; var tracer = GetTracer(); var span = tracer.StartSpan("Test operation"); var wrapper = KafkaProduceSyncDeliveryHandlerIntegration.CachedWrapperDelegate<Action<DeliveryReport<string, string>>>.CreateWrapper(original, span); wrapper.Invoke(testReport); wasOriginalInvoked.Should().BeTrue(); span.IsFinished.Should().BeTrue(); } [Fact] public void CanCreateMultipleWrapperDelegates() { var stringReport = new DeliveryReport<string, string>(); var intReport = new DeliveryReport<int, string>(); var tracer = GetTracer(); var stringSpan = tracer.StartSpan("Test string message operation"); var stringWrapper = KafkaProduceSyncDeliveryHandlerIntegration .CachedWrapperDelegate<Action<DeliveryReport<string, string>>>.CreateWrapper(x => { }, stringSpan); stringWrapper.Invoke(stringReport); var intSpan = tracer.StartSpan("Test int message operation"); var intWrapper = KafkaProduceSyncDeliveryHandlerIntegration .CachedWrapperDelegate<Action<DeliveryReport<int, string>>>.CreateWrapper(x => { }, intSpan); intWrapper.Invoke(intReport); stringSpan.IsFinished.Should().BeTrue(); intSpan.IsFinished.Should().BeTrue(); } private static Tracer GetTracer() { var settings = new TracerSettings(); var writerMock = new Mock<IAgentWriter>(); var samplerMock = new Mock<ISampler>(); return new Tracer(settings, writerMock.Object, samplerMock.Object, scopeManager: null, statsd: null); } } }
38.972222
161
0.650392
[ "Apache-2.0" ]
DataDog/dd-trace-csharp
tracer/test/Datadog.Trace.ClrProfiler.Managed.Tests/AutoInstrumentation/Kafka/CachedWrapperDelegateTests.cs
2,808
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NP.Roxy.Attributes { [AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = false)] public class ShareSubPluginAttribute : Attribute { public string SharedPluginName { get; } string _mapsToExternalName; public string MapsToExternalName { get => _mapsToExternalName ?? SharedPluginName; private set { if (_mapsToExternalName == value) return; _mapsToExternalName = value; } } public ShareSubPluginAttribute(string sharedPluginName, string mapsToName = null) { SharedPluginName = sharedPluginName; MapsToExternalName = mapsToName; } } }
26.235294
89
0.619955
[ "Apache-2.0" ]
npolyak/NP.Roxy
NP.Roxy/Attributes/ShareSubPluginAttribute.cs
894
C#
// <copyright file="DevToolsDomains.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; namespace OpenQA.Selenium.DevTools { /// <summary> /// Interface providing version-independent implementations of operations available using the DevTools Protocol. /// </summary> public abstract class DevToolsDomains { // By default, we will look for a supported version within this // number of versions, as that will most likely still work. private static readonly int DefaultVersionRange = 5; // This is the list of known supported DevTools version implementation. // When new versions are implemented for support, new types must be // added to this dictionary. private static readonly Dictionary<int, Type> SupportedDevToolsVersions = new Dictionary<int, Type>() { { 89, typeof(V89.V89Domains) }, { 88, typeof(V88.V88Domains) }, { 87, typeof(V87.V87Domains) }, { 86, typeof(V86.V86Domains) }, { 85, typeof(V85.V85Domains) } }; /// <summary> /// Gets the version-specific domains for the DevTools session. This value must be cast to a version specific type to be at all useful. /// </summary> public abstract DevToolsSessionDomains VersionSpecificDomains { get; } /// <summary> /// Gets the object used for manipulating network information in the browser. /// </summary> public abstract Network Network { get; } /// <summary> /// Gets the object used for manipulating the browser's JavaScript execution. /// </summary> public abstract JavaScript JavaScript { get; } /// <summary> /// Gets the object used for manipulating DevTools Protocol targets. /// </summary> public abstract Target Target { get; } /// <summary> /// Gets the object used for manipulating the browser's logs. /// </summary> public abstract Log Log { get; } /// <summary> /// Initializes the supplied DevTools session's domains for the specified browser version. /// </summary> /// <param name="protocolVersion">The version of the DevTools Protocol to use.</param> /// <param name="session">The <see cref="DevToolsSession"/> for which to initialiize the domains.</param> /// <returns>The <see cref="DevToolsDomains"/> object containing the version-specific domains.</returns> public static DevToolsDomains InitializeDomains(int protocolVersion, DevToolsSession session) { return InitializeDomains(protocolVersion, session, DefaultVersionRange); } /// <summary> /// Initializes the supplied DevTools session's domains for the specified browser version within the specified number of versions. /// </summary> /// <param name="protocolVersion">The version of the DevTools Protocol to use.</param> /// <param name="session">The <see cref="DevToolsSession"/> for which to initialiize the domains.</param> /// <param name="versionRange">The range of versions within which to match the provided version number. Defaults to 5 versions.</param> /// <returns>The <see cref="DevToolsDomains"/> object containing the version-specific domains.</returns> public static DevToolsDomains InitializeDomains(int protocolVersion, DevToolsSession session, int versionRange) { if (versionRange < 0) { throw new ArgumentException("Version range must be positive", "versionRange"); } DevToolsDomains domains = null; Type domainType = MatchDomainsVersion(protocolVersion, versionRange); ConstructorInfo constructor = domainType.GetConstructor(new Type[] { typeof(DevToolsSession) }); if (constructor != null) { domains = constructor.Invoke(new object[] { session }) as DevToolsDomains; } return domains; } private static Type MatchDomainsVersion(int desiredVersion, int versionRange) { // Return fast on an exact match if (SupportedDevToolsVersions.ContainsKey(desiredVersion)) { return SupportedDevToolsVersions[desiredVersion]; } // Get the list of supported versions and sort descending List<int> supportedVersions = new List<int>(SupportedDevToolsVersions.Keys); supportedVersions.Sort((first, second) => second.CompareTo(first)); foreach (int supportedVersion in supportedVersions) { // Match the version with the desired version within the // version range, using "The Price Is Right" style matching // (that is, closest without going over). if (desiredVersion >= supportedVersion && desiredVersion - supportedVersion < versionRange) { return SupportedDevToolsVersions[supportedVersion]; } } // TODO: Return a no-op implementation or throw exception. return null; } } }
45.382353
143
0.65068
[ "MIT" ]
INOS-soft/selenium
dotnet/src/webdriver/DevTools/DevToolsDomains.cs
6,172
C#
#if DEBUG using Logy.Maps.Exchange; using Logy.Maps.Geometry; namespace Logy.Maps.ReliefMaps.World.Ocean { public class ReliefParadiseEnd : ReliefParadise { public ReliefParadiseEnd() : base(5) { MainAlgorithm = new ShiftAxis(new OceanData(HealpixManager) { WithRelief = true, }) { Geoisostasy = true, DesiredDatum = Datum.Strahov48 }; } } } #endif
23.363636
72
0.519455
[ "MIT" ]
it4history/Logy.Exchange
src/Logy.Maps/ReliefMaps/World/Ocean/ReliefParadiseEnd.cs
514
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 Microsoft.Build.Framework; using NuGet.Common; using System.Collections.Generic; using System.Threading.Tasks; using INuGetLogger = NuGet.Common.ILogger; namespace Microsoft.Build.NuGetSdkResolver { /// <summary> /// An implementation of <see cref="T:NuGet.Common.ILogger" /> that logs messages to an <see cref="T:Microsoft.Build.Framework.SdkLogger" />. /// </summary> /// <inheritdoc /> internal class NuGetSdkLogger : INuGetLogger { /// <summary> /// A collection of errors that have been logged. /// </summary> private readonly ICollection<string> _errors; /// <summary> /// A <see cref="SdkLogger"/> to forward events to. /// </summary> private readonly SdkLogger _sdkLogger; /// <summary> /// A collection of warnings that have been logged. /// </summary> private readonly ICollection<string> _warnings; /// <summary> /// Initializes a new instance of the NuGetLogger class. /// </summary> /// <param name="sdkLogger">A <see cref="SdkLogger"/> to forward events to.</param> /// <param name="warnings">A <see cref="ICollection{String}"/> to add logged warnings to.</param> /// <param name="errors">An <see cref="ICollection{String}"/> to add logged errors to.</param> public NuGetSdkLogger(SdkLogger sdkLogger, ICollection<string> warnings, ICollection<string> errors) { _sdkLogger = sdkLogger ?? throw new ArgumentNullException(nameof(sdkLogger)); _warnings = warnings ?? throw new ArgumentNullException(nameof(warnings)); _errors = errors ?? throw new ArgumentNullException(nameof(errors)); } public void Log(LogLevel level, string data) { switch (level) { case LogLevel.Debug: case LogLevel.Verbose: // Detailed and Diagnostic verbosity in MSBuild shows high, normal, and low importance messages _sdkLogger.LogMessage(data, MessageImportance.Low); break; case LogLevel.Information: // Normal verbosity in MSBuild shows only high and normal importance messages _sdkLogger.LogMessage(data, MessageImportance.Normal); break; case LogLevel.Minimal: // Minimal verbosity in MSBuild shows only high importance messages _sdkLogger.LogMessage(data, MessageImportance.High); break; case LogLevel.Warning: _warnings.Add(data); break; case LogLevel.Error: _errors.Add(data); break; } } public void Log(ILogMessage message) => Log(message.Level, message.Message); public Task LogAsync(LogLevel level, string data) { Log(level, data); return Task.CompletedTask; } public Task LogAsync(ILogMessage message) { Log(message); return Task.CompletedTask; } public void LogDebug(string data) => Log(LogLevel.Debug, data); public void LogError(string data) => Log(LogLevel.Error, data); public void LogInformation(string data) => Log(LogLevel.Information, data); public void LogInformationSummary(string data) => Log(LogLevel.Information, data); public void LogMinimal(string data) => Log(LogLevel.Minimal, data); public void LogVerbose(string data) => Log(LogLevel.Verbose, data); public void LogWarning(string data) => Log(LogLevel.Warning, data); } }
36.688073
145
0.597399
[ "Apache-2.0" ]
BdDsl/NuGet.Client
src/NuGet.Core/Microsoft.Build.NuGetSdkResolver/NuGetSdkLogger.cs
3,999
C#
using System.Collections; using System.Collections.Generic; using NUnit.Framework; using UnityEngine; using UnityEngine.TestTools; namespace FastMessageRouter.Tests { public class MessageRouterTests { public class TestMessageA { } public class TestMessageB { } private MessageRouter _messageRouter; [SetUp] public void SetUp() { _messageRouter = new MessageRouter(); } [TearDown] public void TearDown() { _messageRouter?.ClearAllHandlers(); _messageRouter = null; } [Test] public void Handlers_With_Parameters_Are_Bound_And_Raised_And_Removed() { int number = 0; System.Action<TestMessageA> handler = (TestMessageA message) => { number += 1; }; _messageRouter.BindMessageHandler<TestMessageA>(handler); _messageRouter.RaiseMessage<TestMessageA>(); Assert.AreEqual(number, 1); _messageRouter.RemoveMessageHandler<TestMessageA>(handler); _messageRouter.RaiseMessage<TestMessageA>(); Assert.AreEqual(number, 1); } [Test] public void Handlers_Without_Parameters_Are_Bound_And_Raised_And_Removed() { int number = 0; System.Action handler = () => { number += 1; }; _messageRouter.BindMessageHandler<TestMessageA>(handler); _messageRouter.RaiseMessage<TestMessageA>(); Assert.AreEqual(number, 1); _messageRouter.RemoveMessageHandler<TestMessageA>(handler); _messageRouter.RaiseMessage<TestMessageA>(); Assert.AreEqual(number, 1); } [Test] public void Messages_Raised_Without_Parameters_Do_Not_Send_Null() { TestMessageA parameter = null; System.Action<TestMessageA> handler = (TestMessageA message) => { parameter = message; }; _messageRouter.BindMessageHandler<TestMessageA>(handler); _messageRouter.RaiseMessage<TestMessageA>(); Assert.IsNotNull(parameter); } [Test] public void Messages_Raised_With_Parameters_Do_Not_Send_Default_Instance() { TestMessageA parameter = new TestMessageA(); TestMessageA receivedMessage = null; System.Action<TestMessageA> handler = (message) => receivedMessage = message; _messageRouter.BindMessageHandler(handler); _messageRouter.RaiseMessage(parameter); Assert.AreSame(parameter, receivedMessage); } [Test] public void Messages_Are_Delivered_To_Multiple_Handlers() { bool handlerAWasCalled = false; System.Action handlerA = () => handlerAWasCalled = true; bool handlerBWasCalled = false; System.Action handlerB = () => handlerBWasCalled = true; _messageRouter.BindMessageHandler<TestMessageA>(handlerA); _messageRouter.BindMessageHandler<TestMessageA>(handlerB); _messageRouter.RaiseMessage<TestMessageA>(); Assert.IsTrue(handlerAWasCalled); Assert.IsTrue(handlerBWasCalled); } [Test] public void Clear_All_Removes_All_Bound_Handlers() { int a = 0, b = 0; System.Action handlerA = () => a += 1; System.Action handlerB = () => b += 1; _messageRouter.BindMessageHandler<TestMessageA>(handlerA); _messageRouter.BindMessageHandler<TestMessageB>(handlerB); _messageRouter.RaiseMessage<TestMessageA>(); _messageRouter.RaiseMessage<TestMessageB>(); _messageRouter.ClearAllHandlers(); _messageRouter.RaiseMessage<TestMessageA>(); _messageRouter.RaiseMessage<TestMessageB>(); Assert.AreEqual(a, 1); Assert.AreEqual(b, 1); } [Test] public void Messages_Are_Only_Send_To_Handlers_Bound_To_Same_Type() { int a = 0, b = 0; System.Action handlerA = () => a += 1; System.Action handlerB = () => b += 1; _messageRouter.BindMessageHandler<TestMessageA>(handlerA); _messageRouter.BindMessageHandler<TestMessageB>(handlerB); _messageRouter.RaiseMessage<TestMessageA>(); _messageRouter.ClearAllHandlers(); Assert.AreEqual(a, 1); Assert.AreEqual(b, 0); } } }
28.845679
89
0.594907
[ "MIT" ]
cgaudino/FastMessageRouter
Assets/FastMessageRouterPackage/Tests/MessageRouterTests.cs
4,673
C#
using System; using System.IO; using GroupDocs.Annotation.Models; using GroupDocs.Annotation.Models.AnnotationModels; namespace GroupDocs.Annotation.Examples.CSharp.BasicUsage.AddAnnotationToTheDocument { /// <summary> /// This example demonstrates adding image annotation with local path. /// </summary> class AddImageAnnotationLocalPath { public static void Run() { string outputPath = Path.Combine(Constants.GetOutputDirectoryPath(), "result" + Path.GetExtension(Constants.INPUT)); using (Annotator annotator = new Annotator(Constants.INPUT)) { ImageAnnotation image = new ImageAnnotation { Box = new Rectangle(100, 100, 100, 100), CreatedOn = DateTime.Now, Opacity = 0.7, PageNumber = 0, ImagePath = Constants.PICTURE }; annotator.Add(image); annotator.Save(outputPath); } Console.WriteLine($"\nDocument saved successfully.\nCheck output in {outputPath}."); } } }
34.088235
128
0.58585
[ "MIT" ]
groupdocs-annotation/GroupDocs.Annotation-for-.NET
Examples/GroupDocs.Annotation.Examples.CSharp/BasicUsage/AddAnnotationToTheDocument/AddImageAnnotationLocalPath.cs
1,161
C#
using System; using System.Linq; using CLAP; using Retia.Gui; using Retia.Gui.Models; using Retia.Gui.Windows; using Retia.Integration; using Retia.Mathematics; using Retia.Neural; using Retia.Neural.ErrorFunctions; using Retia.Neural.Layers; using Retia.Optimizers; using Retia.Training.Data.Samples; using Retia.Training.Trainers; using Retia.Training.Trainers.Actions; using Retia.Training.Trainers.Sessions; namespace SimpleExamples { public partial class Examples { [Verb] public void Xor() { MklProvider.TryUseMkl(true, ConsoleProgressWriter.Instance); var optimizer = new RMSPropOptimizer<float>(1e-3f); var net = new LayeredNet<float>(1, 1, new AffineLayer<float>(2, 3, AffineActivation.Tanh), new AffineLayer<float>(3, 1, AffineActivation.Tanh) { ErrorFunction = new MeanSquareError<float>() }) { Optimizer = optimizer }; var trainer = new OptimizingTrainer<float>(net, optimizer, new XorDataset(true), new OptimizingTrainerOptions(1) { ErrorFilterSize = 0, ReportProgress = new EachIteration(1), ReportMesages = true, ProgressWriter = ConsoleProgressWriter.Instance, LearningRateScaler = new ProportionalLearningRateScaler(new EachIteration(1), 9e-5f) }, new OptimizingSession("XOR")); var runner = ConsoleRunner.Create(trainer, net); trainer.TrainReport += (sender, args) => { if (args.Errors.Last().RawError < 1e-7f) { runner.Stop(); Console.WriteLine("Finished training."); } }; var gui = new RetiaGui(); gui.RunAsync(() => new TrainingWindow(new TypedTrainingModel<float>(trainer))); runner.Run(); } } }
32.233333
204
0.608583
[ "Apache-2.0" ]
olegtarasov/Retia
Examples/SimpleExamples/Examples.Xor.cs
1,936
C#
using CoreSampleAnnotation.AnnotationPlane; using CoreSampleAnnotation.AnnotationPlane.Columns; using CoreSampleAnnotation.AnnotationPlane.LayerBoundaries; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace CoreSampleAnnotation.Reports.SVG { /// <summary> /// Knows about different column types and construct suitable painer for each particular column /// </summary> public class ColumnPainterFactory { private static ILayerPainter universalLayerPainter = new LayerPainter(); public static ColumnPainter Create(UIElement headerView, ColumnView view, ColumnVM vm) { if (vm is BoundaryEditorColumnVM) { BoundaryEditorColumnVM becVM = (BoundaryEditorColumnVM)vm; ILayerBoundariesVM lbVM = becVM.BoundariesVM; if (becVM.ColumnVM is BoundaryLineColumnVM) { BoundaryLineColumnVM blcVM = (BoundaryLineColumnVM)becVM.ColumnVM; lbVM = blcVM.BoundariesVM; if (blcVM.ColumnVM is BoundaryLabelColumnVM) { BoundaryLabelColumnVM blcVM2 = (BoundaryLabelColumnVM)blcVM.ColumnVM; lbVM = blcVM2.BoundariesVM; } } return new BoundaryColumnPainter(headerView, view, vm, lbVM); } else if (vm is BoundaryLineColumnVM) { BoundaryLineColumnVM blcVM = (BoundaryLineColumnVM)vm; return Create(headerView, view, blcVM.ColumnVM); } else if (vm is ImageColumnVM) { return new ImageColumnPainter(headerView, view, (ImageColumnVM)vm); } else if (vm is DepthAxisColumnVM) { return new DepthColumnPainter(headerView, view, (DepthAxisColumnVM)vm); } else if (vm is ILayerColumn) { return new LayeredColumnPainter(headerView, view, vm, (ILayerColumn)vm, universalLayerPainter); } else if (vm is SamplesColumnVM) { return new SamplesColumnPainter(headerView, view, (SamplesColumnVM)vm); } else if (vm is VisualColumnVM) { return new VisualColumnPainter(headerView, view, (VisualColumnVM)vm); } else return new ColumnPainter(headerView, view, vm); } } }
37.926471
111
0.601784
[ "MIT" ]
itislab/CoreSampleAnnotation
Application/Reports/SVG/ColumnPainterFactory.cs
2,581
C#
using System; using System.CodeDom; using System.Collections.Generic; using System.IO; using System.Linq; using csmatio.io; using csmatio.types; using NUnit.Framework; namespace test { public class ReaderWriterTests { string _tempFileName; [TearDown] public void TearDown() { if (File.Exists(_tempFileName)) File.Delete(_tempFileName); } [TestCaseSource(nameof(ReadDataFolder))] [Test] public void ReadTestData(string matFileName) { var reader = new MatFileReader(matFileName); Assert.That(reader.Data, Is.Not.Empty); } [TestCaseSource(nameof(ReadDataFolder))] [Test] public void RoundTrip(string matFileName) { var reader = new MatFileReader(matFileName); _tempFileName = Path.GetTempFileName(); var writer = new MatFileWriter(_tempFileName, reader.Data, false); var roundTrip = new MatFileReader(_tempFileName); foreach (var (mla1, mla2) in reader.Data.Zip(roundTrip.Data, (mla1, mla2) => (mla1: mla1, mla2 :mla2))) Compare(mla1, mla2); } void Compare(MLArray mla1, MLArray mla2) { Assert.That(mla1.Flags, Is.EqualTo(mla2.Flags)); Assert.That(mla1.Dimensions, Is.EqualTo(mla2.Dimensions)); Assert.That(mla1.Name, Is.EqualTo(mla2.Name)); Assert.That(mla1.Type, Is.EqualTo(mla2.Type)); switch (mla1.Type) { case MLArray.mxCHAR_CLASS : var c1 = ((MLChar) mla1); var c2 = ((MLChar) mla2); break; case MLArray.mxDOUBLE_CLASS: CompareNumericArray((MLNumericArray<double>) mla1, (MLNumericArray<double>) mla2); break; case MLArray.mxSINGLE_CLASS: CompareNumericArray((MLNumericArray<float>) mla1, (MLNumericArray<float>) mla2); break; case MLArray.mxUINT8_CLASS: CompareNumericArray((MLNumericArray<byte>) mla1, (MLNumericArray<byte>) mla2); break; case MLArray.mxINT8_CLASS: CompareNumericArray((MLNumericArray<sbyte>) mla1, (MLNumericArray<sbyte>) mla2); break; case MLArray.mxUINT16_CLASS: CompareNumericArray((MLNumericArray<ushort>) mla1, (MLNumericArray<ushort>) mla2); break; case MLArray.mxINT16_CLASS: CompareNumericArray((MLNumericArray<short>) mla1, (MLNumericArray<short>) mla2); break; case MLArray.mxUINT32_CLASS: CompareNumericArray((MLNumericArray<uint>) mla1, (MLNumericArray<uint>) mla2); break; case MLArray.mxINT32_CLASS: CompareNumericArray((MLNumericArray<int>) mla1, (MLNumericArray<int>) mla2); break; case MLArray.mxUINT64_CLASS: CompareNumericArray((MLNumericArray<ulong>) mla1, (MLNumericArray<ulong>) mla2); break; case MLArray.mxINT64_CLASS: CompareNumericArray((MLNumericArray<long>) mla1, (MLNumericArray<long>) mla2); break; case MLArray.mxSTRUCT_CLASS: Assert.That(((MLStructure) mla1).GetKeySetToByteArray(), Is.EquivalentTo(((MLStructure) mla2).GetKeySetToByteArray())); foreach (var (a1, a2) in ((MLStructure)mla1).AllFields.Zip(((MLStructure)mla2).AllFields, (a1, a2) => (a1: a1, a2: a2))) Compare(a1, a2); break; case MLArray.mxCELL_CLASS: foreach (var (a1, a2) in ((MLCell)mla1).Cells.Cast<MLArray>().Zip(((MLCell)mla2).Cells.Cast<MLArray>(), (a1, a2) => (a1: a1, a2: a2))) Compare(a1, a2); break; case MLArray.mxSPARSE_CLASS: // int[] ai; // // //write ir // buffer = new MemoryStream(); // bufferBW = new BinaryWriter(buffer); // ai = ((MLSparse)array).IR; // foreach (var i in ai) // { // bufferBW.Write(i); // } // tag = new OSArrayTag(MatDataTypes.miINT32, buffer.ToArray()); // tag.WriteTo(bw); // // // write jc // buffer = new MemoryStream(); // bufferBW = new BinaryWriter(buffer); // ai = ((MLSparse)array).JC; // foreach (var i in ai) // { // bufferBW.Write(i); // } // tag = new OSArrayTag(MatDataTypes.miINT32, buffer.ToArray()); // tag.WriteTo(bw); // // //write real // buffer = new MemoryStream(); // bufferBW = new BinaryWriter(buffer); // var ad = ((MLSparse)array).ExportReal(); // for (var i = 0; i < ad.Length; i++) // { // bufferBW.Write(ad[i]); // } // tag = new OSArrayTag(MatDataTypes.miDOUBLE, buffer.ToArray()); // tag.WriteTo(bw); // // //write imaginary // if (array.IsComplex) // { // buffer = new MemoryStream(); // bufferBW = new BinaryWriter(buffer); // ad = ((MLSparse)array).ExportImaginary(); // for (var i = 0; i < ad.Length; i++) // { // bufferBW.Write(ad[i]); // } // tag = new OSArrayTag(MatDataTypes.miDOUBLE, buffer.ToArray()); // tag.WriteTo(bw); // } break; default: throw new Exception("Cannot compare matrix of type: " + MLArray.TypeToString(mla1.Type)); } } static void CompareNumericArray<T>(MLNumericArray<T> mna1, MLNumericArray<T> mna2) { Assert.That(mna1.IsComplex, Is.EqualTo(mna2.IsComplex)); Assert.That(mna1.RealByteBuffer.Array(), Is.EquivalentTo(mna2.RealByteBuffer.Array())); if (mna1.IsComplex) Assert.That(mna1.ImaginaryByteBuffer.Array(), Is.EquivalentTo(mna2.ImaginaryByteBuffer.Array())); } public static IEnumerable<TestCaseData> ReadDataFolder() { #if NET471 var baseDir = TestContext.CurrentContext.TestDirectory; #elif NETCOREAPP2_0 var baseDir = TestContext.CurrentContext.WorkDirectory; #endif var dir = Path.Combine(baseDir, "..", "..", "..", "..", "data"); foreach (var f in Directory.EnumerateFiles(dir, "*.mat")) { var tcd = new TestCaseData(f) {TestName = TestContext.CurrentContext.Test.MethodName + "." + Path.GetFileNameWithoutExtension(f)}; yield return tcd; } } } }
32.464865
146
0.620879
[ "BSD-2-Clause" ]
damageboy/csmatio
test/ReaderWriterTests.cs
6,008
C#
using HotChocolate.Types; namespace HotChocolate.Benchmark.Tests.Execution { public class QueryType : ObjectType<Query> { protected override void Configure(IObjectTypeDescriptor<Query> descriptor) { descriptor.Field(t => t.GetHero(default)) .Type<CharacterType>() .Argument("episode", a => a.DefaultValue(Episode.NewHope)); descriptor.Field(t => t.GetHeroes(default)) .Type<NonNullType<ListType<NonNullType<CharacterType>>>>() .Argument("episodes", a => a.Type<NonNullType<ListType<NonNullType<EpisodeType>>>>()); descriptor.Field(t => t.Search(default)) .Type<ListType<SearchResultType>>(); } } }
31.791667
102
0.601573
[ "MIT" ]
Dolfik1/hotchocolate
benchmarks/Benchmark.Tests/Execution/QueryType.cs
765
C#
using System; using System.Linq; using Microsoft.Extensions.DependencyInjection; namespace R5T.Gepidia.Remote.Construction { public static class Construction { public static void SubMain() { Construction.TestEnumerationOfFileSystemEntryPaths(); } private static void TestEnumerationOfFileSystemEntryPaths() { var serviceProvider = Program.GetServiceProvider(); var remoteFileSystemOperator = serviceProvider.GetRequiredService<RemoteFileSystemOperator>(); var directoryPath = @"/home/ec2-user/"; var remotePaths = remoteFileSystemOperator.EnumerateFileSystemEntryPaths(directoryPath, true).ToList(); foreach (var remotePath in remotePaths) { Console.WriteLine(remotePath); } } } }
27.875
116
0.632287
[ "MIT" ]
MinexAutomation/R5T.Gepidia.Remote
source/R5T.Gepidia.Remote.Construction/Code/Construction.cs
894
C#
using PublishR.Abstractions; using PublishR.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Http; namespace PublishR.Server { [RoutePrefix("api/invite")] public class InviteController : ApiController { private IAccounts accounts; [HttpPost] [Route("")] [Authorize(Roles = Known.Role.Owner)] public async Task<IHttpActionResult> Invite(InviteModel invite) { Check.BadRequestIfNull(invite); Check.BadRequestIfInvalid(invite); var inviteToken = await accounts.Invite(invite.Email, invite.Roles); return Ok(inviteToken); } public InviteController(IAccounts accounts) { this.accounts = accounts; } } }
23.666667
80
0.64554
[ "MIT" ]
clusta/publishr
PublishR.Server/InviteController.cs
854
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Response to the UserCallForwardingSelectiveGetCriteriaRequest. /// <see cref="UserCallForwardingSelectiveGetCriteriaRequest"/> /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""ab0042aa512abc10edb3c55e4b416b0b:10939""}]")] public class UserCallForwardingSelectiveGetCriteriaResponse : BroadWorksConnector.Ocip.Models.C.OCIDataResponse { private BroadWorksConnector.Ocip.Models.TimeSchedule _timeSchedule; [XmlElement(ElementName = "timeSchedule", IsNullable = false, Namespace = "")] [Optional] [Group(@"ab0042aa512abc10edb3c55e4b416b0b:10939")] public BroadWorksConnector.Ocip.Models.TimeSchedule TimeSchedule { get => _timeSchedule; set { TimeScheduleSpecified = true; _timeSchedule = value; } } [XmlIgnore] protected bool TimeScheduleSpecified { get; set; } private BroadWorksConnector.Ocip.Models.CallForwardingSelectiveNumberSelection _forwardToNumberSelection; [XmlElement(ElementName = "forwardToNumberSelection", IsNullable = false, Namespace = "")] [Group(@"ab0042aa512abc10edb3c55e4b416b0b:10939")] public BroadWorksConnector.Ocip.Models.CallForwardingSelectiveNumberSelection ForwardToNumberSelection { get => _forwardToNumberSelection; set { ForwardToNumberSelectionSpecified = true; _forwardToNumberSelection = value; } } [XmlIgnore] protected bool ForwardToNumberSelectionSpecified { get; set; } private string _forwardToPhoneNumber; [XmlElement(ElementName = "forwardToPhoneNumber", IsNullable = false, Namespace = "")] [Optional] [Group(@"ab0042aa512abc10edb3c55e4b416b0b:10939")] [MinLength(1)] [MaxLength(161)] public string ForwardToPhoneNumber { get => _forwardToPhoneNumber; set { ForwardToPhoneNumberSpecified = true; _forwardToPhoneNumber = value; } } [XmlIgnore] protected bool ForwardToPhoneNumberSpecified { get; set; } private BroadWorksConnector.Ocip.Models.CriteriaFromDn _fromDnCriteria; [XmlElement(ElementName = "fromDnCriteria", IsNullable = false, Namespace = "")] [Group(@"ab0042aa512abc10edb3c55e4b416b0b:10939")] public BroadWorksConnector.Ocip.Models.CriteriaFromDn FromDnCriteria { get => _fromDnCriteria; set { FromDnCriteriaSpecified = true; _fromDnCriteria = value; } } [XmlIgnore] protected bool FromDnCriteriaSpecified { get; set; } } }
33.638298
131
0.64105
[ "MIT" ]
JTOne123/broadworks-connector-net
BroadworksConnector/Ocip/Models/UserCallForwardingSelectiveGetCriteriaResponse.cs
3,162
C#
using System; using System.Threading; using System.Threading.Tasks; using Microsoft.DncEng.CommandLineLib; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; namespace Microsoft.DncEng.SecretManager.SecretTypes { [Name("azure-storage-container-sas-uri")] public class AzureStorageContainerSasUri : SecretType<AzureStorageContainerSasUri.Parameters> { public class Parameters { public SecretReference ConnectionString { get; set; } public string Container { get; set; } public string Permissions { get; set; } } private readonly ISystemClock _clock; public AzureStorageContainerSasUri(ISystemClock clock) { _clock = clock; } protected override async Task<SecretData> RotateValue(Parameters parameters, RotationContext context, CancellationToken cancellationToken) { DateTimeOffset expiresOn = _clock.UtcNow.AddMonths(1); DateTimeOffset nextRotationOn = _clock.UtcNow.AddDays(15); string connectionString = await context.GetSecretValue(parameters.ConnectionString); (string containerUri, string sas) containerUriAndSas = StorageUtils.GenerateBlobContainerSas(connectionString, parameters.Container, parameters.Permissions, expiresOn); string uriWithSas = containerUriAndSas.containerUri + containerUriAndSas.sas; return new SecretData(uriWithSas, expiresOn, nextRotationOn); } } }
38.575
180
0.709008
[ "MIT" ]
dkurepa/arcade-services
src/Microsoft.DncEng.SecretManager/SecretTypes/AzureStorageContainerSasUri.cs
1,543
C#
using System.Collections.Generic; namespace Cosmos.Business.Extensions.SMS.Aliyun.Core.Extensions { public static class StringExtensions{ public static byte[] HexToBytes(this string value) { int index = 0; List<byte> list = new List<byte>(value.Length / 2); while (index< value.Length) { list.Add(byte.Parse(value.Substring(index, 2), System.Globalization.NumberStyles.AllowHexSpecifier)); index += 2; } return list.ToArray(); } } }
29.684211
117
0.586879
[ "MIT" ]
ElderJames/SMS
src/Cosmos.Business.Extensions.SMS.Aliyun/Core/Extensions/StringExtensions.cs
566
C#
//----------------------------------------------------------------------------- // FILE: ServiceMount.cs // CONTRIBUTOR: Jeff Lill // COPYRIGHT: Copyright (c) 2005-2021 by neonFORGE LLC. 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. using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.Serialization; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using YamlDotNet.Serialization; namespace Neon.Docker { /// <summary> /// Service mount specification. /// </summary> public class ServiceMount : INormalizable { /// <summary> /// Specifies where the mount will appear within the service containers. /// </summary> [JsonProperty(PropertyName = "Target", Required = Required.Default, DefaultValueHandling = DefaultValueHandling.Populate)] [YamlMember(Alias = "Target", ApplyNamingConventions = false)] [DefaultValue(null)] public string Target { get; set; } /// <summary> /// Specifies the external mount source /// </summary> [JsonProperty(PropertyName = "Source", Required = Required.Default, DefaultValueHandling = DefaultValueHandling.Populate)] [YamlMember(Alias = "Source", ApplyNamingConventions = false)] [DefaultValue(null)] public string Source { get; set; } /// <summary> /// The mount type. /// </summary> [JsonProperty(PropertyName = "Type", Required = Required.Default, DefaultValueHandling = DefaultValueHandling.Populate)] [YamlMember(Alias = "Type", ApplyNamingConventions = false)] [DefaultValue(default(ServiceMountType))] public ServiceMountType Type { get; set; } /// <summary> /// Specifies whether the mount is to be read-only within the service containers. /// </summary> [JsonProperty(PropertyName = "ReadOnly", Required = Required.Default, DefaultValueHandling = DefaultValueHandling.Populate)] [YamlMember(Alias = "ReadOnly", ApplyNamingConventions = false)] [DefaultValue(false)] public bool ReadOnly { get; set; } /// <summary> /// Specifies the mount consistency. /// </summary> [JsonProperty(PropertyName = "Consistency", Required = Required.Default, DefaultValueHandling = DefaultValueHandling.Populate)] [YamlMember(Alias = "Consistency", ApplyNamingConventions = false)] [DefaultValue(default(ServiceMountConsistency))] public ServiceMountConsistency Consistency { get; set; } /// <summary> /// Specifies the bind propagation mode. /// </summary> [JsonProperty(PropertyName = "BindOptions", Required = Required.Default, DefaultValueHandling = DefaultValueHandling.Populate)] [YamlMember(Alias = "BindOptions", ApplyNamingConventions = false)] [DefaultValue(null)] public ServiceBindOptions BindOptions { get; set; } /// <summary> /// Optionally specifies volume mount configuration options. /// </summary> [JsonProperty(PropertyName = "VolumeOptions", Required = Required.Default, DefaultValueHandling = DefaultValueHandling.Populate)] [YamlMember(Alias = "VolumeOptions", ApplyNamingConventions = false)] [DefaultValue(null)] public ServiceVolumeOptions VolumeOptions { get; set; } /// <summary> /// Optionally specifies Tempfs mount configuration options. /// </summary> [JsonProperty(PropertyName = "TmpfsOptions", Required = Required.Default, DefaultValueHandling = DefaultValueHandling.Populate)] [YamlMember(Alias = "TmpfsOptions", ApplyNamingConventions = false)] [DefaultValue(null)] public ServiceTmpfsOptions TmpfsOptions { get; set; } /// <inheritdoc/> public void Normalize() { switch (Type) { case ServiceMountType.Bind: BindOptions = BindOptions ?? new ServiceBindOptions(); BindOptions.Normalize(); break; case ServiceMountType.Tmpfs: TmpfsOptions = TmpfsOptions ?? new ServiceTmpfsOptions(); TmpfsOptions.Normalize(); break; case ServiceMountType.Volume: VolumeOptions = VolumeOptions ?? new ServiceVolumeOptions(); VolumeOptions.Normalize(); break; } } } }
40.84
137
0.637023
[ "Apache-2.0" ]
nforgeio/neonKUBE
Lib/Neon.Docker/Model/Service/ServiceMount.cs
5,107
C#
using System; using System.Windows.Forms; namespace Json.Viewer { internal class AjaxNetDateTime : ICustomTextProvider { private static readonly long epoch = new DateTime(1970, 1, 1).Ticks; public string GetText(JsonObject jsonObject) { string text = (string)jsonObject.Value; return "Ajax.Net Date:" + ConvertJSTicksToDateTime(Convert.ToInt64(text.Substring(1, text.Length - 2))).ToString(); } private DateTime ConvertJSTicksToDateTime(long ticks) { return new DateTime(ticks * 10000 + epoch); } public string DisplayName => "Ajax.Net DateTime"; public bool CanVisualize(JsonObject jsonObject) { if (jsonObject.JsonType == JsonType.Value && jsonObject.Value is string) { string text = (string)jsonObject.Value; return text.Length > 2 && text[0] == '@' && text[text.Length - 1] == '@'; } return false; } } internal class CustomDate : ICustomTextProvider { public string GetText(JsonObject jsonObject) { int year, month, day, hour, min, second, ms; year = (int)(long)jsonObject.Fields["y"].Value; month = (int)(long)jsonObject.Fields["M"].Value; day = (int)(long)jsonObject.Fields["d"].Value; hour = (int)(long)jsonObject.Fields["h"].Value; min = (int)(long)jsonObject.Fields["m"].Value; second = (int)(long)jsonObject.Fields["s"].Value; ms = (int)(long)jsonObject.Fields["ms"].Value; return new DateTime(year, month, day, hour, min, second, ms).ToString(); } public string DisplayName => "Date"; public bool CanVisualize(JsonObject jsonObject) { return jsonObject.ContainsFields("y", "M", "d", "h", "m", "s", "ms"); } } internal class Sample : IJsonVisualizer { private TextBox tb; public Control GetControl(JsonObject jsonObject) { if (tb == null) { tb = new TextBox(); tb.Multiline = true; } return tb; } public void Visualize(JsonObject jsonObject) { tb.Text = string.Format("Array {0} has {1} items", jsonObject.Id, jsonObject.Fields.Count); } public string DisplayName => "Sample"; public bool CanVisualize(JsonObject jsonObject) { return jsonObject.JsonType == JsonType.Array && jsonObject.ContainsFields("[0]"); } } }
31.86747
127
0.559546
[ "MIT" ]
ChenDaqian/JsonViewer
JsonViewer/InternalPlugins.cs
2,645
C#
/* * Copyright 2020 James Courtney * * 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 FlatSharp.Compiler { /// <summary> /// Defines the node at the root of the schema. /// </summary> internal class RootNodeDefinition : BaseSchemaMember { public RootNodeDefinition(string fileName) : base("", null) { this.DeclaringFile = fileName; } public string? InputHash { get; set; } protected override bool SupportsChildren => true; protected override void OnWriteCode(CodeWriter writer, CompileContext context) { writer.AppendLine($@" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by the FlatSharp FBS to C# compiler (source hash: {this.InputHash}) // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ "); writer.AppendLine("using System;"); writer.AppendLine("using System.Collections.Generic;"); writer.AppendLine("using System.Linq;"); writer.AppendLine("using System.Runtime.CompilerServices;"); writer.AppendLine("using System.Threading;"); writer.AppendLine("using System.Threading.Tasks;"); writer.AppendLine("using FlatSharp;"); writer.AppendLine("using FlatSharp.Attributes;"); // disable obsolete warnings. Flatsharp allows marking default constructors // as obsolete and we don't want to raise warnings for our own code. writer.AppendLine("#pragma warning disable 0618"); // Test hook to check deeply for nullability violations. #if NET5_0_OR_GREATER if (RoslynSerializerGenerator.EnableStrictValidation && context.Options.NullableWarnings == null) { context = context with { Options = context.Options with { NullableWarnings = true } }; } #endif if (context.Options.NullableWarnings == true) { writer.AppendLine("#nullable enable"); } else { writer.AppendLine("#nullable enable annotations"); } if (context.CompilePass > CodeWritingPass.PropertyModeling && context.PreviousAssembly is not null) { context.FullyQualifiedCloneMethodName = CloneMethodsGenerator.GenerateCloneMethodsForAssembly( writer, context.Options, context.PreviousAssembly, context.TypeModelContainer); } foreach (var child in this.Children.Values) { child.WriteCode(writer, context); } writer.AppendLine("#nullable restore"); writer.AppendLine("#pragma warning restore 0618"); } } }
36.22549
111
0.572124
[ "Apache-2.0" ]
StirlingLabs/FlatSharp
src/FlatSharp.Compiler/TypeDefinitions/RootNodeDefinition.cs
3,697
C#
using System; using System.Threading; using System.Threading.Tasks; using Elasticsearch.Net; namespace Nest { public partial interface IElasticClient { /// <inheritdoc /> DeletePipelineResponse DeletePipeline(Id id, Func<DeletePipelineDescriptor, IDeletePipelineRequest> selector = null); /// <inheritdoc /> DeletePipelineResponse DeletePipeline(IDeletePipelineRequest request); /// <inheritdoc /> Task<DeletePipelineResponse> DeletePipelineAsync(Id id, Func<DeletePipelineDescriptor, IDeletePipelineRequest> selector = null, CancellationToken cancellationToken = default ); /// <inheritdoc /> Task<DeletePipelineResponse> DeletePipelineAsync(IDeletePipelineRequest request, CancellationToken ct = default ); } public partial class ElasticClient { /// <inheritdoc /> public DeletePipelineResponse DeletePipeline(IDeletePipelineRequest request) => DoRequest<IDeletePipelineRequest, DeletePipelineResponse>(request, request.RequestParameters); /// <inheritdoc /> public DeletePipelineResponse DeletePipeline(Id id, Func<DeletePipelineDescriptor, IDeletePipelineRequest> selector = null) => DeletePipeline(selector.InvokeOrDefault(new DeletePipelineDescriptor(id))); /// <inheritdoc /> public Task<DeletePipelineResponse> DeletePipelineAsync( Id id, Func<DeletePipelineDescriptor, IDeletePipelineRequest> selector = null, CancellationToken cancellationToken = default ) => DeletePipelineAsync(selector.InvokeOrDefault(new DeletePipelineDescriptor(id)), cancellationToken); /// <inheritdoc /> public Task<DeletePipelineResponse> DeletePipelineAsync(IDeletePipelineRequest request, CancellationToken ct = default) => DoRequestAsync<IDeletePipelineRequest, DeletePipelineResponse>(request, request.RequestParameters, ct); } }
36.673469
129
0.794658
[ "Apache-2.0" ]
591094733/elasticsearch-net
src/Nest/Ingest/DeletePipeline/ElasticClient-DeletePipeline.cs
1,799
C#
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. // // ███╗ ██╗ ██████╗ ████████╗██╗ ██████╗███████╗ // ████╗ ██║██╔═══██╗╚══██╔══╝██║██╔════╝██╔════╝ // ██╔██╗ ██║██║ ██║ ██║ ██║██║ █████╗ // ██║╚██╗██║██║ ██║ ██║ ██║██║ ██╔══╝ // ██║ ╚████║╚██████╔╝ ██║ ██║╚██████╗███████╗ // ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝╚══════╝ // ------------------------------------------------ // // This file is automatically generated. // Please do not edit these files manually. // // ------------------------------------------------ using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Text.Json; using System.Text.Json.Serialization; #nullable restore namespace Elastic.Clients.Elasticsearch.Xpack { public partial class SecurityRolesFile { [JsonInclude] [JsonPropertyName("dls")] public bool Dls { get; init; } [JsonInclude] [JsonPropertyName("fls")] public bool Fls { get; init; } [JsonInclude] [JsonPropertyName("size")] public long Size { get; init; } } }
29.195122
76
0.487886
[ "Apache-2.0" ]
SimonCropp/elasticsearch-net
src/Elastic.Clients.Elasticsearch/_Generated/Types/Xpack/SecurityRolesFile.g.cs
1,643
C#
using Microsoft.EntityFrameworkCore; using Volo.Abp.Identity; using Volo.Abp.ObjectExtending; using Volo.Abp.Threading; namespace Profiler.EntityFrameworkCore { public static class ProfilerEfCoreEntityExtensionMappings { private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner(); public static void Configure() { ProfilerGlobalFeatureConfigurator.Configure(); ProfilerModuleExtensionConfigurator.Configure(); OneTimeRunner.Run(() => { /* You can configure extra properties for the * entities defined in the modules used by your application. * * This class can be used to map these extra properties to table fields in the database. * * USE THIS CLASS ONLY TO CONFIGURE EF CORE RELATED MAPPING. * USE ProfilerModuleExtensionConfigurator CLASS (in the Domain.Shared project) * FOR A HIGH LEVEL API TO DEFINE EXTRA PROPERTIES TO ENTITIES OF THE USED MODULES * * Example: Map a property to a table field: ObjectExtensionManager.Instance .MapEfCoreProperty<IdentityUser, string>( "MyProperty", (entityBuilder, propertyBuilder) => { propertyBuilder.HasMaxLength(128); } ); * See the documentation for more: * https://docs.abp.io/en/abp/latest/Customizing-Application-Modules-Extending-Entities */ }); } } }
38.391304
104
0.552095
[ "MIT" ]
271943794/abp-samples
MiniProfiler/src/Profiler.EntityFrameworkCore/EntityFrameworkCore/ProfilerEfCoreEntityExtensionMappings.cs
1,768
C#
//------------------------------------------------------------------------------ // <auto-generated> // Ce code a été généré par un outil. // // Les changements apportés à ce fichier peuvent provoquer un comportement incorrect et seront perdus si // le code est regénéré. // </auto-generated> //------------------------------------------------------------------------------ namespace ServiceReference1 { [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.2")] [System.ServiceModel.ServiceContractAttribute(ConfigurationName="ServiceReference1.IMathsOperations")] public interface IMathsOperations { [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IMathsOperations/Add", ReplyAction="http://tempuri.org/IMathsOperations/AddResponse")] System.Threading.Tasks.Task<int> AddAsync(int nb1, int nb2); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IMathsOperations/Multiply", ReplyAction="http://tempuri.org/IMathsOperations/MultiplyResponse")] System.Threading.Tasks.Task<int> MultiplyAsync(int nb1, int nb2); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IMathsOperations/Substract", ReplyAction="http://tempuri.org/IMathsOperations/SubstractResponse")] System.Threading.Tasks.Task<int> SubstractAsync(int nb1, int nb2); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IMathsOperations/divide", ReplyAction="http://tempuri.org/IMathsOperations/divideResponse")] System.Threading.Tasks.Task<double> divideAsync(double nb1, double nb2); } [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.2")] public interface IMathsOperationsChannel : ServiceReference1.IMathsOperations, System.ServiceModel.IClientChannel { } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.2")] public partial class MathsOperationsClient : System.ServiceModel.ClientBase<ServiceReference1.IMathsOperations>, ServiceReference1.IMathsOperations { /// <summary> /// Implémentez cette méthode partielle pour configurer le point de terminaison de service. /// </summary> /// <param name="serviceEndpoint">Point de terminaison à configurer</param> /// <param name="clientCredentials">Informations d'identification du client</param> static partial void ConfigureEndpoint(System.ServiceModel.Description.ServiceEndpoint serviceEndpoint, System.ServiceModel.Description.ClientCredentials clientCredentials); public MathsOperationsClient() : base(MathsOperationsClient.GetDefaultBinding(), MathsOperationsClient.GetDefaultEndpointAddress()) { this.Endpoint.Name = EndpointConfiguration.BasicHttpBinding_IMathsOperations.ToString(); ConfigureEndpoint(this.Endpoint, this.ClientCredentials); } public MathsOperationsClient(EndpointConfiguration endpointConfiguration) : base(MathsOperationsClient.GetBindingForEndpoint(endpointConfiguration), MathsOperationsClient.GetEndpointAddress(endpointConfiguration)) { this.Endpoint.Name = endpointConfiguration.ToString(); ConfigureEndpoint(this.Endpoint, this.ClientCredentials); } public MathsOperationsClient(EndpointConfiguration endpointConfiguration, string remoteAddress) : base(MathsOperationsClient.GetBindingForEndpoint(endpointConfiguration), new System.ServiceModel.EndpointAddress(remoteAddress)) { this.Endpoint.Name = endpointConfiguration.ToString(); ConfigureEndpoint(this.Endpoint, this.ClientCredentials); } public MathsOperationsClient(EndpointConfiguration endpointConfiguration, System.ServiceModel.EndpointAddress remoteAddress) : base(MathsOperationsClient.GetBindingForEndpoint(endpointConfiguration), remoteAddress) { this.Endpoint.Name = endpointConfiguration.ToString(); ConfigureEndpoint(this.Endpoint, this.ClientCredentials); } public MathsOperationsClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : base(binding, remoteAddress) { } public System.Threading.Tasks.Task<int> AddAsync(int nb1, int nb2) { return base.Channel.AddAsync(nb1, nb2); } public System.Threading.Tasks.Task<int> MultiplyAsync(int nb1, int nb2) { return base.Channel.MultiplyAsync(nb1, nb2); } public System.Threading.Tasks.Task<int> SubstractAsync(int nb1, int nb2) { return base.Channel.SubstractAsync(nb1, nb2); } public System.Threading.Tasks.Task<double> divideAsync(double nb1, double nb2) { return base.Channel.divideAsync(nb1, nb2); } public virtual System.Threading.Tasks.Task OpenAsync() { return System.Threading.Tasks.Task.Factory.FromAsync(((System.ServiceModel.ICommunicationObject)(this)).BeginOpen(null, null), new System.Action<System.IAsyncResult>(((System.ServiceModel.ICommunicationObject)(this)).EndOpen)); } public virtual System.Threading.Tasks.Task CloseAsync() { return System.Threading.Tasks.Task.Factory.FromAsync(((System.ServiceModel.ICommunicationObject)(this)).BeginClose(null, null), new System.Action<System.IAsyncResult>(((System.ServiceModel.ICommunicationObject)(this)).EndClose)); } private static System.ServiceModel.Channels.Binding GetBindingForEndpoint(EndpointConfiguration endpointConfiguration) { if ((endpointConfiguration == EndpointConfiguration.BasicHttpBinding_IMathsOperations)) { System.ServiceModel.BasicHttpBinding result = new System.ServiceModel.BasicHttpBinding(); result.MaxBufferSize = int.MaxValue; result.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max; result.MaxReceivedMessageSize = int.MaxValue; result.AllowCookies = true; return result; } throw new System.InvalidOperationException(string.Format("Le point de terminaison nommé \'{0}\' est introuvable.", endpointConfiguration)); } private static System.ServiceModel.EndpointAddress GetEndpointAddress(EndpointConfiguration endpointConfiguration) { if ((endpointConfiguration == EndpointConfiguration.BasicHttpBinding_IMathsOperations)) { return new System.ServiceModel.EndpointAddress("http://localhost:8733/Design_Time_Addresses/MathsLibrary/MathsOperations/"); } throw new System.InvalidOperationException(string.Format("Le point de terminaison nommé \'{0}\' est introuvable.", endpointConfiguration)); } private static System.ServiceModel.Channels.Binding GetDefaultBinding() { return MathsOperationsClient.GetBindingForEndpoint(EndpointConfiguration.BasicHttpBinding_IMathsOperations); } private static System.ServiceModel.EndpointAddress GetDefaultEndpointAddress() { return MathsOperationsClient.GetEndpointAddress(EndpointConfiguration.BasicHttpBinding_IMathsOperations); } public enum EndpointConfiguration { BasicHttpBinding_IMathsOperations, } } }
52.052632
241
0.683392
[ "MIT" ]
alexandre-girard-moi/eiin839
TD4/SOAP/SOAP_WEB_SERVICE/SOAP_WEB_SERVICE/Connected Services/ServiceReference1/Reference.cs
7,929
C#
namespace MassTransit.EntityFrameworkIntegration.Tests { using System; using System.Collections.Generic; using System.Data.Entity; using System.Threading.Tasks; using MassTransit.Saga; using NUnit.Framework; using Saga; using TestFramework; using Testing; [TestFixture] [Category("EntityFramework")] [Category("Flaky")] public class When_using_EntityFrameworkConcurrencyFail : InMemoryTestFixture { [Test] public async Task Should_not_capture_all_events_many_sagas() { var tasks = new List<Task>(); var sagaIds = new Guid[20]; for (var i = 0; i < 20; i++) { var correlationId = NewId.NextGuid(); await InputQueueSendEndpoint.Send(new RehersalBegins {CorrelationId = correlationId}); sagaIds[i] = correlationId; } for (var i = 0; i < 20; i++) { Guid? sagaId = await _repository.Value.ShouldContainSaga(sagaIds[i], TestTimeout); Assert.IsTrue(sagaId.HasValue); } for (var i = 0; i < 20; i++) { tasks.Add(InputQueueSendEndpoint.Send(new Bass { CorrelationId = sagaIds[i], Name = "John" })); tasks.Add(InputQueueSendEndpoint.Send(new Baritone { CorrelationId = sagaIds[i], Name = "Mark" })); tasks.Add(InputQueueSendEndpoint.Send(new Tenor { CorrelationId = sagaIds[i], Name = "Anthony" })); tasks.Add(InputQueueSendEndpoint.Send(new Countertenor { CorrelationId = sagaIds[i], Name = "Tom" })); } await Task.WhenAll(tasks); tasks.Clear(); foreach (var sid in sagaIds) { Guid? sagaId = await _repository.Value.ShouldContainSagaInState(sid, _machine, _machine.Warmup, TestTimeout); Assert.IsTrue(sagaId.HasValue); } } [Test] public async Task Should_not_capture_all_events_single_saga() { var correlationId = Guid.NewGuid(); await InputQueueSendEndpoint.Send(new RehersalBegins {CorrelationId = correlationId}); Guid? sagaId = await _repository.Value.ShouldContainSaga(correlationId, TestTimeout); Assert.IsTrue(sagaId.HasValue); await Task.WhenAll( InputQueueSendEndpoint.Send(new Bass { CorrelationId = correlationId, Name = "John" }), InputQueueSendEndpoint.Send(new Baritone { CorrelationId = correlationId, Name = "Mark" }), InputQueueSendEndpoint.Send(new Tenor { CorrelationId = correlationId, Name = "Anthony" }), InputQueueSendEndpoint.Send(new Countertenor { CorrelationId = correlationId, Name = "Tom" }) ); sagaId = await _repository.Value.ShouldContainSagaInState(correlationId, _machine, _machine.Warmup, TestTimeout); Assert.IsTrue(sagaId.HasValue); } ChoirStateMachine _machine; readonly ISagaDbContextFactory<ChoirStateOptimistic> _sagaDbContextFactory; readonly Lazy<ISagaRepository<ChoirStateOptimistic>> _repository; protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator) { _machine = new ChoirStateMachine(); configurator.StateMachineSaga(_machine, _repository.Value); } public When_using_EntityFrameworkConcurrencyFail() { _sagaDbContextFactory = new DelegateSagaDbContextFactory<ChoirStateOptimistic>(() => new ChoirStateOptimisticSagaDbContext(LocalDbConnectionStringProvider.GetLocalDbConnectionString())); _repository = new Lazy<ISagaRepository<ChoirStateOptimistic>>(() => EntityFrameworkSagaRepository<ChoirStateOptimistic>.CreateOptimistic(_sagaDbContextFactory)); } async Task<ChoirStateOptimistic> GetSaga(Guid id) { using (var dbContext = _sagaDbContextFactory.Create()) { return await dbContext.Set<ChoirStateOptimistic>().SingleOrDefaultAsync(x => x.CorrelationId == id); } } protected override void ConfigureInMemoryBus(IInMemoryBusFactoryConfigurator configurator) { base.ConfigureInMemoryBus(configurator); configurator.TransportConcurrencyLimit = 16; } } }
33.642384
125
0.558858
[ "ECL-2.0", "Apache-2.0" ]
AhmedKhalil777/MassTransit
tests/MassTransit.EntityFrameworkIntegration.Tests/UsingEntityFrameworkConcurrencyFail_Specs.cs
5,082
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; using AnnoDesigner.Core.Models; using AnnoDesigner.model; namespace AnnoDesigner.viewmodel { public class WelcomeViewModel : Notify { private readonly ICommons _commons; private readonly IAppSettings _appSettings; private ObservableCollection<SupportedLanguage> _languages; private SupportedLanguage _selectedItem; public WelcomeViewModel(ICommons commonsToUse, IAppSettings appSettingsToUse) { _commons = commonsToUse; _appSettings = appSettingsToUse; Languages = new ObservableCollection<SupportedLanguage>(); Languages.Add(new SupportedLanguage("English") { FlagPath = "Flags/United Kingdom.png" }); Languages.Add(new SupportedLanguage("Deutsch") { FlagPath = "Flags/Germany.png" }); Languages.Add(new SupportedLanguage("Français") { FlagPath = "Flags/France.png" }); Languages.Add(new SupportedLanguage("Polski") { FlagPath = "Flags/Poland.png" }); Languages.Add(new SupportedLanguage("Русский") { FlagPath = "Flags/Russia.png" }); ContinueCommand = new RelayCommand(Continue, CanContinue); } public ObservableCollection<SupportedLanguage> Languages { get { return _languages; } set { UpdateProperty(ref _languages, value); } } public SupportedLanguage SelectedItem { get { return _selectedItem; } set { UpdateProperty(ref _selectedItem, value); } } public ICommand ContinueCommand { get; private set; } private void Continue(object param) { LoadSelectedLanguage(param as ICloseable); } private bool CanContinue(object param) { return SelectedItem != null; } private void LoadSelectedLanguage(ICloseable window) { _commons.SelectedLanguage = SelectedItem.Name; _appSettings.SelectedLanguage = _commons.SelectedLanguage; _appSettings.Save(); window?.Close(); } } }
29.174419
85
0.598645
[ "MIT" ]
AgmasGold/anno-designer
AnnoDesigner/viewmodel/WelcomeViewModel.cs
2,519
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable namespace Azure.Communication.CallingServer { /// <summary> The request payload for cancel all media operations. </summary> internal partial class CancelAllMediaOperationsRequest { /// <summary> Initializes a new instance of CancelAllMediaOperationsRequest. </summary> public CancelAllMediaOperationsRequest() { } /// <summary> The context for this operation. </summary> public string OperationContext { get; set; } } }
28.318182
95
0.691814
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/communication/Azure.Communication.CallingServer/src/Generated/Models/CancelAllMediaOperationsRequest.cs
623
C#
using SpecsFor.Configuration; namespace SpecsFor.Tests.ComposingContext.TestDomain { public class ProvideMagicByTypeName : Behavior<ISpecs> { public override void Given(ISpecs instance) { ((ILikeMagic)instance).CalledByDuringGiven.Add(GetType().Name); } public override void AfterSpec(ISpecs instance) { ((ILikeMagic)instance).CalledByAfterTest.Add(GetType().Name); } } }
24.117647
67
0.729268
[ "MIT" ]
milesibastos/SpecsFor
SpecsFor.Tests/ComposingContext/TestDomain/ProvideMagicByTypeName.cs
410
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.EntityFrameworkCore.ValueGeneration; public class GuidValueGeneratorTest { [ConditionalFact] public void Creates_GUIDs() { var sequentialGuidIdentityGenerator = new GuidValueGenerator(); var values = new HashSet<Guid>(); for (var i = 0; i < 100; i++) { var generatedValue = sequentialGuidIdentityGenerator.Next(null); values.Add(generatedValue); } Assert.Equal(100, values.Count); } [ConditionalFact] public void Does_not_generate_temp_values() => Assert.False(new GuidValueGenerator().GeneratesTemporaryValues); }
27.928571
76
0.681586
[ "MIT" ]
Applesauce314/efcore
test/EFCore.Tests/ValueGeneration/GuidValueGeneratorTest.cs
782
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Htp.ITnews.Domain.Contracts.ViewModels; using Microsoft.EntityFrameworkCore; namespace Htp.ITnews.Web.Helpers { public class PaginatedList<T> : List<T> { public int PageIndex { get; private set; } public int TotalPages { get; private set; } public PaginatedList(List<T> items, int count, int pageIndex, int pageSize) { PageIndex = pageIndex; TotalPages = (int)Math.Ceiling(count / (double)pageSize); this.AddRange(items); } public bool HasPreviousPage { get { return (PageIndex > 1); } } public bool HasNextPage { get { return (PageIndex < TotalPages); } } public static async Task<PaginatedList<T>> CreateAsync( IQueryable<T> source, int pageIndex, int pageSize) { var count = await source.CountAsync(); var items = await source .Skip((pageIndex - 1) * pageSize) .Take(pageSize) .ToListAsync(); return new PaginatedList<T>(items, count, pageIndex, pageSize); } internal static Task<PaginatedList<NewsViewModel>> CreateAsync(IQueryable<NewsViewModel> queryable, object p, int pageSize) { throw new NotImplementedException(); } } }
27.464286
131
0.56502
[ "MIT" ]
chertby/Course-M-ND2-33-19
Skuratovich/src/ITnews/Htp.ITnews/Htp.ITnews.Web/Helpers/PaginatedList.cs
1,540
C#
using Abp.Application.Services.Dto; namespace IIASA.FloodCitiSense.DataTypes.Dtos { public class GetAllCitiesInput : PagedAndSortedResultRequestDto { public string Filter { get; set; } public string NameFilter { get; set; } public string UserNameFilter { get; set; } } }
19.5
67
0.682692
[ "MIT" ]
FloodCitiSense/FloodCitiSense
aspnet-core/src/IIASA.FloodCitiSense.Application.Shared/Datatypes/Dtos/GetAllCitiesInput.cs
312
C#
/* Licensed under the MIT/X11 license. * Copyright (c) 2016-2018 jointly owned by eBestow Technocracy India Pvt. Ltd. & M&M Info-Tech UK Ltd. * This notice may not be removed from any source distribution. * See license.txt for detailed licensing details. */ // Author: Mukesh Adhvaryu. namespace MnM.GWS { #if Dates || Advanced using System; #region CHANGE TYPE /// <summary> /// Enum ChangeType /// </summary> public enum DateChangeType { /// <summary> /// The date replacement /// </summary> DateReplacement, /// <summary> /// The day increment /// </summary> DayIncrement, /// <summary> /// The day replacement /// </summary> DayReplacement, /// <summary> /// The month increment /// </summary> MonthIncrement, /// <summary> /// The month replacement /// </summary> MonthReplacement, /// <summary> /// The year increment /// </summary> YearIncrement, /// <summary> /// The year replacement /// </summary> YearReplacement } #endregion #region DATE INTERVAL /// <summary> /// Enum DateInterval /// </summary> public enum DateInterval { /// <summary> /// The year /// </summary> Year, /// <summary> /// The month /// </summary> Month, /// <summary> /// The weekday /// </summary> Weekday, /// <summary> /// The day /// </summary> Day, /// <summary> /// The hour /// </summary> Hour, /// <summary> /// The minute /// </summary> Minute, /// <summary> /// The second /// </summary> Second } #endregion #region HMDifference /// <summary> /// Enum HMDifference /// </summary> public enum HMDifference { /// <summary> /// As it is /// </summary> AsItIs, /// <summary> /// The positive /// </summary> Positive, /// <summary> /// The zero if negative /// </summary> ZeroIFNegative } #endregion #region RETURNDATE /// <summary> /// Enum ReturnDate /// </summary> public enum ReturnDate { /// <summary> /// The smaller /// </summary> Smaller, /// <summary> /// The bigger /// </summary> Bigger, /// <summary> /// The near match /// </summary> NearMatch } #endregion #endif }
21.421875
102
0.464624
[ "MIT" ]
MnMInfoTech/GWS
GWSCommon/Enums/DateTime.cs
2,744
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class SwitchMenu : MonoBehaviour { public void ShowRanks() { SceneManager.LoadScene(1); } public void BackToMainPage() { SceneManager.LoadScene(0); } public void SwitchPage(int sceneNumber) { SceneManager.LoadScene(sceneNumber); } }
18.173913
44
0.681818
[ "Apache-2.0" ]
HawkEyyeAce/PlayerRankingModule
Assets/Scripts/SwitchMenu.cs
420
C#
#pragma checksum "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\Modules\Image\Image.razor" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "570f6dc8aae5a4ecae9c53078d66fe3665cca23d" // <auto-generated/> #pragma warning disable 1591 #pragma warning disable 0414 #pragma warning disable 0649 #pragma warning disable 0169 namespace YourSpace.Modules.Image { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; #nullable restore #line 1 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using System.Net.Http; #line default #line hidden #nullable disable #nullable restore #line 2 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using Microsoft.AspNetCore.Authorization; #line default #line hidden #nullable disable #nullable restore #line 3 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using Microsoft.AspNetCore.Components.Authorization; #line default #line hidden #nullable disable #nullable restore #line 4 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using Microsoft.AspNetCore.Components.Forms; #line default #line hidden #nullable disable #nullable restore #line 5 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using Microsoft.AspNetCore.Components.Routing; #line default #line hidden #nullable disable #nullable restore #line 6 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using Microsoft.AspNetCore.Components.Web; #line default #line hidden #nullable disable #nullable restore #line 7 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using Microsoft.JSInterop; #line default #line hidden #nullable disable #nullable restore #line 8 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace; #line default #line hidden #nullable disable #nullable restore #line 9 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Shared; #line default #line hidden #nullable disable #nullable restore #line 11 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.ModalWindow; #line default #line hidden #nullable disable #nullable restore #line 13 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.Pages.Page; #line default #line hidden #nullable disable #nullable restore #line 14 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.Pages.Page.Models; #line default #line hidden #nullable disable #nullable restore #line 15 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.Pages.Page.Components; #line default #line hidden #nullable disable #nullable restore #line 16 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.Pages.Page.ModifyComponents; #line default #line hidden #nullable disable #nullable restore #line 17 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.Pages.Blocks.ModifyComponents; #line default #line hidden #nullable disable #nullable restore #line 18 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.Pages.Blocks.Components; #line default #line hidden #nullable disable #nullable restore #line 19 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.Pages.Blocks.Models; #line default #line hidden #nullable disable #nullable restore #line 20 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.Pages.Blocks; #line default #line hidden #nullable disable #nullable restore #line 21 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.Pages.Groups.ModifyComponents; #line default #line hidden #nullable disable #nullable restore #line 22 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.Pages.Groups.ViewMode; #line default #line hidden #nullable disable #nullable restore #line 23 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.Pages.Groups.Models; #line default #line hidden #nullable disable #nullable restore #line 25 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.ThingCounter; #line default #line hidden #nullable disable #nullable restore #line 26 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.ThingCounter.Components; #line default #line hidden #nullable disable #nullable restore #line 28 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.DataWorker; #line default #line hidden #nullable disable #nullable restore #line 29 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.Cloner; #line default #line hidden #nullable disable #nullable restore #line 30 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.Gallery; #line default #line hidden #nullable disable #nullable restore #line 31 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.Gallery.Models; #line default #line hidden #nullable disable #nullable restore #line 32 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.FileUpload; #line default #line hidden #nullable disable #nullable restore #line 33 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.Inputs; #line default #line hidden #nullable disable #nullable restore #line 35 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.Moderation; #line default #line hidden #nullable disable #nullable restore #line 36 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.Moderation.Models; #line default #line hidden #nullable disable #nullable restore #line 38 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.ComponentsView; #line default #line hidden #nullable disable #nullable restore #line 39 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Services; #line default #line hidden #nullable disable #nullable restore #line 40 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.Lister; #line default #line hidden #nullable disable #nullable restore #line 41 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.Image; #line default #line hidden #nullable disable #nullable restore #line 43 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.UserProfile; #line default #line hidden #nullable disable #nullable restore #line 44 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.UserProfile.Compoents; #line default #line hidden #nullable disable #nullable restore #line 46 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using Microsoft.Extensions.Localization; #line default #line hidden #nullable disable #nullable restore #line 47 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.Localization; #line default #line hidden #nullable disable #nullable restore #line 48 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using YourSpace.Modules.Music; #line default #line hidden #nullable disable #nullable restore #line 50 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\_Imports.razor" using BlazorInputFile; #line default #line hidden #nullable disable public partial class Image : Microsoft.AspNetCore.Components.ComponentBase { #pragma warning disable 1998 protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) { } #pragma warning restore 1998 #nullable restore #line 5 "C:\Users\qzwse\source\repos\YourSpaceMDB_4.2\YourSpace\Modules\Image\Image.razor" [Parameter] public string src { get; set; } [Parameter] public string Class { get; set; } [Parameter] public bool FullScreenEnabled { get; set; } = true; [Inject] protected ISModal SModal { get; set; } void ShowFullScreen() { if(FullScreenEnabled) { var p = new ModalParameters(); p.Add("Image", src); var o = new ModalOptions(); o.HideHeader = true; o.Style = "none"; SModal.Show<ImageFullScreen>("Image", p, o, null); } } #line default #line hidden #nullable disable } } #pragma warning restore 1591
26.867257
183
0.788757
[ "MIT" ]
Invectys/Sites
YourSpaceMDB_4.2_Optimization/YourSpace/obj/Debug/netcoreapp3.0/RazorDeclaration/Modules/Image/Image.razor.g.cs
9,108
C#
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Web.Http; namespace System.Net.Http { /// <summary> /// Provides extension methods for the <see cref="HttpRequestMessage"/> class. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public static class HttpRequestMessageExtensions { /// <summary> /// Creates an <see cref="HttpResponseMessage"/> wired up to the associated <see cref="HttpRequestMessage"/>. /// </summary> /// <param name="request">The HTTP request.</param> /// <param name="statusCode">The HTTP status code.</param> /// <returns>An initialized <see cref="HttpResponseMessage"/>.</returns> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Caller will dispose")] public static HttpResponseMessage CreateResponse(this HttpRequestMessage request, HttpStatusCode statusCode) { if (request == null) { throw Error.ArgumentNull("request"); } return new HttpResponseMessage { StatusCode = statusCode, RequestMessage = request }; } /// <summary> /// Creates an <see cref="HttpResponseMessage"/> wired up to the associated <see cref="HttpRequestMessage"/>. /// </summary> /// <param name="request">The HTTP request.</param> /// <returns>An initialized <see cref="HttpResponseMessage"/>.</returns> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Caller will dispose")] public static HttpResponseMessage CreateResponse(this HttpRequestMessage request) { if (request == null) { throw Error.ArgumentNull("request"); } return new HttpResponseMessage { RequestMessage = request }; } } }
38.803571
135
0.617579
[ "Apache-2.0" ]
Distrotech/mono
external/aspnetwebstack/src/System.Net.Http.Formatting/HttpRequestMessageExtensions.cs
2,175
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.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; namespace Microsoft.AspNetCore.Mvc.Razor.Extensions { internal class ViewComponentTypeVisitor : SymbolVisitor { private readonly INamedTypeSymbol _viewComponentAttribute; private readonly INamedTypeSymbol _nonViewComponentAttribute; private readonly List<INamedTypeSymbol> _results; public ViewComponentTypeVisitor( INamedTypeSymbol viewComponentAttribute, INamedTypeSymbol nonViewComponentAttribute, List<INamedTypeSymbol> results) { _viewComponentAttribute = viewComponentAttribute; _nonViewComponentAttribute = nonViewComponentAttribute; _results = results; } public override void VisitNamedType(INamedTypeSymbol symbol) { if (IsViewComponent(symbol)) { _results.Add(symbol); } if (symbol.DeclaredAccessibility != Accessibility.Public) { return; } foreach (var member in symbol.GetTypeMembers()) { Visit(member); } } public override void VisitNamespace(INamespaceSymbol symbol) { foreach (var member in symbol.GetMembers()) { Visit(member); } } internal bool IsViewComponent(INamedTypeSymbol symbol) { if (_viewComponentAttribute == null) { return false; } if (symbol.DeclaredAccessibility != Accessibility.Public || symbol.IsAbstract || symbol.IsGenericType || AttributeIsDefined(symbol, _nonViewComponentAttribute)) { return false; } return symbol.Name.EndsWith(ViewComponentTypes.ViewComponentSuffix) || AttributeIsDefined(symbol, _viewComponentAttribute); } private static bool AttributeIsDefined(INamedTypeSymbol type, INamedTypeSymbol queryAttribute) { if (type == null || queryAttribute == null) { return false; } var attribute = type.GetAttributes().Where(a => Equals(a.AttributeClass, queryAttribute)).FirstOrDefault(); if (attribute != null) { return true; } return AttributeIsDefined(type.BaseType, queryAttribute); } } }
30.842697
119
0.588342
[ "Apache-2.0" ]
Pilchie/aspnetcore-tooling
src/Razor/src/Microsoft.AspNetCore.Mvc.Razor.Extensions/ViewComponentTypeVisitor.cs
2,747
C#
// Copyright 2015 Google 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. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using WindowsAccessBridgeInterop.Win32; namespace WindowsAccessBridgeInterop { /// <summary> /// Class used to dynamically load and access the Java Access Bridge DLL. /// </summary> public class AccessBridge : IDisposable { private AccessBridgeLibrary _library; private AccessBridgeFunctions _functions; private AccessBridgeEvents _events; private bool _disposed; public AccessBridge() { CollectionSizeLimit = 100; TextLineCountLimit = 200; TextLineLengthLimit = 200; TextBufferLengthLimit = 1024; } public AccessBridgeFunctions Functions { get { ThrowIfDisposed(); Initialize(false); return _functions; } } public AccessBridgeEvents Events { get { ThrowIfDisposed(); Initialize(false); return _events; } } public bool IsLoaded { get { return _library != null; } } public FileVersionInfo LibraryVersion { get { ThrowIfDisposed(); Initialize(false); return _library.Version; } } public bool IsLegacy { get { ThrowIfDisposed(); Initialize(false); return _library.IsLegacy; } } public int CollectionSizeLimit { get; set; } public int TextLineCountLimit { get; set; } public int TextLineLengthLimit { get; set; } public int TextBufferLengthLimit { get; set; } public event EventHandler Initilized; public event EventHandler Disposed; public void Initialize(bool ForceLegacy) { ThrowIfDisposed(); if (_library != null) return; var library = LoadLibrary(ForceLegacy); if (library.IsLegacy) { var libraryFunctions = LoadEntryPointsLegacy(library); var functions = new AccessBridgeNativeFunctionsLegacy(libraryFunctions); var events = new AccessBridgeNativeEventsLegacy(libraryFunctions); // Everything is initialized correctly, save to member variables. _library = library; _functions = functions; _events = events; } else { var libraryFunctions = LoadEntryPoints(library); var functions = new AccessBridgeNativeFunctions(libraryFunctions); var events = new AccessBridgeNativeEvents(libraryFunctions); // Everything is initialized correctly, save to member variables. _library = library; _functions = functions; _events = events; } _functions.Windows_run(); OnInitilized(); } public void Dispose() { if (_disposed) return; if (_events != null) { _events.Dispose(); } if (_library != null) { _library.Dispose(); _functions = null; _library = null; } _disposed = true; OnDisposed(); } private void ThrowIfDisposed() { if (_disposed) throw new ObjectDisposedException("Access Bridge library has been disposed"); } public List<AccessibleJvm> EnumJvms() { return EnumJvms(hwnd => { return CreateAccessibleWindow(hwnd); }); } public List<AccessibleJvm> EnumJvms(Func<IntPtr, AccessibleWindow> windowFunc) { if (_library == null) return new List<AccessibleJvm>(); try { var windows = new List<AccessibleWindow>(); var success = NativeMethods.EnumWindows((hWnd, lParam) => { var window = windowFunc(hWnd); if (window != null) { windows.Add(window); } return true; }, IntPtr.Zero); if (!success) { var hr = Marshal.GetHRForLastWin32Error(); Marshal.ThrowExceptionForHR(hr); } // Group windows by JVM id return windows.GroupBy(x => x.JvmId).Select(g => { var result = new AccessibleJvm(this, g.Key); result.Windows.AddRange(g.OrderBy(x => x.GetDisplaySortString())); return result; }).OrderBy(x => x.JvmId).ToList(); } catch (Exception e) { throw new ApplicationException("Error detecting running applications", e); } } public AccessibleWindow CreateAccessibleWindow(IntPtr hwnd) { if (!Functions.IsJavaWindow(hwnd)) return null; int vmId; JavaObjectHandle ac; //Console.WriteLine("Value : {0:X}", hwnd); //Console.WriteLine("Value : {0:X}", hwnd.ToInt64()); if (!Functions.GetAccessibleContextFromHWND(hwnd, out vmId, out ac)) return null; return new AccessibleWindow(this, hwnd, ac); } public class AccessBridgeLibrary : UnmanagedLibrary { public AccessBridgeLibrary(string fileName) : base(fileName) { } public bool IsLegacy { get; set; } } private static AccessBridgeLibrary LoadLibrary(bool ForceLegacy) { try { AccessBridgeLibrary library; if(ForceLegacy) { library = new AccessBridgeLibrary("WindowsAccessBridge.dll"); library.IsLegacy = true; } else if (IntPtr.Size == 4) { try { library = new AccessBridgeLibrary("WindowsAccessBridge-32.dll"); } catch { try { library = new AccessBridgeLibrary("WindowsAccessBridge.dll"); library.IsLegacy = true; } catch { // Ignore, we'll trow the initial exception library = null; } if (library == null) throw; } } else if (IntPtr.Size == 8) { library = new AccessBridgeLibrary("WindowsAccessBridge-64.dll"); } else { throw new InvalidOperationException("Unknown platform."); } return library; } catch (Exception e) { var sb = new StringBuilder(); sb.AppendLine("Error loading the Java Access Bridge DLL."); sb.AppendLine("This usually happens if the Java Access Bridge is not installed."); if (IntPtr.Size == 8) { sb.Append("Please make sure to install the 64-bit version of the " + "Java SE Runtime Environment version 7 or later. "); sb.AppendFormat("Alternatively, try running the 32-bit version of {0} " + "if a 32-bit version of the JRE is installed.", Assembly.GetEntryAssembly().GetName().Name); } else { sb.Append( "Please make sure to install the 32-bit version of the " + "Java SE Runtime Environment version 7 or later."); } throw new ApplicationException(sb.ToString(), e); } } private static AccessBridgeEntryPoints LoadEntryPoints(UnmanagedLibrary library) { var functions = new AccessBridgeEntryPoints(); LoadEntryPointsImpl(library, functions); return functions; } private static AccessBridgeEntryPointsLegacy LoadEntryPointsLegacy(UnmanagedLibrary library) { var functions = new AccessBridgeEntryPointsLegacy(); LoadEntryPointsImpl(library, functions); return functions; } private static void LoadEntryPointsImpl(UnmanagedLibrary library, object functions) { var publicMembers = BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance; foreach (var property in functions.GetType().GetProperties(publicMembers)) { var name = property.Name; // All entry point names have lower case, except for "Windows_run" switch (name) { case "Windows_run": break; default: name = char.ToLower(name[0], CultureInfo.InvariantCulture) + name.Substring(1); break; } // Event setters have a "FP" suffix if (name.StartsWith("set") && name != "setTextContents") { name += "FP"; } try { var function = library.GetUnmanagedFunction(name, property.PropertyType); if (function == null) { throw new ApplicationException(string.Format("Function {0} not found in AccessBridge", name)); } property.SetValue(functions, function, null); } catch (Exception e) { throw new ArgumentException(string.Format("Error loading function {0} from access bridge library", name), e); } } } protected virtual void OnInitilized() { var handler = Initilized; if (handler != null) handler(this, EventArgs.Empty); } protected virtual void OnDisposed() { var handler = Disposed; if (handler != null) handler(this, EventArgs.Empty); } } }
31.651007
119
0.621607
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
IBM/openrpa
WindowsAccessBridgeInterop/AccessBridge.cs
9,434
C#
using System; using System.Collections.Generic; using System.Text; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; namespace EasyShare.Data { public class ApplicationDbContext : IdentityDbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } } }
24.117647
84
0.704878
[ "Apache-2.0" ]
andandrijana/EasyShareCap
EasyShare/Data/ApplicationDbContext.cs
412
C#
using System; using System.Collections.Concurrent; using NuGet.Protocol.Plugins; namespace JetBrains.TeamCity.NuGet.RequestHandlers { /// <summary> /// Represents a collection of NuGet plug-in request handlers. /// </summary> /// <remarks>This custom collection is used instead of <see cref="JetBrains.TeamCity.NuGet.RequestHandlers"/> because it inherits /// <see cref="ConcurrentDictionary{TKey,TValue}"/> which allows for the initializer syntax.</remarks> internal class RequestHandlerCollection : ConcurrentDictionary<MessageMethod, IRequestHandler>, IRequestHandlers { public void Add(MessageMethod method, IRequestHandler handler) { TryAdd(method, handler); } public void AddOrUpdate(MessageMethod method, Func<IRequestHandler> addHandlerFunc, Func<IRequestHandler, IRequestHandler> updateHandlerFunc) { AddOrUpdate(method, messageMethod => addHandlerFunc(), (messageMethod, requestHandler) => updateHandlerFunc(requestHandler)); } public bool TryGet(MessageMethod method, out IRequestHandler requestHandler) { return TryGetValue(method, out requestHandler); } public bool TryRemove(MessageMethod method) { return TryRemove(method, out IRequestHandler _); } } }
36.028571
145
0.747819
[ "ECL-2.0", "Apache-2.0", "BSD-3-Clause" ]
JetBrains/teamcity-nuget-support
nuget-extensions/nuget-plugin/RequestHandlers/RequestHandlerCollection.cs
1,263
C#
namespace RelhaxModpack.Utilities.Enums { /// <summary> /// The build distribution version of the application /// </summary> public enum ApplicationVersions { /// <summary> /// The stable distribution for all users /// </summary> Stable, /// <summary> /// The beta distribution, for advanced users, may have new features or improvements, and bugs /// </summary> Beta, /// <summary> /// The alpha distribution. Should never be publicly distributed /// </summary> Alpha } }
28.190476
102
0.569257
[ "Apache-2.0" ]
Arkhorse/RelhaxModpack
RelhaxModpack/RelhaxModpack/Utilities/Enums/ApplicationVersions.cs
594
C#
using Entitas; using System.Collections; [Pool] public class CoroutineComponent : IComponent { public IEnumerator value; }
14.222222
44
0.773438
[ "MIT" ]
409544041/entitas-2d-roguelike
Assets/Sources/Features/Coroutine/CoroutineComponent.cs
128
C#
using DotNetSurfer_Backend.Core.Models; namespace DotNetSurfer.Core.TokenGenerators { public interface ITokenGenerator { string GetToken(User user); } }
17.5
43
0.725714
[ "MIT" ]
kims07231992/DotNetSurfer_Backend
DotNetSurfer_Backend/src/Core/DotNetSurfer_Backend.Core/Interfaces/TokenGenerators/ITokenGenerator.cs
177
C#
#region Header /** * IJsonWrapper.cs * Interface that represents a type capable of handling all kinds of JSON * data. This is mainly used when mapping objects through JsonMapper, and * it's implemented by JsonData. * * The authors disclaim copyright to this source code. For more details, see * the COPYING file included with this distribution. **/ #endregion Header using System.Collections; using System.Collections.Specialized; namespace CrowSerialization.LitJson { public enum JsonType { None, Object, Array, String, Int, Long, Double, Boolean } public interface IJsonWrapper : IList, IOrderedDictionary { bool IsArray { get; } bool IsBoolean { get; } bool IsDouble { get; } bool IsInt { get; } bool IsLong { get; } bool IsObject { get; } bool IsString { get; } bool GetBoolean (); double GetDouble (); int GetInt (); JsonType GetJsonType (); long GetLong (); string GetString (); void SetBoolean ( bool val ); void SetDouble ( double val ); void SetInt ( int val ); void SetJsonType ( JsonType type ); void SetLong ( long val ); void SetString ( string val ); string ToJson (); void ToJson ( JsonWriter writer ); } }
15.909091
76
0.675918
[ "MIT" ]
Benkei/Crow
CrowSerialization/LitJson/IJsonWrapper.cs
1,225
C#
namespace Liquid.Core.Telemetry.ElasticApm.Tests.Mocks { public sealed class ResponseMock { } }
15.571429
55
0.706422
[ "MIT" ]
Avanade/Liquid.Core
test/Liquid.Core.Telemetry.ElasticApm.Tests/Mocks/ResponseMock.cs
111
C#
// ***************************************************************************** // // © Component Factory Pty Ltd, 2006 - 2016. All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, PO Box 1504, // Glen Waverley, Vic 3150, Australia and are supplied subject to licence terms. // // Version 5.400.0.0 www.ComponentFactory.com // ***************************************************************************** using System; using System.Drawing; using System.Windows.Forms; using ComponentFactory.Krypton.Ribbon; using ComponentFactory.Krypton.Toolkit; namespace KryptonGalleryExamples { public partial class Form1 : KryptonForm { public Form1() { InitializeComponent(); } private void radioSmallList_CheckedChanged(object sender, EventArgs e) { if (radioSmallList.Checked) kryptonGallery1.ImageList = imageListSmall; } private void radioMediumList_CheckedChanged(object sender, EventArgs e) { if (radioMediumList.Checked) kryptonGallery1.ImageList = imageListMedium; } private void radioLargeList_CheckedChanged(object sender, EventArgs e) { if (radioLargeList.Checked) kryptonGallery1.ImageList = imageListLarge; } private void numericWidth_ValueChanged(object sender, EventArgs e) { kryptonGallery1.PreferredItemSize = new Size(Convert.ToInt32(numericWidth.Value), kryptonGallery1.PreferredItemSize.Height); } private void numericHeight_ValueChanged(object sender, EventArgs e) { kryptonGallery1.PreferredItemSize = new Size(kryptonGallery1.PreferredItemSize.Width, Convert.ToInt32(numericHeight.Value)); } private void checkBoxGroupImages_CheckedChanged(object sender, EventArgs e) { kryptonGallery1.DropButtonRanges.Clear(); if (checkBoxGroupImages.Checked) { kryptonGallery1.DropButtonRanges.Add(kryptonGalleryRange1); kryptonGallery1.DropButtonRanges.Add(kryptonGalleryRange2); kryptonGallery1.DropButtonRanges.Add(kryptonGalleryRange3); } } private void kryptonGallery1_GalleryDropMenu(object sender, GalleryDropMenuEventArgs e) { if (checkBoxAddCustomItems.Checked) { KryptonContextMenuHeading h = new KryptonContextMenuHeading(); h.Text = "Customize Drop Menu"; KryptonContextMenuItems items1 = new KryptonContextMenuItems(); KryptonContextMenuItem item1 = new KryptonContextMenuItem(); item1.Text = "Custom Entry 1"; KryptonContextMenuItem item2 = new KryptonContextMenuItem(); item2.Text = "Custom Entry 2"; item2.Checked = true; items1.Items.Add(item1); items1.Items.Add(item2); KryptonContextMenuItems items2 = new KryptonContextMenuItems(); KryptonContextMenuItem item3 = new KryptonContextMenuItem(); item3.Text = "Custom Entry 3"; KryptonContextMenuItem item4 = new KryptonContextMenuItem(); item4.Text = "Custom Entry 4"; item4.CheckState = CheckState.Indeterminate; items2.Items.Add(item3); items2.Items.Add(item4); e.KryptonContextMenu.Items.Insert(0, new KryptonContextMenuSeparator()); e.KryptonContextMenu.Items.Insert(0, items1); e.KryptonContextMenu.Items.Insert(0, h); e.KryptonContextMenu.Items.Add(new KryptonContextMenuSeparator()); e.KryptonContextMenu.Items.Add(items2); } } private void buttonClose_Click(object sender, EventArgs e) { Close(); } } }
38.657143
136
0.607785
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy/Krypton-NET-5.400
Source/Demos/Non-NuGet/Krypton Ribbon Examples/KryptonGallery Examples/Form1.cs
4,062
C#
// *********************************************************************** // Copyright (c) Charlie Poole and TestCentric GUI contributors. // Licensed under the MIT License. See LICENSE file in root directory. // *********************************************************************** using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Windows.Forms; using TestCentric.Common; namespace TestCentric.Gui.Presenters { using Model; using Model.Services; using Model.Settings; using Views; using Dialogs; /// <summary> /// TestCentricPresenter does all file opening and closing that /// involves interacting with the user. /// /// NOTE: This class originated as the static class /// TestLoaderUI and is slowly being converted to a /// true presenter. Current limitations include: /// /// 1. Many functions, which should properly be in /// the presenter, remain in the form. /// /// 2. The presenter creates dialogs itself, which /// limits testability. /// </summary> public class TestCentricPresenter { private static readonly Logger log = InternalTrace.GetLogger(nameof(TestCentricPresenter)); #region Instance Variables private readonly IMainView _view; private readonly ITestModel _model; private readonly CommandLineOptions _options; private readonly UserSettings _settings; private string _guiLayout; private readonly RecentFiles _recentFiles; private AgentSelectionController _agentSelectionController; private List<string> _resultFormats = new List<string>(); private string[] _lastFilesLoaded = null; #endregion #region Constructor // TODO: Use an interface for view public TestCentricPresenter(IMainView view, ITestModel model, CommandLineOptions options) { _view = view; _model = model; _options = options; _settings = _model.Settings; _recentFiles = _model.RecentFiles; _agentSelectionController = new AgentSelectionController(_model, _view); _view.Font = _settings.Gui.Font; _view.ResultTabs.SelectedIndex = _settings.Gui.SelectedTab; SetTreeDisplayFormat(_settings.Gui.TestTree.DisplayFormat); UpdateViewCommands(); _view.StopRunButton.Visible = true; _view.ForceStopButton.Visible = false; foreach (string format in _model.ResultFormats) if (format != "cases" && format != "user") _resultFormats.Add(format); WireUpEvents(); } #endregion #region Event Handling private void WireUpEvents() { #region Model Events _model.Events.TestsLoading += (TestFilesLoadingEventArgs e) => { UpdateViewCommands(testLoading: true); var message = e.TestFilesLoading.Count == 1 ? $"Loading Assembly: {e.TestFilesLoading[0]}" : $"Loading {e.TestFilesLoading.Count} Assemblies..."; BeginLongRunningOperation(message); }; _model.Events.TestLoaded += (TestNodeEventArgs e) => { OnLongRunningOperationComplete(); UpdateViewCommands(); _view.StopRunButton.Visible = true; _view.ForceStopButton.Visible = false; _lastFilesLoaded = _model.TestFiles.ToArray(); if (_lastFilesLoaded.Length == 1) _view.SetTitleBar(_lastFilesLoaded.First()); }; _model.Events.TestsUnloading += (TestEventArgse) => { UpdateViewCommands(); _view.StopRunButton.Visible = true; _view.ForceStopButton.Visible = false; BeginLongRunningOperation("Unloading..."); }; _model.Events.TestUnloaded += (TestEventArgs e) => { OnLongRunningOperationComplete(); UpdateViewCommands(); _view.StopRunButton.Visible = true; _view.ForceStopButton.Visible = false; }; _model.Events.TestsReloading += (TestEventArgs e) => { UpdateViewCommands(); BeginLongRunningOperation("Reloading..."); }; _model.Events.TestReloaded += (TestNodeEventArgs e) => { OnLongRunningOperationComplete(); UpdateViewCommands(); _view.StopRunButton.Visible = true; _view.ForceStopButton.Visible = false; }; _model.Events.TestLoadFailure += (TestLoadFailureEventArgs e) => { OnLongRunningOperationComplete(); // HACK: Engine should recognize .NET Standard and give the // appropriate error message. For now, we compensate for its // failure by issuing the message ourselves and reloading the // previously loaded test. var msg = e.Exception.Message; bool isNetStandardError = e.Exception.Message == "Unrecognized Target Framework Identifier: .NETStandard"; if (!isNetStandardError) { _view.MessageDisplay.Error(e.Exception.Message); return; } _view.MessageDisplay.Error("Test assemblies must target a specific platform, rather than .NETStandard."); if (_lastFilesLoaded == null) _view.Close(); else { _model.UnloadTests(); _model.LoadTests(_lastFilesLoaded); } }; _model.Events.RunStarting += (RunStartingEventArgs e) => { UpdateViewCommands(); _view.StopRunButton.Visible = true; _view.ForceStopButton.Visible = false; }; _model.Events.RunFinished += (TestResultEventArgs e) => OnRunFinished(e.Result); // Separate internal method for testing void OnRunFinished(ResultNode result) { OnLongRunningOperationComplete(); UpdateViewCommands(); // Reset these in case run was cancelled _view.StopRunButton.Visible = true; _view.ForceStopButton.Visible = false; //string resultPath = Path.Combine(TestProject.BasePath, "TestResult.xml"); // TODO: Use Work Directory string resultPath = "TestResult.xml"; _model.SaveResults(resultPath); //try //{ // _model.SaveResults(resultPath); // //log.Debug("Saved result to {0}", resultPath); //} //catch (Exception ex) //{ // //log.Warning("Unable to save result to {0}\n{1}", resultPath, ex.ToString()); //} //if (e.Result.Outcome.Status == TestStatus.Failed) // _view.Activate(); // TODO: Should this be an option? // Display the run summary _view.RunSummaryButton.Checked = true; // If we were running unattended, it's time to close if (_options.Unattended) _view.Close(); }; _settings.Changed += (s, e) => { switch (e.SettingName) { case "TestCentric.Gui.GuiLayout": // Settings have changed (from settings dialog) // so we want to update the GUI to match. var newLayout = _settings.Gui.GuiLayout; var oldLayout = _view.GuiLayout.SelectedItem; // Make sure it hasn't already been changed if (oldLayout != newLayout) { // Save position of form for old layout SaveFormLocationAndSize(oldLayout); // Update the GUI itself SetGuiLayout(newLayout); _view.GuiLayout.SelectedItem = newLayout; } break; case "TestCentric.Gui.MainForm.ShowStatusBar": _view.StatusBarView.Visible = _settings.Gui.MainForm.ShowStatusBar; break; } }; _model.Events.UnhandledException += (UnhandledExceptionEventArgs e) => { MessageBoxDisplay.Error($"{e.Message}\n\n{e.StackTrace}", "TestCentric - Internal Error"); }; #endregion #region View Events _view.Load += (s, e) => { _guiLayout = _options.GuiLayout ?? _settings.Gui.GuiLayout; _view.GuiLayout.SelectedItem = _guiLayout; SetGuiLayout(_guiLayout); var settings = _model.PackageOverrides; if (_options.MaxAgents >= 0) _model.Settings.Engine.Agents = _options.MaxAgents; _view.RunAsX86.Checked = _options.RunAsX86; }; _view.Shown += (s, e) => { Application.DoEvents(); // Load test specified on command line or // the most recent one if options call for it if (_options.InputFiles.Count != 0) LoadTests(_options.InputFiles); else if (_settings.Gui.LoadLastProject && !_options.NoLoad) { foreach (string entry in _recentFiles.Entries) { if (entry != null && File.Exists(entry)) { LoadTests(entry); break; } } } //if ( guiOptions.include != null || guiOptions.exclude != null) //{ // testTree.ClearSelectedCategories(); // bool exclude = guiOptions.include == null; // string[] categories = exclude // ? guiOptions.exclude.Split(',') // : guiOptions.include.Split(','); // if ( categories.Length > 0 ) // testTree.SelectCategories( categories, exclude ); //} // Run loaded test automatically if called for if (_model.IsPackageLoaded && _options.RunAllTests) _model.RunTests(_model.LoadedTests); // Currently, --unattended without --run does nothing except exit. else if (_options.Unattended) _view.Close(); }; _view.SplitterPositionChanged += (s, e) => { _settings.Gui.MainForm.SplitPosition = _view.SplitterPosition; }; _view.FormClosing += (s, e) => { if (_model.IsPackageLoaded) { if (_model.IsTestRunning) { if (!_view.MessageDisplay.YesNo("A test is running, do you want to forcibly stop the test and exit?")) { e.Cancel = true; return; } _model.StopTestRun(true); } if (CloseProject() == DialogResult.Cancel) e.Cancel = true; } if (!e.Cancel) SaveFormLocationAndSize(_guiLayout); }; _view.FileMenu.Popup += () => { bool isPackageLoaded = _model.IsPackageLoaded; bool isTestRunning = _model.IsTestRunning; _view.OpenCommand.Enabled = !isTestRunning; _view.CloseCommand.Enabled = isPackageLoaded && !isTestRunning; _view.ReloadTestsCommand.Enabled = isPackageLoaded && !isTestRunning; _view.SelectAgentMenu.Enabled = _agentSelectionController.AllowAgentSelection(); _view.RunAsX86.Enabled = isPackageLoaded && !isTestRunning; _view.RecentFilesMenu.Enabled = !isTestRunning; //if (!isTestRunning) //{ // _recentProjectsMenuHandler.Load(); //} }; _view.OpenCommand.Execute += () => OpenProject(); _view.CloseCommand.Execute += () => CloseProject(); _view.AddTestFilesCommand.Execute += () => AddTestFiles(); _view.ReloadTestsCommand.Execute += () => ReloadTests(); _view.SelectAgentMenu.Popup += () => { _agentSelectionController.PopulateMenu(); }; _view.RunAsX86.CheckedChanged += () => { var key = EnginePackageSettings.RunAsX86; if (_view.RunAsX86.Checked) ChangePackageSettingAndReload(key, true); else ChangePackageSettingAndReload(key, null); }; _view.RecentFilesMenu.Popup += () => { var menuItems = _view.RecentFilesMenu.MenuItems; // Test for null, in case we are running tests with a mock if (menuItems == null) return; menuItems.Clear(); int num = 0; foreach (string entry in _model.RecentFiles.Entries) { var menuText = string.Format("{0} {1}", ++num, entry); var menuItem = new ToolStripMenuItem(menuText); menuItem.Click += (sender, ea) => { // HACK: We are loading new files, cancel any runtime override _model.PackageOverrides.Remove(EnginePackageSettings.RequestedRuntimeFramework); string path = ((ToolStripMenuItem)sender).Text.Substring(2); _model.LoadTests(new[] { path }); }; menuItems.Add(menuItem); if (num >= _settings.Gui.RecentProjects.MaxFiles) break; } }; _view.ExitCommand.Execute += () => _view.Close(); _view.GuiLayout.SelectionChanged += () => { // Selection menu item has changed, so we want // to update both the display and the settings var oldSetting = _settings.Gui.GuiLayout; var newSetting = _view.GuiLayout.SelectedItem; if (oldSetting != newSetting) { SaveFormLocationAndSize(oldSetting); SetGuiLayout(newSetting); } _guiLayout = newSetting; _settings.Gui.GuiLayout = _view.GuiLayout.SelectedItem; }; _view.IncreaseFontCommand.Execute += () => { applyFont(IncreaseFont(_settings.Gui.Font)); }; _view.DecreaseFontCommand.Execute += () => { applyFont(DecreaseFont(_settings.Gui.Font)); }; _view.ChangeFontCommand.Execute += () => { Font currentFont = _settings.Gui.Font; Font newFont = _view.DialogManager.SelectFont(currentFont); if (newFont != _settings.Gui.Font) applyFont(newFont); }; _view.DialogManager.ApplyFont += (font) => applyFont(font); _view.RestoreFontCommand.Execute += () => { applyFont(Form.DefaultFont); }; _view.IncreaseFixedFontCommand.Execute += () => { _settings.Gui.FixedFont = IncreaseFont(_settings.Gui.FixedFont); }; _view.DecreaseFixedFontCommand.Execute += () => { _settings.Gui.FixedFont = DecreaseFont(_settings.Gui.FixedFont); }; _view.RestoreFixedFontCommand.Execute += () => { _settings.Gui.FixedFont = new Font(FontFamily.GenericMonospace, 8.0f); }; _view.RunAllButton.Execute += RunAllTests; _view.RunSelectedButton.Execute += RunSelectedTests; _view.RerunButton.Execute += () => _model.RepeatLastRun(); _view.RunFailedButton.Execute += RunFailedTests; _view.DisplayFormat.SelectionChanged += () => { SetTreeDisplayFormat(_view.DisplayFormat.SelectedItem); }; _view.GroupBy.SelectionChanged += () => { switch(_view.DisplayFormat.SelectedItem) { case "TEST_LIST": _settings.Gui.TestTree.TestList.GroupBy = _view.GroupBy.SelectedItem; break; case "FIXTURE_LIST": _settings.Gui.TestTree.FixtureList.GroupBy = _view.GroupBy.SelectedItem; break; } }; _view.StopRunButton.Execute += ExecuteNormalStop; _view.ForceStopButton.Execute += ExecuteForcedStop; _view.RunParametersButton.Execute += DisplayTestParametersDialog; _view.RunSummaryButton.CheckedChanged += () => { if (_view.RunSummaryButton.Checked) { var report = ResultSummaryReporter.WriteSummaryReport(_model.ResultSummary); _view.RunSummaryDisplay.Display(report); } else { _view.RunSummaryDisplay.Hide(); } }; _view.ToolsMenu.Popup += () => { _view.SaveResultsAsMenu.MenuItems.Clear(); foreach (string format in _resultFormats) { var formatItem = new ToolStripMenuItem(format); formatItem.Click += (s, e) => SaveResults(format); _view.SaveResultsAsMenu.MenuItems.Add(formatItem); } }; _view.SaveResultsCommand.Execute += () => SaveResults(); _view.OpenWorkDirectoryCommand.Execute += () => System.Diagnostics.Process.Start(_model.WorkDirectory); _view.ExtensionsCommand.Execute += () => { using (var extensionsDialog = new ExtensionDialog(_model.Services.ExtensionService)) { extensionsDialog.Font = _settings.Gui.Font; extensionsDialog.ShowDialog(); } }; _view.SettingsCommand.Execute += () => { SettingsDialog.Display(this, _model); }; _view.TestCentricHelpCommand.Execute += () => { System.Diagnostics.Process.Start("https://test-centric.org/testcentric-gui"); }; _view.NUnitHelpCommand.Execute += () => { System.Diagnostics.Process.Start("https://docs.nunit.org/articles/nunit/intro.html"); }; _view.AboutCommand.Execute += () => { using (AboutBox aboutBox = new AboutBox()) { aboutBox.ShowDialog(); } }; _view.ResultTabs.SelectionChanged += () => { _settings.Gui.SelectedTab = _view.ResultTabs.SelectedIndex; }; #endregion } private void SaveFormLocationAndSize(string guiLayout) { if (guiLayout == "Mini") { _settings.Gui.MiniForm.Location = _view.Location; _settings.Gui.MiniForm.Size = _view.Size; } else { _settings.Gui.MainForm.Location = _view.Location; _settings.Gui.MainForm.Size = _view.Size; } } private void ExecuteNormalStop() { BeginLongRunningOperation("Waiting for all running tests to complete."); _view.StopRunButton.Visible = false; _view.ForceStopButton.Visible = true; _model.StopTestRun(false); } private void ExecuteForcedStop() { _view.ForceStopButton.Enabled = false; _model.StopTestRun(true); } private void DisplayTestParametersDialog() { using (var dlg = new TestParametersDialog()) { dlg.Font = _settings.Gui.Font; dlg.StartPosition = FormStartPosition.CenterParent; if (_model.PackageOverrides.ContainsKey("TestParametersDictionary")) { var testParms = _model.PackageOverrides["TestParametersDictionary"] as IDictionary<string, string>; foreach (string key in testParms.Keys) dlg.Parameters.Add(key, testParms[key]); } if (dlg.ShowDialog(_view as IWin32Window) == DialogResult.OK) { ChangePackageSettingAndReload("TestParametersDictionary", dlg.Parameters); } } } #endregion #region Public Methods #region Open Methods private void OpenProject() { var files = _view.DialogManager.SelectMultipleFiles("Open Project", CreateOpenFileFilter()); if (files.Count > 0) { // HACK: We are loading new files, cancel any runtime override _model.PackageOverrides.Remove(EnginePackageSettings.RequestedRuntimeFramework); LoadTests(files); } } public void LoadTests(string testFileName) { LoadTests(new[] { testFileName }); } private void LoadTests(IList<string> testFileNames) { _model.LoadTests(testFileNames); } #endregion #region Close Methods public DialogResult CloseProject() { //DialogResult result = SaveProjectIfDirty(); //if (result != DialogResult.Cancel) _model.UnloadTests(); //return result; return DialogResult.OK; } #endregion #region Add Methods public void AddTestFiles() { var filesToAdd = _view.DialogManager.SelectMultipleFiles("Add Test Files", CreateOpenFileFilter()); if (filesToAdd.Count > 0) { var files = new List<string>(_model.TestFiles); files.AddRange(filesToAdd); _model.LoadTests(files); } } #endregion #region Save Methods public void SaveResults(string format = "nunit3") { string savePath = _view.DialogManager.GetFileSavePath($"Save Results in {format} format", "XML Files (*.xml)|*.xml|All Files (*.*)|*.*", _model.WorkDirectory, "TestResult.xml"); if (savePath != null) { try { _model.SaveResults(savePath, format); _view.MessageDisplay.Info(String.Format($"Results saved in {format} format as {savePath}")); } catch (Exception exception) { _view.MessageDisplay.Error("Unable to Save Results\n\n" + MessageBuilder.FromException(exception)); } } } #endregion #region Reload Methods public void ReloadTests() { _model.ReloadTests(); //NUnitProject project = loader.TestProject; //bool wrapper = project.IsAssemblyWrapper; //string projectPath = project.ProjectPath; //string activeConfigName = project.ActiveConfigName; //// Unload first to avoid message asking about saving //loader.UnloadProject(); //if (wrapper) // OpenProject(projectPath); //else // OpenProject(projectPath, activeConfigName, null); } #endregion #endregion #region Helper Methods private void UpdateViewCommands(bool testLoading = false) { bool testLoaded = _model.HasTests; bool testRunning = _model.IsTestRunning; bool hasResults = _model.HasResults; bool hasFailures = _model.HasResults && _model.ResultSummary.FailedCount > 0; _view.RunAllButton.Enabled = _view.RunSelectedButton.Enabled = _view.DisplayFormatButton.Enabled = _view.RunParametersButton.Enabled = testLoaded && !testRunning; _view.RerunButton.Enabled = testLoaded && !testRunning && hasResults; _view.RunFailedButton.Enabled = testLoaded && !testRunning && hasFailures; _view.StopRunButton.Enabled = _view.ForceStopButton.Enabled = testRunning; _view.RunSummaryButton.Enabled = testLoaded && !testRunning && hasResults; _view.OpenCommand.Enabled = !testRunning & !testLoading; _view.CloseCommand.Enabled = testLoaded & !testRunning; _view.AddTestFilesCommand.Enabled = testLoaded && !testRunning; _view.ReloadTestsCommand.Enabled = testLoaded && !testRunning; _view.RecentFilesMenu.Enabled = !testRunning && !testLoading; _view.ExitCommand.Enabled = !testLoading; _view.SaveResultsCommand.Enabled = _view.SaveResultsAsMenu.Enabled = !testRunning && !testLoading && hasResults; } private string CreateOpenFileFilter() { StringBuilder sb = new StringBuilder(); bool nunit = _model.NUnitProjectSupport; bool vs = _model.VisualStudioSupport; if (nunit && vs) sb.Append("Projects & Assemblies (*.nunit,*.csproj,*.fsproj,*.vbproj,*.vjsproj,*.vcproj,*.sln,*.dll,*.exe)|*.nunit;*.csproj;*.fsproj;*.vbproj;*.vjsproj;*.vcproj;*.sln;*.dll;*.exe|"); else if (nunit) sb.Append("Projects & Assemblies (*.nunit,*.dll,*.exe)|*.nunit;*.dll;*.exe|"); else if (vs) sb.Append("Projects & Assemblies (*.csproj,*.fsproj,*.vbproj,*.vjsproj,*.vcproj,*.sln,*.dll,*.exe)|*.csproj;*.fsproj;*.vbproj;*.vjsproj;*.vcproj;*.sln;*.dll;*.exe|"); if (nunit) sb.Append("NUnit Projects (*.nunit)|*.nunit|"); if (vs) sb.Append("Visual Studio Projects (*.csproj,*.fsproj,*.vbproj,*.vjsproj,*.vcproj,*.sln)|*.csproj;*.fsproj;*.vbproj;*.vjsproj;*.vcproj;*.sln|"); sb.Append("Assemblies (*.dll,*.exe)|*.dll;*.exe|"); sb.Append("All Files (*.*)|*.*"); return sb.ToString(); } private static bool CanWriteProjectFile(string path) { return !File.Exists(path) || (File.GetAttributes(path) & FileAttributes.ReadOnly) == 0; } private static string Quoted(string s) { return "\"" + s + "\""; } private void ChangePackageSettingAndReload(string key, object setting) { if (setting == null || setting as string == "DEFAULT") _model.PackageOverrides.Remove(key); else _model.PackageOverrides[key] = setting; // Even though the _model has a Reload method, we cannot use it because Reload // does not re-create the Engine. Since we just changed a setting, we must // re-create the Engine by unloading/reloading the tests. We make a copy of // __model.TestFiles because the method does an unload before it loads. LoadTests(new List<string>(_model.TestFiles)); } private void applyFont(Font font) { _settings.Gui.Font = _view.Font = font; } private void SetGuiLayout(string guiLayout) { Point location; Size size; bool isMaximized = false; bool useFullGui = guiLayout != "Mini"; // Configure the GUI _view.Configure(useFullGui); if (useFullGui) { location = _settings.Gui.MainForm.Location; size = _settings.Gui.MainForm.Size; isMaximized = _settings.Gui.MainForm.Maximized; } else { location = _settings.Gui.MiniForm.Location; size = _settings.Gui.MiniForm.Size; isMaximized = _settings.Gui.MiniForm.Maximized; } if (!IsValidLocation(location, size)) location = new Point(10, 10); _view.Location = location; _view.Size = size; _view.Maximized = isMaximized; if (useFullGui) _view.SplitterPosition = _settings.Gui.MainForm.SplitPosition; _view.StatusBarView.Visible = useFullGui && _settings.Gui.MainForm.ShowStatusBar; } private static bool IsValidLocation(Point location, Size size) { Rectangle myArea = new Rectangle(location, size); bool intersect = false; foreach (System.Windows.Forms.Screen screen in System.Windows.Forms.Screen.AllScreens) { intersect |= myArea.IntersectsWith(screen.WorkingArea); } return intersect; } private static Font IncreaseFont(Font font) { return new Font(font.FontFamily, font.SizeInPoints * 1.2f, font.Style); } private static Font DecreaseFont(Font font) { return new Font(font.FontFamily, font.SizeInPoints / 1.2f, font.Style); } private LongRunningOperationDisplay _longRunningOperation; private void BeginLongRunningOperation(string text) { _longRunningOperation = new LongRunningOperationDisplay(); _longRunningOperation.Display(text); } private void OnLongRunningOperationComplete() { _longRunningOperation?.Close(); _longRunningOperation = null; } private void SetTreeDisplayFormat(string displayFormat) { _view.DisplayFormat.SelectedItem = displayFormat; _settings.Gui.TestTree.DisplayFormat = displayFormat; switch (displayFormat) { case "NUNIT_TREE": _view.GroupBy.Enabled = false; break; case "TEST_LIST": _view.GroupBy.Enabled = true; _view.GroupBy.SelectedItem = _settings.Gui.TestTree.TestList.GroupBy; break; case "FIXTURE_LIST": _view.GroupBy.Enabled = true; // HACK: Should be handled by the element itself ((Elements.CheckedToolStripMenuGroup)_view.GroupBy).MenuItems[1].Enabled = false; _view.GroupBy.SelectedItem = _settings.Gui.TestTree.FixtureList.GroupBy; break; } } private void RunAllTests() { _model.ClearResults(); var allTests = _model.LoadedTests; _model.RunTests(allTests); } private void RunSelectedTests() { var testSelection = _model.SelectedTests; _model.RunTests(testSelection); } private void RunFailedTests() { var failedTests = new TestSelection(); foreach (var entry in _model.Results) { var test = entry.Value; if (!test.IsSuite && test.Outcome.Status == TestStatus.Failed) failedTests.Add(test); } _model.RunTests(failedTests); } #endregion } }
35.079702
198
0.523629
[ "MIT" ]
Test-Centric/test-centric-gui
src/TestCentric/testcentric.gui/Presenters/TestCentricPresenter.cs
33,010
C#
using System; using System.Collections.Generic; using System.Text; namespace Classes { public class userDoctor { public string Name { get; set; } public string Login { get; set; } public string Password { get; set; } public string Speciality { get; set; } public List<Appointment> Appointments { get; set; } public string NameAndSpecialty { get { return $"{Name} - {Speciality}"; } } } }
21.8
60
0.515596
[ "MIT" ]
BigBoyMato/HospitalSoft
Classes/userDoctor.cs
547
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("Problem8")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Problem8")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e046d4df-e6ec-41ed-bc24-7f02e384e115")] // 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.540541
84
0.743701
[ "MIT" ]
BoyanDimitrov77/DataStructure
Linear Data Structures Homework/Problem8/Properties/AssemblyInfo.cs
1,392
C#
 using System; using System.Collections.Generic; using System.Threading.Tasks; using IFramework.Config; using IFramework.Infrastructure; using IFramework.Infrastructure.Caching; using IFramework.IoC; using Microsoft.VisualStudio.TestTools.UnitTesting; using IFramework.FoundatioRedis.Config; namespace IFramework4._5Tests { [TestClass] public class DistributedLockTest { //static readonly ConnectionMultiplexer Muxer = SharedConnection.GetMuxer(); //static readonly ILockProvider Locker = new CacheLockProvider(new RedisCacheClient(Muxer), new RedisMessageBus(Muxer.GetSubscriber())); //static ILockProvider Locker = new CacheLockProvider(new InMemoryCacheClient(), new InMemoryMessageBus()); private ILockProvider _lockProvider; private ICacheManager _cacheManager; private static int _sum = 0; [TestInitialize] public void Initialize() { Configuration.Instance .UseUnityContainer() .RegisterCommonComponents() .UseFoundatioRedisCache() .UseFoundatioLockRedis(); // .UseFoundatioLockInMemory(); _lockProvider = IoCFactory.Resolve<ILockProvider>(); _cacheManager = IoCFactory.Resolve<ICacheManager>(); } [TestMethod] public void TestDistributedLock() { var tasks = new List<Task>(); var n = 10000; for (int i = 0; i < n; i++) { tasks.Add(AddSum()); } Console.WriteLine($"{DateTime.Now} start waiting"); Task.WaitAll(tasks.ToArray()); Console.WriteLine($"{DateTime.Now} end waiting sum:{_sum}"); Assert.IsTrue(_sum == n); } private Task AddSum() { return _lockProvider.LockAsync("test", () => _sum ++, TimeSpan.FromSeconds(10)); } [TestMethod] public async Task TestDistributedLockAsync() { var tasks = new List<Task>(); var n = 10000; for (int i = 0; i < n; i++) { tasks.Add(AddSumAsync()); } Console.WriteLine($"{DateTime.Now} start waiting"); await Task.WhenAll(tasks.ToArray()); Console.WriteLine($"{DateTime.Now} end waiting sum:{_sum}"); Assert.IsTrue(_sum == n); } private Task AddSumAsync() { return _lockProvider.LockAsync("test", DoAsync, TimeSpan.FromSeconds(10)); } private Task DoAsync() { return Task.Run(() => _sum++); } [TestMethod] public async Task TestAll() { await TestRedisCacheAsync(); await TestDistributedLockAsync(); } [TestMethod] public async Task TestRedisCacheAsync() { await _cacheManager.ClearAsync().ConfigureAwait(false); int t = 0; var result = await _cacheManager.GetAsync<int>("key"); Assert.IsTrue(!result.HasValue); result = await _cacheManager.GetAsync("key", 1, async () => await Task.FromResult(++t)) .ConfigureAwait(false); var tasks = new List<Task>(); for (int i = 0; i < 100; i++) { tasks.Add(_cacheManager.GetAsync("key", 1, async () => await Task.FromResult(++t))); } await Task.WhenAll(tasks.ToArray()); result = await _cacheManager.GetAsync("key", 1, async () => await Task.FromResult(++t)) .ConfigureAwait(false); Assert.IsTrue(result.HasValue && result.Value == 1 && t == 1); } } }
32.965812
144
0.550687
[ "MIT" ]
IvanZheng/IFramework
Src/iFramework.Plugins/FoundatioTest/DistributedLockTest.cs
3,859
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.Net.Http; using System.Web.Http.Controllers; namespace System.Web.Http.Filters { public class HttpActionExecutedContext { private HttpActionContext _actionContext; public HttpActionExecutedContext(HttpActionContext actionContext, Exception exception) { if (actionContext == null) { throw Error.ArgumentNull("actionContext"); } Exception = exception; _actionContext = actionContext; } /// <summary> /// Initializes a new instance of the <see cref="HttpActionExecutedContext"/> class. /// </summary> /// <remarks>The default constructor is intended for use by unit testing only.</remarks> public HttpActionExecutedContext() { } public HttpActionContext ActionContext { get { return _actionContext; } set { if (value == null) { throw Error.PropertyNull(); } _actionContext = value; } } public Exception Exception { get; set; } public HttpResponseMessage Response { get { return ActionContext != null ? ActionContext.Response : null; } set { ActionContext.Response = value; } } /// <summary> /// Gets the current <see cref="HttpRequestMessage"/>. /// </summary> public HttpRequestMessage Request { get { return (ActionContext != null && ActionContext.ControllerContext != null) ? ActionContext.ControllerContext.Request : null; } } } }
27.635135
111
0.526161
[ "Apache-2.0" ]
1508553303/AspNetWebStack
src/System.Web.Http/Filters/HttpActionExecutedContext.cs
2,047
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Management; using System.Net; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using System.Web; using System.Xml.Linq; namespace EA.Gen.Hub.Model.Licencing { /// <summary> /// Lience Management /// </summary> public static class Generator { /// <summary> /// Create RSA pair of public and privat /// </summary> /// <returns></returns> public static LicenceKeys CreateKeys () { using (var rsa = new RSACryptoServiceProvider ()) { return new LicenceKeys { PrivateKey = rsa.ToXmlString ( true ), PublicKey = rsa.ToXmlString ( false ) }; } } public static void SaveKeys () { SaveKeys ( CreateKeys () ); } public static void SaveKeys ( LicenceKeys p) { File.WriteAllText ( "privateKey.xml", p.PrivateKey); File.WriteAllText ( "publicKey.xml", p.PublicKey); } public static Guid CreateMachineKey () { var k = Environment.MachineName + CPUId () + typeof ( Licence ).Assembly.GetName ().Version; var h = Md5Hash ( k ); var g = new Guid ( h ); return g; } public static string CPUId () { var sb = new StringBuilder (); using (var mc = new ManagementClass ( "Win32_Processor" )) using (var moc = mc.GetInstances ()) { foreach (var v in moc) { sb.Append ( v.Properties["ProcessorId"].Value ); } } return sb.ToString (); } private static string Md5Hash ( string input ) { MD5 md5 = MD5.Create (); byte[] inputBytes = Encoding.ASCII.GetBytes ( input ); byte[] hash = md5.ComputeHash ( inputBytes ); StringBuilder sb = new StringBuilder (); for (int i = 0; i < hash.Length; i++) { sb.Append ( hash[i].ToString ( "X2" ) ); } return sb.ToString (); } public static string CreateLicence ( string privateKey, Guid machineKey, string email ) { var licence = new Licence ( privateKey, machineKey, DateTime.Now.AddYears ( 1 ) ); return licence.Save ( email ); } public static string CreateLicence ( string privateKey, string email ) { var machineKey = CreateMachineKey (); var licence = new Licence ( privateKey, machineKey, DateTime.Now.AddYears ( 1 ) ); return licence.Save ( email ); } public static string RenewLicence (string address, string email, string machineKey ) { var v = typeof ( Licence ).Assembly.GetName ().Version.ToString (); var w = new WebClient (); w.Encoding = Encoding.UTF8; var u = "https://" + address + '/' + System.Web.HttpUtility.UrlEncode ( email ) + "/" + machineKey + "/" + v; var s = w.DownloadString ( u ); return s; } } }
32.317308
121
0.525439
[ "Apache-2.0" ]
channell/Ea.Gen
EA.Gen.Hub.Model/Licencing/Generator.cs
3,363
C#