content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// Copyright (c) 2019 Lykke Corp. // See the LICENSE file in the project root for more information. namespace Axle.Settings { using Lykke.SettingsReader.Attributes; public class ConnectionStrings { [AmqpCheck] public string RabbitMq { get; set; } } }
21.357143
66
0.64214
[ "MIT-0" ]
LykkeBusiness/axle
src/Axle/Settings/ConnectionStrings.cs
301
C#
 using System; using System.Reflection; using Unity.Interception.Interceptors; using Unity.Interception.PolicyInjection; using Unity.Interception.PolicyInjection.Pipeline; using Unity.Interception.Utilities; namespace Microsoft.Practices.Unity.InterceptionExtension.Tests.VirtualMethodInterception { internal class WireupHelper { internal static T GetInterceptingInstance<T>(params object[] ctorValues) { Type typeToIntercept = typeof(T); if (typeToIntercept.IsGenericType) { typeToIntercept = typeToIntercept.GetGenericTypeDefinition(); } global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator generator = new global::Unity.Interception.Interceptors.TypeInterceptors.VirtualMethodInterception.InterceptingClassGeneration.InterceptingClassGenerator(typeToIntercept); Type generatedType = generator.GenerateType(); if (generatedType.IsGenericTypeDefinition) { generatedType = generatedType.MakeGenericType(typeof(T).GetGenericArguments()); } return (T)Activator.CreateInstance(generatedType, ctorValues); } internal static T GetInterceptedInstance<T>(string methodName, ICallHandler handler) { MethodInfo method = typeof(T).GetMethod(methodName); T instance = GetInterceptingInstance<T>(); PipelineManager manager = new PipelineManager(); manager.SetPipeline(method, new HandlerPipeline(Sequence.Collect(handler))); IInterceptingProxy pm = (IInterceptingProxy)instance; pm.AddInterceptionBehavior(new PolicyInjectionBehavior(manager)); return instance; } } }
37.714286
321
0.708333
[ "Apache-2.0" ]
ENikS/interception
tests/VirtualMethodInterception/WireupHelper.cs
1,850
C#
#pragma checksum "..\..\UserControlWindow.xaml" "{8829d00f-11b8-4213-878b-770e8597ac16}" "9C713D1215141C174F5949B35D55C684244DFF2F949846DC0B0BD1436F263071" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using PropertyChangedTest; using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; using Xceed.Wpf.AvalonDock; namespace PropertyChangedTest { /// <summary> /// UserControlWindow /// </summary> public partial class UserControlWindow : System.Windows.Controls.UserControl, System.Windows.Markup.IComponentConnector { private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Uri resourceLocater = new System.Uri("/PropertyChangedTest;component/usercontrolwindow.xaml", System.UriKind.Relative); #line 1 "..\..\UserControlWindow.xaml" System.Windows.Application.LoadComponent(this, resourceLocater); #line default #line hidden } [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { this._contentLoaded = true; } } }
39.935065
156
0.679675
[ "MIT" ]
mamannon/WPF_and_AvalonDock
PropertyChanged with DependencyProperty/PropertyChanged3/PropertyChangedTest3/obj/Debug/UserControlWindow.g.cs
3,077
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Win32.SafeHandles; using System; using System.IO; using System.Threading.Tasks; using Xunit; namespace System.IO.Tests { [ActiveIssue("https://github.com/dotnet/runtime/issues/34582", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] public class FileStream_SafeFileHandle : FileSystemTest { [Fact] public void HandleNotNull() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { Assert.NotNull(fs.SafeFileHandle); } } [Fact] public void DisposeClosesHandle() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { SafeFileHandle handle = fs.SafeFileHandle; if (!handle.IsInvalid) { fs.Dispose(); Assert.True(handle.IsClosed); } } } [Fact] public void DisposingBufferedFileStreamThatWasClosedViaSafeFileHandleCloseDoesNotThrow() { FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.ReadWrite, FileShare.Read, bufferSize: 100); fs.SafeFileHandle.Dispose(); fs.Dispose(); // must not throw } [Fact] public void AccessFlushesFileClosesHandle() { string fileName = GetTestFilePath(); using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete)) using (FileStream fsr = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) { // write will be buffered fs.Write(TestBuffer, 0, TestBuffer.Length); // other handle doesn't yet see the change Assert.Equal(0, fsr.Length); _ = fs.SafeFileHandle; // expect the handle to be flushed Assert.Equal(TestBuffer.Length, fsr.Length); } } } }
32.842857
145
0.594606
[ "MIT" ]
333fred/runtime
src/libraries/System.IO.FileSystem/tests/FileStream/SafeFileHandle.cs
2,299
C#
using System; namespace Standard; internal enum KDC { FREQUENT = 1, RECENT }
8.8
19
0.659091
[ "MIT" ]
Muzsor/HandyControl
src/Shared/Microsoft.Windows.Shell/Standard/KDC.cs
90
C#
using System.Collections.Generic; using System.Linq; using Zutatensuppe.D2Reader.Models; namespace Zutatensuppe.D2Reader { public static class QuestFactory { static readonly IReadOnlyDictionary<QuestId, QuestDetails> Quests = new Dictionary<QuestId, QuestDetails>() { { QuestId.Andariel, new QuestDetails { Id = QuestId.Andariel, Act = 1, ActOrder = 6, Name = "Sisters to the Slaughter", CommonName = "Andariel", IsBossQuest = true, BufferIndex = 6, } }, { QuestId.Duriel, new QuestDetails { Id = QuestId.Duriel, Act = 2, ActOrder = 6, Name = "The Seven Tombs", CommonName = "Duriel", IsBossQuest = true, BufferIndex = 14, CompletionBitMask = (1 << 5), } }, { QuestId.Mephisto, new QuestDetails { Id = QuestId.Mephisto, Act = 3, ActOrder = 6, Name = "The Guardian", CommonName = "Mephisto", IsBossQuest = true, BufferIndex = 22, } }, { QuestId.Diablo, new QuestDetails { Id = QuestId.Diablo, Act = 4, ActOrder = 3, Name = "Terror's End", CommonName = "Diablo", IsBossQuest = true, BufferIndex = 26, } }, { QuestId.Baal, new QuestDetails { Id = QuestId.Baal, Act = 5, ActOrder = 6, Name = "Eve of Destruction", CommonName = "Baal", IsBossQuest = true, BufferIndex = 40, } }, { QuestId.DenOfEvil, new QuestDetails { Id = QuestId.DenOfEvil, Act = 1, ActOrder = 1, Name = "Den of Evil", CommonName = "Den of Evil", BufferIndex = 1, } }, { QuestId.SistersBurialGrounds, new QuestDetails { Id = QuestId.SistersBurialGrounds, Act = 1, ActOrder = 2, Name = "Sisters' Burial Grounds", CommonName = "Blood Raven", BufferIndex = 2, } }, { QuestId.ToolsOfTheTrade, new QuestDetails { Id = QuestId.ToolsOfTheTrade, Act = 1, ActOrder = 5, Name = "Tools of the Trade", CommonName = "Charsie Imbue", BufferIndex = 3, } }, { QuestId.TheSearchForCain, new QuestDetails { Id = QuestId.TheSearchForCain, Act = 1, ActOrder = 3, Name = "The Search for Cain", CommonName = "Cain", BufferIndex = 4, } }, { QuestId.TheForgottenTower, new QuestDetails { Id = QuestId.TheForgottenTower, Act = 1, ActOrder = 4, Name = "The Forgotten Tower", CommonName = "Countess", BufferIndex = 5, } }, { QuestId.RadamentsLair, new QuestDetails { Id = QuestId.RadamentsLair, Act = 2, ActOrder = 1, Name = "Radament's Lair", CommonName = "Radament", BufferIndex = 9, } }, { QuestId.TheHoradricStaff, new QuestDetails { Id = QuestId.TheHoradricStaff, Act = 2, ActOrder = 2, Name = "The Horadric Staff", CommonName = "Horadric Staff", BufferIndex = 10, } }, { QuestId.TaintedSun, new QuestDetails { Id = QuestId.TaintedSun, Act = 2, ActOrder = 3, Name = "Tainted Sun", CommonName = "Claw Viper Temple", BufferIndex = 11, } }, { QuestId.ArcaneSanctuary, new QuestDetails { Id = QuestId.ArcaneSanctuary, Act = 2, ActOrder = 4, Name = "Arcane Sanctuary", CommonName = "Arcane Sancuary", BufferIndex = 12, } }, { QuestId.TheSummoner, new QuestDetails { Id = QuestId.TheSummoner, Act = 2, ActOrder = 5, Name = "The Summoner", CommonName = "Horazon", BufferIndex = 13, } }, { QuestId.LamEsensTome, new QuestDetails { Id = QuestId.LamEsensTome, Act = 3, ActOrder = 4, Name = "Lam Esen's Tome", CommonName = "Battlemaid Sarina", BufferIndex = 17, } }, { QuestId.KhalimsWill, new QuestDetails { Id = QuestId.KhalimsWill, Act = 3, ActOrder = 3, Name = "Khalim's Will", CommonName = "Khalim's Will", BufferIndex = 18, } }, { QuestId.BladeOfTheOldReligion, new QuestDetails { Id = QuestId.BladeOfTheOldReligion, Act = 3, ActOrder = 2, Name = "Blade of the Old Religion", CommonName = "Gibdinn", BufferIndex = 19, } }, { QuestId.TheGoldenBird, new QuestDetails { Id = QuestId.TheGoldenBird, Act = 3, ActOrder = 1, Name = "The Golden Bird", CommonName = "Alkor Quest", BufferIndex = 20, } }, { QuestId.TheBlackenedTemple, new QuestDetails { Id = QuestId.TheBlackenedTemple, Act = 3, ActOrder = 5, Name = "The Blackened Temple", CommonName = "Travincal Council", BufferIndex = 21, } }, { QuestId.TheFallenAngel, new QuestDetails { Id = QuestId.TheFallenAngel, Act = 4, ActOrder = 1, Name = "The Fallen Angel", CommonName = "Izual", BufferIndex = 25, } }, { QuestId.HellsForge, new QuestDetails { Id = QuestId.HellsForge, Act = 4, ActOrder = 2, Name = "Hell's Forge", CommonName = "Hell Forge", BufferIndex = 27, } }, { QuestId.SiegeOnHarrogath, new QuestDetails { Id = QuestId.SiegeOnHarrogath, Act = 5, ActOrder = 1, Name = "Siege on Harrogath", CommonName = "Shenk", BufferIndex = 35, } }, { QuestId.RescueOnMountArreat, new QuestDetails { Id = QuestId.RescueOnMountArreat, Act = 5, ActOrder = 2, Name = "Rescue on Mount Arreat", CommonName = "Rescue Barbs", BufferIndex = 36, } }, { QuestId.PrisonOfIce, new QuestDetails { Id = QuestId.PrisonOfIce, Act = 5, ActOrder = 3, Name = "Prison of Ice", CommonName = "Rescue Anya", BufferIndex = 37, } }, { QuestId.BetrayalOfHarrogath, new QuestDetails { Id = QuestId.BetrayalOfHarrogath, Act = 5, ActOrder = 4, Name = "Betrayal of Harrogath", CommonName = "Kill Nihlathak", BufferIndex = 38, } }, { QuestId.RiteOfPassage, new QuestDetails { Id = QuestId.RiteOfPassage, Act = 5, ActOrder = 5, Name = "Rite of Passage", CommonName = "Ancients", BufferIndex = 39, } }, { QuestId.CowKing, new QuestDetails { Id = QuestId.CowKing, Act = 0, ActOrder = 0, Name = "Cow King", CommonName = "Cow King", CompletionBitMask = (1 << 10), FullCompletionBitMask = (1 << 10), BufferIndex = 4, } }, }; public static Quest Create(QuestId id, ushort completionBits) => Quests.TryGetValue(id, out var details) ? new Quest(details, completionBits) : null; public static Quest CreateByActAndOrder(int act, int quest) { return (from item in Quests where item.Value.Act == act && item.Value.ActOrder == quest select new Quest(item.Value, 0)).FirstOrDefault(); } public static List<Quest> CreateListFromBuffer(IEnumerable<ushort> questBuffer) { List<Quest> quests = new List<Quest>(); foreach (var pair in Quests) { var bits = questBuffer.ElementAtOrDefault(pair.Value.BufferIndex); quests.Add(Create(pair.Key, bits)); } return quests; } } }
44.386861
115
0.344927
[ "MIT" ]
DiabloRun/DiabloInterface
src/D2Reader/QuestFactory.cs
12,162
C#
//----------------------------------------------------------------------- // <copyright file="ORMultiValueDictionary.cs" company="Akka.NET Project"> // Copyright (C) 2009-2020 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2020 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using Akka.Cluster; namespace Akka.DistributedData { /// <summary> /// INTERNAL API /// /// Marker interface for serialization /// </summary> internal interface IORMultiValueDictionaryKey { Type KeyType { get; } Type ValueType { get; } } /// <summary> /// INTERNAL API. /// /// For serialization purposes. /// </summary> internal interface IORMultiValueDictionaryDeltaOperation { bool WithValueDeltas { get; } ORDictionary.IDeltaOperation Underlying { get; } } [Serializable] public sealed class ORMultiValueDictionaryKey<TKey, TValue> : Key<ORMultiValueDictionary<TKey, TValue>>, IORMultiValueDictionaryKey { public ORMultiValueDictionaryKey(string id) : base(id) { } public Type KeyType { get; } = typeof(TKey); public Type ValueType { get; } = typeof(TValue); } /// <summary> /// INTERNAL API /// /// Marker interface for serialization /// </summary> internal interface IORMultiValueDictionary { Type KeyType { get; } Type ValueType { get; } } /// <summary> /// An immutable multi-map implementation. This class wraps an /// <see cref="ORDictionary{TKey,TValue}"/> with an <see cref="ORSet{T}"/> for the map's value. /// /// This class is immutable, i.e. "modifying" methods return a new instance. /// </summary> [Serializable] public sealed class ORMultiValueDictionary<TKey, TValue> : IDeltaReplicatedData<ORMultiValueDictionary<TKey, TValue>, ORDictionary<TKey, ORSet<TValue>>.IDeltaOperation>, IRemovedNodePruning<ORMultiValueDictionary<TKey, TValue>>, IReplicatedDataSerialization, IEquatable<ORMultiValueDictionary<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, IImmutableSet<TValue>>>, IORMultiValueDictionary { public static readonly ORMultiValueDictionary<TKey, TValue> Empty = new ORMultiValueDictionary<TKey, TValue>(ORDictionary<TKey, ORSet<TValue>>.Empty, withValueDeltas: false); public static readonly ORMultiValueDictionary<TKey, TValue> EmptyWithValueDeltas = new ORMultiValueDictionary<TKey, TValue>(ORDictionary<TKey, ORSet<TValue>>.Empty, withValueDeltas: true); internal readonly ORDictionary<TKey, ORSet<TValue>> Underlying; private readonly bool _withValueDeltas; internal ORMultiValueDictionary(ORDictionary<TKey, ORSet<TValue>> underlying, bool withValueDeltas) { Underlying = underlying; _withValueDeltas = withValueDeltas; } public bool DeltaValues => _withValueDeltas; public IImmutableDictionary<TKey, IImmutableSet<TValue>> Entries => _withValueDeltas ? Underlying.Entries .Where(kv => Underlying.KeySet.Contains(kv.Key)) .Select(kv => new KeyValuePair<TKey, IImmutableSet<TValue>>(kv.Key, kv.Value.Elements)) .ToImmutableDictionary() : Underlying.Entries .Select(kv => new KeyValuePair<TKey, IImmutableSet<TValue>>(kv.Key, kv.Value.Elements)) .ToImmutableDictionary(); public IImmutableSet<TValue> this[TKey key] => Underlying[key].Elements; public bool TryGetValue(TKey key, out IImmutableSet<TValue> value) { if (!_withValueDeltas || Underlying.KeySet.Contains(key)) { ORSet<TValue> set; if (Underlying.TryGetValue(key, out set)) { value = set.Elements; return true; } } value = null; return false; } public bool ContainsKey(TKey key) => Underlying.KeySet.Contains(key); public bool IsEmpty => Underlying.IsEmpty; public int Count => Underlying.Count; /// <summary> /// Returns all keys stored within current ORMultiDictionary. /// </summary> public IEnumerable<TKey> Keys => Underlying.KeySet; /// <summary> /// Returns all values stored in all buckets within current ORMultiDictionary. /// </summary> public IEnumerable<TValue> Values { get { foreach (var value in Underlying.Values) foreach (var v in value) { yield return v; } } } /// <summary> /// Sets a <paramref name="bucket"/> of values inside current dictionary under provided <paramref name="key"/> /// in the context of the provided cluster <paramref name="node"/>. /// </summary> public ORMultiValueDictionary<TKey, TValue> SetItems(Cluster.Cluster node, TKey key, IImmutableSet<TValue> bucket) => SetItems(node.SelfUniqueAddress, key, bucket); /// <summary> /// Sets a <paramref name="bucket"/> of values inside current dictionary under provided <paramref name="key"/> /// in the context of the provided cluster <paramref name="node"/>. /// </summary> public ORMultiValueDictionary<TKey, TValue> SetItems(UniqueAddress node, TKey key, IImmutableSet<TValue> bucket) { var newUnderlying = Underlying.AddOrUpdate(node, key, ORSet<TValue>.Empty, _withValueDeltas, old => bucket.Aggregate(old.Clear(node), (set, element) => set.Add(node, element))); return new ORMultiValueDictionary<TKey, TValue>(newUnderlying, _withValueDeltas); } /// <summary> /// Removes all values inside current dictionary stored under provided <paramref name="key"/> /// in the context of the provided cluster <paramref name="node"/>. /// </summary> public ORMultiValueDictionary<TKey, TValue> Remove(Cluster.Cluster node, TKey key) => Remove(node.SelfUniqueAddress, key); /// <summary> /// Removes all values inside current dictionary stored under provided <paramref name="key"/> /// in the context of the provided cluster <paramref name="node"/>. /// </summary> public ORMultiValueDictionary<TKey, TValue> Remove(UniqueAddress node, TKey key) { if (_withValueDeltas) { var u = Underlying.AddOrUpdate(node, key, ORSet<TValue>.Empty, true, existing => existing.Clear(node)); return new ORMultiValueDictionary<TKey, TValue>(u.RemoveKey(node, key), _withValueDeltas); } else return new ORMultiValueDictionary<TKey, TValue>(Underlying.Remove(node, key), _withValueDeltas); } public ORMultiValueDictionary<TKey, TValue> Merge(ORMultiValueDictionary<TKey, TValue> other) { if (_withValueDeltas == other._withValueDeltas) { return _withValueDeltas ? new ORMultiValueDictionary<TKey, TValue>(Underlying.MergeRetainingDeletedValues(other.Underlying), _withValueDeltas) : new ORMultiValueDictionary<TKey, TValue>(Underlying.Merge(other.Underlying), _withValueDeltas); } throw new ArgumentException($"Trying to merge two ORMultiValueDictionaries of different map sub-types"); } /// <summary> /// Add an element to a set associated with a key. If there is no existing set then one will be initialised. /// </summary> public ORMultiValueDictionary<TKey, TValue> AddItem(Cluster.Cluster node, TKey key, TValue element) => AddItem(node.SelfUniqueAddress, key, element); /// <summary> /// Add an element to a set associated with a key. If there is no existing set then one will be initialised. /// </summary> public ORMultiValueDictionary<TKey, TValue> AddItem(UniqueAddress node, TKey key, TValue element) { var newUnderlying = Underlying.AddOrUpdate(node, key, ORSet<TValue>.Empty, _withValueDeltas, x => x.Add(node, element)); return new ORMultiValueDictionary<TKey, TValue>(newUnderlying, _withValueDeltas); } /// <summary> /// Remove an element of a set associated with a key. If there are no more elements in the set then the /// entire set will be removed. /// </summary> public ORMultiValueDictionary<TKey, TValue> RemoveItem(Cluster.Cluster node, TKey key, TValue element) => RemoveItem(node.SelfUniqueAddress, key, element); /// <summary> /// Remove an element of a set associated with a key. If there are no more elements in the set then the /// entire set will be removed. /// </summary> public ORMultiValueDictionary<TKey, TValue> RemoveItem(UniqueAddress node, TKey key, TValue element) { var newUnderlying = Underlying.AddOrUpdate(node, key, ORSet<TValue>.Empty, _withValueDeltas, set => set.Remove(node, element)); ORSet<TValue> found; if (newUnderlying.TryGetValue(key, out found) && found.IsEmpty) { if (_withValueDeltas) newUnderlying = newUnderlying.RemoveKey(node, key); else newUnderlying = newUnderlying.Remove(node, key); } return new ORMultiValueDictionary<TKey, TValue>(newUnderlying, _withValueDeltas); } /// <summary> /// Replace an element of a set associated with a key with a new one if it is different. This is useful when an element is removed /// and another one is added within the same Update. The order of addition and removal is important in order /// to retain history for replicated data. /// </summary> public ORMultiValueDictionary<TKey, TValue> ReplaceItem(Cluster.Cluster node, TKey key, TValue oldElement, TValue newElement) => ReplaceItem(node.SelfUniqueAddress, key, oldElement, newElement); /// <summary> /// Replace an element of a set associated with a key with a new one if it is different. This is useful when an element is removed /// and another one is added within the same Update. The order of addition and removal is important in order /// to retain history for replicated data. /// </summary> public ORMultiValueDictionary<TKey, TValue> ReplaceItem(UniqueAddress node, TKey key, TValue oldElement, TValue newElement) => !Equals(newElement, oldElement) ? AddItem(node, key, newElement).RemoveItem(node, key, oldElement) : this; public IReplicatedData Merge(IReplicatedData other) => Merge((ORMultiValueDictionary<TKey, TValue>)other); public ImmutableHashSet<UniqueAddress> ModifiedByNodes => Underlying.ModifiedByNodes; public bool NeedPruningFrom(UniqueAddress removedNode) => Underlying.NeedPruningFrom(removedNode); IReplicatedData IRemovedNodePruning.PruningCleanup(UniqueAddress removedNode) => PruningCleanup(removedNode); IReplicatedData IRemovedNodePruning.Prune(UniqueAddress removedNode, UniqueAddress collapseInto) => Prune(removedNode, collapseInto); public ORMultiValueDictionary<TKey, TValue> Prune(UniqueAddress removedNode, UniqueAddress collapseInto) => new ORMultiValueDictionary<TKey, TValue>(Underlying.Prune(removedNode, collapseInto), _withValueDeltas); public ORMultiValueDictionary<TKey, TValue> PruningCleanup(UniqueAddress removedNode) => new ORMultiValueDictionary<TKey, TValue>(Underlying.PruningCleanup(removedNode), _withValueDeltas); public bool Equals(ORMultiValueDictionary<TKey, TValue> other) { if (ReferenceEquals(other, null)) return false; if (ReferenceEquals(this, other)) return true; return Equals(Underlying, other.Underlying); } public IEnumerator<KeyValuePair<TKey, IImmutableSet<TValue>>> GetEnumerator() => Underlying.Select(x => new KeyValuePair<TKey, IImmutableSet<TValue>>(x.Key, x.Value.Elements)).GetEnumerator(); public override bool Equals(object obj) => obj is ORMultiValueDictionary<TKey, TValue> && Equals((ORMultiValueDictionary<TKey, TValue>)obj); public override int GetHashCode() => Underlying.GetHashCode(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public override string ToString() { var sb = new StringBuilder("ORMutliDictionary("); foreach (var entry in Entries) { sb.Append(entry.Key).Append("-> ["); foreach (var value in entry.Value) { sb.Append(value).Append(", "); } sb.Append("], "); } sb.Append(')'); return sb.ToString(); } #region delta internal sealed class ORMultiValueDictionaryDelta : ORDictionary<TKey, ORSet<TValue>>.IDeltaOperation, IReplicatedDeltaSize, IORMultiValueDictionaryDeltaOperation { internal readonly ORDictionary<TKey, ORSet<TValue>>.IDeltaOperation Underlying; public bool WithValueDeltas { get; } public ORMultiValueDictionaryDelta(ORDictionary<TKey, ORSet<TValue>>.IDeltaOperation underlying, bool withValueDeltas) { Underlying = underlying; WithValueDeltas = withValueDeltas; if (underlying is IReplicatedDeltaSize s) { DeltaSize = s.DeltaSize; } else { DeltaSize = 1; } } public IReplicatedData Merge(IReplicatedData other) { if (other is ORMultiValueDictionaryDelta d) { return new ORMultiValueDictionaryDelta((ORDictionary<TKey, ORSet<TValue>>.IDeltaOperation)Underlying.Merge(d.Underlying), WithValueDeltas || d.WithValueDeltas); } return new ORMultiValueDictionaryDelta((ORDictionary<TKey, ORSet<TValue>>.IDeltaOperation)Underlying.Merge(other), WithValueDeltas); } public IDeltaReplicatedData Zero => WithValueDeltas ? ORMultiValueDictionary<TKey, TValue>.EmptyWithValueDeltas : ORMultiValueDictionary<TKey, TValue>.Empty; public override bool Equals(object obj) { return obj is ORMultiValueDictionary<TKey, TValue>.ORMultiValueDictionaryDelta operation && Equals(operation.Underlying); } public bool Equals(ORDictionary<TKey, ORSet<TValue>>.IDeltaOperation other) { if (other is ORDictionary<TKey, ORSet<TValue>>.DeltaGroup group) { if (Underlying is ORDictionary<TKey, ORSet<TValue>>.DeltaGroup ourGroup) { return ourGroup.Operations.SequenceEqual(group.Operations); } if (group.Operations.Length == 1) { return Underlying.Equals(group.Operations.First()); } return false; } return Underlying.Equals(other); } public override int GetHashCode() { return Underlying.GetHashCode(); } public int DeltaSize { get; } ORDictionary.IDeltaOperation IORMultiValueDictionaryDeltaOperation.Underlying => (ORDictionary.IDeltaOperation)Underlying; } // TODO: optimize this so it doesn't allocate each time it's called public ORDictionary<TKey, ORSet<TValue>>.IDeltaOperation Delta => new ORMultiValueDictionaryDelta(Underlying.Delta, _withValueDeltas); public ORMultiValueDictionary<TKey, TValue> MergeDelta(ORDictionary<TKey, ORSet<TValue>>.IDeltaOperation delta) { if (delta is ORMultiValueDictionaryDelta ormmd) delta = ormmd.Underlying; if (_withValueDeltas) return new ORMultiValueDictionary<TKey, TValue>(Underlying.MergeDeltaRetainingDeletedValues(delta), _withValueDeltas); else return new ORMultiValueDictionary<TKey, TValue>(Underlying.MergeDelta(delta), _withValueDeltas); } IReplicatedDelta IDeltaReplicatedData.Delta => Delta; IReplicatedData IDeltaReplicatedData.MergeDelta(IReplicatedDelta delta) { switch (delta) { case ORMultiValueDictionaryDelta d: return MergeDelta(d.Underlying); default: return MergeDelta((ORDictionary<TKey, ORSet<TValue>>.IDeltaOperation)delta); } } IReplicatedData IDeltaReplicatedData.ResetDelta() => ResetDelta(); public ORMultiValueDictionary<TKey, TValue> ResetDelta() => new ORMultiValueDictionary<TKey, TValue>(Underlying.ResetDelta(), _withValueDeltas); #endregion public Type KeyType { get; } = typeof(TKey); public Type ValueType { get; } = typeof(TValue); } }
43.563107
196
0.621351
[ "Apache-2.0" ]
Bogdan-Rotund/akka.net
src/contrib/cluster/Akka.DistributedData/ORMultiValueDictionary.cs
17,950
C#
// ReSharper disable All using System.Collections.Generic; using System.Dynamic; using System.Net; using System.Net.Http; using System.Web.Http; using MixERP.Net.Api.Framework; using MixERP.Net.ApplicationState.Cache; using MixERP.Net.Common.Extensions; using MixERP.Net.EntityParser; using MixERP.Net.Framework; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using PetaPoco; using MixERP.Net.Schemas.Localization.Data; namespace MixERP.Net.Api.Localization { /// <summary> /// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Resources. /// </summary> [RoutePrefix("api/v1.5/localization/resource")] public class ResourceController : ApiController { /// <summary> /// The Resource repository. /// </summary> private readonly IResourceRepository ResourceRepository; public ResourceController() { this._LoginId = AppUsers.GetCurrent().View.LoginId.ToLong(); this._UserId = AppUsers.GetCurrent().View.UserId.ToInt(); this._OfficeId = AppUsers.GetCurrent().View.OfficeId.ToInt(); this._Catalog = AppUsers.GetCurrentUserDB(); this.ResourceRepository = new MixERP.Net.Schemas.Localization.Data.Resource { _Catalog = this._Catalog, _LoginId = this._LoginId, _UserId = this._UserId }; } public ResourceController(IResourceRepository repository, string catalog, LoginView view) { this._LoginId = view.LoginId.ToLong(); this._UserId = view.UserId.ToInt(); this._OfficeId = view.OfficeId.ToInt(); this._Catalog = catalog; this.ResourceRepository = repository; } public long _LoginId { get; } public int _UserId { get; private set; } public int _OfficeId { get; private set; } public string _Catalog { get; } /// <summary> /// Creates meta information of "resource" entity. /// </summary> /// <returns>Returns the "resource" meta information to perform CRUD operation.</returns> [AcceptVerbs("GET", "HEAD")] [Route("meta")] [Route("~/api/localization/resource/meta")] public EntityView GetEntityView() { if (this._LoginId == 0) { return new EntityView(); } return new EntityView { PrimaryKey = "resource_id", Columns = new List<EntityColumn>() { new EntityColumn { ColumnName = "resource_id", PropertyName = "ResourceId", DataType = "int", DbDataType = "int4", IsNullable = false, IsPrimaryKey = true, IsSerial = true, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "resource_class", PropertyName = "ResourceClass", DataType = "string", DbDataType = "text", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "key", PropertyName = "Key", DataType = "string", DbDataType = "text", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "value", PropertyName = "Value", DataType = "string", DbDataType = "text", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 } } }; } /// <summary> /// Counts the number of resources. /// </summary> /// <returns>Returns the count of the resources.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count")] [Route("~/api/localization/resource/count")] public long Count() { try { return this.ResourceRepository.Count(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (MixERPException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// Returns all collection of resource. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("all")] [Route("~/api/localization/resource/all")] public IEnumerable<MixERP.Net.Entities.Localization.Resource> GetAll() { try { return this.ResourceRepository.GetAll(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (MixERPException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// Returns collection of resource for export. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("export")] [Route("~/api/localization/resource/export")] public IEnumerable<dynamic> Export() { try { return this.ResourceRepository.Export(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (MixERPException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// Returns an instance of resource. /// </summary> /// <param name="resourceId">Enter ResourceId to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("{resourceId}")] [Route("~/api/localization/resource/{resourceId}")] public MixERP.Net.Entities.Localization.Resource Get(int resourceId) { try { return this.ResourceRepository.Get(resourceId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (MixERPException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } [AcceptVerbs("GET", "HEAD")] [Route("get")] [Route("~/api/localization/resource/get")] public IEnumerable<MixERP.Net.Entities.Localization.Resource> Get([FromUri] int[] resourceIds) { try { return this.ResourceRepository.Get(resourceIds); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (MixERPException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// Returns the first instance of resource. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("first")] [Route("~/api/localization/resource/first")] public MixERP.Net.Entities.Localization.Resource GetFirst() { try { return this.ResourceRepository.GetFirst(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (MixERPException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// Returns the previous instance of resource. /// </summary> /// <param name="resourceId">Enter ResourceId to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("previous/{resourceId}")] [Route("~/api/localization/resource/previous/{resourceId}")] public MixERP.Net.Entities.Localization.Resource GetPrevious(int resourceId) { try { return this.ResourceRepository.GetPrevious(resourceId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (MixERPException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// Returns the next instance of resource. /// </summary> /// <param name="resourceId">Enter ResourceId to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("next/{resourceId}")] [Route("~/api/localization/resource/next/{resourceId}")] public MixERP.Net.Entities.Localization.Resource GetNext(int resourceId) { try { return this.ResourceRepository.GetNext(resourceId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (MixERPException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// Returns the last instance of resource. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("last")] [Route("~/api/localization/resource/last")] public MixERP.Net.Entities.Localization.Resource GetLast() { try { return this.ResourceRepository.GetLast(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (MixERPException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// Creates a paginated collection containing 10 resources on each page, sorted by the property ResourceId. /// </summary> /// <returns>Returns the first page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("")] [Route("~/api/localization/resource")] public IEnumerable<MixERP.Net.Entities.Localization.Resource> GetPaginatedResult() { try { return this.ResourceRepository.GetPaginatedResult(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (MixERPException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// Creates a paginated collection containing 10 resources on each page, sorted by the property ResourceId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset.</param> /// <returns>Returns the requested page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("page/{pageNumber}")] [Route("~/api/localization/resource/page/{pageNumber}")] public IEnumerable<MixERP.Net.Entities.Localization.Resource> GetPaginatedResult(long pageNumber) { try { return this.ResourceRepository.GetPaginatedResult(pageNumber); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (MixERPException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// Counts the number of resources using the supplied filter(s). /// </summary> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the count of filtered resources.</returns> [AcceptVerbs("POST")] [Route("count-where")] [Route("~/api/localization/resource/count-where")] public long CountWhere([FromBody]JArray filters) { try { List<EntityParser.Filter> f = filters.ToObject<List<EntityParser.Filter>>(JsonHelper.GetJsonSerializer()); return this.ResourceRepository.CountWhere(f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (MixERPException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// Creates a filtered and paginated collection containing 10 resources on each page, sorted by the property ResourceId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("POST")] [Route("get-where/{pageNumber}")] [Route("~/api/localization/resource/get-where/{pageNumber}")] public IEnumerable<MixERP.Net.Entities.Localization.Resource> GetWhere(long pageNumber, [FromBody]JArray filters) { try { List<EntityParser.Filter> f = filters.ToObject<List<EntityParser.Filter>>(JsonHelper.GetJsonSerializer()); return this.ResourceRepository.GetWhere(pageNumber, f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (MixERPException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// Counts the number of resources using the supplied filter name. /// </summary> /// <param name="filterName">The named filter.</param> /// <returns>Returns the count of filtered resources.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count-filtered/{filterName}")] [Route("~/api/localization/resource/count-filtered/{filterName}")] public long CountFiltered(string filterName) { try { return this.ResourceRepository.CountFiltered(filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (MixERPException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// Creates a filtered and paginated collection containing 10 resources on each page, sorted by the property ResourceId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param> /// <param name="filterName">The named filter.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("GET", "HEAD")] [Route("get-filtered/{pageNumber}/{filterName}")] [Route("~/api/localization/resource/get-filtered/{pageNumber}/{filterName}")] public IEnumerable<MixERP.Net.Entities.Localization.Resource> GetFiltered(long pageNumber, string filterName) { try { return this.ResourceRepository.GetFiltered(pageNumber, filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (MixERPException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// Displayfield is a lightweight key/value collection of resources. /// </summary> /// <returns>Returns an enumerable key/value collection of resources.</returns> [AcceptVerbs("GET", "HEAD")] [Route("display-fields")] [Route("~/api/localization/resource/display-fields")] public IEnumerable<DisplayField> GetDisplayFields() { try { return this.ResourceRepository.GetDisplayFields(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (MixERPException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// A custom field is a user defined field for resources. /// </summary> /// <returns>Returns an enumerable custom field collection of resources.</returns> [AcceptVerbs("GET", "HEAD")] [Route("custom-fields")] [Route("~/api/localization/resource/custom-fields")] public IEnumerable<PetaPoco.CustomField> GetCustomFields() { try { return this.ResourceRepository.GetCustomFields(null); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (MixERPException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// A custom field is a user defined field for resources. /// </summary> /// <returns>Returns an enumerable custom field collection of resources.</returns> [AcceptVerbs("GET", "HEAD")] [Route("custom-fields/{resourceId}")] [Route("~/api/localization/resource/custom-fields/{resourceId}")] public IEnumerable<PetaPoco.CustomField> GetCustomFields(string resourceId) { try { return this.ResourceRepository.GetCustomFields(resourceId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (MixERPException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// Adds or edits your instance of Resource class. /// </summary> /// <param name="resource">Your instance of resources class to add or edit.</param> [AcceptVerbs("POST")] [Route("add-or-edit")] [Route("~/api/localization/resource/add-or-edit")] public object AddOrEdit([FromBody]Newtonsoft.Json.Linq.JArray form) { dynamic resource = form[0].ToObject<ExpandoObject>(JsonHelper.GetJsonSerializer()); List<EntityParser.CustomField> customFields = form[1].ToObject<List<EntityParser.CustomField>>(JsonHelper.GetJsonSerializer()); if (resource == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { return this.ResourceRepository.AddOrEdit(resource, customFields); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (MixERPException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// Adds your instance of Resource class. /// </summary> /// <param name="resource">Your instance of resources class to add.</param> [AcceptVerbs("POST")] [Route("add/{resource}")] [Route("~/api/localization/resource/add/{resource}")] public void Add(MixERP.Net.Entities.Localization.Resource resource) { if (resource == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { this.ResourceRepository.Add(resource); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (MixERPException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// Edits existing record with your instance of Resource class. /// </summary> /// <param name="resource">Your instance of Resource class to edit.</param> /// <param name="resourceId">Enter the value for ResourceId in order to find and edit the existing record.</param> [AcceptVerbs("PUT")] [Route("edit/{resourceId}")] [Route("~/api/localization/resource/edit/{resourceId}")] public void Edit(int resourceId, [FromBody] MixERP.Net.Entities.Localization.Resource resource) { if (resource == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { this.ResourceRepository.Update(resource, resourceId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (MixERPException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } private List<ExpandoObject> ParseCollection(JArray collection) { return JsonConvert.DeserializeObject<List<ExpandoObject>>(collection.ToString(), JsonHelper.GetJsonSerializerSettings()); } /// <summary> /// Adds or edits multiple instances of Resource class. /// </summary> /// <param name="collection">Your collection of Resource class to bulk import.</param> /// <returns>Returns list of imported resourceIds.</returns> /// <exception cref="MixERPException">Thrown when your any Resource class in the collection is invalid or malformed.</exception> [AcceptVerbs("POST")] [Route("bulk-import")] [Route("~/api/localization/resource/bulk-import")] public List<object> BulkImport([FromBody]JArray collection) { List<ExpandoObject> resourceCollection = this.ParseCollection(collection); if (resourceCollection == null || resourceCollection.Count.Equals(0)) { return null; } try { return this.ResourceRepository.BulkImport(resourceCollection); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (MixERPException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } /// <summary> /// Deletes an existing instance of Resource class via ResourceId. /// </summary> /// <param name="resourceId">Enter the value for ResourceId in order to find and delete the existing record.</param> [AcceptVerbs("DELETE")] [Route("delete/{resourceId}")] [Route("~/api/localization/resource/delete/{resourceId}")] public void Delete(int resourceId) { try { this.ResourceRepository.Delete(resourceId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (MixERPException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } } }
39.068802
259
0.552513
[ "MPL-2.0" ]
asine/mixerp
src/Libraries/Web API/Localization/ResourceController.cs
32,935
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable namespace Azure.ResourceManager.MachineLearning.Models { /// <summary> N-Cross validations value. </summary> public partial class NCrossValidations { /// <summary> Initializes a new instance of NCrossValidations. </summary> public NCrossValidations() { } /// <summary> Initializes a new instance of NCrossValidations. </summary> /// <param name="mode"> [Required] Mode for determining N-Cross validations. </param> internal NCrossValidations(NCrossValidationsMode mode) { Mode = mode; } /// <summary> [Required] Mode for determining N-Cross validations. </summary> internal NCrossValidationsMode Mode { get; set; } } }
30.172414
93
0.653714
[ "MIT" ]
sampa-msft/azure-sdk-for-net
sdk/machinelearningservices/Azure.ResourceManager.MachineLearning/src/Generated/Models/NCrossValidations.cs
875
C#
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events; using System; using System.Data.Common; using System.Linq; using System.Threading.Tasks; namespace Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF.Services { public class IntegrationEventLogService : IIntegrationEventLogService { private readonly DbConnection _dbConnection; private readonly IntegrationEventLogContext _integrationEventLogContext; public IntegrationEventLogService(DbConnection dbConnection) { _dbConnection = dbConnection ?? throw new ArgumentNullException("dbConnection"); _integrationEventLogContext = new IntegrationEventLogContext( new DbContextOptionsBuilder<IntegrationEventLogContext>() .UseSqlServer(_dbConnection) .ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning)) .Options); } public Task MarkEventAsPublishedAsync(IntegrationEvent @event) { var eventLogEntry = _integrationEventLogContext.IntegrationEventLogs.Single(ie => ie.EventId == @event.Id); eventLogEntry.TimesSent++; eventLogEntry.State = EventStateEnum.Published; _integrationEventLogContext.IntegrationEventLogs.Update(eventLogEntry); return _integrationEventLogContext.SaveChangesAsync(); } public Task SaveEventAsync(IntegrationEvent @event, DbTransaction transaction) { if (transaction == null) { throw new ArgumentNullException("transaction", $"A {typeof(DbTransaction).FullName} is required as a pre-requisite to save the event."); } var eventLogEntry = new IntegrationEventLogEntry(@event); _integrationEventLogContext.Database.UseTransaction(transaction); _integrationEventLogContext.IntegrationEventLogs.Add(eventLogEntry); return _integrationEventLogContext.SaveChangesAsync(); } } }
41.692308
152
0.710332
[ "MIT" ]
danibaptista/MicroserviceWithGraphQL
MicroserviceTemplate/BuildingBlocks/EventBus/IntegrationEventLogEF/Services/IntegrationEventLogService.cs
2,170
C#
using System; using System.Linq; using Sitecore.LogAnalyzer.Attributes; using Sitecore.MemoryDiagnostics; using Sitecore.MemoryDiagnostics.Models.FallBack.AspNetRelated; using Sitecore.MemoryDiagnostics.Models.InternalProcessing; using Sitecore.LogAnalyzer.MemoryDiagnostics.Connector.ClrObjToLogEntryTransformations.Interfaces; using Sitecore.LogAnalyzer.MemoryDiagnostics.Connector; namespace Sitecore.LogAnalyzer.MemoryDiagnostics.RunningRequests { /// <summary> /// Appends additional details from <see cref="HttpContextMappingModel"/> to <see cref="ClrObjLogEntry"/>. /// <para>Adds requested url, duration, cookies (analytics, asp.net).</para> /// </summary> public class AddRequestInfoToParentText : IInitLogEntryFields { public virtual void ApplyCustomLogicOnLogEntry([NotNull] ClrObjLogEntry entry) { if (!(entry.Model is HttpContextMappingModel mapping)) { return; } var requestInfo = from context in new[] { mapping } where context.HasURL let request = context._request as HttpRequestMappingModel let cookies = request?._cookies?.Value as HashtableMappingModel where cookies != null let analyticsCookie = cookies?[TextConstants.CookieNames.SitecoreAnalyticsGlobal] as HttpCookieModel let sessionCookie = cookies?[TextConstants.CookieNames.AspNetSession] as HttpCookieModel let analyticsId = analyticsCookie?.Value ?? "[No_Analytics_Cookie]" let aspSession = sessionCookie?.Value ?? "[No_Session_Cookie]" let metadata = new { context.URL, TotalSeconds = Math.Round(context.ExecutionDuration.TotalSeconds, digits: 2), ExecutionStarted = context.ContextCreationTime, analyticsId = analyticsId, aspSession = aspSession, context = context.HexAddress, request = request.HexAddress, } select metadata; var groupedRequestInfo = requestInfo.FirstOrDefault(); string message = string.Empty; if (groupedRequestInfo != null) { message = string.Join( Environment.NewLine, $"URL: {groupedRequestInfo.URL}", $"Executed for: {groupedRequestInfo.TotalSeconds} seconds", $"Asp.Net session: {groupedRequestInfo.aspSession}", $"Analytics: {groupedRequestInfo.analyticsId}", $"Started: {groupedRequestInfo.ExecutionStarted}", $"HttpRequest: {groupedRequestInfo.request}", Environment.NewLine); } if (string.IsNullOrEmpty(message)) { return; } if (entry.Parent != null && !entry.Parent.Text.StartsWith(message)) { var existingText = entry.Parent.Text; entry.Parent.Text = string.Join(Environment.NewLine, message, entry.Parent.Text); } } } }
39.3625
124
0.620514
[ "Apache-2.0" ]
mitikov/Sitecore.LogAnalyzer.MemoryDiagnostics
src/Sitecore.LogAnalyzer.MemoryDiagnostics.RunningRequests/AddRequestInfoToParentText.cs
3,151
C#
namespace MyServer.Web.Services { using System.Threading.Tasks; public interface IEmailSender { Task SendEmailAsync(string email, string subject, string message); } }
21.333333
74
0.703125
[ "MIT" ]
atanas-georgiev/MyServer
src/Web/MyServer.Web/Services/IEmailSender.cs
194
C#
global using NetDimension.NanUI; global using NetDimension.NanUI.HostWindow;
38.5
43
0.857143
[ "MIT" ]
XuanchenLin/NanUI-0.9-Examples
src/HostWindowFeatures/GlobalUsings.cs
79
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using BnGClub.Data; using BnGClub.Models; using Microsoft.Extensions.Configuration; using BnGClub.Utilities; namespace BnGClub.Controllers { public class UsersProfileController : Controller { private readonly BnGClubContext _context; private readonly IConfiguration _configuration; public UsersProfileController(BnGClubContext context, IConfiguration configuration) { _context = context; _configuration = configuration; } // GET: UsersProfile public async Task<IActionResult> Index() { return RedirectToAction(nameof(Details)); } // GET: UsersProfile/Details/5 public async Task<IActionResult> Details(int? id) { var users = await _context.Users .Where(u => u.userEmail == User.Identity.Name) .FirstOrDefaultAsync(); if (users == null) { return RedirectToAction(nameof(Create)); } return View(users); } // GET: UsersProfile/Create public IActionResult Create() { return View(); } // POST: UsersProfile/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("ID,userFName,userMName,userLName,userEmail,userPhone,notificationOptIn")] Users users) { users.userEmail = User.Identity.Name; try { if (ModelState.IsValid) { _context.Add(users); await _context.SaveChangesAsync(); UpdateUserNameCookie(users.FullName); return LocalRedirect("/Children/Create"); } } catch (DbUpdateException) { ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator."); } return View(users); } // GET: UsersProfile/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var users = await _context.Users .Where(u => u.userEmail == User.Identity.Name) .FirstOrDefaultAsync(); if (users == null) { return NotFound(); } ViewBag.PublicKey = _configuration.GetSection("VapidKeys")["PublicKey"]; return View(users); } // POST: UsersProfile/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, string PushEndpoint, string PushP256DH, string PushAuth, bool notifications) { var usersToUpdate = await _context.Users .FirstOrDefaultAsync(u => u.ID == id); AddToNotifications(id, PushEndpoint, PushP256DH, PushAuth, notifications, usersToUpdate); if (await TryUpdateModelAsync<Users>(usersToUpdate, "", u => u.userFName, u => u.userMName, u => u.userLName, u => u.userPhone, u => u.notificationOptIn)) { try { //Put the original RowVersion value in the OriginalValues collection for the entity usersToUpdate.notificationOptIn = notifications; _context.Update(usersToUpdate); await _context.SaveChangesAsync(); UpdateUserNameCookie(usersToUpdate.FullName); return RedirectToAction(nameof(Details)); } catch (DbUpdateConcurrencyException) { if (!UsersExists(usersToUpdate.ID)) { return NotFound(); } else { ModelState.AddModelError("", "Unable to save changes. The record you attempted to edit " + "was modified by another user after you received your values. You need to go back and try your edit again."); } } } return View(usersToUpdate); } // GET: UsersProfile/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var users = await _context.Users .FirstOrDefaultAsync(m => m.ID == id); if (users == null) { return NotFound(); } return View(users); } // POST: UsersProfile/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var users = await _context.Users.FindAsync(id); _context.Users.Remove(users); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private void AddToNotifications(int id, string PushEndpoint, string PushP256DH, string PushAuth, bool notifications, Users users) { var subUserExists = false; foreach (var s in _context.Subscriptions) { if (s.UserID == id) { subUserExists = true; } } if (notifications == true) { if (subUserExists == false) { _context.Subscriptions.Add(new Subscriptions { Name = users.FullName, PushEndpoint = PushEndpoint, PushP256DH = PushP256DH, PushAuth = PushAuth, UserID = id }); } } else if (notifications == false) { if (subUserExists == true) { Subscriptions subToRemove = _context.Subscriptions.FirstOrDefault(s => s.UserID == id); if (subToRemove != null) { _context.Subscriptions.Remove(subToRemove); } } } } private void UpdateUserNameCookie(string userName) { CookieHelper.CookieSet(HttpContext, "userName", userName, 960); } private bool UsersExists(int id) { return _context.Users.Any(e => e.ID == id); } } }
33.935484
144
0.522542
[ "Apache-2.0" ]
WiseNoobCrusher/BnGApplication
BnGClub/BnGClub/Controllers/UsersProfileController.cs
7,366
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace Microsoft.Azure.IIoT.Modules.OpcUa.Twin.Tests { using Microsoft.Azure.IIoT.Module.Framework; using Microsoft.Azure.IIoT.Module.Framework.Client; using Microsoft.Azure.IIoT.OpcUa.Protocol.Services; using Microsoft.Azure.IIoT.OpcUa.Registry; using Microsoft.Azure.IIoT.OpcUa.Registry.Models; using Microsoft.Azure.IIoT.OpcUa.Registry.Services; using Microsoft.Azure.IIoT.OpcUa.Testing.Runtime; using Microsoft.Azure.IIoT.OpcUa.Core.Models; using Microsoft.Azure.IIoT.OpcUa.Api.Core.Models; using Microsoft.Azure.IIoT.OpcUa.Api.Registry.Clients; using Microsoft.Azure.IIoT.OpcUa.Api.Twin; using Microsoft.Azure.IIoT.OpcUa.Api.Twin.Clients; using Microsoft.Azure.IIoT.Http.Default; using Microsoft.Azure.IIoT.Hub; using Microsoft.Azure.IIoT.Hub.Client; using Microsoft.Azure.IIoT.Hub.Mock; using Microsoft.Azure.IIoT.Hub.Models; using Microsoft.Azure.IIoT.Utils; using Microsoft.Azure.IIoT.Serializers; using Microsoft.Azure.IIoT.Serializers.NewtonSoft; using Microsoft.Extensions.Configuration; using Autofac; using Opc.Ua; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; /// <summary> /// Harness for opc twin module /// </summary> public class TwinModuleFixture : IInjector, ITwinModuleConfig, IDisposable { /// <summary> /// Device id /// </summary> public string DeviceId { get; } /// <summary> /// Module id /// </summary> public string ModuleId { get; } /// <summary> /// ServerPkiRootPath /// </summary> public string ServerPkiRootPath { get; } /// <summary> /// ClientPkiRootPath /// </summary> public string ClientPkiRootPath { get; } /// <summary> /// Hub container /// </summary> public IContainer HubContainer { get; } /// <summary> /// Create fixture /// </summary> public TwinModuleFixture() { DeviceId = Utils.GetHostName(); ModuleId = Guid.NewGuid().ToString(); ServerPkiRootPath = Path.Combine(Directory.GetCurrentDirectory(), "pki", Guid.NewGuid().ToByteArray().ToBase16String()); ClientPkiRootPath = Path.Combine(Directory.GetCurrentDirectory(), "pki", Guid.NewGuid().ToByteArray().ToBase16String()); _config = new ConfigurationBuilder() .AddInMemoryCollection(new Dictionary<string, string> { {"EnableMetrics", "false"}, {"PkiRootPath", ClientPkiRootPath} }) .Build(); HubContainer = CreateHubContainer(); _hub = HubContainer.Resolve<IIoTHubTwinServices>(); // Create module identitity var twin = _hub.CreateOrUpdateAsync(new DeviceTwinModel { Id = DeviceId, ModuleId = ModuleId }).Result; _etag = twin.Etag; // Get device registration and create module host with controller _device = _hub.GetRegistrationAsync(twin.Id, twin.ModuleId).Result; _running = false; _module = new ModuleProcess(_config, this); var tcs = new TaskCompletionSource<bool>(); _module.OnRunning += (_, e) => tcs.TrySetResult(e); _process = Task.Run(() => _module.RunAsync()); // Wait _running = tcs.Task.Result; } /// <inheritdoc/> public void Dispose() { if (_running) { _module.Exit(1); var result = _process.Result; Assert.Equal(1, result); _running = false; } if (Directory.Exists(ServerPkiRootPath)) { Try.Op(() => Directory.Delete(ServerPkiRootPath, true)); } HubContainer.Dispose(); } /// <inheritdoc/> public void Inject(ContainerBuilder builder) { // Register mock iot hub builder.RegisterInstance(_hub) .AsImplementedInterfaces().ExternallyOwned(); // Only configure if not yet running - otherwise we use twin host config. if (!_running) { builder.RegisterInstance(new TestModuleConfig(_device)) .AsImplementedInterfaces(); } // Add mock sdk builder.RegisterModule<IoTHubMockModule>(); // Override client config builder.RegisterInstance(_config).AsImplementedInterfaces(); builder.RegisterType<TestClientServicesConfig>() .AsImplementedInterfaces(); } /// <summary> /// Twin Module supervisor test harness /// </summary> /// <param name="test"></param> /// <returns></returns> public async Task RunTestAsync(Func<string, string, IContainer, Task> test) { AssertRunning(); try { await test(DeviceId, ModuleId, HubContainer); } finally { _module.Exit(1); var result = await _process; Assert.Equal(1, result); _running = false; } AssertStopped(); } /// <summary> /// Twin module twin test harness /// </summary> /// <param name="ep"></param> /// <param name="test"></param> /// <returns></returns> public async Task RunTestAsync(EndpointModel ep, Func<EndpointRegistrationModel, IContainer, Task> test) { var endpoint = new EndpointRegistrationModel { Endpoint = ep, SupervisorId = SupervisorModelEx.CreateSupervisorId( DeviceId, ModuleId) }; AssertRunning(); try { endpoint = RegisterAndActivateTwinId(endpoint); await test(endpoint, HubContainer); DeactivateTwinId(endpoint); } finally { _module.Exit(1); var result = await _process; Assert.Equal(1, result); _running = false; } AssertStopped(); } private void AssertStopped() { Assert.False(_running); var twin = _hub.GetAsync(DeviceId, ModuleId).Result; // TODO : Fix cleanup!!! // TODO :Assert.NotEqual("testType", twin.Properties.Reported[TwinProperty.kType]); // TODO :Assert.Equal("Disconnected", twin.ConnectionState); Assert.NotEqual(_etag, twin.Etag); } /// <summary> /// Assert module running /// </summary> public void AssertRunning() { Assert.True(_running); var twin = _hub.GetAsync(DeviceId, ModuleId).Result; // Assert Assert.Equal("Connected", twin.ConnectionState); Assert.Equal(IdentityType.Supervisor, twin.Properties.Reported[TwinProperty.Type]); Assert.False(twin.Properties.Reported.TryGetValue(TwinProperty.SiteId, out _)); } /// <summary> /// Activate /// </summary> /// <param name="endpoint"></param> /// <returns></returns> public EndpointRegistrationModel RegisterAndActivateTwinId(EndpointRegistrationModel endpoint) { var twin = new EndpointInfoModel { Registration = endpoint, ApplicationId = "uas" + Guid.NewGuid().ToString() }.ToEndpointRegistration(_serializer).ToDeviceTwin(_serializer); var result = _hub.CreateOrUpdateAsync(twin).Result; var registry = HubContainer.Resolve<IEndpointRegistry>(); var activate = HubContainer.Resolve<IEndpointActivation>(); var endpoints = registry.ListAllEndpointsAsync().Result; var ep1 = endpoints.FirstOrDefault(); if (ep1.ActivationState == EndpointActivationState.Deactivated) { // Activate activate.ActivateEndpointAsync(ep1.Registration.Id).Wait(); } return ep1.Registration; } /// <summary> /// Deactivate /// </summary> /// <param name="endpoint"></param> /// <returns></returns> public void DeactivateTwinId(EndpointRegistrationModel endpoint) { var activate = HubContainer.Resolve<IEndpointActivation>(); // Deactivate activate.DeactivateEndpointAsync(endpoint.Id).Wait(); } /// <inheritdoc/> public class TestModuleConfig : IModuleConfig { /// <inheritdoc/> public TestModuleConfig(DeviceModel device) { _device = device; } /// <inheritdoc/> public string EdgeHubConnectionString => ConnectionString.CreateModuleConnectionString("test.test.org", _device.Id, _device.ModuleId, _device.Authentication.PrimaryKey) .ToString(); /// <inheritdoc/> public bool BypassCertVerification => true; /// <inheritdoc/> public TransportOption Transport => TransportOption.Any; /// <inheritdoc/> public bool EnableMetrics => false; private readonly DeviceModel _device; } /// <inheritdoc/> public class TestIoTHubConfig : IIoTHubConfig { /// <inheritdoc/> public string IoTHubConnString => ConnectionString.CreateServiceConnectionString( "test.test.org", "iothubowner", Convert.ToBase64String( Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()))).ToString(); } /// <summary> /// Create hub container /// </summary> /// <returns></returns> private IContainer CreateHubContainer() { var builder = new ContainerBuilder(); builder.RegisterModule<NewtonSoftJsonModule>(); builder.RegisterInstance(this).AsImplementedInterfaces(); builder.RegisterInstance(_config).AsImplementedInterfaces(); builder.AddDiagnostics(); builder.RegisterModule<IoTHubMockService>(); builder.RegisterType<TestIoTHubConfig>() .AsImplementedInterfaces(); // Twin and history clients builder.RegisterType<TwinModuleControlClient>() .AsImplementedInterfaces(); builder.RegisterType<TwinModuleSupervisorClient>() .AsImplementedInterfaces(); builder.RegisterType<HistoryRawSupervisorAdapter>() .AsImplementedInterfaces(); builder.RegisterType<TwinSupervisorAdapter>() .AsImplementedInterfaces(); builder.RegisterType<TwinModuleClient>() .AsImplementedInterfaces(); // Supervisor clients builder.RegisterType<TwinModuleActivationClient>() .AsImplementedInterfaces(); builder.RegisterType<TwinModuleCertificateClient>() .AsImplementedInterfaces(); builder.RegisterType<TwinModuleDiagnosticsClient>() .AsImplementedInterfaces(); builder.RegisterType<DiscovererModuleClient>() .AsImplementedInterfaces(); builder.RegisterType<VariantEncoderFactory>() .AsImplementedInterfaces(); // Add services builder.RegisterModule<RegistryServices>(); builder.RegisterType<ApplicationTwins>() .AsImplementedInterfaces(); builder.RegisterModule<EventBrokerStubs>(); // Register http client module builder.RegisterModule<HttpClientModule>(); return builder.Build(); } private readonly IIoTHubTwinServices _hub; private readonly string _etag; private readonly DeviceModel _device; private bool _running; private readonly ModuleProcess _module; private readonly IConfiguration _config; private readonly Task<int> _process; private readonly IJsonSerializer _serializer = new NewtonSoftJsonSerializer(); } }
37.239884
104
0.574544
[ "MIT" ]
PayalDodeja/Industrial-IoT
modules/src/Microsoft.Azure.IIoT.Modules.OpcUa.Twin/tests/Fixtures/TwinModuleFixture.cs
12,885
C#
using System; using Abp.Application.Services.Dto; using Abp.AutoMapper; using NorthLion.Zero.Authorization.Users; namespace NorthLion.Zero.Users.Dto { [AutoMapFrom(typeof(User))] public class UserListDto : EntityDto<long> { public string Name { get; set; } public string Surname { get; set; } public string UserName { get; set; } public string FullName { get; set; } public string EmailAddress { get; set; } public bool IsEmailConfirmed { get; set; } public DateTime? LastLoginTime { get; set; } public bool IsActive { get; set; } public DateTime CreationTime { get; set; } } }
23.241379
52
0.639466
[ "MIT" ]
CodefyMX/NorthLionAbpZeroNetCore
aspnet-core/src/NorthLion.Zero.Application/Users/Dto/UserListDto.cs
674
C#
// c:\program files (x86)\windows kits\10\include\10.0.22000.0\um\dxvahd.h(459,9) using System; using System.Runtime.InteropServices; namespace DirectN { [StructLayout(LayoutKind.Sequential)] public partial struct _DXVAHD_STREAM_STATE_FILTER_DATA { public bool Enable; public int Level; } }
24.142857
83
0.683432
[ "MIT" ]
Steph55/DirectN
DirectN/DirectN/Generated/_DXVAHD_STREAM_STATE_FILTER_DATA.cs
340
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("TessyRegisterConverter")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TessyRegisterConverter")] [assembly: AssemblyCopyright("Copyright © 2020")] [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("5b9566a1-6d34-4812-a7cd-0268f858f253")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.297297
84
0.748765
[ "MIT" ]
ajn96/TessyRegisterConverter
Properties/AssemblyInfo.cs
1,420
C#
/* * File: Synchronizable.cs * * Author: Akira Sugiura (urasandesu@gmail.com) * * * Copyright (c) 2017 Akira Sugiura * * This software is MIT License. * * 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 Urasandesu.Enkidu { public static class Synchronizable { public static ISynchronizable EventWait(Predicate<object> willHandle, HandledCallback begun = null, HandledCallback ended = null, AllNotifiedCallback allNotified = null) { if (willHandle == null) throw new ArgumentNullException(nameof(willHandle)); return new EventWaitable(willHandle, begun, ended, allNotified); } public static ISynchronizable EventSet(Predicate<object> willHandle, HandledCallback begun = null, HandledCallback ended = null, AllNotifiedCallback allNotified = null) { if (willHandle == null) throw new ArgumentNullException(nameof(willHandle)); return new EventSettable(willHandle, begun, ended, allNotified); } public static ISynchronizable SystemWideEventWait(string name, Predicate<object> willHandle, HandledCallback begun = null, HandledCallback ended = null, AllNotifiedCallback allNotified = null) { if (willHandle == null) throw new ArgumentNullException(nameof(willHandle)); return new SystemWideEventWaitable(name, willHandle, begun, ended, allNotified); } public static ISynchronizable SystemWideEventSet(string name, Predicate<object> willHandle, HandledCallback begun = null, HandledCallback ended = null, AllNotifiedCallback allNotified = null) { if (willHandle == null) throw new ArgumentNullException(nameof(willHandle)); return new SystemWideEventSettable(name, willHandle, begun, ended, allNotified); } public static ISynchronizable Empty() { return new EmptySynchronizable(); } public static ISynchronizable Delay(this ISynchronizable source, TimeSpan delay) { var totalMilliseconds = (long)delay.TotalMilliseconds; if (totalMilliseconds < -1 || int.MaxValue < totalMilliseconds) throw new ArgumentOutOfRangeException(nameof(delay), Resources.GetString("Synchronizable_Delay_InvalidDelay")); return source.Delay((int)totalMilliseconds); } public static ISynchronizable Delay(this ISynchronizable source, int millisecondsDelay) { if (millisecondsDelay < -1) throw new ArgumentOutOfRangeException(nameof(millisecondsDelay), Resources.GetString("Synchronizable_Delay_InvalidMillisecondsDelay")); if (millisecondsDelay == 0) return Empty(); else if (source is EmptySynchronizable) return source; else return new DelaySynchronizable(source, millisecondsDelay); } public static ISynchronizable Pause(this ISynchronizable source, TimeSpan delay) { var totalMilliseconds = (long)delay.TotalMilliseconds; if (totalMilliseconds < -1 || int.MaxValue < totalMilliseconds) throw new ArgumentOutOfRangeException(nameof(delay), Resources.GetString("Synchronizable_Pause_InvalidPause")); return source.Pause((int)totalMilliseconds); } public static ISynchronizable Pause(this ISynchronizable source, int millisecondsPause) { if (millisecondsPause < -1) throw new ArgumentOutOfRangeException(nameof(millisecondsPause), Resources.GetString("Synchronizable_Pause_InvalidMillisecondsPause")); if (millisecondsPause == 0) return Empty(); else if (source is EmptySynchronizable) return source; else return new PauseSynchronizable(source, millisecondsPause); } public static ISynchronizable Then(this ISynchronizable lhs, ISynchronizable rhs) { if (lhs == null) throw new ArgumentNullException(nameof(lhs)); if (rhs == null) throw new ArgumentNullException(nameof(rhs)); if (lhs is EmptySynchronizable && rhs is EmptySynchronizable) return Empty(); else if (lhs is EmptySynchronizable) return rhs; else if (rhs is EmptySynchronizable) return lhs; else return new ThenSynchronizable(lhs, rhs); } public static ISynchronizable And(this ISynchronizable lhs, ISynchronizable rhs) { if (lhs == null) throw new ArgumentNullException(nameof(lhs)); if (rhs == null) throw new ArgumentNullException(nameof(rhs)); if (lhs is EmptySynchronizable && rhs is EmptySynchronizable) return Empty(); else if (lhs is EmptySynchronizable) return rhs; else if (rhs is EmptySynchronizable) return lhs; else return new AndSynchronizable(lhs, rhs); } public static ISynchronizable Or(this ISynchronizable lhs, ISynchronizable rhs) { if (lhs == null) throw new ArgumentNullException(nameof(lhs)); if (rhs == null) throw new ArgumentNullException(nameof(rhs)); if (lhs is EmptySynchronizable && rhs is EmptySynchronizable) return Empty(); else if (lhs is EmptySynchronizable) return rhs; else if (rhs is EmptySynchronizable) return lhs; else return new OrSynchronizable(lhs, rhs); } } }
39.988889
152
0.620172
[ "MIT" ]
urasandesu/Enkidu
Urasandesu.Enkidu/Synchronizable.cs
7,200
C#
// Generated class v2.13.0.0, don't modify using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; namespace NHtmlUnit.Javascript.Host.Svg { public partial class SVGFEFuncBElement : NHtmlUnit.Javascript.Host.Svg.SVGElement { static SVGFEFuncBElement() { ObjectWrapper.RegisterWrapperCreator((com.gargoylesoftware.htmlunit.javascript.host.svg.SVGFEFuncBElement o) => new SVGFEFuncBElement(o)); } public SVGFEFuncBElement(com.gargoylesoftware.htmlunit.javascript.host.svg.SVGFEFuncBElement wrappedObject) : base(wrappedObject) {} public new com.gargoylesoftware.htmlunit.javascript.host.svg.SVGFEFuncBElement WObj { get { return (com.gargoylesoftware.htmlunit.javascript.host.svg.SVGFEFuncBElement)WrappedObject; } } public SVGFEFuncBElement() : this(new com.gargoylesoftware.htmlunit.javascript.host.svg.SVGFEFuncBElement()) {} } }
31.363636
139
0.716908
[ "Apache-2.0" ]
timorzadir/NHtmlUnit
app/NHtmlUnit/Generated/Javascript/Host/Svg/SVGFEFuncBElement.cs
1,035
C#
using Aurora.Profiles.Generic.GSI.Nodes; using Aurora.Profiles.StardewValley.GSI.Nodes; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Aurora.Profiles.StardewValley.GSI { public class GameState_StardewValley : GameState { public ProviderNode Provider => NodeFor<ProviderNode>("Provider"); public WorldNode World => NodeFor<WorldNode>("World"); public PlayerNode Player => NodeFor<PlayerNode>("Player"); public InventoryNode Inventory => NodeFor<InventoryNode>("Inventory"); public JournalNode Journal => NodeFor<JournalNode>("Journal"); public GameStatusNode Game => NodeFor<GameStatusNode>("Game"); public GameState_StardewValley() : base() { } /// <summary> /// Creates a GameState_StardewValley instance based on the passed JSON data. /// </summary> /// <param name="JSONstring"></param> public GameState_StardewValley(string JSONstring) : base(JSONstring) { } } }
37.1
86
0.683738
[ "MIT" ]
ADoesGit/Aurora
Project-Aurora/Project-Aurora/Profiles/Stardew Valley/GSI/GameState_StardewValley.cs
1,084
C#
using System; namespace PnP.Core.Model.SharePoint { /// <summary> /// Public interface to define a SPAppLicenseManager object /// </summary> [ConcreteType(typeof(SPAppLicenseManager))] public interface ISPAppLicenseManager : IDataModel<ISPAppLicenseManager>, IDataModelGet<ISPAppLicenseManager>, IDataModelUpdate, IDataModelDelete { #region New properties /// <summary> /// To update... /// </summary> public string Id4a81de82eeb94d6080ea5bf63e27023a { get; set; } #endregion } }
24.391304
149
0.666667
[ "MIT" ]
DonKirkham/pnpcore
src/generated/SP/Public/ISPAppLicenseManager.cs
561
C#
using System; using System.Collections.Generic; using System.Linq; namespace Orders { class Program { static void Main(string[] args) { var dict = new Dictionary<string,Product>(); while (true) { string[] input = Console.ReadLine().Split(" "); if(input[0]== "buy") { break; } string product = input[0]; double price = double.Parse(input[1]); int quantity = int.Parse(input[2]); Product product1 = new Product(price, quantity); if (!dict.ContainsKey(product)) { dict[product] = product1; } else { dict[product].Quontity += quantity; dict[product].Price = price; } } foreach (var item in dict) { Console.WriteLine($"{item.Key} -> {item.Value.Price*item.Value.Quontity:f2}"); } } } class Product { public double Price { get; set; } public int Quontity { get; set; } public Product(double price,int quontity) { this.Price = price; this.Quontity = quontity; } } }
22.430769
94
0.41358
[ "MIT" ]
VladimirDikovski/C-Fundamentals-May-2019
Associative Arrays - Exercise/Orders/Orders/Program.cs
1,460
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MenuAudioManager : MonoBehaviour { private AudioSource source; [SerializeField] private string introBGMusic; void Awake() { source = this.GetComponent<AudioSource>(); } public void PlayIntroMusic() { PlayMusic(Resources.Load("Music/" + introBGMusic) as AudioClip); } private void PlayMusic(AudioClip clip) { source.clip = clip; source.Play(); } public void StopMusic() { source.Stop(); } }
18.962963
66
0.726563
[ "MIT" ]
michelsara/GameDevelopment
SlimeTime/Assets/Scripts/MenuAudioManager.cs
512
C#
// Copyright (c) Josef Pihrt and Contributors. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Roslynator.Testing.CSharp; using Xunit; namespace Roslynator.CSharp.Refactorings.Tests { public class RR0175WrapLinesInRegionTests : AbstractCSharpRefactoringVerifier { public override string RefactoringId { get; } = RefactoringIdentifiers.WrapLinesInRegion; [Fact, Trait(Traits.Refactoring, RefactoringIdentifiers.WrapLinesInRegion)] public async Task Test_EndsAtStartOfLine() { await VerifyRefactoringAsync(@" class C { [| void M() { } |]} ", @" class C { #region void M() { } #endregion } ", equivalenceKey: EquivalenceKey.Create(RefactoringId)); } [Fact, Trait(Traits.Refactoring, RefactoringIdentifiers.WrapLinesInRegion)] public async Task Test_EndsAtEndOfLine() { await VerifyRefactoringAsync(@" class C { [| void M() { }|] } ", @" class C { #region void M() { } #endregion } ", equivalenceKey: EquivalenceKey.Create(RefactoringId)); } [Fact, Trait(Traits.Refactoring, RefactoringIdentifiers.WrapLinesInRegion)] public async Task Test_StartsAfterSingeLineDocumentationComment() { await VerifyRefactoringAsync(@" class C { /// <summary> /// /// </summary> [| void M() { } |]} ", @" class C { /// <summary> /// /// </summary> #region void M() { } #endregion } ", equivalenceKey: EquivalenceKey.Create(RefactoringId)); } [Fact, Trait(Traits.Refactoring, RefactoringIdentifiers.WrapLinesInRegion)] public async Task Test_StartsAndEndsInSingleLineDocumentationComment() { await VerifyRefactoringAsync(@" class C { /// <summary> [| /// |] /// </summary> void M() { } } ", @" class C { /// <summary> #region /// #endregion /// </summary> void M() { } } ", equivalenceKey: EquivalenceKey.Create(RefactoringId)); } [Fact, Trait(Traits.Refactoring, RefactoringIdentifiers.WrapLinesInRegion)] public async Task Test_EndsAtEndOfSingleLineDocumentationComment() { await VerifyRefactoringAsync(@" class C { [| /// <summary> /// /// </summary>|] void M() { } } ", @" class C { #region /// <summary> /// /// </summary> #endregion void M() { } } ", equivalenceKey: EquivalenceKey.Create(RefactoringId)); } [Fact, Trait(Traits.Refactoring, RefactoringIdentifiers.WrapLinesInRegion)] public async Task Test_MultiLineDocumentationComment() { await VerifyRefactoringAsync(@" class C { [| /** * <summary></summary> */ |] void M() { } } ", @" class C { #region /** * <summary></summary> */ #endregion void M() { } } ", equivalenceKey: EquivalenceKey.Create(RefactoringId)); } [Fact, Trait(Traits.Refactoring, RefactoringIdentifiers.WrapLinesInRegion)] public async Task Test_EndsAtEndOfMultiLineDocumentationComment() { await VerifyRefactoringAsync(@" class C { [| /** * <summary></summary> */|] void M() { } } ", @" class C { #region /** * <summary></summary> */ #endregion void M() { } } ", equivalenceKey: EquivalenceKey.Create(RefactoringId)); } [Fact, Trait(Traits.Refactoring, RefactoringIdentifiers.WrapLinesInRegion)] public async Task Test_EntireText() { await VerifyRefactoringAsync(@"[|class C { void M() { } } |]", @"#region class C { void M() { } } #endregion ", equivalenceKey: EquivalenceKey.Create(RefactoringId)); } [Fact, Trait(Traits.Refactoring, RefactoringIdentifiers.WrapLinesInRegion)] public async Task TestNoRefactoring_SpanIsEmpty() { await VerifyNoRefactoringAsync(@" class C { void M() { [||] } } ", equivalenceKey: EquivalenceKey.Create(RefactoringId)); } [Fact, Trait(Traits.Refactoring, RefactoringIdentifiers.WrapLinesInRegion)] public async Task TestNoRefactoring_StartInMultiLineDocumentationComment() { await VerifyNoRefactoringAsync(@" class C { /** [| * <summary></summary> */ void M() |] { } } ", equivalenceKey: EquivalenceKey.Create(RefactoringId)); } [Fact, Trait(Traits.Refactoring, RefactoringIdentifiers.WrapLinesInRegion)] public async Task TestNoRefactoring_EndsInMultiLineDocumentationComment() { await VerifyNoRefactoringAsync(@" class C [|{ /** * <summary></summary> |] */ void M() { } } ", equivalenceKey: EquivalenceKey.Create(RefactoringId)); } [Fact, Trait(Traits.Refactoring, RefactoringIdentifiers.WrapLinesInRegion)] public async Task TestNoRefactoring_EndsInMultiLineDocumentationComment2() { await VerifyNoRefactoringAsync(@" class C [|{ /** * <summary></summary>|] */ void M() { } } ", equivalenceKey: EquivalenceKey.Create(RefactoringId)); } } }
19.238434
156
0.595634
[ "Apache-2.0" ]
ProphetLamb-Organistion/Roslynator
src/Tests/Refactorings.Tests/RR0175WrapLinesInRegionTests.cs
5,408
C#
using Microsoft.Xna.Framework; using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace tsorcRevamp.Projectiles.Enemy.Okiku { public class AntiMatterBlast : ModProjectile { public override void SetDefaults() { projectile.width = 55; projectile.height = 55; projectile.scale = 2.3f; projectile.aiStyle = 9; projectile.hostile = true; projectile.damage = 80; projectile.penetrate = 2; projectile.tileCollide = false; projectile.ranged = true; } public override bool PreKill(int timeLeft) { projectile.type = 79; //killpretendtype return true; } public override bool PreAI() { projectile.rotation++; int dust = Dust.NewDust(new Vector2((float)projectile.position.X + 10, (float)projectile.position.Y), projectile.width, projectile.height, 6, 0, 0, 200, Color.Red, 1f); Main.dust[dust].noGravity = true; if (projectile.velocity.X <= 10 && projectile.velocity.Y <= 10 && projectile.velocity.X >= -10 && projectile.velocity.Y >= -10) { projectile.velocity.X *= 1.01f; projectile.velocity.Y *= 1.01f; } return true; } public override void OnHitPlayer(Player target, int damage, bool crit) { target.AddBuff(BuffID.Confused, 300, false); target.AddBuff(BuffID.Gravitation, 300, false); target.AddBuff(BuffID.Slow, 300, false); } } }
36.906977
180
0.587902
[ "MIT" ]
RecursiveCollapse/tsorcRevamp
Projectiles/Enemy/Okiku/AntiMatterBlast.cs
1,589
C#
using PandaSharp.Bamboo.Rest.Contract; using PandaSharp.Bamboo.Services.Build.Contract; using PandaSharp.Bamboo.Services.Build.Request.Base; using PandaSharp.Bamboo.Services.Build.Response; using PandaSharp.Bamboo.Services.Common.Aspect; using RestSharp; namespace PandaSharp.Bamboo.Services.Build.Request { internal sealed class GetCommentsOfBuildRequest : BuildRequestBase<CommentListResponse>, IGetCommentsOfBuildRequest { public GetCommentsOfBuildRequest(IRestFactory restClientFactory, IRequestParameterAspectFactory parameterAspectFactory) : base(restClientFactory, parameterAspectFactory) { } protected override string GetResourcePath() { return $"result/{ProjectKey}-{PlanKey}-{BuildNumber}/comment"; } protected override Method GetRequestMethod() { return Method.GET; } protected override void ApplyToRestRequest(IRestRequest restRequest) { restRequest.AddParameter("expand", "comments.comment"); } } }
33.46875
127
0.716153
[ "MIT" ]
soerendd/PandaSharp
PandaSharp.Bamboo/Services/Build/Request/GetCommentsOfBuildRequest.cs
1,071
C#
using System; using System.Collections.Generic; using System.Drawing; using System.Text; using System.Windows.Forms; using System.ComponentModel; namespace DictControls.Controls { public class SplitView : SplitContainer { #region Variables /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; #endregion #region Constructor public SplitView() { this.InitializeComponent(); this.InitializeControl(); } public SplitView(IContainer container) { container.Add(this); this.InitializeComponent(); this.InitializeControl(); } protected void InitializeControl() { this.SetStyle(ControlStyles.ResizeRedraw, true); this.SetStyle(ControlStyles.UserPaint, true); this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); this.SetStyle(ControlStyles.DoubleBuffer, true); this.UpdateStyles(); } #endregion #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { } #endregion #region Methods /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } protected override void OnPaintBackground(PaintEventArgs e) { base.OnPaintBackground(e); e.Graphics.DrawLine(SystemPens.ActiveBorder, this.SplitterDistance, 4, this.SplitterDistance, this.Height - 8); } #endregion } }
27.833333
123
0.585444
[ "Apache-2.0" ]
soeminnminn/EngMyanDictionary-WIN
EngMyanDict/Controls/SplitView.cs
2,173
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Android.App; // 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("Xamarin.Posed.Demo")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Xamarin.Posed.Demo")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
33.666667
77
0.750275
[ "MIT" ]
UlyssesWu/XamarinPosed
Xamarin.Posed.Demo/Properties/AssemblyInfo.cs
912
C#
// <auto-generated /> using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using PawPadIO.Hub.Domain.Data; namespace PawPadIO.Hub.Domain.Migrations { [DbContext(typeof(HubDbContext))] [Migration("20201212032947_Init")] partial class Init { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.10"); modelBuilder.Entity("PawPadIO.Hub.Domain.Models.HubUser", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Email") .HasColumnType("TEXT"); b.Property<string>("Issuer") .HasColumnType("TEXT"); b.Property<string>("Name") .HasColumnType("TEXT"); b.Property<string>("Subject") .HasColumnType("TEXT"); b.HasKey("Id"); b.ToTable("HubUsers"); }); #pragma warning restore 612, 618 } } }
30.065217
75
0.547361
[ "MIT" ]
PawPadIO/Hub
src/PawPadIO.Hub.Domain/Migrations/20201212032947_Init.Designer.cs
1,385
C#
// ----------------------------------------------------------------------------------- // // GRABCASTER LTD CONFIDENTIAL // ___________________________ // // Copyright © 2013 - 2016 GrabCaster Ltd. All rights reserved. // This work is registered with the UK Copyright Service: Registration No:284701085 // // // NOTICE: All information contained herein is, and remains // the property of GrabCaster Ltd and its suppliers, // if any. The intellectual and technical concepts contained // herein are proprietary to GrabCaster Ltd // and its suppliers and may be covered by UK and Foreign Patents, // patents in process, and are protected by trade secret or copyright law. // Dissemination of this information or reproduction of this material // is strictly forbidden unless prior written permission is obtained // from GrabCaster Ltd. // // ----------------------------------------------------------------------------------- using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("EventHubEvent")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EventHubEvent")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("fdea48aa-9bbc-406a-89a7-105234c719b4")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.847458
87
0.693281
[ "MIT" ]
debiaggi/GrabCaster
Events/EventHubEvent/Properties/AssemblyInfo.cs
2,296
C#
using Domain; using Repository.Interfaces.Base; using System.Collections.Generic; namespace Repository.Interfaces { public interface IWishRepository : IRepository<Wish> { void InsertWish(Wish wish); List<Wish> GetWishesPerCustomer(int custid); List<Wish> GetWishesPerSpot(int spotid); List<Wish> GetWishesPerCustomerSpot(int custid, int spotid); void AttendWish(WishTarget target); void GrantWish(Exchange exchange); } }
22.181818
68
0.704918
[ "MIT" ]
Thijapones/MTG4Us
MTG4Us/Repository/Interfaces/IWishRepository.cs
490
C#
#region License // Copyright (c) 2009, ClearCanvas Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of ClearCanvas Inc. nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // 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 namespace ClearCanvas.Common { /// <summary> /// An extension filter that checks for equality with the extension class name. /// </summary> public class ClassNameExtensionFilter : ExtensionFilter { private string _name; /// <summary> /// Constructor. /// </summary> /// <param name="name">The extension class name that will be a match for this filter.</param> public ClassNameExtensionFilter(string name) { _name = name; } /// <summary> /// Tests whether or not the input <see cref="ExtensionInfo.ExtensionClass"/>' full name matches /// the name supplied to the filter constructor. /// </summary> public override bool Test(ExtensionInfo extension) { return extension.ExtensionClass.FullName.Equals(_name); } } }
41.983333
100
0.698293
[ "Apache-2.0" ]
econmed/ImageServer20
Common/ClassNameExtensionFilter.cs
2,521
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Xaml.Interactions.UnitTests { using System; using System.Diagnostics; using System.Windows.Controls; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.Xaml.Behaviors; using SysWindows = System.Windows; [TestClass] public class ActionTest { [TestInitialize] public void Setup() { Interaction.ShouldRunInDesignMode = true; } [TestCleanup] public void Teardown() { Interaction.ShouldRunInDesignMode = false; } [TestMethod] public void AttachDetachTest() { StubAction stubAction = new StubAction(); BehaviorTestUtilities.TestIAttachedObject<Button>((IAttachedObject)stubAction); StubTargetedTriggerAction stubTargetedTriggerAction = new StubTargetedTriggerAction(); BehaviorTestUtilities.TestIAttachedObject<Button>((IAttachedObject)stubTargetedTriggerAction); } [TestMethod] public void ConstrainedActionTest() { BehaviorTestUtilities.TestConstraintOnAssociatedObject<Button>(new StubButtonTriggerAction()); } [TestMethod] public void InvokeTest() { StubAction action = new StubAction(); StubTrigger trigger = new StubTrigger(); Assert.AreEqual(action.InvokeCount, 0, "action.InvokeCount == 0"); action.StubInvoke(); Assert.AreEqual(action.InvokeCount, 1, "After invoking action, action.InvokeCount == 1"); trigger.Actions.Add(action); action.IsEnabled = false; trigger.FireStubTrigger(); Assert.AreEqual(action.InvokeCount, 1, "action.InvokeCount == 1"); action.IsEnabled = true; trigger.FireStubTrigger(); Assert.AreEqual(action.InvokeCount, 2, "action.InvokeCount == 2"); } [TestMethod] public void TestCreateInstanceCore() { StubAction action = new StubAction(); SysWindows.Freezable freezable = action.GetCreateInstanceCore(); Assert.AreEqual(freezable.GetType(), typeof(StubAction), "freezable.GetType() == typeof(StubAction)"); } [TestMethod] public void ParentTriggerTest() { StubTrigger trigger = new StubTrigger(); StubAction action = new StubAction(); trigger.Actions.Add(action); Assert.AreEqual(((IAttachedObject)action).AssociatedObject, trigger.HostObject, "After adding action to trigger, action.AssociatedObject should equal trigger.Host"); Assert.AreEqual(trigger.Actions.Count, 1, "trigger.Actions.Count == 1"); trigger.Actions.Remove(action); Assert.IsNull(((IAttachedObject)action).AssociatedObject, "After removing action from trigger, action.AssociatedObject should be null"); Assert.AreEqual(trigger.Actions.Count, 0, "trigger.Actions.Count == 0"); } [TestMethod] public void ReparentActionTest() { SysWindows.Shapes.Rectangle hostRectangle = new SysWindows.Shapes.Rectangle(); // try parenting an action more than once; should throw StubAction action = new StubAction(); StubTrigger trigger1 = new StubTrigger(); StubTrigger trigger2 = new StubTrigger(); trigger1.Attach(hostRectangle); trigger2.Attach(hostRectangle); trigger1.Actions.Add(action); try { trigger2.Actions.Add(action); Debug.Fail("Expected InvalidOperationException to be thrown after adding an action to a second trigger."); } catch (InvalidOperationException) { } // now try the same, properly unhooking before reparenting action = new StubAction(); trigger1 = new StubTrigger(); trigger2 = new StubTrigger(); trigger1.Actions.Add(action); trigger1.Actions.Remove(action); trigger2.Actions.Add(action); Assert.AreEqual(((IAttachedObject)action).AssociatedObject, trigger2.HostObject, "action.AssociatedObject == trigger2.Host"); Assert.AreEqual(trigger2.Actions.Count, 1, "trigger2.Actions.Count == 1"); } } }
39.059829
177
0.626039
[ "MIT" ]
Bhaskers-Blu-Org2/XamlBehaviorsWpf
Test/UnitTests/ActionTest.cs
4,572
C#
using System.Linq; using BenchmarkDotNet.Running; using BenchmarkMockNet.Benchmarks; namespace BenchmarkMockNet { public static class Program { private static readonly BenchmarkSwitcher Runner = new(new[] { typeof(Construction), typeof(Callback), typeof(EmptyMethod), typeof(EmptyReturn), typeof(Return), typeof(Verify), typeof(OneParameter) }); public static void Main(string[] args) { if (args.Any(a => a.Contains("filter"))) Runner.Run(args); else Runner.RunAll(); } } }
18.75
62
0.693333
[ "MIT" ]
JasonBock/BenchmarkMockNet
BenchmarkMockNet/Program.cs
525
C#
using System.Collections.Generic; using System.Runtime.CompilerServices; using FastMember; [assembly: InternalsVisibleTo("desee.Tests")] namespace desee.EntityObjects { public class TypeMemberIndex : SortedDictionary<string, Member> { } }
20.076923
67
0.747126
[ "MIT" ]
rvegajr/desee
Src/desee.EntityObjects/Classes/TypeMemberIndex.cs
261
C#
namespace RedCorners.Forms.GoogleMaps { public enum MapType { Street, Satellite, Hybrid, Terrain, None } }
15.363636
39
0.491124
[ "MIT" ]
saeedafshari/RedCorners.Forms.GoogleMaps
RedCorners.Forms.GoogleMaps/RedCorners.Forms.GoogleMaps.Shared/MapType.cs
171
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Bonrix_App_Store.Admin { public partial class Master { /// <summary> /// rt_style_components control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlLink rt_style_components; /// <summary> /// head control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.ContentPlaceHolder head; /// <summary> /// ScriptManager1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.ScriptManager ScriptManager1; /// <summary> /// profile_img control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlImage profile_img; /// <summary> /// B2CNameRight control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl B2CNameRight; /// <summary> /// profile_img_left control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlImage profile_img_left; /// <summary> /// B2CNameLeft control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl B2CNameLeft; /// <summary> /// ContentPlaceHolder1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.ContentPlaceHolder ContentPlaceHolder1; } }
35.488636
91
0.544669
[ "Unlicense" ]
bonrix/AndroidAppStore
Bonrix App Store/Admin/Master.Master.designer.cs
3,125
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.MixedReality.Toolkit.Utilities; using Unity.Profiling; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Teleport { [RequireComponent(typeof(ParabolaPhysicalLineDataProvider))] [AddComponentMenu("Scripts/MRTK/SDK/ParabolicTeleportPointer")] public class ParabolicTeleportPointer : TeleportPointer { [SerializeField] private float minParabolaVelocity = 1f; [SerializeField] private float maxParabolaVelocity = 5f; [SerializeField] private float minDistanceModifier = 1f; [SerializeField] private float maxDistanceModifier = 5f; [SerializeField] private ParabolaPhysicalLineDataProvider parabolicLineData; #region MonoBehaviour Implementation protected override void OnEnable() { base.OnEnable(); EnsureSetup(); } private void EnsureSetup() { if (parabolicLineData == null) { parabolicLineData = gameObject.GetComponent<ParabolaPhysicalLineDataProvider>(); } if (parabolicLineData.LineTransform == transform) { Debug.LogWarning("Missing Parabolic line helper.\nThe Parabolic Teleport Pointer requires an empty GameObject child for calculating the parabola arc. Creating one now."); var pointerHelper = transform.Find("ParabolicLinePointerHelper"); if (pointerHelper == null) { pointerHelper = new GameObject("ParabolicLinePointerHelper").transform; pointerHelper.transform.SetParent(transform); } pointerHelper.transform.localPosition = Vector3.zero; parabolicLineData.LineTransform = pointerHelper.transform; } } #endregion MonoBehaviour Implementation #region IMixedRealityPointer Implementation private static readonly ProfilerMarker OnPreSceneQueryPerfMarker = new ProfilerMarker("[MRTK] ParabolicTeleportPointer.OnPreSceneQuery"); private StabilizedRay stabilizedRay = new StabilizedRay(0.5f); private Ray stabilizationRay = new Ray(); /// <inheritdoc /> public override void OnPreSceneQuery() { using (OnPreSceneQueryPerfMarker.Auto()) { stabilizationRay.origin = transform.position; stabilizationRay.direction = transform.forward; stabilizedRay.AddSample(stabilizationRay); parabolicLineData.LineTransform.rotation = Quaternion.identity; parabolicLineData.Direction = stabilizedRay.StabilizedDirection; // when pointing straight up, angle should be close to 1. // when pointing straight down, angle should be close to -1. // when pointing straight forward in any direction, upDot should be 0. var angle = (Vector3.Angle(stabilizedRay.StabilizedDirection, Vector3.down) - 90.0f) / 90.0f; var sqr_angle = angle * angle; var velocity = minParabolaVelocity; var distance = minDistanceModifier; // If we're pointing below the horizon, always use the minimum modifiers. // We use square angle so that the velocity change is less noticeable the closer the teleport point // is to the user if (sqr_angle > 0) { velocity = Mathf.Lerp(minParabolaVelocity, maxParabolaVelocity, sqr_angle); distance = Mathf.Lerp(minDistanceModifier, maxDistanceModifier, sqr_angle); } parabolicLineData.Velocity = velocity; parabolicLineData.DistanceMultiplier = distance; base.OnPreSceneQuery(); } } #endregion IMixedRealityPointer Implementation } }
37.431193
186
0.627696
[ "MIT" ]
AdsyArena/ARbot
Assets/MRTK/SDK/Features/UX/Scripts/Pointers/ParabolicTeleportPointer.cs
4,082
C#
/* package main import "fmt" const Pi = 3.14 func main() { const World = "世界" fmt.Println("Hello", World) fmt.Println("Happy", Pi, "Day") const Truth = true fmt.Println("Go rules?", Truth) } */ #region source using fmt = go.fmt_package; static class main_package { // Conversion will need to determine "inferred" type for members const double Pi = 3.14; static void Main() { const string World = "世界"; fmt.Println("Hello ", World); fmt.Println("Happy", Pi, "Day"); const bool Truth = true; fmt.Println("Go rules?", Truth); } } #endregion // Note that getting Chinese characters on console output requires a font capable // of displaying Unicode characters, e.g., MS Gothic, plus UTF8 encoding: //System.Console.OutputEncoding = Encoding.UTF8;
21.763158
81
0.64208
[ "MIT" ]
GridProtectionAlliance/go2cs
src/Examples/Manual Tour of Go Conversions/basics/constants/main_package.cs
837
C#
namespace QuizHut.Services.Data.Tests { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using QuizHut.Data.Models; using QuizHut.Services.Categories; using QuizHut.Web.ViewModels.Categories; using QuizHut.Web.ViewModels.Quizzes; using Xunit; public class CategoriesServiceTests : BaseServiceTests { private ICategoriesService Service => this.ServiceProvider.GetRequiredService<ICategoriesService>(); [Fact] public async Task GetByIdAsyncShouldReturnCorrectModel() { var creatorId = await this.CreateUserAsync(); var category = await this.CreateCategoryAsync("Category 1", creatorId); var model = new CategoryWithQuizzesViewModel() { Id = category.Id, Name = category.Name, Error = false, Quizzes = new List<QuizAssignViewModel>(), }; var resultModel = await this.Service.GetByIdAsync<CategoryWithQuizzesViewModel>(category.Id); Assert.Equal(model.Id, resultModel.Id); Assert.Equal(model.Name, resultModel.Name); Assert.Equal(model.Error, resultModel.Error); Assert.Equal(model.Quizzes.Count, resultModel.Quizzes.Count); } [Fact] public async Task GetAllPerPageShouldReturnCorrectModelCollection() { var creatorId = Guid.NewGuid().ToString(); var firstCategory = await this.CreateCategoryAsync("Category 1", creatorId); var secondCategory = await this.CreateCategoryAsync("Category 2", creatorId); var firstModel = new CategoryViewModel() { Name = firstCategory.Name, Id = firstCategory.Id, QuizzesCount = firstCategory.Quizzes.Count().ToString(), CreatedOn = firstCategory.CreatedOn, }; var secondModel = new CategoryViewModel() { Name = secondCategory.Name, Id = secondCategory.Id, QuizzesCount = secondCategory.Quizzes.Count().ToString(), CreatedOn = secondCategory.CreatedOn, }; var resultModelCollection = await this.Service.GetAllPerPage<CategoryViewModel>(1, 2, creatorId); Assert.Equal(firstModel.Id, resultModelCollection.Last().Id); Assert.Equal(firstModel.Name, resultModelCollection.Last().Name); Assert.Equal(firstModel.QuizzesCount, resultModelCollection.Last().QuizzesCount); Assert.Equal(firstModel.CreatedOn, resultModelCollection.Last().CreatedOn); Assert.Equal(secondModel.Id, resultModelCollection.First().Id); Assert.Equal(secondModel.Name, resultModelCollection.First().Name); Assert.Equal(secondModel.QuizzesCount, resultModelCollection.First().QuizzesCount); Assert.Equal(secondModel.CreatedOn, resultModelCollection.First().CreatedOn); Assert.Equal(2, resultModelCollection.Count()); } [Fact] public async Task GetAllByCreatorIdAsyncShouldReturnCorrectModelCollection() { var creatorId = Guid.NewGuid().ToString(); var firstCategory = await this.CreateCategoryAsync("Category 1", creatorId); var secondCategory = await this.CreateCategoryAsync("Category 2", creatorId); var firstModel = new CategoryViewModel() { Name = firstCategory.Name, Id = firstCategory.Id, QuizzesCount = firstCategory.Quizzes.Count().ToString(), CreatedOn = firstCategory.CreatedOn, }; var secondModel = new CategoryViewModel() { Name = secondCategory.Name, Id = secondCategory.Id, QuizzesCount = secondCategory.Quizzes.Count().ToString(), CreatedOn = secondCategory.CreatedOn, }; var resultModelCollection = await this.Service.GetAllPerPage<CategoryViewModel>(1, 2, creatorId); Assert.Equal(firstModel.Id, resultModelCollection.Last().Id); Assert.Equal(firstModel.Name, resultModelCollection.Last().Name); Assert.Equal(firstModel.QuizzesCount, resultModelCollection.Last().QuizzesCount); Assert.Equal(firstModel.CreatedOn, resultModelCollection.Last().CreatedOn); Assert.Equal(secondModel.Id, resultModelCollection.First().Id); Assert.Equal(secondModel.Name, resultModelCollection.First().Name); Assert.Equal(secondModel.QuizzesCount, resultModelCollection.First().QuizzesCount); Assert.Equal(secondModel.CreatedOn, resultModelCollection.First().CreatedOn); Assert.Equal(2, resultModelCollection.Count()); } [Fact] public async Task GetAllCategoriesCountShouldReturnCorrectCount() { var creatorId = Guid.NewGuid().ToString(); await this.CreateCategoryAsync("first category", creatorId); var categoriesCount = await this.Service.GetAllCategoriesCountAsync(creatorId); Assert.Equal(1, categoriesCount); } [Fact] public async Task CreateCategoryAsyncShouldCreateNewCategoryInDb() { var creatorId = Guid.NewGuid().ToString(); await this.CreateCategoryAsync(creatorId); var newCategoryId = await this.Service.CreateCategoryAsync(name: "Second category", creatorId); var categoriesCount = this.DbContext.Categories.ToArray().Count(); var newCategory = await this.DbContext.Categories.FirstOrDefaultAsync(x => x.Id == newCategoryId); Assert.Equal(2, categoriesCount); Assert.Equal("Second category", newCategory.Name); Assert.Equal(creatorId, newCategory.CreatorId); } [Fact] public async Task GetAllPerPageShouldSkipCorrectly() { var creatorId = await this.CreateUserAsync(); var firstCategory = await this.CreateCategoryAsync("Category 1", creatorId); await this.CreateCategoryAsync("Category 2", creatorId); var firstModel = new CategoryViewModel() { Name = firstCategory.Name, Id = firstCategory.Id, QuizzesCount = firstCategory.Quizzes.Count().ToString(), CreatedOn = firstCategory.CreatedOn, }; var resultModelCollection = await this.Service.GetAllPerPage<CategoryViewModel>(2, 1, creatorId); Assert.Single(resultModelCollection); Assert.Equal(firstModel.Id, resultModelCollection.Last().Id); Assert.Equal(firstModel.Name, resultModelCollection.Last().Name); Assert.Equal(firstModel.QuizzesCount, resultModelCollection.Last().QuizzesCount); Assert.Equal(firstModel.CreatedOn, resultModelCollection.Last().CreatedOn); } [Theory] [InlineData(1, 5)] [InlineData(1, 1000)] public async Task GetAllPerPageShouldTakeCorrectCountPerPage(int page, int countPerPage) { var creatorId = await this.CreateUserAsync(); for (int i = 0; i < countPerPage * 2; i++) { await this.CreateCategoryAsync($"Category {i}", creatorId); } var resultModelCollection = await this.Service.GetAllPerPage<CategoryViewModel>(page, countPerPage, creatorId); Assert.Equal(countPerPage, resultModelCollection.Count()); } [Fact] public async Task UpdateNameAsyncShouldUpdateCorrectly() { var category = await this.CreateCategoryAsync("Category"); await this.Service.UpdateNameAsync(category.Id, "First test category"); var updatedCategory = await this.DbContext.Categories.FirstOrDefaultAsync(x => x.Id == category.Id); Assert.Equal("First test category", updatedCategory.Name); } [Fact] public async Task DeleteAsyncShouldDeleteCorrectly() { var firstCategory = await this.CreateCategoryAsync("Category 1"); await this.Service.DeleteAsync(firstCategory.Id); var categoriesCount = this.DbContext.Categories.Where(x => !x.IsDeleted).ToArray().Count(); var category = await this.DbContext.Categories.FindAsync(firstCategory.Id); Assert.Equal(0, categoriesCount); Assert.True(category.IsDeleted); } [Fact] public async Task AssignQuizzesToCategoryAsyncShouldAssignQuizzesCorrectly() { var firstQuizId = this.CreateQuiz(name: "First quiz"); var secondQuizId = this.CreateQuiz(name: "Second quiz"); var firstCategory = await this.CreateCategoryAsync("Category 1"); var quizzesIdList = new List<string>() { firstQuizId, secondQuizId }; await this.Service.AssignQuizzesToCategoryAsync(firstCategory.Id, quizzesIdList); var categoryQuizzesIds = await this.DbContext .Categories .Where(x => x.Id == firstCategory.Id) .Select(x => x.Quizzes.Select(x => x.Id)) .FirstOrDefaultAsync(); Assert.Equal(2, categoryQuizzesIds.Count()); Assert.Contains(firstQuizId, categoryQuizzesIds); Assert.Contains(secondQuizId, categoryQuizzesIds); } [Fact] public async Task DeleteQuizFromCategoryAsyncShouldUnAssignQuizCorrectly() { var firstCategory = await this.CreateCategoryAsync("Category 2"); var quizId = this.CreateQuiz(name: "quiz"); await this.AssignQuizToFirstCategoryAsync(quizId); await this.Service.DeleteQuizFromCategoryAsync(firstCategory.Id, quizId); var categoryQuizzesIds = await this.DbContext .Categories .Where(x => x.Id == firstCategory.Id) .Select(x => x.Quizzes.Select(x => x.Id)) .FirstOrDefaultAsync(); var quiz = await this.DbContext.Quizzes.FirstOrDefaultAsync(x => x.Id == quizId); Assert.Empty(categoryQuizzesIds); Assert.Null(quiz.CategoryId); } private async Task AssignQuizToFirstCategoryAsync(string quizId) { var category = await this.CreateCategoryAsync("Category"); var quiz = await this.DbContext.Quizzes.FirstOrDefaultAsync(x => x.Id == quizId); category.Quizzes.Add(quiz); await this.DbContext.SaveChangesAsync(); this.DbContext.Entry<Category>(category).State = EntityState.Detached; this.DbContext.Entry<Quiz>(quiz).State = EntityState.Detached; } private async Task<Category> CreateCategoryAsync(string name, string creatorId = null) { if (creatorId == null) { creatorId = Guid.NewGuid().ToString(); } var category = new Category() { Name = name, CreatorId = creatorId, }; await this.DbContext.Categories.AddAsync(category); await this.DbContext.SaveChangesAsync(); this.DbContext.Entry<Category>(category).State = EntityState.Detached; return category; } private string CreateQuiz(string name) { var creatorId = Guid.NewGuid().ToString(); var quiz = new Quiz() { Name = name, CreatorId = creatorId, }; this.DbContext.Quizzes.Add(quiz); this.DbContext.SaveChanges(); this.DbContext.Entry<Quiz>(quiz).State = EntityState.Detached; return quiz.Id; } private async Task<string> CreateUserAsync() { var user = new ApplicationUser() { FirstName = "First Name", LastName = "Last Name", Email = "email@email.com", UserName = "email@email.com", }; await this.DbContext.Users.AddAsync(user); await this.DbContext.SaveChangesAsync(); this.DbContext.Entry<ApplicationUser>(user).State = EntityState.Detached; return user.Id; } } }
42.312081
123
0.616623
[ "MIT" ]
miraDask/QuizHut
QuizHut/Tests/QuizHut.Services.Data.Tests/CategoriesServiceTests.cs
12,611
C#
using System.Collections.Generic; using System.Collections.ObjectModel; namespace NewHost.Areas.HelpPage.ModelDescriptions { public class EnumTypeModelDescription : ModelDescription { public EnumTypeModelDescription() { Values = new Collection<EnumValueDescription>(); } public Collection<EnumValueDescription> Values { get; private set; } } }
26.733333
76
0.705736
[ "MIT" ]
Nongzhsh/WexFlow
NewHost/Areas/HelpPage/ModelDescriptions/EnumTypeModelDescription.cs
401
C#
using System; using System.IO; namespace SaveScumAgent.DirectoryWatcher { public interface IDirectoryWatcher : IDisposable { bool Enabled { get; set; } event EventHandler<DirectoryWatcherEventArgs> DirectoryChangeDetected; event EventHandler<ErrorEventArgs> DirectoryWatchError; } }
26.666667
78
0.740625
[ "MIT" ]
SaveScum/SaveScumAgent
SaveScumAgent.DirectoryWatcher/IDirectoryWatcher.cs
322
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using System.Net; namespace Admin { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseMiddleware(typeof(ErrorHandlingMiddleware)); app.UseMvc(); } } //http://stackoverflow.com/a/38935583/697126 public class ErrorHandlingMiddleware { private readonly RequestDelegate next; public ErrorHandlingMiddleware(RequestDelegate next) { this.next = next; } public async Task Invoke(HttpContext context /* other scoped dependencies */) { try { await next(context); } catch (Exception ex) { await HandleExceptionAsync(context, ex); } } private static Task HandleExceptionAsync(HttpContext context, Exception exception) { var code = HttpStatusCode.InternalServerError; // 500 if unexpected var result = JsonConvert.SerializeObject(new { error = exception.Message }); context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)code; return context.Response.WriteAsync(result); } } }
32.654321
109
0.638941
[ "MIT" ]
flyingoverclouds/ServiceFabricPubSub
src/ServiceFabricPubSub/Admin/Startup.cs
2,647
C#
using System; using System.Reflection; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using MelonLoader; namespace HouseLights { class HouseLightsUtils { internal static object InvokePrivMethod(object inst, string name, params object[] arguments) { MethodInfo method = inst.GetType().GetMethod(name, BindingFlags.Instance | BindingFlags.NonPublic); if (!method.Equals(null)) { return method.Invoke(inst, arguments); } return null; } internal static void SetPrivObj(object inst, string name, object value, Type type) { FieldInfo field = inst.GetType().GetField(name, BindingFlags.Instance | BindingFlags.NonPublic); if (!field.Equals(null) && field.FieldType.Equals(type)) { field.SetValue(inst, value); } } internal static void SetPrivFloat(object inst, string name, float value) { SetPrivObj(inst, name, value, typeof(float)); } internal static List<GameObject> GetRootObjects() { List<GameObject> rootObj = new List<GameObject>(); for (int i = 0; i < UnityEngine.SceneManagement.SceneManager.sceneCount; i++) { Scene scene = UnityEngine.SceneManagement.SceneManager.GetSceneAt(i); GameObject[] sceneObj = scene.GetRootGameObjects(); foreach (GameObject obj in sceneObj) { rootObj.Add(obj); } } return rootObj; } internal static void GetChildrenWithName(GameObject obj, string name, List<GameObject> result) { if (obj.transform.childCount > 0) { for (int i = 0; i < obj.transform.childCount; i++) { GameObject child = obj.transform.GetChild(i).gameObject; if (child.name.ToLower().Contains(name)) { result.Add(child); } GetChildrenWithName(child, name, result); } } } } }
30.783784
111
0.543898
[ "MIT" ]
ttr/tld-house-lights
src/HouseLightsUtils.cs
2,280
C#
using Abp.AspNetCore.Mvc.Controllers; using Abp.IdentityFramework; using Microsoft.AspNetCore.Identity; namespace IdentityServervNextDemo.Controllers { public abstract class IdentityServervNextDemoControllerBase: AbpController { protected IdentityServervNextDemoControllerBase() { LocalizationSourceName = IdentityServervNextDemoConsts.LocalizationSourceName; } protected void CheckErrors(IdentityResult identityResult) { identityResult.CheckErrors(LocalizationManager); } } }
28.15
90
0.738899
[ "MIT" ]
OzBob/aspnetboilerplate-samples
IdentityServervNextDemo/aspnet-core/src/IdentityServervNextDemo.Web.Core/Controllers/IdentityServervNextDemoControllerBase.cs
563
C#
using System; using System.Threading.Tasks; using ClusterClient.Chaos.Common; using Vostok.Clusterclient.Core.Model; using Vostok.Clusterclient.Core.Modules; namespace ClusterClient.Chaos.Latency { internal class LatencyModule : IRequestModule { private readonly Func<TimeSpan> latencyProvider; private readonly Func<double> rateProvider; private ILatencyPerformer latencyPerformer; private readonly RateManager rateManager; public LatencyModule(ILatencyPerformer latencyPerformer, RateManager rateManager, Func<TimeSpan> latencyProvider, Func<double> rateProvider) { this.latencyProvider = latencyProvider; this.rateProvider = rateProvider; this.latencyPerformer = latencyPerformer; this.rateManager = rateManager; } public async Task<ClusterResult> ExecuteAsync(IRequestContext context, Func<IRequestContext, Task<ClusterResult>> next) { var latency = latencyProvider(); var rate = rateProvider(); var remainingTimeBudget = context.Budget.Remaining; if (rateManager.ShouldInjectWithRate(rate)) { if (latency > remainingTimeBudget) { await latencyPerformer.PerformLatencyAsync(remainingTimeBudget, context.CancellationToken).ConfigureAwait(false); return new ClusterResult(ClusterResultStatus.TimeExpired, new ReplicaResult[] {}, null, context.Request); } await latencyPerformer.PerformLatencyAsync(latency, context.CancellationToken).ConfigureAwait(false); } return await next(context).ConfigureAwait(false); } } }
41.511628
148
0.663305
[ "MIT" ]
shumantt/ClusterClient.Chaos
ClusterClient.Chaos/Latency/LatencyModule.cs
1,785
C#
using System.Collections.Generic; using System.Linq; using System.Text.Json; namespace ChunkedDataTransfer { internal class PackageCreator { private readonly int _chunkSize; internal PackageCreator(int chunkSize) { this._chunkSize = chunkSize; } internal Package CreatePackage<TData>(TData data) { var (zippedDataStrToSend, dataType) = ConvertHelper.GetZippedDataStrToSend(data); var package = CreatePackageFromString(zippedDataStrToSend, dataType); return package; } private Package CreatePackageFromString(string data, string dataType) { var dataHash = HashHelper.GetStringHash(data); string objectID = dataHash; var dataParts = SplitHelper.SplitStringToChunks(data, this._chunkSize).ToArray(); var dataPartsMessages = CreateDataPartsMessages(dataParts, objectID); var packageInfoMessage = CreatePackageInfoMessage(dataPartsMessages, dataType, dataHash, objectID); var package = new Package { PackageInfoMessage = packageInfoMessage, DataPartsMessages = dataPartsMessages, }; return package; } private static string CreatePackageInfoMessage( string[] dataParts, string dataType, string dataHash, string objectID) { var packageInfoMessage = new PackageInfoMessage { MsgIntegrity = Constants.PackageInfoMessageIntegrityCheckID, NumberOfParts = dataParts.Length, DataType = dataType, DataHash = dataHash, ObjectID = objectID, }; var packageInfoMessageStr = JsonSerializer.Serialize(packageInfoMessage); return packageInfoMessageStr; } private static string[] CreateDataPartsMessages(string[] dataParts, string objectID) { var dataPartsMessages = new List<string>(); for (int i = 0; i < dataParts.Length; i++) { var dataPartMessage = new DataPartMessage { MsgIntegrity = Constants.DataPartMessageIntegrityCheckID, PartID = i, Data = dataParts[i], DataHash = HashHelper.GetStringHash(dataParts[i]), ObjectID = objectID, }; var dataPartMessageStr = JsonSerializer.Serialize(dataPartMessage); dataPartsMessages.Add(dataPartMessageStr); } return dataPartsMessages.ToArray(); } } }
31.929412
111
0.593589
[ "MIT" ]
Johnnyborov/QRCopyPaste
Lib/ChunkedDataTransfer/Sender/PackageCreator.cs
2,716
C#
//------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. // All rights reserved. // // This code is licensed under the MIT License. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Security.Cryptography; using Microsoft.IdentityModel.Logging; namespace Microsoft.IdentityModel.Tokens { /// <summary> /// Defines the default set of algorithms this library supports /// </summary> internal static class SupportedAlgorithms { internal static readonly ICollection<string> EcdsaSigningAlgorithms = new Collection<string> { SecurityAlgorithms.EcdsaSha256, SecurityAlgorithms.EcdsaSha256Signature, SecurityAlgorithms.EcdsaSha384, SecurityAlgorithms.EcdsaSha384Signature, SecurityAlgorithms.EcdsaSha512, SecurityAlgorithms.EcdsaSha512Signature }; internal static readonly ICollection<string> HashAlgorithms = new Collection<string> { SecurityAlgorithms.Sha256, SecurityAlgorithms.Sha256Digest, SecurityAlgorithms.Sha384, SecurityAlgorithms.Sha384Digest, SecurityAlgorithms.Sha512, SecurityAlgorithms.Sha512Digest }; // doubles as RsaKeyWrapAlgorithms internal static readonly ICollection<string> RsaEncryptionAlgorithms = new Collection<string> { SecurityAlgorithms.RsaOAEP, SecurityAlgorithms.RsaPKCS1, SecurityAlgorithms.RsaOaepKeyWrap }; internal static readonly ICollection<string> RsaSigningAlgorithms = new Collection<string> { SecurityAlgorithms.RsaSha256, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.RsaSha384, SecurityAlgorithms.RsaSha384Signature, SecurityAlgorithms.RsaSha512, SecurityAlgorithms.RsaSha512Signature }; internal static readonly ICollection<string> RsaPssSigningAlgorithms = new Collection<string> { SecurityAlgorithms.RsaSsaPssSha256, SecurityAlgorithms.RsaSsaPssSha256Signature, SecurityAlgorithms.RsaSsaPssSha384, SecurityAlgorithms.RsaSsaPssSha384Signature, SecurityAlgorithms.RsaSsaPssSha512, SecurityAlgorithms.RsaSsaPssSha512Signature }; internal static readonly ICollection<string> SymmetricEncryptionAlgorithms = new Collection<string> { SecurityAlgorithms.Aes128CbcHmacSha256, SecurityAlgorithms.Aes192CbcHmacSha384, SecurityAlgorithms.Aes256CbcHmacSha512 }; internal static readonly ICollection<string> SymmetricKeyWrapAlgorithms = new Collection<string> { SecurityAlgorithms.Aes128KW, SecurityAlgorithms.Aes128KeyWrap, SecurityAlgorithms.Aes256KW, SecurityAlgorithms.Aes256KeyWrap }; internal static readonly ICollection<string> SymmetricSigningAlgorithms = new Collection<string> { SecurityAlgorithms.HmacSha256, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.HmacSha384, SecurityAlgorithms.HmacSha384Signature, SecurityAlgorithms.HmacSha512, SecurityAlgorithms.HmacSha512Signature }; #if NET461 || NET472 || NETSTANDARD2_0 /// <summary> /// Creating a Signature requires the use of a <see cref="HashAlgorithm"/>. /// This method returns the <see cref="HashAlgorithmName"/> /// that describes the <see cref="HashAlgorithm"/>to use when generating a Signature. /// </summary> /// <param name="algorithm">The SignatureAlgorithm in use.</param> /// <returns>The <see cref="HashAlgorithmName"/> to use.</returns> /// <exception cref="ArgumentNullException">if <paramref name="algorithm"/> is null or whitespace.</exception> /// <exception cref="ArgumentOutOfRangeException">if <paramref name="algorithm"/> is not supported.</exception> internal static HashAlgorithmName GetHashAlgorithmName(string algorithm) { if (string.IsNullOrWhiteSpace(algorithm)) throw LogHelper.LogArgumentNullException(nameof(algorithm)); switch (algorithm) { case SecurityAlgorithms.EcdsaSha256: case SecurityAlgorithms.EcdsaSha256Signature: case SecurityAlgorithms.RsaSha256: case SecurityAlgorithms.RsaSha256Signature: case SecurityAlgorithms.RsaSsaPssSha256: case SecurityAlgorithms.RsaSsaPssSha256Signature: return HashAlgorithmName.SHA256; case SecurityAlgorithms.EcdsaSha384: case SecurityAlgorithms.EcdsaSha384Signature: case SecurityAlgorithms.RsaSha384: case SecurityAlgorithms.RsaSha384Signature: case SecurityAlgorithms.RsaSsaPssSha384: case SecurityAlgorithms.RsaSsaPssSha384Signature: return HashAlgorithmName.SHA384; case SecurityAlgorithms.EcdsaSha512: case SecurityAlgorithms.EcdsaSha512Signature: case SecurityAlgorithms.RsaSha512: case SecurityAlgorithms.RsaSha512Signature: case SecurityAlgorithms.RsaSsaPssSha512: case SecurityAlgorithms.RsaSsaPssSha512Signature: return HashAlgorithmName.SHA512; } throw LogHelper.LogExceptionMessage(new ArgumentOutOfRangeException(nameof(algorithm), LogHelper.FormatInvariant(LogMessages.IDX10652, algorithm))); } #endif /// <summary> /// Creating a Signature requires the use of a <see cref="HashAlgorithm"/>. /// This method returns the HashAlgorithm string that is associated with a SignatureAlgorithm. /// </summary> /// <param name="algorithm">The SignatureAlgorithm of interest.</param> /// <exception cref="ArgumentNullException">if <paramref name="algorithm"/>is null or whitespace.</exception> /// <exception cref="ArgumentException">if <paramref name="algorithm"/> is not supported.</exception> internal static string GetDigestFromSignatureAlgorithm(string algorithm) { if (string.IsNullOrWhiteSpace(algorithm)) throw LogHelper.LogArgumentNullException(nameof(algorithm)); switch (algorithm) { case SecurityAlgorithms.EcdsaSha256: case SecurityAlgorithms.HmacSha256: case SecurityAlgorithms.RsaSha256: case SecurityAlgorithms.RsaSsaPssSha256: return SecurityAlgorithms.Sha256; case SecurityAlgorithms.EcdsaSha256Signature: case SecurityAlgorithms.HmacSha256Signature: case SecurityAlgorithms.RsaSha256Signature: case SecurityAlgorithms.RsaSsaPssSha256Signature: return SecurityAlgorithms.Sha256Digest; case SecurityAlgorithms.EcdsaSha384: case SecurityAlgorithms.HmacSha384: case SecurityAlgorithms.RsaSha384: case SecurityAlgorithms.RsaSsaPssSha384: return SecurityAlgorithms.Sha384; case SecurityAlgorithms.EcdsaSha384Signature: case SecurityAlgorithms.HmacSha384Signature: case SecurityAlgorithms.RsaSha384Signature: case SecurityAlgorithms.RsaSsaPssSha384Signature: return SecurityAlgorithms.Sha384Digest; case SecurityAlgorithms.EcdsaSha512: case SecurityAlgorithms.HmacSha512: case SecurityAlgorithms.RsaSha512: case SecurityAlgorithms.RsaSsaPssSha512: return SecurityAlgorithms.Sha512; case SecurityAlgorithms.EcdsaSha512Signature: case SecurityAlgorithms.HmacSha512Signature: case SecurityAlgorithms.RsaSha512Signature: case SecurityAlgorithms.RsaSsaPssSha512Signature: return SecurityAlgorithms.Sha512Digest; } throw LogHelper.LogExceptionMessage(new ArgumentException(LogHelper.FormatInvariant(LogMessages.IDX10652, algorithm), nameof(algorithm))); } /// <summary> /// Checks if an 'algorithm, key' pair is supported. /// </summary> /// <param name="algorithm">the algorithm to check.</param> /// <param name="key">the <see cref="SecurityKey"/>.</param> /// <returns>true if 'algorithm, key' pair is supported.</returns> public static bool IsSupportedAlgorithm(string algorithm, SecurityKey key) { if (key as RsaSecurityKey != null) return IsSupportedRsaAlgorithm(algorithm, key); if (key is X509SecurityKey x509Key) { // only RSA keys are supported if (x509Key.PublicKey as RSA == null) return false; return IsSupportedRsaAlgorithm(algorithm, key); } if (key is JsonWebKey jsonWebKey) { if (JsonWebAlgorithmsKeyTypes.RSA.Equals(jsonWebKey.Kty, StringComparison.Ordinal)) return IsSupportedRsaAlgorithm(algorithm, key); else if (JsonWebAlgorithmsKeyTypes.EllipticCurve.Equals(jsonWebKey.Kty, StringComparison.Ordinal)) return IsSupportedEcdsaAlgorithm(algorithm); else if (JsonWebAlgorithmsKeyTypes.Octet.Equals(jsonWebKey.Kty, StringComparison.Ordinal)) return IsSupportedSymmetricAlgorithm(algorithm); return false; } if (key is ECDsaSecurityKey) return IsSupportedEcdsaAlgorithm(algorithm); if (key as SymmetricSecurityKey != null) return IsSupportedSymmetricAlgorithm(algorithm); return false; } internal static bool IsSupportedAuthenticatedEncryptionAlgorithm(string algorithm, SecurityKey key) { if (key == null) return false; if (string.IsNullOrEmpty(algorithm)) return false; if (!(algorithm.Equals(SecurityAlgorithms.Aes128CbcHmacSha256, StringComparison.Ordinal) || algorithm.Equals(SecurityAlgorithms.Aes192CbcHmacSha384, StringComparison.Ordinal) || algorithm.Equals(SecurityAlgorithms.Aes256CbcHmacSha512, StringComparison.Ordinal))) return false; if (key is SymmetricSecurityKey) return true; if (key is JsonWebKey jsonWebKey) return (jsonWebKey.K != null && jsonWebKey.Kty == JsonWebAlgorithmsKeyTypes.Octet); return false; } private static bool IsSupportedEcdsaAlgorithm(string algorithm) { return EcdsaSigningAlgorithms.Contains(algorithm); } internal static bool IsSupportedHashAlgorithm(string algorithm) { return HashAlgorithms.Contains(algorithm); } internal static bool IsSupportedRsaKeyWrap(string algorithm, SecurityKey key) { if (key == null) return false; if (string.IsNullOrEmpty(algorithm)) return false; if (!RsaEncryptionAlgorithms.Contains(algorithm)) return false; if (key is RsaSecurityKey || key is X509SecurityKey || (key is JsonWebKey rsaJsonWebKey && rsaJsonWebKey.Kty == JsonWebAlgorithmsKeyTypes.RSA)) return key.KeySize >= 2048; return false; } internal static bool IsSupportedSymmetricKeyWrap(string algorithm, SecurityKey key) { if (key == null) return false; if (string.IsNullOrEmpty(algorithm)) return false; if (!SymmetricKeyWrapAlgorithms.Contains(algorithm)) return false; return (key is SymmetricSecurityKey || (key is JsonWebKey jsonWebKey && jsonWebKey.Kty == JsonWebAlgorithmsKeyTypes.Octet)); } internal static bool IsSupportedRsaAlgorithm(string algorithm, SecurityKey key) { return RsaSigningAlgorithms.Contains(algorithm) || RsaEncryptionAlgorithms.Contains(algorithm) || (RsaPssSigningAlgorithms.Contains(algorithm) && IsSupportedRsaPss(key)); } private static bool IsSupportedRsaPss(SecurityKey key) { #if NET45 // RSA-PSS is not available on .NET 4.5 LogHelper.LogInformation(LogMessages.IDX10692); return false; #elif NET461 || NET472 || NETSTANDARD2_0 // RSACryptoServiceProvider doesn't support RSA-PSS if (key is RsaSecurityKey rsa && rsa.Rsa is RSACryptoServiceProvider) { LogHelper.LogInformation(LogMessages.IDX10693); return false; } else if (key is X509SecurityKey x509SecurityKey && x509SecurityKey.PublicKey is RSACryptoServiceProvider) { LogHelper.LogInformation(LogMessages.IDX10693); return false; } else { return true; } #else return true; #endif } internal static bool IsSupportedSymmetricAlgorithm(string algorithm) { return SymmetricEncryptionAlgorithms.Contains(algorithm) || SymmetricKeyWrapAlgorithms.Contains(algorithm) || SymmetricSigningAlgorithms.Contains(algorithm); } } }
42.105556
160
0.638673
[ "MIT" ]
RufusJWB/azure-activedirectory-identitymodel-extensions-for-dotnet
src/Microsoft.IdentityModel.Tokens/SupportedAlgorithms.cs
15,158
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code++. Version 5.2.97.0. www.xsd2code.com // </auto-generated> // ------------------------------------------------------------------------------ #pragma warning disable namespace MsProjectMapper { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Runtime.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.Xml; using System.IO; using System.Text; using System.ComponentModel.DataAnnotations; using System.Collections.Generic; [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.8.4084.0")] [Serializable] [XmlTypeAttribute(AnonymousType=true, Namespace="http://schemas.microsoft.com/project")] public enum ProjectTaskFixedCostAccrual { [XmlEnumAttribute("1")] Start, [XmlEnumAttribute("2")] Prorated, [XmlEnumAttribute("3")] End, } } #pragma warning restore
28.222222
88
0.640748
[ "MIT" ]
dodbrian/Sandbox
MsProjectMapper/Domain/ProjectTaskFixedCostAccrual.cs
1,016
C#
using Microsoft.Graph; using Office365Groups.Library.Helpers; using Office365Groups.Library.Models; using OfficeDevPnP.Core.Entities; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.WebJobs.Host; namespace Office365Groups.Library { public class OfficeGroupUtility { public static TraceWriter Logger; private const int defaultRetryCount = 3; private const int defaultDelay = 500; private static WebClient wc = new WebClient(); /// <summary> /// Returns the URL of the Modern SharePoint Site backing an Office 365 Group (i.e. Unified Group) /// </summary> /// <param name="groupId">The ID of the Office 365 Group</param> /// <param name="accessToken">The OAuth 2.0 Access Token to use for invoking the Microsoft Graph</param> /// <param name="retryCount">Number of times to retry the request in case of throttling</param> /// <param name="delay">Milliseconds to wait before retrying the request. The delay will be increased (doubled) every retry</param> /// <returns>The URL of the modern site backing the Office 365 Group</returns> public static String GetUnifiedGroupSiteUrl(String groupId, String accessToken, int retryCount = 10, int delay = 500) { if (String.IsNullOrEmpty(groupId)) { throw new ArgumentNullException(nameof(groupId)); } if (String.IsNullOrEmpty(accessToken)) { throw new ArgumentNullException(nameof(accessToken)); } string result; try { // Use a synchronous model to invoke the asynchronous process result = Task.Run(async () => { String siteUrl = null; var graphClient = GraphHelper.GetAuthenticatedClient(); var groupDrive = await graphClient.Groups[groupId].Drive.Request().GetAsync(); if (groupDrive != null) { var rootFolder = await graphClient.Groups[groupId].Drive.Root.Request().GetAsync(); if (rootFolder != null) { if (!String.IsNullOrEmpty(rootFolder.WebUrl)) { var modernSiteUrl = rootFolder.WebUrl; siteUrl = modernSiteUrl.Substring(0, modernSiteUrl.LastIndexOf("/")); } } } return (siteUrl); }).GetAwaiter().GetResult(); } catch (ServiceException ex) { throw ex; } return (result); } /// <summary> /// Creates a new Office 365 Group (i.e. Unified Group) with its backing Modern SharePoint Site /// </summary> /// <param name="displayName">The Display Name for the Office 365 Group</param> /// <param name="description">The Description for the Office 365 Group</param> /// <param name="mailNickname">The Mail Nickname for the Office 365 Group</param> /// <param name="accessToken">The OAuth 2.0 Access Token to use for invoking the Microsoft Graph</param> /// <param name="owners">A list of UPNs for group owners, if any</param> /// <param name="members">A list of UPNs for group members, if any</param> /// <param name="groupLogo">The binary stream of the logo for the Office 365 Group</param> /// <param name="isPrivate">Defines whether the group will be private or public, optional with default false (i.e. public)</param> /// <param name="retryCount">Number of times to retry the request in case of throttling</param> /// <param name="delay">Milliseconds to wait before retrying the request. The delay will be increased (doubled) every retry</param> /// <returns>The just created Office 365 Group</returns> public static UnifiedGroupEntity CreateUnifiedGroup(string displayName, string description, string mailNickname, string accessToken, string[] owners = null, string[] members = null, Stream groupLogo = null, bool isPrivate = false, int retryCount = 3, int delay = 500) { UnifiedGroupEntity result = null; if (String.IsNullOrEmpty(displayName)) { throw new ArgumentNullException(nameof(displayName)); } if (String.IsNullOrEmpty(description)) { throw new ArgumentNullException(nameof(description)); } if (String.IsNullOrEmpty(mailNickname)) { throw new ArgumentNullException(nameof(mailNickname)); } if (String.IsNullOrEmpty(accessToken)) { throw new ArgumentNullException(nameof(accessToken)); } try { // Use a synchronous model to invoke the asynchronous process result = Task.Run(async () => { var group = new UnifiedGroupEntity(); var graphClient = GraphHelper.GetAuthenticatedClient(); // Prepare the group resource object var newGroup = new Microsoft.Graph.Group { DisplayName = displayName, Description = description, MailNickname = mailNickname, MailEnabled = true, SecurityEnabled = false, Visibility = isPrivate == true ? "Private" : "Public", GroupTypes = new List<string> {"Unified"}, }; Microsoft.Graph.Group addedGroup = null; String modernSiteUrl = null; SiteResponse newRestGroup = null; // Add the group to the collection of groups (if it does not exist if (addedGroup == null) { using (var ctx = AuthHelper.GetSharePointClientContext()) { List<string> additionalOwners = GetAdditionalUsersWithoutCurrent(owners, ctx); // Create UnifiedGroup using SharePoint API for ModernSites newRestGroup = new ModernSiteCreator(ctx).CreateGroup(displayName, mailNickname, !isPrivate, description, additionalOwners); modernSiteUrl = newRestGroup.SiteUrl; } //await Task.Delay(10 * 1000); var tryCount = 60; // try 60 seconds // wait for 10 seconds & try again while (true) { try { // And if any, add it to the collection of group's owners addedGroup = await graphClient.Groups[newRestGroup.GroupId].Request().GetAsync(); break; } catch (ServiceException ex) { if (ex.Error.Code == "Request_ResourceNotFound" && ex.Error.Message.Contains(newRestGroup.GroupId) && --tryCount <= 0) { throw; } else { Logger.Info($"\n\nwaiting group provisioning: {(tryCount - 60) * -1}/60 tries."); await Task.Delay(1000); } } } //addedGroup = await graphClient.Groups.Request().AddAsync(newGroup); if (addedGroup != null) { group.DisplayName = addedGroup.DisplayName; group.Description = addedGroup.Description; group.GroupId = addedGroup.Id; group.Mail = addedGroup.Mail; group.MailNickname = addedGroup.MailNickname; int imageRetryCount = retryCount; if (groupLogo != null) { using (var memGroupLogo = new MemoryStream()) { groupLogo.CopyTo(memGroupLogo); while (imageRetryCount > 0) { bool groupLogoUpdated = false; memGroupLogo.Position = 0; using (var tempGroupLogo = new MemoryStream()) { memGroupLogo.CopyTo(tempGroupLogo); tempGroupLogo.Position = 0; try { groupLogoUpdated = UpdateUnifiedGroup(addedGroup.Id, accessToken, groupLogo: tempGroupLogo); } catch { // Skip any exception and simply retry } } // In case of failure retry up to 10 times, with 500ms delay in between if (!groupLogoUpdated) { // Pop up the delay for the group image await Task.Delay(delay * (retryCount - imageRetryCount)); imageRetryCount--; } else { break; } } } } int driveRetryCount = retryCount; while (driveRetryCount > 0 && String.IsNullOrEmpty(modernSiteUrl)) { try { modernSiteUrl = GetUnifiedGroupSiteUrl(addedGroup.Id, accessToken); } catch { // Skip any exception and simply retry } // In case of failure retry up to 10 times, with 500ms delay in between if (String.IsNullOrEmpty(modernSiteUrl)) { await Task.Delay(delay * (retryCount - driveRetryCount)); driveRetryCount--; } } group.SiteUrl = modernSiteUrl; } } #region Handle group's members if (members != null && members.Length > 0) { string[] allMembers = members; //if (owners != null && owners.Length > 0) allMembers = allMembers.Concat(owners).Distinct().ToArray(); await AddMembers(allMembers, graphClient, addedGroup); } #endregion #region Handle group's owners if (owners != null && owners.Length > 0) { await AddOwners(owners, graphClient, addedGroup); } #endregion try { Logger.Info("Start removing default owner"); if (owners != null && owners.Length > 1) { await RemoveOwners(new[] {AuthHelper.SPUserId}, graphClient, addedGroup); } if (members != null && members.Length > 1) { await RemoveMembers(new[] {AuthHelper.SPUserId}, graphClient, addedGroup); } } catch (Exception e) { Logger.Error("Error removing default owner " + e.Message); // :) No need to warry about initial removing a user. // :( What? // :) Why not? } return (group); }).GetAwaiter().GetResult(); } catch (ServiceException ex) { throw ex; } catch (System.Net.WebException e) { Logger.Error(e.Message, e); throw e; } return (result); } private static List<string> GetAdditionalUsersWithoutCurrent(string[] owners, Microsoft.SharePoint.Client.ClientContext ctx) { List<string> additionalOwners = new List<string>(); if (owners != null) { var _owners = owners.ToList<string>(); var usr = ctx.Web.CurrentUser; ctx.Load(usr); ctx.ExecuteQuery(); additionalOwners = _owners.Where(owner => !string.Equals(owner, usr.Email)).ToList<string>(); } return additionalOwners; } /// <summary> /// Gets a list of UPNs for group members /// </summary> /// <param name="graphMembers">group members</param> /// <returns>a list of UPNs for group members</returns> public static List<string> GetMembersEmail(List<Microsoft.Graph.User> graphMembers) { List<string> members = new List<string>(); foreach (var member in graphMembers) { members.Add(member.UserPrincipalName); } return members; } public static async Task AddMembers(string[] members, GraphServiceClient graphClient, Microsoft.Graph.Group addedGroup) { foreach (var m in members) { // Search for the user object var memberQuery = await graphClient.Users .Request() .Filter($"userPrincipalName eq '{m}'") .GetAsync(); var member = memberQuery.FirstOrDefault(); if (member != null) { try { // And if any, add it to the collection of group's owners await graphClient.Groups[addedGroup.Id].Members.References.Request().AddAsync(member); } catch (ServiceException ex) { if (ex.Error.Code == "Request_BadRequest" && ex.Error.Message.Contains("added object references already exist")) { // Skip any already existing member } else { throw ex; } } catch (WebException e) { Logger.Error(e.Message, e); throw; } } } } public static async Task AddOwners(string[] owners, GraphServiceClient graphClient, Microsoft.Graph.Group addedGroup) { foreach (var o in owners) { // Search for the user object var ownerQuery = await graphClient.Users .Request() .Filter($"userPrincipalName eq '{o}'") .GetAsync(); var owner = ownerQuery.FirstOrDefault(); if (owner != null) { try { // And if any, add it to the collection of group's owners await graphClient.Groups[addedGroup.Id].Owners.References.Request().AddAsync(owner); } catch (ServiceException ex) { if (ex.Error.Code == "Request_BadRequest" && ex.Error.Message.Contains("added object references already exist")) { // Skip any already existing owner } else { throw ex; } } catch (WebException e) { Logger.Error(e.Message, e); throw; } } } } public static async Task RemoveMembers(string[] members, GraphServiceClient graphClient, Microsoft.Graph.Group addedGroup) { foreach (var m in members) { // Search for the user object var memberQuery = await graphClient.Users .Request() .Filter($"userPrincipalName eq '{m}'") .GetAsync(); var member = memberQuery.FirstOrDefault(); if (member != null) { try { // And if any, add it to the collection of group's owners await graphClient.Groups[addedGroup.Id].Members[member.Id].Reference.Request().DeleteAsync(); } catch (ServiceException ex) { if (ex.Error.Code == "Request_ResourceNotFound" && ex.Error.Message.Contains("does not exist or one of its queried reference")) { // Skip not found to delete } else { throw ex; } } catch (WebException e) { Logger.Error(e.Message, e); throw; } } } } public static async Task RemoveOwners(string[] owners, GraphServiceClient graphClient, Microsoft.Graph.Group addedGroup) { foreach (var o in owners) { // Search for the user object var ownerQuery = await graphClient.Users .Request() .Filter($"userPrincipalName eq '{o}'") .GetAsync(); var owner = ownerQuery.FirstOrDefault(); if (owner != null) { try { // And if any, add it to the collection of group's owners await graphClient.Groups[addedGroup.Id].Owners[owner.Id].Reference.Request().DeleteAsync(); } catch (ServiceException ex) { if (ex.Error.Code == "Request_ResourceNotFound" && ex.Error.Message.Contains("does not exist or one of its queried reference")) { // Skip not found to delete } else { throw ex; } } catch (WebException e) { Logger.Error(e.Message, e); throw; } } } } public static async Task UpdateGroupMetaData(string groupId, InmetaGenericExtension metadata, string extensionId) { var graphClient = GraphHelper.GetAuthenticatedClient(); IDictionary<string, object> extensionInstance = new Dictionary<string, object>(); extensionInstance.Add(extensionId, metadata); await graphClient.Groups[groupId].Request().UpdateAsync(new Group { AdditionalData = extensionInstance }); } public static void AllowToAddGuests(string groupId, bool allow, string accessToken) { try { var body = $"{{'displayName': 'Group.Unified.Guest', 'templateId': '08d542b9-071f-4e16-94b0-74abb372e3d9', 'values': [{{'name': 'AllowToAddGuests','value': '{allow}'}}]}}"; GetRequest($"https://graph.microsoft.com/v1.0/groups/{groupId}/settings", "POST", new WebHeaderCollection { { "Authorization", "Bearer " + accessToken } }, body).GetResponse(); } catch (Exception e) { Console.WriteLine($"Could not adjust group external sharing settings: {e.Message}"); } } // A generic method you can use for constructing web requests public static HttpWebRequest GetRequest(string url, string method, WebHeaderCollection headers, string body = null, string contentType = "application/json") { var request = (HttpWebRequest)WebRequest.Create(url); request.Method = method; request.Headers = headers; if (body != null) { var bytes = Encoding.UTF8.GetBytes(body); request.ContentLength = bytes.Length; request.ContentType = contentType; var stream = request.GetRequestStream(); stream.Write(bytes, 0, bytes.Length); stream.Close(); } return request; } /// <summary> /// Updates the logo, members or visibility state of an Office 365 Group /// </summary> /// <param name="groupId">The ID of the Office 365 Group</param> /// <param name="displayName">The Display Name for the Office 365 Group</param> /// <param name="description">The Description for the Office 365 Group</param> /// <param name="owners">A list of UPNs for group owners, if any, to be added to the site</param> /// <param name="members">A list of UPNs for group members, if any, to be added to the site</param> /// <param name="isPrivate">Defines whether the group will be private or public, optional with default false (i.e. public)</param> /// <param name="groupLogo">The binary stream of the logo for the Office 365 Group</param> /// <param name="accessToken">The OAuth 2.0 Access Token to use for invoking the Microsoft Graph</param> /// <param name="retryCount">Number of times to retry the request in case of throttling</param> /// <param name="delay">Milliseconds to wait before retrying the request. The delay will be increased (doubled) every retry</param> /// <returns>Declares whether the Office 365 Group has been updated or not</returns> public static bool UpdateUnifiedGroup(string groupId, string accessToken, int retryCount = 3, int delay = 500, string displayName = null, string description = null, string[] owners = null, string[] members = null, Stream groupLogo = null, bool isPrivate = false) { bool result; try { // Use a synchronous model to invoke the asynchronous process result = Task.Run(async () => { var graphClient = GraphHelper.GetAuthenticatedClient(); var groupToUpdate = await graphClient.Groups[groupId] .Request() .GetAsync(); #region Logic to update the group DisplayName and Description var updateGroup = false; var groupUpdated = false; // Check if we have to update the DisplayName if (!String.IsNullOrEmpty(displayName) && groupToUpdate.DisplayName != displayName) { groupToUpdate.DisplayName = displayName; updateGroup = true; } // Check if we have to update the Description if (!String.IsNullOrEmpty(description) && groupToUpdate.Description != description) { groupToUpdate.Description = description; updateGroup = true; } // Check if visibility has changed for the Group bool existingIsPrivate = groupToUpdate.Visibility == "Private"; if (existingIsPrivate != isPrivate) { groupToUpdate.Visibility = isPrivate == true ? "Private" : "Public"; updateGroup = true; } // Check if we are to add owners if (owners != null && owners.Length > 0) { // For each and every owner await AddOwners(owners, graphClient, groupToUpdate); updateGroup = true; } // Check if we are to add members if (members != null && members.Length > 0) { // For each and every owner await AddMembers(members, graphClient, groupToUpdate); updateGroup = true; } // If the Group has to be updated, just do it if (updateGroup) { var updatedGroup = await graphClient.Groups[groupId] .Request() .UpdateAsync(groupToUpdate); groupUpdated = true; } #endregion #region Logic to update the group Logo var logoUpdated = false; if (groupLogo != null) { await graphClient.Groups[groupId].Photo.Content.Request().PutAsync(groupLogo); logoUpdated = true; } #endregion // If any of the previous update actions has been completed return (groupUpdated || logoUpdated); }).GetAwaiter().GetResult(); } catch (ServiceException ex) { throw ex; } return (result); } /// <summary> /// Creates a new Office 365 Group (i.e. Unified Group) with its backing Modern SharePoint Site /// </summary> /// <param name="displayName">The Display Name for the Office 365 Group</param> /// <param name="description">The Description for the Office 365 Group</param> /// <param name="mailNickname">The Mail Nickname for the Office 365 Group</param> /// <param name="accessToken">The OAuth 2.0 Access Token to use for invoking the Microsoft Graph</param> /// <param name="owners">A list of UPNs for group owners, if any</param> /// <param name="members">A list of UPNs for group members, if any</param> /// <param name="groupLogoPath">The path of the logo for the Office 365 Group</param> /// <param name="isPrivate">Defines whether the group will be private or public, optional with default false (i.e. public)</param> /// <param name="retryCount">Number of times to retry the request in case of throttling</param> /// <param name="delay">Milliseconds to wait before retrying the request. The delay will be increased (doubled) every retry</param> /// <returns>The just created Office 365 Group</returns> public static UnifiedGroupEntity CreateUnifiedGroup(string displayName, string description, string mailNickname, string accessToken, string[] owners = null, string[] members = null, String groupLogoPath = null, bool isPrivate = false, int retryCount = 3, int delay = 500) { if (!String.IsNullOrEmpty(groupLogoPath) && IsLocalPath(groupLogoPath) && !System.IO.File.Exists(groupLogoPath)) { throw new FileNotFoundException("Group logo file does not exist", groupLogoPath); } else if (!String.IsNullOrEmpty(groupLogoPath) && !IsLocalPath(groupLogoPath)) { using (MemoryStream groupLogoStream = new MemoryStream(wc.DownloadData(groupLogoPath))) { return (CreateUnifiedGroup(displayName, description, mailNickname, accessToken, owners, members, groupLogo: groupLogoStream, isPrivate: isPrivate, retryCount: retryCount, delay: delay)); } } else if (!String.IsNullOrEmpty(groupLogoPath) && IsLocalPath(groupLogoPath)) { using (var groupLogoStream = new FileStream(groupLogoPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { return (CreateUnifiedGroup(displayName, description, mailNickname, accessToken, owners, members, groupLogo: groupLogoStream, isPrivate: isPrivate, retryCount: retryCount, delay: delay)); } } else { return (CreateUnifiedGroup(displayName, description, mailNickname, accessToken, owners, members, groupLogo: null, isPrivate: isPrivate, retryCount: retryCount, delay: delay)); } } /// <summary> /// Creates a new Office 365 Group (i.e. Unified Group) with its backing Modern SharePoint Site /// </summary> /// <param name="displayName">The Display Name for the Office 365 Group</param> /// <param name="description">The Description for the Office 365 Group</param> /// <param name="mailNickname">The Mail Nickname for the Office 365 Group</param> /// <param name="accessToken">The OAuth 2.0 Access Token to use for invoking the Microsoft Graph</param> /// <param name="owners">A list of UPNs for group owners, if any</param> /// <param name="members">A list of UPNs for group members, if any</param> /// <param name="isPrivate">Defines whether the group will be private or public, optional with default false (i.e. public)</param> /// <param name="retryCount">Number of times to retry the request in case of throttling</param> /// <param name="delay">Milliseconds to wait before retrying the request. The delay will be increased (doubled) every retry</param> /// <returns>The just created Office 365 Group</returns> public static UnifiedGroupEntity CreateUnifiedGroup(string displayName, string description, string mailNickname, string accessToken, string[] owners = null, string[] members = null, bool isPrivate = false, int retryCount = 3, int delay = 500) { return (CreateUnifiedGroup(displayName, description, mailNickname, accessToken, owners, members, groupLogo: null, isPrivate: isPrivate, retryCount: retryCount, delay: delay)); } /// <summary> /// Deletes an Office 365 Group (i.e. Unified Group) /// </summary> /// <param name="groupId">The ID of the Office 365 Group</param> /// <param name="accessToken">The OAuth 2.0 Access Token to use for invoking the Microsoft Graph</param> /// <param name="retryCount">Number of times to retry the request in case of throttling</param> /// <param name="delay">Milliseconds to wait before retrying the request. The delay will be increased (doubled) every retry</param> public static void DeleteUnifiedGroup(String groupId, String accessToken, int retryCount = 3, int delay = 500) { if (String.IsNullOrEmpty(groupId)) { throw new ArgumentNullException(nameof(groupId)); } if (String.IsNullOrEmpty(accessToken)) { throw new ArgumentNullException(nameof(accessToken)); } try { // Use a synchronous model to invoke the asynchronous process Task.Run(async () => { var graphClient = GraphHelper.GetAuthenticatedClient(); await graphClient.Groups[groupId].Request().DeleteAsync(); }).GetAwaiter().GetResult(); } catch (ServiceException ex) { throw ex; } } /// <summary> /// Get an Office 365 Group (i.e. Unified Group) by Id /// </summary> /// <param name="groupId">The ID of the Office 365 Group</param> /// <param name="accessToken">The OAuth 2.0 Access Token to use for invoking the Microsoft Graph</param> /// <param name="includeSite">Defines whether to return details about the Modern SharePoint Site backing the group. Default is true.</param> /// <param name="retryCount">Number of times to retry the request in case of throttling</param> /// <param name="delay">Milliseconds to wait before retrying the request. The delay will be increased (doubled) every retry</param> public static UnifiedGroupEntity GetUnifiedGroup(String groupId, String accessToken, int retryCount = 3, int delay = 500, bool includeSite = true) { if (String.IsNullOrEmpty(groupId)) { throw new ArgumentNullException(nameof(groupId)); } if (String.IsNullOrEmpty(accessToken)) { throw new ArgumentNullException(nameof(accessToken)); } UnifiedGroupEntity result = null; try { // Use a synchronous model to invoke the asynchronous process result = Task.Run(async () => { UnifiedGroupEntity group = null; var graphClient = GraphHelper.GetAuthenticatedClient(); var g = await graphClient.Groups[groupId].Request().GetAsync(); group = new UnifiedGroupEntity { GroupId = g.Id, DisplayName = g.DisplayName, Description = g.Description, Mail = g.Mail, MailNickname = g.MailNickname }; if (includeSite) { try { group.SiteUrl = GetUnifiedGroupSiteUrl(groupId, accessToken); } catch (ServiceException e) { group.SiteUrl = e.Error.Message; } } return (group); }).GetAwaiter().GetResult(); } catch (ServiceException ex) { throw ex; } return (result); } /// <summary> /// Returns all the Office 365 Groups in the current Tenant based on a startIndex. IncludeSite adds additional properties about the Modern SharePoint Site backing the group /// </summary> /// <param name="accessToken">The OAuth 2.0 Access Token to use for invoking the Microsoft Graph</param> /// <param name="displayName">The DisplayName of the Office 365 Group</param> /// <param name="mailNickname">The MailNickname of the Office 365 Group</param> /// <param name="startIndex">Not relevant anymore</param> /// <param name="endIndex">Not relevant anymore</param> /// <param name="includeSite">Defines whether to return details about the Modern SharePoint Site backing the group. Default is true.</param> /// <param name="retryCount">Number of times to retry the request in case of throttling</param> /// <param name="delay">Milliseconds to wait before retrying the request. The delay will be increased (doubled) every retry</param> /// <returns>An IList of SiteEntity objects</returns> public static List<UnifiedGroupEntity> ListUnifiedGroups(string accessToken, String displayName = null, string mailNickname = null, int startIndex = 0, int endIndex = 999, bool includeSite = true, int retryCount = 3, int delay = 500) { if (String.IsNullOrEmpty(accessToken)) { throw new ArgumentNullException(nameof(accessToken)); } List<UnifiedGroupEntity> result = null; try { // Use a synchronous model to invoke the asynchronous process result = Task.Run(async () => { List<UnifiedGroupEntity> groups = new List<UnifiedGroupEntity>(); var graphClient = GraphHelper.GetAuthenticatedClient(); // Apply the DisplayName filter, if any var displayNameFilter = !String.IsNullOrEmpty(displayName) ? $" and startswith(DisplayName,'{displayName}')" : String.Empty; var mailNicknameFilter = !String.IsNullOrEmpty(mailNickname) ? $" and startswith(MailNickname,'{mailNickname}')" : String.Empty; var pagedGroups = await graphClient.Groups .Request() .Filter($"groupTypes/any(grp: grp eq 'Unified'){displayNameFilter}{mailNicknameFilter}") .Top(endIndex) .GetAsync(); Int32 pageCount = 0; Int32 currentIndex = 0; while (true) { pageCount++; foreach (var g in pagedGroups) { currentIndex++; if (currentIndex >= startIndex) { var group = new UnifiedGroupEntity { GroupId = g.Id, DisplayName = g.DisplayName, Description = g.Description, Mail = g.Mail, MailNickname = g.MailNickname, }; if (includeSite) { try { group.SiteUrl = GetUnifiedGroupSiteUrl(g.Id, accessToken); } catch (ServiceException e) { group.SiteUrl = e.Error.Message; } } groups.Add(group); } } if (pagedGroups.NextPageRequest != null && groups.Count < endIndex) { pagedGroups = await pagedGroups.NextPageRequest.GetAsync(); } else { break; } } return (groups); }).GetAwaiter().GetResult(); } catch (ServiceException ex) { throw ex; } return (result); } private static bool IsLocalPath(string p) { if (p.StartsWith("http:\\") || p.StartsWith("https:\\") || p.StartsWith("ftp:\\")) { return false; } return new Uri(p).IsFile; } } }
35.487315
192
0.597391
[ "Apache-2.0" ]
UNINETT/spfx-uninett-webparts
other_components/Office365Groups.Library/OfficeGroupUtility.cs
33,573
C#
#pragma warning disable CS0626 // Method, operator, or accessor is marked external and has no attributes on it #pragma warning disable CS0649 using System; using System.Collections.Generic; using System.IO; using System.Linq; using Ionic.Crc; using Ionic.Zip; using Mod.Courier; using Mod.Courier.Module; using MonoMod; using UnityEngine; public class patch_DialogManager : DialogManager { [MonoModIgnore] private Dictionary<string, List<DialogInfo>> dialogByLocID; [MonoModIgnore] private extern void CreateDialogInfo(string currentDialogName, string[] lineItems, int languageIndex, int skippableIndex, int avatarIndex, int boxPositionIndex, int autoCloseIndex, int autoCloseDelayIndex, int locIdIndex, int forcedPortraitOrientationIndex); [MonoModIgnore] private extern string GetActualDialogID(string locId); private extern void orig_LoadTSVDialogs(string languageID); private void LoadTSVDialogs(string languageID) { orig_LoadTSVDialogs(languageID); foreach (CourierModuleMetadata modMeta in Courier.Mods) { if (modMeta.DirectoryMod) { string[] modFiles = Directory.GetFiles(modMeta.DirectoryPath); // Check files in subfolders foreach (string path in modFiles) { if (path.EndsWith(".tsv", StringComparison.InvariantCulture) && Path.GetFileName(path).Contains("Dialog")) { Mod.Courier.CourierLogger.Log("Courier", "Loading dialog localization file from " + path); LoadTSVDialogsFromStream(languageID, File.OpenRead(path)); } } } else if (modMeta.ZippedMod) { foreach (ZipEntry entry in modMeta.ZipFile) { if (entry.FileName.EndsWith(".tsv", StringComparison.InvariantCulture) && entry.FileName.Contains("Dialog")) { CrcCalculatorStream stream = entry.OpenReader(); Mod.Courier.CourierLogger.Log("Courier", "Loading zipped dialog localization file from " + Path.Combine(modMeta.ZipFile.Name, entry.FileName)); LoadTSVDialogsFromStream(languageID, stream); } } } } } private void LoadTSVDialogsFromStream(string languageID, Stream stream) { StreamReader streamReader = new StreamReader(stream); string[] headings = streamReader.ReadLine().Split('\t'); // The index of the column the language we're reading is in int langColumnIndex = -1; int skippableIndex = -1; int avatarIndex = -1; int boxPositionIndex = -1; int autoCloseIndex = -1; int autoCloseDelayIndex = -1; int forcedPortraitOrientationIndex = -1; int locIDIndex = -1; for (int i = headings.Length - 1; i >= 0; i--) { if (headings[i] == languageID) { langColumnIndex = i; } else if (headings[i] == ELanguage.EN.ToString() && langColumnIndex == -1) { // Set it to English if a language hasn't been found yet langColumnIndex = i; } else if (headings[i] == "LOC_ID") { locIDIndex = i; } else if (headings[i] == "SKIPPABLE") { skippableIndex = i; } else if (headings[i] == "AVATAR") { avatarIndex = i; } else if (headings[i] == "BOX_POSITION") { boxPositionIndex = i; } else if (headings[i] == "AUTO_CLOSE") { autoCloseIndex = i; } else if (headings[i] == "AUTO_CLOSE_DELAY") { autoCloseDelayIndex = i; } else if (headings[i] == "FORCED_PORTRAIT_ORIENTATION") { forcedPortraitOrientationIndex = i; } } // If we couldn't find the specified language if (langColumnIndex == -1) { return; } bool duringConversation = false; // The loc ID representing the whole conversation // Basically the starting loc ID without _BEGIN at the end string conversationLocID = string.Empty; while (!streamReader.EndOfStream) { string[] entry = streamReader.ReadLine().Split('\t'); string locID = entry[locIDIndex]; if (locID == string.Empty) { continue; } if (!duringConversation) { conversationLocID = locID; if (locID.Length > 6) { if (locID.Substring(locID.Length - 6) == "_BEGIN") { duringConversation = true; conversationLocID = locID.Substring(0, locID.Length - 6); } } // I removed a thing to check if anything was already in this conversationLocID // I can't think of anything that could go wrong, but you never know dialogByLocID[conversationLocID] = new List<DialogInfo>(); CreateDialogInfo(conversationLocID, entry, langColumnIndex, skippableIndex, avatarIndex, boxPositionIndex, autoCloseIndex, autoCloseDelayIndex, locIDIndex, forcedPortraitOrientationIndex); continue; } string actualDialogID = GetActualDialogID(locID); if (actualDialogID != conversationLocID) { if (!dialogByLocID.ContainsKey(locID)) { dialogByLocID[locID] = new List<DialogInfo>(); } CreateDialogInfo(locID, entry, langColumnIndex, skippableIndex, avatarIndex, boxPositionIndex, autoCloseIndex, autoCloseDelayIndex, locIDIndex, forcedPortraitOrientationIndex); continue; } if (locID.Length > 4 && locID.Substring(locID.Length - 4) == "_END") { duringConversation = false; } CreateDialogInfo(conversationLocID, entry, langColumnIndex, skippableIndex, avatarIndex, boxPositionIndex, autoCloseIndex, autoCloseDelayIndex, locIDIndex, forcedPortraitOrientationIndex); } streamReader.Close(); } }
47.19084
262
0.600129
[ "MIT" ]
Brokemia/Courier
Assembly-CSharp.Courier.mm/Patches/DialogManager.cs
6,184
C#
 // Monster.cs // Copyright (c) 2014+ by Michael Penner. All rights reserved. using System; using System.Diagnostics; using System.Text; using Eamon; using Eamon.Framework; using Eamon.Game.Attributes; using Eamon.Game.Extensions; using Enums = Eamon.Framework.Primitive.Enums; using static StrongholdOfKahrDur.Game.Plugin.PluginContext; namespace StrongholdOfKahrDur.Game { [ClassMappings] public class Monster : Eamon.Game.Monster, IMonster { public override RetCode BuildPrintedFullDesc(StringBuilder buf, bool showName) { RetCode rc; rc = base.BuildPrintedFullDesc(buf, showName); // Lich will ask to be freed if (gEngine.IsSuccess(rc) && Uid == 15 && !Seen) { var effect = gEDB[53]; Debug.Assert(effect != null); buf.AppendPrint("{0}", effect.Desc); } return rc; } public override bool CanMoveToRoom(bool fleeing) { // Tree ents can't flee or follow return Uid < 8 || Uid > 10 ? base.CanMoveToRoom(fleeing) : false; } public override bool CanMoveToRoomUid(long roomUid, bool fleeing) { // Necromancer can't move into a dark area return Uid != 22 || roomUid != 54 ? base.CanMoveToRoomUid(roomUid, fleeing) : false; } public override bool ShouldReadyWeapon() { // Necromancer never tries to pick up or ready weapon return Uid != 22 ? base.ShouldReadyWeapon() : false; } public override void AddHealthStatus(StringBuilder buf, bool addNewLine = true) { string result = null; if (buf == null) { // PrintError goto Cleanup; } if (IsDead()) { result = "dead!"; } else { var x = DmgTaken; x = (((long)((double)(x * 5) / (double)Hardiness)) + 1) * (x > 0 ? 1 : 0); result = "at death's door, knocking loudly."; if (x == 4) { result = "gravely injured."; } else if (x == 3) { result = "badly hurt."; } else if (x == 2) { result = "hurt."; } else if (x == 1) { result = "still in good shape."; } else if (x < 1) { result = "in perfect health."; } } Debug.Assert(result != null); buf.AppendFormat("{0}{1}", result, addNewLine ? Environment.NewLine : ""); Cleanup: ; } public override string[] GetWeaponMissDescs(IArtifact artifact) { var missDescs = base.GetWeaponMissDescs(artifact); Debug.Assert(missDescs != null && missDescs.Length >= 1); switch ((Enums.Weapon)artifact.GeneralWeapon.Field2) { case Enums.Weapon.Axe: case Enums.Weapon.Club: case Enums.Weapon.Spear: missDescs[0] = "Parried"; break; } return missDescs; } } }
20.248175
88
0.59553
[ "MIT" ]
TheRealEamonCS/Eamon-CS
Adventures/StrongholdOfKahrDur/Game/Monster.cs
2,776
C#
/*A marketing company wants to keep record of its employees. Each record would have the following characteristics: First name Last name Age (0...100) Gender (m or f) Personal ID number (e.g. 8306112507) Unique employee number (27560000…27569999) Declare the variables needed to keep the information for a single employee using appropriate primitive data types. Use descriptive names. Print the data at the console.*/ using System; namespace EmployeeData { class EmployeeData { static void Main() { string firstName = "Valentina"; string secondName = "Petrova"; byte age = 25; char gender = 'f'; ulong personalID = 8306112507; uint employeeNum = 27569999; Console.WriteLine(firstName +" "+secondName+" "+age+" "+gender+" "+personalID+" "+employeeNum); } } }
27.625
115
0.650452
[ "MIT" ]
AYankova/CSharp
HomeworkPrimitiveDataTypesAndValuables/10.EmployeeData/EmployeeData.cs
888
C#
/// Copyright (c) Pomelo Foundation. All rights reserved. // Licensed under the MIT. See LICENSE in the project root for license information. using System; using System.Collections.Generic; using System.Linq.Expressions; using EFCore.MySql.Query.Expressions.Internal; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Query.Expressions; using Microsoft.EntityFrameworkCore.Query.Sql; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Utilities; namespace EFCore.MySql.Query.Sql.Internal { /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public class MySqlQuerySqlGenerator : DefaultQuerySqlGenerator, IMySqlExpressionVisitor { protected override string TypedTrueLiteral => "TRUE"; protected override string TypedFalseLiteral => "FALSE"; /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public MySqlQuerySqlGenerator( [NotNull] QuerySqlGeneratorDependencies dependencies, [NotNull] SelectExpression selectExpression) : base(dependencies, selectExpression) { } protected override void GenerateTop(SelectExpression selectExpression) { } /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> protected override void GenerateLimitOffset(SelectExpression selectExpression) { Check.NotNull(selectExpression, nameof(selectExpression)); if (selectExpression.Limit != null) { Sql.AppendLine().Append("LIMIT "); Visit(selectExpression.Limit); } if (selectExpression.Offset != null) { if (selectExpression.Limit == null) { // if we want to use Skip() without Take() we have to define the upper limit of LIMIT Sql.AppendLine().Append("LIMIT ").Append(18446744073709551610); } Sql.Append(" OFFSET "); Visit(selectExpression.Offset); } } /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public override Expression VisitSqlFunction(SqlFunctionExpression sqlFunctionExpression) { if (sqlFunctionExpression.FunctionName.StartsWith("@@", StringComparison.Ordinal)) { Sql.Append(sqlFunctionExpression.FunctionName); return sqlFunctionExpression; } return base.VisitSqlFunction(sqlFunctionExpression); } protected override void GenerateProjection(Expression projection) { var aliasedProjection = projection as AliasExpression; var expressionToProcess = aliasedProjection?.Expression ?? projection; var updatedExperssion = ExplicitCastToBool(expressionToProcess); expressionToProcess = aliasedProjection != null ? new AliasExpression(aliasedProjection.Alias, updatedExperssion) : updatedExperssion; base.GenerateProjection(expressionToProcess); } private Expression ExplicitCastToBool(Expression expression) { return (expression as BinaryExpression)?.NodeType == ExpressionType.Coalesce && expression.Type.UnwrapNullableType() == typeof(bool) ? new ExplicitCastExpression(expression, expression.Type) : expression; } protected override Expression VisitBinary(BinaryExpression binaryExpression) { if (binaryExpression.NodeType == ExpressionType.Add && binaryExpression.Left.Type == typeof(string) && binaryExpression.Right.Type == typeof(string)) { Sql.Append("CONCAT("); //var exp = base.VisitBinary(binaryExpression); Visit(binaryExpression.Left); Sql.Append(","); var exp = Visit(binaryExpression.Right); Sql.Append(")"); return exp; } var expr = base.VisitBinary(binaryExpression); return expr; } public virtual Expression VisitRegexp(RegexpExpression regexpExpression) { Check.NotNull(regexpExpression, nameof(regexpExpression)); Visit(regexpExpression.Match); Sql.Append(" REGEXP "); Visit(regexpExpression.Pattern); return regexpExpression; } private static readonly Dictionary<string, string[]> CastMappings = new Dictionary<string, string[]> { { "signed", new []{ "tinyint", "smallint", "mediumint", "int", "bigint" }}, { "decimal", new []{ "decimal", "double", "float" } }, { "binary", new []{ "binary", "varbinary", "tinyblob", "blob", "mediumblob", "longblob" } }, { "datetime", new []{ "datetime", "timestamp" } }, { "time", new []{ "time" } }, { "json", new []{ "json" } }, }; public override Expression VisitExplicitCast(ExplicitCastExpression explicitCastExpression) { Sql.Append("CAST("); Visit(explicitCastExpression.Operand); Sql.Append(" AS "); var typeMapping = Dependencies.RelationalTypeMapper.FindMapping(explicitCastExpression.Type); if (typeMapping == null) { throw new InvalidOperationException($"Cannot cast to type '{explicitCastExpression.Type.Name}'"); } var storeTypeLower = typeMapping.StoreType.ToLower(); string castMapping = null; foreach (var kvp in CastMappings) { foreach (var storeType in kvp.Value) { if (storeTypeLower.StartsWith(storeType)) { castMapping = kvp.Key; break; } } if (castMapping != null) { break; } } if (castMapping == "signed" && storeTypeLower.Contains("unsigned")) { castMapping = "unsigned"; } else if (castMapping == null) { castMapping = "char"; } Sql.Append(castMapping); Sql.Append(")"); return explicitCastExpression; } } }
38.924731
113
0.582873
[ "MIT" ]
boxburner/Pomelo.EntityFrameworkCore.MySql
src/EFCore.MySql/Query/Sql/Internal/MySqlQuerySqlGenerator.cs
7,240
C#
using UnityEngine; using GOAP_S.Planning; public class FindBarrelAction_GS : Action_GS { public float time = 1.0f; private float timer = 0.0f; public override ACTION_RESULT ActionUpdate() { timer += Time.deltaTime; if (timer > time) { RecollectorBehaviour agent_behaviour = ((RecollectorBehaviour)agent.behaviour); GameObject[] stores = GameObject.FindGameObjectsWithTag("Store"); foreach (GameObject store in stores) { if (store.GetComponentInChildren<SlotManager>().slot_available == true) { agent_behaviour.targeted_slot = store.GetComponentInChildren<SlotManager>(); agent_behaviour.targeted_slot.slot_available = false; blackboard.SetVariable<Vector3>("store_pos", agent_behaviour.targeted_slot.gameObject.transform.position); break; } } return ACTION_RESULT.A_NEXT; } return ACTION_RESULT.A_CURRENT; } }
29.944444
126
0.605751
[ "MIT" ]
ferranmartinvila/Unity-GOAP_S
Unity_Project/Assets/ExampleScripts/Actions/FindBarrelAction_GS.cs
1,080
C#
/* --------------------------- * SharePoint Manager 2010 v2 * Created by Carsten Keutmann * --------------------------- */ using System; using Microsoft.SharePoint; using Microsoft.SharePoint.Administration; using SPM2.Framework; namespace SPM2.SharePoint.Model { [Title(PropertyName="DisplayName")] [Icon(Small="BULLET.GIF")][View(50)] [ExportToNode("SPM2.SharePoint.Model.SPServiceProxyCollectionNode")] public partial class ApplicationRegistryServiceProxyNode { } }
21.909091
69
0.684647
[ "MIT" ]
keutmann/SPM
Libraries/SPM2.SharePoint/Model/Custom/ApplicationRegistryServiceProxyNode.cs
482
C#
/* * Copyright (c) 2018 Samsung Electronics Co., Ltd All Rights Reserved * * Licensed under the Flora License, Version 1.1 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://floralicense.org/license/ * * 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.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; using Tizen.Wearable.CircularUI.Forms; namespace WearableUIGallery.TC { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class TCInformationPopup : ContentPage { InformationPopup _textPopUp; InformationPopup _textButtonPopUp; InformationPopup _progressPopUp; MenuItem _textBottomButton; MenuItem _iconBottomButton; MenuItem _textIconBottomButton; string _longText; public TCInformationPopup() { InitializeComponent(); _textBottomButton = new MenuItem { Text = "OK", Command = new Command(() => { Console.WriteLine("text bottom button Command!!"); _textButtonPopUp?.Dismiss(); _textButtonPopUp = null; }) }; _iconBottomButton = new MenuItem { Icon = new FileImageSource { File = "image/tw_ic_popup_btn_delete.png", }, Command = new Command(() => { Console.WriteLine("icon bottom button Command!!"); _textButtonPopUp?.Dismiss(); _textButtonPopUp = null; }) }; _textIconBottomButton = new MenuItem { Text = "OK", Icon = new FileImageSource { File = "image/tw_ic_popup_btn_delete.png", }, Command = new Command(() => { Console.WriteLine("text&icon bottom button Command!!"); _textButtonPopUp?.Dismiss(); _textButtonPopUp = null; }) }; _longText = @"This is scrollable popup text. This part is made by adding long text in popup.Popup internally added scroller to this layout when size of text is greater than total popup height.This has two button in action area and title text in title area"; } void createTextPopup() { _textPopUp = new InformationPopup(); _textPopUp.BackButtonPressed += (s, e) => { _textPopUp?.Dismiss(); _textPopUp = null; label1.Text = "text popup is dismissed"; }; } void createTextButtonPopup() { _textButtonPopUp = new InformationPopup(); _textButtonPopUp.Title = "Popup title"; _textButtonPopUp.Text = "This is text and button popup test"; _textButtonPopUp.BottomButton = _textBottomButton; _textButtonPopUp.BackButtonPressed += (s, e) => { _textButtonPopUp?.Dismiss(); _textButtonPopUp = null; label1.Text = "text&button is dismissed"; }; _textButtonPopUp.BottomButton.Clicked += (s, e) => { _textButtonPopUp?.Dismiss(); _textButtonPopUp = null; label1.Text = "text&button is dismissed"; }; } void createProgressPopup() { _progressPopUp = new InformationPopup(); _progressPopUp.Title = "Popup title"; _progressPopUp.Text = "This is progress test"; _progressPopUp.IsProgressRunning = true; _progressPopUp.BackButtonPressed += (s, e) => { _progressPopUp?.Dismiss(); _progressPopUp = null; label1.Text = "progress is dismissed"; }; } private void OnTextButtonClicked(object sender, EventArgs e) { createTextPopup(); _textPopUp.Text = "This is text popup test"; _textPopUp.Show(); } private void OnLongTextButtonClicked(object sender, EventArgs e) { createTextPopup(); _textPopUp.Text = _longText; _textPopUp.Show(); } private void OnTitleTextButtonClicked(object sender, EventArgs e) { createTextButtonPopup(); _textButtonPopUp.Text = "This is text and button popup test"; _textButtonPopUp.BottomButton = _textBottomButton; _textButtonPopUp.Show(); } private void OnIconBottomButtonClicked(object sender, EventArgs e) { createTextButtonPopup(); _textButtonPopUp.Text = _longText; _textButtonPopUp.BottomButton = _iconBottomButton; _textButtonPopUp.Show(); } private void OnIconAndTextBottomButtonClicked(object sender, EventArgs e) { createTextButtonPopup(); _textButtonPopUp.Text = "This is text and button popup test"; _textButtonPopUp.BottomButton = _textIconBottomButton; _textButtonPopUp.Show(); } private void OnProcessButtonClicked(object sender, EventArgs e) { createProgressPopup(); _progressPopUp.Show(); Device.StartTimer(TimeSpan.FromMilliseconds(3000), () => { _progressPopUp?.SetValue(InformationPopup.TitleProperty, "Stopped Popup"); _progressPopUp?.SetValue(InformationPopup.TextProperty, "Progress is finished"); _progressPopUp?.SetValue(InformationPopup.IsProgressRunningProperty, false); _progressPopUp?.SetValue(InformationPopup.BottomButtonProperty, new MenuItem { Text = "Reset", Command = new Command(() => { _progressPopUp.Title = "Popup title"; _progressPopUp.Text = "This is progress test"; _progressPopUp.IsProgressRunning = true; _progressPopUp.BottomButton = null; }) }); return false; }); } private void OnProcessLongTextButtonClicked(object sender, EventArgs e) { createProgressPopup(); _progressPopUp.Text = @"This is scrollable popup text. This part is made by adding long text in popup.Popup internally added scroller to this layout when size of text is greater than total popup height.This has two button in action area and title text in title area"; _progressPopUp.Show(); } } }
34.492958
96
0.566626
[ "SHL-0.51" ]
hj-na-park/Tizen.CircularUI
test/WearableUIGallery/WearableUIGallery/TC/TCInformationPopup.xaml.cs
7,349
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Internal.Subscriptions.Models { using System; using System.Linq; using System.Collections.Generic; using Newtonsoft.Json; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Microsoft.Rest.Azure; /// <summary> /// Subscription policies. /// </summary> public partial class SubscriptionPolicies { /// <summary> /// Initializes a new instance of the SubscriptionPolicies class. /// </summary> public SubscriptionPolicies() { } /// <summary> /// Initializes a new instance of the SubscriptionPolicies class. /// </summary> public SubscriptionPolicies(string locationPlacementId = default(string), string quotaId = default(string), SpendingLimit? spendingLimit = default(SpendingLimit?)) { LocationPlacementId = locationPlacementId; QuotaId = quotaId; SpendingLimit = spendingLimit; } /// <summary> /// The subscription location placement ID. The ID indicates which /// regions are visible for a subscription. For example, a /// subscription with a location placement Id of Public_2014-09-01 /// has access to Azure public regions. /// </summary> [JsonProperty(PropertyName = "locationPlacementId")] public string LocationPlacementId { get; private set; } /// <summary> /// The subscription quota ID. /// </summary> [JsonProperty(PropertyName = "quotaId")] public string QuotaId { get; private set; } /// <summary> /// The subscription spending limit. Possible values include: 'On', /// 'Off', 'CurrentPeriodOff' /// </summary> [JsonProperty(PropertyName = "spendingLimit")] public SpendingLimit? SpendingLimit { get; private set; } } }
36.190476
172
0.626316
[ "MIT" ]
Azure/azure-powershell-common
src/ResourceManager/Version2016_09_01/Generated/Models/SubscriptionPolicies.cs
2,280
C#
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace Imager { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } } }
21.727273
65
0.596234
[ "MIT" ]
leonschrijvers/Imager
Source/Imager/Program.cs
480
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Общие сведения об этой сборке предоставляются следующим набором // набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения, // связанные со сборкой. [assembly: AssemblyTitle("Epam.Task.7.1.Users.DAL")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Epam.Task.7.1.Users.DAL")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми // для компонентов COM. Если необходимо обратиться к типу в этой сборке через // COM, задайте атрибуту ComVisible значение TRUE для этого типа. [assembly: ComVisible(false)] // Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM [assembly: Guid("bc36ce0d-9e7f-4c54-b7e6-65926e13bf32")] // Сведения о версии сборки состоят из следующих четырех значений: // // Основной номер версии // Дополнительный номер версии // Номер сборки // Редакция // // Можно задать все значения или принять номер сборки и номер редакции по умолчанию. // используя "*", как показано ниже: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.162162
99
0.760524
[ "MIT" ]
TimofeyRudometkin/XT-2018Q4
Epam.Task7/Epam.Task.7.1.Users.DAL/Properties/AssemblyInfo.cs
2,029
C#
using System; namespace TileDraw { [Flags] public enum Neighbour { None = 0, Left = 1, Top = 2, Right = 4, Bottom = 8, LeftTop = Left | Top, RightTop = Right | Top, LeftBottom = Left | Bottom, RightBottom = Right | Bottom } }
16.631579
36
0.477848
[ "MIT" ]
vassald2/Games2
Assets/TileDraw/Scripts/Util/Enums.cs
318
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Gov.Jag.Spice.Interfaces.Models { using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// Microsoft.Dynamics.CRM.import /// </summary> public partial class MicrosoftDynamicsCRMimport { /// <summary> /// Initializes a new instance of the MicrosoftDynamicsCRMimport class. /// </summary> public MicrosoftDynamicsCRMimport() { CustomInit(); } /// <summary> /// Initializes a new instance of the MicrosoftDynamicsCRMimport class. /// </summary> public MicrosoftDynamicsCRMimport(bool? sendnotification = default(bool?), string _createdonbehalfbyValue = default(string), System.DateTimeOffset? modifiedon = default(System.DateTimeOffset?), string _modifiedbyValue = default(string), string emailaddress = default(string), int? statecode = default(int?), string _modifiedonbehalfbyValue = default(string), string _owningbusinessunitValue = default(string), int? sequence = default(int?), int? statuscode = default(int?), string _owneridValue = default(string), string name = default(string), string _owninguserValue = default(string), System.DateTimeOffset? createdon = default(System.DateTimeOffset?), int? modecode = default(int?), string importid = default(string), string _owningteamValue = default(string), string _createdbyValue = default(string), MicrosoftDynamicsCRMsystemuser createdby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMteam owningteam = default(MicrosoftDynamicsCRMteam), MicrosoftDynamicsCRMsystemuser owninguser = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMsystemuser createdonbehalfby = default(MicrosoftDynamicsCRMsystemuser), IList<MicrosoftDynamicsCRMimportfile> importImportFile = default(IList<MicrosoftDynamicsCRMimportfile>), MicrosoftDynamicsCRMprincipal ownerid = default(MicrosoftDynamicsCRMprincipal), MicrosoftDynamicsCRMsystemuser modifiedonbehalfby = default(MicrosoftDynamicsCRMsystemuser), IList<MicrosoftDynamicsCRMbulkdeletefailure> importBulkDeleteFailures = default(IList<MicrosoftDynamicsCRMbulkdeletefailure>), MicrosoftDynamicsCRMbusinessunit owningbusinessunit = default(MicrosoftDynamicsCRMbusinessunit), MicrosoftDynamicsCRMsystemuser modifiedby = default(MicrosoftDynamicsCRMsystemuser), IList<MicrosoftDynamicsCRMasyncoperation> importAsyncOperations = default(IList<MicrosoftDynamicsCRMasyncoperation>)) { Sendnotification = sendnotification; this._createdonbehalfbyValue = _createdonbehalfbyValue; Modifiedon = modifiedon; this._modifiedbyValue = _modifiedbyValue; Emailaddress = emailaddress; Statecode = statecode; this._modifiedonbehalfbyValue = _modifiedonbehalfbyValue; this._owningbusinessunitValue = _owningbusinessunitValue; Sequence = sequence; Statuscode = statuscode; this._owneridValue = _owneridValue; Name = name; this._owninguserValue = _owninguserValue; Createdon = createdon; Modecode = modecode; Importid = importid; this._owningteamValue = _owningteamValue; this._createdbyValue = _createdbyValue; Createdby = createdby; Owningteam = owningteam; Owninguser = owninguser; Createdonbehalfby = createdonbehalfby; ImportImportFile = importImportFile; Ownerid = ownerid; Modifiedonbehalfby = modifiedonbehalfby; ImportBulkDeleteFailures = importBulkDeleteFailures; Owningbusinessunit = owningbusinessunit; Modifiedby = modifiedby; ImportAsyncOperations = importAsyncOperations; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// </summary> [JsonProperty(PropertyName = "sendnotification")] public bool? Sendnotification { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_createdonbehalfby_value")] public string _createdonbehalfbyValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "modifiedon")] public System.DateTimeOffset? Modifiedon { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_modifiedby_value")] public string _modifiedbyValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "emailaddress")] public string Emailaddress { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "statecode")] public int? Statecode { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_modifiedonbehalfby_value")] public string _modifiedonbehalfbyValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_owningbusinessunit_value")] public string _owningbusinessunitValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "sequence")] public int? Sequence { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "statuscode")] public int? Statuscode { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_ownerid_value")] public string _owneridValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_owninguser_value")] public string _owninguserValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "createdon")] public System.DateTimeOffset? Createdon { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "modecode")] public int? Modecode { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "importid")] public string Importid { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_owningteam_value")] public string _owningteamValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_createdby_value")] public string _createdbyValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "createdby")] public MicrosoftDynamicsCRMsystemuser Createdby { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "owningteam")] public MicrosoftDynamicsCRMteam Owningteam { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "owninguser")] public MicrosoftDynamicsCRMsystemuser Owninguser { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "createdonbehalfby")] public MicrosoftDynamicsCRMsystemuser Createdonbehalfby { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "Import_ImportFile")] public IList<MicrosoftDynamicsCRMimportfile> ImportImportFile { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "ownerid")] public MicrosoftDynamicsCRMprincipal Ownerid { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "modifiedonbehalfby")] public MicrosoftDynamicsCRMsystemuser Modifiedonbehalfby { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "Import_BulkDeleteFailures")] public IList<MicrosoftDynamicsCRMbulkdeletefailure> ImportBulkDeleteFailures { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "owningbusinessunit")] public MicrosoftDynamicsCRMbusinessunit Owningbusinessunit { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "modifiedby")] public MicrosoftDynamicsCRMsystemuser Modifiedby { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "Import_AsyncOperations")] public IList<MicrosoftDynamicsCRMasyncoperation> ImportAsyncOperations { get; set; } } }
41.643519
1,853
0.64458
[ "Apache-2.0" ]
BrendanBeachBC/jag-spd-spice
interfaces/Dynamics-Autorest/Models/MicrosoftDynamicsCRMimport.cs
8,995
C#
using System; namespace LeetCode.LeetAgain { public class ArrayPairSumSln : ISolution { public int ArrayPairSum(int[] nums) { //1. sort //2. sum odd index item Array.Sort(nums); int result = 0; for (int i = 0; i < nums.Length; i += 2) { result += nums[i]; } return result; } void QuickSort(int[] nums, int fromIndex, int toIndex) { if (fromIndex < toIndex) { //partion int pivotIndex = Partition(nums, fromIndex, toIndex); QuickSort(nums, fromIndex, pivotIndex - 1); QuickSort(nums, pivotIndex + 1, toIndex); } } int Partition(int[] nums, int left, int right) { int pivot = nums[left]; int l = left + 1; int r = right; while (l <= r) { if (nums[l] < pivot && nums[r] > pivot) Swap(nums, l--, r--); if (nums[l] >= pivot) l++; if (nums[r] <= pivot) r--; } Swap(nums, left, r); return r; } void Swap(int[] nums, int fromIndex, int toIndex) { int temp = nums[fromIndex]; nums[fromIndex] = nums[toIndex]; nums[toIndex] = temp; } public void Execute() { int[] arr = new[] { 1, 1 }; QuickSort(arr, 0, arr.Length - 1); } } }
24.90625
69
0.41468
[ "MIT" ]
YouenZeng/LeetCode
LeetCode/LeetAgain/ArrayPairSumSln.cs
1,596
C#
// Access failure exception class. // Copyright (C) 2009-2010 Lex Li // // 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. /* * Created by SharpDevelop. * User: lextm * Date: 11/28/2009 * Time: 7:41 PM * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Runtime.Serialization; namespace Lextm.SharpSnmpLib.Pipeline { /// <summary> /// Access failure exception. /// Raised when, /// 1. GET operation is performed on a write-only object. /// 2. SET operation is performed on a read-only object. /// </summary> [DataContract] public sealed class AccessFailureException : Exception { /// <summary> /// Creates a <see cref="AccessFailureException"/>. /// </summary> public AccessFailureException() { } /// <summary> /// Creates a <see cref="AccessFailureException"/> instance with a specific <see cref="String"/>. /// </summary> /// <param name="message">Message</param> public AccessFailureException(string message) : base(message) { } /// <summary> /// Creates a <see cref="AccessFailureException"/> instance with a specific <see cref="String"/> and an <see cref="Exception"/>. /// </summary> /// <param name="message">Message</param> /// <param name="inner">Inner exception</param> public AccessFailureException(string message, Exception inner) : base(message, inner) { } /// <summary> /// Creates a <see cref="AccessFailureException"/> instance. /// </summary> /// <param name="info">Info</param> /// <param name="context">Context</param> private AccessFailureException(SerializationInfo info, StreamingContext context) : base(info, context) { } /// <summary> /// Returns a <see cref="String"/> that represents this <see cref="AccessFailureException"/>. /// </summary> /// <returns></returns> public override string ToString() { return "AccessFailureException: " + Message; } } }
37.425287
136
0.641892
[ "MIT" ]
7amza123/azu
SharpSnmpLib/Pipeline/AccessFailureException.cs
3,258
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security; using Owin; using WebForm.Models; namespace WebForm.Account { public partial class Manage : System.Web.UI.Page { protected string SuccessMessage { get; private set; } private bool HasPassword(ApplicationUserManager manager) { return manager.HasPassword(User.Identity.GetUserId()); } public bool HasPhoneNumber { get; private set; } public bool TwoFactorEnabled { get; private set; } public bool TwoFactorBrowserRemembered { get; private set; } public int LoginsCount { get; set; } protected void Page_Load() { var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); HasPhoneNumber = String.IsNullOrEmpty(manager.GetPhoneNumber(User.Identity.GetUserId())); // Enable this after setting up two-factor authentientication //PhoneNumber.Text = manager.GetPhoneNumber(User.Identity.GetUserId()) ?? String.Empty; TwoFactorEnabled = manager.GetTwoFactorEnabled(User.Identity.GetUserId()); LoginsCount = manager.GetLogins(User.Identity.GetUserId()).Count; var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; if (!IsPostBack) { // Determine the sections to render if (HasPassword(manager)) { ChangePassword.Visible = true; } else { CreatePassword.Visible = true; ChangePassword.Visible = false; } // Render success message var message = Request.QueryString["m"]; if (message != null) { // Strip the query string from action Form.Action = ResolveUrl("~/Account/Manage"); SuccessMessage = message == "ChangePwdSuccess" ? "Your password has been changed." : message == "SetPwdSuccess" ? "Your password has been set." : message == "RemoveLoginSuccess" ? "The account was removed." : message == "AddPhoneNumberSuccess" ? "Phone number has been added" : message == "RemovePhoneNumberSuccess" ? "Phone number was removed" : String.Empty; successMessage.Visible = !String.IsNullOrEmpty(SuccessMessage); } } } private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError("", error); } } // Remove phonenumber from user protected void RemovePhone_Click(object sender, EventArgs e) { var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>(); var result = manager.SetPhoneNumber(User.Identity.GetUserId(), null); if (!result.Succeeded) { return; } var user = manager.FindById(User.Identity.GetUserId()); if (user != null) { signInManager.SignIn(user, isPersistent: false, rememberBrowser: false); Response.Redirect("/Account/Manage?m=RemovePhoneNumberSuccess"); } } // DisableTwoFactorAuthentication protected void TwoFactorDisable_Click(object sender, EventArgs e) { var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); manager.SetTwoFactorEnabled(User.Identity.GetUserId(), false); Response.Redirect("/Account/Manage"); } //EnableTwoFactorAuthentication protected void TwoFactorEnable_Click(object sender, EventArgs e) { var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); manager.SetTwoFactorEnabled(User.Identity.GetUserId(), true); Response.Redirect("/Account/Manage"); } } }
35.710938
101
0.583898
[ "MIT" ]
edsonaraujo1/WebForm
WebForm/WebForm/Account/Manage.aspx.cs
4,573
C#
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member namespace ConoHaNet.Services.Compute { using Newtonsoft.Json; using OpenStack.ObjectModel; using System; public class BackupService : ExtensibleJsonObject { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("instance_id")] public string InstanceId { get; set; } [JsonProperty("volume_id")] public string VolumeId { get; set; } [JsonProperty("created_at")] public DateTimeOffset CreatedAt { get; set; } [JsonProperty("backupruns")] public BackupRun[] BackupRuns { get; set; } } public class BackupRun : ExtensibleJsonObject { [JsonProperty("backuprun_id")] public string BackupRunId { get; set; } [JsonProperty("type")] public string Type { get; set; } [JsonProperty("status")] public string Status { get; set; } [JsonProperty("created_at")] public DateTimeOffset CreatedAt { get; set; } [JsonProperty("volume_id")] public string VolumeId { get; set; } } [JsonObject(MemberSerialization.OptIn)] public class ListBackupServicesResponse { [JsonProperty("backup", DefaultValueHandling = DefaultValueHandling.Include)] public BackupService[] BackupServices { get; set; } } [JsonObject(MemberSerialization.OptIn)] public class GetBackupServiceResponse { [JsonProperty("backup", DefaultValueHandling = DefaultValueHandling.Include)] public BackupService BackupServices { get; set; } } [JsonObject(MemberSerialization.OptIn)] internal class CreateImageFromBackupRunRequest { [JsonProperty("createImage")] public CreateImageFromBackupRunRequestDetails Details { get; private set; } public CreateImageFromBackupRunRequest(string backupRunId, string imageName = null) { Details = new CreateImageFromBackupRunRequestDetails(backupRunId, imageName); } [JsonObject(MemberSerialization.OptIn)] public class CreateImageFromBackupRunRequestDetails { [JsonProperty("backuprun_id")] public string BackupRunId { get; private set; } [JsonProperty("image_name")] public string ImageName { get; private set; } public CreateImageFromBackupRunRequestDetails(string backupRunId, string imageName = null) { BackupRunId = backupRunId; ImageName = imageName; } } } } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
31.709302
102
0.649065
[ "MIT" ]
crowdy/OpenStack-ConoHa
ConoHaNet.portable-net45/ConoHa/Services/Compute/BackupService.cs
2,729
C#
#if UNITY_EDITOR || UNITY_STANDALONE_OSX || UNITY_STANDALONE_WIN #define UNITY_PLATFORM_SUPPORTS_LINEAR #elif UNITY_IOS || UNITY_ANDROID #if UNITY_5_5_OR_NEWER || (UNITY_5 && !UNITY_5_0 && !UNITY_5_1 && !UNITY_5_2 && !UNITY_5_3 && !UNITY_5_4) #define UNITY_PLATFORM_SUPPORTS_LINEAR #endif #endif #if UNITY_5_4_OR_NEWER || (UNITY_5 && !UNITY_5_0) #define UNITY_HELPATTRIB #endif using UnityEngine; //----------------------------------------------------------------------------- // Copyright 2015-2020 RenderHeads Ltd. All rights reserved. //----------------------------------------------------------------------------- namespace RenderHeads.Media.AVProVideo { /// <summary> /// Sets up a material to display the video from a MediaPlayer /// </summary> [AddComponentMenu("AVPro Video/Apply To Material", 300)] #if UNITY_HELPATTRIB [HelpURL("http://renderheads.com/products/avpro-video/")] #endif public class ApplyToMaterial : MonoBehaviour { [Header("Media Source")] [Space(8f)] [SerializeField] MediaPlayer _media = null; public MediaPlayer Player { get { return _media; } set { ChangeMediaPlayer(value); } } [Tooltip("Default texture to display when the video texture is preparing")] [SerializeField] Texture2D _defaultTexture = null; public Texture2D DefaultTexture { get { return _defaultTexture; } set { if (_defaultTexture != value) { _defaultTexture = value; _isDirty = true; } } } [Space(8f)] [Header("Material Target")] [SerializeField] Material _material = null; public Material Material { get { return _material; } set { if (_material != value) { _material = value; _isDirty = true; } } } [SerializeField] string _texturePropertyName = "_MainTex"; public string TexturePropertyName { get { return _texturePropertyName; } set { if (_texturePropertyName != value) { _texturePropertyName = value; #if UNITY_5_6_OR_NEWER _propTexture = Shader.PropertyToID(_texturePropertyName); #endif _isDirty = true; } } } [SerializeField] Vector2 _offset = Vector2.zero; public Vector2 Offset { get { return _offset; } set { if (_offset != value) { _offset = value; _isDirty = true; } } } [SerializeField] Vector2 _scale = Vector2.one; public Vector2 Scale { get { return _scale; } set { if (_scale != value) { _scale = value; _isDirty = true; } } } private bool _isDirty = false; private Texture _lastTextureApplied; #if UNITY_5_6_OR_NEWER private int _propTexture; #endif private Texture _originalTexture; private Vector2 _originalScale = Vector2.one; private Vector2 _originalOffset = Vector2.zero; private static int _propStereo; private static int _propAlphaPack; private static int _propApplyGamma; private static int _propLayout; private static int _propCroppingScalars; private const string PropChromaTexName = "_ChromaTex"; private static int _propChromaTex; private const string PropYpCbCrTransformName = "_YpCbCrTransform"; private static int _propYpCbCrTransform; private const string PropUseYpCbCrName = "_UseYpCbCr"; private static int _propUseYpCbCr; private void Awake() { if (_propStereo == 0) { _propStereo = Shader.PropertyToID("Stereo"); } if (_propAlphaPack == 0) { _propAlphaPack = Shader.PropertyToID("AlphaPack"); } if (_propApplyGamma == 0) { _propApplyGamma = Shader.PropertyToID("_ApplyGamma"); } if (_propLayout == 0) { _propLayout = Shader.PropertyToID("Layout"); } if (_propChromaTex == 0) { _propChromaTex = Shader.PropertyToID(PropChromaTexName); } if (_propYpCbCrTransform == 0) { _propYpCbCrTransform = Shader.PropertyToID(PropYpCbCrTransformName); } if (_propUseYpCbCr == 0) { _propUseYpCbCr = Shader.PropertyToID(PropUseYpCbCrName); } if (_propCroppingScalars == 0) { _propCroppingScalars = Shader.PropertyToID("_CroppingScalars"); } if (_media != null) { _media.Events.AddListener(OnMediaPlayerEvent); } } private void ChangeMediaPlayer(MediaPlayer player) { if (_media != player) { if (_media != null) { _media.Events.RemoveListener(OnMediaPlayerEvent); } _media = player; if (_media != null) { _media.Events.AddListener(OnMediaPlayerEvent); } _isDirty = true; } } public void ForceUpdate() { _isDirty = true; LateUpdate(); } // Callback function to handle events private void OnMediaPlayerEvent(MediaPlayer mp, MediaPlayerEvent.EventType et, ErrorCode errorCode) { switch (et) { case MediaPlayerEvent.EventType.FirstFrameReady: case MediaPlayerEvent.EventType.PropertiesChanged: ForceUpdate(); break; } } // We do a LateUpdate() to allow for any changes in the texture that may have happened in Update() private void LateUpdate() { bool applied = false; if (_media != null && _media.TextureProducer != null) { Texture resamplerTex = _media.FrameResampler == null || _media.FrameResampler.OutputTexture == null ? null : _media.FrameResampler.OutputTexture[0]; Texture texture = _media.m_Resample ? resamplerTex : _media.TextureProducer.GetTexture(0); if (texture != null) { // Check for changing texture if (texture != _lastTextureApplied) { _isDirty = true; } if (_isDirty) { int planeCount = _media.m_Resample ? 1 : _media.TextureProducer.GetTextureCount(); for (int plane = 0; plane < planeCount; ++plane) { Texture resamplerTexPlane = _media.FrameResampler == null || _media.FrameResampler.OutputTexture == null ? null : _media.FrameResampler.OutputTexture[plane]; texture = _media.m_Resample ? resamplerTexPlane : _media.TextureProducer.GetTexture(plane); if (texture != null) { ApplyMapping(texture, _media.TextureProducer.RequiresVerticalFlip(), plane); } } } applied = true; } } // If the media didn't apply a texture, then try to apply the default texture if (!applied) { if (_defaultTexture != _lastTextureApplied) { _isDirty = true; } if (_isDirty) { if (_material != null && _material.HasProperty(_propUseYpCbCr)) { _material.DisableKeyword("USE_YPCBCR"); } ApplyMapping(_defaultTexture, false); } } } private void ApplyMapping(Texture texture, bool requiresYFlip, int plane = 0) { if (_material != null) { _isDirty = false; if (plane == 0) { if (string.IsNullOrEmpty(_texturePropertyName)) { _material.mainTexture = texture; _lastTextureApplied = texture; if (texture != null) { if (requiresYFlip) { _material.mainTextureScale = new Vector2(_scale.x, -_scale.y); _material.mainTextureOffset = Vector2.up + _offset; } else { _material.mainTextureScale = _scale; _material.mainTextureOffset = _offset; } } } else { #if UNITY_5_6_OR_NEWER _material.SetTexture(_propTexture, texture); #else _material.SetTexture(_texturePropertyName, texture); #endif _lastTextureApplied = texture; if (texture != null) { if (requiresYFlip) { _material.SetTextureScale(_texturePropertyName, new Vector2(_scale.x, -_scale.y)); _material.SetTextureOffset(_texturePropertyName, Vector2.up + _offset); } else { _material.SetTextureScale(_texturePropertyName, _scale); _material.SetTextureOffset(_texturePropertyName, _offset); } } } } else if (plane == 1) { if (_material.HasProperty(_propUseYpCbCr)) { _material.EnableKeyword("USE_YPCBCR"); } if (_material.HasProperty(_propChromaTex)) { _material.SetTexture(_propChromaTex, texture); _material.SetMatrix(_propYpCbCrTransform, _media.TextureProducer.GetYpCbCrTransform()); if (texture != null) { #if UNITY_5_6_OR_NEWER if (requiresYFlip) { _material.SetTextureScale(_propChromaTex, new Vector2(_scale.x, -_scale.y)); _material.SetTextureOffset(_propChromaTex, Vector2.up + _offset); } else { _material.SetTextureScale(_propChromaTex, _scale); _material.SetTextureOffset(_propChromaTex, _offset); } #else if (requiresYFlip) { _material.SetTextureScale(PropChromaTexName, new Vector2(_scale.x, -_scale.y)); _material.SetTextureOffset(PropChromaTexName, Vector2.up + _offset); } else { _material.SetTextureScale(PropChromaTexName, _scale); _material.SetTextureOffset(PropChromaTexName, _offset); } #endif } } } if (_media != null) { // Apply changes for layout if (_material.HasProperty(_propLayout)) { Helper.SetupLayoutMaterial(_material, _media.VideoLayoutMapping); } // Apply changes for stereo videos if (_material.HasProperty(_propStereo)) { Helper.SetupStereoMaterial(_material, _media.m_StereoPacking, _media.m_DisplayDebugStereoColorTint); } // Apply changes for alpha videos if (_material.HasProperty(_propAlphaPack)) { Helper.SetupAlphaPackedMaterial(_material, _media.m_AlphaPacking); } #if UNITY_PLATFORM_SUPPORTS_LINEAR // Apply gamma if (_material.HasProperty(_propApplyGamma) && _media.Info != null) { Helper.SetupGammaMaterial(_material, _media.Info.PlayerSupportsLinearColorSpace()); } #else _propApplyGamma |= 0; // Prevent compiler warning about unused variable #endif #if (!UNITY_EDITOR && UNITY_ANDROID) // Adjust for cropping (when the decoder decodes in blocks that overrun the video frame size, it pads), OES only as we apply this lower down for none-OES if (_media.PlatformOptionsAndroid.useFastOesPath && _media.Info != null && _material.HasProperty(_propCroppingScalars) ) { float[] transform = _media.Info.GetTextureTransform(); if (transform != null) { _material.SetVector(_propCroppingScalars, new Vector4(transform[0], transform[3], 1.0f, 1.0f)); } } #else _propCroppingScalars |= 0; // Prevent compiler warning about unused variable #endif } } } private void Start() { SaveProperties(); LateUpdate(); } private void OnEnable() { SaveProperties(); #if UNITY_5_6_OR_NEWER _propTexture = Shader.PropertyToID(_texturePropertyName); #endif _isDirty = true; LateUpdate(); } private void OnDisable() { RestoreProperties(); } private void SaveProperties() { if (_material != null) { if (string.IsNullOrEmpty(_texturePropertyName)) { _originalTexture = _material.mainTexture; _originalScale = _material.mainTextureScale; _originalOffset = _material.mainTextureOffset; } else { _originalTexture = _material.GetTexture(_texturePropertyName); _originalScale = _material.GetTextureScale(_texturePropertyName); _originalOffset = _material.GetTextureOffset(_texturePropertyName); } } } private void RestoreProperties() { if (_material != null) { if (string.IsNullOrEmpty(_texturePropertyName)) { _material.mainTexture = _originalTexture; _material.mainTextureScale = _originalScale; _material.mainTextureOffset = _originalOffset; } else { _material.SetTexture(_texturePropertyName, _originalTexture); _material.SetTextureScale(_texturePropertyName, _originalScale); _material.SetTextureOffset(_texturePropertyName, _originalOffset); } } } } }
26.636569
164
0.663305
[ "Apache-2.0" ]
takemurakimio/missing-part-1
Assets/AVProVideo/Scripts/Components/ApplyToMaterial.cs
11,800
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.ContainerRegistry.V20190601Preview.Inputs { /// <summary> /// The parameters for a quick task run request. /// </summary> public sealed class EncodedTaskRunRequestArgs : Pulumi.ResourceArgs { /// <summary> /// The machine configuration of the run agent. /// </summary> [Input("agentConfiguration")] public Input<Inputs.AgentPropertiesArgs>? AgentConfiguration { get; set; } /// <summary> /// The dedicated agent pool for the run. /// </summary> [Input("agentPoolName")] public Input<string>? AgentPoolName { get; set; } /// <summary> /// The properties that describes a set of credentials that will be used when this run is invoked. /// </summary> [Input("credentials")] public Input<Inputs.CredentialsArgs>? Credentials { get; set; } /// <summary> /// Base64 encoded value of the template/definition file content. /// </summary> [Input("encodedTaskContent", required: true)] public Input<string> EncodedTaskContent { get; set; } = null!; /// <summary> /// Base64 encoded value of the parameters/values file content. /// </summary> [Input("encodedValuesContent")] public Input<string>? EncodedValuesContent { get; set; } /// <summary> /// The value that indicates whether archiving is enabled for the run or not. /// </summary> [Input("isArchiveEnabled")] public Input<bool>? IsArchiveEnabled { get; set; } /// <summary> /// The template that describes the repository and tag information for run log artifact. /// </summary> [Input("logTemplate")] public Input<string>? LogTemplate { get; set; } /// <summary> /// The platform properties against which the run has to happen. /// </summary> [Input("platform", required: true)] public Input<Inputs.PlatformPropertiesArgs> Platform { get; set; } = null!; /// <summary> /// The URL(absolute or relative) of the source context. It can be an URL to a tar or git repository. /// If it is relative URL, the relative path should be obtained from calling listBuildSourceUploadUrl API. /// </summary> [Input("sourceLocation")] public Input<string>? SourceLocation { get; set; } /// <summary> /// Run timeout in seconds. /// </summary> [Input("timeout")] public Input<int>? Timeout { get; set; } /// <summary> /// The type of the run request. /// Expected value is 'EncodedTaskRunRequest'. /// </summary> [Input("type", required: true)] public Input<string> Type { get; set; } = null!; [Input("values")] private InputList<Inputs.SetValueArgs>? _values; /// <summary> /// The collection of overridable values that can be passed when running a task. /// </summary> public InputList<Inputs.SetValueArgs> Values { get => _values ?? (_values = new InputList<Inputs.SetValueArgs>()); set => _values = value; } public EncodedTaskRunRequestArgs() { IsArchiveEnabled = false; Timeout = 3600; } } }
35.114286
114
0.59642
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/ContainerRegistry/V20190601Preview/Inputs/EncodedTaskRunRequestArgs.cs
3,687
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/MsHTML.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows.IID; namespace TerraFX.Interop.Windows.UnitTests; /// <summary>Provides validation of the <see cref="DOMFocusEvent" /> struct.</summary> public static unsafe partial class DOMFocusEventTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="DOMFocusEvent" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(DOMFocusEvent).GUID, Is.EqualTo(IID_DOMFocusEvent)); } /// <summary>Validates that the <see cref="DOMFocusEvent" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<DOMFocusEvent>(), Is.EqualTo(sizeof(DOMFocusEvent))); } /// <summary>Validates that the <see cref="DOMFocusEvent" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(DOMFocusEvent).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="DOMFocusEvent" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(DOMFocusEvent), Is.EqualTo(1)); } }
36.227273
145
0.705144
[ "MIT" ]
IngmarBitter/terrafx.interop.windows
tests/Interop/Windows/Windows/um/MsHTML/DOMFocusEventTests.cs
1,596
C#
// // complete.cs: Expression that are used for completion suggestions. // // Author: // Miguel de Icaza (miguel@ximian.com) // Marek Safar (marek.safar@gmail.com) // // Copyright 2001, 2002, 2003 Ximian, Inc. // Copyright 2003-2009 Novell, Inc. // Copyright 2011 Xamarin Inc // // Completion* classes derive from ExpressionStatement as this allows // them to pass through the parser in many conditions that require // statements even when the expression is incomplete (for example // completing inside a lambda // using System.Collections.Generic; using System.Linq; namespace Mono.CSharp { // // A common base class for Completing expressions, it // is just a very simple ExpressionStatement // public abstract class CompletingExpression : ExpressionStatement { public static void AppendResults (List<string> results, string prefix, IEnumerable<string> names) { foreach (string name in names) { if (name == null) continue; if (prefix != null && !name.StartsWith (prefix)) continue; if (results.Contains (name)) continue; if (prefix != null) results.Add (name.Substring (prefix.Length)); else results.Add (name); } } public override bool ContainsEmitWithAwait () { return false; } public override Expression CreateExpressionTree (ResolveContext ec) { return null; } public override void EmitStatement (EmitContext ec) { // Do nothing } public override void Emit (EmitContext ec) { // Do nothing } } public class CompletionSimpleName : CompletingExpression { public string Prefix; public CompletionSimpleName (string prefix, Location l) { this.loc = l; this.Prefix = prefix; } protected override Expression DoResolve (ResolveContext ec) { var results = new List<string> (); AppendResults (results, Prefix, ec.Module.Evaluator.GetVarNames ()); AppendResults (results, Prefix, ec.CurrentMemberDefinition.Parent.NamespaceEntry.CompletionGetTypesStartingWith (Prefix)); AppendResults (results, Prefix, ec.Module.Evaluator.GetUsingList ()); throw new CompletionResult (Prefix, results.ToArray ()); } protected override void CloneTo (CloneContext clonectx, Expression t) { // Nothing } } public class CompletionMemberAccess : CompletingExpression { Expression expr; string partial_name; TypeArguments targs; public CompletionMemberAccess (Expression e, string partial_name, Location l) { this.expr = e; this.loc = l; this.partial_name = partial_name; } public CompletionMemberAccess (Expression e, string partial_name, TypeArguments targs, Location l) { this.expr = e; this.loc = l; this.partial_name = partial_name; this.targs = targs; } protected override Expression DoResolve (ResolveContext ec) { Expression expr_resolved = expr.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type); if (expr_resolved == null) return null; TypeSpec expr_type = expr_resolved.Type; if (expr_type.IsPointer || expr_type.Kind == MemberKind.Void || expr_type == InternalType.NullLiteral || expr_type == InternalType.AnonymousMethod) { Unary.Error_OperatorCannotBeApplied (ec, loc, ".", expr_type); return null; } if (targs != null) { if (!targs.Resolve (ec)) return null; } var results = new List<string> (); if (expr_resolved is Namespace){ Namespace nexpr = expr_resolved as Namespace; string namespaced_partial; if (partial_name == null) namespaced_partial = nexpr.Name; else namespaced_partial = nexpr.Name + "." + partial_name; #if false Console.WriteLine ("Workign with: namespaced partial {0}", namespaced_partial); foreach (var x in ec.TypeContainer.NamespaceEntry.CompletionGetTypesStartingWith (ec.TypeContainer, namespaced_partial)){ Console.WriteLine (" {0}", x); } #endif CompletionSimpleName.AppendResults ( results, partial_name, ec.CurrentMemberDefinition.Parent.NamespaceEntry.CompletionGetTypesStartingWith (namespaced_partial)); } else { var r = MemberCache.GetCompletitionMembers (ec, expr_type, partial_name).Select (l => l.Name); AppendResults (results, partial_name, r); } throw new CompletionResult (partial_name == null ? "" : partial_name, results.Distinct ().ToArray ()); } protected override void CloneTo (CloneContext clonectx, Expression t) { CompletionMemberAccess target = (CompletionMemberAccess) t; if (targs != null) target.targs = targs.Clone (); target.expr = expr.Clone (clonectx); } } public class CompletionElementInitializer : CompletingExpression { string partial_name; public CompletionElementInitializer (string partial_name, Location l) { this.partial_name = partial_name; this.loc = l; } protected override Expression DoResolve (ResolveContext ec) { var members = MemberCache.GetCompletitionMembers (ec, ec.CurrentInitializerVariable.Type, partial_name); // TODO: Does this mean exact match only ? // if (partial_name != null && results.Count > 0 && result [0] == "") // throw new CompletionResult ("", new string [] { "=" }); var results = members.Where (l => (l.Kind & (MemberKind.Field | MemberKind.Property)) != 0).Select (l => l.Name).ToList (); if (partial_name != null) { var temp = new List<string> (); AppendResults (temp, partial_name, results); results = temp; } throw new CompletionResult (partial_name == null ? "" : partial_name, results.Distinct ().ToArray ()); } protected override void CloneTo (CloneContext clonectx, Expression t) { // Nothing } } }
27.396135
152
0.700406
[ "Apache-2.0" ]
OpenPSS/psm-mono
mcs/mcs/complete.cs
5,671
C#
using System.Collections.Generic; using Microsoft.Extensions.DependencyInjection; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Neleus.DependencyInjection.Extensions.Tests { [TestClass] public class ServiceByNameFactoryTests { private ServiceCollection _container; [TestInitialize] public void Init() { _container = new Microsoft.Extensions.DependencyInjection.ServiceCollection(); } [TestMethod] public void ServiceByNameFactory_GetByName_ResolvesToAppropriateTypes() { _container.AddTransient<List<int>>(); _container.AddTransient<HashSet<int>>(); _container.AddByName<IEnumerable<int>>() .Add<List<int>>("list") .Add<HashSet<int>>("hashSet") .Build(); var serviceProvider = _container.BuildServiceProvider(); // direct resolution by calling GetByName var list = serviceProvider.GetService<IServiceByNameFactory<IEnumerable<int>>>() .GetByName("list"); var hashSet = serviceProvider.GetService<IServiceByNameFactory<IEnumerable<int>>>() .GetByName("hashSet"); Assert.AreEqual(typeof(List<int>), list.GetType()); Assert.AreEqual(typeof(HashSet<int>), hashSet.GetType()); } [TestMethod] public void ResolutionLogicInContainerRegistration_ResolvesToAppropriateTypes() { _container.AddTransient<List<int>>(); _container.AddTransient<HashSet<int>>(); _container.AddByName<IEnumerable<int>>() .Add<List<int>>("list") .Add<HashSet<int>>("hashSet") .Build(); //The named services are resolved by IoC container and the client is abstracted from the //dependency resolution _container.AddTransient<ClientA>(s => new ClientA(s.GetServiceByName<IEnumerable<int>>("list"))); _container.AddTransient<ClientB>(s => new ClientB(s.GetServiceByName<IEnumerable<int>>("hashSet"))); var serviceProvider = _container.BuildServiceProvider(); var a = serviceProvider.GetService<ClientA>(); var b = serviceProvider.GetService<ClientB>(); Assert.AreEqual(typeof(List<int>), a.Dependency.GetType()); Assert.AreEqual(typeof(HashSet<int>), b.Dependency.GetType()); } [TestMethod] public void ResolutionLogicInClient_ResolvesToAppropriateTypes() { _container.AddTransient<List<int>>(); _container.AddTransient<HashSet<int>>(); _container.AddByName<IEnumerable<int>>() .Add<List<int>>("list") .Add<HashSet<int>>("hashSet") .Build(); //The named service is resolved by the client itself _container.AddTransient<ClientZ>(); var serviceProvider = _container.BuildServiceProvider(); var z = serviceProvider.GetService<ClientZ>(); Assert.AreEqual(typeof(HashSet<int>), z.Dependency.GetType()); } [TestMethod] public void ServiceByNameFactory_GetByName_CaseInsensitive() { _container.AddTransient<List<int>>(); _container.AddTransient<HashSet<int>>(); _container.AddByName<IEnumerable<int>>(new NameBuilderSettings() { CaseInsensitiveNames = true }) .Add<List<int>>("list") .Add<HashSet<int>>("hashSet") .Build(); var serviceProvider = _container.BuildServiceProvider(); // direct resolution by calling GetByName var list = serviceProvider.GetService<IServiceByNameFactory<IEnumerable<int>>>() .GetByName("LiSt"); var hashSet = serviceProvider.GetService<IServiceByNameFactory<IEnumerable<int>>>() .GetByName("HASHSET"); Assert.AreEqual(typeof(List<int>), list.GetType()); Assert.AreEqual(typeof(HashSet<int>), hashSet.GetType()); } [TestMethod] public void ServiceByNameFactory_GetNames() { _container.AddTransient<List<int>>(); _container.AddTransient<HashSet<int>>(); _container.AddByName<IEnumerable<int>>(new NameBuilderSettings() { CaseInsensitiveNames = true }) .Add<List<int>>("list") .Add<HashSet<int>>("hashSet") .Build(); var serviceProvider = _container.BuildServiceProvider(); // allow to get each type var group = serviceProvider.GetService<IServiceByNameFactory<IEnumerable<int>>>(); foreach (var name in group.GetNames()) { var instance = group.GetByName(name); switch (name) { case "list": Assert.AreEqual(typeof(List<int>), instance.GetType()); break; case "hashSet": Assert.AreEqual(typeof(HashSet<int>), instance.GetType()); break; } } } } }
35.885906
112
0.576959
[ "MIT" ]
kevmoens/DependencyInjection.Extensions
Neleus.DependencyInjection.Extensions.Tests/ServiceByNameFactoryTests.cs
5,347
C#
using System.Windows.Controls; namespace StarryEyes.Views.WindowParts.Primitives { /// <summary> /// UsersList.xaml の相互作用ロジック /// </summary> public partial class UsersList : UserControl { public UsersList() { InitializeComponent(); } } }
19.933333
49
0.598662
[ "MIT" ]
karno/StarryEyes
StarryEyes/Views/WindowParts/Primitives/UsersList.xaml.cs
319
C#
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) using System; using System.Windows.Forms; using ICSharpCode.Core; using ICSharpCode.SharpDevelop; namespace ICSharpCode.XamlBinding.PowerToys.Commands { /// <summary> /// Description of RemoveUnneccessaryAttributesCommand /// </summary> public class RemoveUnnecessaryAttributesCommand : RemoveMarginCommand { protected override bool Refactor(ICSharpCode.SharpDevelop.Editor.ITextEditor editor, System.Xml.Linq.XDocument document) { RemoveRecursive(document.Root, "Margin"); RemoveRecursive(document.Root, "MinWidth"); RemoveRecursive(document.Root, "MinHeight"); return true; } } }
30.961538
122
0.775155
[ "MIT" ]
Plankankul/SharpDevelop-w-Framework
src/AddIns/BackendBindings/XamlBinding/XamlBinding/PowerToys/Commands/RemoveUnnecessaryAttributesCommand.cs
807
C#
// Instance generated by TankLibHelper.InstanceBuilder // ReSharper disable All namespace TankLib.STU.Types { [STUAttribute(0xBD8713E8)] public class STU_BD8713E8 : STU_15043B61 { [STUFieldAttribute(0x82165976, ReaderType = typeof(InlineInstanceFieldReader))] public STU_8823ADCD m_82165976; [STUFieldAttribute(0x801BC827, ReaderType = typeof(EmbeddedInstanceFieldReader))] public STU_95ECA8A6 m_801BC827; } }
32.571429
89
0.747807
[ "MIT" ]
Mike111177/OWLib
TankLib/STU/Types/STU_BD8713E8.cs
456
C#
namespace HelpFileMarkdownBuilder.Tests.Assembly1 { /// <summary> /// Public enumeration /// </summary> public enum PublicEnumeration { /// <summary> /// Public enumeration field 1 /// </summary> PublicEnumerationField1, /// <summary> /// Public enumeration field 2 /// </summary> PublicEnumerationField2 } }
21
50
0.561404
[ "MIT" ]
BastienPerdriau/HelpFileMarkdownBuilder
Tests/HelpFileMarkdownBuilder.Tests.Assembly1/PublicEnumeration.cs
401
C#
/* * OpenDoc_API-文档访问 * * API to access AnyShare 如有任何疑问,可到开发者社区提问:https://developers.aishu.cn # Authentication - 调用需要鉴权的API,必须将token放在HTTP header中:\"Authorization: Bearer ACCESS_TOKEN\" - 对于GET请求,除了将token放在HTTP header中,也可以将token放在URL query string中:\"tokenid=ACCESS_TOKEN\" * * The version of the OpenAPI document: 6.0.10 * * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = AnyShareSDK.Client.OpenAPIDateConverter; namespace AnyShareSDK.Model { /// <summary> /// 文档相关信息和下次请求的边界值 /// </summary> [DataContract] public partial class SearchSearchResResponse : IEquatable<SearchSearchResResponse>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="SearchSearchResResponse" /> class. /// </summary> [JsonConstructorAttribute] protected SearchSearchResResponse() { } /// <summary> /// Initializes a new instance of the <see cref="SearchSearchResResponse" /> class. /// </summary> /// <param name="next">返回下次发起请求的start (required).</param> /// <param name="docs">返回各个文档的信息 (required).</param> /// <param name="hits">返回检索命中总数(查询第一页时返回).</param> public SearchSearchResResponse(string next = default(string), List<SearchSearchResResponseDoc> docs = default(List<SearchSearchResResponseDoc>), long? hits = default(long?)) { this.Next = next; this.Docs = docs; this.Hits = hits; } /// <summary> /// 返回下次发起请求的start /// </summary> /// <value>返回下次发起请求的start</value> [DataMember(Name="next", EmitDefaultValue=false)] public string Next { get; set; } /// <summary> /// 返回各个文档的信息 /// </summary> /// <value>返回各个文档的信息</value> [DataMember(Name="docs", EmitDefaultValue=false)] public List<SearchSearchResResponseDoc> Docs { get; set; } /// <summary> /// 返回检索命中总数(查询第一页时返回) /// </summary> /// <value>返回检索命中总数(查询第一页时返回)</value> [DataMember(Name="hits", EmitDefaultValue=false)] public long? Hits { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class SearchSearchResResponse {\n"); sb.Append(" Next: ").Append(Next).Append("\n"); sb.Append(" Docs: ").Append(Docs).Append("\n"); sb.Append(" Hits: ").Append(Hits).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as SearchSearchResResponse); } /// <summary> /// Returns true if SearchSearchResResponse instances are equal /// </summary> /// <param name="input">Instance of SearchSearchResResponse to be compared</param> /// <returns>Boolean</returns> public bool Equals(SearchSearchResResponse input) { if (input == null) return false; return ( this.Next == input.Next || (this.Next != null && this.Next.Equals(input.Next)) ) && ( this.Docs == input.Docs || this.Docs != null && input.Docs != null && this.Docs.SequenceEqual(input.Docs) ) && ( this.Hits == input.Hits || (this.Hits != null && this.Hits.Equals(input.Hits)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Next != null) hashCode = hashCode * 59 + this.Next.GetHashCode(); if (this.Docs != null) hashCode = hashCode * 59 + this.Docs.GetHashCode(); if (this.Hits != null) hashCode = hashCode * 59 + this.Hits.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
35.253012
257
0.560492
[ "MIT" ]
ArtyDinosaur404/AnyShareSDK
AnyShareSDK/Model/SearchSearchResResponse.cs
6,210
C#
using APS_6.Domain.Entities; using APS_6.Domain.Interfaces.Services; using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace APS.Client.PropertyForms { public partial class frmConsultProperty : Form { private IRuralPropertyService _propertyService; private Guid _propertyId; private IEnumerable<RuralProperty> _propertiesList; public frmConsultProperty(IRuralPropertyService propertyService) { InitializeComponent(); _propertyService = propertyService; } private void frmConsultProperty_Load(object sender, EventArgs e) { UpdateGrid(); } private void UpdateGrid() { _propertiesList = _propertyService.GetAllRuralProperty(); dgvProperties.DataSource = _propertiesList; } private void dgvProperties_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex >= 0) { var row = dgvProperties.Rows [e.RowIndex]; txtName.Text = row.Cells [0].Value.ToString(); txtCity.Text = row.Cells [5].Value.ToString(); txtDistrict.Text = row.Cells [3].Value.ToString(); txtNumber.Text = row.Cells [2].Value.ToString(); txtState.Text = row.Cells [6].Value.ToString(); txtStreet.Text = row.Cells [1].Value.ToString(); mtbCep.Text = row.Cells [4].Value.ToString(); Guid.TryParse(row.Cells [9].Value.ToString(), out _propertyId); var selectedProperty = _propertiesList.FirstOrDefault(p => p.Id == _propertyId); dgvTickets.DataSource = selectedProperty.Tickets; dgvPesticides.DataSource = selectedProperty.PesticideRuralProperties.Select(p => p.Pesticide); } } } }
36.396226
110
0.618455
[ "MIT" ]
FelipeAlves99/APS_6_Semestre
src/APS.Client/PropertyForms/frmConsultProperty.cs
1,931
C#
// Copyright (c) Amer Koleci and contributors. // Distributed under the MIT license. See the LICENSE file in the project root for more information. using System; using System.IO; using SharpGen.Runtime; using SharpGen.Runtime.Win32; using Vortice.Win32; namespace Vortice.WIC { public partial class IWICImagingFactory { public IWICImagingFactory() { ComUtilities.CreateComInstance( WICImagingFactoryClsid, ComContext.InprocServer, typeof(IWICImagingFactory).GUID, this); } /// <summary> /// Create new unitialized <see cref="IWICStream"/> instance. /// </summary> /// <returns>New instance of <see cref="IWICStream"/>.</returns> public IWICStream CreateStream() => CreateStream_(); /// <summary> /// Create a <see cref="IWICStream"/> from file name. /// </summary> /// <param name="fileName">The file name.</param> /// <param name="access">The <see cref="FileAccess"/> mode.</param> /// <returns>New instance of <see cref="IWICStream"/> or throws exception.</returns> public IWICStream CreateStream(string fileName, FileAccess access) { var stream = CreateStream_(); stream.Initialize(fileName, access); return stream; } /// <summary> /// Create a <see cref="IWICStream"/> from another stream. Access rights are inherited from the underlying stream /// </summary> /// <param name="comStream">The initialize stream.</param> /// <returns>New instance of <see cref="IWICStream"/> or throws exception.</returns> public IWICStream CreateStream(IStream comStream) { var stream = CreateStream_(); stream.Initialize(comStream); return stream; } /// <summary> /// Create a <see cref="IWICStream"/> from another stream. Access rights are inherited from the underlying stream /// </summary> /// <param name="stream">The initialize stream.</param> /// <returns>New instance of <see cref="IWICStream"/> or throws exception.</returns> public IWICStream CreateStream(Stream stream) { var wicStream = CreateStream_(); wicStream.Initialize(stream); return wicStream; } /// <summary> /// Create a <see cref="IWICStream"/> from given data. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="data">Data to initialize with.</param> /// <returns>New instance of <see cref="IWICStream"/> or throws exception.</returns> public IWICStream CreateStream<T>(T[] data) where T : unmanaged { var wicStream = CreateStream_(); wicStream.Initialize(data); return wicStream; } public IWICBitmap CreateBitmap(int width, int height, Guid pixelFormatGuid, BitmapCreateCacheOption option = BitmapCreateCacheOption.CacheOnLoad) { return CreateBitmap_(width, height, pixelFormatGuid, option); } public IWICBitmapEncoder CreateEncoder(Guid guidContainerFormat) { var encoder = CreateEncoder_(guidContainerFormat, null); encoder._factory = this; return encoder; } public IWICBitmapEncoder CreateEncoder(ContainerFormat format, Guid? guidVendor = null) { IWICBitmapEncoder encoder; switch (format) { case ContainerFormat.Bmp: encoder = CreateEncoder_(ContainerFormatGuids.Bmp, guidVendor); break; case ContainerFormat.Png: encoder = CreateEncoder_(ContainerFormatGuids.Png, guidVendor); break; case ContainerFormat.Ico: encoder = CreateEncoder_(ContainerFormatGuids.Ico, guidVendor); break; case ContainerFormat.Jpeg: encoder = CreateEncoder_(ContainerFormatGuids.Jpeg, guidVendor); break; case ContainerFormat.Tiff: encoder = CreateEncoder_(ContainerFormatGuids.Tiff, guidVendor); break; case ContainerFormat.Gif: encoder = CreateEncoder_(ContainerFormatGuids.Gif, guidVendor); break; case ContainerFormat.Wmp: encoder = CreateEncoder_(ContainerFormatGuids.Wmp, guidVendor); break; case ContainerFormat.Dds: encoder = CreateEncoder_(ContainerFormatGuids.Dds, guidVendor); break; case ContainerFormat.Adng: encoder = CreateEncoder_(ContainerFormatGuids.Adng, guidVendor); break; case ContainerFormat.Heif: encoder = CreateEncoder_(ContainerFormatGuids.Heif, guidVendor); break; case ContainerFormat.Webp: encoder = CreateEncoder_(ContainerFormatGuids.Webp, guidVendor); break; default: return null; } encoder._factory = this; return encoder; } public IWICBitmapEncoder CreateEncoder(Guid guidContainerFormat, IStream stream, BitmapEncoderCacheOption cacheOption = BitmapEncoderCacheOption.NoCache) { var encoder = CreateEncoder_(guidContainerFormat, null); encoder._factory = this; encoder.Initialize(stream, cacheOption); return encoder; } public IWICBitmapEncoder CreateEncoder(ContainerFormat format, IStream stream, BitmapEncoderCacheOption cacheOption = BitmapEncoderCacheOption.NoCache) { var encoder = CreateEncoder(format, null); encoder.Initialize(stream, cacheOption); return encoder; } public IWICBitmapEncoder CreateEncoder(ContainerFormat format, Guid guidVendor, IStream stream, BitmapEncoderCacheOption cacheOption = BitmapEncoderCacheOption.NoCache) { var encoder = CreateEncoder(format, guidVendor); encoder.Initialize(stream, cacheOption); return encoder; } public IWICBitmapEncoder CreateEncoder(Guid guidContainerFormat, Stream stream, BitmapEncoderCacheOption cacheOption = BitmapEncoderCacheOption.NoCache) { var encoder = CreateEncoder_(guidContainerFormat, null); encoder._factory = this; encoder.Initialize(stream, cacheOption); return encoder; } public IWICBitmapEncoder CreateEncoder(ContainerFormat format, Stream stream, BitmapEncoderCacheOption cacheOption = BitmapEncoderCacheOption.NoCache) { var encoder = CreateEncoder(format, null); encoder.Initialize(stream, cacheOption); return encoder; } public IWICBitmapEncoder CreateEncoder(ContainerFormat format, Guid guidVendor, Stream stream, BitmapEncoderCacheOption cacheOption = BitmapEncoderCacheOption.NoCache) { var encoder = CreateEncoder(format, guidVendor); encoder.Initialize(stream, cacheOption); return encoder; } public IWICBitmapDecoder CreateDecoderFromStream(IStream stream, DecodeOptions metadataOptions = DecodeOptions.CacheOnDemand) { return CreateDecoderFromStream_(stream, null, metadataOptions); } public IWICBitmapDecoder CreateDecoderFromStream(IStream stream, Guid vendor, DecodeOptions metadataOptions = DecodeOptions.CacheOnDemand) { return CreateDecoderFromStream_(stream, vendor, metadataOptions); } public IWICBitmapDecoder CreateDecoderFromStream(Stream stream, DecodeOptions metadataOptions = DecodeOptions.CacheOnDemand) { var wicStream = CreateStream(stream); var decoder = CreateDecoderFromStream_(wicStream, null, metadataOptions); decoder._wicStream = wicStream; return decoder; } public IWICBitmapDecoder CreateDecoderFromStream(Stream stream, Guid vendor, DecodeOptions metadataOptions = DecodeOptions.CacheOnDemand) { var wicStream = CreateStream(stream); var decoder = CreateDecoderFromStream_(wicStream, vendor, metadataOptions); decoder._wicStream = wicStream; return decoder; } public IWICBitmapDecoder CreateDecoderFromFilename(string fileName, DecodeOptions metadataOptions) { return CreateDecoderFromFilename(fileName, null, FileAccess.Read, metadataOptions); } public IWICBitmapDecoder CreateDecoderFromFilename( string fileName, FileAccess desiredAccess, DecodeOptions metadataOptions) { return CreateDecoderFromFilename(fileName, null, desiredAccess, metadataOptions); } public IWICBitmapDecoder CreateDecoderFromFilename(string fileName, Guid? guidVendor, FileAccess desiredAccess, DecodeOptions metadataOptions) { var nativeAccess = desiredAccess.ToNative(); return CreateDecoderFromFilename_(fileName, guidVendor, (int)nativeAccess, metadataOptions); } } }
42.096916
176
0.623064
[ "MIT" ]
DanielElam/Vortice.Windows
src/Vortice.Direct2D1/WIC/IWICImagingFactory.cs
9,556
C#
using AutoMapper; using ManagerCV.Authorization.Users; namespace ManagerCV.Users.Dto { public class UserMapProfile : Profile { public UserMapProfile() { CreateMap<UserDto, User>(); CreateMap<UserDto, User>() .ForMember(x => x.Roles, opt => opt.Ignore()) .ForMember(x => x.CreationTime, opt => opt.Ignore()); CreateMap<CreateUserDto, User>(); CreateMap<CreateUserDto, User>().ForMember(x => x.Roles, opt => opt.Ignore()); } } }
27.3
90
0.564103
[ "MIT" ]
trinhtri/tin_dung
aspnet-core/src/ManagerCV.Application/Users/Dto/UserMapProfile.cs
548
C#
using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Abp.Application.Services.Dto; using Abp.AspNetCore.Mvc.Authorization; using ModularTodoApp.Authorization; using ModularTodoApp.Controllers; using ModularTodoApp.Users; using ModularTodoApp.Web.Models.Users; using ModularTodoApp.Users.Dto; namespace ModularTodoApp.Web.Controllers { [AbpMvcAuthorize(PermissionNames.Pages_Users)] public class UsersController : ModularTodoAppControllerBase { private readonly IUserAppService _userAppService; public UsersController(IUserAppService userAppService) { _userAppService = userAppService; } public async Task<ActionResult> Index() { var users = (await _userAppService.GetAll(new PagedUserResultRequestDto {MaxResultCount = int.MaxValue})).Items; // Paging not implemented yet var roles = (await _userAppService.GetRoles()).Items; var model = new UserListViewModel { Users = users, Roles = roles }; return View(model); } public async Task<ActionResult> EditUserModal(long userId) { var user = await _userAppService.Get(new EntityDto<long>(userId)); var roles = (await _userAppService.GetRoles()).Items; var model = new EditUserModalViewModel { User = user, Roles = roles }; return View("_EditUserModal", model); } } }
32.270833
154
0.640413
[ "MIT" ]
aspnetboilerplate/modular-todo-app
src/ModularTodoApp.Web.Mvc/Controllers/UsersController.cs
1,551
C#
namespace TeaTime.Slack.Commands { using System.Threading.Tasks; using CommandRouter.Attributes; using CommandRouter.Results; using Common.Abstractions; using Common.Features.RoomItemGroups.Commands; using Common.Features.RoomItemGroups.Queries; using MediatR; using Models.Responses; using Resources; using Services; [CommandPrefix("groups")] public class GroupsCommand : BaseCommand { private readonly IMediator _mediator; private readonly IIdGenerator<long> _idGenerator; public GroupsCommand(ISlackService slackService, IMediator mediator, IIdGenerator<long> idGenerator) : base(slackService) { _mediator = mediator; _idGenerator = idGenerator; } [Command("add")] public async Task<ICommandResult> AddGroup(string name) { var context = await GetContextAsync().ConfigureAwait(false); var command = new CreateRoomItemGroupCommand( id: await _idGenerator.GenerateAsync().ConfigureAwait(false), roomId: context.Room.Id, name: name, userId: context.User.Id ); await _mediator.Send(command).ConfigureAwait(false); return Response(ResponseStrings.GroupAdded(name), ResponseType.User); } [Command("remove")] public async Task<ICommandResult> RemoveGroup(string name) { if (string.IsNullOrWhiteSpace(name)) return Response(ErrorStrings.RemoveGroup_BadArguments(), ResponseType.User); var context = await GetContextAsync().ConfigureAwait(false); var group = await _mediator.Send(new GetRoomItemGroupByNameQuery(context.Room.Id, context.User.Id, name)).ConfigureAwait(false); if(group == null) return Response(ErrorStrings.RemoveGroup_GroupInvalidName(name), ResponseType.User); var command = new DeleteRoomItemGroupCommand( groupId: group.Id, userId: context.User.Id ); await _mediator.Send(command).ConfigureAwait(false); return Response(ResponseStrings.GroupRemoved(name), ResponseType.User); } } }
35
140
0.643516
[ "MIT" ]
MrSmoke/TeaTime
src/TeaTime.Slack/Commands/GroupsCommand.cs
2,277
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Cactus.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
35.193548
152
0.563703
[ "Apache-2.0" ]
fearedbliss/Cactus-Core
Cactus/Properties/Settings.Designer.cs
1,093
C#
using System; using System.Diagnostics; using System.Drawing; using System.Runtime.InteropServices; using System.Threading; using System.Windows.Forms; using Boxd.Domain.Box; using Boxd.Domain.Box.Host; using Boxd.Domain.Box.Host.State; namespace Boxd.Windows.Adapter.Host.WinForms { public partial class Win32BoxHost : WindowsBoxFrame { private const int SW_MAXIMIZE = 3; public Panel panel; public static int GWL_STYLE = -16; public static int WS_CHILD = 0x40000000; //child window public static int WS_BORDER = 0x00800000; //window with border public static int WS_DLGFRAME = 0x00400000; //window with double border but no title public static int WS_CAPTION = WS_BORDER | WS_DLGFRAME; //window with a title bar public Win32BoxHost() { this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(800, 450); this.Text = "WinFormsNativeWindowHost"; this.panel = new Panel(); panel.Dock = DockStyle.Fill; panel.Top = _titleBrowser.Height; panel.Left = 2; panel.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom; panel.Width = this.Width - (2 * 2); // panel.Height = this._titleBrowser.Height - 2; panel.Height = 300; this.Controls.Add( panel); ProcessStartInfo psi = new ProcessStartInfo("notepad.exe"); psi.WindowStyle = ProcessWindowStyle.Minimized; psi.UseShellExecute = true; psi.CreateNoWindow = true; Process p = Process.Start(psi); Thread.Sleep(1000); panel.Resize += (sender, args) => { MoveWindow(p.MainWindowHandle, 0, 0, panel.Width, panel.Height, true); }; SetParent(p.MainWindowHandle, panel.Handle); const int GWL_STYLE = (-16); const UInt32 WS_VISIBLE = 0x10000000; SetWindowLong(p.MainWindowHandle, GWL_STYLE, (WS_VISIBLE)); ShowWindow(p.MainWindowHandle, SW_MAXIMIZE); } protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; cp.Style |= 0x20000; // <--- use 0x20000 return cp; } } protected override void WndProc(ref Message m) { const int RESIZE_HANDLE_SIZE = 10; switch (m.Msg) { case 0x0084 /*NCHITTEST*/: base.WndProc(ref m); if ((int)m.Result == 0x01 /*HTCLIENT*/) { Point screenPoint = new Point(m.LParam.ToInt32()); Point clientPoint = this.PointToClient(screenPoint); if (clientPoint.Y <= RESIZE_HANDLE_SIZE) { if (clientPoint.X <= RESIZE_HANDLE_SIZE) m.Result = (IntPtr)13 /*HTTOPLEFT*/; else if (clientPoint.X < (Size.Width - RESIZE_HANDLE_SIZE)) m.Result = (IntPtr)12 /*HTTOP*/; else m.Result = (IntPtr)14 /*HTTOPRIGHT*/; } else if (clientPoint.Y <= (Size.Height - RESIZE_HANDLE_SIZE)) { if (clientPoint.X <= RESIZE_HANDLE_SIZE) m.Result = (IntPtr)10 /*HTLEFT*/; else if (clientPoint.X < (Size.Width - RESIZE_HANDLE_SIZE)) m.Result = (IntPtr)2 /*HTCAPTION*/; else m.Result = (IntPtr)11 /*HTRIGHT*/; } else { if (clientPoint.X <= RESIZE_HANDLE_SIZE) m.Result = (IntPtr)16 /*HTBOTTOMLEFT*/; else if (clientPoint.X < (Size.Width - RESIZE_HANDLE_SIZE)) m.Result = (IntPtr)15 /*HTBOTTOM*/; else m.Result = (IntPtr)17 /*HTBOTTOMRIGHT*/; } } return; } base.WndProc(ref m); } [DllImport("user32.dll")] static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); //Sets window attributes [DllImport("USER32.DLL")] public static extern int SetWindowLong(IntPtr hWnd, int nIndex, uint dwNewLong); [DllImport("user32.dll", SetLastError = true)] public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint); } }
37.814286
112
0.501322
[ "MIT" ]
armunro/boxd
src/Boxd.Windows/Adapter/Host/WinForms/Win32BoxHost.cs
5,294
C#
using System.Linq; using Microsoft.AspNet.Authorization; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Mvc; using Microsoft.Framework.DependencyInjection; namespace security { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(); // OPTIONAL: Use a custom authorization handler to implement resource-based // authorization in the application. // services.AddTransient<IAuthorizationHandler,AdminUserHandler>(); // The authorization for the application is defined in a number of policies. // Each policy defines what the user has to comply to in order to get access. services.AddAuthorization(authorization => { authorization.AddPolicy("Anonymous", policy => policy.RequireDelegate((context,requirement) => { // When none of the identities are authenticated the user is anonymous. // So the requirement was succesful. if(context.User.Identities.All(identity => !identity.IsAuthenticated)) { context.Succeed(requirement); } else { context.Fail(); } })); authorization.AddPolicy("Authenticated", policy => policy.RequireAuthenticatedUser()); }); services.AddMvc(); } public void Configure(IApplicationBuilder app) { app.UseErrorPage(); // Allow users to log on using a username + password. // The authentication ticket is stored in a cookie. app.UseCookieAuthentication(options => { options.AutomaticAuthentication = true; options.LoginPath = "/Account/Logon"; options.LogoutPath = "/Account/Logoff"; }); app.UseMvc(routes => { routes.MapRoute("DefaultRoute", "{controller}/{action}/{id?}", new { controller = "Home", action = "Index"}); }); } } }
38.576271
113
0.54833
[ "Apache-2.0" ]
wmeints/aspnet-demo
security/Startup.cs
2,276
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection.Emit; using System.Reflection; using System.Text; using System.Threading.Tasks; using SyZero.Client; namespace SyZero.Feign { public class FeignProxyBuilder : IFeignProxyBuilder { public static Dictionary<string, MethodInfo> MethodsCache { get; set; } = new Dictionary<string, MethodInfo>(); private Type targetType; private static ConcurrentDictionary<string, Type> TargetTypeCache { set; get; } = new ConcurrentDictionary<string, Type>(); public object Build(Type interfaceType, params object[] constructor) { var cacheKey = interfaceType.FullName; var resultType = TargetTypeCache.GetOrAdd(cacheKey, (s) => BuildTargetType(interfaceType, constructor)); var result = Activator.CreateInstance(resultType, args: constructor); return result; } /// <summary> /// 动态生成接口的实现类 /// </summary> /// <param name="interfaceType"></param> /// <param name="constructor"></param> /// <returns></returns> private Type BuildTargetType(Type interfaceType, params object[] constructor) { targetType = interfaceType; string assemblyName = targetType.Name + "ProxyAssembly"; string moduleName = targetType.Name + "ProxyModule"; string typeName = targetType.Name + "Proxy"; AssemblyName assyName = new AssemblyName(assemblyName); AssemblyBuilder assyBuilder = AssemblyBuilder.DefineDynamicAssembly(assyName, AssemblyBuilderAccess.Run); ModuleBuilder modBuilder = assyBuilder.DefineDynamicModule(moduleName); //新类型的属性 TypeAttributes newTypeAttribute = TypeAttributes.Class | TypeAttributes.Public; //父类型 Type parentType; //要实现的接口 Type[] interfaceTypes; if (targetType.IsInterface) { parentType = typeof(object); interfaceTypes = new Type[] { targetType }; } else { parentType = targetType; interfaceTypes = Type.EmptyTypes; } //得到类型生成器 TypeBuilder typeBuilder = modBuilder.DefineType(typeName, newTypeAttribute, parentType, interfaceTypes); //定义一个字段存放httpService var httpType = typeof(IClient); FieldBuilder httpServiceField = typeBuilder.DefineField("httpService", httpType, FieldAttributes.Public); //定义一个字段存放IServiceProvider var iServiceProviderType = typeof(IServiceProvider); FieldBuilder serviceProviderField = typeBuilder.DefineField("iServiceProvider", iServiceProviderType, FieldAttributes.Public); //定义一个集合存放参数集合 FieldBuilder paramterArrField = typeBuilder.DefineField("paramterArr", typeof(List<object>), FieldAttributes.Public); //创建构造函数 ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { httpType, iServiceProviderType }); //il创建构造函数,对httpService和IServiceProvider两个字段进行赋值,同时初始化存放参数的集合 ILGenerator ilgCtor = constructorBuilder.GetILGenerator(); ilgCtor.Emit(OpCodes.Ldarg_0); //加载当前类 ilgCtor.Emit(OpCodes.Ldarg_1); ilgCtor.Emit(OpCodes.Stfld, httpServiceField); ilgCtor.Emit(OpCodes.Ldarg_0); //加载当前类 ilgCtor.Emit(OpCodes.Ldarg_2); ilgCtor.Emit(OpCodes.Stfld, serviceProviderField); ilgCtor.Emit(OpCodes.Ldarg_0); //加载当前类 ilgCtor.Emit(OpCodes.Newobj, typeof(List<object>).GetConstructors().First()); ilgCtor.Emit(OpCodes.Stfld, paramterArrField); ilgCtor.Emit(OpCodes.Ret); //返回 MethodInfo[] targetMethods = targetType.GetMethods(); foreach (MethodInfo targetMethod in targetMethods) { //只挑出virtual的方法 if (targetMethod.IsVirtual) { //缓存接口的方法体,便于后续将方法体传递给httpService string methodKey = Guid.NewGuid().ToString(); MethodsCache[methodKey] = targetMethod; //得到方法的各个参数的类型和参数 var paramInfo = targetMethod.GetParameters(); var parameterType = paramInfo.Select(it => it.ParameterType).ToArray(); var returnType = targetMethod.ReturnType; //方法返回值只能是task,即只支持异步,因为http操作是io操作 if (!typeof(Task).IsAssignableFrom(returnType)) throw new Exception("return type must be task<>"); var underType = returnType.IsGenericType ? returnType.GetGenericArguments().First() : returnType; //通过emit生成方法体 MethodBuilder methodBuilder = typeBuilder.DefineMethod(targetMethod.Name, MethodAttributes.Public | MethodAttributes.Virtual, targetMethod.ReturnType, parameterType); ILGenerator ilGen = methodBuilder.GetILGenerator(); MethodInfo executeMethod = null; var methodTmp = httpType.GetMethod("ExecuteAsync"); if (methodTmp == null) throw new Exception("找不到执行方法"); executeMethod = methodTmp.IsGenericMethod ? methodTmp.MakeGenericMethod(underType) : methodTmp; // 栈底放这玩意,加载字段前要加载类实例,即Ldarg_0 ilGen.Emit(OpCodes.Ldarg_0); ilGen.Emit(OpCodes.Ldfld, httpServiceField); //把所有参数都放到list<object>里 ilGen.Emit(OpCodes.Ldarg_0); ilGen.Emit(OpCodes.Ldfld, paramterArrField); for (int i = 0; i < parameterType.Length; i++) { ilGen.Emit(OpCodes.Dup); ilGen.Emit(OpCodes.Ldarg_S, i + 1); if (parameterType[i].IsValueType) { ilGen.Emit(OpCodes.Box, parameterType[i]); } ilGen.Emit(OpCodes.Callvirt, typeof(List<object>).GetMethod("Add")); } // 当前栈[httpServiceField paramterArrField] //从缓存里取出方法体 ilGen.Emit(OpCodes.Call, typeof(FeignProxyBuilder).GetMethod("get_MethodsCache", BindingFlags.Static | BindingFlags.Public)); ilGen.Emit(OpCodes.Ldstr, methodKey); ilGen.Emit(OpCodes.Call, typeof(Dictionary<string, MethodInfo>).GetMethod("get_Item")); ilGen.Emit(OpCodes.Ldarg_0); ilGen.Emit(OpCodes.Ldfld, serviceProviderField); ilGen.Emit(OpCodes.Callvirt, executeMethod); //清空list里的参数 ilGen.Emit(OpCodes.Ldarg_0); ilGen.Emit(OpCodes.Ldfld, paramterArrField); ilGen.Emit(OpCodes.Callvirt, typeof(List<object>).GetMethod("Clear")); // pop the stack if return void if (targetMethod.ReturnType == typeof(void)) { ilGen.Emit(OpCodes.Pop); } // complete ilGen.Emit(OpCodes.Ret); typeBuilder.DefineMethodOverride(methodBuilder, targetMethod); } } var resultType = typeBuilder.CreateTypeInfo().AsType(); return resultType; } public T Build<T>(params object[] constructor) { return (T)this.Build(typeof(T), constructor); } } }
43.190217
186
0.580722
[ "Apache-2.0" ]
winter-2022/SYZERO
src/SyZero.Core/SyZero.Feign/FeignProxyBuilder.cs
8,425
C#
namespace MassTransit.SimpleInjectorIntegration.ScopeProviders { using Scoping; using SimpleInjector; static class InternalScopeExtensions { public static void UpdateScope(this Scope scope, ConsumeContext context) { scope.Container.GetInstance<ScopedConsumeContextProvider>().SetContext(context); } } }
24.066667
92
0.709141
[ "ECL-2.0", "Apache-2.0" ]
AhmedKhalil777/MassTransit
src/Containers/MassTransit.SimpleInjectorIntegration/ScopeProviders/InternalScopeExtensions.cs
361
C#
using System; using System.Collections.Specialized; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using System.Linq; using System.Web; using System.Security.Cryptography; namespace Sage_One_Authorisation_Client { public class SageOneWebRequest { public enum Method { GET, POST, PUT, DELETE }; public HttpWebRequest webRequestinfo = null; public string GetData(Uri url, string token, string signingSecret) { // Create the nonce to be used by the request string nonce = GenerateNonce(); // Create the web request HttpWebRequest webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest; // Generate a signature string signature = SageOneAPIRequestSigner.GenerateSignature("GET", url, null, signingSecret, token, nonce); // Set the request headers SetHeaders(Method.GET, webRequest, token, signature, nonce); // Send the GET request return GetRequest(webRequest); } public string PostData(Uri url, List<KeyValuePair<string, string>> requestBody, string token, string signingSecret) { try { // Create the nonce to be used by the request string nonce = GenerateNonce(); // Create the web request HttpWebRequest webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest; // Generate a signature string signature = SageOneAPIRequestSigner.GenerateSignature("POST", url, requestBody, signingSecret, token, nonce); // Set the request headers SetHeaders(Method.POST, webRequest, token, signature, nonce); // Convert the requestBody into post parameters string postParams = ConvertPostParams(requestBody); webRequestinfo = webRequest; // Send the POST request return SendRequest(webRequest, postParams); } catch (Exception ex) { string exceptionMessage = ex.Message.ToString(); if(ex.InnerException != null) { exceptionMessage += ex.InnerException.Message.ToString(); } return exceptionMessage; } } public string PutData(Uri url, List<KeyValuePair<string, string>> requestBody, string token, string signingSecret) { // Create the nonce to be used by the request string nonce = GenerateNonce(); // Create the web request HttpWebRequest webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest; // Generate a signature string signature = SageOneAPIRequestSigner.GenerateSignature("PUT", url, requestBody, signingSecret, token, nonce); // Set the request headers SetHeaders(Method.PUT, webRequest, token, signature, nonce); // Convert the requestBody into put parameters string putParams = ConvertPostParams(requestBody); // Send the PUT request return SendRequest(webRequest, putParams); } public string DeleteData(Uri baseurl, string token, string signingSecret) { // Create the nonce to be used by the request string nonce = GenerateNonce(); // Create the web request HttpWebRequest webRequest = System.Net.WebRequest.Create(baseurl) as HttpWebRequest; // Generate a signature string signature = SageOneAPIRequestSigner.GenerateSignature("DELETE", baseurl, null, signingSecret, token, nonce); // Set the request headers SetHeaders(Method.DELETE, webRequest, token, signature, nonce); // Send the DELETE request return GetRequest(webRequest); } private void SetHeaders(Method method, HttpWebRequest webRequest, string accessToken, string signature, string nonce) { // Set the required header values on the web request webRequest.AllowAutoRedirect = true; webRequest.Accept = "*/*"; webRequest.UserAgent = "CSharp Test"; webRequest.Headers.Add("X-Signature", signature); webRequest.Headers.Add("X-Nonce", nonce); webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.Timeout = 100000; // pass the current access token as a header parameter if (accessToken != "") { string authorization = String.Concat("Bearer ", accessToken); webRequest.Headers.Add("Authorization", authorization); } // Set the request method verb switch (method) { case Method.GET: webRequest.Method = "GET"; break; case Method.POST: webRequest.Method = "POST"; break; case Method.PUT: webRequest.Method = "PUT"; break; case Method.DELETE: webRequest.Method = "DELETE"; break; } } private string GetRequest(HttpWebRequest webRequest) { string responseData = ""; responseData = GetWebResponse(webRequest); webRequest = null; return responseData; } private string SendRequest(HttpWebRequest webRequest, string postData) { StreamWriter requestWriter = null; requestWriter = new StreamWriter(webRequest.GetRequestStream()); try { requestWriter.Write(postData); } catch { throw; } finally { requestWriter.Close(); requestWriter = null; } return GetRequest(webRequest); } private string GetWebResponse(HttpWebRequest webRequest) { StreamReader responseReader = null; WebResponse response; string responseData = ""; try { response = webRequest.GetResponse(); responseReader = new StreamReader(response.GetResponseStream()); responseData = responseReader.ReadToEnd(); } catch (WebException webex) { string text; using (var sr = new StreamReader(webex.Response.GetResponseStream())) { text = sr.ReadToEnd(); } throw new Exception(text, webex); } catch (Exception ex) { string message = ex.Message; } finally { webRequest.GetResponse().GetResponseStream().Close(); responseReader.Close(); responseReader = null; } return responseData; } public string GenerateNonce() { RandomNumberGenerator rng = RNGCryptoServiceProvider.Create(); Byte[] output = new Byte[32]; rng.GetBytes(output); return Convert.ToBase64String(output); } private string ConvertPostParams(List<KeyValuePair<string, string>> requestBody) { IEnumerable<KeyValuePair<string, string>> kvpParams = requestBody; // Sort the parameters IEnumerable<string> sortedParams = from p in requestBody select p.Key + "=" + p.Value; // Add the ampersand delimiter and then URL-encode string encodedParams = String.Join("&", sortedParams); return encodedParams; } } }
33.266393
132
0.555008
[ "MIT" ]
aareschluchtje/SageOneDemo
Sage One Authorisation Client/SageOneWebRequest.cs
8,119
C#
using System; using System.Diagnostics; namespace WebOptimizer.AngularTemplateCache { internal static class Guard { [DebuggerHidden] internal static void ArgumentIsNotNull(object value, string argument) { if (value == null) { throw new ArgumentNullException(argument); } } } }
19.789474
77
0.585106
[ "MIT" ]
kdcllc/WebOptimizer.AngularTemplateCache
src/Guard.cs
378
C#
using JsonApiDotNetCore.Data; using JsonApiDotNetCore.Internal.Contracts; using JsonApiDotNetCore.Models.Annotation; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; namespace JsonApiDotNetCore.Internal { /// <summary> /// Responsible for populating the RelationshipAttribute InverseNavigation property. /// /// This service is instantiated in the configure phase of the application. /// /// When using a data access layer different from EF Core, and when using ResourceHooks /// that depend on the inverse navigation property (BeforeImplicitUpdateRelationship), /// you will need to override this service, or pass along the inverseNavigationProperty in /// the RelationshipAttribute. /// </summary> public interface IInverseRelationships { /// <summary> /// This method is called upon startup by JsonApiDotNetCore. It should /// deal with resolving the inverse relationships. /// </summary> void Resolve(); } /// <inheritdoc /> public class InverseRelationships : IInverseRelationships { private readonly IResourceContextProvider _provider; private readonly IDbContextResolver _resolver; public InverseRelationships(IResourceContextProvider provider, IDbContextResolver resolver = null) { _provider = provider; _resolver = resolver; } /// <inheritdoc /> public void Resolve() { if (IsEntityFrameworkCoreEnabled()) { DbContext context = _resolver.GetContext(); foreach (ResourceContext ce in _provider.GetResourceContexts()) { IEntityType meta = context.Model.FindEntityType(ce.ResourceType); if (meta == null) continue; foreach (var attr in ce.Relationships) { if (attr is HasManyThroughAttribute) continue; INavigation inverseNavigation = meta.FindNavigation(attr.Property.Name)?.FindInverse(); attr.InverseNavigation = inverseNavigation?.Name; } } } } /// <summary> /// If EF Core is not being used, we're expecting the resolver to not be registered. /// </summary> /// <returns><c>true</c>, if Entity Framework Core was enabled, <c>false</c> otherwise.</returns> private bool IsEntityFrameworkCoreEnabled() => _resolver != null; } }
37.652174
111
0.626251
[ "MIT" ]
bjornharrtell/JsonApiDotNetCore
src/JsonApiDotNetCore/Internal/InverseRelationships.cs
2,598
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.Domain.Transform; using Aliyun.Acs.Domain.Transform.V20180129; namespace Aliyun.Acs.Domain.Model.V20180129 { public class QueryRegistrantProfileRealNameVerificationInfoRequest : RpcAcsRequest<QueryRegistrantProfileRealNameVerificationInfoResponse> { public QueryRegistrantProfileRealNameVerificationInfoRequest() : base("Domain", "2018-01-29", "QueryRegistrantProfileRealNameVerificationInfo", "domain", "openAPI") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Endpoint.endpointRegionalType, null); } Method = MethodType.POST; } private bool? fetchImage; private long? registrantProfileId; private string userClientIp; private string lang; public bool? FetchImage { get { return fetchImage; } set { fetchImage = value; DictionaryUtil.Add(QueryParameters, "FetchImage", value.ToString()); } } public long? RegistrantProfileId { get { return registrantProfileId; } set { registrantProfileId = value; DictionaryUtil.Add(QueryParameters, "RegistrantProfileId", value.ToString()); } } public string UserClientIp { get { return userClientIp; } set { userClientIp = value; DictionaryUtil.Add(QueryParameters, "UserClientIp", value); } } public string Lang { get { return lang; } set { lang = value; DictionaryUtil.Add(QueryParameters, "Lang", value); } } public override QueryRegistrantProfileRealNameVerificationInfoResponse GetResponse(UnmarshallerContext unmarshallerContext) { return QueryRegistrantProfileRealNameVerificationInfoResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
28.284404
142
0.692832
[ "Apache-2.0" ]
chys0404/aliyun-openapi-net-sdk
aliyun-net-sdk-domain/Domain/Model/V20180129/QueryRegistrantProfileRealNameVerificationInfoRequest.cs
3,083
C#
using Insurance.Web.Client; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization.Infrastructure; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Newtonsoft.Json; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Security.Claims; using System.Threading.Tasks; namespace Insurance.Web.Authorization { public class RoleHandler : AuthorizationHandler<RolesAuthorizationRequirement> { private readonly IHttpContextAccessor _httpContext; private readonly IAppClient _client; public RoleHandler(IHttpContextAccessor httpContext, IAppClient client) { _httpContext = httpContext; _client = client; } protected async override Task HandleRequirementAsync(AuthorizationHandlerContext context, RolesAuthorizationRequirement requirement) { _httpContext.HttpContext.Session.Remove("roles"); if (!context.User.Identity.IsAuthenticated) { context.Fail(); } else { var currentUserId = int.Parse(context.User.FindFirst(ClaimTypes.NameIdentifier).Value); var roles = await _client.GetRolesByUserIdAsync(currentUserId); var isValidRole = roles.Intersect(requirement.AllowedRoles).Any(); if (isValidRole) { _httpContext.HttpContext.Session.SetString("roles", string.Join(",", roles)); context.Succeed(requirement); } else { context.Fail(); } } } } }
33.396226
140
0.634463
[ "Unlicense" ]
Kemma87/gap
Insurance.Web/Insurance.Web/Authorization/RoleHandler.cs
1,772
C#
// // Copyright (c) 2022 karamem0 // // This software is released under the MIT License. // // https://github.com/karamem0/sp-client-core/blob/main/LICENSE // using Karamem0.SharePoint.PowerShell.Models.V1; using Karamem0.SharePoint.PowerShell.Runtime.Commands; using Karamem0.SharePoint.PowerShell.Services.V1; using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; namespace Karamem0.SharePoint.PowerShell.Commands { [Cmdlet("Get", "KshRecycleBinItem")] [OutputType(typeof(RecycleBinItem))] public class GetRecycleBinItemCommand : ClientObjectCmdlet<IRecycleBinItemService> { public GetRecycleBinItemCommand() { } [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ParameterSetName = "ParamSet1")] public RecycleBinItem Identity { get; private set; } [Parameter(Mandatory = true, Position = 0, ParameterSetName = "ParamSet2")] public Guid? ItemId { get; private set; } [Parameter(Mandatory = false, ParameterSetName = "ParamSet2")] [Parameter(Mandatory = false, ParameterSetName = "ParamSet3")] public SwitchParameter SecondStage { get; private set; } [Parameter(Mandatory = false, ParameterSetName = "ParamSet3")] public SwitchParameter NoEnumerate { get; private set; } protected override void ProcessRecordCore() { if (this.ParameterSetName == "ParamSet1") { this.Outputs.Add(this.Service.GetObject(this.Identity)); } if (this.ParameterSetName == "ParamSet2") { if (this.SecondStage) { this.Outputs.Add(this.Service.GetObject(this.ItemId, RecycleBinItemState.SecondStageRecycleBin)); } else { this.Outputs.Add(this.Service.GetObject(this.ItemId, RecycleBinItemState.FirstStageRecycleBin)); } } if (this.ParameterSetName == "ParamSet3") { if (this.SecondStage) { if (this.NoEnumerate) { this.Outputs.Add(this.Service.GetObjectEnumerable(RecycleBinItemState.SecondStageRecycleBin)); } else { this.Outputs.AddRange(this.Service.GetObjectEnumerable(RecycleBinItemState.SecondStageRecycleBin)); } } else { if (this.NoEnumerate) { this.Outputs.Add(this.Service.GetObjectEnumerable(RecycleBinItemState.FirstStageRecycleBin)); } else { this.Outputs.AddRange(this.Service.GetObjectEnumerable(RecycleBinItemState.FirstStageRecycleBin)); } } } } } }
35.122222
124
0.556469
[ "MIT" ]
karamem0/SPClientCore
source/Karamem0.SPClientCore/Commands/GetRecycleBinItemCommand.cs
3,161
C#
using CWBFightClub.Models.Interfaces; using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace CWBFightClub.Models { public class DatabaseAdministration { /// <summary> /// Gets or sets the File name from directory. /// </summary> [DisplayName("File Name")] public string FileName { get; set; } /// <summary> /// Gets or sets the File location of the directory. /// </summary> [DisplayName("File Location")] public string FileLocation { get; set; } /// <summary> /// Gets or sets the File date from directory. /// </summary> [DisplayName("File Date")] public DateTime FileDate { get; set; } } }
27.548387
60
0.622951
[ "MIT" ]
GreyIceWater/CWBFightClub
CWBFightClub/CWBFightClub/Models/DatabaseAdministration.cs
856
C#
namespace SKIT.FlurlHttpClient.Wechat.Api.Models { /// <summary> /// <para>表示 [POST] /card/paycell/set 接口的请求。</para> /// </summary> public class CardPayCellSetRequest : WechatApiRequest, IMapResponse<CardPayCellSetRequest, CardPayCellSetResponse> { /// <summary> /// 获取或设置卡券模板编号。 /// </summary> [Newtonsoft.Json.JsonProperty("card_id")] [System.Text.Json.Serialization.JsonPropertyName("card_id")] public string CardId { get; set; } = string.Empty; /// <summary> /// 获取或设置是否开启买单功能。 /// </summary> [Newtonsoft.Json.JsonProperty("is_open")] [System.Text.Json.Serialization.JsonPropertyName("is_open")] public bool IsOpen { get; set; } } }
33
118
0.616601
[ "MIT" ]
vst-h/DotNetCore.SKIT.FlurlHttpClient.Wechat
src/SKIT.FlurlHttpClient.Wechat.Api/Models/Card/CardPayCellSetRequest.cs
829
C#
using Microsoft.Extensions.DependencyInjection; using ZwiftSteero.Application.Abstractions; using ZwiftSteero.Ble; using ZwiftSteero.Ble.Emulator; namespace ZwiftSteero.Application { public static class ServiceConfiguration { public static IServiceCollection AddApplicationServices(this IServiceCollection services) { services.AddTransient<IPortApplication,PortApplication>(); services.AddSingleton<ISteererApplication, SteererApplication>(); services.AddTransient<ISteeringService, SteeringService>(); services.AddBleServices(); return services; } } }
31.047619
98
0.72546
[ "MIT" ]
ttotty/ZwiftSteeroApi
src/ZwiftSteero.Application/ConfigureExtensions.cs
652
C#
using System.IO; using System.Runtime.Serialization; using GameEstate.Red.Formats.Red.CR2W.Reflection; using FastMember; using static GameEstate.Red.Formats.Red.Records.Enums; namespace GameEstate.Red.Formats.Red.Types { [DataContract(Namespace = "")] [REDMeta] public class CAINpcTaggedWanderParams : CAINpcWanderParams { [Ordinal(1)] [RED("wanderPointsGroupTag")] public CName WanderPointsGroupTag { get; set;} public CAINpcTaggedWanderParams(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CAINpcTaggedWanderParams(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
34.2
136
0.748538
[ "MIT" ]
bclnet/GameEstate
src/Estates/Red/GameEstate.Red.Format/Red/W3/RTTIConvert/CAINpcTaggedWanderParams.cs
855
C#
using System; using System.Collections.Generic; namespace ServiceStack.Text { public static class JsonExtensions { public static T JsonTo<T>(this Dictionary<string, string> map, string key) { return Get<T>(map, key); } public static T Get<T>(this Dictionary<string, string> map, string key) { string strVal; return map.TryGetValue(key, out strVal) ? JsonSerializer.DeserializeFromString<T>(strVal) : default(T); } public static string Get(this Dictionary<string, string> map, string key) { string strVal; return map.TryGetValue(key, out strVal) ? strVal : null; } public static JsonArrayObjects ArrayObjects(this string json, string propertyName) { return Text.JsonArrayObjects.Parse(json); } public static List<T> ConvertAll<T>(this JsonArrayObjects jsonArrayObjects, Func<JsonObject, T> converter) { var results = new List<T>(); foreach (var jsonObject in jsonArrayObjects) { results.Add(converter(jsonObject)); } return results; } public static T ConvertTo<T>(this JsonObject jsonObject, Func<JsonObject, T> converFn) { return jsonObject == null ? default(T) : converFn(jsonObject); } public static Dictionary<string, string> ToDictionary(this JsonObject jsonObject) { return jsonObject == null ? new Dictionary<string, string>() : new Dictionary<string, string>(jsonObject); } } public class JsonObject : Dictionary<string, string> { public static JsonObject Parse(string json) { return JsonSerializer.DeserializeFromString<JsonObject>(json); } public JsonArrayObjects ArrayObjects(string propertyName) { string strValue; return this.TryGetValue(propertyName, out strValue) ? JsonArrayObjects.Parse(strValue) : null; } public JsonObject Object(string propertyName) { string strValue; return this.TryGetValue(propertyName, out strValue) ? Parse(strValue) : null; } } public class JsonArrayObjects : List<JsonObject> { public static JsonArrayObjects Parse(string json) { return JsonSerializer.DeserializeFromString<JsonArrayObjects>(json); } } }
24.955056
109
0.688429
[ "BSD-3-Clause" ]
scopely/ServiceStack.Text
src/ServiceStack.Text/JsonObject.cs
2,221
C#
//------------------------------------------------------------------------------ // <auto-generated /> // // This file was automatically generated by SWIG (http://www.swig.org). // Version 3.0.12 // // Do not make changes to this file unless you know what you are doing--modify // the SWIG interface file instead. //------------------------------------------------------------------------------ namespace QuantLib { public class Futures : global::System.IDisposable { private global::System.Runtime.InteropServices.HandleRef swigCPtr; protected bool swigCMemOwn; internal Futures(global::System.IntPtr cPtr, bool cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Futures obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } ~Futures() { Dispose(); } public virtual void Dispose() { lock(this) { if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; NQuantLibcPINVOKE.delete_Futures(swigCPtr); } swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } global::System.GC.SuppressFinalize(this); } } public Futures() : this(NQuantLibcPINVOKE.new_Futures(), true) { if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } public enum Type { IMM, ASX } } }
30.018182
129
0.629316
[ "BSD-3-Clause" ]
x-xing/Quantlib-SWIG
CSharp/csharp/Futures.cs
1,651
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Remote.Storage { // Have to re-export this in remote layer for it to be picked up. [ExportWorkspaceService(typeof(IPersistentStorageLocationService), layer: WorkspaceKind.RemoteWorkspace), Shared] internal class RemoteWorkspacePersistentStorageLocationService : DefaultPersistentStorageLocationService { public override bool IsSupported(Workspace workspace) => true; } [ExportWorkspaceService(typeof(IPersistentStorageLocationService), layer: WorkspaceKind.RemoteTemporaryWorkspace), Shared] internal class RemoteTemporaryWorkspacePersistentStorageLocationService : DefaultPersistentStorageLocationService { public override bool IsSupported(Workspace workspace) => true; } }
44.458333
126
0.796626
[ "Apache-2.0" ]
Sliptory/roslyn
src/Workspaces/Remote/Core/Storage/RemotePersistentStorageLocationService.cs
1,069
C#