content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Linq; using System.Net.Http; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using NUnit.Framework; using Prometheus.DotNetRuntime.Metrics; using Prometheus.DotNetRuntime.Metrics.Producers; namespace Prometheus.DotNetRuntime.Tests.IntegrationTests { internal class Given_Only_Runtime_Counters_Are_Enabled_For_ThreadPoolStats : IntegrationTestBase<ThreadPoolMetricsProducer> { protected override DotNetRuntimeStatsBuilder.Builder ConfigureBuilder(DotNetRuntimeStatsBuilder.Builder toConfigure) { return toConfigure.WithThreadPoolStats(CaptureLevel.Counters); } [Test] public async Task When_work_is_executed_on_the_thread_pool_then_executed_work_is_measured() { var startingThroughput = MetricProducer.Throughput.Value; const int numTasksToSchedule = 100; // schedule a bunch of tasks var tasks = Enumerable.Range(1, numTasksToSchedule) .Select(_ => Task.Run(() => { })); await Task.WhenAll(tasks); Assert.That(() => MetricProducer.NumThreads.Value, Is.GreaterThanOrEqualTo(Environment.ProcessorCount).After(2_000, 10)); Assert.That(() => MetricProducer.Throughput.Value, Is.GreaterThanOrEqualTo(startingThroughput + numTasksToSchedule).After(2_000, 10)); } [Test] public async Task When_timers_are_active_then_they_are_measured() { var startingTimers = MetricProducer.NumTimers.Value; const int numTimersToSchedule = 100; // schedule a bunch of timers var tasks = Enumerable.Range(1, numTimersToSchedule) .Select(n => Task.Delay(3000 + n)) .ToArray(); Assert.That(() => MetricProducer.NumTimers.Value, Is.GreaterThanOrEqualTo(startingTimers + numTimersToSchedule).After(2_000, 10)); } [Test] public async Task When_blocking_work_is_executed_on_the_thread_pool_then_thread_pool_delays_are_measured() { var startingQueueLength = MetricProducer.QueueLength.Sum; var sleepDelay = TimeSpan.FromMilliseconds(250); int desiredSecondsToBlock = 5; int numTasksToSchedule = (int)(Environment.ProcessorCount / sleepDelay.TotalSeconds) * desiredSecondsToBlock; Console.WriteLine($"Scheduling {numTasksToSchedule} blocking tasks..."); // schedule a bunch of blocking tasks that will make the thread pool will grow var tasks = Enumerable.Range(1, numTasksToSchedule) .Select(_ => Task.Run(() => Thread.Sleep(sleepDelay))) .ToArray(); // dont' wait for the tasks to complete- we want to see stats present during a period of thread pool starvation Assert.That(() => MetricProducer.NumThreads.Value, Is.GreaterThan(Environment.ProcessorCount).After(desiredSecondsToBlock * 1000, 10)); Assert.That(() => MetricProducer.QueueLength.Sum, Is.GreaterThan(startingQueueLength).After(desiredSecondsToBlock * 1000, 10)); } } internal class Given_Runtime_Counters_And_ThreadPool_Info_Events_Are_Enabled_For_ThreadPoolStats : IntegrationTestBase<ThreadPoolMetricsProducer> { protected override DotNetRuntimeStatsBuilder.Builder ConfigureBuilder(DotNetRuntimeStatsBuilder.Builder toConfigure) { return toConfigure.WithThreadPoolStats(CaptureLevel.Informational); } [Test] public async Task When_work_is_executed_on_the_thread_pool_then_executed_work_is_measured() { // schedule a bunch of blocking tasks that will make the thread pool will grow var tasks = Enumerable.Range(1, 1000) .Select(_ => Task.Run(() => Thread.Sleep(20))); await Task.WhenAll(tasks); Assert.That(() => MetricProducer.NumThreads.Value, Is.GreaterThanOrEqualTo(Environment.ProcessorCount).After(2000, 10)); Assert.That(MetricProducer.AdjustmentsTotal.CollectAllValues().Sum(), Is.GreaterThanOrEqualTo(1)); } [Test] public async Task When_IO_work_is_executed_on_the_thread_pool_then_the_number_of_io_threads_is_measured() { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) Assert.Inconclusive("Cannot run this test on non-windows platforms."); // need to schedule a bunch of IO work to make the IO pool grow using (var client = new HttpClient()) { var httpTasks = Enumerable.Range(1, 50) .Select(_ => client.GetAsync("http://google.com")); await Task.WhenAll(httpTasks); } Assert.That(() => MetricProducer.NumIocThreads.Value, Is.GreaterThanOrEqualTo(1).After(2000, 10)); } } }
47.065421
149
0.663026
[ "MIT" ]
NetMatch/prometheus-net.DotNetRuntime
src/prometheus-net.DotNetRuntime.Tests/IntegrationTests/ThreadPoolTests.cs
5,036
C#
using BlinkHilight.Views; using Prism.Ioc; using Prism.Modularity; using Prism.Regions; using Prism.Unity; using System.Windows; namespace BlinkHilight { /// <summary> /// App.xaml の相互作用ロジック /// </summary> public partial class App : PrismApplication { protected override Window CreateShell() { return Container.Resolve<MainWindow>(); } protected override void RegisterTypes(IContainerRegistry containerRegistry) { } protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog) { } } }
20.466667
84
0.648208
[ "MIT" ]
hsytkm/ImageCompareViewer
08_ImageFunctions/BlinkHilight/App.xaml.cs
634
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v8/enums/content_label_type.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Ads.GoogleAds.V8.Enums { /// <summary>Holder for reflection information generated from google/ads/googleads/v8/enums/content_label_type.proto</summary> public static partial class ContentLabelTypeReflection { #region Descriptor /// <summary>File descriptor for google/ads/googleads/v8/enums/content_label_type.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ContentLabelTypeReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjZnb29nbGUvYWRzL2dvb2dsZWFkcy92OC9lbnVtcy9jb250ZW50X2xhYmVs", "X3R5cGUucHJvdG8SHWdvb2dsZS5hZHMuZ29vZ2xlYWRzLnY4LmVudW1zGhxn", "b29nbGUvYXBpL2Fubm90YXRpb25zLnByb3RvIvYCChRDb250ZW50TGFiZWxU", "eXBlRW51bSLdAgoQQ29udGVudExhYmVsVHlwZRIPCgtVTlNQRUNJRklFRBAA", "EgsKB1VOS05PV04QARIXChNTRVhVQUxMWV9TVUdHRVNUSVZFEAISEgoOQkVM", "T1dfVEhFX0ZPTEQQAxIRCg1QQVJLRURfRE9NQUlOEAQSDAoISlVWRU5JTEUQ", "BhINCglQUk9GQU5JVFkQBxILCgdUUkFHRURZEAgSCQoFVklERU8QCRIVChFW", "SURFT19SQVRJTkdfRFZfRxAKEhYKElZJREVPX1JBVElOR19EVl9QRxALEhUK", "EVZJREVPX1JBVElOR19EVl9UEAwSFgoSVklERU9fUkFUSU5HX0RWX01BEA0S", "FwoTVklERU9fTk9UX1lFVF9SQVRFRBAOEhIKDkVNQkVEREVEX1ZJREVPEA8S", "GAoUTElWRV9TVFJFQU1JTkdfVklERU8QEBIRCg1TT0NJQUxfSVNTVUVTEBFC", "6gEKIWNvbS5nb29nbGUuYWRzLmdvb2dsZWFkcy52OC5lbnVtc0IVQ29udGVu", "dExhYmVsVHlwZVByb3RvUAFaQmdvb2dsZS5nb2xhbmcub3JnL2dlbnByb3Rv", "L2dvb2dsZWFwaXMvYWRzL2dvb2dsZWFkcy92OC9lbnVtcztlbnVtc6ICA0dB", "QaoCHUdvb2dsZS5BZHMuR29vZ2xlQWRzLlY4LkVudW1zygIdR29vZ2xlXEFk", "c1xHb29nbGVBZHNcVjhcRW51bXPqAiFHb29nbGU6OkFkczo6R29vZ2xlQWRz", "OjpWODo6RW51bXNiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V8.Enums.ContentLabelTypeEnum), global::Google.Ads.GoogleAds.V8.Enums.ContentLabelTypeEnum.Parser, null, null, new[]{ typeof(global::Google.Ads.GoogleAds.V8.Enums.ContentLabelTypeEnum.Types.ContentLabelType) }, null, null) })); } #endregion } #region Messages /// <summary> /// Container for enum describing content label types in ContentLabel. /// </summary> public sealed partial class ContentLabelTypeEnum : pb::IMessage<ContentLabelTypeEnum> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<ContentLabelTypeEnum> _parser = new pb::MessageParser<ContentLabelTypeEnum>(() => new ContentLabelTypeEnum()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ContentLabelTypeEnum> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V8.Enums.ContentLabelTypeReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ContentLabelTypeEnum() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ContentLabelTypeEnum(ContentLabelTypeEnum other) : this() { _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ContentLabelTypeEnum Clone() { return new ContentLabelTypeEnum(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ContentLabelTypeEnum); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ContentLabelTypeEnum other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ContentLabelTypeEnum other) { if (other == null) { return; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; } } } #endif #region Nested types /// <summary>Container for nested types declared in the ContentLabelTypeEnum message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { /// <summary> /// Enum listing the content label types supported by ContentLabel criterion. /// </summary> public enum ContentLabelType { /// <summary> /// Not specified. /// </summary> [pbr::OriginalName("UNSPECIFIED")] Unspecified = 0, /// <summary> /// Used for return value only. Represents value unknown in this version. /// </summary> [pbr::OriginalName("UNKNOWN")] Unknown = 1, /// <summary> /// Sexually suggestive content. /// </summary> [pbr::OriginalName("SEXUALLY_SUGGESTIVE")] SexuallySuggestive = 2, /// <summary> /// Below the fold placement. /// </summary> [pbr::OriginalName("BELOW_THE_FOLD")] BelowTheFold = 3, /// <summary> /// Parked domain. /// </summary> [pbr::OriginalName("PARKED_DOMAIN")] ParkedDomain = 4, /// <summary> /// Juvenile, gross &amp; bizarre content. /// </summary> [pbr::OriginalName("JUVENILE")] Juvenile = 6, /// <summary> /// Profanity &amp; rough language. /// </summary> [pbr::OriginalName("PROFANITY")] Profanity = 7, /// <summary> /// Death &amp; tragedy. /// </summary> [pbr::OriginalName("TRAGEDY")] Tragedy = 8, /// <summary> /// Video. /// </summary> [pbr::OriginalName("VIDEO")] Video = 9, /// <summary> /// Content rating: G. /// </summary> [pbr::OriginalName("VIDEO_RATING_DV_G")] VideoRatingDvG = 10, /// <summary> /// Content rating: PG. /// </summary> [pbr::OriginalName("VIDEO_RATING_DV_PG")] VideoRatingDvPg = 11, /// <summary> /// Content rating: T. /// </summary> [pbr::OriginalName("VIDEO_RATING_DV_T")] VideoRatingDvT = 12, /// <summary> /// Content rating: MA. /// </summary> [pbr::OriginalName("VIDEO_RATING_DV_MA")] VideoRatingDvMa = 13, /// <summary> /// Content rating: not yet rated. /// </summary> [pbr::OriginalName("VIDEO_NOT_YET_RATED")] VideoNotYetRated = 14, /// <summary> /// Embedded video. /// </summary> [pbr::OriginalName("EMBEDDED_VIDEO")] EmbeddedVideo = 15, /// <summary> /// Live streaming video. /// </summary> [pbr::OriginalName("LIVE_STREAMING_VIDEO")] LiveStreamingVideo = 16, /// <summary> /// Sensitive social issues. /// </summary> [pbr::OriginalName("SOCIAL_ISSUES")] SocialIssues = 17, } } #endregion } #endregion } #endregion Designer generated code
37.268817
300
0.66859
[ "Apache-2.0" ]
deni-skaraudio/google-ads-dotnet
src/V8/Types/ContentLabelType.g.cs
10,398
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Threading; using System.Threading.Tasks; namespace Tests { /// <summary> /// This is a test class for TaskTest and is intended ///to contain all TaskTest Unit Tests /// </summary> [TestClass] public class TaskMembersTest { public const int NestingCount = 100; /// <summary> /// A test for IsFaulted /// </summary> [TestMethod] public void Task_IsFaultedTest() { Action action = () => { }; Task target = new Task(action); target.Start(); Action actionEx = () => { throw new Exception(); }; Task targetEx = new Task(actionEx); targetEx.Start(); target.Wait(); try { targetEx.Wait(); } catch (AggregateException) { } Assert.IsFalse(target.IsFaulted); Assert.IsTrue(targetEx.IsFaulted); } /// <summary> /// A test for IsCompleted /// </summary> [TestMethod] public void Task_IsCompletedTest() { Action action = () => Thread.Sleep(100); Task target = new Task(action); target.Start(); Assert.IsFalse(target.IsCompleted); target.Wait(); Assert.IsTrue(target.IsCompleted); } /// <summary> /// A test for Exception /// </summary> [TestMethod] public void Task_ExceptionTest() { Action action = () => { throw new ArgumentNullException("none"); }; Task target = new Task(action); target.Start(); try { target.Wait(); } catch (AggregateException) { } Assert.AreEqual(1, target.Exception.InnerExceptions.Count); var ex = target.Exception.InnerExceptions[0] as ArgumentNullException; Assert.IsNotNull(ex); } /// <summary> /// A test for CompletedSynchronously /// </summary> [TestMethod] public void Task_CompletedSynchronouslyTest() { int counter = 0; Action action = () => { Interlocked.Increment(ref counter); }; Task target = new Task(action); target.Start(); target.Wait(); Assert.IsFalse(((IAsyncResult)target).CompletedSynchronously); Assert.AreEqual(1, counter); target = new Task(action); target.RunSynchronously(); // Always false Assert.IsFalse(((IAsyncResult)target).CompletedSynchronously); Assert.AreEqual(2, counter); } /// <summary> /// A test for AsyncWaitHandle /// </summary> [TestMethod] public void Task_AsyncWaitHandleTest() { int counter = 0; Action action = () => { Interlocked.Increment(ref counter); }; Task target = new Task(action); target.Start(); Assert.IsTrue(((IAsyncResult)target).AsyncWaitHandle.WaitOne()); Assert.AreEqual(1, counter); } /// <summary> /// A test for AsyncState /// </summary> [TestMethod] public void Task_AsyncStateTest() { object refobj = new object(); int counter = 0; Action<object> action = state => { Interlocked.Increment(ref counter); Assert.AreEqual(refobj, state); }; Task target = new Task(action, refobj); target.Start(); target.Wait(); Assert.AreEqual(refobj, target.AsyncState); } /// <summary> /// A test for Wait /// </summary> [TestMethod] public void Task_WaitTest_Int32() { Action action = () => Thread.Sleep(100); Task target = new Task(action); target.Start(); Assert.IsFalse(target.Wait(0)); Assert.IsTrue(target.Wait(500)); } /// <summary> /// A test for Wait /// </summary> [TestMethod] public void Task_WaitTest_TimeSpan() { Action action = () => Thread.Sleep(100); Task target = new Task(action); target.Start(); Assert.IsFalse(target.Wait(new TimeSpan(0))); Assert.IsTrue(target.Wait(new TimeSpan(0, 0, 1))); } /// <summary> /// A test for Wait /// </summary> [TestMethod] public void Task_WaitTest() { int counter = 0; Action action = () => Interlocked.Increment(ref counter); Task target = new Task(action); target.Start(); target.Wait(); Assert.AreEqual(1, counter); } /// <summary> /// A test for TaskCallback /// </summary> [TestMethod] public void Task_TaskStartActionTest() { int counter = 0; Action action = () => Interlocked.Increment(ref counter); Task target = new Task(action); PrivateObject pvTarget = new PrivateObject(target); pvTarget.Invoke("TaskStartAction", new object[] { null }); Assert.AreEqual(1, counter); } /// <summary> /// A test for Start /// </summary> [TestMethod] public void Task_StartTest() { int counter = 0; Action action = () => Interlocked.Increment(ref counter); Task target = new Task(action); target.Start(); Thread.Sleep(50); Assert.AreEqual(1, counter); } /// <summary> /// A test for RunSynchronously /// </summary> [TestMethod] public void Task_RunSynchronouslyTest() { int counter = 0; Action action = () => Interlocked.Increment(ref counter); Task target = new Task(action); target.RunSynchronously(); Assert.AreEqual(1, counter); } /// <summary> /// A test for EnsureStartOnce /// </summary> [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void Task_EnsureStartOnceTest() { Action action = () => { }; Task target = new Task(action); PrivateObject pvTarget = new PrivateObject(target); pvTarget.Invoke("EnsureStartOnce"); pvTarget.Invoke("EnsureStartOnce"); } /// <summary> /// A test for EndWait /// </summary> [TestMethod] public void Task_EndWaitTest() { Exception ex = new ArgumentNullException("none"); Action action = () => { throw ex; }; Task target = new Task(action); target.Start(); var ar = target.BeginWait(null, null); bool throwException = false; try { target.EndWait(ar); } catch (AggregateException) { throwException = true; } Assert.IsTrue(throwException); Assert.AreEqual(1, target.Exception.InnerExceptions.Count); Assert.IsTrue(target.Exception.InnerExceptions[0] is ArgumentNullException); } /// <summary> /// A test for Dispose /// </summary> [TestMethod] public void Task_DisposeTest() { Action action = () => { }; Task target = new Task(action); bool throwException = false; try { target.Dispose(); } catch (InvalidOperationException) { throwException = true; } Assert.IsTrue(throwException, "Should not dispose a task that is not completed"); target.Start(); target.Wait(); target.Dispose(); } /// <summary> /// A test for ContinueWith /// </summary> [TestMethod] public void Task_ContinueWithTest() { int value = 1; Action action = () => Interlocked.CompareExchange(ref value, 2, 1); Task target = new Task(action); Action<Task> continueAction = t => { Assert.IsNotNull(t); Assert.IsFalse(t.IsFaulted); Interlocked.CompareExchange(ref value, 3, 2); }; Task target2 = target.ContinueWith(continueAction); target.Start(); if (!target2.Wait(100)) Assert.Fail("Timeout waiting for continuation task signal"); Assert.IsTrue(target.IsCompleted); Assert.IsTrue(target2.IsCompleted); Assert.AreEqual(3, value); } /// <summary> /// A test for BeginWait /// </summary> [TestMethod] public void Task_BeginWaitTest() { int counter = 0; Action action = () => Interlocked.Increment(ref counter); Task target = new Task(action); target.Start(); target.BeginWait(ar => { target.EndWait(ar); Assert.AreEqual(1, counter); }, null); target.Wait(); Assert.AreEqual(1, counter); } /// <summary> /// A test for Task Constructor /// </summary> [TestMethod] public void Task_ConstructorTest_Action() { int counter = 0; Action action = () => Interlocked.Increment(ref counter); Task target = new Task(action); target.Start(); target.Wait(); Assert.AreEqual(1, counter); } /// <summary> /// A test for Task Constructor /// </summary> [TestMethod] public void Task_ConstructorTest_Action_State() { int[] values = new int[] { 0 }; Action<object> action = obj => { int[] v = obj as int[]; Assert.IsNotNull(v); Interlocked.Increment(ref v[0]); }; Task target = new Task(action, values); target.Start(); target.Wait(); Assert.AreEqual(1, values[0]); } [TestMethod] public void TaskDeepNesting() { int counter = 0; Action action = () => Interlocked.Increment(ref counter); var task = new Task(action); task.Start(); Action<Task> continueAction = t => Interlocked.Increment(ref counter); for (int i = 0; i < NestingCount; i++) { task = task.ContinueWith(continueAction); } Assert.IsNotNull(task); task.Wait(); Assert.AreEqual(NestingCount + 1, counter); Assert.IsNull(task.Exception); } [TestMethod] public void TaskDeepNesting_Delayed() { int counter = 0; Action action = () => Interlocked.Increment(ref counter); var firstTask = new Task(action); var task = firstTask; Action<Task> continueAction = t => Interlocked.Increment(ref counter); for (int i = 0; i < NestingCount; i++) { task = task.ContinueWith(continueAction); } Assert.AreEqual(TaskStatus.Created, firstTask.Status); firstTask.Start(); Assert.IsNotNull(task); task.Wait(); Assert.AreEqual(NestingCount + 1, counter); Assert.IsNull(task.Exception); } [TestMethod] public void TaskDeepNesting_Multicast() { int counter = 0; Action action = () => Interlocked.Increment(ref counter); var firstTask = new Task(action); var task = firstTask; Action<Task> continueAction = t => Interlocked.Increment(ref counter); for (int i = 0; i < NestingCount; i++) { task = firstTask.ContinueWith(continueAction); } Assert.AreEqual(TaskStatus.Created, firstTask.Status); firstTask.Start(); Assert.IsNotNull(task); task.Wait(); Assert.AreEqual(NestingCount + 1, counter); Assert.IsNull(task.Exception); } } }
30.9022
93
0.505578
[ "Apache-2.0" ]
WindowsCE-Deprecated/System.Threading.Tasks
test/Tasks.Tests/TaskMembersTests.cs
12,641
C#
#region License // // Copyright (c) 2013, Kooboo team // // Licensed under the BSD License // See the file LICENSE.txt for details. // #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; namespace Kooboo.CMS.Sites.Extension.ModuleArea.Management.Events { public interface IModuleUninstallingEvents { /// <summary> /// Called when [uninstalling]. /// Will only enabled when the module have install template(The InstallingTemplate property in ModuleInfo) /// </summary> /// <param name="moduleContext">The module context.</param> /// <param name="controllerContext">The controller context.</param> void OnUninstalling(ModuleContext moduleContext, ControllerContext controllerContext); } }
29.535714
114
0.704958
[ "BSD-3-Clause" ]
Bringsy/Kooboo.CMS
Kooboo.CMS/Kooboo.CMS.Sites/Extension/ModuleArea/Management/Events/IModuleUninstallingEvents.cs
829
C#
using System; using System.Collections.Generic; using NHapi.Base.Log; using NHapi.Model.V23.Group; using NHapi.Model.V23.Segment; using NHapi.Model.V23.Datatype; using NHapi.Base; using NHapi.Base.Parser; using NHapi.Base.Model; namespace NHapi.Model.V23.Message { ///<summary> /// Represents a SRM_S01 message structure (see chapter [AAA]). This structure contains the /// following elements: ///<ol> ///<li>0: MSH (Message header segment) </li> ///<li>1: ARQ (Appointment Request) </li> ///<li>2: APR (Appointment Preferences) optional </li> ///<li>3: NTE (Notes and comments segment) optional repeating</li> ///<li>4: SRM_S01_PATIENT (a Group object) optional repeating</li> ///<li>5: SRM_S01_RESOURCES (a Group object) repeating</li> ///</ol> ///</summary> [Serializable] public class SRM_S01 : AbstractMessage { ///<summary> /// Creates a new SRM_S01 Group with custom IModelClassFactory. ///</summary> public SRM_S01(IModelClassFactory factory) : base(factory){ init(factory); } ///<summary> /// Creates a new SRM_S01 Group with DefaultModelClassFactory. ///</summary> public SRM_S01() : base(new DefaultModelClassFactory()) { init(new DefaultModelClassFactory()); } ///<summary> /// initalize method for SRM_S01. This does the segment setup for the message. ///</summary> private void init(IModelClassFactory factory) { try { this.add(typeof(MSH), true, false); this.add(typeof(ARQ), true, false); this.add(typeof(APR), false, false); this.add(typeof(NTE), false, true); this.add(typeof(SRM_S01_PATIENT), false, true); this.add(typeof(SRM_S01_RESOURCES), true, true); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating SRM_S01 - this is probably a bug in the source code generator.", e); } } public override string Version { get{ return Constants.VERSION; } } ///<summary> /// Returns MSH (Message header segment) - creates it if necessary ///</summary> public MSH MSH { get{ MSH ret = null; try { ret = (MSH)this.GetStructure("MSH"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns ARQ (Appointment Request) - creates it if necessary ///</summary> public ARQ ARQ { get{ ARQ ret = null; try { ret = (ARQ)this.GetStructure("ARQ"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns APR (Appointment Preferences) - creates it if necessary ///</summary> public APR APR { get{ APR ret = null; try { ret = (APR)this.GetStructure("APR"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns first repetition of NTE (Notes and comments segment) - creates it if necessary ///</summary> public NTE GetNTE() { NTE ret = null; try { ret = (NTE)this.GetStructure("NTE"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of NTE /// * (Notes and comments segment) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public NTE GetNTE(int rep) { return (NTE)this.GetStructure("NTE", rep); } /** * Returns the number of existing repetitions of NTE */ public int NTERepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("NTE").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the NTE results */ public IEnumerable<NTE> NTEs { get { for (int rep = 0; rep < NTERepetitionsUsed; rep++) { yield return (NTE)this.GetStructure("NTE", rep); } } } ///<summary> ///Adds a new NTE ///</summary> public NTE AddNTE() { return this.AddStructure("NTE") as NTE; } ///<summary> ///Removes the given NTE ///</summary> public void RemoveNTE(NTE toRemove) { this.RemoveStructure("NTE", toRemove); } ///<summary> ///Removes the NTE at the given index ///</summary> public void RemoveNTEAt(int index) { this.RemoveRepetition("NTE", index); } ///<summary> /// Returns first repetition of SRM_S01_PATIENT (a Group object) - creates it if necessary ///</summary> public SRM_S01_PATIENT GetPATIENT() { SRM_S01_PATIENT ret = null; try { ret = (SRM_S01_PATIENT)this.GetStructure("PATIENT"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of SRM_S01_PATIENT /// * (a Group object) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public SRM_S01_PATIENT GetPATIENT(int rep) { return (SRM_S01_PATIENT)this.GetStructure("PATIENT", rep); } /** * Returns the number of existing repetitions of SRM_S01_PATIENT */ public int PATIENTRepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("PATIENT").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the SRM_S01_PATIENT results */ public IEnumerable<SRM_S01_PATIENT> PATIENTs { get { for (int rep = 0; rep < PATIENTRepetitionsUsed; rep++) { yield return (SRM_S01_PATIENT)this.GetStructure("PATIENT", rep); } } } ///<summary> ///Adds a new SRM_S01_PATIENT ///</summary> public SRM_S01_PATIENT AddPATIENT() { return this.AddStructure("PATIENT") as SRM_S01_PATIENT; } ///<summary> ///Removes the given SRM_S01_PATIENT ///</summary> public void RemovePATIENT(SRM_S01_PATIENT toRemove) { this.RemoveStructure("PATIENT", toRemove); } ///<summary> ///Removes the SRM_S01_PATIENT at the given index ///</summary> public void RemovePATIENTAt(int index) { this.RemoveRepetition("PATIENT", index); } ///<summary> /// Returns first repetition of SRM_S01_RESOURCES (a Group object) - creates it if necessary ///</summary> public SRM_S01_RESOURCES GetRESOURCES() { SRM_S01_RESOURCES ret = null; try { ret = (SRM_S01_RESOURCES)this.GetStructure("RESOURCES"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of SRM_S01_RESOURCES /// * (a Group object) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public SRM_S01_RESOURCES GetRESOURCES(int rep) { return (SRM_S01_RESOURCES)this.GetStructure("RESOURCES", rep); } /** * Returns the number of existing repetitions of SRM_S01_RESOURCES */ public int RESOURCESRepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("RESOURCES").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the SRM_S01_RESOURCES results */ public IEnumerable<SRM_S01_RESOURCES> RESOURCESs { get { for (int rep = 0; rep < RESOURCESRepetitionsUsed; rep++) { yield return (SRM_S01_RESOURCES)this.GetStructure("RESOURCES", rep); } } } ///<summary> ///Adds a new SRM_S01_RESOURCES ///</summary> public SRM_S01_RESOURCES AddRESOURCES() { return this.AddStructure("RESOURCES") as SRM_S01_RESOURCES; } ///<summary> ///Removes the given SRM_S01_RESOURCES ///</summary> public void RemoveRESOURCES(SRM_S01_RESOURCES toRemove) { this.RemoveStructure("RESOURCES", toRemove); } ///<summary> ///Removes the SRM_S01_RESOURCES at the given index ///</summary> public void RemoveRESOURCESAt(int index) { this.RemoveRepetition("RESOURCES", index); } } }
28.413598
146
0.644965
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
afaonline/nHapi
src/NHapi.Model.V23/Message/SRM_S01.cs
10,030
C#
using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using CrystalDuelingEngine.Serialization; using CrystalDuelingEngine.States; using GoldenAnvil.Utility; namespace CrystalDuelingEngine.Conditions { public abstract class BinaryLogicCondition : ConditionBase { public ReadOnlyCollection<ConditionBase> Children { get; } public override bool IsTrue(AttackState state) { bool? result = Children.EmptyIfNull().Aggregate<ConditionBase, bool?>(null, (current, child) => CombineResult(current, child.IsTrue(state))); return result.GetValueOrDefault(); } public override string RenderForLog() { return $"({string.Join($" {RenderOperatorForLog()} ", Children.Select(x => x.RenderForLog()))})"; } public override string RenderForUi() { return $"({string.Join($" {RenderOperatorForUi()} ", Children.Select(x => x.RenderForLog()))})"; } public override void Serialize(ISerializer serializer) { serializer.SerializeValue(nameof(Children), Children); base.Serialize(serializer); } protected BinaryLogicCondition(IEnumerable<ConditionBase> children) { Children = children.EmptyIfNull().ToList().AsReadOnly(); } protected BinaryLogicCondition(IDeserializer deserializer) : base(deserializer) { Children = deserializer.GetValues<ConditionBase>(nameof(Children)).EmptyIfNull().ToList().AsReadOnly(); } protected abstract bool CombineResult(bool? current, bool result); protected abstract string RenderOperatorForLog(); protected abstract string RenderOperatorForUi(); protected override bool IsValidCore(List<string> errors) { if (Children.Count < 2) { errors.Add(OurResources.InvalidConditionMissingChildren.FormatCurrentCulture(GetType().Name, 2)); return false; } return Children.All(x => x.IsValid(errors)); } } }
28.507692
144
0.744199
[ "MIT" ]
SaberSnail/CrystalDuelingEngine
CrystalDuelingEngine/Conditions/BinaryLogicCondition.cs
1,855
C#
using SharpDX.Windows; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace D3D12HelloDepthBuffer { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { var form = new RenderForm("Hello Depth Buffer"); form.Width = 1280; form.Height = 800; form.Show(); using (HelloDepthBuffer app = new HelloDepthBuffer()) { app.Initialize(form); using (var loop = new RenderLoop(form)) { while (loop.NextFrame()) { app.Update(); app.Render(); } } } } } }
24.769231
66
0.451346
[ "MIT" ]
RobyDX/SharpDX_D3D12HelloWorld
D3D12HelloDepthBuffer/Program.cs
968
C#
using System; namespace T01.FruitMarket { class Program { static void Main(string[] args) { double strawberriesPrice = double.Parse(Console.ReadLine()); double bananasWeight = double.Parse(Console.ReadLine()); double orangesWeight = double.Parse(Console.ReadLine()); double raspberriesWeight = double.Parse(Console.ReadLine()); double strawberriesWeight = double.Parse(Console.ReadLine()); double raspberriesPrice = strawberriesPrice / 2; double orangesPrice = raspberriesPrice * 0.60; double bananasPrice = raspberriesPrice * 0.20; double totalPrice = strawberriesPrice * strawberriesWeight + bananasPrice * bananasWeight + orangesPrice * orangesWeight + raspberriesPrice * raspberriesWeight; Console.WriteLine($"{totalPrice:f2}"); } } }
37.458333
172
0.649611
[ "MIT" ]
akdimitrov/CSharp-Basics
_PB - EXAMS/Exam Prep - PB Online Exam 2-3May2019/T01.FruitMarket/Program.cs
901
C#
using System; using System.Collections.Generic; using System.Linq; using Moq; using RomanticWeb.Converters; using RomanticWeb.Entities; using RomanticWeb.Mapping.Model; using RomanticWeb.Mapping.Visitors; namespace RomanticWeb.Tests.Stubs { public class TestEntityMapping<TEntity> : IEntityMapping { private readonly IList<IClassMapping> _classes = new List<IClassMapping>(); private readonly IList<IPropertyMapping> _properties = new List<IPropertyMapping>(); public Type EntityType { get { return typeof(TEntity); } } public IEnumerable<IClassMapping> Classes { get { return _classes; } } public IEnumerable<IPropertyMapping> Properties { get { return _properties; } } public IEnumerable<IPropertyMapping> HiddenProperties { get { return new IPropertyMapping[0]; } } public IPropertyMapping PropertyFor(string propertyName) { return _properties.FirstOrDefault(p => p.Name == propertyName); } public void Accept(IMappingModelVisitor mappingModelVisitor) { mappingModelVisitor.Visit(this); foreach (var propertyMapping in Properties) { mappingModelVisitor.Visit(propertyMapping); } foreach (var classMapping in Classes) { mappingModelVisitor.Visit(classMapping); } } protected void Class(Uri clazz) { var mapping = new Mock<IQueryableClassMapping>(); mapping.SetupGet(instance => instance.Uris).Returns(new[] { clazz }); mapping.SetupGet(instance => instance.Uri).Returns(clazz); _classes.Add(mapping.Object); } protected void Property(string name, Uri predicate, Type returnType, INodeConverter converter) { var property = new Mock<IPropertyMapping>(); property.SetupGet(instance => instance.Name).Returns(name); property.SetupGet(instance => instance.Uri).Returns(predicate); property.SetupGet(instance => instance.ReturnType).Returns(returnType); property.SetupGet(instance => instance.Converter).Returns(converter); property.SetupGet(instance => instance.EntityMapping).Returns(this); _properties.Add(property.Object); } protected void Collection(string name, Uri predicate, Type returnType, INodeConverter converter) { var collection = new Mock<ICollectionMapping>(); collection.SetupGet(instance => instance.Name).Returns(name); collection.SetupGet(instance => instance.Uri).Returns(predicate); collection.SetupGet(instance => instance.ReturnType).Returns(returnType); collection.SetupGet(instance => instance.Converter).Returns(converter); collection.SetupGet(instance => instance.ElementConverter).Returns(converter); collection.SetupGet(instance => instance.StoreAs).Returns(StoreAs.SimpleCollection); collection.SetupGet(instance => instance.EntityMapping).Returns(this); _properties.Add(collection.Object); } protected void RdfList(string name, Uri predicate, Type returnType) { var collection = new Mock<ICollectionMapping>(); collection.SetupGet(instance => instance.Name).Returns(name); collection.SetupGet(instance => instance.Uri).Returns(predicate); collection.SetupGet(instance => instance.ReturnType).Returns(returnType); collection.SetupGet(instance => instance.Converter).Returns(new AsEntityConverter<IEntity>()); collection.SetupGet(instance => instance.ElementConverter).Returns(new AsEntityConverter<IEntity>()); collection.SetupGet(instance => instance.StoreAs).Returns(StoreAs.RdfList); collection.SetupGet(instance => instance.EntityMapping).Returns(this); _properties.Add(collection.Object); } } }
38.640351
114
0.607719
[ "BSD-3-Clause" ]
alien-mcl/RomanticWeb
Tests/RomanticWeb.Tests/Stubs/TestEntityMapping.cs
4,407
C#
using System.IO; namespace TeleSharp.TL.Messages { [TLObject(911761060)] public class TLBotCallbackAnswer : TLObject { public override int Constructor { get { return 911761060; } } public int Flags { get; set; } public bool Alert { get; set; } public bool HasUrl { get; set; } public string Message { get; set; } public string Url { get; set; } public int CacheTime { get; set; } public void ComputeFlags() { Flags = 0; Flags = Alert ? (Flags | 2) : (Flags & ~2); Flags = HasUrl ? (Flags | 8) : (Flags & ~8); Flags = Message != null ? (Flags | 1) : (Flags & ~1); Flags = Url != null ? (Flags | 4) : (Flags & ~4); } public override void DeserializeBody(BinaryReader br) { Flags = br.ReadInt32(); Alert = (Flags & 2) != 0; HasUrl = (Flags & 8) != 0; if ((Flags & 1) != 0) { Message = StringUtil.Deserialize(br); } else { Message = null; } if ((Flags & 4) != 0) { Url = StringUtil.Deserialize(br); } else { Url = null; } CacheTime = br.ReadInt32(); } public override void SerializeBody(BinaryWriter bw) { bw.Write(Constructor); ComputeFlags(); bw.Write(Flags); if ((Flags & 1) != 0) { StringUtil.Serialize(Message, bw); } if ((Flags & 4) != 0) { StringUtil.Serialize(Url, bw); } bw.Write(CacheTime); } } }
23.134146
65
0.411703
[ "MIT" ]
cobra91/TelegramCSharpForward
TeleSharp.TL/TL/Messages/TLBotCallbackAnswer.cs
1,897
C#
using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.UI; using UnityEngine.SceneManagement; public class GameControl : MonoBehaviour { /// <summary> /// A reference to the UI text component that displays the player's score. /// </summary> private Text scoreText; /// <summary> /// The player's score. /// </summary> private int score = 0; /// <summary> /// A reference to our game control script so we can access it statically. /// </summary> public static GameControl Instance; /// <summary> /// Boolean that indicates if the game is over. /// </summary> public bool GameOver = false; /// <summary> /// Instance of the parameter class. /// </summary> public Parameters Parameters; /// <summary> /// OutputValue Text. /// </summary> public Text OutputSliderValue; /// <summary> /// Reference to the start button. /// </summary> public Button Start; /// <summary> /// Reference to the slider. /// </summary> public Slider Slider; public GameObject Settings; public void Awake() { if (Parameters == null) { Parameters = new Parameters(); } if (Instance == null) { Instance = this; } else if (Instance != this) { Destroy(gameObject); } } void Update() { } /// <summary> /// Method that keeps track of the score while the game is not over. /// </summary> public void BirdScored() { //The bird can't score if the game is over. if (GameOver) return; //If the game is not over, increase the score... score++; //...and adjust the score text. scoreText = GameObject.Find("ScoreText").GetComponent<Text>(); scoreText.text = "Score: " + score.ToString(); } /// <summary> /// Method that innitiates GameOver + brings us back to the setting menu. /// </summary> public void BirdDied() { SceneManager.LoadScene("SettingsMenu"); } /// <summary> /// Method that innitiate a scene, after the start button is clicked. /// </summary> public void OnStartClick() { SceneManager.LoadScene("Main"); } /// <summary> /// Method, that's used by the slider to change the value of the scroll speed, between -1.5f and -3f; /// </summary> /// <param name="speed"></param> public void SetSpeed(float speed) { Debug.Log(speed); } public void QuitGame() { } }
20.176471
105
0.55102
[ "MIT" ]
DanielD2/3DMenu
Assets/Flappy Bird Style/Scripts/GameControl.cs
2,746
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace GCC_trial_3 { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new UserSelectionScreen()); } } }
22.782609
65
0.622137
[ "MIT" ]
Jaswanthjc/GCC-Compiler
user_design/Program.cs
526
C#
using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; namespace WeatherOnRoute.iOS { public class Application { // This is the main entry point of the application. static void Main(string[] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. UIApplication.Main(args, null, typeof(AppDelegate)); } } }
23.428571
91
0.640244
[ "MIT" ]
JoanGil/weather-on-route
WeatherOnRoute/WeatherOnRoute/WeatherOnRoute.iOS/Main.cs
494
C#
using System; using System.Collections.Generic; using System.Text; namespace RequestHelper.Models { public class ParametersDictionary : List<KeyValuePair<string, string>> { public void Add(string key, string value) { var element = new KeyValuePair<string, string>(key, value); Add(element); } } }
22.4375
74
0.640669
[ "MIT" ]
EuFindlay/RequestHelper
Source/RequestHelper/Models/UrlDictionary.cs
361
C#
using System; using System.ServiceModel; using System.ServiceModel.Dispatcher; using System.ServiceModel.Channels; using System.ServiceModel.Web; using WcfRestContrib.DependencyInjection; using WcfRestContrib.ServiceModel.Channels; using WcfRestContrib.ServiceModel.Dispatcher; using System.Net.Mime; using System.Runtime.Serialization; using WcfRestContrib.ServiceModel.Description; using WcfRestContrib.Net.Http; using WcfRestContrib.ServiceModel.Web.Exceptions; namespace WcfRestContrib.ServiceModel.Web { public class WebErrorHandler : IErrorHandler { public void ProvideFault(Exception error, MessageVersion version, ref Message fault) { WebException webException; if (error is WebException) webException = (WebException)error; else { var behavior = GetWebErrorHandlerConfiguration(); string unhandledErrorMessage; if (behavior.ReturnRawException) unhandledErrorMessage = error.ToString(); else unhandledErrorMessage = (behavior != null && behavior.UnhandledErrorMessage != null) ? behavior.UnhandledErrorMessage : "An error has occured processing your request."; webException = new WebException(error, System.Net.HttpStatusCode.InternalServerError, unhandledErrorMessage); } webException.UpdateHeaders(WebOperationContext.Current.OutgoingResponse.Headers); WebOperationContext.Current.OutgoingResponse.StatusCode = webException.Status; WebOperationContext.Current.OutgoingResponse.StatusDescription = webException.Status.ToString(); WebDispatchFormatter webDispatchFormatter = null; if (OperationContext.Current.OutgoingMessageProperties.ContainsKey(WebDispatchFormatter.WebDispatcherFormatterProperty)) webDispatchFormatter = OperationContext.Current.OutgoingMessageProperties[WebDispatchFormatter.WebDispatcherFormatterProperty] as WebDispatchFormatter; if (webDispatchFormatter != null) { var behavior = GetWebErrorHandlerConfiguration(); IWebExceptionDataContract exceptionContract = null; if (behavior != null) exceptionContract = behavior.CreateExceptionDataContract(); if (exceptionContract == null) exceptionContract = new WebExceptionContract(); exceptionContract.Init(webException); fault = webDispatchFormatter.Serialize( exceptionContract, typeof(WebExceptionContract), WebOperationContext.Current.IncomingRequest.GetAcceptTypes()); } else { WebOperationContext.Current.OutgoingResponse.ContentType = MediaTypeNames.Text.Html; fault = Message.CreateMessage( MessageVersion.None, null, new BinaryBodyWriter(GenerateResponseText(webException.Message))); fault.SetWebContentFormatProperty(WebContentFormat.Raw); } fault.UpdateHttpProperty(); if (OperationContainer.Exists()) DependencyResolver.Current.OperationError(OperationContainer.GetCurrent(), error); } public bool HandleError(Exception error) { InternalHandleError(error); return true; } private static void InternalHandleError(Exception error) { var behavior = GetWebErrorHandlerConfiguration(); if (behavior == null || behavior.LogHandler == null) return; RequestInformation info; if (OperationContext.Current.OutgoingMessageProperties.ContainsKey( ErrorHandlerBehavior.HttpRequestInformationProperty)) info = (RequestInformation)OperationContext.Current.OutgoingMessageProperties[ ErrorHandlerBehavior.HttpRequestInformationProperty]; else info = new RequestInformation(); behavior.LogHandler.Write(error, info); } private static WebErrorHandlerConfigurationBehavior GetWebErrorHandlerConfiguration() { return OperationContext.Current.Host.Description.FindBehavior<WebErrorHandlerConfigurationBehavior, WebErrorHandlerConfigurationAttribute>(x => x.BaseBehavior); } private static string GenerateResponseText(string message) { return string.Format( "<html><body style=\"font-family:Arial;font-size:11pt;\">{0}</body></html>", message); } [DataContract(Name="Error", Namespace="")] private class WebExceptionContract : IWebExceptionDataContract { [DataMember(Name = "Status")] public int Status { get; set; } [DataMember(Name = "Message")] public string Message { get; set; } public void Init(WebException exception) { Message = exception.Message; Status = (int)exception.Status; } } } }
41.022222
168
0.614482
[ "MIT" ]
mikeobrien/WcfRestContrib
src/WcfRestContrib/ServiceModel/Web/WebErrorHandler.cs
5,540
C#
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using WhatsAppApi.Settings; namespace WhatsAppApi.Register { public static class WhatsRegisterV2 { public static string GenerateIdentity(string phoneNumber, string salt = "") { return (phoneNumber + salt).Reverse().ToSHAString(); } public static string GetToken(string number) { return WaToken.GenerateToken(number); } public static bool RequestCode(string countryCode, string phoneNumber, out string password, string method = "sms", string id = null, string language = null, string locale = null, string mcc = "204", string salt = "") { string response = string.Empty; return RequestCode(countryCode, phoneNumber, out password, out response, method, id, mcc, salt); } public static bool RequestCode(string countryCode, string phoneNumber, out string password, out string response, string method = "sms", string id = null, string language = null, string locale = null, string mcc = "204", string salt = "") { string request = string.Empty; return RequestCode(countryCode, phoneNumber, out password, out request, out response, method, id, language, locale, mcc, salt); } public static bool RequestCode(string countryCode, string phoneNumber, out string password, out string request, out string response, string method = "sms", string id = null, string language = null, string locale = null, string mcc = "204", string salt = "") { response = null; password = null; request = null; try { if (string.IsNullOrEmpty(language) || string.IsNullOrEmpty(locale)) { CultureInfo.CurrentCulture.GetLanguageAndLocale(out language, out locale); } if (string.IsNullOrEmpty(id)) { //auto-generate id = GenerateIdentity(phoneNumber, salt); } string token = System.Uri.EscapeDataString(WhatsRegisterV2.GetToken(phoneNumber)); request = string.Format("https://v.whatsapp.net/v2/code?cc={0}&in={1}&to={0}{1}&lg={2}&lc={3}&mcc={7}&mnc=008&method={4}&id={5}&token={6}", countryCode, phoneNumber, language, locale, method, id, token, mcc); response = GetResponse(request); password = response.GetJsonValue("pw"); if (!string.IsNullOrEmpty(password)) { return true; } return (response.GetJsonValue("status") == "sent"); } catch(Exception e) { response = e.Message; return false; } } public static string RegisterCode(string countryCode, string phoneNumber, string code, string id = null, string salt = "") { string response = string.Empty; return WhatsRegisterV2.RegisterCode(countryCode, phoneNumber, code, out response, id, salt); } public static string RegisterCode(string countryCode, string phoneNumber, string code, out string response, string id = null, string salt = "") { response = string.Empty; try { if (string.IsNullOrEmpty(id)) { //auto generate id = GenerateIdentity(phoneNumber, salt); } string uri = string.Format("https://v.whatsapp.net/v2/register?cc={0}&in={1}&id={2}&code={3}", countryCode, phoneNumber, id, code); response = GetResponse(uri); if (response.GetJsonValue("status") == "ok") { return response.GetJsonValue("pw"); } return null; } catch { return null; } } public static string RequestExist(string countryCode, string phoneNumber, string id = null) { string response = string.Empty; return RequestExist(countryCode, phoneNumber, out response, id); } public static string RequestExist(string countryCode, string phoneNumber, out string response, string id = null) { response = string.Empty; try { if (String.IsNullOrEmpty(id)) { id = phoneNumber.Reverse().ToSHAString(); } string uri = string.Format("https://v.whatsapp.net/v2/exist?cc={0}&in={1}&id={2}", countryCode, phoneNumber, id); response = GetResponse(uri); if (response.GetJsonValue("status") == "ok") { return response.GetJsonValue("pw"); } return null; } catch { return null; } } private static string GetResponse(string uri) { HttpWebRequest request = HttpWebRequest.Create(new Uri(uri)) as HttpWebRequest; request.KeepAlive = false; request.UserAgent = WhatsConstants.UserAgent; request.Accept = "text/json"; using (var reader = new StreamReader(request.GetResponse().GetResponseStream())) { return reader.ReadLine(); } } private static string ToSHAString(this IEnumerable<char> s) { return new string(s.ToArray()).ToSHAString(); } public static string UrlEncode(string data) { StringBuilder sb = new StringBuilder(); foreach (char c in data.ToCharArray()) { int i = (int)c; if ( ( i >= 0 && i <= 31 ) || ( i >= 32 && i <= 47 ) || ( i >= 58 && i <= 64 ) || ( i >= 91 && i <= 96 ) || ( i >= 123 && i <= 126 ) || i > 127 ) { //encode sb.Append('%'); sb.AppendFormat("{0:x2}", (byte)c); } else { //do not encode sb.Append(c); } } return sb.ToString(); } private static string ToSHAString(this string s) { byte[] data = SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(s)); string str = Encoding.GetEncoding("iso-8859-1").GetString(data); str = WhatsRegisterV2.UrlEncode(str).ToLower(); return str; } private static string ToMD5String(this IEnumerable<char> s) { return new string(s.ToArray()).ToMD5String(); } private static string ToMD5String(this string s) { return string.Join(string.Empty, MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(s)).Select(item => item.ToString("x2")).ToArray()); } private static void GetLanguageAndLocale(this CultureInfo self, out string language, out string locale) { string name = self.Name; int n1 = name.IndexOf('-'); if (n1 > 0) { int n2 = name.LastIndexOf('-'); language = name.Substring(0, n1); locale = name.Substring(n2 + 1); } else { language = name; switch (language) { case "cs": locale = "CZ"; return; case "da": locale = "DK"; return; case "el": locale = "GR"; return; case "ja": locale = "JP"; return; case "ko": locale = "KR"; return; case "sv": locale = "SE"; return; case "sr": locale = "RS"; return; } locale = language.ToUpper(); } } private static string GetJsonValue(this string s, string parameter) { Match match; if ((match = Regex.Match(s, string.Format("\"?{0}\"?:\"(?<Value>.+?)\"", parameter), RegexOptions.Singleline | RegexOptions.IgnoreCase)).Success) { return match.Groups["Value"].Value; } return null; } } }
35.025926
265
0.472454
[ "MIT" ]
paulocorcino/AutoZap
WhatsAppApi/Register/WhatsRegisterV2.cs
9,457
C#
//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.18444 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ namespace MyMiniTradingSystem.Properties { using System; /// <summary> /// 一个强类型的资源类,用于查找本地化的字符串等。 /// </summary> // 此类是由 StronglyTypedResourceBuilder // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen // (以 /str 作为命令选项),或重新生成 VS 项目。 [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// 返回此类使用的缓存的 ResourceManager 实例。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MyMiniTradingSystem.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// 使用此强类型资源类,为所有资源查找 /// 重写当前线程的 CurrentUICulture 属性。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
38.515625
185
0.590669
[ "MIT" ]
wangzhiqing999/my-csharp-project
MyMiniTradingSystem.Chart/Properties/Resources.Designer.cs
2,815
C#
using System; using System.Xml.Serialization; namespace Aop.Api.Domain { /// <summary> /// SearchToggleBoxStatusRequest Data Structure. /// </summary> [Serializable] public class SearchToggleBoxStatusRequest : AopObject { /// <summary> /// 品牌id /// </summary> [XmlElement("brand_id")] public string BrandId { get; set; } /// <summary> /// 用户id /// </summary> [XmlElement("pid")] public string Pid { get; set; } /// <summary> /// 需切换的状态 /// </summary> [XmlElement("status")] public string Status { get; set; } } }
22.387097
58
0.5
[ "Apache-2.0" ]
554393109/alipay-sdk-net-all
AlipaySDKNet.Standard/Domain/SearchToggleBoxStatusRequest.cs
714
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.WebJobs.Extensions.MicrosoftGraph.Tests { using System; using System.IO; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Graph; using Moq; internal static class OneDriveMockUtilities { public static void MockGetOneDriveContentStreamAsync(this Mock<IGraphServiceClient> mock, Stream returnValue) { mock.Setup(client => client.Me .Drive .Root .ItemWithPath(It.IsAny<string>()) .Content .Request(null) .GetAsync(It.IsAny<CancellationToken>(), System.Net.Http.HttpCompletionOption.ResponseContentRead)) .Returns(Task.FromResult(returnValue)); } public static void MockGetOneDriveContentStreamFromShareAsync(this Mock<IGraphServiceClient> mock, Stream returnValue) { mock.Setup(client => client .Shares[It.IsAny<string>()] .Root .Content .Request(null) .GetAsync(It.IsAny<CancellationToken>(), System.Net.Http.HttpCompletionOption.ResponseContentRead)) .Returns(Task.FromResult(returnValue)); } public static void VerifyGetOneDriveContentStreamFromShareAsync(this Mock<IGraphServiceClient> mock, string shareToken) { //First verify GetAsync() called mock.Verify(client => client .Shares[shareToken] .Root .Content .Request(null) .GetAsync(It.IsAny<CancellationToken>(), System.Net.Http.HttpCompletionOption.ResponseContentRead)); //Then verify sharetoken correct mock.Verify(client => client .Shares[shareToken]); } public static void MockGetOneDriveItemAsync(this Mock<IGraphServiceClient> mock, DriveItem returnValue) { mock.Setup(client => client .Me .Drive .Root .ItemWithPath(It.IsAny<string>()) .Request() .GetAsync(It.IsAny<CancellationToken>())) .Returns(Task.FromResult(returnValue)); } public static void MockUploadOneDriveItemAsync(this Mock<IGraphServiceClient> mock, DriveItem returnValue) { mock.Setup(client => client .Me .Drive .Root .ItemWithPath(It.IsAny<string>()) .Content .Request(null) .PutAsync<DriveItem>(It.IsAny<Stream>(), It.IsAny<CancellationToken>(), System.Net.Http.HttpCompletionOption.ResponseContentRead)) .Returns(Task.FromResult(returnValue)); } public static void VerifyUploadOneDriveItemAsync(this Mock<IGraphServiceClient> mock, string path, Expression<Func<Stream, bool>> streamCondition) { mock.Verify(client => client .Me .Drive .Root .ItemWithPath(path) .Content .Request(null) .PutAsync<DriveItem>(It.Is<Stream>(streamCondition), It.IsAny<CancellationToken>(), System.Net.Http.HttpCompletionOption.ResponseContentRead)); } } }
38.215054
159
0.586944
[ "MIT" ]
Azure/azure-functions-microsoftgraph-extension
test/MicrosoftGraph.Tests/OneDriveMockUtilities.cs
3,556
C#
// ReSharper disable UnusedMember.Global #pragma warning disable 1591 // ReSharper disable InconsistentNaming using System.ComponentModel; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Exchange.Core.Contracts.ExchangeRates { /// <summary> /// Global Currency Codes /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum ExchangeRateCurrencyCodes { /// <summary> /// USD - US Dollar US$ /// </summary> [Description("USD")] USD, /// <summary> /// BRL - Brazilian Real R$ /// </summary> [Description("BRL")] BRL, /// <summary> /// USD - Australian Dollar US$ /// </summary> [Description("AUD")] AUD, [Description("BGN")] BGN, [Description("CAD")] CAD, [Description("CHF")] CHF, [Description("CNY")] CNY, [Description("CZK")] CZK, [Description("DKK")] DKK, [Description("GBP")] GBP, [Description("HKD")] HKD, [Description("HRK")] HRK, [Description("HUF")] HUF, [Description("IDR")] IDR, [Description("ILS")] ILS, [Description("INR")] INR, [Description("ISK")] ISK, [Description("JPY")] JPY, [Description("KRW")] KRW, [Description("MXN")] MXN, [Description("MYR")] MYR, [Description("NOK")] NOK, [Description("NZD")] NZD, [Description("PHP")] PHP, [Description("PLN")] PLN, [Description("RON")] RON, [Description("RUB")] RUB, [Description("SEK")] SEK, [Description("SGD")] SGD, [Description("THB")] THB, [Description("TRY")] TRY, [Description("ZAR")] ZAR } }
21.978261
48
0.470326
[ "Apache-2.0" ]
elioseverojunior/Exchange
src/Core/Exchange.Core/Contracts/ExchangeRates/ExchangeRateCurrencyCodes.cs
2,022
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Live_Demo_Web_Forms.Models; namespace Live_Demo_Web_Forms.Account { public partial class TwoFactorAuthenticationSignIn : System.Web.UI.Page { private ApplicationSignInManager signinManager; private ApplicationUserManager manager; public TwoFactorAuthenticationSignIn() { manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>(); } protected void Page_Load(object sender, EventArgs e) { var userId = signinManager.GetVerifiedUserId<ApplicationUser, string>(); if (userId == null) { Response.Redirect("/Account/Error", true); } var userFactors = manager.GetValidTwoFactorProviders(userId); Providers.DataSource = userFactors.Select(x => x).ToList(); Providers.DataBind(); } protected void CodeSubmit_Click(object sender, EventArgs e) { bool rememberMe = false; bool.TryParse(Request.QueryString["RememberMe"], out rememberMe); var result = signinManager.TwoFactorSignIn<ApplicationUser, string>(SelectedProvider.Value, Code.Text, isPersistent: rememberMe, rememberBrowser: RememberBrowser.Checked); switch (result) { case SignInStatus.Success: IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); break; case SignInStatus.LockedOut: Response.Redirect("/Account/Lockout"); break; case SignInStatus.Failure: default: FailureText.Text = "Invalid code"; ErrorMessage.Visible = true; break; } } protected void ProviderSubmit_Click(object sender, EventArgs e) { if (!signinManager.SendTwoFactorCode(Providers.SelectedValue)) { Response.Redirect("/Account/Error"); } var user = manager.FindById(signinManager.GetVerifiedUserId<ApplicationUser, string>()); if (user != null) { var code = manager.GenerateTwoFactorToken(user.Id, Providers.SelectedValue); } SelectedProvider.Value = Providers.SelectedValue; sendcode.Visible = false; verifycode.Visible = true; } } }
36.883117
183
0.607746
[ "MIT" ]
kaizer04/Telerik-Academy-2013-2014
ASP.NET WebForms/Live-Demo-Web-Forms/Live-Demo-Web-Forms/Account/TwoFactorAuthenticationSignIn.aspx.cs
2,842
C#
using MassTransit.EntityFrameworkCoreIntegration.Mappings; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Registration; namespace WorkerRoleCommandProcessor { public class OrderStateMap : SagaClassMap<OrderState> { protected override void Configure(EntityTypeBuilder<OrderState> entity, ModelBuilder model) { entity.Property(x => x.ConferenceId); entity.Property(x => x.CurrentState).HasMaxLength(100); entity.Property(x => x.ExpirationId); entity.Property(x => x.OrderId); entity.Property(x => x.ReservationId); entity.Property(x => x.ReservationAutoExpiration); entity.Property(x => x.RowVersion).IsRowVersion(); } } }
37.761905
99
0.686003
[ "Apache-2.0" ]
huy-ngoduc/ConferenceManagement
src/Conference/CommandProcessorWorker/OrderStateMap.cs
795
C#
/* * Exchange Web Services Managed API * * Copyright (c) Microsoft Corporation * All rights reserved. * * 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. */ namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.Generic; using System.Text; /// <summary> /// Represents a GetUserAvailability request. /// </summary> internal sealed class GetUserAvailabilityRequest : SimpleServiceRequestBase { private IEnumerable<AttendeeInfo> attendees; private TimeWindow timeWindow; private AvailabilityData requestedData = AvailabilityData.FreeBusyAndSuggestions; private AvailabilityOptions options; /// <summary> /// Initializes a new instance of the <see cref="GetUserAvailabilityRequest"/> class. /// </summary> /// <param name="service">The service.</param> internal GetUserAvailabilityRequest(ExchangeService service) : base(service) { } /// <summary> /// Gets the name of the XML element. /// </summary> /// <returns>XML element name,</returns> internal override string GetXmlElementName() { return XmlElementNames.GetUserAvailabilityRequest; } /// <summary> /// Gets a value indicating whether the TimeZoneContext SOAP header should be eimitted. /// </summary> /// <value><c>true</c> if the time zone should be emitted; otherwise, <c>false</c>.</value> internal override bool EmitTimeZoneHeader { get { return true; } } /// <summary> /// Gets a value indicating whether free/busy data is requested. /// </summary> internal bool IsFreeBusyViewRequested { get { return this.requestedData == AvailabilityData.FreeBusy || this.requestedData == AvailabilityData.FreeBusyAndSuggestions; } } /// <summary> /// Gets a value indicating whether suggestions are requested. /// </summary> internal bool IsSuggestionsViewRequested { get { return this.requestedData == AvailabilityData.Suggestions || this.requestedData == AvailabilityData.FreeBusyAndSuggestions; } } /// <summary> /// Validate request. /// </summary> internal override void Validate() { base.Validate(); this.Options.Validate(this.TimeWindow.Duration); } /// <summary> /// Writes XML elements. /// </summary> /// <param name="writer">The writer.</param> internal override void WriteElementsToXml(EwsServiceXmlWriter writer) { // Only serialize the TimeZone property against an Exchange 2007 SP1 server. // Against Exchange 2010, the time zone is emitted in the request's SOAP header. if (writer.Service.RequestedServerVersion == ExchangeVersion.Exchange2007_SP1) { LegacyAvailabilityTimeZone legacyTimeZone = new LegacyAvailabilityTimeZone(writer.Service.TimeZone); legacyTimeZone.WriteToXml(writer, XmlElementNames.TimeZone); } writer.WriteStartElement(XmlNamespace.Messages, XmlElementNames.MailboxDataArray); foreach (AttendeeInfo attendee in this.Attendees) { attendee.WriteToXml(writer); } writer.WriteEndElement(); // MailboxDataArray this.Options.WriteToXml(writer, this); } /// <summary> /// Gets the name of the response XML element. /// </summary> /// <returns>XML element name,</returns> internal override string GetResponseXmlElementName() { return XmlElementNames.GetUserAvailabilityResponse; } /// <summary> /// Parses the response. /// </summary> /// <param name="reader">The reader.</param> /// <returns>Response object.</returns> internal override object ParseResponse(EwsServiceXmlReader reader) { GetUserAvailabilityResults serviceResponse = new GetUserAvailabilityResults(); if (this.IsFreeBusyViewRequested) { serviceResponse.AttendeesAvailability = new ServiceResponseCollection<AttendeeAvailability>(); reader.ReadStartElement(XmlNamespace.Messages, XmlElementNames.FreeBusyResponseArray); do { reader.Read(); if (reader.IsStartElement(XmlNamespace.Messages, XmlElementNames.FreeBusyResponse)) { AttendeeAvailability freeBusyResponse = new AttendeeAvailability(); freeBusyResponse.LoadFromXml(reader, XmlElementNames.ResponseMessage); if (freeBusyResponse.ErrorCode == ServiceError.NoError) { freeBusyResponse.LoadFreeBusyViewFromXml(reader, this.Options.RequestedFreeBusyView); } serviceResponse.AttendeesAvailability.Add(freeBusyResponse); } } while (!reader.IsEndElement(XmlNamespace.Messages, XmlElementNames.FreeBusyResponseArray)); } if (this.IsSuggestionsViewRequested) { serviceResponse.SuggestionsResponse = new SuggestionsResponse(); reader.ReadStartElement(XmlNamespace.Messages, XmlElementNames.SuggestionsResponse); serviceResponse.SuggestionsResponse.LoadFromXml(reader, XmlElementNames.ResponseMessage); if (serviceResponse.SuggestionsResponse.ErrorCode == ServiceError.NoError) { serviceResponse.SuggestionsResponse.LoadSuggestedDaysFromXml(reader); } reader.ReadEndElement(XmlNamespace.Messages, XmlElementNames.SuggestionsResponse); } return serviceResponse; } /// <summary> /// Gets the request version. /// </summary> /// <returns>Earliest Exchange version in which this request is supported.</returns> internal override ExchangeVersion GetMinimumRequiredServerVersion() { return ExchangeVersion.Exchange2007_SP1; } /// <summary> /// Executes this request. /// </summary> /// <returns>Service response.</returns> internal GetUserAvailabilityResults Execute() { return (GetUserAvailabilityResults)this.InternalExecute(); } /// <summary> /// Gets or sets the attendees. /// </summary> public IEnumerable<AttendeeInfo> Attendees { get { return this.attendees; } set { this.attendees = value; } } /// <summary> /// Gets or sets the time window in which to retrieve user availability information. /// </summary> public TimeWindow TimeWindow { get { return this.timeWindow; } set { this.timeWindow = value; } } /// <summary> /// Gets or sets a value indicating what data is requested (free/busy and/or suggestions). /// </summary> public AvailabilityData RequestedData { get { return this.requestedData; } set { this.requestedData = value; } } /// <summary> /// Gets an object that allows you to specify options controlling the information returned /// by the GetUserAvailability request. /// </summary> public AvailabilityOptions Options { get { return this.options; } set { this.options = value; } } } }
38.091286
144
0.600545
[ "MIT" ]
AdamMachera/ews-managed-api
Core/Requests/GetUserAvailabilityRequest.cs
9,180
C#
using System.Configuration; using Microsoft.Practices.Unity; using Microsoft.Practices.Unity.Configuration; using Nancy; using Nancy.Bootstrapper; using Nancy.Bootstrappers.Unity; namespace Chiro.Gap.UpdateApi { public class Bootstrapper : UnityNancyBootstrapper { protected override void ApplicationStartup(IUnityContainer container, IPipelines pipelines) { // No registrations should be performed in here, however you may // resolve things that are needed during application startup. } protected override void ConfigureApplicationContainer(IUnityContainer existingContainer) { // Perform registation that should have an application lifetime var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity"); // Als section null is, is er geen unity-configuratie in app.config of web.config. // Op zich geen probleem, want de configuratie kan ook at runtime if (section != null) { // Als je hier een IoException of zoiets krijgt, dan mis je waarschijnlijk referenties // naar assemblies die in je untiy-configuratie voorkomen. // Typisch voor services: Chiro.Cdf.DependencyInjectionBehavior. // Kijk ook eens na of alle assembly's in de types van de unity-configuratie // bij de 'References' van je project staan. // Ook een mogelijke bron van problemen, is als interfaces van assembly zijn veranderd, // maar als dat niet is aangepast in de configuratiefile :) section.Configure(existingContainer); } } protected override void ConfigureRequestContainer(IUnityContainer container, NancyContext context) { // Perform registrations that should have a request lifetime } protected override void RequestStartup(IUnityContainer container, IPipelines pipelines, NancyContext context) { // No registrations should be performed in here, however you may // resolve things that are needed during request startup. } } }
42.576923
117
0.669377
[ "Apache-2.0" ]
Chirojeugd-Vlaanderen/gap
Solution/Chiro.Gap.UpdateApi/Bootstrapper.cs
2,216
C#
using System; using OpenTelemetry.Trace; using Samples.AspNetCoreMvc.Controllers; namespace Samples.AspNetCoreMvc { public class OtelSdkPlugin { public TracerProviderBuilder ConfigureTracerProvider(TracerProviderBuilder builder) { var typeName = this.ToString(); Console.WriteLine($"Hello from {typeName}"); return builder.AddRedisInstrumentation(RedisController.Connection); } } }
26.764706
91
0.698901
[ "Apache-2.0" ]
mic-max/opentelemetry-dotnet-instrumentation
samples/Samples.AspNetCoreMvc31/OtelSdkPlugin.cs
455
C#
// // ButtonShadowEffect.cs // Creates a custom Button Shadow Effect using PlatformEffects (Android) // // Created by Steven F. Daniel on 16/07/2018. // Copyright © 2018 GENIESOFT STUDIOS. All rights reserved. // using Xamarin.Forms; using Xamarin.Forms.Platform.Android; using System; [assembly: ResolutionGroupName("GeniesoftStudios")] [assembly: ExportEffect(typeof(TrackMyWalks.Droid.CustomEffects.ButtonShadowEffect), "ButtonShadowEffect")] namespace TrackMyWalks.Droid.CustomEffects { public class ButtonShadowEffect : PlatformEffect { protected override void OnAttached() { try { var control = Control as Android.Widget.Button; Android.Graphics.Color color = Android.Graphics.Color.Red; control.SetShadowLayer(12, 4, 4, color); } catch (Exception ex) { Console.WriteLine("Cannot set property on attached control. Error: " + ex.Message); } } protected override void OnDetached() { throw new NotImplementedException(); } } }
30.918919
107
0.634615
[ "MIT" ]
PacktPublishing/Mastering-Xamarin-UI-Development---Second-Edition
Chapter08/TrackMyWalks/TrackMyWalks.Android/CustomEffects/ButtonShadowEffect.cs
1,147
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace DemoMVC { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
25.727273
70
0.704947
[ "MIT" ]
rombo84fx/fictional-spork
DemoMVC/DemoMVC/Global.asax.cs
568
C#
/* MIT LICENSE Copyright 2017 Digital Ruby, LLC - http://www.digitalruby.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace ExchangeSharp { /// <summary> /// Useful extension methods for all sorts of things. Who says a kitchen sink class is bad? /// </summary> public static class CryptoUtility { private static readonly DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); private static readonly DateTime unixEpochLocal = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Local); private static readonly Encoding utf8EncodingNoPrefix = new UTF8Encoding(false, true); private static Func<DateTime> utcNowFunc = UtcNowFuncImpl; private static DateTime UtcNowFuncImpl() { // this is the only place in the code that DateTime.UtcNow is allowed. DateTime.UtcNow and DateTime.Now should not exist anywhere else in the code. return DateTime.UtcNow; } /// <summary> /// Set utc now func for override CryptoUtility.UtcNow. Set to null to go back to default CryptoUtility.UtcNow. /// This is primarily useful for unit or integration testing. /// </summary> /// <param name="utcNowFunc">Utc now override func</param> public static void SetDateTimeUtcNowFunc(Func<DateTime> utcNowFunc) { CryptoUtility.utcNowFunc = utcNowFunc ?? UtcNowFuncImpl; } /// <summary> /// Empty object array /// </summary> public static readonly object[] EmptyObjectArray = new object[0]; /// <summary> /// Empty string array /// </summary> public static readonly string[] EmptyStringArray = new string[0]; /// <summary> /// Throw ArgumentNullException if obj is null /// </summary> /// <param name="obj">Object</param> /// <param name="name">Parameter name</param> /// <param name="message">Message</param> public static void ThrowIfNull(this object obj, string name, string message = null) { if (obj == null) { throw new ArgumentNullException(name, message); } } /// <summary> /// Throw ArgumentNullException if obj is null or whitespace /// </summary> /// <param name="obj">Object</param> /// <param name="name">Parameter name</param> /// <param name="message">Message</param> public static void ThrowIfNullOrWhitespace(this string obj, string name, string message = null) { if (string.IsNullOrWhiteSpace(obj)) { throw new ArgumentNullException(name, message); } } /// <summary> /// Convert an object to string using invariant culture /// </summary> /// <param name="obj">Object</param> /// <param name="defaultValue">Default value if null</param> /// <returns>String</returns> public static string ToStringInvariant(this object obj, string defaultValue = "") { return Convert.ToString(obj, CultureInfo.InvariantCulture) ?? defaultValue; } /// <summary> /// Convert an object to string uppercase using invariant culture /// </summary> /// <param name="obj">Object</param> /// <returns>String</returns> public static string ToStringUpperInvariant(this object obj) { return ToStringInvariant(obj).ToUpperInvariant(); } /// <summary> /// Convert an object to string lowercase using invariant culture /// </summary> /// <param name="obj">Object</param> /// <returns>String</returns> public static string ToStringLowerInvariant(this object obj) { return ToStringInvariant(obj).ToLowerInvariant(); } /// <summary> /// Convenience method to compare strings. The default uses OrginalIgnoreCase. /// </summary> /// <param name="s">String</param> /// <param name="other">Other string</param> /// <param name="option">Option</param> /// <returns>True if equal, false if not</returns> public static bool EqualsWithOption(this string s, string other, StringComparison option = StringComparison.OrdinalIgnoreCase) { if (s == null || other == null) { return false; } return s.Equals(other, option); } /// <summary> /// Decompress gzip bytes /// </summary> /// <param name="bytes">Bytes that are gzipped</param> /// <returns>Uncompressed bytes</returns> public static byte[] DecompressGzip(byte[] bytes) { using (var compressStream = new MemoryStream(bytes)) { using (var zipStream = new GZipStream(compressStream, CompressionMode.Decompress)) { using (var resultStream = new MemoryStream()) { zipStream.CopyTo(resultStream); return resultStream.ToArray(); } } } } /// <summary> /// Decompress deflate bytes /// </summary> /// <param name="bytes">Bytes that are Deflate</param> /// <returns>Uncompressed bytes</returns> public static byte[] DecompressDeflate(byte[] bytes) { using (var compressStream = new MemoryStream(bytes)) { using (var zipStream = new DeflateStream(compressStream, CompressionMode.Decompress)) { using (var resultStream = new MemoryStream()) { zipStream.CopyTo(resultStream); return resultStream.ToArray(); } } } } /// <summary> /// Convert a DateTime and set the kind to UTC using the DateTimeKind property. /// </summary> /// <param name="obj">Object to convert</param> /// <param name="defaultValue">Default value if no conversion is possible</param> /// <returns>DateTime with DateTimeKind kind or defaultValue if no conversion possible</returns> public static DateTime ToDateTimeInvariant(this object obj, DateTime defaultValue = default) { if (obj == null) { return defaultValue; } JValue jValue = obj as JValue; if (jValue != null && jValue.Value == null) { return defaultValue; } DateTime dt = (DateTime)Convert.ChangeType(jValue == null ? obj : jValue.Value, typeof(DateTime), CultureInfo.InvariantCulture); return DateTime.SpecifyKind(dt, DateTimeKind.Utc); } /// <summary> /// Convert an object to another type using invariant culture. Consider using the string or DateTime conversions if you are dealing with those types. /// </summary> /// <typeparam name="T">Type</typeparam> /// <param name="obj">Object</param> /// <param name="defaultValue">Default value if no conversion is possible</param> /// <returns>Converted value or defaultValue if not conversion was possible</returns> public static T ConvertInvariant<T>(this object obj, T defaultValue = default) { if (obj == null) { return defaultValue; } JValue jValue = obj as JValue; if (jValue != null && jValue.Value == null) { return defaultValue; } T result; try { result = (T)Convert.ChangeType(jValue == null ? obj : jValue.Value, typeof(T), CultureInfo.InvariantCulture); if (typeof(T) == typeof(decimal)) { return (T)(object)((decimal)(object)result).Normalize(); } } catch { if (typeof(T) == typeof(bool)) { // try zero or one return (T)(object)((jValue ?? obj).ToStringInvariant() == "1"); } else { // fallback to float conversion, i.e. 1E-1 for a decimal conversion will fail string stringValue = (jValue == null ? obj.ToStringInvariant() : jValue.Value.ToStringInvariant()); if (string.IsNullOrWhiteSpace(stringValue)) return defaultValue; decimal decimalValue = decimal.Parse(stringValue, System.Globalization.NumberStyles.Float, CultureInfo.InvariantCulture); return (T)Convert.ChangeType(decimalValue, typeof(T), CultureInfo.InvariantCulture); } } return result; } /// <summary> /// Converts a hex string to a byte array /// </summary> /// <param name="hex">hex string</param> /// <returns>byte array representation of the same string</returns> public static byte[] StringToByteArray(this string hex) { // https://stackoverflow.com/questions/321370/how-can-i-convert-a-hex-string-to-a-byte-array return Enumerable.Range(0, hex.Length / 2) .Select(x => Convert .ToByte(hex.Substring(x * 2, 2), 16)) .ToArray(); } /// <summary> /// Covnert a secure string to a non-secure string /// </summary> /// <param name="s">SecureString</param> /// <returns>Non-secure string</returns> public static string ToUnsecureString(this SecureString s) { if (s == null) { return null; } IntPtr valuePtr = IntPtr.Zero; try { valuePtr = Marshal.SecureStringToGlobalAllocUnicode(s); return Marshal.PtrToStringUni(valuePtr); } finally { Marshal.ZeroFreeGlobalAllocUnicode(valuePtr); } } /// <summary> /// Convert a secure string to non-secure binary data /// </summary> /// <param name="s">SecureString</param> /// <returns>Binary data</returns> public static byte[] ToUnsecureBytesUTF8(this SecureString s) { if (s == null) { return null; } return ToUnsecureString(s).ToBytesUTF8(); } /// <summary> /// Decode a secure string that is in base64 format to binary data /// </summary> /// <param name="s">SecureString in base64 format</param> /// <returns>Binary data</returns> public static byte[] ToBytesBase64Decode(this SecureString s) { if (s == null) { return null; } return Convert.FromBase64String(ToUnsecureString(s)); } /// <summary> /// Convert a string to a secure string /// </summary> /// <param name="unsecure">Plain text string</param> /// <returns>SecureString</returns> public static SecureString ToSecureString(this string unsecure) { if (unsecure == null) { return null; } SecureString secure = new SecureString(); foreach (char c in unsecure) { secure.AppendChar(c); } return secure; } /// <summary> /// Get utf-8 bytes from a string /// </summary> /// <param name="s">String</param> /// <returns>UTF8 bytes or null if s is null</returns> public static byte[] ToBytesUTF8(this string s) { if (s == null) { return null; } return utf8EncodingNoPrefix.GetBytes(s); } /// <summary> /// Convert utf-8 bytes to a string /// </summary> /// <param name="bytes"></param> /// <param name="index">Offset</param> /// <param name="length">Length</param> /// <returns>UTF-8 string or null if bytes is null</returns> public static string ToStringFromUTF8(this byte[] bytes, int index = 0, int length = 0) { if (bytes == null) { return null; } length = (length <= 0 ? bytes.Length : length); return utf8EncodingNoPrefix.GetString(bytes, index, length); } /// <summary> /// Convert gzipped utf-8 bytes to a string /// </summary> /// <param name="bytes"></param> /// <returns>UTF-8 string or null if bytes is null</returns> public static string ToStringFromUTF8Gzip(this byte[] bytes) { if (bytes == null) { return null; } return DecompressGzip(bytes).ToStringFromUTF8(); } /// <summary> /// Convert Deflate utf-8 bytes to a string /// </summary> /// <param name="bytes"></param> /// <returns>UTF-8 string or null if bytes is null</returns> public static string ToStringFromUTF8Deflate(this byte[] bytes) { if (bytes == null) { return null; } return DecompressDeflate(bytes).ToStringFromUTF8(); } /// <summary> /// JWT encode - converts to base64 string first then replaces + with - and / with _ /// </summary> /// <param name="input">Input string</param> /// <returns>Encoded string</returns> public static string JWTEncode(this byte[] input) { return Convert.ToBase64String(input) .Trim('=') .Replace('+', '-') .Replace('/', '_'); } /// <summary> /// JWT encode - converts to base64 string first then replaces + with - and / with _ /// </summary> /// <param name="input">Input string</param> /// <returns>Encoded string</returns> public static string JWTEncode(this string input) { return Convert.ToBase64String(input.ToBytesUTF8()) .Trim('=') .Replace('+', '-') .Replace('/', '_'); } /// <summary> /// JWT decode from JWTEncode /// </summary> /// <param name="input">Input</param> /// <returns>Decoded string</returns> public static string JWTDecodedString(this string input) { string output = input.Replace('-', '+').Replace('_', '/'); switch (output.Length % 4) // Pad with trailing '='s { case 0: break; // No pad chars in this case case 2: output += "=="; break; // Two pad chars case 3: output += "="; break; // One pad char default: throw new ArgumentException("Bad JWT string: " + input); } return Convert.FromBase64String(output).ToStringFromUTF8(); } /// <summary> /// JWT decode from JWTEncode /// </summary> /// <param name="input">Input</param> /// <returns>Decoded bytes</returns> public static byte[] JWTDecodedBytes(this string input) { string output = input.Replace('-', '+').Replace('_', '/'); switch (output.Length % 4) // Pad with trailing '='s { case 0: break; // No pad chars in this case case 2: output += "=="; break; // Two pad chars case 3: output += "="; break; // One pad char default: throw new ArgumentException("Bad JWT string: " + input); } return Convert.FromBase64String(output); } /// <summary> /// Url encode extension - use this for ALL url encoding / escaping /// </summary> /// <param name="s">String to url encode</param> /// <returns>Url encoded string</returns> public static string UrlEncode(this string s) { return WebUtility.UrlEncode((s ?? string.Empty)); } /// <summary> /// Form encode extension - use this for ALL form encoding / escaping /// </summary> /// <param name="s">String to form encode</param> /// <returns>Form encoded string</returns> public static string FormEncode(this string s) { return (s ?? string.Empty) .Replace("%", "%25") .Replace("+", "%2B") .Replace(' ', '+') .Replace("&", "%26") .Replace("=", "%3D") .Replace("\r", "%0D") .Replace("\n", "%0A") .Replace(":", "%3A") .Replace("/", "%2F") .Replace("@", "%40") .Replace(";", "%3B"); } /// <summary> /// Clamp a decimal to a min and max value /// </summary> /// <param name="minValue">Min value</param> /// <param name="maxValue">Max value</param> /// <param name="stepSize">Smallest unit value should be evenly divisible by</param> /// <param name="value">Value to clamp</param> /// <returns>Clamped value</returns> public static decimal ClampDecimal(decimal minValue, decimal maxValue, decimal? stepSize, decimal value) { if (minValue < 0) { throw new ArgumentOutOfRangeException(nameof(minValue)); } else if (maxValue < 0) { throw new ArgumentOutOfRangeException(nameof(maxValue)); } else if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value)); } else if (minValue > maxValue) { throw new ArgumentOutOfRangeException(nameof(minValue)); } if (stepSize.HasValue) { if (stepSize < 0) { throw new ArgumentOutOfRangeException(nameof(stepSize)); } decimal mod = value % stepSize.Value; value -= mod; } if (maxValue > 0) { value = Math.Min(maxValue, value); } value = Math.Max(minValue, value); return value.Normalize(); } /// <summary>Remove trailing zeroes on the decimal.</summary> /// <param name="value">The value to normalize.</param> /// <returns>1.230000 becomes 1.23</returns> public static decimal Normalize(this decimal value) { return value / 1.000000000000000000000000000000000m; } /// <summary> /// Get a UTC date time from a unix epoch in seconds /// </summary> /// <param name="unixTimeStampSeconds">Unix epoch in seconds</param> /// <returns>UTC DateTime</returns> public static DateTime UnixTimeStampToDateTimeSeconds(this double unixTimeStampSeconds) { return unixEpoch.AddSeconds(unixTimeStampSeconds); } /// <summary> /// Get a UTC date time from a unix epoch in seconds /// </summary> /// <param name="unixTimeStampSeconds">Unix epoch in seconds</param> /// <returns>UTC DateTime</returns> public static DateTime UnixTimeStampToDateTimeSeconds(this long unixTimeStampSeconds) { return unixEpoch.AddSeconds(unixTimeStampSeconds); } /// <summary> /// Get a utc date time from a local unix epoch in seconds /// </summary> /// <param name="unixTimeStampSeconds">Unix epoch in seconds</param> /// <returns>UTC DateTime</returns> public static DateTime UnixTimeStampLocalToDateTimeSeconds(this double unixTimeStampSeconds) { return unixEpochLocal.AddSeconds(unixTimeStampSeconds).ToUniversalTime(); } /// <summary> /// Get a UTC date time from a unix epoch in milliseconds /// </summary> /// <param name="unixTimeStampSeconds">Unix epoch in milliseconds</param> /// <returns>UTC DateTime</returns> public static DateTime UnixTimeStampToDateTimeMilliseconds(this double unixTimeStampMilliseconds) { return unixEpoch.AddMilliseconds(unixTimeStampMilliseconds); } /// <summary> /// Get a UTC date time from a unix epoch in milliseconds /// </summary> /// <param name="unixTimeStampSeconds">Unix epoch in milliseconds</param> /// <returns>UTC DateTime</returns> public static DateTime UnixTimeStampToDateTimeMilliseconds(this long unixTimeStampMilliseconds) { return unixEpoch.AddMilliseconds(unixTimeStampMilliseconds); } /// <summary> /// Get a utc date time from a local unix epoch in milliseconds /// </summary> /// <param name="unixTimeStampSeconds">Unix epoch in milliseconds</param> /// <returns>Local DateTime</returns> public static DateTime UnixTimeStampLocalToDateTimeMilliseconds(this double unixTimeStampMilliseconds) { return unixEpochLocal.AddMilliseconds(unixTimeStampMilliseconds).ToUniversalTime(); } /// <summary> /// Get a utc date time from a local unix epoch in milliseconds /// </summary> /// <param name="unixTimeStampSeconds">Unix epoch in milliseconds</param> /// <returns>Local DateTime</returns> public static DateTime UnixTimeStampLocalToDateTimeMilliseconds(this long unixTimeStampMilliseconds) { return unixEpochLocal.AddMilliseconds(unixTimeStampMilliseconds).ToUniversalTime(); } /// <summary> /// Get a UTC date time from a unix epoch in microseconds /// </summary> /// <param name="unixTimeStampSeconds">Unix epoch in microseconds</param> /// <returns>UTC DateTime</returns> public static DateTime UnixTimeStampToDateTimeMicroseconds(this long unixTimeStampMicroseconds) { return unixEpoch.AddTicks(unixTimeStampMicroseconds * 10); } /// <summary> /// Get a UTC date time from a unix epoch in nanoseconds /// </summary> /// <param name="unixTimeStampSeconds">Unix epoch in milliseconds</param> /// <returns>UTC DateTime</returns> public static DateTime UnixTimeStampToDateTimeNanoseconds(this double unixTimeStampNanoseconds) { return unixEpoch.AddTicks((long)unixTimeStampNanoseconds / 100); } /// <summary> /// Get a UTC date time from a unix epoch in nanoseconds /// </summary> /// <param name="unixTimeStampSeconds">Unix epoch in milliseconds</param> /// <returns>UTC DateTime</returns> public static DateTime UnixTimeStampToDateTimeNanoseconds(this long unixTimeStampNanoseconds) { return unixEpoch.AddTicks(unixTimeStampNanoseconds / 100); } /// <summary> /// Get a unix timestamp in seconds from a DateTime /// </summary> /// <param name="dt">DateTime</param> /// <returns>Unix epoch in seconds</returns> public static double UnixTimestampFromDateTimeSeconds(this DateTime dt) { if (dt.Kind != DateTimeKind.Utc) { dt = dt.ToUniversalTime(); } return (dt - unixEpoch).TotalSeconds; } /// <summary> /// Get a unix timestamp in milliseconds from a DateTime /// </summary> /// <param name="dt">DateTime</param> /// <returns>Unix timestamp in milliseconds</returns> public static double UnixTimestampFromDateTimeMilliseconds(this DateTime dt) { if (dt.Kind != DateTimeKind.Utc) { dt = dt.ToUniversalTime(); } return (dt - unixEpoch).TotalMilliseconds; } /// <summary> /// Convert a timestamp to DateTime. If value is null, CryptoUtility.UtcNow is returned. /// </summary> /// <param name="value">Timestamp object (JToken, string, double, etc.)</param> /// <param name="type">Type of timestamp</param> /// <returns>DateTime</returns> public static DateTime ParseTimestamp(object value, TimestampType type) { if (value == null || type == TimestampType.None) { return CryptoUtility.UtcNow; } switch (type) { case TimestampType.Iso8601: return value.ToDateTimeInvariant(); case TimestampType.UnixNanoseconds: return UnixTimeStampToDateTimeNanoseconds(value.ConvertInvariant<long>()); case TimestampType.UnixMicroeconds: return UnixTimeStampToDateTimeMicroseconds(value.ConvertInvariant<long>()); case TimestampType.UnixMillisecondsDouble: return UnixTimeStampToDateTimeMilliseconds(value.ConvertInvariant<double>()); case TimestampType.UnixMilliseconds: return UnixTimeStampToDateTimeMilliseconds(value.ConvertInvariant<long>()); case TimestampType.UnixSecondsDouble: return UnixTimeStampToDateTimeSeconds(value.ConvertInvariant<double>()); case TimestampType.UnixSeconds: return UnixTimeStampToDateTimeSeconds(value.ConvertInvariant<long>()); default: throw new ArgumentException("Invalid timestamp type " + type); } } /// <summary> /// Get a string that can be used for basic authentication. Put this in the 'Authorization' http header, and ensure you are using https. /// </summary> /// <param name="userName">User name or public key</param> /// <param name="password">Password or private key</param> /// <returns>Full authorization header text</returns> public static string BasicAuthenticationString(string userName, string password) { return "Basic " + Convert.ToBase64String((userName + ":" + password).ToBytesUTF8()); } /// <summary> /// Forces GetJsonForPayload to serialize the value of this key and nothing else. /// This is a little hacky, but allows posting arrays instead of dictionary to API for bulk calls. /// Normally a good API design would require a dictionary post with an array key and then /// an array of values, allowing other key/values to be posted with the bulk call, /// but some API (I'm looking at you Bitmex) just accept an array and nothing else. /// </summary> public const string PayloadKeyArray = "__hacky_array_key__"; /// <summary> /// Convert a payload into json. If payload contains key PayloadKeyArray, that item is used only and serialized by itself /// </summary> /// <param name="payload">Payload</param> /// <returns>Json string</returns> public static string GetJsonForPayload(this Dictionary<string, object> payload) { if (payload != null && payload.Count != 0) { if (payload.TryGetValue(PayloadKeyArray, out object array)) { return JsonConvert.SerializeObject(array, DecimalConverter.Instance); } return JsonConvert.SerializeObject(payload, DecimalConverter.Instance); } return string.Empty; } public static string GetJsonForPayload(this Dictionary<string, object> payload, bool includeNonce = true) { if (includeNonce == false) { payload.Remove("nonce"); } return (GetJsonForPayload(payload)); } /// <summary> /// Write a form to a request /// </summary> /// <param name="request">Request</param> /// <param name="form">Form to write</param> public static async Task WriteToRequestAsync(this IHttpWebRequest request, string form) { if (string.IsNullOrEmpty(form) && request.Method != "GET") { request.AddHeader("content-length", "0"); } else if (!string.IsNullOrEmpty(form)) { byte[] bytes = form.ToBytesUTF8(); request.AddHeader("content-length", bytes.Length.ToStringInvariant()); await request.WriteAllAsync(bytes, 0, bytes.Length); } } /// <summary> /// Write a payload form to a request /// </summary> /// <param name="request">Request</param> /// <param name="payload">Payload</param> /// <returns>The form string that was written</returns> public static async Task<string> WritePayloadFormToRequestAsync(this IHttpWebRequest request, Dictionary<string, object> payload) { string form = GetFormForPayload(payload); await WriteToRequestAsync(request, form); return form; } /// <summary> /// Write a payload json to a request /// </summary> /// <param name="request">Request</param> /// <param name="payload">Payload</param> /// <returns>The json string that was written</returns> public static async Task<string> WritePayloadJsonToRequestAsync(this IHttpWebRequest request, Dictionary<string, object> payload) { string json = GetJsonForPayload(payload); await WriteToRequestAsync(request, json); return json; } /// <summary> /// Get a form for a request (form-encoded, like a query string) /// </summary> /// <param name="payload">Payload</param> /// <param name="includeNonce">Whether to add the nonce</param> /// <param name="orderByKey">Whether to order by the key</param> /// <param name="formEncode">True to use form encoding, false to use url encoding</param> /// <returns>Form string</returns> public static string GetFormForPayload(this IReadOnlyDictionary<string, object> payload, bool includeNonce = true, bool orderByKey = true, bool formEncode = true) { if (payload != null && payload.Count != 0) { StringBuilder form = new StringBuilder(); IEnumerable<KeyValuePair<string, object>> e = (orderByKey ? payload.OrderBy(kv => kv.Key) : payload.AsEnumerable<KeyValuePair<string, object>>()); foreach (KeyValuePair<string, object> keyValue in e) { if (!string.IsNullOrWhiteSpace(keyValue.Key) && keyValue.Value != null && (includeNonce || keyValue.Key != "nonce")) { string key = (formEncode ? keyValue.Key.FormEncode() : keyValue.Key.UrlEncode()); string value = (formEncode ? keyValue.Value.ToStringInvariant().FormEncode() : keyValue.Value.ToStringInvariant().UrlEncode()); form.Append($"{key}={value}&"); } } if (form.Length != 0) { form.Length--; // trim ampersand } return form.ToString(); } return string.Empty; } /// <summary> /// Append a dictionary of key/values to a url builder query /// </summary> /// <param name="uri">Uri builder</param> /// <param name="payload">Payload to append</param> public static void AppendPayloadToQuery(this UriBuilder uri, Dictionary<string, object> payload) { if (uri.Query.Length > 1) { uri.Query += "&"; } foreach (var kv in payload) { uri.Query += $"{kv.Key.UrlEncode()}={kv.Value.ToStringInvariant().UrlEncode()}&"; } uri.Query = uri.Query.Trim('&'); } /// <summary> /// Get a value from dictionary with default fallback /// </summary> /// <typeparam name="TKey">Key type</typeparam> /// <typeparam name="TValue">Value type</typeparam> /// <param name="dictionary">Dictionary</param> /// <param name="key">Key</param> /// <param name="defaultValue">Default value</param> /// <returns>Found value or default</returns> public static TValue TryGetValueOrDefault<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue) { if (!dictionary.TryGetValue(key, out TValue value)) { value = defaultValue; } return value; } /// <summary> /// Copy dictionary to another dictionary /// </summary> /// <typeparam name="TKey">Key type</typeparam> /// <typeparam name="TValue">Value type</typeparam> /// <param name="sourceDictionary"></param> /// <param name="destinationDictionary"></param> public static void CopyTo<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> sourceDictionary, IDictionary<TKey, TValue> destinationDictionary) { foreach (var kv in sourceDictionary) { destinationDictionary[kv.Key] = kv.Value; } } /// <summary> /// Sign a message with SHA256 hash /// </summary> /// <param name="message">Message to sign</param> /// <param name="key">Private key</param> /// <returns>Signature in hex</returns> public static string SHA256Sign(string message, string key) { return new HMACSHA256(key.ToBytesUTF8()).ComputeHash(message.ToBytesUTF8()).Aggregate(new StringBuilder(), (sb, b) => sb.AppendFormat("{0:x2}", b), (sb) => sb.ToString()); } public static string SHA256Sign(string message, string key, bool UseASCII) { var encoding = new ASCIIEncoding(); return Convert.ToBase64String(new HMACSHA256(encoding.GetBytes(key)).ComputeHash(encoding.GetBytes(message))); } /// <summary> /// Sign a message with SHA256 hash /// </summary> /// <param name="message">Message to sign</param> /// <param name="key">Private key bytes</param> /// <returns>Signature in hex</returns> public static string SHA256Sign(string message, byte[] key) { return new HMACSHA256(key).ComputeHash(message.ToBytesUTF8()).Aggregate(new StringBuilder(), (sb, b) => sb.AppendFormat("{0:x2}", b), (sb) => sb.ToString()); } /// <summary> /// Sign a message with SHA256 hash /// </summary> /// <param name="message">Message to sign</param> /// <param name="key">Private key bytes</param> /// <returns>Signature in base64</returns> public static string SHA256SignBase64(string message, byte[] key) { return Convert.ToBase64String(new HMACSHA256(key).ComputeHash(message.ToBytesUTF8())); } /// <summary> /// Sign a message with SHA384 hash /// </summary> /// <param name="message">Message to sign</param> /// <param name="key">Private key</param> /// <returns>Signature in hex</returns> public static string SHA384Sign(string message, string key) { return new HMACSHA384(key.ToBytesUTF8()).ComputeHash(message.ToBytesUTF8()).Aggregate(new StringBuilder(), (sb, b) => sb.AppendFormat("{0:x2}", b), (sb) => sb.ToString()); } /// <summary> /// Sign a message with SHA384 hash /// </summary> /// <param name="message">Message to sign</param> /// <param name="key">Private key bytes</param> /// <returns>Signature</returns> public static string SHA384Sign(string message, byte[] key) { return new HMACSHA384(key).ComputeHash(message.ToBytesUTF8()).Aggregate(new StringBuilder(), (sb, b) => sb.AppendFormat("{0:x2}", b), (sb) => sb.ToString()); } /// <summary> /// Sign a message with SHA384 hash /// </summary> /// <param name="message">Message to sign</param> /// <param name="key">Private key bytes</param> /// <returns>Signature in base64</returns> public static string SHA384SignBase64(string message, byte[] key) { return Convert.ToBase64String(new HMACSHA384(key).ComputeHash(message.ToBytesUTF8())); } /// <summary> /// Sign a message with SHA512 hash /// </summary> /// <param name="message">Message to sign</param> /// <param name="key">Private key</param> /// <returns>Signature in hex</returns> public static string SHA512Sign(string message, string key) { var hmac = new HMACSHA512(key.ToBytesUTF8()); var messagebyte = message.ToBytesUTF8(); var hashmessage = hmac.ComputeHash(messagebyte); return BitConverter.ToString(hashmessage).Replace("-", ""); } /// <summary> /// Sign a message with SHA512 hash /// </summary> /// <param name="message">Message to sign</param> /// <param name="key">Private key bytes</param> /// <returns>Signature in hex</returns> public static string SHA512Sign(string message, byte[] key) { var hmac = new HMACSHA512(key); var messagebyte = message.ToBytesUTF8(); var hashmessage = hmac.ComputeHash(messagebyte); return BitConverter.ToString(hashmessage).Replace("-", ""); } /// <summary> /// Sign a message with SHA512 hash /// </summary> /// <param name="message">Message to sign</param> /// <param name="key">Private key bytes</param> /// <returns>Signature in base64</returns> public static string SHA512SignBase64(string message, byte[] key) { var hmac = new HMACSHA512(key); var messagebyte = message.ToBytesUTF8(); var hashmessage = hmac.ComputeHash(messagebyte); return Convert.ToBase64String(hashmessage); } /// <summary> /// Sign a message with MD5 hash /// </summary> /// <param name="message">Message to sign</param> /// <returns>Signature in hex</returns> public static string MD5Sign(string message, byte[] key) { var hmac = new HMACMD5(key); var messagebyte = message.ToBytesUTF8(); var hashmessage = hmac.ComputeHash(messagebyte); return BitConverter.ToString(hashmessage).Replace("-", ""); } /// <summary> /// Sign a message with MD5 hash /// </summary> /// <param name="message">Message to sign</param> /// <returns>Signature in hex</returns> public static string MD5Sign(string message) { var md5 = new MD5CryptoServiceProvider(); var messagebyte = message.ToBytesUTF8(); var hashmessage = md5.ComputeHash(messagebyte); return BitConverter.ToString(hashmessage).Replace("-", ""); } /// <summary> /// Generate random salt /// </summary> /// <param name="length">Length of salt</param> /// <returns>Salt</returns> public static byte[] GenerateSalt(int length) { byte[] salt = new byte[length]; using (var rng = new RNGCryptoServiceProvider()) { rng.GetBytes(salt); } return salt; } /// <summary> /// AES encrypt data with a password and salt /// </summary> /// <param name="input">Data to encrypt</param> /// <param name="password">Password</param> /// <param name="salt">Salt</param> /// <returns>Encrypted data</returns> public static byte[] AesEncryption(byte[] input, byte[] password, byte[] salt) { if (input == null || input.Length == 0 || password == null || password.Length == 0 || salt == null || salt.Length == 0) { return null; } var encrypted = new MemoryStream(); var AES = new RijndaelManaged() { KeySize = 256, BlockSize = 128, Padding = PaddingMode.PKCS7, }; var key = new Rfc2898DeriveBytes(password, salt, 1024); AES.Key = key.GetBytes(AES.KeySize / 8); AES.IV = key.GetBytes(AES.BlockSize / 8); AES.Mode = CipherMode.CBC; encrypted.Write(salt, 0, salt.Length); var cs = new CryptoStream(encrypted, AES.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(input, 0, input.Length); cs.FlushFinalBlock(); return encrypted.ToArray(); } /// <summary> /// AES decrypt data with a password and salt /// </summary> /// <param name="input">Data to decrypt</param> /// <param name="password">Password</param> /// <param name="salt">Salt</param> /// <returns>Decrypted data</returns> public static byte[] AesDecryption(byte[] input, byte[] password, byte[] salt) { if (input == null || input.Length == 0 || password == null || password.Length == 0 || salt == null || salt.Length == 0) { return null; } MemoryStream decrypted = new MemoryStream(); var AES = new RijndaelManaged() { KeySize = 256, BlockSize = 128, Padding = PaddingMode.PKCS7, }; var key = new Rfc2898DeriveBytes(password, salt, 1024); AES.Key = key.GetBytes(AES.KeySize / 8); AES.IV = key.GetBytes(AES.BlockSize / 8); AES.Mode = CipherMode.CBC; MemoryStream encrypted = new MemoryStream(input); byte[] saltMatch = new byte[salt.Length]; if (encrypted.Read(saltMatch, 0, saltMatch.Length) != salt.Length || !salt.SequenceEqual(saltMatch)) { throw new InvalidOperationException("Invalid salt"); } var cs = new CryptoStream(encrypted, AES.CreateDecryptor(), CryptoStreamMode.Read); byte[] buffer = new byte[8192]; int count; while ((count = cs.Read(buffer, 0, buffer.Length)) > 0) { decrypted.Write(buffer, 0, count); } return decrypted.ToArray(); } /// <summary> /// Convert seconds to a period string, i.e. 5s, 1m, 2h, 3d, 1w, 1M, etc. /// </summary> /// <param name="seconds">Seconds. Use 60 for minute, 3600 for hour, 3600*24 for day, 3600*24*30 for month.</param> /// <returns>Period string</returns> public static string SecondsToPeriodString(int seconds) { const int minuteThreshold = 60; const int hourThreshold = 60 * 60; const int dayThreshold = 60 * 60 * 24; const int weekThreshold = dayThreshold * 7; const int monthThreshold = dayThreshold * 30; if (seconds >= monthThreshold) { return seconds / monthThreshold + "M"; } else if (seconds >= weekThreshold) { return seconds / weekThreshold + "w"; } else if (seconds >= dayThreshold) { return seconds / dayThreshold + "d"; } else if (seconds >= hourThreshold) { return seconds / hourThreshold + "h"; } else if (seconds >= minuteThreshold) { return seconds / minuteThreshold + "m"; } return seconds + "s"; } /// <summary> /// Convert seconds to a period string, i.e. 5sec, 1min, 2hour, 3day, 1week, 1month, 1year etc. /// </summary> /// <param name="seconds">Seconds. Use 60 for minute, 3600 for hour, 3600*24 for day, 3600*24*30 for month.</param> /// <returns>Period string</returns> public static string SecondsToPeriodStringLong(int seconds) { const int minuteThreshold = 60; const int hourThreshold = 60 * 60; const int dayThreshold = 60 * 60 * 24; const int weekThreshold = dayThreshold * 7; const int monthThreshold = dayThreshold * 30; const int yearThreshold = monthThreshold * 12; if (seconds >= yearThreshold) { return seconds / yearThreshold + "year"; } else if (seconds >= monthThreshold) { return seconds / monthThreshold + "mon"; } else if (seconds >= weekThreshold) { return seconds / weekThreshold + "week"; } else if (seconds >= dayThreshold) { return seconds / dayThreshold + "day"; } else if (seconds >= hourThreshold) { return seconds / hourThreshold + "hour"; } else if (seconds >= minuteThreshold) { return seconds / minuteThreshold + "min"; } return seconds + "sec"; } /// <summary> /// Load protected data as strings from file. Call this function in your production environment, loading in a securely encrypted file which will stay encrypted in memory. /// </summary> /// <param name="path">Path to load from</param> /// <returns>Protected data</returns> public static SecureString[] LoadProtectedStringsFromFile(string path) { byte[] bytes = File.ReadAllBytes(path); // while unprotectedBytes is populated, app is vulnerable - we clear this array ASAP to remove sensitive data from memory byte[] unprotectedBytes = DataProtector.Unprotect(bytes); MemoryStream memory = new MemoryStream(unprotectedBytes); BinaryReader reader = new BinaryReader(memory, Encoding.UTF8); SecureString current; int len; List<SecureString> strings = new List<SecureString>(); while (memory.Position != memory.Length) { // copy char by char into secure string to avoid making additional string copies of sensitive data current = new SecureString(); strings.Add(current); len = reader.ReadInt32(); while (len-- > 0) { current.AppendChar(reader.ReadChar()); } } // cleanup and zero it out, hopefully GC hasn't moved unprotectedBytes around in memory Array.Clear(bytes, 0, bytes.Length); Array.Clear(unprotectedBytes, 0, unprotectedBytes.Length); return strings.ToArray(); } /// <summary> /// Save unprotected data as strings to a file, where it will be encrypted for the current user account. Call this method offline with the data you need to secure. /// Call CryptoUtility.LoadProtectedStringsFromFile to later load these strings from the file. /// </summary> /// <param name="path">Path to save to</param> /// <param name="strings">Strings to save.</param> /// <example><![CDATA[ /// CryptoUtility.SaveUnprotectedStringsToFile("test.bin", new string[] { "my super secret user name", "my super secret password with a ❤heart" }); /// SecureString[] secure = CryptoUtility.LoadProtectedStringsFromFile("test.bin"); /// string s; /// for (int i = 0; i<secure.Length; i++) /// { /// s = CryptoUtility.SecureStringToString(secure[i]); /// Console.WriteLine(s); /// } /// Console.ReadLine(); /// ]]></example> public static void SaveUnprotectedStringsToFile(string path, string[] strings) { MemoryStream memory = new MemoryStream(); BinaryWriter writer = new BinaryWriter(memory, Encoding.UTF8); char[] chars; foreach (string s in strings) { chars = s.ToArray(); writer.Write(chars.Length); foreach (char c in chars) { writer.Write(c); } } writer.Flush(); File.WriteAllBytes(path, DataProtector.Protect(memory.ToArray())); } /// <summary> /// Round an amount appropriate to its quantity /// </summary> /// <param name="amount">Amount</param> /// <returns>Rounded amount</returns> /// <remarks> /// Less than 1 : 7 decimal places /// Less than 10 : 3 decimal places /// Everything else : floor, no decimal places /// </remarks> public static decimal RoundAmount(decimal amount) { int places = GetDecimalPlaces(amount); if (places == 0) { return Math.Floor(amount); } return Math.Round(amount, places); } /// <summary>Gets the number of decimal places to preserve based on the size of the amount.</summary> /// <param name="amount">The amount.</param> /// <returns>The number of decimal places</returns> public static int GetDecimalPlaces(decimal amount) { if (amount < 1.0m) { return 7; } if (amount < 10.0m) { return 3; } return 0; } /// <summary>Rounds down at the specified number of decimal places. Do not specify places to use default decimal rules</summary> /// <param name="amount">The amount to round.</param> /// <param name="places">The decimal places to preserve.</param> /// <returns>(amount: 1.23456, places: 2) = 1.23</returns> public static decimal RoundDown(decimal amount, int? places = null) { if (!places.HasValue) { places = GetDecimalPlaces(amount); } else if (places.Value < 0) { throw new ArgumentOutOfRangeException(nameof(places)); } decimal adjustment = (decimal)Math.Pow(10, places.Value); return Math.Floor(amount * adjustment) / adjustment; } /// <summary>Calculates the precision allowed based on the number of decimal points in a number.</summary> /// <param name="numberWithDecimals">The number on which to count decimal points.</param> /// <returns>A number indicating how many digits are after the decimal point. /// For example, 5 zeroes after the decimal would indicate a price step size of 0.00001</returns> public static decimal CalculatePrecision(string numberWithDecimals) { int precision = 0; int decPoint = numberWithDecimals.IndexOf('.'); if (decPoint != -1) { precision = numberWithDecimals.Length - decPoint - 1; } return (decimal)Math.Pow(10, -1 * precision); } /// <summary> /// Make a task execute synchronously - do not call this from the UI thread or it will lock up the application /// You should almos always use async / await instead /// </summary> /// <param name="task">Task</param> public static void Sync(this Task task) { task.ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Make a task execute synchronously - do not call this from the UI thread or it will lock up the application /// You should almos always use async / await instead /// </summary> /// <param name="task">Task</param> /// <returns>Result</returns> public static T Sync<T>(this Task<T> task) { return task.ConfigureAwait(false).GetAwaiter().GetResult(); } /// <summary> /// Wrap a method in caching logic. Also takes care of making a new SynchronizationContextRemover. /// This should not be used for post requests or other requests that operate on real-time data that changes with each request. /// </summary> /// <typeparam name="T">Return type</typeparam> /// <param name="cache">Cache</param> /// <param name="methodCachePolicy">Method cache policy</param> /// <param name="method">Method implementation</param> /// <param name="arguments">Function arguments - function name and then param name, value, name, value, etc.</param> /// <returns></returns> public static async Task<T> CacheMethod<T>(this ICache cache, Dictionary<string, TimeSpan> methodCachePolicy, Func<Task<T>> method, params object[] arguments) where T : class { await new SynchronizationContextRemover(); methodCachePolicy.ThrowIfNull(nameof(methodCachePolicy)); if (arguments.Length % 2 == 0) { throw new ArgumentException("Must pass function name and then name and value of each argument"); } string methodName = arguments[0].ToStringInvariant(); string cacheKey = methodName; for (int i = 1; i < arguments.Length;) { cacheKey += "|" + arguments[i++].ToStringInvariant() + "=" + arguments[i++].ToStringInvariant("(null)"); } if (methodCachePolicy.TryGetValue(methodName, out TimeSpan cacheTime)) { return (await cache.Get<T>(cacheKey, async () => { T innerResult = await method(); return new CachedItem<T>(innerResult, CryptoUtility.UtcNow.Add(cacheTime)); })).Value; } else { return await method(); } } /// <summary> /// Utf-8 encoding with no prefix bytes /// </summary> public static Encoding UTF8EncodingNoPrefix { get { return utf8EncodingNoPrefix; } } /// <summary> /// Return CryptoUtility.UtcNow or override if SetDateTimeUtcNowFunc has been called /// </summary> public static DateTime UtcNow { get { return utcNowFunc(); } } /// <summary> /// True if platform is Windows, false otherwise /// </summary> public static bool IsWindows { get; } = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); /// <summary> /// True if running under Mono (https://www.mono-project.com/), false if not /// </summary> public static bool IsMono { get; } = (Type.GetType("Mono.Runtime") != null); } /// <summary> /// Possible types of timestamps /// </summary> public enum TimestampType { /// <summary> /// No timestamp type /// </summary> None, /// <summary> /// Unix nanoseconds (long) /// </summary> UnixNanoseconds, /// <summary> /// Unix microseconds (long) /// </summary> UnixMicroeconds, /// <summary> /// Unix milliseconds (double) /// </summary> UnixMillisecondsDouble, /// <summary> /// Unix milliseconds (long) /// </summary> UnixMilliseconds, /// <summary> /// Unix seconds (double) /// </summary> UnixSecondsDouble, /// <summary> /// Unix seconds (long) /// </summary> UnixSeconds, /// <summary> /// ISO 8601 /// </summary> Iso8601 } }
39.780822
460
0.560451
[ "MIT" ]
Kukks/ExchangeSharp
ExchangeSharp/Utility/CryptoUtility.cs
58,082
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.Automation.Latest { public static class GetSchedule { public static Task<GetScheduleResult> InvokeAsync(GetScheduleArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetScheduleResult>("azure-nextgen:automation/latest:getSchedule", args ?? new GetScheduleArgs(), options.WithVersion()); } public sealed class GetScheduleArgs : Pulumi.InvokeArgs { /// <summary> /// The name of the automation account. /// </summary> [Input("automationAccountName", required: true)] public string AutomationAccountName { get; set; } = null!; /// <summary> /// Name of an Azure Resource group. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; /// <summary> /// The schedule name. /// </summary> [Input("scheduleName", required: true)] public string ScheduleName { get; set; } = null!; public GetScheduleArgs() { } } [OutputType] public sealed class GetScheduleResult { /// <summary> /// Gets or sets the advanced schedule. /// </summary> public readonly Outputs.AdvancedScheduleResponse? AdvancedSchedule; /// <summary> /// Gets or sets the creation time. /// </summary> public readonly string? CreationTime; /// <summary> /// Gets or sets the description. /// </summary> public readonly string? Description; /// <summary> /// Gets or sets the end time of the schedule. /// </summary> public readonly string? ExpiryTime; /// <summary> /// Gets or sets the expiry time's offset in minutes. /// </summary> public readonly double? ExpiryTimeOffsetMinutes; /// <summary> /// Gets or sets the frequency of the schedule. /// </summary> public readonly string? Frequency; /// <summary> /// Gets or sets the interval of the schedule. /// </summary> public readonly object? Interval; /// <summary> /// Gets or sets a value indicating whether this schedule is enabled. /// </summary> public readonly bool? IsEnabled; /// <summary> /// Gets or sets the last modified time. /// </summary> public readonly string? LastModifiedTime; /// <summary> /// The name of the resource /// </summary> public readonly string Name; /// <summary> /// Gets or sets the next run time of the schedule. /// </summary> public readonly string? NextRun; /// <summary> /// Gets or sets the next run time's offset in minutes. /// </summary> public readonly double? NextRunOffsetMinutes; /// <summary> /// Gets or sets the start time of the schedule. /// </summary> public readonly string? StartTime; /// <summary> /// Gets the start time's offset in minutes. /// </summary> public readonly double StartTimeOffsetMinutes; /// <summary> /// Gets or sets the time zone of the schedule. /// </summary> public readonly string? TimeZone; /// <summary> /// The type of the resource. /// </summary> public readonly string Type; [OutputConstructor] private GetScheduleResult( Outputs.AdvancedScheduleResponse? advancedSchedule, string? creationTime, string? description, string? expiryTime, double? expiryTimeOffsetMinutes, string? frequency, object? interval, bool? isEnabled, string? lastModifiedTime, string name, string? nextRun, double? nextRunOffsetMinutes, string? startTime, double startTimeOffsetMinutes, string? timeZone, string type) { AdvancedSchedule = advancedSchedule; CreationTime = creationTime; Description = description; ExpiryTime = expiryTime; ExpiryTimeOffsetMinutes = expiryTimeOffsetMinutes; Frequency = frequency; Interval = interval; IsEnabled = isEnabled; LastModifiedTime = lastModifiedTime; Name = name; NextRun = nextRun; NextRunOffsetMinutes = nextRunOffsetMinutes; StartTime = startTime; StartTimeOffsetMinutes = startTimeOffsetMinutes; TimeZone = timeZone; Type = type; } } }
30.891566
174
0.576248
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/Automation/Latest/GetSchedule.cs
5,128
C#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using NUnit.Framework; using osu.Game.Rulesets.Karaoke.Edit.Dialog; using osu.Game.Tests.Visual; namespace osu.Game.Rulesets.Karaoke.Tests { /// <summary> /// Test all the windows karaoke will use /// </summary> [TestFixture] [Ignore("getting CI working")] [System.ComponentModel.Description("Test windows")] public class TestCaseWindows : OsuTestCase { public TestCaseWindows() { AddStep("Add Dialog", () => AddDialog()); AddStep("Add Lyrics Dialog", () => AddLyricsDialog()); AddStep("Add Translate Dialog", () => AddTranslateDialog()); AddStep("Add singer Dialog", () => AddListSingerDialog()); AddStep("Add template Dialog", () => AddEditKaraokeTemplateDialog()); AddStep("Add subtext Dialog", () => AddEditKaraokeSubTextDialog()); } protected void AddDialog() { try { DialogContainer dialog = new DialogContainer(); Add(dialog); } catch (Exception ex) { Console.WriteLine(""); } } protected void AddLyricsDialog() { try { ListKaraokeLyricsDialog dialog = new ListKaraokeLyricsDialog(null); Add(dialog); } catch (Exception ex) { Console.WriteLine(""); } } protected void AddTranslateDialog() { try { ListKaraokeTranslateDialog dialog = new ListKaraokeTranslateDialog(null); Add(dialog); } catch (Exception ex) { Console.WriteLine(""); } } protected void AddListSingerDialog() { try { ListSingerDialog dialog = new ListSingerDialog(); Add(dialog); } catch (Exception ex) { Console.WriteLine(""); } } protected void AddEditKaraokeTemplateDialog() { try { EditKaraokeTemplateDialog dialog = new EditKaraokeTemplateDialog(null, null); Add(dialog); } catch (Exception ex) { Console.WriteLine(""); } } protected void AddEditKaraokeSubTextDialog() { try { EditKaraokeSubTextDialog dialog = new EditKaraokeSubTextDialog(null); Add(dialog); } catch (Exception ex) { Console.WriteLine(""); } } } }
27.238938
94
0.472385
[ "MIT" ]
karaoke-dev/karaoke-legacy
osu.Game.Rulesets.Karaoke.Tests/TestCaseWindows.cs
2,968
C#
namespace Vidly.Web.Migrations { using System; using System.Data.Entity.Migrations; public partial class AddIsSubscribedToCustomer : DbMigration { public override void Up() { AddColumn("dbo.Customers", "IsSubscribedToNewsletter", c => c.Boolean(nullable: false)); } public override void Down() { DropColumn("dbo.Customers", "IsSubscribedToNewsletter"); } } }
24.473684
100
0.597849
[ "MIT" ]
s-janjic/Vidly
Vidly.Web/Migrations/202105252114392_AddIsSubscribedToCustomer.cs
465
C#
using System; using System.Runtime.InteropServices; using System.Windows.Forms; // ReSharper disable UnusedMember.Local namespace MageDisplayLib { /// <summary> /// Intercepts horizontal scrollbar events, gets X position of scroll, and fires the OnScroll event /// </summary> public class ListViewEx : ListView { /// <summary> /// Event that is fired to simulate a .NET scroll event /// </summary> public event EventHandler<ScrollEventArgs> OnScroll; // ReSharper disable IdentifierTypo // Windows messages private const int WM_HSCROLL = 0x0114; private const int WM_VSCROLL = 0x0115; // ScrollBar types private const int SB_HORZ = 0; private const int SB_VERT = 1; // ReSharper restore IdentifierTypo /// <summary> /// Override WndProc to snare horizontal scrolling event from raw Windows message stream /// (since ListView does not provide scrolling event) /// </summary> /// <param name="message">Message object</param> protected override void WndProc(ref Message message) { base.WndProc(ref message); if (message.Msg == WM_HSCROLL) { var args = new ScrollEventArgs(ScrollEventType.EndScroll, GetScrollPos(Handle, SB_HORZ)); OnScroll?.Invoke(this, args); } } /// <summary> /// Call to raw WinAPI function to get position of horizontal scroll bar /// </summary> [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern int GetScrollPos(IntPtr hWnd, int nBar); } }
32.37037
106
0.599542
[ "BSD-2-Clause" ]
PNNL-Comp-Mass-Spec/Mage
MageDisplayLib/ListViewEx.cs
1,750
C#
using System; namespace Sexy { public struct _Touch { public CGPoint location; public CGPoint previousLocation; public int tapCount; public double timestamp; public _Phase phase; } }
9.125
34
0.671233
[ "MIT" ]
OptiJuegos/Plants-VS-Zombies-NET
DotNETPvZ_Shared/Sexy/_Input/_Touch.cs
221
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** 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.Aws.Alb.Outputs { [OutputType] public sealed class TargetGroupStickiness { /// <summary> /// Only used when the type is `lb_cookie`. The time period, in seconds, during which requests from a client should be routed to the same target. After this time period expires, the load balancer-generated cookie is considered stale. The range is 1 second to 1 week (604800 seconds). The default value is 1 day (86400 seconds). /// </summary> public readonly int? CookieDuration; /// <summary> /// Name of the application based cookie. AWSALB, AWSALBAPP, and AWSALBTG prefixes are reserved and cannot be used. Only needed when type is `app_cookie`. /// </summary> public readonly string? CookieName; /// <summary> /// Boolean to enable / disable `stickiness`. Default is `true`. /// </summary> public readonly bool? Enabled; /// <summary> /// The type of sticky sessions. The only current possible values are `lb_cookie`, `app_cookie` for ALBs, and `source_ip` for NLBs. /// </summary> public readonly string Type; [OutputConstructor] private TargetGroupStickiness( int? cookieDuration, string? cookieName, bool? enabled, string type) { CookieDuration = cookieDuration; CookieName = cookieName; Enabled = enabled; Type = type; } } }
36.62
335
0.637357
[ "ECL-2.0", "Apache-2.0" ]
RafalSumislawski/pulumi-aws
sdk/dotnet/Alb/Outputs/TargetGroupStickiness.cs
1,831
C#
#region License /* * WebSocketContext.cs * * The MIT License * * Copyright (c) 2012-2018 sta.blockhead * * 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. */ #endregion using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Security.Principal; namespace WebSocketCore.Net.WebSockets { /// <summary> /// Exposes the access to the information in a WebSocket handshake request. /// </summary> /// <remarks> /// This class is an abstract class. /// </remarks> public abstract class WebSocketContext { #region Protected Constructors /// <summary> /// Initializes a new instance of the <see cref="WebSocketContext"/> class. /// </summary> protected WebSocketContext () { } #endregion #region Public Properties /// <summary> /// Gets the HTTP cookies included in the handshake request. /// </summary> /// <value> /// A <see cref="WebSocketCore.Net.CookieCollection"/> that contains /// the cookies. /// </value> public abstract CookieCollection CookieCollection { get; } /// <summary> /// Gets the HTTP headers included in the handshake request. /// </summary> /// <value> /// A <see cref="NameValueCollection"/> that contains the headers. /// </value> public abstract NameValueCollection Headers { get; } /// <summary> /// Gets the value of the Host header included in the handshake request. /// </summary> /// <value> /// A <see cref="string"/> that represents the server host name requested /// by the client. /// </value> public abstract string Host { get; } /// <summary> /// Gets a value indicating whether the client is authenticated. /// </summary> /// <value> /// <c>true</c> if the client is authenticated; otherwise, <c>false</c>. /// </value> public abstract bool IsAuthenticated { get; } /// <summary> /// Gets a value indicating whether the handshake request is sent from /// the local computer. /// </summary> /// <value> /// <c>true</c> if the handshake request is sent from the same computer /// as the server; otherwise, <c>false</c>. /// </value> public abstract bool IsLocal { get; } /// <summary> /// Gets a value indicating whether a secure connection is used to send /// the handshake request. /// </summary> /// <value> /// <c>true</c> if the connection is secure; otherwise, <c>false</c>. /// </value> public abstract bool IsSecureConnection { get; } /// <summary> /// Gets a value indicating whether the request is a WebSocket handshake /// request. /// </summary> /// <value> /// <c>true</c> if the request is a WebSocket handshake request; otherwise, /// <c>false</c>. /// </value> public abstract bool IsWebSocketRequest { get; } /// <summary> /// Gets the value of the Origin header included in the handshake request. /// </summary> /// <value> /// A <see cref="string"/> that represents the value of the Origin header. /// </value> public abstract string Origin { get; } /// <summary> /// Gets the query string included in the handshake request. /// </summary> /// <value> /// A <see cref="NameValueCollection"/> that contains the query parameters. /// </value> public abstract NameValueCollection QueryString { get; } /// <summary> /// Gets the URI requested by the client. /// </summary> /// <value> /// A <see cref="Uri"/> that represents the URI parsed from the request. /// </value> public abstract Uri RequestUri { get; } /// <summary> /// Gets the value of the Sec-WebSocket-Key header included in /// the handshake request. /// </summary> /// <value> /// <para> /// A <see cref="string"/> that represents the value of /// the Sec-WebSocket-Key header. /// </para> /// <para> /// The value is used to prove that the server received /// a valid WebSocket handshake request. /// </para> /// </value> public abstract string SecWebSocketKey { get; } /// <summary> /// Gets the names of the subprotocols from the Sec-WebSocket-Protocol /// header included in the handshake request. /// </summary> /// <value> /// <para> /// An <see cref="T:System.Collections.Generic.IEnumerable{string}"/> /// instance. /// </para> /// <para> /// It provides an enumerator which supports the iteration over /// the collection of the names of the subprotocols. /// </para> /// </value> public abstract IEnumerable<string> SecWebSocketProtocols { get; } /// <summary> /// Gets the value of the Sec-WebSocket-Version header included in /// the handshake request. /// </summary> /// <value> /// A <see cref="string"/> that represents the WebSocket protocol /// version specified by the client. /// </value> public abstract string SecWebSocketVersion { get; } /// <summary> /// Gets the endpoint to which the handshake request is sent. /// </summary> /// <value> /// A <see cref="System.Net.IPEndPoint"/> that represents the server IP /// address and port number. /// </value> public abstract System.Net.IPEndPoint ServerEndPoint { get; } /// <summary> /// Gets the client information. /// </summary> /// <value> /// A <see cref="IPrincipal"/> instance that represents identity, /// authentication, and security roles for the client. /// </value> public abstract IPrincipal User { get; } /// <summary> /// Gets the endpoint from which the handshake request is sent. /// </summary> /// <value> /// A <see cref="System.Net.IPEndPoint"/> that represents the client IP /// address and port number. /// </value> public abstract System.Net.IPEndPoint UserEndPoint { get; } /// <summary> /// Gets the WebSocket instance used for two-way communication between /// the client and server. /// </summary> /// <value> /// A <see cref="WebSocketCore.WebSocket"/>. /// </value> public abstract WebSocket WebSocket { get; } #endregion } }
32.475556
80
0.633502
[ "MIT" ]
16it/surging
src/WebSocket/WebSocketCore/Net/WebSockets/WebSocketContext.cs
7,307
C#
namespace TrashMob.Shared.Tests { using Moq; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using TrashMob.Shared.Engine; using TrashMob.Shared.Models; using Xunit; public abstract class UpcomingEventsInYourAreaNotifierTestsBase : NotifierTestsBase { protected abstract INotificationEngine Engine { get; } protected abstract int NumberOfDaysToAddForEventOutOfWindow { get; } [Fact] public async Task GenerateNotificationsAsync_WithNoDataAvailable_Succeeds() { // Arrange // Act await Engine.GenerateNotificationsAsync().ConfigureAwait(false); // Assert UserNotificationRepository.Verify(_ => _.AddUserNotification(It.IsAny<UserNotification>()), Times.Never); EmailSender.Verify(_ => _.SendEmailAsync(It.IsAny<Email>(), It.IsAny<CancellationToken>()), Times.Never); } [Fact] public async Task GenerateNotificationsAsync_With1EventForUser_Sends1Email() { // Arrange List<Event> events = GetEventList1(); List<User> users = GetUserList1(); EventRepository.Setup(e => e.GetActiveEvents()).ReturnsAsync(events); UserRepository.Setup(u => u.GetAllUsers()).ReturnsAsync(users); // Act await Engine.GenerateNotificationsAsync().ConfigureAwait(false); // Assert EventRepository.Verify(_ => _.GetActiveEvents(), Times.Once); UserNotificationPreferenceRepository.Verify(_ => _.GetUserNotificationPreferences(It.IsAny<Guid>()), Times.Once); UserRepository.Verify(_ => _.GetAllUsers(), Times.Once); EventAttendeeRepository.Verify(_ => _.GetEventsUserIsAttending(It.IsAny<Guid>(), It.IsAny<bool>()), Times.Once); UserNotificationRepository.Verify(_ => _.AddUserNotification(It.IsAny<UserNotification>()), Times.Once); EmailSender.Verify(_ => _.SendEmailAsync(It.IsAny<Email>(), It.IsAny<CancellationToken>()), Times.Once); } [Fact] public async Task GenerateNotificationsAsync_With2EventForUser_Sends1Email() { // Arrange List<Event> events = GetEventList2(); List<User> users = GetUserList1(); EventRepository.Setup(e => e.GetActiveEvents()).ReturnsAsync(events); UserRepository.Setup(u => u.GetAllUsers()).ReturnsAsync(users); // Act await Engine.GenerateNotificationsAsync().ConfigureAwait(false); // Assert EventRepository.Verify(_ => _.GetActiveEvents(), Times.Once); UserNotificationPreferenceRepository.Verify(_ => _.GetUserNotificationPreferences(It.IsAny<Guid>()), Times.Once); UserRepository.Verify(_ => _.GetAllUsers(), Times.Once); EventAttendeeRepository.Verify(_ => _.GetEventsUserIsAttending(It.IsAny<Guid>(), It.IsAny<bool>()), Times.Once); UserNotificationRepository.Verify(_ => _.AddUserNotification(It.IsAny<UserNotification>()), Times.Exactly(2)); EmailSender.Verify(_ => _.SendEmailAsync(It.IsAny<Email>(), It.IsAny<CancellationToken>()), Times.Once); } [Fact] public async Task GenerateNotificationsAsync_With1EventFor2Users_Sends2Email() { // Arrange List<Event> events = GetEventList1(); List<User> users = GetUserList2(); EventRepository.Setup(e => e.GetActiveEvents()).ReturnsAsync(events); UserRepository.Setup(u => u.GetAllUsers()).ReturnsAsync(users); // Act await Engine.GenerateNotificationsAsync().ConfigureAwait(false); // Assert UserRepository.Verify(_ => _.GetAllUsers(), Times.Once); UserNotificationPreferenceRepository.Verify(_ => _.GetUserNotificationPreferences(It.IsAny<Guid>()), Times.Exactly(2)); EventRepository.Verify(_ => _.GetActiveEvents(), Times.Exactly(2)); EventAttendeeRepository.Verify(_ => _.GetEventsUserIsAttending(It.IsAny<Guid>(), It.IsAny<bool>()), Times.Exactly(2)); UserNotificationRepository.Verify(_ => _.AddUserNotification(It.IsAny<UserNotification>()), Times.Exactly(2)); EmailSender.Verify(_ => _.SendEmailAsync(It.IsAny<Email>(), It.IsAny<CancellationToken>()), Times.Exactly(2)); } [Fact] public async Task GenerateNotificationsAsync_With1EventFor1UsersWhoIsAlreadyAttending_SendsNoEmail() { // Arrange List<Event> events = GetEventList1(); List<User> users = GetUserList1(); EventRepository.Setup(e => e.GetActiveEvents()).ReturnsAsync(events); UserRepository.Setup(u => u.GetAllUsers()).ReturnsAsync(users); // The user is attending all available events EventAttendeeRepository.Setup(ea => ea.GetEventsUserIsAttending(It.IsAny<Guid>(), It.IsAny<bool>())).ReturnsAsync(events); // Act await Engine.GenerateNotificationsAsync().ConfigureAwait(false); // Assert UserRepository.Verify(_ => _.GetAllUsers(), Times.Once); UserNotificationPreferenceRepository.Verify(_ => _.GetUserNotificationPreferences(It.IsAny<Guid>()), Times.Once); EventRepository.Verify(_ => _.GetActiveEvents(), Times.Once); EventAttendeeRepository.Verify(_ => _.GetEventsUserIsAttending(It.IsAny<Guid>(), It.IsAny<bool>()), Times.Once); UserNotificationRepository.Verify(_ => _.AddUserNotification(It.IsAny<UserNotification>()), Times.Never); EmailSender.Verify(_ => _.SendEmailAsync(It.IsAny<Email>(), It.IsAny<CancellationToken>()), Times.Never); } [Fact] public async Task GenerateNotificationsAsync_With1EventFor1UsersWhoIsAttendingOtherEventsButNotThisOne_SendsOneEmail() { // Arrange List<Event> events = GetEventList1(); List<User> users = GetUserList1(); List<Event> alternateEvents = GetEventList1(); alternateEvents[0].Id = new Guid(); EventRepository.Setup(e => e.GetActiveEvents()).ReturnsAsync(events); UserRepository.Setup(u => u.GetAllUsers()).ReturnsAsync(users); // The user is attending all available events EventAttendeeRepository.Setup(ea => ea.GetEventsUserIsAttending(It.IsAny<Guid>(), It.IsAny<bool>())).ReturnsAsync(alternateEvents); // Act await Engine.GenerateNotificationsAsync().ConfigureAwait(false); // Assert UserRepository.Verify(_ => _.GetAllUsers(), Times.Once); UserNotificationPreferenceRepository.Verify(_ => _.GetUserNotificationPreferences(It.IsAny<Guid>()), Times.Once); EventRepository.Verify(_ => _.GetActiveEvents(), Times.Once); EventAttendeeRepository.Verify(_ => _.GetEventsUserIsAttending(It.IsAny<Guid>(), It.IsAny<bool>()), Times.Once); UserNotificationRepository.Verify(_ => _.AddUserNotification(It.IsAny<UserNotification>()), Times.Once); EmailSender.Verify(_ => _.SendEmailAsync(It.IsAny<Email>(), It.IsAny<CancellationToken>()), Times.Once); } [Fact] public async Task GenerateNotificationsAsync_With1EventFor1UsersWhoHasAlreadyReceivedTheEmail_SendsNoEmail() { // Arrange List<Event> events = GetEventList1(); List<User> users = GetUserList1(); EventRepository.Setup(e => e.GetActiveEvents()).ReturnsAsync(events); UserRepository.Setup(u => u.GetAllUsers()).ReturnsAsync(users); // The user has already received notifications for all events var userNotification = new UserNotification() { EventId = events[0].Id, UserId = users[0].Id, SentDate = DateTimeOffset.UtcNow.AddDays(-1), UserNotificationTypeId = (int)NotificationType, }; var userNotifications = new List<UserNotification>() { userNotification }; UserNotificationRepository.Setup(ea => ea.GetUserNotifications(It.IsAny<Guid>(), It.IsAny<Guid>())).ReturnsAsync(userNotifications); // Act await Engine.GenerateNotificationsAsync().ConfigureAwait(false); // Assert UserRepository.Verify(_ => _.GetAllUsers(), Times.Once); UserNotificationPreferenceRepository.Verify(_ => _.GetUserNotificationPreferences(It.IsAny<Guid>()), Times.Once); EventRepository.Verify(_ => _.GetActiveEvents(), Times.Once); EventAttendeeRepository.Verify(_ => _.GetEventsUserIsAttending(It.IsAny<Guid>(), It.IsAny<bool>()), Times.Once); UserNotificationRepository.Verify(_ => _.AddUserNotification(It.IsAny<UserNotification>()), Times.Never); EmailSender.Verify(_ => _.SendEmailAsync(It.IsAny<Email>(), It.IsAny<CancellationToken>()), Times.Never); } [Fact] public async Task GenerateNotificationsAsync_With1EventFor1UsersWhoHasNotAlreadyReceivedTheEmail_Sends1Email() { // Arrange List<Event> events = GetEventList1(); List<User> users = GetUserList1(); EventRepository.Setup(e => e.GetActiveEvents()).ReturnsAsync(events); UserRepository.Setup(u => u.GetAllUsers()).ReturnsAsync(users); var userNotifications = new List<UserNotification>(); UserNotificationRepository.Setup(ea => ea.GetUserNotifications(It.IsAny<Guid>(), It.IsAny<Guid>())).ReturnsAsync(userNotifications); // Act await Engine.GenerateNotificationsAsync().ConfigureAwait(false); // Assert UserRepository.Verify(_ => _.GetAllUsers(), Times.Once); UserNotificationPreferenceRepository.Verify(_ => _.GetUserNotificationPreferences(It.IsAny<Guid>()), Times.Once); EventRepository.Verify(_ => _.GetActiveEvents(), Times.Once); EventAttendeeRepository.Verify(_ => _.GetEventsUserIsAttending(It.IsAny<Guid>(), It.IsAny<bool>()), Times.Once); UserNotificationRepository.Verify(_ => _.AddUserNotification(It.IsAny<UserNotification>()), Times.Once); EmailSender.Verify(_ => _.SendEmailAsync(It.IsAny<Email>(), It.IsAny<CancellationToken>()), Times.Once); } [Fact] public async Task GenerateNotificationsAsync_With1EventFor1UsersWhoHasOptedOutOfAllEmails_SendsNoEmail() { // Arrange List<Event> events = GetEventList1(); List<User> users = GetUserList1(); users[0].IsOptedOutOfAllEmails = true; EventRepository.Setup(e => e.GetActiveEvents()).ReturnsAsync(events); UserRepository.Setup(u => u.GetAllUsers()).ReturnsAsync(users); // Act await Engine.GenerateNotificationsAsync().ConfigureAwait(false); // Assert UserRepository.Verify(_ => _.GetAllUsers(), Times.Once); UserNotificationPreferenceRepository.Verify(_ => _.GetUserNotificationPreferences(It.IsAny<Guid>()), Times.Never); EventRepository.Verify(_ => _.GetActiveEvents(), Times.Never); EventAttendeeRepository.Verify(_ => _.GetEventsUserIsAttending(It.IsAny<Guid>(), It.IsAny<bool>()), Times.Never); UserNotificationRepository.Verify(_ => _.AddUserNotification(It.IsAny<UserNotification>()), Times.Never); EmailSender.Verify(_ => _.SendEmailAsync(It.IsAny<Email>(), It.IsAny<CancellationToken>()), Times.Never); } [Fact] public async Task GenerateNotificationsAsync_With1EventFor1UsersWhoHasOptedOutOfThisEmail_SendsNoEmail() { // Arrange List<Event> events = GetEventList1(); List<User> users = GetUserList1(); List<UserNotificationPreference> userNotificationPreferences = GetUserNotificationPreferences(); var unIndex = userNotificationPreferences.FindIndex(unp => unp.UserNotificationTypeId == (int)NotificationType); userNotificationPreferences[unIndex].IsOptedOut = true; EventRepository.Setup(e => e.GetActiveEvents()).ReturnsAsync(events); UserRepository.Setup(u => u.GetAllUsers()).ReturnsAsync(users); UserNotificationPreferenceRepository.Setup(unp => unp.GetUserNotificationPreferences(It.IsAny<Guid>())).ReturnsAsync(userNotificationPreferences); // Act await Engine.GenerateNotificationsAsync().ConfigureAwait(false); // Assert UserRepository.Verify(_ => _.GetAllUsers(), Times.Once); EventRepository.Verify(_ => _.GetActiveEvents(), Times.Never); UserNotificationPreferenceRepository.Verify(_ => _.GetUserNotificationPreferences(It.IsAny<Guid>()), Times.Once); EventAttendeeRepository.Verify(_ => _.GetEventsUserIsAttending(It.IsAny<Guid>(), It.IsAny<bool>()), Times.Never); UserNotificationRepository.Verify(_ => _.AddUserNotification(It.IsAny<UserNotification>()), Times.Never); EmailSender.Verify(_ => _.SendEmailAsync(It.IsAny<Email>(), It.IsAny<CancellationToken>()), Times.Never); } [Fact] public async Task GenerateNotificationsAsync_With1EventFor1UsersWhereEventIsMoreThanRequiredHoursAway_SendsNoEmail() { // Arrange List<Event> events = GetEventList1(); List<User> users = GetUserList1(); events[0].EventDate = DateTimeOffset.UtcNow.AddDays(NumberOfDaysToAddForEventOutOfWindow); EventRepository.Setup(e => e.GetActiveEvents()).ReturnsAsync(events); UserRepository.Setup(u => u.GetAllUsers()).ReturnsAsync(users); // Act await Engine.GenerateNotificationsAsync().ConfigureAwait(false); // Assert UserRepository.Verify(_ => _.GetAllUsers(), Times.Once); EventRepository.Verify(_ => _.GetActiveEvents(), Times.Once); UserNotificationPreferenceRepository.Verify(_ => _.GetUserNotificationPreferences(It.IsAny<Guid>()), Times.Once); EventAttendeeRepository.Verify(_ => _.GetEventsUserIsAttending(It.IsAny<Guid>(), It.IsAny<bool>()), Times.Once); UserNotificationRepository.Verify(_ => _.AddUserNotification(It.IsAny<UserNotification>()), Times.Never); EmailSender.Verify(_ => _.SendEmailAsync(It.IsAny<Email>(), It.IsAny<CancellationToken>()), Times.Never); } [Fact] public async Task GenerateNotificationsAsync_With1EventFor1UsersWhereEventIsOutsideOfTravelPreference_SendsNoEmail() { // Arrange List<Event> events = GetEventList1(); List<User> users = GetUserList1(); events[0].EventDate = DateTimeOffset.UtcNow.AddDays(3); EventRepository.Setup(e => e.GetActiveEvents()).ReturnsAsync(events); UserRepository.Setup(u => u.GetAllUsers()).ReturnsAsync(users); // Setup a return of distance between User and Event of 50 (in whatever units) MapRepository.Setup(mr => mr.GetDistanceBetweenTwoPoints(It.IsAny<Tuple<double, double>>(), It.IsAny<Tuple<double, double>>(), It.IsAny<bool>())).ReturnsAsync(50); // Act await Engine.GenerateNotificationsAsync().ConfigureAwait(false); // Assert UserRepository.Verify(_ => _.GetAllUsers(), Times.Once); EventRepository.Verify(_ => _.GetActiveEvents(), Times.Once); UserNotificationPreferenceRepository.Verify(_ => _.GetUserNotificationPreferences(It.IsAny<Guid>()), Times.Once); EventAttendeeRepository.Verify(_ => _.GetEventsUserIsAttending(It.IsAny<Guid>(), It.IsAny<bool>()), Times.Once); UserNotificationRepository.Verify(_ => _.AddUserNotification(It.IsAny<UserNotification>()), Times.Never); EmailSender.Verify(_ => _.SendEmailAsync(It.IsAny<Email>(), It.IsAny<CancellationToken>()), Times.Never); } } }
52.475728
175
0.654641
[ "Apache-2.0" ]
ambientlight/TrashMob
TrashMob.Shared.Tests/UpcomingEventsInYourAreaNotifierTestsBase.cs
16,215
C#
// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Steeltoe.Discovery.Eureka.Test; using Steeltoe.Discovery.Eureka.Transport; using Steeltoe.Discovery.Eureka.Util; using System; using Xunit; namespace Steeltoe.Discovery.Eureka.AppInfo.Test { public class LeaseInfoTest : AbstractBaseTest { [Fact] public void Constructor_Defaults() { LeaseInfo info = new LeaseInfo(); Assert.Equal(LeaseInfo.Default_DurationInSecs, info.DurationInSecs); Assert.Equal(LeaseInfo.Default_RenewalIntervalInSecs, info.RenewalIntervalInSecs); } [Fact] public void FromJson_Correct() { JsonLeaseInfo jinfo = new JsonLeaseInfo() { RenewalIntervalInSecs = 100, DurationInSecs = 200, RegistrationTimestamp = 1457973741708, LastRenewalTimestamp = 1457973741708, LastRenewalTimestampLegacy = 1457973741708, EvictionTimestamp = 1457973741708, ServiceUpTimestamp = 1457973741708 }; LeaseInfo result = LeaseInfo.FromJson(jinfo); Assert.Equal(100, result.RenewalIntervalInSecs); Assert.Equal(200, result.DurationInSecs); Assert.Equal(1457973741708, DateTimeConversions.ToJavaMillis(new DateTime(result.RegistrationTimestamp, DateTimeKind.Utc))); Assert.Equal(1457973741708, DateTimeConversions.ToJavaMillis(new DateTime(result.LastRenewalTimestamp, DateTimeKind.Utc))); Assert.Equal(1457973741708, DateTimeConversions.ToJavaMillis(new DateTime(result.LastRenewalTimestampLegacy, DateTimeKind.Utc))); Assert.Equal(1457973741708, DateTimeConversions.ToJavaMillis(new DateTime(result.EvictionTimestamp, DateTimeKind.Utc))); Assert.Equal(1457973741708, DateTimeConversions.ToJavaMillis(new DateTime(result.ServiceUpTimestamp, DateTimeKind.Utc))); } [Fact] public void ToJson_Correct() { JsonLeaseInfo jinfo = new JsonLeaseInfo() { RenewalIntervalInSecs = 100, DurationInSecs = 200, RegistrationTimestamp = 1457973741708, LastRenewalTimestamp = 1457973741708, LastRenewalTimestampLegacy = 1457973741708, EvictionTimestamp = 1457973741708, ServiceUpTimestamp = 1457973741708 }; LeaseInfo result = LeaseInfo.FromJson(jinfo); jinfo = result.ToJson(); Assert.Equal(100, result.RenewalIntervalInSecs); Assert.Equal(200, result.DurationInSecs); Assert.Equal(1457973741708, DateTimeConversions.ToJavaMillis(new DateTime(result.RegistrationTimestamp, DateTimeKind.Utc))); Assert.Equal(1457973741708, DateTimeConversions.ToJavaMillis(new DateTime(result.LastRenewalTimestamp, DateTimeKind.Utc))); Assert.Equal(1457973741708, DateTimeConversions.ToJavaMillis(new DateTime(result.LastRenewalTimestampLegacy, DateTimeKind.Utc))); Assert.Equal(1457973741708, DateTimeConversions.ToJavaMillis(new DateTime(result.EvictionTimestamp, DateTimeKind.Utc))); Assert.Equal(1457973741708, DateTimeConversions.ToJavaMillis(new DateTime(result.ServiceUpTimestamp, DateTimeKind.Utc))); } [Fact] public void FromConfig_Correct() { EurekaInstanceConfig config = new EurekaInstanceConfig(); LeaseInfo info = LeaseInfo.FromConfig(config); Assert.Equal(config.LeaseRenewalIntervalInSeconds, info.RenewalIntervalInSecs); Assert.Equal(config.LeaseExpirationDurationInSeconds, info.DurationInSecs); } } }
46.031915
141
0.685694
[ "ECL-2.0", "Apache-2.0" ]
DrDao/Discovery
test/Steeltoe.Discovery.EurekaBase.Test/AppInfo/LeaseInfoTest.cs
4,329
C#
// // Copyright 2010-2017 Deveel // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; namespace Deveel { static class BigArraySortUtil<T> { private static readonly IComparer<T> comparer = new ItemComparer(); private class ItemComparer : IComparer<T> { public int Compare(T x, T y) { if (x is IComparable<T>) { var a = (IComparable<T>)x; return a.CompareTo(y); } else if (x is IComparable) { var a = (IComparable)x; return a.CompareTo(y); } else { throw new NotSupportedException(); } } } public static void QuickSort(BigArray<T> elements, long left, long right) { long i = left, j = right; var pivot = elements[(left + right) / 2]; while (i <= j) { while (comparer.Compare(elements[i], pivot) < 0) { i++; } while (comparer.Compare(elements[j], pivot) > 0) { j--; } if (i <= j) { // Swap var tmp = elements[i]; elements[i] = elements[j]; elements[j] = tmp; i++; j--; } } // Recursive calls if (left < j) { QuickSort(elements, left, j); } if (i < right) { QuickSort(elements, i, right); } } } }
23.972603
78
0.614286
[ "Apache-2.0" ]
deveel/deveeldb.core
src/DeveelDb.Core/BigArraySortUtil.cs
1,752
C#
using System; using System.Collections; namespace Lesnikowski.Pawel.Mail.Pop3 { public class BaseEntity { protected string header; //all header public string contentType; public string contentTransferEncoding; public string charset; public string boundary; public bool hasAttachments=false; public ArrayList attachments=new ArrayList(); public BaseEntity(string buffer) { GetHeader(buffer); this.contentType =this.GetValueFromHeader("Content-Type: "); //Try again? Not per spec... if (this.contentType == null || this.contentType.Length == 0) { this.contentType = this.GetValueFromHeader("Content-type: "); } this.contentTransferEncoding=this.GetValueFromHeader("Content-Transfer-Encoding: "); if (contentType.IndexOf("text/plain")!=-1 || contentType.IndexOf("text/html")!=-1) this.charset=GetValueEqualFromHeader2("charset="); } internal bool ParseMixedMessage(string buffer, string boundary) { int start=0,end; for(;;) { start=buffer.IndexOf(boundary,start); if (start==-1) break; end=buffer.IndexOf(boundary,start+1); if (end==-1) break; // remove boundary from buffer start += boundary.Length; Attachment a=new Attachment( buffer.Substring(start,end-start-2) ); this.attachments.Add(a); } return true; } protected void GetHeader(string buffer) { int end=buffer.IndexOf("\r\n\r\n"); if (end==-1) throw new Exception("can't get header"); header=buffer.Substring(0, end); header+="\r\n\r\n"; } protected string GetValueFromHeader(string key) { int start=header.ToLower().IndexOf(key.ToLower()); if(start<0) return ""; start=header.IndexOf(' ',start); if (start<0) return ""; int end=header.IndexOf("\r\n",start); if (end<=0) return ""; return QuotedCoding.Decode(header.Substring(start+1, end-start-1).Trim()); } /// <summary> /// z 'ala="123"' /// </summary> /// <param name="key">ala=</param> /// <returns>123</returns> protected string GetValueEqualFromHeader(string key) { int start=header.IndexOf(key); if (start==-1) return ""; start=header.IndexOf('"',start); int end=header.IndexOf('"',start+1); if (start==-1 || end==-1) return ""; return QuotedCoding.Decode(header.Substring(start+1,end-start-1)); } /// <summary> /// z 'ala="123"' /// </summary> /// <param name="key">ala=</param> /// <returns>123</returns> protected string GetValueEqualFromHeader2(string key) { bool noQuotes = false; int end = -1; int start = header.IndexOf(key); if (start == -1) return ""; start = header.IndexOf('"', start); if (start == -1) { noQuotes = true; start = header.IndexOf('=', header.IndexOf(key)); } if (noQuotes) { end = header.IndexOf("\r\n", start + 1); } else { end = header.IndexOf('"', start + 1); } if (start == -1 || end == -1) return ""; return QuotedCoding.Decode(header.Substring(start + 1, end - start - 1)); } } }
24.445255
96
0.575396
[ "MIT" ]
garethhubball/dasblog-core
source/Lesnikowski.Pawel.Mail.Pop3/BaseEntity.cs
3,349
C#
using System.Collections.Generic; using Umbraco.Cms.Core.Events; using Umbraco.Cms.Core.Models; namespace Umbraco.Cms.Core.Notifications { public class MemberTypeDeletedNotification : DeletedNotification<IMemberType> { public MemberTypeDeletedNotification(IMemberType target, EventMessages messages) : base(target, messages) { } public MemberTypeDeletedNotification(IEnumerable<IMemberType> target, EventMessages messages) : base(target, messages) { } } }
28.777778
126
0.72973
[ "MIT" ]
Ambertvu/Umbraco-CMS
src/Umbraco.Core/Notifications/MemberTypeDeletedNotification.cs
518
C#
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using System; using System.Linq; namespace Workbench.DependencyInjection.Extensions { public static class ServiceCollectionExtensions { public static IServiceCollection Decorate<TInterface, TDecorator>(this IServiceCollection services) where TInterface : class where TDecorator : class, TInterface { ServiceDescriptor innerDescriptor = services.FirstOrDefault(s => s.ServiceType == typeof(TInterface)); if (innerDescriptor == null) { throw new InvalidOperationException($"{typeof(TInterface).Name} is not registered"); } var objectFactory = ActivatorUtilities.CreateFactory( typeof(TDecorator), new[] { typeof(TInterface) }); services.Replace(ServiceDescriptor.Describe( typeof(TInterface), s => (TInterface)objectFactory(s, new[] { s.CreateInstance(innerDescriptor) }), innerDescriptor.Lifetime) ); return services; } private static object CreateInstance(this IServiceProvider services, ServiceDescriptor descriptor) { if (descriptor.ImplementationInstance != null) return descriptor.ImplementationInstance; if (descriptor.ImplementationFactory != null) return descriptor.ImplementationFactory(services); return ActivatorUtilities.GetServiceOrCreateInstance(services, descriptor.ImplementationType); } } }
38.232558
130
0.6618
[ "MIT" ]
Sammarquinho/Design-Patterns-Csharp-DIO
Workbench.DependencyInjection.Extensions/ServiceCollectionExtensions.cs
1,646
C#
/* --------------------------- * SharePoint Manager 2010 v2 * Created by Carsten Keutmann * --------------------------- */ using System; using Microsoft.SharePoint.Administration; using SPM2.Framework; namespace SPM2.SharePoint.Model { [AdapterItemType("Microsoft.SharePoint.Administration.SPOutboundMailService, Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")] public partial class SPOutboundMailServiceNode : SPServiceNode { public SPOutboundMailService OutboundMailService { get { return (SPOutboundMailService)this.SPObject; } set { this.SPObject = value; } } } }
24.8
169
0.604839
[ "MIT" ]
keutmann/SPM
SharePoint Manager 2010 v2/Src/Main/SPM2.SharePoint/Model/Generated/SPOutboundMailServiceNode.cs
744
C#
using System; using System.Reflection; using HotChocolate.Internal; using HotChocolate.Types.Pagination; namespace HotChocolate.PreProcessingExtensions.Pagination { /// <summary> /// A Paging Provider for HotChocolate that provides No Operation during the execution /// of the Pipeline; because all processing was already completed within the Resolver method! /// /// This enables Pagination handling, dynamic Schema creation, dynamic /// Connection class creation, etc. while allowing the actual pagination logic to be implemented /// at a lower layer in the Resolvers or below (e.g. in Service or Repository classes that may /// already exist) so that the results are unaffected by the HotChocolate pipeline; because they /// have already been pre-processed. /// </summary> public class PreProcessedCursorPagingProvider : CursorPagingProvider { //BBernard //This allows one single instance to be used for Generic types that are not known a compile time, // because of the dynamic Schema & Classes gen processes provided by HotChocolate OOTB Sorting/Paging // functionality. //NOTE: Borrowed from QueryableCursorPagingProvider implementation of HotChocolate. private static readonly MethodInfo _createHandler = typeof(PreProcessedCursorPagingProvider).GetMethod( nameof(CreateHandlerInternal), BindingFlags.Static | BindingFlags.NonPublic )!; /// <summary> /// BBernard /// This determines if this Paging Provider can handle the request. Here we validate that we /// are using PagedResult and handle those only as NoOp-Paged processing, leaving other requests /// to be handled by Default implementations. /// NOTE: Borrowed from QueryableCursorPagingProvider implementation of HotChocolate. /// </summary> /// <param name="source"></param> /// <returns></returns> public override bool CanHandle(IExtendedType source) { if (source is null) throw new ArgumentNullException(nameof(source)); bool isPreProcessedResult = source.Type.IsDerivedFromGenericParent(typeof(IPreProcessedCursorSlice<>)); return source.IsArrayOrList && isPreProcessedResult; } /// <summary> /// BBernard /// This is the dynamic initialization of the Handler based on Generic type provided at Runtime. /// HotChocolate handles a lot of dynamic Schema and Class type generation, therefore this must be /// completely dynamic at runtime to support. /// NOTE: Borrowed from QueryableCursorPagingProvider implementation of HotChocolate. /// </summary> /// <param name="source"></param> /// <param name="options"></param> /// <returns></returns> protected override CursorPagingHandler CreateHandler(IExtendedType source, PagingOptions options) { if (source is null) throw new ArgumentNullException(nameof(source)); return (CursorPagingHandler)_createHandler .MakeGenericMethod(source.ElementType?.Source ?? source.Source) .Invoke(null, new object[] { options })!; } private static PreProcessedCursorPagingHandler<TEntity> CreateHandlerInternal<TEntity>( PagingOptions options) => new PreProcessedCursorPagingHandler<TEntity>(options); } }
48.736111
115
0.680251
[ "MIT" ]
DJBMASTER/GraphQL.RepoDB
GraphQL.PreProcessingExtensions/Paging/CursorPaging/PreProcessedCursorPagingProvider.cs
3,511
C#
using Sharpen; namespace android.view.animation { /// <summary> /// An interpolator where the rate of change starts and ends slowly but /// accelerates through the middle. /// </summary> /// <remarks> /// An interpolator where the rate of change starts and ends slowly but /// accelerates through the middle. /// </remarks> [Sharpen.Sharpened] public class AccelerateDecelerateInterpolator : android.view.animation.Interpolator { public AccelerateDecelerateInterpolator() { } public AccelerateDecelerateInterpolator(android.content.Context context, android.util.AttributeSet attrs) { } [Sharpen.ImplementsInterface(@"android.animation.TimeInterpolator")] public virtual float getInterpolation(float input) { return (float)(System.Math.Cos((input + 1) * System.Math.PI) / 2.0f) + 0.5f; } } }
26.03125
100
0.729892
[ "Apache-2.0" ]
Conceptengineai/XobotOS
android/generated/android/view/animation/AccelerateDecelerateInterpolator.cs
833
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> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.ProvideApplicationPartFactoryAttribute("Microsoft.AspNetCore.Mvc.ApplicationParts.CompiledRazorAssemblyApplicationPartFac" + "tory, Microsoft.AspNetCore.Mvc.Razor")] [assembly: System.Reflection.AssemblyCompanyAttribute("Blog")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyProductAttribute("Blog")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyTitleAttribute("Blog.Views")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
46.769231
178
0.668586
[ "MIT" ]
hilylove/Blog-Beginner
Blog/obj/Debug/netcoreapp3.1/Blog.RazorTargetAssemblyInfo.cs
1,216
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Minsk.CodeAnalysis; using Minsk.CodeAnalysis.Authoring; using Minsk.CodeAnalysis.Symbols; using Minsk.CodeAnalysis.Syntax; using Minsk.IO; namespace Minsk { internal sealed class MinskRepl : Repl { private bool _loadingSubmission; private static readonly Compilation emptyCompilation = Compilation.CreateScript(null); private Compilation? _previous; private bool _showTree; private bool _showProgram; private readonly Dictionary<VariableSymbol, object> _variables = new Dictionary<VariableSymbol, object>(); public MinskRepl() { LoadSubmissions(); } protected override object? RenderLine(IReadOnlyList<string> lines, int lineIndex, object? state) { SyntaxTree syntaxTree; if (state == null) { var text = string.Join(Environment.NewLine, lines); syntaxTree = SyntaxTree.Parse(text); } else { syntaxTree = (SyntaxTree) state; } var lineSpan = syntaxTree.Text.Lines[lineIndex].Span; var classifiedSpans = Classifier.Classify(syntaxTree, lineSpan); foreach (var classifiedSpan in classifiedSpans) { var classifiedText = syntaxTree.Text.ToString(classifiedSpan.Span); switch (classifiedSpan.Classification) { case Classification.Keyword: Console.ForegroundColor = ConsoleColor.Blue; break; case Classification.Identifier: Console.ForegroundColor = ConsoleColor.DarkYellow; break; case Classification.Number: Console.ForegroundColor = ConsoleColor.Cyan; break; case Classification.String: Console.ForegroundColor = ConsoleColor.Magenta; break; case Classification.Comment: Console.ForegroundColor = ConsoleColor.Green; break; case Classification.Text: default: Console.ForegroundColor = ConsoleColor.DarkGray; break; } Console.Write(classifiedText); Console.ResetColor(); } return syntaxTree; } [MetaCommand("exit", "Exits the REPL")] private void EvaluateExit() { Environment.Exit(0); } [MetaCommand("cls", "Clears the screen")] private void EvaluateCls() { Console.Clear(); } [MetaCommand("reset", "Clears all previous submissions")] private void EvaluateReset() { _previous = null; _variables.Clear(); ClearSubmissions(); } [MetaCommand("showTree", "Shows the parse tree")] private void EvaluateShowTree() { _showTree = !_showTree; Console.WriteLine(_showTree ? "Showing parse trees." : "Not showing parse trees."); } [MetaCommand("showProgram", "Shows the bound tree")] private void EvaluateShowProgram() { _showProgram = !_showProgram; Console.WriteLine(_showProgram ? "Showing bound tree." : "Not showing bound tree."); } [MetaCommand("load", "Loads a script file")] private void EvaluateLoad(string path) { path = Path.GetFullPath(path); if (!File.Exists(path)) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"error: file does not exist '{path}'"); Console.ResetColor(); return; } var text = File.ReadAllText(path); EvaluateSubmission(text); } [MetaCommand("ls", "Lists all symbols")] private void EvaluateLs() { var compilation = _previous ?? emptyCompilation; var symbols = compilation.GetSymbols().OrderBy(s => s.Kind).ThenBy(s => s.Name); foreach (var symbol in symbols) { symbol.WriteTo(Console.Out); Console.WriteLine(); } } [MetaCommand("dump", "Shows bound tree of a given function")] private void EvaluateDump(string functionName) { var compilation = _previous ?? emptyCompilation; var symbol = compilation.GetSymbols().OfType<FunctionSymbol>().SingleOrDefault(f => f.Name == functionName); if (symbol == null) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"error: function '{functionName}' does not exist"); Console.ResetColor(); return; } compilation.EmitTree(symbol, Console.Out); } protected override bool IsCompleteSubmission(string text) { if (string.IsNullOrEmpty(text)) return true; var lastTwoLinesAreBlank = text.Split(Environment.NewLine) .Reverse() .TakeWhile(s => string.IsNullOrEmpty(s)) .Take(2) .Count() == 2; if (lastTwoLinesAreBlank) return true; var syntaxTree = SyntaxTree.Parse(text); // Use Members because we need to exclude the EndOfFileToken. var lastMember = syntaxTree.Root.Members.LastOrDefault(); if (lastMember == null || lastMember.GetLastToken().IsMissing) return false; return true; } protected override void EvaluateSubmission(string text) { var syntaxTree = SyntaxTree.Parse(text); var compilation = Compilation.CreateScript(_previous, syntaxTree); if (_showTree) syntaxTree.Root.WriteTo(Console.Out); if (_showProgram) compilation.EmitTree(Console.Out); var result = compilation.Evaluate(_variables); if (!result.Diagnostics.Any()) { if (result.Value != null) { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(result.Value); Console.ResetColor(); } _previous = compilation; SaveSubmission(text); } else { Console.Out.WriteDiagnostics(result.Diagnostics); } } private static string GetSubmissionsDirectory() { var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); var submissionsDirectory = Path.Combine(localAppData, "Minsk", "Submissions"); return submissionsDirectory; } private void LoadSubmissions() { var submissionsDirectory = GetSubmissionsDirectory(); if (!Directory.Exists(submissionsDirectory)) return; var files = Directory.GetFiles(submissionsDirectory).OrderBy(f => f).ToArray(); if (files.Length == 0) return; Console.ForegroundColor = ConsoleColor.DarkGray; Console.WriteLine($"Loaded {files.Length} submission(s)"); Console.ResetColor(); _loadingSubmission = true; foreach (var file in files) { var text = File.ReadAllText(file); EvaluateSubmission(text); } _loadingSubmission = false; } private static void ClearSubmissions() { var dir = GetSubmissionsDirectory(); if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); } private void SaveSubmission(string text) { if (_loadingSubmission) return; var submissionsDirectory = GetSubmissionsDirectory(); Directory.CreateDirectory(submissionsDirectory); var count = Directory.GetFiles(submissionsDirectory).Length; var name = $"submission{count:0000}"; var fileName = Path.Combine(submissionsDirectory, name); File.WriteAllText(fileName, text); } } }
33.469697
120
0.536442
[ "MIT" ]
fedeazzato/minsk
src/msi/MinskRepl.cs
8,836
C#
#region BSD License /* * Use of this source code is governed by a BSD-style * license or other governing licenses that can be found in the LICENSE.md file or at * https://raw.githubusercontent.com/Krypton-Suite/Extended-Toolkit/master/LICENSE */ // Original license /** * MIT License * * Copyright (c) 2017 - 2018 Jacob Mesu * * 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. */ #endregion namespace Krypton.Toolkit.Suite.Extended.Navi.Suite { public class NaviColourTableOff7Silver : NaviColourTable { // General colors public override Color Border { get { return Color.FromArgb(111, 112, 116); } } public override Color BorderInner { get { return Color.FromArgb(255, 255, 255); } } public override Color Text { get { return Color.FromArgb(21, 66, 139); } } public override Color ShapesFront { get { return Color.FromArgb(101, 104, 112); } } public override Color Background { get { return Color.FromArgb(255, 255, 255); } } // Designtime only public override Color DashedLineColor { get { return Color.FromArgb(101, 147, 207); } } // NaviBandCollapsed public override Color BandCollapsedBgColor1 { get { return Color.FromArgb(238, 238, 244); } } public override Color BandCollapsedBgColor2 { get { return Color.FromArgb(209, 214, 220); } } public override Color BandCollapsedHoveredColor1 { get { return Color.FromArgb(255, 231, 162); } } public override Color BandCollapsedClickedColor1 { get { return Color.FromArgb(251, 140, 60); } } // NaviBand Popup public override Color PopupBandBackground1 { get { return Color.FromArgb(240, 241, 242); } } public override Color PopupBandBackground2 { get { return Color.FromArgb(227, 239, 255); } } // NaviBar header public override Color HeaderColor1 { get { return Color.FromArgb(218, 223, 230); } } public override Color HeaderColor2 { get { return Color.FromArgb(255, 255, 255); } } public override Color HeaderText { get { return Color.FromArgb(21, 66, 139); } } // NaviBar Overflowpanel public override Color OverflowColor1 { get { return Color.FromArgb(209, 214, 220); } } public override Color OverflowColor2 { get { return Color.FromArgb(209, 214, 220); } } // NaviButton Normal public override Color ButtonNormalColor1 { get { return Color.FromArgb(219, 222, 226); } } public override Color ButtonNormalColor2 { get { return Color.FromArgb(197, 199, 209); } } public override Color ButtonNormalColor3 { get { return Color.FromArgb(214, 218, 228); } } public override Color ButtonNormalColor4 { get { return Color.FromArgb(235, 238, 250); } } // NaviButton hovered public override Color ButtonHoveredColor1 { get { return Color.FromArgb(255, 230, 159); } } public override Color ButtonHoveredColor2 { get { return Color.FromArgb(255, 215, 103); } } public override Color ButtonHoveredColor3 { get { return Color.FromArgb(255, 233, 168); } } public override Color ButtonHoveredColor4 { get { return Color.FromArgb(255, 254, 228); } } // NaviButton active public override Color ButtonActiveColor1 { get { return Color.FromArgb(254, 225, 122); } } public override Color ButtonActiveColor2 { get { return Color.FromArgb(255, 171, 63); } } public override Color ButtonActiveColor3 { get { return Color.FromArgb(255, 188, 111); } } public override Color ButtonActiveColor4 { get { return Color.FromArgb(255, 217, 170); } } // NaviButton clicked public override Color ButtonClickedColor1 { get { return Color.FromArgb(255, 211, 101); } } public override Color ButtonClickedColor2 { get { return Color.FromArgb(251, 140, 60); } } public override Color ButtonClickedColor3 { get { return Color.FromArgb(255, 173, 67); } } public override Color ButtonClickedColor4 { get { return Color.FromArgb(255, 189, 105); } } // NaviClientArea public override Color NaviClientareaBgColor1 { get { return Color.FromArgb(209, 214, 220); } } public override Color NaviClientareaBgColor2 { get { return Color.FromArgb(231, 235, 239); } } // NaviCollapseButton Normal public override Color CollapseButtonNormalColor1 { get { return Color.FromArgb(255, 255, 255); } } public override Color CollapseButtonNormalColor2 { get { return Color.FromArgb(218, 223, 230); } } // NaviCollapseButton Hovered public override Color CollapseButtonHoveredColor1 { get { return Color.FromArgb(248, 194, 94); } } // Dark public override Color CollapseButtonHoveredColor2 { get { return Color.FromArgb(255, 255, 220); } } // Light // NaviCollapseButton Clicked public override Color CollapseButtonClickedColor1 { get { return Color.FromArgb(232, 127, 8); } } public override Color CollapseButtonClickedColor2 { get { return Color.FromArgb(247, 217, 121); } } // NaviCollapseButton button public override Color ButtonCollapseFront { get { return Color.FromArgb(255, 248, 203); } } public override Color ButtonCollapseActive { get { return Color.FromArgb(255, 248, 203); } } // NaviGroup normal public override Color GroupColor1 { get { return Color.FromArgb(215, 215, 229); } } public override Color GroupColor2 { get { return Color.FromArgb(216, 216, 230); } } // NaviGroup hovered public override Color GroupHoveredColor1 { get { return Color.FromArgb(215, 215, 229); } } public override Color GroupHoveredColor2 { get { return Color.FromArgb(216, 216, 230); } } public override Color GroupBorderLight { get { return Color.FromArgb(197, 199, 199); } } // Navigroup expanded public override Color GroupExpandedColor1 { get { return Color.FromArgb(37, 37, 37); } } public override Color GroupExpandedColor2 { get { return Color.FromArgb(98, 98, 98); } } // Splitter public override Color SplitterColor1 { get { return Color.FromArgb(119, 118, 151); } } public override Color SplitterColor2 { get { return Color.FromArgb(168, 167, 191); } } public override Color SplitterColor3 { get { return Color.FromArgb(255, 255, 255); } } } }
56.6
116
0.69122
[ "BSD-3-Clause" ]
Krypton-Suite/Extended-Toolk
Source/Krypton Toolkit/Main/Krypton.Toolkit.Suite.Extended.Navi.Suite/Classes/Colours/NaviColourTableOff7Silver.cs
7,360
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: Templates\CSharp\Model\EntityType.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// The type Dep IOSEnrollment Profile. /// </summary> [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public partial class DepIOSEnrollmentProfile : DepEnrollmentBaseProfile { /// <summary> /// Gets or sets i tunes pairing mode. /// Indicates the iTunes pairing mode /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "iTunesPairingMode", Required = Newtonsoft.Json.Required.Default)] public ITunesPairingMode? ITunesPairingMode { get; set; } /// <summary> /// Gets or sets management certificates. /// Management certificates for Apple Configurator /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "managementCertificates", Required = Newtonsoft.Json.Required.Default)] public IEnumerable<ManagementCertificateWithThumbprint> ManagementCertificates { get; set; } /// <summary> /// Gets or sets restore from android disabled. /// Indicates if Restore from Android is disabled /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "restoreFromAndroidDisabled", Required = Newtonsoft.Json.Required.Default)] public bool? RestoreFromAndroidDisabled { get; set; } /// <summary> /// Gets or sets await device configured confirmation. /// Indicates if the device will need to wait for configured confirmation /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "awaitDeviceConfiguredConfirmation", Required = Newtonsoft.Json.Required.Default)] public bool? AwaitDeviceConfiguredConfirmation { get; set; } /// <summary> /// Gets or sets shared ipad maximum user count. /// This specifies the maximum number of users that can use a shared iPad. Only applicable in shared iPad mode. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "sharedIPadMaximumUserCount", Required = Newtonsoft.Json.Required.Default)] public Int32? SharedIPadMaximumUserCount { get; set; } /// <summary> /// Gets or sets enable shared ipad. /// This indicates whether the device is to be enrolled in a mode which enables multi user scenarios. Only applicable in shared iPads. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "enableSharedIPad", Required = Newtonsoft.Json.Required.Default)] public bool? EnableSharedIPad { get; set; } /// <summary> /// Gets or sets company portal vpp token id. /// If set, indicates which Vpp token should be used to deploy the Company Portal w/ device licensing. 'enableAuthenticationViaCompanyPortal' must be set in order for this property to be set. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "companyPortalVppTokenId", Required = Newtonsoft.Json.Required.Default)] public string CompanyPortalVppTokenId { get; set; } /// <summary> /// Gets or sets enable single app enrollment mode. /// Tells the device to enable single app mode and apply app-lock during enrollment. Default is false. 'enableAuthenticationViaCompanyPortal' and 'companyPortalVppTokenId' must be set for this property to be set. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "enableSingleAppEnrollmentMode", Required = Newtonsoft.Json.Required.Default)] public bool? EnableSingleAppEnrollmentMode { get; set; } /// <summary> /// Gets or sets home button screen disabled. /// Indicates if home button sensitivity screen is disabled /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "homeButtonScreenDisabled", Required = Newtonsoft.Json.Required.Default)] public bool? HomeButtonScreenDisabled { get; set; } /// <summary> /// Gets or sets i message and face time screen disabled. /// Indicates if iMessage and FaceTime screen is disabled /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "iMessageAndFaceTimeScreenDisabled", Required = Newtonsoft.Json.Required.Default)] public bool? IMessageAndFaceTimeScreenDisabled { get; set; } /// <summary> /// Gets or sets on boarding screen disabled. /// Indicates if onboarding setup screen is disabled /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "onBoardingScreenDisabled", Required = Newtonsoft.Json.Required.Default)] public bool? OnBoardingScreenDisabled { get; set; } /// <summary> /// Gets or sets screen time screen disabled. /// Indicates if screen timeout setup is disabled /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "screenTimeScreenDisabled", Required = Newtonsoft.Json.Required.Default)] public bool? ScreenTimeScreenDisabled { get; set; } /// <summary> /// Gets or sets sim setup screen disabled. /// Indicates if the SIMSetup screen is disabled /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "simSetupScreenDisabled", Required = Newtonsoft.Json.Required.Default)] public bool? SimSetupScreenDisabled { get; set; } /// <summary> /// Gets or sets software update screen disabled. /// Indicates if the mandatory sofware update screen is disabled /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "softwareUpdateScreenDisabled", Required = Newtonsoft.Json.Required.Default)] public bool? SoftwareUpdateScreenDisabled { get; set; } /// <summary> /// Gets or sets watch migration screen disabled. /// Indicates if the watch migration screen is disabled /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "watchMigrationScreenDisabled", Required = Newtonsoft.Json.Required.Default)] public bool? WatchMigrationScreenDisabled { get; set; } } }
54.120301
220
0.670464
[ "MIT" ]
gurry/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Models/Generated/DepIOSEnrollmentProfile.cs
7,198
C#
using Newtonsoft.Json; namespace CarWash.Models { public class PostSelectedOptionsAndTime { [JsonProperty("selectedOptionId")] public int[] SelectedWashServices { get; set; } [JsonProperty("timeFrom")] public string TimeFrom { get; set; } [JsonProperty("timeTo")] public string TimeTo { get; set; } } }
24.333333
55
0.627397
[ "MIT" ]
NPerederiy/car-wash-2.0
CarWash/Models/PostSelectedOptionsAndTime.cs
367
C#
using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using AutoMapper; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using PortfolioGallery.API.Controllers.Resources; using PortfolioGallery.API.Core; using PortfolioGallery.API.Core.Models; using PortfolioGallery.API.Core.Repositories; using PortfolioGallery.API.Core.Services; using PortfolioGallery.API.Helpers; namespace PortfolioGallery.API.Controllers { [Authorize] [Route("api/[controller]/{userId}")] [ApiController] public class PhotosController : ControllerBase { private readonly IUserRepository userRepo; private readonly IPhotoService photoService; private readonly IUnitOfWork unit; private readonly IMapper mapper; private readonly IRepository<Photo> photoRepo; public PhotosController(IUserRepository userRepo, IRepository<Photo> photoRepo, IPhotoService photoService, IUnitOfWork unit, IMapper mapper) { this.photoRepo = photoRepo; this.mapper = mapper; this.unit = unit; this.photoService = photoService; this.userRepo = userRepo; } [HttpGet] public async Task<IEnumerable<PhotoResource>> GetPhotos([FromQuery] FilterResource filter) { IEnumerable<Photo> photos; if (filter.PhotoName != null) photos = await photoRepo.Find(p => p.Name.Contains(filter.PhotoName)); else photos = await photoRepo.GetAll(); return mapper.Map<IEnumerable<Photo>, IEnumerable<PhotoResource>>(photos); } [HttpPost] public async Task<IActionResult> UploadPhoto(int userId, IFormFile photoFile) { if (!ControllerHelper.IsAllowedUser(userId, User)) return Unauthorized(); var user = await userRepo.GetUserEager(userId); var photo = photoService.UploadPhotoToCloudinary(photoFile); user.Photos.Add(photo); if (await unit.CompleteAsync()) { var photoToReturn = mapper.Map<PhotoResource>(photo); return CreatedAtRoute("GetPhoto", new { photoId = photo.Id }, photoToReturn); } return BadRequest("Could not add the photo"); } [HttpGet("{photoId}", Name = "GetPhoto")] public async Task<IActionResult> GetPhoto(int photoId) { var photo = await photoRepo.Get(photoId); return Ok(mapper.Map<PhotoResource>(photo)); } [HttpPut("{photoId}")] public async Task<IActionResult> UpdatePhotoInformation(int userId, int photoId, PhotoResource resource) { if (!ControllerHelper.IsAllowedUser(userId, User)) return Unauthorized(); var photo = await photoRepo.Get(photoId); if (photo == null) return NotFound(); photo.Name = resource.Name; photo.Description = resource.Description; await unit.CompleteAsync(); return Ok(mapper.Map<PhotoResource>(photo)); } [HttpDelete("{photoId}")] public async Task<IActionResult> DeletePhoto(int userId, int photoId) { if (!ControllerHelper.IsAllowedUser(userId, User)) return Unauthorized(); var user = await userRepo.GetUserEager(userId); var photo = user.Photos.FirstOrDefault(p => p.Id == photoId); if (photo == null) return NotFound(); photoRepo.Remove(photo); if (await unit.CompleteAsync()) { photoService.DeletePhotoFromCloudinary(photo); return Ok(photoId); } return BadRequest("Failed to delete the photo"); } } }
32.479675
115
0.61577
[ "MIT" ]
Radek12345/PortfolioGallery
PortfolioGallery.API/Controllers/PhotosController.cs
3,995
C#
using System; using System.Collections.Generic; namespace UnityGoogleDrive.Data { /// <summary> /// A permission for a file. A permission grants a user, group, domain or the world access to a file or a folder hierarchy. /// Prototype: https://developers.google.com/drive/v3/reference/permissions#resource-representations. /// </summary> public class Permission : ResourceData { public class TeamDrivePermissionDetailsData { /// <summary> /// Whether this permission is inherited. This field is always populated. /// This is an output-only field. /// </summary> public bool? Inherited { get; private set; } /// <summary> /// The ID of the item from which this permission is inherited. /// This is an output-only field and is only populated for members of the Team Drive. /// </summary> public string InheritedFrom { get; private set; } /// <summary> /// The primary role for this user. While new values may be added in the future, /// the following are currently possible: /// - organizer /// - writer /// - commenter /// - reader /// </summary> public string Role { get; private set; } /// <summary> /// The Team Drive permission type for this user. /// While new values may be added in future, the following are currently possible: /// - file /// - member /// </summary> public string TeamDrivePermissionType { get; private set; } } /// <summary> /// Identifies what kind of resource this is. Value: the fixed string "drive#permission". /// </summary> public override string Kind { get { return "drive#permission"; } } /// <summary> /// The ID of this permission. This is a unique identifier for the grantee, and is /// published in User resources as permissionId. /// </summary> public string Id { get; private set; } /// <summary> /// Whether the permission allows the file to be discovered through search. /// This is only applicable for permissions of type domain or anyone. /// </summary> public bool? AllowFileDiscovery { get; private set; } /// <summary> /// Whether the account associated with this permission has been deleted. /// This field only pertains to user and group permissions. /// </summary> public bool? Deleted { get; private set; } /// <summary> /// A displayable name for users, groups or domains. /// </summary> public string DisplayName { get; private set; } /// <summary> /// The domain to which this permission refers. /// </summary> public string Domain { get; private set; } /// <summary> /// The email address of the user or group to which this permission refers. /// </summary> public string EmailAddress { get; private set; } /// <summary> /// The time at which this permission will expire (RFC 3339 date-time). /// Expiration times have the following restrictions: /// - They can only be set on user and group permissions /// - The time must be in the future /// - The time cannot be more than a year in the future /// </summary> public DateTime? ExpirationTime { get; private set; } /// <summary> /// A link to the user's profile photo, if available. /// </summary> public string PhotoLink { get; private set; } /// <summary> /// The role granted by this permission. /// While new values may be supported in the future, the following are currently allowed: /// - organizer /// - owner /// - writer /// - commenter /// - reader /// </summary> public string Role { get; private set; } /// <summary> /// Details of whether the permissions on this Team Drive item are inherited or directly /// on this item. This is an output-only field which is present only for Team Drive items. /// </summary> public List<TeamDrivePermissionDetailsData> TeamDrivePermissionDetails { get; private set; } /// <summary> /// The type of the grantee. Valid values are: /// - user /// - group /// - domain /// - anyone /// </summary> public string Type { get; private set; } } }
43.163636
127
0.564238
[ "MIT" ]
anmolbajajnet/UnityGoogleDrive
Assets/UnityGoogleDrive/Runtime/API/Data/Permission.cs
4,750
C#
using UnityEngine; namespace Main { public interface IHead : IGoalHandler, IGamePause { void LookAt(Vector3 forward); void OnBlowed(); } }
15.272727
53
0.636905
[ "MIT" ]
khayreddinebiada/Code-HC-Prototype-Example
Characters/Interfaces/IHead.cs
168
C#
//参考自http://schemingdeveloper.com/2014/12/04/serializing-delegates-unity/ //Delegate没有Serializable标记,但是可以序列化的原因是https://referencesource.microsoft.com/#mscorlib/system/rttype.cs,3830130f2931fca3 /* * 看BinaryFormatter源码时发现会调用该方法判断是否可序列化 * internal bool IsSpecialSerializableType() { RuntimeType rt = this; do { // In all sane cases we only need to compare the direct level base type with // System.Enum and System.MulticastDelegate. However, a generic argument can // have a base type constraint that is Delegate or even a real delegate type. // Let's maintain compatibility and return true for them. if (rt == RuntimeType.DelegateType || rt == RuntimeType.EnumType) return true; rt = rt.GetBaseType(); } while (rt != null); return false; } * */ using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using UnityEngine; using Object = UnityEngine.Object; [Serializable] public class SerializableDelegate : ISerializationCallbackReceiver { [SerializeField] UnityEngine.Object mTarget; [SerializeField] string mMethodName; [SerializeField] byte[] mSerialData; [SerializeField] string mDelegateTypeFullName; object mValue; public object value { get { return mValue; } private set { mValue = value; } } public SerializableDelegate(object pValue) { if (pValue == null) return; var tType = pValue.GetType(); if (!tType.IsSubclassOf(typeof(Delegate))) { throw new InvalidOperationException(pValue.GetType().Name + " is not a delegate type."); } mDelegateTypeFullName = tType.FullName; value = pValue; } void Serialize(object pValue) { if (pValue == null) { mTarget = null; mMethodName = ""; mSerialData = null; return; } var tDelegate = pValue as Delegate; if (tDelegate == null) { throw new InvalidOperationException(pValue.GetType().Name + " is not a delegate type."); } mTarget = tDelegate.Target as Object; if (mTarget != null) { mMethodName = tDelegate.Method.Name; mSerialData = null; } else { //Serialize the data to a binary stream using (var tStream = new MemoryStream()) { (new BinaryFormatter()).Serialize(tStream, pValue); tStream.Flush(); mSerialData = tStream.ToArray(); } mMethodName = null; } } object Deserialize() { if ((mSerialData == null || mSerialData.Length == 0) && string.IsNullOrEmpty(mMethodName)) { return null; } if (mTarget != null) { return Delegate.CreateDelegate(Type.GetType(mDelegateTypeFullName), mTarget, mMethodName); } using (var tStream = new MemoryStream(mSerialData)) { return (new BinaryFormatter()).Deserialize(tStream); } } void ISerializationCallbackReceiver.OnBeforeSerialize() { Serialize(mValue); } void ISerializationCallbackReceiver.OnAfterDeserialize() { value = Deserialize(); } }
26.744361
119
0.570143
[ "MIT" ]
tylearymf/UnityStepPlayTool
Assets/Editor/SerializableDelegate.cs
3,637
C#
// Copyright (c) Solal Pirelli // This code is licensed under the MIT License (see Licence.txt for details) using System; namespace ThriftSharp.Utilities { /// <summary> /// Utility class for validating method parameters. /// </summary> internal static class Validation { /// <summary> /// Ensures the specified object is not null. /// </summary> public static void IsNotNull<T>( T obj, string parameterName ) where T : class { if( obj == null ) { throw new ArgumentNullException( $"Parameter {parameterName} must not be null." ); } } /// <summary> /// Ensures the specified string is not null, empty or entirely composed of whitespace. /// </summary> public static void IsNeitherNullNorWhitespace( string s, string parameterName ) { if( string.IsNullOrWhiteSpace( s ) ) { throw new ArgumentException( $"Parameter {parameterName} must not be null, empty or contain only whitespace. It was '{s ?? "null"}'." ); } } } }
32.27027
153
0.554439
[ "MIT" ]
SolalPirelli/ThriftSharp
src/Utilities/Validation.cs
1,196
C#
using Microsoft.AspNetCore.Mvc; using Packt.CS7; using System.Collections.Generic; using System.Linq; namespace NorthwindService.Controllers { [Route("api/[controller]")] public class CategoriesController : Controller { private readonly Northwind db; public CategoriesController(Northwind db) { this.db = db; } // GET: api/categories [HttpGet] public IEnumerable<Category> Get() { var categories = db.Categories.ToArray(); return categories; } // GET api/categories/5 [HttpGet("{id}")] public Category Get(int id) { var category = db.Categories.Find(id); return category; } } }
22.028571
53
0.570687
[ "MIT" ]
Narasegowda/CSharp-7.1-and-.NET-Core-2.0-Modern-Cross-Platform-Development-Third-Edition
VS2017/Part3/NorthwindService/Controllers/CategoriesController.cs
773
C#
using Microsoft.Extensions.DependencyInjection; using StockTradingAnalysis.Services.External.Interfaces; using StockTradingAnalysis.Services.External.Services; using StockTradingAnalysis.Web.Common.Interfaces; namespace StockTradingAnalysis.Web.BindingModules { /// <summary> /// Binding module for the external services /// </summary> public class ExternalServicesBindingModule : IBindingModule { /// <summary> /// Loads the binding configuration. /// </summary> /// <param name="serviceCollection">The service collection.</param> public void Load(IServiceCollection serviceCollection) { //Services serviceCollection.AddSingleton<IStockQuoteExternalService, StockQuoteExternalService>(); } } }
31.391304
91
0.783934
[ "Unlicense" ]
BenjaminBest/StockTradingAnalysisWebsite
StockTradingAnalysisWebsite/StockTradingAnalysis.Web/App_Start/BindingModules/ExternalServicesBindingModule.cs
724
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System.Collections.Immutable; namespace Pulumi.Nsxt { public static class Config { private static readonly Pulumi.Config __config = new Pulumi.Config("nsxt"); public static bool? AllowUnverifiedSsl { get; set; } = __config.GetBoolean("allowUnverifiedSsl") ?? Utilities.GetEnvBoolean("NSXT_ALLOW_UNVERIFIED_SSL"); public static string? CaFile { get; set; } = __config.Get("caFile") ?? Utilities.GetEnv("NSXT_CA_FILE"); public static string? ClientAuthCertFile { get; set; } = __config.Get("clientAuthCertFile") ?? Utilities.GetEnv("NSXT_CLIENT_AUTH_CERT_FILE"); public static string? ClientAuthKeyFile { get; set; } = __config.Get("clientAuthKeyFile") ?? Utilities.GetEnv("NSXT_CLIENT_AUTH_KEY_FILE"); /// <summary> /// Enforcement Point for NSXT Policy /// </summary> public static string? EnforcementPoint { get; set; } = __config.Get("enforcementPoint") ?? Utilities.GetEnv("NSXT_POLICY_ENFORCEMENT_POINT"); /// <summary> /// Is this a policy global manager endpoint /// </summary> public static bool? GlobalManager { get; set; } = __config.GetBoolean("globalManager") ?? Utilities.GetEnvBoolean("NSXT_GLOBAL_MANAGER"); /// <summary> /// The hostname or IP address of the NSX manager. /// </summary> public static string? Host { get; set; } = __config.Get("host") ?? Utilities.GetEnv("NSXT_MANAGER_HOST"); /// <summary> /// Maximum number of HTTP client retries /// </summary> public static int? MaxRetries { get; set; } = __config.GetInt32("maxRetries") ?? Utilities.GetEnvInt32("NSXT_MAX_RETRIES"); public static string? Password { get; set; } = __config.Get("password") ?? Utilities.GetEnv("NSXT_PASSWORD"); public static bool? RemoteAuth { get; set; } = __config.GetBoolean("remoteAuth") ?? Utilities.GetEnvBoolean("NSXT_REMOTE_AUTH"); /// <summary> /// Maximum delay in milliseconds between retries of a request /// </summary> public static int? RetryMaxDelay { get; set; } = __config.GetInt32("retryMaxDelay") ?? Utilities.GetEnvInt32("NSXT_RETRY_MAX_DELAY"); /// <summary> /// Minimum delay in milliseconds between retries of a request /// </summary> public static int? RetryMinDelay { get; set; } = __config.GetInt32("retryMinDelay") ?? Utilities.GetEnvInt32("NSXT_RETRY_MIN_DELAY"); /// <summary> /// HTTP replies status codes to retry on /// </summary> public static ImmutableArray<int> RetryOnStatusCodes { get; set; } = __config.GetObject<ImmutableArray<int>>("retryOnStatusCodes"); /// <summary> /// Treat partial success status as success /// </summary> public static bool? ToleratePartialSuccess { get; set; } = __config.GetBoolean("toleratePartialSuccess") ?? Utilities.GetEnvBoolean("NSXT_TOLERATE_PARTIAL_SUCCESS"); public static string? Username { get; set; } = __config.Get("username") ?? Utilities.GetEnv("NSXT_USERNAME"); /// <summary> /// URL for VMC authorization service (CSP) /// </summary> public static string? VmcAuthHost { get; set; } = __config.Get("vmcAuthHost") ?? Utilities.GetEnv("NSXT_VMC_AUTH_HOST"); /// <summary> /// Long-living API token for VMC authorization /// </summary> public static string? VmcToken { get; set; } = __config.Get("vmcToken") ?? Utilities.GetEnv("NSXT_VMC_TOKEN"); } }
48.363636
173
0.653061
[ "ECL-2.0", "Apache-2.0" ]
nvpnathan/pulumi-nsxt
sdk/dotnet/Config/Config.cs
3,724
C#
using UnityEngine; public class TestFunction : MonoBehaviour { Elliptical e; Vector2[] points = new Vector2[10]; // Start is called before the first frame update void Start() { e = new Elliptical(new Rect(1,1,1,3), EInflexionType.DESCANDANTE); float x = 1; float step = 1 / 10f; for (int i = 0; i < 10; i++) { Debug.LogFormat("x : {0}, y : {1}, d : {2}, d2 : {3}", x, e.image(x), e.derivative(x, 1), e.derivative(x, 2)); x += step; points[i] = new Vector2(x, e.image(x)); } } private void OnDrawGizmos() { for (int i = 0; i < 9; i++) Gizmos.DrawLine(new Vector3(points[i].x, points[i].y, 0), new Vector3(points[i+1].x, points[i+1].y, 0)); } }
26.333333
122
0.516456
[ "MIT" ]
Renardjojo/TinyWings
Assets/Scripts/TestFunction.cs
792
C#
using AutomationIoC.Integration.Commands; using System.Management.Automation; using Xunit; namespace AutomationIoC.Tools.Command; public class AutomationCommandTests { [Fact] public void ShouldRunExternalCommands() { var environmentKey = Guid.NewGuid().ToString(); var expectedValue = Guid.NewGuid().ToString(); using var automationCommand = new AutomationCommand<TestCommand>(); automationCommand.RunExternalCommand("Set-Variable", command => command .AddParameter("Name", environmentKey) .AddParameter("Value", expectedValue)); var results = automationCommand.RunExternalCommand<PSVariable>("Get-Variable", command => command.AddParameter("Name", environmentKey)); Assert.Single(results); Assert.Equal(expectedValue, results.First().Value); } }
30.413793
97
0.681406
[ "MIT" ]
kenswan/AutomationIoC
test/tools/Command/AutomationCommandTests.cs
884
C#
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using LibGit2Sharp.Core; using LibGit2Sharp.Core.Handles; namespace LibGit2Sharp { /// <summary> /// Holds the result of the determination of the state of the working directory. /// <para>Only files that differ from the current index and/or commit will be considered.</para> /// </summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public class RepositoryStatus : IEnumerable<StatusEntry> { private readonly ICollection<StatusEntry> statusEntries; private readonly List<StatusEntry> added = new List<StatusEntry>(); private readonly List<StatusEntry> staged = new List<StatusEntry>(); private readonly List<StatusEntry> removed = new List<StatusEntry>(); private readonly List<StatusEntry> missing = new List<StatusEntry>(); private readonly List<StatusEntry> modified = new List<StatusEntry>(); private readonly List<StatusEntry> untracked = new List<StatusEntry>(); private readonly List<StatusEntry> ignored = new List<StatusEntry>(); private readonly List<StatusEntry> renamedInIndex = new List<StatusEntry>(); private readonly List<StatusEntry> renamedInWorkDir = new List<StatusEntry>(); private readonly List<StatusEntry> unaltered = new List<StatusEntry>(); private readonly bool isDirty; private readonly IDictionary<FileStatus, Action<RepositoryStatus, StatusEntry>> dispatcher = Build(); private static IDictionary<FileStatus, Action<RepositoryStatus, StatusEntry>> Build() { return new Dictionary<FileStatus, Action<RepositoryStatus, StatusEntry>> { { FileStatus.NewInWorkdir, (rs, s) => rs.untracked.Add(s) }, { FileStatus.ModifiedInWorkdir, (rs, s) => rs.modified.Add(s) }, { FileStatus.DeletedFromWorkdir, (rs, s) => rs.missing.Add(s) }, { FileStatus.NewInIndex, (rs, s) => rs.added.Add(s) }, { FileStatus.ModifiedInIndex, (rs, s) => rs.staged.Add(s) }, { FileStatus.DeletedFromIndex, (rs, s) => rs.removed.Add(s) }, { FileStatus.RenamedInIndex, (rs, s) => rs.renamedInIndex.Add(s) }, { FileStatus.Ignored, (rs, s) => rs.ignored.Add(s) }, { FileStatus.RenamedInWorkdir, (rs, s) => rs.renamedInWorkDir.Add(s) }, }; } /// <summary> /// Needed for mocking purposes. /// </summary> protected RepositoryStatus() { } internal unsafe RepositoryStatus(Repository repo, StatusOptions options) { statusEntries = new List<StatusEntry>(); using (GitStatusOptions coreOptions = CreateStatusOptions(options ?? new StatusOptions())) using (StatusListHandle list = Proxy.git_status_list_new(repo.Handle, coreOptions)) { int count = Proxy.git_status_list_entrycount(list); for (int i = 0; i < count; i++) { git_status_entry *entry = Proxy.git_status_byindex(list, i); AddStatusEntryForDelta(entry->status, entry->head_to_index, entry->index_to_workdir); } isDirty = statusEntries.Any(entry => entry.State != FileStatus.Ignored && entry.State != FileStatus.Unaltered); } } private static GitStatusOptions CreateStatusOptions(StatusOptions options) { var coreOptions = new GitStatusOptions { Version = 1, Show = (GitStatusShow)options.Show, }; if (options.IncludeIgnored) { coreOptions.Flags |= GitStatusOptionFlags.IncludeIgnored; } if (options.IncludeUntracked) { coreOptions.Flags |= GitStatusOptionFlags.IncludeUntracked; } if (options.DetectRenamesInIndex) { coreOptions.Flags |= GitStatusOptionFlags.RenamesHeadToIndex | GitStatusOptionFlags.RenamesFromRewrites; } if (options.DetectRenamesInWorkDir) { coreOptions.Flags |= GitStatusOptionFlags.RenamesIndexToWorkDir | GitStatusOptionFlags.RenamesFromRewrites; } if (options.ExcludeSubmodules) { coreOptions.Flags |= GitStatusOptionFlags.ExcludeSubmodules; } if (options.RecurseIgnoredDirs) { coreOptions.Flags |= GitStatusOptionFlags.RecurseIgnoredDirs; } if (options.RecurseUntrackedDirs) { coreOptions.Flags |= GitStatusOptionFlags.RecurseUntrackedDirs; } if (options.PathSpec != null) { coreOptions.PathSpec = GitStrArrayManaged.BuildFrom(options.PathSpec); } if (options.DisablePathSpecMatch) { coreOptions.Flags |= GitStatusOptionFlags.DisablePathspecMatch; } if (options.IncludeUnaltered) { coreOptions.Flags |= GitStatusOptionFlags.IncludeUnmodified; } return coreOptions; } private unsafe void AddStatusEntryForDelta(FileStatus gitStatus, git_diff_delta* deltaHeadToIndex, git_diff_delta* deltaIndexToWorkDir) { RenameDetails headToIndexRenameDetails = null; RenameDetails indexToWorkDirRenameDetails = null; if ((gitStatus & FileStatus.RenamedInIndex) == FileStatus.RenamedInIndex) { headToIndexRenameDetails = new RenameDetails(LaxUtf8Marshaler.FromNative(deltaHeadToIndex->old_file.Path), LaxUtf8Marshaler.FromNative(deltaHeadToIndex->new_file.Path), (int)deltaHeadToIndex->similarity); } if ((gitStatus & FileStatus.RenamedInWorkdir) == FileStatus.RenamedInWorkdir) { indexToWorkDirRenameDetails = new RenameDetails(LaxUtf8Marshaler.FromNative(deltaIndexToWorkDir->old_file.Path), LaxUtf8Marshaler.FromNative(deltaIndexToWorkDir->new_file.Path), (int)deltaIndexToWorkDir->similarity); } var filePath = LaxUtf8Marshaler.FromNative(deltaIndexToWorkDir != null ? deltaIndexToWorkDir->new_file.Path : deltaHeadToIndex->new_file.Path); StatusEntry statusEntry = new StatusEntry(filePath, gitStatus, headToIndexRenameDetails, indexToWorkDirRenameDetails); if (gitStatus == FileStatus.Unaltered) { unaltered.Add(statusEntry); } else { foreach (KeyValuePair<FileStatus, Action<RepositoryStatus, StatusEntry>> kvp in dispatcher) { if (!gitStatus.HasFlag(kvp.Key)) { continue; } kvp.Value(this, statusEntry); } } statusEntries.Add(statusEntry); } /// <summary> /// Gets the <see cref="StatusEntry"/> for the specified relative path. /// </summary> public virtual StatusEntry this[string path] { get { Ensure.ArgumentNotNullOrEmptyString(path, "path"); var entries = statusEntries.Where(e => string.Equals(e.FilePath, path, StringComparison.Ordinal)).ToList(); Debug.Assert(!(entries.Count > 1)); if (entries.Count == 0) { return new StatusEntry(path, FileStatus.Nonexistent); } return entries.Single(); } } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>An <see cref="IEnumerator{T}"/> object that can be used to iterate through the collection.</returns> public virtual IEnumerator<StatusEntry> GetEnumerator() { return statusEntries.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>An <see cref="IEnumerator"/> object that can be used to iterate through the collection.</returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// List of files added to the index, which are not in the current commit /// </summary> public virtual IEnumerable<StatusEntry> Added { get { return added; } } /// <summary> /// List of files added to the index, which are already in the current commit with different content /// </summary> public virtual IEnumerable<StatusEntry> Staged { get { return staged; } } /// <summary> /// List of files removed from the index but are existent in the current commit /// </summary> public virtual IEnumerable<StatusEntry> Removed { get { return removed; } } /// <summary> /// List of files existent in the index but are missing in the working directory /// </summary> public virtual IEnumerable<StatusEntry> Missing { get { return missing; } } /// <summary> /// List of files with unstaged modifications. A file may be modified and staged at the same time if it has been modified after adding. /// </summary> public virtual IEnumerable<StatusEntry> Modified { get { return modified; } } /// <summary> /// List of files existing in the working directory but are neither tracked in the index nor in the current commit. /// </summary> public virtual IEnumerable<StatusEntry> Untracked { get { return untracked; } } /// <summary> /// List of files existing in the working directory that are ignored. /// </summary> public virtual IEnumerable<StatusEntry> Ignored { get { return ignored; } } /// <summary> /// List of files that were renamed and staged. /// </summary> public virtual IEnumerable<StatusEntry> RenamedInIndex { get { return renamedInIndex; } } /// <summary> /// List of files that were renamed in the working directory but have not been staged. /// </summary> public virtual IEnumerable<StatusEntry> RenamedInWorkDir { get { return renamedInWorkDir; } } /// <summary> /// List of files that were unmodified in the working directory. /// </summary> public virtual IEnumerable<StatusEntry> Unaltered { get { return unaltered; } } /// <summary> /// True if the index or the working directory has been altered since the last commit. False otherwise. /// </summary> public virtual bool IsDirty { get { return isDirty; } } private string DebuggerDisplay { get { return string.Format(CultureInfo.InvariantCulture, "+{0} ~{1} -{2} | +{3} ~{4} -{5} | i{6}", Added.Count(), Staged.Count(), Removed.Count(), Untracked.Count(), Modified.Count(), Missing.Count(), Ignored.Count()); } } } }
36.946588
143
0.553128
[ "MIT" ]
7b3cbaf1/GTA
LibGit2Sharp/RepositoryStatus.cs
12,453
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace spa2.Models { // Models returned by MeController actions. public class GetViewModel { public string Hometown { get; set; } } }
21.25
47
0.717647
[ "Apache-2.0" ]
gawelczyk/SpaTests
spa2/Models/MeViewModels.cs
257
C#
using System; using AssetStudio; using JetBrains.Annotations; namespace Imas.Data.Serialized.Sway { public sealed class SwayBone : SwayBase { internal SwayBone() { Colliders = Array.Empty<SwayCollider>(); } public float Radius { get; internal set; } public ColliderType Type { get; internal set; } public bool IsSkirt { get; internal set; } public bool HitMuteForce { get; internal set; } public float HitMuteRate { get; internal set; } public bool IsZConstraint { get; internal set; } public bool HasAngleLimit { get; internal set; } public bool UseBindingDirection { get; internal set; } /// <summary> /// Angle in degrees. /// </summary> public float MinYAngle { get; internal set; } /// <summary> /// Angle in degrees. /// </summary> public float MaxYAngle { get; internal set; } /// <summary> /// Angle in degrees. /// </summary> public float MinZAngle { get; internal set; } /// <summary> /// Angle in degrees. /// </summary> public float MaxZAngle { get; internal set; } public float FollowForce { get; internal set; } public RefParam RefParam { get; internal set; } public float StiffnessForce { get; internal set; } public float DragForce { get; internal set; } public bool HitTwice { get; internal set; } public bool UseLinkHit { get; internal set; } public Vector3 Gravity { get; internal set; } public Vector3 ColliderOffset { get; internal set; } public float SideSpringTolerance { get; internal set; } public float SideSpringForce { get; internal set; } public float SideAntiSpringTolerance { get; internal set; } public float SideAntiSpringForce { get; internal set; } public float AntiFoldForceK { get; internal set; } public float AntiFoldAngle { get; internal set; } [NotNull, ItemNotNull] public SwayCollider[] Colliders { get; internal set; } [CanBeNull] public SwayBone SideLink { get; internal set; } public override string ToString() { return $"SwayBone \"{Path}\""; } [CanBeNull, ItemNotNull] internal string[] ColliderPaths { get; set; } [CanBeNull] internal string SideLinkPath { get; set; } } }
26.478723
67
0.595018
[ "BSD-3-Clause-Clear" ]
765Pro-Hoshimi/MLTDTools
src/Imas.Data.Serialized/Sway/SwayBone.cs
2,491
C#
// GE Common Assets 1.0 // Free asssets for using in many packages of Gold Experience Team. // // Developer: Gold Experience Team (https://www.assetstore.unity3d.com/en/#!/search/page=1/sortby=popularity/query=publisher:4162) // Support: geteamdev@gmail.com // // Please direct any bugs/comments/suggestions to geteamdev@gmail.com. #region Namespaces using UnityEngine; using UnityEngine.UI; using System.Collections; #endregion // Namespaces // ###################################################################### // GE_OrbitCamera class // Handles mouse and touch inputs for orbiting the camera around the target object. // ###################################################################### public class GE_OrbitCamera : MonoBehaviour { // ######################################## // Variables // ######################################## #region Variables public Transform m_Target; // Distance private float m_Distance = 10.0f; public float m_MinDistance = 5.0f; public float m_MaxDistance = 25.0f; // Orbit speed public float m_XSpeed = 250.0f; public float m_YSpeed = 120.0f; // Zoom speed public float m_ZoomSpeed = 5.0f; // Orbit inversion public bool m_XInvert = false; public bool m_YInvert = false; // Zoom inversion public bool m_ZoomInvert = false; // y angle limit public float m_YMinLimit = -20f; public float m_YMaxLimit = 70f; // Angles private float m_X = 0.0f; private float m_Y = 0.0f; // Orbit Sensitivity private float m_OrbitSpeedDelayTime = 0.0f; public float m_OrbitSpeedMultiplier = 2.0f; // Two fingers touch zoom private Vector2 m_CurrTouch1 = Vector2.zero; private Vector2 m_LastTouch1 = Vector2.zero; private Vector2 m_CurrTouch2 = Vector2.zero; private Vector2 m_LastTouch2 = Vector2.zero; private float m_CurrDist = 0.0f; private float m_LastDist = 0.0f; public enum ZoomMethod { PinchZoom = 1, SlideZoom = 2 } public ZoomMethod m_ZoomMethod = ZoomMethod.PinchZoom; #endregion // Variables // ######################################## // MonoBehaviour Functions // http://docs.unity3d.com/ScriptReference/MonoBehaviour.html // ######################################## #region MonoBehaviour // Start is called on the frame when a script is enabled just before any of the Update methods is called the first time. // http://docs.unity3d.com/ScriptReference/MonoBehaviour.Start.html void Start() { this.gameObject.transform.LookAt(m_Target); var angles = transform.eulerAngles; m_X = angles.y; m_Y = angles.x; // Check Min and Max distance. if (m_MaxDistance < m_MinDistance) m_MaxDistance = m_MinDistance + 1; if (m_MinDistance > m_MaxDistance) m_MinDistance = m_MaxDistance + 1; // Set start position according to distance bool ShouldUpdateZoom = false; m_Distance = Vector3.Distance(this.transform.position, m_Target.transform.position); if (m_Distance < m_MinDistance) { m_Distance = m_MinDistance; ShouldUpdateZoom = true; } else if (m_Distance > m_MaxDistance) { m_Distance = m_MaxDistance; ShouldUpdateZoom = true; } if (ShouldUpdateZoom == true) { UpdatePosition(); } // Make the rigid body not change rotation if (GetComponent<Rigidbody>()) GetComponent<Rigidbody>().freezeRotation = true; } // Update is called every frame, if the MonoBehaviour is enabled. // http://docs.unity3d.com/ScriptReference/MonoBehaviour.Update.html void Update() { if (m_Target) { bool ShouldUpdateZoom = false; bool ShouldUpdateOrbit = false; //////////////////////////////////////////////// // ZOOM //////////////////////////////////////////////// // Touch or mouse flag for zoom bool ZoomedbyTouch = false; if (Input.touchCount == 2) { // Use two fingers to pinch zoom if (m_ZoomMethod == ZoomMethod.PinchZoom) { if (Input.touchCount == 2) { ZoomedbyTouch = true; ShouldUpdateZoom = true; for (int i = 0; i < Input.touchCount; i++) { Touch touch = Input.GetTouch(i); // Touch moved if (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary) { if (i == 0) { m_CurrTouch1 = touch.position; m_LastTouch1 = m_CurrTouch1 - touch.deltaPosition; } else { m_CurrTouch2 = touch.position; m_LastTouch2 = m_CurrTouch2 - touch.deltaPosition; } } } m_CurrDist = Vector2.Distance(m_CurrTouch1, m_CurrTouch2); m_LastDist = Vector2.Distance(m_LastTouch1, m_LastTouch2); // Calculate the zoom magnitude float delta = m_LastDist - m_CurrDist; // Invert zoom if (m_ZoomInvert == true) delta *= -1; m_Distance += delta * m_ZoomSpeed * 0.01f; if (m_Distance < m_MinDistance) { m_Distance = m_MinDistance; } else if (m_Distance > m_MaxDistance) { m_Distance = m_MaxDistance; } } // reset touch else if (Input.touchCount < 2) { m_CurrDist = 0.0f; m_LastDist = 0.0f; } } // Use two fingers slide up/down to zoom else if (m_ZoomMethod == ZoomMethod.SlideZoom) { if (Input.touchCount == 2) { ZoomedbyTouch = true; ShouldUpdateZoom = true; for (int i = 0; i < Input.touchCount; i++) { Touch touch = Input.GetTouch(i); // Touch moved if (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary) { if (i == 0) { m_CurrTouch1 = touch.position; m_LastTouch1 = m_CurrTouch1 - touch.deltaPosition; } else { m_CurrTouch2 = touch.position; m_LastTouch2 = m_CurrTouch2 - touch.deltaPosition; } } } // Calculate the zoom magnitude float PinchZoomFactor = Vector2.Distance(m_LastTouch1, m_LastTouch2) - Vector2.Distance(m_CurrTouch1, m_CurrTouch2); if (PinchZoomFactor > -2.0f && PinchZoomFactor < 2.0f) { ZoomedbyTouch = true; ShouldUpdateZoom = true; m_CurrDist = (m_CurrTouch1.y + m_CurrTouch2.y) / 2.0f; m_LastDist = (m_LastTouch1.y + m_LastTouch2.y) / 2.0f; //Calculate the zoom magnitude float delta = m_LastDist - m_CurrDist; // Invert zoom if (m_ZoomInvert == true) delta *= -1; m_Distance += delta * m_ZoomSpeed * 0.01f; if (m_Distance < m_MinDistance) { m_Distance = m_MinDistance; } else if (m_Distance > m_MaxDistance) { m_Distance = m_MaxDistance; } } } // reset touch else if (Input.touchCount < 2) { m_CurrDist = 0.0f; m_LastDist = 0.0f; } } } float deadZone = 0.01f; // Zoom by mouse if (ZoomedbyTouch == false) { if (Input.GetAxis("Mouse ScrollWheel") < -deadZone || Input.GetAxis("Mouse ScrollWheel") > deadZone) { ShouldUpdateZoom = true; float delta = Input.GetAxis("Mouse ScrollWheel"); // Invert zoom if (m_ZoomInvert == true) delta *= -1; m_Distance -= delta * m_ZoomSpeed; if (m_Distance < m_MinDistance) { m_Distance = m_MinDistance; } else if (m_Distance > m_MaxDistance) { m_Distance = m_MaxDistance; } } } //////////////////////////////////////////////// // ORBIT //////////////////////////////////////////////// // Touch or mouse flag for orbit bool OrbitByTouch = false; // Orbit by touch if (Input.touchCount == 1) { OrbitByTouch = true; // Get touch Touch touch = Input.GetTouch(0); // Touch began if (touch.phase == TouchPhase.Began) { m_OrbitSpeedDelayTime = 0.0f; } // Touch ended or canceld else if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled) { m_OrbitSpeedDelayTime = 0.0f; } // Touch moved else if (touch.phase == TouchPhase.Moved) { ShouldUpdateOrbit = true; float TouchDeltaX = touch.deltaPosition.x; float TouchDeltaY = touch.deltaPosition.y; // Invert X and Y axis if (m_XInvert) TouchDeltaX *= -1; if (m_YInvert) TouchDeltaY *= -1; m_X += touch.deltaPosition.x * m_XSpeed * 0.005f * m_OrbitSpeedDelayTime; m_Y -= touch.deltaPosition.y * m_YSpeed * 0.005f * m_OrbitSpeedDelayTime; } } // Orbit by mouse if (OrbitByTouch == false) { // Reset orbit speed when left mouse down if (Input.GetMouseButtonDown(0)) { m_OrbitSpeedDelayTime = 0.0f; } else if (Input.GetMouseButtonUp(0)) { m_OrbitSpeedDelayTime = 0.0f; } if (Input.GetMouseButton(0)) { ShouldUpdateOrbit = true; float MouseAxisX = Input.GetAxis("Mouse X"); float MouseAxisY = Input.GetAxis("Mouse Y"); // Invert X and Y axis if (m_XInvert) MouseAxisX *= -1; if (m_YInvert) MouseAxisY *= -1; m_X += MouseAxisX * m_XSpeed * 0.02f * m_OrbitSpeedDelayTime; m_Y -= MouseAxisY * m_YSpeed * 0.02f * m_OrbitSpeedDelayTime; } } //////////////////////////////////////////////// // UPDATE POSITON //////////////////////////////////////////////// if (ShouldUpdateZoom || ShouldUpdateOrbit) { UpdatePosition(); } } } #endregion // MonoBehaviour // ######################################## // Utilities functions // ######################################## #region Utilities // Update camera position void UpdatePosition() { m_OrbitSpeedDelayTime += Time.deltaTime * m_OrbitSpeedMultiplier; if (m_OrbitSpeedDelayTime > 1.0f) m_OrbitSpeedDelayTime = 1.0f; m_Y = ClampAngle(m_Y, m_YMinLimit, m_YMaxLimit); Quaternion rotation = Quaternion.Euler(m_Y, m_X, 0); Vector3 direction = new Vector3(0.0f, 0.0f, -m_Distance); Vector3 position = (rotation * direction) + m_Target.position; transform.rotation = rotation; transform.position = position; } // Clamp angle around 0 to 360 degree static float ClampAngle(float angle, float min, float max) { if (angle < -360) angle += 360; if (angle > 360) angle -= 360; return Mathf.Clamp(angle, min, max); } // Set zooming method public void SetZoomMethod(ZoomMethod zoomMethod) { m_ZoomMethod = zoomMethod; } #endregion Utilities }
25.42217
133
0.573244
[ "MIT" ]
DennisTDev/HackPrinceton
Assets/GE Common Assets/GE Orbit Camera/Scripts/GE_OrbitCamera.cs
10,781
C#
using System.Windows.Controls; namespace Examples.Conventions.Implementations.TabControlConventions { public partial class FirstTabView : UserControl { public FirstTabView() { InitializeComponent(); } } }
16.846154
68
0.767123
[ "MIT" ]
mahizsas/Caliburn.Micro.Telerik
Silverlight/Examples.Conventions/Implementations/TabControlConventions/FirstTabView.xaml.cs
221
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FIreWeapon : MonoBehaviour { [SerializeField] Camera cameraController; private void Update() { if (Input.GetKeyDown(KeyCode.Mouse0)) { Shoot(); } } //fire the weapon using a raycast. void Shoot() { //calculate direction to shoot the ray //cast a debug ray //do the raycast detection Vector3 rayDirection = cameraController.transform.forward; } }
21.074074
67
0.59754
[ "MIT" ]
dzc170030/FPS_Project_02
Assets/Scripts/FIreWeapon.cs
571
C#
using System; class JoroTheFootballPlayer { static void Main() { string leap = Console.ReadLine(); int hollidaysCount = int.Parse(Console.ReadLine()); int weekendsHomeCount = int.Parse(Console.ReadLine()); int weekendsInYear = 52; int normalWeekendsCount = weekendsInYear - weekendsHomeCount; double gamesCount = normalWeekendsCount * 2d / 3d + weekendsHomeCount * 1d + hollidaysCount / 2d; if (leap == "t") { gamesCount = gamesCount + 3; } Console.WriteLine((int)gamesCount); } }
26
69
0.580128
[ "Apache-2.0" ]
genadi60/SoftUni
SoftUni_Exam/C# Basics Exam 10 April 2014 Morning/Problem01-Joro-The-Football-Player/01.JoroTheFootballPlayer-Solution.cs
626
C#
using AppKit; namespace VolleMoehre.App.macOS { internal static class MainClass { static void Main(string[] args) { NSApplication.Init(); NSApplication.SharedApplication.Delegate = new App(); NSApplication.Main(args); } } }
18.6875
65
0.578595
[ "MIT" ]
TopperDEL/VolleMoehre
VolleMoehre.App/VolleMoehre.App.Mobile/MacOS/Main.cs
301
C#
using System; using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace EnemyMods.NPCs { public class iNPC : NPCInfo { public int specialTimer = 0; public int timerAI = 0; public int timerSuffix = 0; public int countSuffix = 0; public int lives; public int debuffTimer = 0; public int debuffTimer2 = 0; public string prefixes = ""; public string suffixes = ""; public bool rangedResist, meleeResist, magicResist, minionResist; public int rangedResistTimer, meleeResistTimer, magicResistTimer, minionResistTimer = 0; public int postMoonTimer = 0; public int postMoonCount = 0; public bool nameConfirmed = false; } }
29.961538
97
0.627728
[ "MIT" ]
Hiccup251/Prefixes-for-Enemies
NPCs/iNPC.cs
781
C#
using Moq; using NUnit.Framework; namespace Xenon.Tests.ClickTests { [TestFixture] public class XenonScreenClickTests : BaseClickTests<DummyXenonScreen> { protected override BaseXenonTest<DummyXenonScreen> CreateInstance( Mock<IXenonBrowser> browser ) { return new DummyXenonScreen( browser.Object ); } } }
22.857143
98
0.784375
[ "MIT" ]
LiquidThinking/Xenon
Xenon.Tests/ClickTests/XenonScreenClickTests.cs
320
C#
//****************************************************************************************************** // Settings.cs - Gbtc // // Copyright © 2017, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this // file except in compliance with the License. You may obtain a copy of the License at: // // http://opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 04/21/2017 - J. Ritchie Carroll // Generated original version of source code. // //****************************************************************************************************** using System; using System.ComponentModel; using System.Configuration; using ExpressionEvaluator; using GSF.ComponentModel; using GSF.Configuration; namespace GEPDataExtractor { /// <summary> /// Defines settings for the DataExtractor application. /// </summary> /// <remarks> /// <para> /// Default value expressions in this class reference the primary form instance, as a result, /// instances of this class should only be created from the primary UI thread or otherwise /// use <see cref="System.Windows.Forms.Form.Invoke(Delegate)"/>. /// </para> /// <para> /// In order for properties of this class decorated with <see cref="TypeConvertedValueExpressionAttribute"/> /// to have access to form element values, the elements should be declared with "public" access. /// </para> /// </remarks> public sealed class Settings : CategorizedSettingsBase<Settings> { /// <summary> /// Creates a new <see cref="Settings"/> instance. /// </summary> /// <param name="typeRegistry"> /// Type registry to use when parsing <see cref="TypeConvertedValueExpressionAttribute"/> instances, /// or <c>null</c> to use <see cref="ValueExpressionParser.DefaultTypeRegistry"/>. /// </param> public Settings(TypeRegistry typeRegistry) : base("systemSettings", typeRegistry) { } /// <summary> /// Gets or sets host address for historian connection. /// </summary> [TypeConvertedValueExpression("Form.textBoxHistorianHostAddress.Text")] [Description("Host address for historian connection.")] [UserScopedSetting] public string HostAddress { get; set; } /// <summary> /// Gets or sets port for historian GEP connection. /// </summary> [TypeConvertedValueExpression("Form.maskedTextBoxHistorianPort.Text")] [Description("Meta-data port for historian connection.")] [UserScopedSetting] public int Port { get; set; } /// <summary> /// Gets or sets name of historian instance to access. /// </summary> [TypeConvertedValueExpression("Form.textBoxHistorianInstanceName.Text")] [Description("Name of historian instance to access.")] [UserScopedSetting] public string InstanceName { get; set; } /// <summary> /// Gets or sets frame-rate, in frames per second, used to estimate total data for timespan. /// </summary> [TypeConvertedValueExpression("Form.maskedTextBoxFrameRate.Text")] [Description("Frame rate, in frames per second, used to estimate total data for timespan.")] [UserScopedSetting] public int FrameRate { get; set; } /// <summary> /// Gets or sets meta-data retriever timeout, in milliseconds. /// </summary> [UserScopedSetting] [Description("Meta-data retriever timeout, in milliseconds.")] public int MetadataTimeout { get; set; } /// <summary> /// Gets or sets meta-data retriever timeout, in seconds. /// </summary> [TypeConvertedValueExpression("Form.maskedTextBoxMetadataTimeout.Text")] [SerializeSetting(false)] // <-- Do not synchronize to config file public int MetadataTimeoutSeconds { get => MetadataTimeout / 1000; set => MetadataTimeout = value * 1000; } /// <summary> /// Gets or sets selected start time range for historian read. /// </summary> [TypeConvertedValueExpression("Form.dateTimePickerSourceTime.Value")] [Description("Selected start time range for historian read.")] [UserScopedSetting] public DateTime StartTime { get; set; } /// <summary> /// Gets or sets selected end time range for historian read. /// </summary> [TypeConvertedValueExpression("Form.dateTimePickerEndTime.Value")] [Description("Selected end time range for historian read.")] [UserScopedSetting] public DateTime EndTime { get; set; } /// <summary> /// Gets or sets device filter. /// </summary> [TypeConvertedValueExpression("Form.textBoxDeviceFilter.Text")] [Description("Device LIKE filter expression.")] [UserScopedSetting] public string DeviceFilter { get; set; } /// <summary> /// Gets or sets phase filter. /// </summary> [TypeConvertedValueExpression("Form.textBoxPhaseFilter.Text")] [Description("Phase IN filter expression.")] [UserScopedSetting] public string PhaseFilter { get; set; } /// <summary> /// Gets or sets filter expression used for historian read. /// </summary> [TypeConvertedValueExpression("Form.textBoxFilterExpression.Text")] [SerializeSetting(false)] // <-- Do not synchronize to config file public string FilterExpression { get; set; } /// <summary> /// Gets or sets export file name. /// </summary> [TypeConvertedValueExpression("Form.textBoxExportFileName.Text")] [SerializeSetting(false)] // <-- Do not synchronize to config file public string ExportFileName { get; set; } /// <summary> /// Gets or sets message display interval. /// </summary> [TypeConvertedValueExpression("Form.maskedTextBoxMessageInterval.Text")] [Description("Message display interval.")] [UserScopedSetting] public int MessageInterval { get; set; } /// <summary> /// Gets or sets data read interval, in seconds. /// </summary> [TypeConvertedValueExpression("Form.maskedTextBoxReadInterval.Text")] [Description("Data read interval.")] [UserScopedSetting] public int ReadInterval { get; set; } /// <summary> /// Gets or sets flag that controls if exports will align timestamps within frame-rate estimate. /// </summary> [TypeConvertedValueExpression("Form.checkBoxAlignTimestamps.Checked")] [Description("Flag that controls if the signal to noise algorithm is processed.")] [UserScopedSetting] public bool AlignTimestamps { get; set; } /// <summary> /// Gets or sets flag that controls if exports will include missing values as NaN. /// </summary> [TypeConvertedValueExpression("Form.checkBoxExportMissingAsNaN.Checked")] [Description("Flag that controls if the unbalance algorithm is processed.")] [UserScopedSetting] public bool ExportMissingAsNaN { get; set; } /// <summary> /// Gets or sets flag that controls if exports will fill-in missing timestamps. /// </summary> [TypeConvertedValueExpression("Form.checkBoxFillInMissingTimestamps.Checked")] [Description("Flag that controls if the unbalance algorithm is processed.")] [UserScopedSetting] public bool FillInMissingTimestamps { get; set; } /// <summary> /// Gets or sets flag that controls if one export file should be created per data type. /// </summary> [TypeConvertedValueExpression("Form.checkBoxExportFilePerDataType.Checked")] [Description("Flag that controls if one export file should be created per data type.")] [UserScopedSetting] public bool ExportFilePerDataType { get; set; } /// <summary> /// Gets or sets value that determines the acceptable amount of bad data for export. /// </summary> [TypeConvertedValueExpression("Form.maskedTextBoxAcceptableBadData.Text")] [Description("Value that determines the acceptable amount of bad data for export.")] [UserScopedSetting] public int AcceptableBadData { get; set; } /// <summary> /// Gets or sets value that determines the acceptable amount of bad time for export. /// </summary> [TypeConvertedValueExpression("Form.maskedTextBoxAcceptableBadTime.Text")] [Description("Value that determines the acceptable amount of bad time for export.")] [UserScopedSetting] public int AcceptableBadTime { get; set; } /// <summary> /// Gets or sets value that determines the acceptable amount of missing data for export. /// </summary> [TypeConvertedValueExpression("Form.maskedTextBoxAcceptableMissingData.Text")] [Description("Value that determines the acceptable amount of missing data for export.")] [UserScopedSetting] public int AcceptableMissingData { get; set; } } }
43.641921
112
0.630378
[ "MIT" ]
GridProtectionAlliance/gsf
Source/Tools/GEPDataExtractor/Settings.cs
9,997
C#
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Xml; using ICSharpCode.Decompiler.CSharp.Syntax; using ICSharpCode.Decompiler.Documentation; using ICSharpCode.Decompiler.TypeSystem; namespace ICSharpCode.Decompiler.CSharp.Transforms { /// <summary> /// Adds XML documentation for member definitions. /// </summary> public class AddXmlDocumentationTransform : IAstTransform { public void Run(AstNode rootNode, TransformContext context) { if (!context.Settings.ShowXmlDocumentation || context.DecompileRun.DocumentationProvider == null) return; try { var provider = context.DecompileRun.DocumentationProvider; foreach (var entityDecl in rootNode.DescendantsAndSelf.OfType<EntityDeclaration>()) { if (!(entityDecl.GetSymbol() is IEntity entity)) continue; string doc = provider.GetDocumentation(entity); if (doc != null) { InsertXmlDocumentation(entityDecl, new StringReader(doc)); } } } catch (XmlException ex) { string[] msg = (" Exception while reading XmlDoc: " + ex).Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); var insertionPoint = rootNode.FirstChild; for (int i = 0; i < msg.Length; i++) rootNode.InsertChildBefore(insertionPoint, new Comment(msg[i], CommentType.Documentation), Roles.Comment); } } static void InsertXmlDocumentation(AstNode node, StringReader r) { // Find the first non-empty line: string firstLine; do { firstLine = r.ReadLine(); if (firstLine == null) return; } while (string.IsNullOrWhiteSpace(firstLine)); string indentation = firstLine.Substring(0, firstLine.Length - firstLine.TrimStart().Length); string line = firstLine; int skippedWhitespaceLines = 0; // Copy all lines from input to output, except for empty lines at the end. while (line != null) { if (string.IsNullOrWhiteSpace(line)) { skippedWhitespaceLines++; } else { while (skippedWhitespaceLines > 0) { Comment emptyLine = new Comment(string.Empty, CommentType.Documentation); emptyLine.AddAnnotation(node.GetResolveResult()); node.Parent.InsertChildBefore(node, emptyLine, Roles.Comment); skippedWhitespaceLines--; } if (line.StartsWith(indentation, StringComparison.Ordinal)) line = line.Substring(indentation.Length); Comment comment = new Comment(" " + line, CommentType.Documentation); comment.AddAnnotation(node.GetResolveResult()); node.Parent.InsertChildBefore(node, comment, Roles.Comment); } line = r.ReadLine(); } } } }
41.252747
129
0.729355
[ "MIT" ]
164306530/ILSpy
ICSharpCode.Decompiler/CSharp/Transforms/AddXmlDocumentationTransform.cs
3,756
C#
using InformationService.DataModels; using InformationService.Interfaces; using Moq; using NotificationService.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using InformationService.Models; using InformationService.Repositories; using InterfaceModels; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using NotificationService.Repositories; using TrainingNotificationWorker; using Xunit; namespace TrainingNotificationWorkerTest { public class TextWorkerTest { private List<List<SportEmails>> _phoneList; private Mock<ITrainingRepository> _mockTrainingRepository; private Mock<ISmsRepository> _mockSmsRepository; private TextWorker _worker; public TextWorkerTest() { _mockTrainingRepository = new Mock<ITrainingRepository>(); _mockSmsRepository = new Mock<ISmsRepository>(); _worker = new TextWorker(_mockTrainingRepository.Object, _mockSmsRepository.Object); } private void LoadPhones() { _phoneList = new List<List<SportEmails>>(); List<SportEmails> emails1 = new List<SportEmails>(); emails1.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", IsVolunteer = true }); emails1.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212___", LastName = "Wayne", NickName = "Batman", Selected = true }); emails1.Add(new SportEmails { FirstName = "Bruce", Email = "(703) 555-1212", LastName = "Wayne", NickName = "Batman" }); emails1.Add(new SportEmails { FirstName = "Bruce", Email = "703-555-1212", LastName = "Wayne", NickName = "Batman" }); emails1.Add(new SportEmails { FirstName = "Bruce", Email = "703_555_1212", LastName = "Wayne", NickName = "Batman" }); _phoneList.Add(emails1); List<SportEmails> emails2 = new List<SportEmails>(); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 1, SportTypeId = 1, IsVolunteer = true }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 1, SportTypeId = 1, Selected = true }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 1, SportTypeId = 1 }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 1, SportTypeId = 1 }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 1, SportTypeId = 1 }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 2, SportTypeId = 1, IsVolunteer = true }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 2, SportTypeId = 1, Selected = true }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 2, SportTypeId = 1 }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 2, SportTypeId = 1 }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 2, SportTypeId = 2, TeamId = 1, IsVolunteer = true }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 2, SportTypeId = 2, TeamId = 1, IsVolunteer = true }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 2, SportTypeId = 2, TeamId = 1, Selected = true }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 2, SportTypeId = 2, TeamId = 1, Selected = true }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 2, SportTypeId = 2, TeamId = 1, Selected = true }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 2, SportTypeId = 2, TeamId = 1, Selected = true }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 2, SportTypeId = 2, TeamId = 1, Selected = true }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 2, SportTypeId = 2, TeamId = 2, IsVolunteer = true }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 2, SportTypeId = 2, TeamId = 2 }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 2, SportTypeId = 2, TeamId = 2 }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 2, SportTypeId = 2, TeamId = 2 }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 2, SportTypeId = 2, TeamId = 2 }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 2, SportTypeId = 2, TeamId = 2 }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 3, SportTypeId = 1, IsVolunteer = true }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 3, SportTypeId = 1 }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 3, SportTypeId = 1 }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 3, SportTypeId = 1 }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 3, SportTypeId = 2, TeamId = 3, IsVolunteer = true }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 3, SportTypeId = 2, TeamId = 3, IsVolunteer = true }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 3, SportTypeId = 2, TeamId = 3, Selected = true }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 3, SportTypeId = 2, TeamId = 3, Selected = true }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 3, SportTypeId = 2, TeamId = 3, Selected = true }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 3, SportTypeId = 2, TeamId = 3, Selected = true }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 3, SportTypeId = 2, TeamId = 3, Selected = true }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 3, SportTypeId = 3, TeamId = 4, IsVolunteer = true }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 3, SportTypeId = 3, TeamId = 4 }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 3, SportTypeId = 3, TeamId = 4 }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 3, SportTypeId = 3, TeamId = 4 }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 3, SportTypeId = 3, TeamId = 4 }); emails2.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 3, SportTypeId = 3, TeamId = 4 }); _phoneList.Add(emails2); List<SportEmails> emails3 = new List<SportEmails>(); emails3.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 3, SportTypeId = 3, IsVolunteer = true }); emails3.Add(new SportEmails { FirstName = "Bruce", Email = "3015551212", LastName = "Wayne", NickName = "Batman", ProgramId = 3, SportTypeId = 3, Selected = true }); emails3.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 3, SportTypeId = 3 }); emails3.Add(new SportEmails { FirstName = "Bruce", Email = "2025551212", LastName = "Wayne", NickName = "Batman", ProgramId = 3, SportTypeId = 3 }); emails3.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 3, SportTypeId = 3 }); emails3.Add(new SportEmails { FirstName = "Bruce", Email = "2125551212", LastName = "Wayne", NickName = "Batman", ProgramId = 4, SportTypeId = 3, IsVolunteer = true }); emails3.Add(new SportEmails { FirstName = "Bruce", Email = "5715551212", LastName = "Wayne", NickName = "Batman", ProgramId = 4, SportTypeId = 3, Selected = true }); emails3.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 4, SportTypeId = 3 }); emails3.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 4, SportTypeId = 3 }); emails3.Add(new SportEmails { FirstName = "Bruce", Email = "7185551212", LastName = "Wayne", NickName = "Batman", ProgramId = 4, SportTypeId = 4, TeamId = 5, IsVolunteer = true }); emails3.Add(new SportEmails { FirstName = "Bruce", Email = "2015551212", LastName = "Wayne", NickName = "Batman", ProgramId = 4, SportTypeId = 4, TeamId = 5, IsVolunteer = true }); emails3.Add(new SportEmails { FirstName = "Bruce", Email = "3105551212", LastName = "Wayne", NickName = "Batman", ProgramId = 4, SportTypeId = 4, TeamId = 5, Selected = true }); emails3.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 4, SportTypeId = 4, TeamId = 5, Selected = true }); emails3.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 4, SportTypeId = 4, TeamId = 5, Selected = true }); emails3.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 4, SportTypeId = 4, TeamId = 5, Selected = true }); emails3.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 4, SportTypeId = 4, TeamId = 5, Selected = true }); emails3.Add(new SportEmails { FirstName = "Bruce", Email = "2135551212", LastName = "Wayne", NickName = "Batman", ProgramId = 4, SportTypeId = 4, TeamId = 6, IsVolunteer = true }); emails3.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 4, SportTypeId = 4, TeamId = 6 }); emails3.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 4, SportTypeId = 4, TeamId = 6 }); emails3.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 4, SportTypeId = 4, TeamId = 6 }); emails3.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 4, SportTypeId = 4, TeamId = 6 }); emails3.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 4, SportTypeId = 4, TeamId = 6 }); _phoneList.Add(emails3); List<SportEmails> emails4 = new List<SportEmails>(); emails4.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 5, SportTypeId = 5 }); emails4.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 5, SportTypeId = 5 }); emails4.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 5, SportTypeId = 5 }); emails4.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 5, SportTypeId = 6, TeamId = 7, IsVolunteer = true }); emails4.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 5, SportTypeId = 6, TeamId = 7, IsVolunteer = true }); emails4.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 5, SportTypeId = 6, TeamId = 7, Selected = true }); emails4.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 5, SportTypeId = 6, TeamId = 7, Selected = true }); emails4.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 5, SportTypeId = 6, TeamId = 7, Selected = true }); emails4.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 5, SportTypeId = 6, TeamId = 7, Selected = true }); emails4.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 5, SportTypeId = 6, TeamId = 7, Selected = true }); emails4.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 5, SportTypeId = 7, TeamId = 8, IsVolunteer = true }); emails4.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 5, SportTypeId = 7, TeamId = 8 }); emails4.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 5, SportTypeId = 7, TeamId = 8 }); emails4.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 5, SportTypeId = 7, TeamId = 8 }); emails4.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 5, SportTypeId = 7, TeamId = 8 }); emails4.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 5, SportTypeId = 7, TeamId = 8 }); _phoneList.Add(emails4); List<SportEmails> emails5 = new List<SportEmails>(); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 6, SportTypeId = 8, IsVolunteer = true }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 6, SportTypeId = 8, Selected = true }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 6, SportTypeId = 8 }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 6, SportTypeId = 8 }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 6, SportTypeId = 8 }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 7, SportTypeId = 8, IsVolunteer = true }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 7, SportTypeId = 8, Selected = true }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 7, SportTypeId = 8 }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 7, SportTypeId = 8 }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 7, SportTypeId = 8, TeamId = 9, IsVolunteer = true }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 7, SportTypeId = 8, TeamId = 9, IsVolunteer = true }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 7, SportTypeId = 8, TeamId = 9, Selected = true }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 7, SportTypeId = 8, TeamId = 9, Selected = true }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 7, SportTypeId = 8, TeamId = 9, Selected = true }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 7, SportTypeId = 8, TeamId = 9, Selected = true }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 7, SportTypeId = 8, TeamId = 9, Selected = true }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 7, SportTypeId = 8, TeamId = 9, IsVolunteer = true }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 7, SportTypeId = 8, TeamId = 9 }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 7, SportTypeId = 8, TeamId = 9 }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 7, SportTypeId = 8, TeamId = 9 }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 7, SportTypeId = 8, TeamId = 9 }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 7, SportTypeId = 8, TeamId = 9 }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 8, SportTypeId = 8, IsVolunteer = true }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 8, SportTypeId = 8 }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 8, SportTypeId = 8 }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 8, SportTypeId = 8 }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 8, SportTypeId = 8, TeamId = 10, IsVolunteer = true }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 8, SportTypeId = 8, TeamId = 10, IsVolunteer = true }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 8, SportTypeId = 8, TeamId = 10, Selected = true }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 8, SportTypeId = 8, TeamId = 10, Selected = true }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 8, SportTypeId = 8, TeamId = 10, Selected = true }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 8, SportTypeId = 8, TeamId = 10, Selected = true }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 8, SportTypeId = 8, TeamId = 10, Selected = true }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 8, SportTypeId = 8, TeamId = 11, IsVolunteer = true }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 8, SportTypeId = 8, TeamId = 11 }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 8, SportTypeId = 8, TeamId = 11 }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 8, SportTypeId = 8, TeamId = 11 }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 8, SportTypeId = 8, TeamId = 11 }); emails5.Add(new SportEmails { FirstName = "Bruce", Email = "7035551212", LastName = "Wayne", NickName = "Batman", ProgramId = 8, SportTypeId = 8, TeamId = 11 }); _phoneList.Add(emails5); } [Theory] [InlineData(1, 5)] [InlineData(2, 39)] [InlineData(3, 22)] [InlineData(4, 16)] [InlineData(5, 39)] public void GetPhonesForSport_When_executed_create_list_of_SportEmails(int sportId, int expected) { LoadPhones(); _mockTrainingRepository.Setup(repository => repository.GetPhonesBySport(sportId)).ReturnsAsync(_phoneList[sportId - 1]); var actual = _worker.GetPhonesForSport(sportId); Assert.Equal(expected, actual.Result.Count); } [Theory] [InlineData(1, 1)] public void RemoveDuplicatePhones_When_executed_create_list_of_Phones_with_no_dups(int sportId, int expected) { LoadPhones(); var phone = _phoneList[sportId - 1]; List<string> actual = _worker.RemoveDuplicatePhones(phone); Assert.Equal(expected, actual.Count); } [Theory] [InlineData(1, 5)] public void SendSms_When_executed_x_emails_sent(int sportId, int expected) { LoadPhones(); var phone = _phoneList[sportId - 1]; var phoneList = phone.Select(e => e.Email).ToList(); const string message = "text test with C#"; _worker.SendSmsAsync(phoneList, message); _mockSmsRepository.Verify(mock => mock.SendSms(It.IsAny<string>(), message), Times.Exactly(expected)); } [Theory] [InlineData(1, null, null, null, null, null, 1)] [InlineData(3, null, null, null, null, true, 5)] [InlineData(3, null, null, null, true, null, 8)] [InlineData(3, 3, null, null, null, null, 3)] [InlineData(3, null, 3, null, null, null, 5)] [InlineData(3, null, null, 5, null, null, 4)] [InlineData(3, null, 3, null, true, null, 4)] [InlineData(3, null, 3, null, null, true, 2)] public void SendSmsForSport_When_executed_x_text_sent(int sportId, int? locationId, int? categoryId, int? teamId, bool? selected, bool? volunteerOnly, int expected) { LoadPhones(); _mockTrainingRepository.Setup(repository => repository.GetPhonesBySport(sportId)).ReturnsAsync(_phoneList[sportId - 1]); const string text = "and easy to do anywhere, even with C#"; CoachTextDto message = new CoachTextDto { SportId = sportId, Message = text, IsVolunteer = volunteerOnly, Selected = selected, ProgramId = locationId, SportTypeId = categoryId, TeamId = teamId }; var actual = _worker.SendSmsForSport(message); _mockSmsRepository.Verify(mock => mock.SendSms(It.IsAny<string>(), text), Times.Exactly(expected)); Assert.Equal(expected, actual.Result); } [Theory] [InlineData(6, null, null, null, null, null, 1)] public void SendEmailsForSport_WithoutMock(int sportId, int? locationId, int? categoryId, int? teamId, bool? selected, bool? volunteerOnly, int expected) { IConfiguration config = new ConfigurationBuilder().AddJsonFile("appsettings.test.json").Build(); var connectionString = config["TrainingDatabase"]; var options = new DbContextOptionsBuilder<PwsodbContext>().UseSqlServer(connectionString).Options; PwsodbContext context = new PwsodbContext(options); const string plainTextContent = "testing PWSO sending text messages"; CoachTextDto message = new CoachTextDto { SportId = sportId, Message = plainTextContent, IsVolunteer = volunteerOnly, Selected = selected, ProgramId = locationId, SportTypeId = categoryId, TeamId = teamId }; ITrainingRepository trainingRepository = new TrainingRepository(context); var accountSid = config["AccountSid"]; var authToken = config["AuthToken"]; var fromPhone = config["FromPhone"]; ISmsRepository emailRepository = new SmsRepository(accountSid,authToken, fromPhone); TextWorker worker = new TextWorker(trainingRepository, emailRepository); //var actual = worker.SendSmsForSport(message); //Assert.Equal(expected, actual.Result); } } }
92.734899
193
0.633327
[ "MIT" ]
lvanlowe/SMADTools
CoachesFunctons/TrainingNotificationWorkerTest/TextWorkerTest.cs
27,637
C#
using FluentValidation.Results; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ordering.Application.Exceptions { public class ValidationException: ApplicationException { public ValidationException() : base("One or more validation failures have occurred.") { Errors = new Dictionary<string, string[]>(); } public ValidationException(IEnumerable<ValidationFailure> failures) : this() { Errors = failures .GroupBy(e => e.PropertyName, e => e.ErrorMessage) .ToDictionary(failureGroup => failureGroup.Key, failureGroup => failureGroup.ToArray()); } public IDictionary<string, string[]> Errors { get; } } }
28.482759
104
0.644068
[ "MIT" ]
alfaiz12/AspnetMicroservices
src/Services/Ordering/Ordering.Application/Exceptions/ValidationException.cs
828
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Net.Sockets; using Xunit; namespace Steeltoe.Messaging.Handler.Attributes.Support.Test { public class AttributeExceptionHandlerMethodResolverTest { private AttributeExceptionHandlerMethodResolver resolver = new (typeof(ExceptionController)); [Fact] public void ResolveMethodFromAttribute() { var exception = new IOException(); Assert.Equal("HandleIOException", resolver.ResolveMethod(exception).Name); } [Fact] public void ResolveMethodFromArgument() { var exception = new ArgumentException(); Assert.Equal("HandleArgumentException", resolver.ResolveMethod(exception).Name); } [Fact] public void ResolveMethodExceptionSubType() { IOException ioException = new FileNotFoundException(); Assert.Equal("HandleIOException", resolver.ResolveMethod(ioException).Name); SocketException bindException = new BindException(); Assert.Equal("HandleSocketException", resolver.ResolveMethod(bindException).Name); } [Fact] public void ResolveMethodBestMatch() { var exception = new SocketException(); Assert.Equal("HandleSocketException", resolver.ResolveMethod(exception).Name); } [Fact] public void ResolveMethodNoMatch() { var exception = new Exception(); Assert.Null(resolver.ResolveMethod(exception)); // 1st lookup Assert.Null(resolver.ResolveMethod(exception)); // 2nd lookup from cache } [Fact] public void ResolveMethodInherited() { resolver = new AttributeExceptionHandlerMethodResolver(typeof(InheritedController)); var exception = new IOException(); Assert.Equal("HandleIOException", resolver.ResolveMethod(exception).Name); } [Fact] public void ResolveMethodAgainstCause() { var exception = new AggregateException(new IOException()); Assert.Equal("HandleIOException", resolver.ResolveMethod(exception).Name); } [Fact] public void AmbiguousExceptionMapping() { Assert.Throws<InvalidOperationException>(() => new AttributeExceptionHandlerMethodResolver(typeof(AmbiguousController))); } [Fact] public void NoExceptionMapping() { Assert.Throws<InvalidOperationException>(() => new AttributeExceptionHandlerMethodResolver(typeof(NoExceptionController))); } internal class BindException : SocketException { } internal class ExceptionController { public virtual void Handle() { } [MessageExceptionHandler(typeof(IOException))] public virtual void HandleIOException() { } [MessageExceptionHandler(typeof(SocketException))] public virtual void HandleSocketException() { } [MessageExceptionHandler] public virtual void HandleArgumentException(ArgumentException exception) { } [MessageExceptionHandler] public virtual void HandleInvalidOperationException(InvalidOperationException exception) { } } internal class InheritedController : ExceptionController { public override void HandleIOException() { } } internal class AmbiguousController { public void Handle() { } [MessageExceptionHandler(typeof(BindException), typeof(ArgumentException))] public string Handle1(Exception ex) { return ex.GetType().Name; // ClassUtils.getShortName(ex.getClass()); } [MessageExceptionHandler] public string Handle2(ArgumentException ex) { return ex.GetType().Name; // ClassUtils.getShortName(ex.getClass()); } } internal class NoExceptionController { [MessageExceptionHandler] public void Handle() { } } } }
31.292517
135
0.603478
[ "Apache-2.0" ]
ScriptBox99/Steeltoe
src/Messaging/test/MessagingBase.Test/Handler/Attributes/Support/AttributeExceptionHandlerMethodResolverTest.cs
4,602
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Xml.Schema; using Xunit; using Xunit.Abstractions; namespace System.Xml.Tests { // ===================== Constructor ===================== public class TCConstructor : CXmlSchemaValidatorTestCase { private ITestOutputHelper _output; public TCConstructor(ITestOutputHelper output) : base(output) { _output = output; } [Fact] public void SetXmlNameTableToNull() { XmlSchemaValidator val; try { val = new XmlSchemaValidator( null, new XmlSchemaSet(), new XmlNamespaceManager(new NameTable()), AllFlags ); } catch (ArgumentNullException) { return; } _output.WriteLine("ArgumentNullException was not thrown!"); Assert.True(false); } [Theory] [InlineData("empty")] [InlineData("full")] public void SetXmlNameTableTo_Empty_Full(string nameTableStatus) { XmlSchemaValidator val; ObservedNameTable nt = new ObservedNameTable(); XmlSchemaInfo info = new XmlSchemaInfo(); XmlSchemaSet sch = CreateSchemaSetFromXml("<root />"); if (nameTableStatus == "full") { nt.Add("root"); nt.Add("foo"); nt.IsAddCalled = false; nt.IsGetCalled = false; } val = new XmlSchemaValidator( nt, sch, new XmlNamespaceManager(new NameTable()), AllFlags ); Assert.NotNull(val); val.Initialize(); val.ValidateElement("root", "", info); Assert.True(nt.IsAddCalled); Assert.False(nt.IsGetCalled); return; } [Fact] public void SetSchemaSetToNull() { XmlSchemaValidator val; try { val = new XmlSchemaValidator( new NameTable(), null, new XmlNamespaceManager(new NameTable()), AllFlags ); } catch (ArgumentNullException) { return; } _output.WriteLine("ArgumentNullException was not thrown!"); Assert.True(false); } [Theory] [InlineData("empty")] [InlineData("notcompiled")] [InlineData("compiled")] public void SetSchemaSetTo_Empty_NotCompiled_Compiled(string schemaSetStatus) { XmlSchemaValidator val; XmlSchemaSet sch = new XmlSchemaSet(); if (schemaSetStatus != "empty") { sch.Add("", Path.Combine(TestData, XSDFILE_NO_TARGET_NAMESPACE)); if (schemaSetStatus == "compiled") sch.Compile(); } val = new XmlSchemaValidator( new NameTable(), sch, new XmlNamespaceManager(new NameTable()), AllFlags ); Assert.NotNull(val); val.Initialize(); val.ValidateElement("elem1", "", null); val.SkipToEndElement(null); val.EndValidation(); return; } // BUG 304774 - resolved [Fact] public void SetSchemaSetWithInvalidContent_TypeCollision() { XmlSchemaValidator val; XmlSchemaSet sch = new XmlSchemaSet(); sch.Add( "", XmlReader.Create( new StringReader( "<?xml version=\"1.0\" ?>\n" + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + " <xs:element name=\"root\" type=\"xs:int\" />\n" + "</xs:schema>" ) ) ); sch.Add( "", XmlReader.Create( new StringReader( "<?xml version=\"1.0\" ?>\n" + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + " <xs:element name=\"root\" type=\"xs:string\" />\n" + "</xs:schema>" ) ) ); try { val = new XmlSchemaValidator( new NameTable(), sch, new XmlNamespaceManager(new NameTable()), AllFlags ); } catch (XmlSchemaValidationException) { return; } return; } [Fact] public void CustomXmlNameSpaceResolverImplementation() { XmlSchemaValidator val; XmlSchemaInfo info = new XmlSchemaInfo(); XmlSchemaSet sch = new XmlSchemaSet(); ObservedNamespaceManager nsManager = new ObservedNamespaceManager(new NameTable()); nsManager.AddNamespace("n1", "uri:tempuri"); val = new XmlSchemaValidator(new NameTable(), sch, nsManager, AllFlags); val.AddSchema( XmlSchema.Read( XmlReader.Create( new StringReader( "<?xml version=\"1.0\" ?>\n" + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n" + " xmlns:n1=\"uri:tempuri\"\n" + " targetNamespace=\"uri:tempuri1\">\n" + " <xs:complexType name=\"foo\">\n" + " <xs:sequence>\n" + " <xs:element name=\"bar\" />\n" + " </xs:sequence>\n" + " </xs:complexType>\n" + "</xs:schema>" ) ), null ) ); val.Initialize(); val.ValidateElement("root", "", info, "n1:foo", null, null, null); Assert.True(nsManager.IsLookupNamespaceCalled); return; } } // ===================== AddSchema ===================== public class TCAddSchema : CXmlSchemaValidatorTestCase { private ITestOutputHelper _output; public TCAddSchema(ITestOutputHelper output) : base(output) { _output = output; } [Fact] public void PassNull() { XmlSchemaValidator val = CreateValidator(new XmlSchemaSet()); try { val.AddSchema(null); } catch (ArgumentNullException) { return; } Assert.True(false); } [Fact] public void CheckDeepCopyOfXmlSchema() { XmlSchemaValidator val = CreateValidator(new XmlSchemaSet()); XmlSchemaInfo info = new XmlSchemaInfo(); XmlSchema s = new XmlSchema(); XmlSchemaElement e1 = new XmlSchemaElement(); XmlSchemaElement e2 = new XmlSchemaElement(); e1.Name = "foo"; e2.Name = "bar"; s.Items.Add(e1); val.AddSchema(s); s.Items.Add(e2); val.Initialize(); try { val.ValidateElement("bar", "", info); } catch (XmlSchemaValidationException) { return; } Assert.True(false); } [Fact] public void AddSameXmlSchemaTwice() { XmlSchemaValidator val = CreateValidator(new XmlSchemaSet()); XmlSchemaInfo info = new XmlSchemaInfo(); XmlSchema s; s = XmlSchema.Read( XmlReader.Create( new StringReader( "<?xml version=\"1.0\" ?>\n" + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + " <xs:element name=\"root\" />\n" + "</xs:schema>" ) ), null ); val.AddSchema(s); val.AddSchema(s); val.Initialize(); val.ValidateElement("root", "", info); return; } [Fact] public void AddSameXmlSchemaWithTargetNamespaceTwice() { XmlSchemaValidator val = CreateValidator(new XmlSchemaSet()); XmlSchemaInfo info = new XmlSchemaInfo(); XmlSchema s; s = XmlSchema.Read( XmlReader.Create( new StringReader( "<?xml version=\"1.0\" ?>\n" + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n" + " xmlns:n1=\"uri:tempuri\"\n" + " targetNamespace=\"uri:tempuri\">\n" + " <xs:element name=\"root\" />\n" + "</xs:schema>" ) ), null ); val.AddSchema(s); val.AddSchema(s); val.Initialize(); val.ValidateElement("root", "uri:tempuri", info); return; } [Fact] public void AddSchemasWithTypeCollision() { XmlSchemaValidator val = CreateValidator(new XmlSchemaSet()); val.AddSchema( XmlSchema.Read( XmlReader.Create( new StringReader( "<?xml version=\"1.0\" ?>\n" + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + " <xs:element name=\"root\" type=\"xs:string\" />\n" + "</xs:schema>" ) ), null ) ); try { val.AddSchema( XmlSchema.Read( XmlReader.Create( new StringReader( "<?xml version=\"1.0\" ?>\n" + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + " <xs:element name=\"root\" type=\"xs:boolean\" />\n" + "</xs:schema>" ) ), null ) ); } catch (XmlSchemaValidationException) { return; } Assert.True(false); } [Fact] public void ValidateThenAddAdditionalSchemas() { XmlSchemaValidator val; XmlSchemaInfo info = new XmlSchemaInfo(); val = CreateValidator(new XmlSchemaSet()); val.AddSchema( XmlSchema.Read( XmlReader.Create( new StringReader( "<?xml version=\"1.0\" ?>\n" + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n" + " targetNamespace=\"uri:tempuri1\">\n" + " <xs:element name=\"foo\" type=\"xs:string\" />\n" + "</xs:schema>" ) ), null ) ); val.Initialize(); val.ValidateElement("foo", "uri:tempuri1", info); val.SkipToEndElement(info); val.AddSchema( XmlSchema.Read( XmlReader.Create( new StringReader( "<?xml version=\"1.0\" ?>\n" + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n" + " targetNamespace=\"uri:tempuri2\">\n" + " <xs:element name=\"bar\" type=\"xs:string\" />\n" + "</xs:schema>" ) ), null ) ); val.ValidateElement("bar", "uri:tempuri2", info); val.SkipToEndElement(info); val.EndValidation(); return; } [Theory] [InlineData(true)] [InlineData(false)] public void ImportAnotherSchemaThat_Is_IsNot_InSchemaSet(bool importTwice) { XmlSchemaValidator val; XmlSchemaInfo info = new XmlSchemaInfo(); Uri u = new Uri( Uri.UriSchemeFile + Uri.SchemeDelimiter + Path.Combine(Path.GetFullPath(TestData), XSDFILE_TARGET_NAMESPACE) ); XmlSchema s1; XmlSchemaSet schemas = new XmlSchemaSet(); schemas.XmlResolver = new XmlUrlResolver(); val = CreateValidator(new XmlSchemaSet()); s1 = XmlSchema.Read( new StringReader( "<?xml version=\"1.0\"?>\n" + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n" + " xmlns:temp=\"uri:tempuri\">\n" + " <xs:import namespace=\"uri:tempuri\"\n" + " schemaLocation=\"" + u.AbsoluteUri + "\" />\n" + " <xs:element name=\"root\">\n" + " <xs:complexType>\n" + " <xs:sequence>\n" + " <xs:element ref=\"temp:elem1\" />\n" + " </xs:sequence>\n" + " </xs:complexType>\n" + " </xs:element>\n" + "</xs:schema>" ), null ); schemas.Add(s1); if (importTwice) { foreach (XmlSchema s in schemas.Schemas("uri:tempuri")) val.AddSchema(s); } val.AddSchema(s1); val.Initialize(); val.ValidateElement("root", "", info); val.ValidateEndOfAttributes(null); val.ValidateElement("elem1", "uri:tempuri", info); val.ValidateEndOfAttributes(null); val.ValidateEndElement(info); val.ValidateEndElement(info); val.EndValidation(); return; } //(BUG #306858) [Fact] public void SetIgnoreInlineSchemaFlag_AddSchemaShouldDoNothing() { XmlSchemaValidator val; XmlSchemaInfo info = new XmlSchemaInfo(); val = CreateValidator( CreateSchemaSetFromXml("<root />"), XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessSchemaLocation ); val.AddSchema( XmlSchema.Read( XmlReader.Create( new StringReader( "<?xml version=\"1.0\" ?>\n" + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" + " <xs:element name=\"foo\" type=\"xs:string\" />\n" + "</xs:schema>" ) ), null ) ); val.Initialize(); try { val.ValidateElement("foo", "", info); throw new Exception("Additional schema was loaded!"); } catch (XmlSchemaValidationException) { return; } } } }
31.642857
99
0.40941
[ "MIT" ]
belav/runtime
src/libraries/System.Private.Xml/tests/XmlSchema/XmlSchemaValidatorApi/Constructor_AddSchema.cs
16,834
C#
using System.Collections.Generic; using AlbaVulpes.API.Base; namespace AlbaVulpes.API.Models.Identity { public class User : ApiModel { public string UserName { get; set; } public string Email { get; set; } public string Password { get; set; } public List<Role> Roles { get; set; } } }
23.642857
45
0.634441
[ "Apache-2.0" ]
albavulpes/api
src/Models/Identity/User.cs
333
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GTBDDLab4 { enum TransactionType { Optimistic, Pessimistic } }
13.5
33
0.677249
[ "MIT" ]
Andrei15193/Laboratoare-Facultate
Semestrul4/GTBDD/L4/GTBDDLab4/TransactionType.cs
191
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.ConfidentialLedger.V20210513Preview.Inputs { /// <summary> /// Additional Confidential Ledger properties. /// </summary> public sealed class LedgerPropertiesArgs : Pulumi.ResourceArgs { [Input("aadBasedSecurityPrincipals")] private InputList<Inputs.AADBasedSecurityPrincipalArgs>? _aadBasedSecurityPrincipals; /// <summary> /// Array of all AAD based Security Principals. /// </summary> public InputList<Inputs.AADBasedSecurityPrincipalArgs> AadBasedSecurityPrincipals { get => _aadBasedSecurityPrincipals ?? (_aadBasedSecurityPrincipals = new InputList<Inputs.AADBasedSecurityPrincipalArgs>()); set => _aadBasedSecurityPrincipals = value; } [Input("certBasedSecurityPrincipals")] private InputList<Inputs.CertBasedSecurityPrincipalArgs>? _certBasedSecurityPrincipals; /// <summary> /// Array of all cert based Security Principals. /// </summary> public InputList<Inputs.CertBasedSecurityPrincipalArgs> CertBasedSecurityPrincipals { get => _certBasedSecurityPrincipals ?? (_certBasedSecurityPrincipals = new InputList<Inputs.CertBasedSecurityPrincipalArgs>()); set => _certBasedSecurityPrincipals = value; } /// <summary> /// Type of Confidential Ledger /// </summary> [Input("ledgerType")] public InputUnion<string, Pulumi.AzureNative.ConfidentialLedger.V20210513Preview.LedgerType>? LedgerType { get; set; } public LedgerPropertiesArgs() { } } }
36.716981
139
0.685509
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/ConfidentialLedger/V20210513Preview/Inputs/LedgerPropertiesArgs.cs
1,946
C#
/* dotNetRDF is free and open source software licensed under the MIT License ----------------------------------------------------------------------------- Copyright (c) 2009-2012 dotNetRDF Project (dotnetrdf-developer@lists.sf.net) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace VDS.RDF.Utilities.Editor.Selection { /// <summary> /// A selector which adds white space as a deliminator /// </summary> /// <typeparam name="T">Control Type</typeparam> public class WhiteSpaceSelector<T> : DefaultSelector<T> { /// <summary> /// Gets whether the given character is a starting deliminator /// </summary> /// <param name="c">Character</param> /// <returns>True if the character is whitespace of a standard deliminator, false otherwise</returns> protected override bool IsStartingDeliminator(char c) { return Char.IsWhiteSpace(c) || base.IsStartingDeliminator(c); } /// <summary> /// Gets whether the given character is an ending deliminator /// </summary> /// <param name="c">Character</param> /// <returns>True if the character is whitespace or a standard deliminator, false otherwise</returns> protected override bool IsEndingDeliminator(char c) { return Char.IsWhiteSpace(c) || base.IsEndingDeliminator(c); } } /// <summary> /// A selector which adds punctuation as a deliminator /// </summary> /// <typeparam name="T">Control Type</typeparam> public class PunctuationSelector<T> : DefaultSelector<T> { /// <summary> /// Gets whether the given character is a starting deliminator /// </summary> /// <param name="c">Character</param> /// <returns>True if the character is punctuation or a standard deliminator, false otherwise</returns> protected override bool IsStartingDeliminator(char c) { return Char.IsPunctuation(c) || base.IsStartingDeliminator(c); } /// <summary> /// Gets whether the given character is an ending deliminator /// </summary> /// <param name="c">Character</param> /// <returns>True if the character is punctuation or a standard deliminator, false otherwise</returns> protected override bool IsEndingDeliminator(char c) { return Char.IsPunctuation(c) || base.IsEndingDeliminator(c); } } /// <summary> /// A selecotr which adds punctuation and white space as a deliminator /// </summary> /// <typeparam name="T">Control Type</typeparam> public class WhiteSpaceOrPunctuationSelection<T> : DefaultSelector<T> { /// <summary> /// Gets whether the given character is a starting deliminator /// </summary> /// <param name="c">Character</param> /// <returns>True if the character is punctuation, white space or a standard deliminator, false otherwise</returns> protected override bool IsStartingDeliminator(char c) { return Char.IsWhiteSpace(c) || Char.IsPunctuation(c) || base.IsStartingDeliminator(c); } /// <summary> /// Gets whether the given character is an ending deliminator /// </summary> /// <param name="c">Character</param> /// <returns>True if the character is punctuation, white space or a standard deliminator, false otherwise</returns> protected override bool IsEndingDeliminator(char c) { return Char.IsWhiteSpace(c) || Char.IsPunctuation(c) || base.IsEndingDeliminator(c); } } }
40.692308
123
0.657005
[ "MIT" ]
dotnetrdf/dotNetRDF.Toolkit
Libraries/editor/Selection/WhiteSpaceSelector.cs
4,761
C#
#if UNITY_EDITOR using System.Linq; using System.Collections.Generic; using UnityEngine; using UnityEditor; using NodeCanvas.Framework; using ParadoxNotion; namespace NodeCanvas.Editor { public static class GraphEditorUtility { public static event System.Action<IGraphElement> onActiveElementChanged; public static event System.Action PostGUI; public static bool allowClick = true; //Invoke PostGUI public static void InvokePostGUI(){ if (PostGUI != null){ PostGUI(); PostGUI = null; } } ///---------------------------------------------------------------------------------------------- private static IGraphElement _activeElement; private static List<IGraphElement> _activeElements = new List<IGraphElement>(); ///Selected Node or Connection public static IGraphElement activeElement{ get { if (activeElements.Count > 1){ return null; } if (activeElements.Count == 1){ return activeElements[0]; } return _activeElement; } set { if (!activeElements.Contains(value)){ activeElements.Clear(); } _activeElement = value; GUIUtility.keyboardControl = 0; UnityEditor.SceneView.RepaintAll(); //for gizmos if (onActiveElementChanged != null){ onActiveElementChanged(value); } } } ///multiple selected Node or Connection public static List<IGraphElement> activeElements{ get {return _activeElements;} set { if (value != null && value.Count == 1){ activeElement = value[0]; value.Clear(); } _activeElements = value != null? value : new List<IGraphElement>(); } } ///Selected Node if any public static Node activeNode{ get {return activeElement as Node;} } ///Selected Connection if any public static Connection activeConnection{ get {return activeElement as Connection;} } ///---------------------------------------------------------------------------------------------- ///Returns the extension at which the graph will be saved with if exported to JSON public static string GetGraphJSONFileExtension(this Graph graph){ return graph.GetType().Name.GetCapitals(); } ///Make a deep copy of provided graph asset along with it's sub-graphs. public static Graph DeepCopy(Graph root){ if (root == null){ return null; } var path = EditorUtility.SaveFilePanelInProject ("Copy of " + root.name, root.name + "_duplicate.asset", "asset", string.Empty); if (string.IsNullOrEmpty(path)){ return null; } var copy = (Graph)ScriptableObject.CreateInstance(root.GetType()); AssetDatabase.CreateAsset(copy, path); EditorUtility.CopySerialized(root, copy); //make use of IGraphAssignable interface to find nodes that represent a sub-graph. foreach(var subGraphNode in copy.allNodes.OfType<IGraphAssignable>()){ if (subGraphNode.nestedGraph != null){ //duplicate the existing sub-graph and assign the copy to node. subGraphNode.nestedGraph = DeepCopy(subGraphNode.nestedGraph); } } copy.Validate(); AssetDatabase.SaveAssets(); return copy; } } } #endif
26.632479
131
0.654365
[ "MIT" ]
CITMUniversityExercises/AIExercises
AIVisualScripting/AIVisualScripting/Assets/ParadoxNotion/NodeCanvas/Framework/Design/PartialEditor/GraphEditorUtility.cs
3,118
C#
using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Input; using MahApps.Metro.Controls; using TogglDesktop.AutoCompletion; using TogglDesktop.AutoCompletion.Items; using TogglDesktop.Diagnostics; using TogglDesktop.Theming; using TogglDesktop.ViewModels; #if MS_STORE using TogglDesktop.Services.Win10; #endif namespace TogglDesktop { partial class PreferencesWindow { public PreferencesWindowViewModel ViewModel { get => (PreferencesWindowViewModel)DataContext; private set => DataContext = value; } private bool isSaving; private Toggl.TogglAutocompleteView selectedDefaultProject; private List<Toggl.TogglAutocompleteView> knownProjects; public PreferencesWindow() { this.InitializeComponent(); ViewModel = new PreferencesWindowViewModel(MessageBox.Show(this), this.Close); Toggl.OnSettings += this.onSettings; Toggl.OnLogin += this.onLogin; Toggl.OnProjectAutocomplete += this.onProjectAutocomplete; this.Closing += OnClosing; } private void OnClosing(object sender, CancelEventArgs e) { ViewModel.ResetRecordedShortcuts(); } private void onLogin(bool open, ulong userID) { if (this.TryBeginInvoke(this.onLogin, open, userID)) return; this.recordTimelineCheckBox.IsEnabled = !open && userID != 0; this.recordTimelineCheckBox.IsChecked = Toggl.IsTimelineRecordingEnabled(); } private void onSettings(bool open, Toggl.TogglSettingsView settings) { if (this.TryBeginInvoke(this.onSettings, open, settings)) return; if (this.isSaving) return; using (Performance.Measure("filling settings from OnSettings")) { this.updateUI(settings); this.selectDefaultProjectFromSettings(); } if (open) { this.Show(); this.Activate(); } } private void onProjectAutocomplete(List<Toggl.TogglAutocompleteView> list) { if (this.TryBeginInvoke(this.onProjectAutocomplete, list)) return; this.knownProjects = list; this.defaultProjectAutoComplete.SetController(AutoCompleteControllersFactory.ForProjects(list)); } private void updateUI(Toggl.TogglSettingsView settings) { #region general this.idleDetectionCheckBox.IsChecked = settings.UseIdleDetection; this.idleDetectionDurationTextBox.Text = settings.IdleMinutes.ToString(); this.enablePomodoroCheckBox.IsChecked = settings.Pomodoro; this.pomodoroTimerDuration.Text = settings.PomodoroMinutes.ToString(); this.enablePomodoroBreakCheckBox.IsChecked = settings.PomodoroBreak; this.pomodoroBreakTimerDuration.Text = settings.PomodoroBreakMinutes.ToString(); this.recordTimelineCheckBox.IsChecked = settings.RecordTimeline; this.onTopCheckBox.IsChecked = settings.OnTop; this.keepEndTimeFixedCheckbox.IsChecked = Toggl.GetKeepEndTimeFixed(); this.keepDurationFixedCheckbox.IsChecked = !this.keepEndTimeFixedCheckbox.IsChecked; this.onStopEntryCheckBox.IsChecked = settings.StopEntryOnShutdownSleep; this.themeComboBox.SelectedIndex = settings.ColorTheme; Task.Run(UpdateLaunchOnStartupCheckboxAsync); #endregion #region proxy this.useNoProxyRadioButton.IsChecked = true; this.useSystemProxySettingsCheckBox.IsChecked = settings.AutodetectProxy; this.useProxyCheckBox.IsChecked = settings.UseProxy; this.proxyHostTextBox.Text = settings.ProxyHost; this.proxyPortTextBox.Text = settings.ProxyPort.ToString(); this.proxyUsernameTextBox.Text = settings.ProxyUsername; this.proxyPasswordBox.Password = settings.ProxyPassword; #endregion #region reminder this.remindToTrackCheckBox.IsChecked = settings.Reminder; this.remindToTrackIntervalTextBox.Text = settings.ReminderMinutes.ToString(); this.reminderStartTimeTextBox.Text = settings.RemindStarts; this.reminderEndTimeTextBox.Text = settings.RemindEnds; this.remindOnMondayTextBox.IsChecked = settings.RemindMon; this.remindOnTuesdayTextBox.IsChecked = settings.RemindTue; this.remindOnWednesdayTextBox.IsChecked = settings.RemindWed; this.remindOnThursdayTextBox.IsChecked = settings.RemindThu; this.remindOnFridayTextBox.IsChecked = settings.RemindFri; this.remindOnSaturdayTextBox.IsChecked = settings.RemindSat; this.remindOnSundayTextBox.IsChecked = settings.RemindSun; #endregion #region auto tracker this.enableAutotrackerCheckbox.IsChecked = settings.Autotrack; #endregion ViewModel.LoadShortcutsFromSettings(); } private static async Task<bool?> IsRunOnStartupEnabled() { #if MS_STORE return await RunOnStartup.IsRunOnStartupEnabled(); #else return Utils.GetLaunchOnStartupRegistry(); #endif } private async Task UpdateLaunchOnStartupCheckboxAsync() { var isEnabled = await IsRunOnStartupEnabled(); this.TryBeginInvoke((bool? isRunOnStartupEnabled, ToggleSwitch checkBox) => { if (isRunOnStartupEnabled.HasValue == false) { checkBox.Visibility = Visibility.Collapsed; } else { checkBox.Visibility = Visibility.Visible; checkBox.IsChecked = isRunOnStartupEnabled.Value; } }, isEnabled, launchOnStartupCheckBox); } private static bool isChecked(ToggleButton checkBox) { return checkBox.IsChecked ?? false; } private static bool isChecked(ToggleSwitch checkBox) { return checkBox.IsChecked ?? false; } private static ulong toULong(string text) { ulong.TryParse(text, out var ret); return ret; } private static long toLong(string text) { long.TryParse(text, out var ret); return ret; } #region saving private async void saveButtonClicked(object sender, RoutedEventArgs e) { ViewModel.ResetPropsWithErrorsToPreviousValues(); try { this.isSaving = true; this.IsEnabled = false; using (Performance.Measure("saving settings")) { var settings = this.createSettingsFromUI(); var success = await Task.Run(() => this.save(settings)); if (success) this.Hide(); } } finally { this.IsEnabled = true; this.isSaving = false; } } private async Task<bool> save(Settings settings) { using (Performance.Measure("saving global shortcuts")) { Utils.SetShortcutForShow(settings.ShowHideToggl); Utils.SetShortcutForStart(settings.ContinueStopTimer); } Toggl.SetDefaultProject(settings.DefaultProject.ProjectID, settings.DefaultProject.TaskID); Toggl.SetKeepEndTimeFixed(settings.KeepEndTimeFixed); #if MS_STORE await RunOnStartup.TrySetRunOnStartup(settings.LaunchOnStartup); #else Utils.SaveLaunchOnStartupRegistry(settings.LaunchOnStartup); #endif return Toggl.SetSettings(settings.TogglSettings); } private Settings createSettingsFromUI() { var settings = new Toggl.TogglSettingsView { #region general UseIdleDetection = isChecked(this.idleDetectionCheckBox), IdleMinutes = toLong(this.idleDetectionDurationTextBox.Text), RecordTimeline = isChecked(this.recordTimelineCheckBox), OnTop = isChecked(this.onTopCheckBox), Pomodoro = isChecked(this.enablePomodoroCheckBox), PomodoroMinutes = toLong(this.pomodoroTimerDuration.Text), PomodoroBreak = isChecked(this.enablePomodoroBreakCheckBox), PomodoroBreakMinutes = toLong(this.pomodoroBreakTimerDuration.Text), StopEntryOnShutdownSleep = isChecked(this.onStopEntryCheckBox), ColorTheme = (byte)this.themeComboBox.SelectedIndex, #endregion #region proxy AutodetectProxy = isChecked(this.useSystemProxySettingsCheckBox), UseProxy = isChecked(this.useProxyCheckBox), ProxyHost = this.proxyHostTextBox.Text, ProxyPort = toULong(this.proxyPortTextBox.Text), ProxyUsername = this.proxyUsernameTextBox.Text, ProxyPassword = this.proxyPasswordBox.Password, #endregion #region auto tracker Autotrack = isChecked(this.enableAutotrackerCheckbox), #endregion #region reminder Reminder = isChecked(this.remindToTrackCheckBox), ReminderMinutes = toLong(this.remindToTrackIntervalTextBox.Text), RemindStarts = this.reminderStartTimeTextBox.Text, RemindEnds = this.reminderEndTimeTextBox.Text, RemindMon = isChecked(this.remindOnMondayTextBox), RemindTue = isChecked(this.remindOnTuesdayTextBox), RemindWed = isChecked(this.remindOnWednesdayTextBox), RemindThu = isChecked(this.remindOnThursdayTextBox), RemindFri = isChecked(this.remindOnFridayTextBox), RemindSat = isChecked(this.remindOnSaturdayTextBox), RemindSun = isChecked(this.remindOnSundayTextBox), #endregion }; return new Settings { TogglSettings = settings, DefaultProject = this.selectedDefaultProject, KeepEndTimeFixed = isChecked(this.keepEndTimeFixedCheckbox), LaunchOnStartup = isChecked(this.launchOnStartupCheckBox), ContinueStopTimer = ViewModel.GetContinueStopTimerIfChanged(), ShowHideToggl = ViewModel.GetShowHideTogglIfChanged() }; } class Settings { public Toggl.TogglSettingsView TogglSettings { get; set; } public Toggl.TogglAutocompleteView DefaultProject { get; set; } public bool KeepEndTimeFixed { get; set; } public bool LaunchOnStartup { get; set; } public HotKey ShowHideToggl { get; set; } public HotKey ContinueStopTimer { get; set; } } #endregion #region project auto completion private void defaultProjectTextBox_OnLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { if (this.defaultProjectTextBox.Text == "") { this.selectDefaultProject(null); } else if (!string.IsNullOrEmpty(this.selectedDefaultProject.ProjectLabel)) { this.selectDefaultProject(this.selectedDefaultProject); } } private void defaultProjectAutoComplete_OnConfirmCompletion(object sender, IAutoCompleteItem e) { var asProjectItem = e as IModelItem<Toggl.TogglAutocompleteView>; if (asProjectItem == null) return; var item = asProjectItem.Model; this.selectDefaultProject(item); this.defaultProjectTextBox.CaretIndex = this.defaultProjectTextBox.Text.Length; } private void defaultProjectAutoComplete_OnConfirmWithoutCompletion(object sender, string e) { this.selectDefaultProject(null); } private void selectDefaultProject(Toggl.TogglAutocompleteView? item) { var project = item ?? default(Toggl.TogglAutocompleteView); this.selectedDefaultProject = project; this.defaultProjectTextBox.SetText(project.ProjectLabel, project.TaskLabel); this.defaultProjectColorCircle.Background = Utils.ProjectColorBrushFromString(project.ProjectColor); this.defaultProjectTextBox.CaretIndex = this.defaultProjectTextBox.Text.Length; } private void selectDefaultProjectFromSettings() { var projectID = Toggl.GetDefaultProjectId(); var taskID = Toggl.GetDefaultTaskId(); var project = default(Toggl.TogglAutocompleteView); if (this.knownProjects != null) { project = this.knownProjects .FirstOrDefault(p => p.ProjectID == projectID && p.TaskID == taskID); } if (project.ProjectID != projectID || project.TaskID != taskID) { project = new Toggl.TogglAutocompleteView { ProjectLabel = Toggl.GetDefaultProjectName(), ProjectID = projectID, TaskID = taskID, }; } this.selectDefaultProject(project); } #endregion } }
36.220551
113
0.597841
[ "BSD-3-Clause" ]
jiri/toggldesktop
src/ui/windows/TogglDesktop/TogglDesktop/ui/windows/PreferencesWindow.xaml.cs
14,454
C#
using System; using Abp; using Abp.Authorization; using Abp.Dependency; using Abp.UI; namespace Fooww.Research.Authorization { public class AbpLoginResultTypeHelper : AbpServiceBase, ITransientDependency { public AbpLoginResultTypeHelper() { LocalizationSourceName = ResearchConsts.LocalizationSourceName; } public Exception CreateExceptionForFailedLoginAttempt(AbpLoginResultType result, string usernameOrEmailAddress, string tenancyName) { switch (result) { case AbpLoginResultType.Success: return new Exception("Don't call this method with a success result!"); case AbpLoginResultType.InvalidUserNameOrEmailAddress: case AbpLoginResultType.InvalidPassword: return new UserFriendlyException(L("LoginFailed"), L("InvalidUserNameOrPassword")); case AbpLoginResultType.InvalidTenancyName: return new UserFriendlyException(L("LoginFailed"), L("ThereIsNoTenantDefinedWithName{0}", tenancyName)); case AbpLoginResultType.TenantIsNotActive: return new UserFriendlyException(L("LoginFailed"), L("TenantIsNotActive", tenancyName)); case AbpLoginResultType.UserIsNotActive: return new UserFriendlyException(L("LoginFailed"), L("UserIsNotActiveAndCanNotLogin", usernameOrEmailAddress)); case AbpLoginResultType.UserEmailIsNotConfirmed: return new UserFriendlyException(L("LoginFailed"), L("UserEmailIsNotConfirmedAndCanNotLogin")); case AbpLoginResultType.LockedOut: return new UserFriendlyException(L("LoginFailed"), L("UserLockedOutMessage")); default: // Can not fall to default actually. But other result types can be added in the future and we may forget to handle it Logger.Warn("Unhandled login fail reason: " + result); return new UserFriendlyException(L("LoginFailed")); } } public string CreateLocalizedMessageForFailedLoginAttempt(AbpLoginResultType result, string usernameOrEmailAddress, string tenancyName) { switch (result) { case AbpLoginResultType.Success: throw new Exception("Don't call this method with a success result!"); case AbpLoginResultType.InvalidUserNameOrEmailAddress: case AbpLoginResultType.InvalidPassword: return L("InvalidUserNameOrPassword"); case AbpLoginResultType.InvalidTenancyName: return L("ThereIsNoTenantDefinedWithName{0}", tenancyName); case AbpLoginResultType.TenantIsNotActive: return L("TenantIsNotActive", tenancyName); case AbpLoginResultType.UserIsNotActive: return L("UserIsNotActiveAndCanNotLogin", usernameOrEmailAddress); case AbpLoginResultType.UserEmailIsNotConfirmed: return L("UserEmailIsNotConfirmedAndCanNotLogin"); default: // Can not fall to default actually. But other result types can be added in the future and we may forget to handle it Logger.Warn("Unhandled login fail reason: " + result); return L("LoginFailed"); } } } }
53.338462
143
0.645226
[ "MIT" ]
PowerDG/Hundred-Micro
PropertyTools/20190715/Old/src/Fooww.Research.Application/Authorization/AbpLoginResultTypeHelper.cs
3,469
C#
// ----------------------------------------------------------------------- // <copyright file="BatchingSqlServerEventsByPersistenceIdSpec.cs" company="Akka.NET Project"> // Copyright (C) 2013 - 2019 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> // ----------------------------------------------------------------------- using Akka.Configuration; using Akka.Persistence.Query; using Akka.Persistence.Query.Sql; using Akka.Persistence.TCK.Query; using Xunit; using Xunit.Abstractions; namespace Akka.Persistence.SqlServer.Tests.Batching { [Collection("SqlServerSpec")] public class BatchingSqlServerEventsByPersistenceIdSpec : EventsByPersistenceIdSpec { public BatchingSqlServerEventsByPersistenceIdSpec(ITestOutputHelper output, SqlServerFixture fixture) : base(InitConfig(fixture), nameof(BatchingSqlServerEventsByPersistenceIdSpec), output) { ReadJournal = Sys.ReadJournalFor<SqlReadJournal>(SqlReadJournal.Identifier); } private static Config InitConfig(SqlServerFixture fixture) { DbUtils.Initialize(fixture.ConnectionString); var conf = ConfigurationFactory.ParseString($@" akka.loglevel = DEBUG akka.test.single-expect-default = 10s akka.persistence.journal.plugin = ""akka.persistence.journal.sql-server"" akka.persistence.journal.sql-server {{ class = ""Akka.Persistence.SqlServer.Journal.BatchingSqlServerJournal, Akka.Persistence.SqlServer"" plugin-dispatcher = ""akka.actor.default-dispatcher"" table-name = EventJournal schema-name = dbo auto-initialize = on connection-string = ""{DbUtils.ConnectionString}"" refresh-interval = 1s }}"); return conf.WithFallback(SqlReadJournal.DefaultConfiguration()); } protected override void Dispose(bool disposing) { base.Dispose(disposing); DbUtils.Clean(); } } }
40.326923
115
0.617072
[ "Apache-2.0" ]
Arkatufus/Akka.Persistence.SqlServer
src/Akka.Persistence.SqlServer.Tests/Batching/BatchingSqlServerEventsByPersistenceIdSpec.cs
2,099
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. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201 { using Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.PowerShell; /// <summary> /// A PowerShell PSTypeConverter to support converting to an instance of <see cref="OutboundNetworkDependenciesEndpointListResult" /// /> /// </summary> public partial class OutboundNetworkDependenciesEndpointListResultTypeConverter : global::System.Management.Automation.PSTypeConverter { /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c>. /// </returns> public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="OutboundNetworkDependenciesEndpointListResult" /// /> type.</param> /// <returns> /// <c>true</c> if the instance could be converted to a <see cref="OutboundNetworkDependenciesEndpointListResult" /> type, /// otherwise <c>false</c> /// </returns> public static bool CanConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return true; } global::System.Type type = sourceValue.GetType(); if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { // we say yest to PSObjects return true; } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { // we say yest to Hashtables/dictionaries return true; } try { if (null != sourceValue.ToJsonString()) { return true; } } catch { // Not one of our objects } try { string text = sourceValue.ToString()?.Trim(); return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonType.Object; } catch { // Doesn't look like it can be treated as JSON } return false; } /// <summary> /// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c> /// </returns> public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns> /// an instance of <see cref="OutboundNetworkDependenciesEndpointListResult" />, or <c>null</c> if there is no suitable conversion. /// </returns> public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the value to convert into an instance of <see cref="OutboundNetworkDependenciesEndpointListResult" /// />.</param> /// <returns> /// an instance of <see cref="OutboundNetworkDependenciesEndpointListResult" />, or <c>null</c> if there is no suitable conversion. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IOutboundNetworkDependenciesEndpointListResult ConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return null; } global::System.Type type = sourceValue.GetType(); if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api20220201.IOutboundNetworkDependenciesEndpointListResult).IsAssignableFrom(type)) { return sourceValue; } try { return OutboundNetworkDependenciesEndpointListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; } catch { // Unable to use JSON pattern } if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { return OutboundNetworkDependenciesEndpointListResult.DeserializeFromPSObject(sourceValue); } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { return OutboundNetworkDependenciesEndpointListResult.DeserializeFromDictionary(sourceValue); } return null; } /// <summary>NotImplemented -- this will return <c>null</c></summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns>will always return <c>null</c>.</returns> public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; } }
53.113333
241
0.603866
[ "MIT" ]
AlanFlorance/azure-powershell
src/Kusto/generated/api/Models/Api20220201/OutboundNetworkDependenciesEndpointListResult.TypeConverter.cs
7,818
C#
using System; using System.Globalization; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security; using ASP.NET_MVC_Template.Models; namespace ASP.NET_MVC_Template.Controllers { [Authorize] public class AccountController : Controller { private ApplicationUserManager _userManager; public AccountController() { } public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager ) { UserManager = userManager; SignInManager = signInManager; } public ApplicationUserManager UserManager { get { return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); } private set { _userManager = value; } } // // GET: /Account/Login [AllowAnonymous] public ActionResult Login(string returnUrl) { ViewBag.ReturnUrl = returnUrl; return View(); } private ApplicationSignInManager _signInManager; public ApplicationSignInManager SignInManager { get { return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>(); } private set { _signInManager = value; } } // // POST: /Account/Login [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return View(model); } // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false); switch (result) { case SignInStatus.Success: return RedirectToLocal(returnUrl); case SignInStatus.LockedOut: return View("Lockout"); case SignInStatus.RequiresVerification: return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return View(model); } } // // GET: /Account/VerifyCode [AllowAnonymous] public async Task<ActionResult> VerifyCode(string provider, string returnUrl, bool rememberMe) { // Require that the user has already logged in via username/password or external login if (!await SignInManager.HasBeenVerifiedAsync()) { return View("Error"); } var user = await UserManager.FindByIdAsync(await SignInManager.GetVerifiedUserIdAsync()); if (user != null) { var code = await UserManager.GenerateTwoFactorTokenAsync(user.Id, provider); } return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe }); } // // POST: /Account/VerifyCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model) { if (!ModelState.IsValid) { return View(model); } // The following code protects for brute force attacks against the two factor codes. // If a user enters incorrect codes for a specified amount of time then the user account // will be locked out for a specified amount of time. // You can configure the account lockout settings in IdentityConfig var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent: model.RememberMe, rememberBrowser: model.RememberBrowser); switch (result) { case SignInStatus.Success: return RedirectToLocal(model.ReturnUrl); case SignInStatus.LockedOut: return View("Lockout"); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid code."); return View(model); } } // // GET: /Account/Register [AllowAnonymous] public ActionResult Register() { return View(); } // // POST: /Account/Register [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); return RedirectToAction("Index", "Home"); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Account/ConfirmEmail [AllowAnonymous] public async Task<ActionResult> ConfirmEmail(string userId, string code) { if (userId == null || code == null) { return View("Error"); } var result = await UserManager.ConfirmEmailAsync(userId, code); return View(result.Succeeded ? "ConfirmEmail" : "Error"); } // // GET: /Account/ForgotPassword [AllowAnonymous] public ActionResult ForgotPassword() { return View(); } // // POST: /Account/ForgotPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model) { if (ModelState.IsValid) { var user = await UserManager.FindByNameAsync(model.Email); if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id))) { // Don't reveal that the user does not exist or is not confirmed return View("ForgotPasswordConfirmation"); } // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id); // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>"); // return RedirectToAction("ForgotPasswordConfirmation", "Account"); } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Account/ForgotPasswordConfirmation [AllowAnonymous] public ActionResult ForgotPasswordConfirmation() { return View(); } // // GET: /Account/ResetPassword [AllowAnonymous] public ActionResult ResetPassword(string code) { return code == null ? View("Error") : View(); } // // POST: /Account/ResetPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await UserManager.FindByNameAsync(model.Email); if (user == null) { // Don't reveal that the user does not exist return RedirectToAction("ResetPasswordConfirmation", "Account"); } var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password); if (result.Succeeded) { return RedirectToAction("ResetPasswordConfirmation", "Account"); } AddErrors(result); return View(); } // // GET: /Account/ResetPasswordConfirmation [AllowAnonymous] public ActionResult ResetPasswordConfirmation() { return View(); } // // POST: /Account/ExternalLogin [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public ActionResult ExternalLogin(string provider, string returnUrl) { // Request a redirect to the external login provider return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl })); } // // GET: /Account/SendCode [AllowAnonymous] public async Task<ActionResult> SendCode(string returnUrl, bool rememberMe) { var userId = await SignInManager.GetVerifiedUserIdAsync(); if (userId == null) { return View("Error"); } var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(userId); var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList(); return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe }); } // // POST: /Account/SendCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> SendCode(SendCodeViewModel model) { if (!ModelState.IsValid) { return View(); } // Generate the token and send it if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider)) { return View("Error"); } return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe }); } // // GET: /Account/ExternalLoginCallback [AllowAnonymous] public async Task<ActionResult> ExternalLoginCallback(string returnUrl) { var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); if (loginInfo == null) { return RedirectToAction("Login"); } // Sign in the user with this external login provider if the user already has a login var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false); switch (result) { case SignInStatus.Success: return RedirectToLocal(returnUrl); case SignInStatus.LockedOut: return View("Lockout"); case SignInStatus.RequiresVerification: return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false }); case SignInStatus.Failure: default: // If the user does not have an account, then prompt the user to create an account ViewBag.ReturnUrl = returnUrl; ViewBag.LoginProvider = loginInfo.Login.LoginProvider; return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email }); } } // // POST: /Account/ExternalLoginConfirmation [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Index", "Manage"); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return View(model); } // // POST: /Account/LogOff [HttpPost] [ValidateAntiForgeryToken] public ActionResult LogOff() { AuthenticationManager.SignOut(); return RedirectToAction("Index", "Home"); } // // GET: /Account/ExternalLoginFailure [AllowAnonymous] public ActionResult ExternalLoginFailure() { return View(); } #region Helpers // Used for XSRF protection when adding external logins private const string XsrfKey = "XsrfId"; private IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; } } private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError("", error); } } private ActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } return RedirectToAction("Index", "Home"); } internal class ChallengeResult : HttpUnauthorizedResult { public ChallengeResult(string provider, string redirectUri) : this(provider, redirectUri, null) { } public ChallengeResult(string provider, string redirectUri, string userId) { LoginProvider = provider; RedirectUri = redirectUri; UserId = userId; } public string LoginProvider { get; set; } public string RedirectUri { get; set; } public string UserId { get; set; } public override void ExecuteResult(ControllerContext context) { var properties = new AuthenticationProperties { RedirectUri = RedirectUri }; if (UserId != null) { properties.Dictionary[XsrfKey] = UserId; } context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider); } } #endregion } }
36.482906
173
0.559974
[ "MIT" ]
EmilMitev/Telerik-Academy
ASP.NET Web Forms/09. Identity/Demo/ASP.NET MVC Template/Controllers/AccountController.cs
17,076
C#
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; namespace Leto.Interop { public static partial class LibCrypto { [DllImport(Libraries.LibCrypto, CallingConvention = CallingConvention.Cdecl, EntryPoint = "BIO_meth_set_read")] private static extern int Internal_BIO_meth_set_read(BIO_METHOD biom, ReadDelegate method); public static void BIO_meth_set_read(BIO_METHOD biom, ReadDelegate method) { var returnCode = Internal_BIO_meth_set_read(biom, method); ThrowOnErrorReturnCode(returnCode); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate int ReadDelegate(BIO bio, void* buf, int size); } }
33.478261
119
0.728571
[ "MIT" ]
Drawaes/Leto2
src/Leto.Interop/LibCrypto/BIO/BIO_meth_set_read.cs
770
C#
using System; using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; namespace ConversionTool { class DiabloPNG { public static void SavePNG(string filename, byte[] pixels, int width, int height) { for (int i = 0; i < width * height; i++) { byte red = pixels[(i * 4) + 0]; pixels[(i * 4) + 0] = pixels[(i * 4) + 2]; pixels[(i * 4) + 2] = red; } Image image = Image.LoadPixelData<Byte4>(pixels, width, height); image.SaveAsPng(filename); } public static void SavePNG(string filename, byte[] data, byte[] palette, int width, int height, byte transr, byte transg, byte transb, bool bgr) { byte[] buffer = new byte[width * height * 4]; for(int i = 0; i < width * height; i++) { if (palette[(data[i] * 3) + 0] == transr && palette[(data[i] * 3) + 1] == transg && palette[(data[i] * 3) + 2] == transb) { buffer[(i * 4) + 0] = 0; buffer[(i * 4) + 1] = 0; buffer[(i * 4) + 2] = 0; buffer[(i * 4) + 3] = 0; continue; } if(bgr) { buffer[(i * 4) + 0] = palette[(data[i] * 3) + 2]; buffer[(i * 4) + 1] = palette[(data[i] * 3) + 1]; buffer[(i * 4) + 2] = palette[(data[i] * 3) + 0]; } else { buffer[(i * 4) + 0] = palette[(data[i] * 3) + 0]; buffer[(i * 4) + 1] = palette[(data[i] * 3) + 1]; buffer[(i * 4) + 2] = palette[(data[i] * 3) + 2]; } buffer[(i * 4) + 3] = 255; } Image image = Image.LoadPixelData<Byte4>(buffer, width, height); image.SaveAsPng(filename); } } }
26.517241
146
0.527958
[ "Unlicense" ]
jmarshall23/devilutionX
ConversionTool/DiabloPNG.cs
1,538
C#
using Amazon.JSII.Runtime.Deputy; #pragma warning disable CS0672,CS0809,CS1591 namespace aws { [JsiiByValue(fqn: "aws.Wafv2WebAclRuleStatementNotStatementStatementAndStatementStatementXssMatchStatementFieldToMatchBody")] public class Wafv2WebAclRuleStatementNotStatementStatementAndStatementStatementXssMatchStatementFieldToMatchBody : aws.IWafv2WebAclRuleStatementNotStatementStatementAndStatementStatementXssMatchStatementFieldToMatchBody { } }
38.75
223
0.875269
[ "MIT" ]
scottenriquez/cdktf-alpha-csharp-testing
resources/.gen/aws/aws/Wafv2WebAclRuleStatementNotStatementStatementAndStatementStatementXssMatchStatementFieldToMatchBody.cs
465
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.NavigateTo; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Represents a debugging session. /// </summary> internal sealed class DebuggingSession : IDisposable { private readonly Func<Project, CompilationOutputs> _compilationOutputsProvider; private readonly CancellationTokenSource _cancellationSource = new(); /// <summary> /// MVIDs read from the assembly built for given project id. /// </summary> private readonly Dictionary<ProjectId, (Guid Mvid, Diagnostic Error)> _projectModuleIds = new(); private readonly Dictionary<Guid, ProjectId> _moduleIds = new(); private readonly object _projectModuleIdsGuard = new(); /// <summary> /// The current baseline for given project id. /// The baseline is updated when changes are committed at the end of edit session. /// The backing module readers of initial baselines need to be kept alive -- store them in /// <see cref="_initialBaselineModuleReaders"/> and dispose them at the end of the debugging session. /// </summary> /// <remarks> /// The baseline of each updated project is linked to its initial baseline that reads from the on-disk metadata and PDB. /// Therefore once an initial baseline is created it needs to be kept alive till the end of the debugging session, /// even whne it's replaced in <see cref="_projectEmitBaselines"/> by a newer baseline. /// </remarks> private readonly Dictionary<ProjectId, EmitBaseline> _projectEmitBaselines = new(); private readonly List<IDisposable> _initialBaselineModuleReaders = new(); private readonly object _projectEmitBaselinesGuard = new(); // Maps active statement instructions reported by the debugger to their latest spans that might not yet have been applied // (remapping not triggered yet). Consumed by the next edit session and updated when changes are committed at the end of the edit session. // // Consider a function F containing a call to function G. While G is being executed, F is updated a couple of times (in two edit sessions) // before the thread returns from G and is remapped to the latest version of F. At the start of the second edit session, // the active instruction reported by the debugger is still at the original location since function F has not been remapped yet (G has not returned yet). // // '>' indicates an active statement instruction for non-leaf frame reported by the debugger. // v1 - before first edit, G executing // v2 - after first edit, G still executing // v3 - after second edit and G returned // // F v1: F v2: F v3: // 0: nop 0: nop 0: nop // 1> G() 1> nop 1: nop // 2: nop 2: G() 2: nop // 3: nop 3: nop 3> G() // // When entering a break state we query the debugger for current active statements. // The returned statements reflect the current state of the threads in the runtime. // When a change is successfully applied we remember changes in active statement spans. // These changes are passed to the next edit session. // We use them to map the spans for active statements returned by the debugger. // // In the above case the sequence of events is // 1st break: get active statements returns (F, v=1, il=1, span1) the active statement is up-to-date // 1st apply: detected span change for active statement (F, v=1, il=1): span1->span2 // 2nd break: previously updated statements contains (F, v=1, il=1)->span2 // get active statements returns (F, v=1, il=1, span1) which is mapped to (F, v=1, il=1, span2) using previously updated statements // 2nd apply: detected span change for active statement (F, v=1, il=1): span2->span3 // 3rd break: previously updated statements contains (F, v=1, il=1)->span3 // get active statements returns (F, v=3, il=3, span3) the active statement is up-to-date // internal ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> NonRemappableRegions { get; private set; } internal EditSession EditSession { get; private set; } private readonly HashSet<Guid> _modulesPreparedForUpdate = new(); private readonly object _modulesPreparedForUpdateGuard = new(); internal readonly DebuggingSessionId Id; /// <summary> /// The solution captured when the debugging session entered run mode (application debugging started), /// or the solution which the last changes committed to the debuggee at the end of edit session were calculated from. /// The solution reflecting the current state of the modules loaded in the debugee. /// </summary> internal readonly CommittedSolution LastCommittedSolution; internal readonly IManagedEditAndContinueDebuggerService DebuggerService; /// <summary> /// Gets the capabilities of the runtime with respect to applying code changes. /// </summary> internal readonly EditAndContinueCapabilities Capabilities; /// <summary> /// True if the diagnostics produced by the session should be reported to the diagnotic analyzer. /// </summary> internal readonly bool ReportDiagnostics; private readonly DebuggingSessionTelemetry _telemetry; private readonly EditSessionTelemetry _editSessionTelemetry; private PendingSolutionUpdate? _pendingUpdate; private Action<DebuggingSessionTelemetry.Data> _reportTelemetry; internal DebuggingSession( DebuggingSessionId id, Solution solution, IManagedEditAndContinueDebuggerService debuggerService, EditAndContinueCapabilities capabilities, Func<Project, CompilationOutputs> compilationOutputsProvider, IEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>> initialDocumentStates, bool reportDiagnostics) { _compilationOutputsProvider = compilationOutputsProvider; _telemetry = new DebuggingSessionTelemetry(); _editSessionTelemetry = new EditSessionTelemetry(); _reportTelemetry = ReportTelemetry; Id = id; Capabilities = capabilities; DebuggerService = debuggerService; LastCommittedSolution = new CommittedSolution(this, solution, initialDocumentStates); NonRemappableRegions = ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty; EditSession = new EditSession(this, _editSessionTelemetry, inBreakState: false); ReportDiagnostics = reportDiagnostics; } public void Dispose() { _cancellationSource.Cancel(); // Consider: Some APIs on DebuggingSession (GetDocumentDiagnostics, OnSourceFileUpdated, GetXxxSpansAsync) can be called at any point in time. // These APIs should not be using the readers being disposed here, but there is no guarantee. Consider refactoring that would guarantee correctness. foreach (var reader in GetBaselineModuleReaders()) { reader.Dispose(); } _cancellationSource.Dispose(); } internal Task OnSourceFileUpdatedAsync(Document document) => LastCommittedSolution.OnSourceFileUpdatedAsync(document, _cancellationSource.Token); internal void StorePendingUpdate(Solution solution, SolutionUpdate update) { var previousPendingUpdate = Interlocked.Exchange(ref _pendingUpdate, new PendingSolutionUpdate( solution, update.EmitBaselines, update.ModuleUpdates.Updates, update.NonRemappableRegions)); // commit/discard was not called: Contract.ThrowIfFalse(previousPendingUpdate == null); } internal PendingSolutionUpdate RetrievePendingUpdate() { var pendingUpdate = Interlocked.Exchange(ref _pendingUpdate, null); Contract.ThrowIfNull(pendingUpdate); return pendingUpdate; } private void EndEditSession(out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = EditSession.GetDocumentsWithReportedDiagnostics(); var editSessionTelemetryData = EditSession.Telemetry.GetDataAndClear(); // TODO: report a separate telemetry data for hot reload sessions to preserve the semantics of the current telemetry data // https://github.com/dotnet/roslyn/issues/52128 if (EditSession.InBreakState) { _telemetry.LogEditSession(editSessionTelemetryData); } } public void EndSession(out ImmutableArray<DocumentId> documentsToReanalyze, out DebuggingSessionTelemetry.Data telemetryData) { EndEditSession(out documentsToReanalyze); telemetryData = _telemetry.GetDataAndClear(); _reportTelemetry(telemetryData); Dispose(); } public void BreakStateEntered(out ImmutableArray<DocumentId> documentsToReanalyze) => RestartEditSession(inBreakState: true, out documentsToReanalyze); internal void RestartEditSession(bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) { EndEditSession(out documentsToReanalyze); EditSession = new EditSession(this, EditSession.Telemetry, inBreakState); } private ImmutableArray<IDisposable> GetBaselineModuleReaders() { lock (_projectEmitBaselinesGuard) { return _initialBaselineModuleReaders.ToImmutableArrayOrEmpty(); } } internal CompilationOutputs GetCompilationOutputs(Project project) => _compilationOutputsProvider(project); internal bool AddModulePreparedForUpdate(Guid mvid) { lock (_modulesPreparedForUpdateGuard) { return _modulesPreparedForUpdate.Add(mvid); } } public void CommitSolutionUpdate(PendingSolutionUpdate update) { // Save new non-remappable regions for the next edit session. // If no edits were made the pending list will be empty and we need to keep the previous regions. var nonRemappableRegions = GroupToImmutableDictionary( from moduleRegions in update.NonRemappableRegions from region in moduleRegions.Regions group region.Region by new ManagedMethodId(moduleRegions.ModuleId, region.Method)); if (nonRemappableRegions.Count > 0) { NonRemappableRegions = nonRemappableRegions; } // update baselines: lock (_projectEmitBaselinesGuard) { foreach (var (projectId, baseline) in update.EmitBaselines) { _projectEmitBaselines[projectId] = baseline; } } LastCommittedSolution.CommitSolution(update.Solution); } /// <summary> /// Reads the MVID of a compiled project. /// </summary> /// <returns> /// An MVID and an error message to report, in case an IO exception occurred while reading the binary. /// The MVID is default if either project not built, or an it can't be read from the module binary. /// </returns> public async Task<(Guid Mvid, Diagnostic? Error)> GetProjectModuleIdAsync(Project project, CancellationToken cancellationToken) { lock (_projectModuleIdsGuard) { if (_projectModuleIds.TryGetValue(project.Id, out var id)) { return id; } } (Guid Mvid, Diagnostic? Error) ReadMvid() { var outputs = GetCompilationOutputs(project); try { return (outputs.ReadAssemblyModuleVersionId(), Error: null); } catch (Exception e) when (e is FileNotFoundException or DirectoryNotFoundException) { return (Mvid: Guid.Empty, Error: null); } catch (Exception e) { var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); return (Mvid: Guid.Empty, Error: Diagnostic.Create(descriptor, Location.None, new[] { outputs.AssemblyDisplayPath, e.Message })); } } var newId = await Task.Run(ReadMvid, cancellationToken).ConfigureAwait(false); lock (_projectModuleIdsGuard) { if (_projectModuleIds.TryGetValue(project.Id, out var id)) { return id; } _moduleIds[newId.Mvid] = project.Id; return _projectModuleIds[project.Id] = newId; } } public bool TryGetProjectId(Guid moduleId, [NotNullWhen(true)] out ProjectId? projectId) { lock (_projectModuleIdsGuard) { return _moduleIds.TryGetValue(moduleId, out projectId); } } /// <summary> /// Get <see cref="EmitBaseline"/> for given project. /// </summary> /// <returns>True unless the project outputs can't be read.</returns> public bool TryGetOrCreateEmitBaseline(Project project, out ImmutableArray<Diagnostic> diagnostics, [NotNullWhen(true)] out EmitBaseline? baseline) { lock (_projectEmitBaselinesGuard) { if (_projectEmitBaselines.TryGetValue(project.Id, out baseline)) { diagnostics = ImmutableArray<Diagnostic>.Empty; return true; } } var outputs = GetCompilationOutputs(project); if (!TryCreateInitialBaseline(outputs, out diagnostics, out var newBaseline, out var debugInfoReaderProvider, out var metadataReaderProvider)) { // Unable to read the DLL/PDB at this point (it might be open by another process). // Don't cache the failure so that the user can attempt to apply changes again. return false; } lock (_projectEmitBaselinesGuard) { if (_projectEmitBaselines.TryGetValue(project.Id, out baseline)) { metadataReaderProvider.Dispose(); debugInfoReaderProvider.Dispose(); return true; } _projectEmitBaselines[project.Id] = newBaseline; _initialBaselineModuleReaders.Add(metadataReaderProvider); _initialBaselineModuleReaders.Add(debugInfoReaderProvider); } baseline = newBaseline; return true; } private static unsafe bool TryCreateInitialBaseline( CompilationOutputs compilationOutputs, out ImmutableArray<Diagnostic> diagnostics, [NotNullWhen(true)] out EmitBaseline? baseline, [NotNullWhen(true)] out DebugInformationReaderProvider? debugInfoReaderProvider, [NotNullWhen(true)] out MetadataReaderProvider? metadataReaderProvider) { // Read the metadata and symbols from the disk. Close the files as soon as we are done emitting the delta to minimize // the time when they are being locked. Since we need to use the baseline that is produced by delta emit for the subsequent // delta emit we need to keep the module metadata and symbol info backing the symbols of the baseline alive in memory. // Alternatively, we could drop the data once we are done with emitting the delta and re-emit the baseline again // when we need it next time and the module is loaded. diagnostics = default; baseline = null; debugInfoReaderProvider = null; metadataReaderProvider = null; var success = false; var fileBeingRead = compilationOutputs.PdbDisplayPath; try { debugInfoReaderProvider = compilationOutputs.OpenPdb(); if (debugInfoReaderProvider == null) { throw new FileNotFoundException(); } var debugInfoReader = debugInfoReaderProvider.CreateEditAndContinueMethodDebugInfoReader(); fileBeingRead = compilationOutputs.AssemblyDisplayPath; metadataReaderProvider = compilationOutputs.OpenAssemblyMetadata(prefetch: true); if (metadataReaderProvider == null) { throw new FileNotFoundException(); } var metadataReader = metadataReaderProvider.GetMetadataReader(); var moduleMetadata = ModuleMetadata.CreateFromMetadata((IntPtr)metadataReader.MetadataPointer, metadataReader.MetadataLength); baseline = EmitBaseline.CreateInitialBaseline( moduleMetadata, debugInfoReader.GetDebugInfo, debugInfoReader.GetLocalSignature, debugInfoReader.IsPortable); success = true; return true; } catch (Exception e) { var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); diagnostics = ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { fileBeingRead, e.Message })); } finally { if (!success) { debugInfoReaderProvider?.Dispose(); metadataReaderProvider?.Dispose(); } } return false; } private static ImmutableDictionary<K, ImmutableArray<V>> GroupToImmutableDictionary<K, V>(IEnumerable<IGrouping<K, V>> items) where K : notnull { var builder = ImmutableDictionary.CreateBuilder<K, ImmutableArray<V>>(); foreach (var item in items) { builder.Add(item.Key, item.ToImmutableArray()); } return builder.ToImmutable(); } public async ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { try { // Not a C# or VB project. var project = document.Project; if (!project.SupportsEditAndContinue()) { return ImmutableArray<Diagnostic>.Empty; } // Document does not compile to the assembly (e.g. cshtml files, .g.cs files generated for completion only) if (!document.DocumentState.SupportsEditAndContinue()) { return ImmutableArray<Diagnostic>.Empty; } // Do not analyze documents (and report diagnostics) of projects that have not been built. // Allow user to make any changes in these documents, they won't be applied within the current debugging session. // Do not report the file read error - it might be an intermittent issue. The error will be reported when the // change is attempted to be applied. var (mvid, _) = await GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false); if (mvid == Guid.Empty) { return ImmutableArray<Diagnostic>.Empty; } var (oldDocument, oldDocumentState) = await LastCommittedSolution.GetDocumentAndStateAsync(document.Id, document, cancellationToken).ConfigureAwait(false); if (oldDocumentState is CommittedSolution.DocumentState.OutOfSync or CommittedSolution.DocumentState.Indeterminate or CommittedSolution.DocumentState.DesignTimeOnly) { // Do not report diagnostics for existing out-of-sync documents or design-time-only documents. return ImmutableArray<Diagnostic>.Empty; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldDocument, document, activeStatementSpanProvider, Capabilities, cancellationToken).ConfigureAwait(false); if (analysis.HasChanges) { // Once we detected a change in a document let the debugger know that the corresponding loaded module // is about to be updated, so that it can start initializing it for EnC update, reducing the amount of time applying // the change blocks the UI when the user "continues". if (AddModulePreparedForUpdate(mvid)) { // fire and forget: _ = Task.Run(() => DebuggerService.PrepareModuleForUpdateAsync(mvid, cancellationToken), cancellationToken); } } if (analysis.RudeEditErrors.IsEmpty) { return ImmutableArray<Diagnostic>.Empty; } EditSession.Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors); // track the document, so that we can refresh or clean diagnostics at the end of edit session: EditSession.TrackDocumentWithReportedDiagnostics(document.Id); var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); return analysis.RudeEditErrors.SelectAsArray((e, t) => e.ToDiagnostic(t), tree); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ImmutableArray<Diagnostic>.Empty; } } public async ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync( Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var solutionUpdate = await EditSession.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (solutionUpdate.ModuleUpdates.Status == ManagedModuleUpdateStatus.Ready) { StorePendingUpdate(solution, solutionUpdate); } // Note that we may return empty deltas if all updates have been deferred. // The debugger will still call commit or discard on the update batch. return new EmitSolutionUpdateResults(solutionUpdate.ModuleUpdates, solutionUpdate.Diagnostics, solutionUpdate.DocumentsWithRudeEdits); } public void CommitSolutionUpdate(out ImmutableArray<DocumentId> documentsToReanalyze) { var pendingUpdate = RetrievePendingUpdate(); CommitSolutionUpdate(pendingUpdate); // restart edit session with no active statements (switching to run mode): RestartEditSession(inBreakState: false, out documentsToReanalyze); } public void DiscardSolutionUpdate() => _ = RetrievePendingUpdate(); public async ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { if (!EditSession.InBreakState) { return default; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); using var _1 = PooledDictionary<string, ArrayBuilder<(ProjectId, int)>>.GetInstance(out var documentIndicesByMappedPath); using var _2 = PooledHashSet<ProjectId>.GetInstance(out var projectIds); // Construct map of mapped file path to a text document in the current solution // and a set of projects these documents are contained in. for (var i = 0; i < documentIds.Length; i++) { var documentId = documentIds[i]; var document = await solution.GetTextDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); if (document?.FilePath == null) { // document has been deleted or has no path (can't have an active statement anymore): continue; } // Multiple documents may have the same path (linked file). // The documents represent the files that #line directives map to. // Documents that have the same path must have different project id. documentIndicesByMappedPath.MultiAdd(document.FilePath, (documentId.ProjectId, i)); projectIds.Add(documentId.ProjectId); } using var _3 = PooledDictionary<ActiveStatement, ArrayBuilder<(DocumentId unmappedDocumentId, LinePositionSpan span)>>.GetInstance( out var activeStatementsInChangedDocuments); // Analyze changed documents in projects containing active statements: foreach (var projectId in projectIds) { var newProject = solution.GetRequiredProject(projectId); var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); await foreach (var documentId in EditSession.GetChangedDocumentsAsync(LastCommittedSolution, newProject, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newDocument = await solution.GetRequiredDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. continue; } var oldDocumentActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); var analysis = await analyzer.AnalyzeDocumentAsync( LastCommittedSolution.GetRequiredProject(documentId.ProjectId), baseActiveStatements, newDocument, newActiveStatementSpans: ImmutableArray<LinePositionSpan>.Empty, Capabilities, cancellationToken).ConfigureAwait(false); // Document content did not change or unable to determine active statement spans in a document with syntax errors: if (!analysis.ActiveStatements.IsDefault) { for (var i = 0; i < oldDocumentActiveStatements.Length; i++) { // Note: It is possible that one active statement appears in multiple documents if the documents represent a linked file. // Example (old and new contents): // #if Condition #if Condition // #line 1 a.txt #line 1 a.txt // [|F(1);|] [|F(1000);|] // #else #else // #line 1 a.txt #line 1 a.txt // [|F(2);|] [|F(2);|] // #endif #endif // // In the new solution the AS spans are different depending on which document view of the same file we are looking at. // Different views correspond to different projects. activeStatementsInChangedDocuments.MultiAdd(oldDocumentActiveStatements[i].Statement, (analysis.DocumentId, analysis.ActiveStatements[i].Span)); } } } } using var _4 = ArrayBuilder<ImmutableArray<ActiveStatementSpan>>.GetInstance(out var spans); spans.AddMany(ImmutableArray<ActiveStatementSpan>.Empty, documentIds.Length); foreach (var (mappedPath, documentBaseActiveStatements) in baseActiveStatements.DocumentPathMap) { if (documentIndicesByMappedPath.TryGetValue(mappedPath, out var indices)) { // translate active statements from base solution to the new solution, if the documents they are contained in changed: foreach (var (projectId, index) in indices) { spans[index] = documentBaseActiveStatements.SelectAsArray( activeStatement => { LinePositionSpan span; DocumentId? unmappedDocumentId; if (activeStatementsInChangedDocuments.TryGetValue(activeStatement, out var newSpans)) { (unmappedDocumentId, span) = newSpans.Single(ns => ns.unmappedDocumentId.ProjectId == projectId); } else { span = activeStatement.Span; unmappedDocumentId = null; } return new ActiveStatementSpan(activeStatement.Ordinal, span, activeStatement.Flags, unmappedDocumentId); }); } } } documentIndicesByMappedPath.FreeValues(); activeStatementsInChangedDocuments.FreeValues(); return spans.ToImmutable(); } public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument mappedDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { if (!EditSession.InBreakState) { return ImmutableArray<ActiveStatementSpan>.Empty; } if (!mappedDocument.State.SupportsEditAndContinue()) { return ImmutableArray<ActiveStatementSpan>.Empty; } Contract.ThrowIfNull(mappedDocument.FilePath); var newProject = mappedDocument.Project; var newSolution = newProject.Solution; var oldProject = LastCommittedSolution.GetProject(newProject.Id); if (oldProject == null) { // project has been added, no changes in active statement spans: return ImmutableArray<ActiveStatementSpan>.Empty; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.DocumentPathMap.TryGetValue(mappedDocument.FilePath, out var oldMappedDocumentActiveStatements)) { // no active statements in this document return ImmutableArray<ActiveStatementSpan>.Empty; } var newDocumentActiveStatementSpans = await activeStatementSpanProvider(mappedDocument.Id, mappedDocument.FilePath, cancellationToken).ConfigureAwait(false); if (newDocumentActiveStatementSpans.IsEmpty) { return ImmutableArray<ActiveStatementSpan>.Empty; } var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); using var _ = ArrayBuilder<ActiveStatementSpan>.GetInstance(out var adjustedMappedSpans); // Start with the current locations of the tracking spans. adjustedMappedSpans.AddRange(newDocumentActiveStatementSpans); // Update tracking spans to the latest known locations of the active statements contained in changed documents based on their analysis. await foreach (var unmappedDocumentId in EditSession.GetChangedDocumentsAsync(LastCommittedSolution, newProject, cancellationToken).ConfigureAwait(false)) { var newUnmappedDocument = await newSolution.GetRequiredDocumentAsync(unmappedDocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var (oldUnmappedDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newUnmappedDocument.Id, newUnmappedDocument, cancellationToken).ConfigureAwait(false); if (oldUnmappedDocument == null) { // document out-of-date continue; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldUnmappedDocument, newUnmappedDocument, activeStatementSpanProvider, Capabilities, cancellationToken).ConfigureAwait(false); // Document content did not change or unable to determine active statement spans in a document with syntax errors: if (!analysis.ActiveStatements.IsDefault) { foreach (var activeStatement in analysis.ActiveStatements) { var i = adjustedMappedSpans.FindIndex((s, ordinal) => s.Ordinal == ordinal, activeStatement.Ordinal); if (i >= 0) { adjustedMappedSpans[i] = new ActiveStatementSpan(activeStatement.Ordinal, activeStatement.Span, activeStatement.Flags, unmappedDocumentId); } } } } return adjustedMappedSpans.ToImmutable(); } public async ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { try { // It is allowed to call this method before entering or after exiting break mode. In fact, the VS debugger does so. // We return null since there the concept of active statement only makes sense during break mode. if (!EditSession.InBreakState) { return null; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) { return null; } var documentId = await FindChangedDocumentContainingUnmappedActiveStatementAsync(baseActiveStatements, instructionId.Method.Module, baseActiveStatement, solution, cancellationToken).ConfigureAwait(false); if (documentId == null) { // Active statement not found in any changed documents, return its last position: return baseActiveStatement.Span; } var newDocument = await solution.GetDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); if (newDocument == null) { // The document has been deleted. return null; } var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // document out-of-date return null; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldDocument, newDocument, activeStatementSpanProvider, Capabilities, cancellationToken).ConfigureAwait(false); if (!analysis.HasChanges) { // Document content did not change: return baseActiveStatement.Span; } if (analysis.HasSyntaxErrors) { // Unable to determine active statement spans in a document with syntax errors: return null; } Contract.ThrowIfTrue(analysis.ActiveStatements.IsDefault); return analysis.ActiveStatements.GetStatement(baseActiveStatement.Ordinal).Span; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } /// <summary> /// Called by the debugger to determine whether a non-leaf active statement is in an exception region, /// so it can determine whether the active statement can be remapped. This only happens when the EnC is about to apply changes. /// If the debugger determines we can remap active statements, the application of changes proceeds. /// /// TODO: remove (https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1310859) /// </summary> /// <returns> /// True if the instruction is located within an exception region, false if it is not, null if the instruction isn't an active statement in a changed method /// or the exception regions can't be determined. /// </returns> public async ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { try { if (!EditSession.InBreakState) { return null; } // This method is only called when the EnC is about to apply changes, at which point all active statements and // their exception regions will be needed. Hence it's not necessary to scope this query down to just the instruction // the debugger is interested at this point while not calculating the others. var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) { return null; } var documentId = await FindChangedDocumentContainingUnmappedActiveStatementAsync(baseActiveStatements, instructionId.Method.Module, baseActiveStatement, solution, cancellationToken).ConfigureAwait(false); if (documentId == null) { // the active statement is contained in an unchanged document, thus it doesn't matter whether it's in an exception region or not return null; } var newDocument = solution.GetRequiredDocument(documentId); var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. return null; } var analyzer = newDocument.Project.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldDocumentActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); return oldDocumentActiveStatements.GetStatement(baseActiveStatement.Ordinal).ExceptionRegions.IsActiveStatementCovered; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } private async Task<DocumentId?> FindChangedDocumentContainingUnmappedActiveStatementAsync( ActiveStatementsMap activeStatementsMap, Guid moduleId, ActiveStatement baseActiveStatement, Solution newSolution, CancellationToken cancellationToken) { DocumentId? documentId = null; if (TryGetProjectId(moduleId, out var projectId)) { var oldProject = LastCommittedSolution.GetProject(projectId); if (oldProject == null) { // project has been added (should have no active statements under normal circumstances) return null; } var newProject = newSolution.GetProject(projectId); if (newProject == null) { // project has been deleted return null; } documentId = await GetChangedDocumentContainingUnmappedActiveStatementAsync(activeStatementsMap, LastCommittedSolution, newProject, baseActiveStatement, cancellationToken).ConfigureAwait(false); } else { // Search for the document in all changed projects in the solution. using var documentFoundCancellationSource = new CancellationTokenSource(); using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(documentFoundCancellationSource.Token, cancellationToken); async Task GetTaskAsync(ProjectId projectId) { var newProject = newSolution.GetRequiredProject(projectId); var id = await GetChangedDocumentContainingUnmappedActiveStatementAsync(activeStatementsMap, LastCommittedSolution, newProject, baseActiveStatement, linkedTokenSource.Token).ConfigureAwait(false); Interlocked.CompareExchange(ref documentId, id, null); if (id != null) { documentFoundCancellationSource.Cancel(); } } var tasks = newSolution.ProjectIds.Select(GetTaskAsync); try { await Task.WhenAll(tasks).ConfigureAwait(false); } catch (OperationCanceledException) when (documentFoundCancellationSource.IsCancellationRequested) { // nop: cancelled because we found the document } } return documentId; } // Enumerate all changed documents in the project whose module contains the active statement. // For each such document enumerate all #line directives to find which maps code to the span that contains the active statement. private static async ValueTask<DocumentId?> GetChangedDocumentContainingUnmappedActiveStatementAsync(ActiveStatementsMap baseActiveStatements, CommittedSolution oldSolution, Project newProject, ActiveStatement activeStatement, CancellationToken cancellationToken) { var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); await foreach (var documentId in EditSession.GetChangedDocumentsAsync(oldSolution, newProject, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newDocument = newProject.GetRequiredDocument(documentId); var (oldDocument, _) = await oldSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. return null; } var oldActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); if (oldActiveStatements.Any(s => s.Statement == activeStatement)) { return documentId; } } return null; } private static void ReportTelemetry(DebuggingSessionTelemetry.Data data) { // report telemetry (fire and forget): _ = Task.Run(() => LogTelemetry(data, Logger.Log, LogAggregator.GetNextId)); } private static void LogTelemetry(DebuggingSessionTelemetry.Data debugSessionData, Action<FunctionId, LogMessage> log, Func<int> getNextId) { const string SessionId = nameof(SessionId); const string EditSessionId = nameof(EditSessionId); var debugSessionId = getNextId(); log(FunctionId.Debugging_EncSession, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map["SessionCount"] = debugSessionData.EditSessionData.Length; map["EmptySessionCount"] = debugSessionData.EmptyEditSessionCount; })); foreach (var editSessionData in debugSessionData.EditSessionData) { var editSessionId = getNextId(); log(FunctionId.Debugging_EncSession_EditSession, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["HadCompilationErrors"] = editSessionData.HadCompilationErrors; map["HadRudeEdits"] = editSessionData.HadRudeEdits; map["HadValidChanges"] = editSessionData.HadValidChanges; map["HadValidInsignificantChanges"] = editSessionData.HadValidInsignificantChanges; map["RudeEditsCount"] = editSessionData.RudeEdits.Length; map["EmitDeltaErrorIdCount"] = editSessionData.EmitErrorIds.Length; })); foreach (var errorId in editSessionData.EmitErrorIds) { log(FunctionId.Debugging_EncSession_EditSession_EmitDeltaErrorId, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["ErrorId"] = errorId; })); } foreach (var (editKind, syntaxKind) in editSessionData.RudeEdits) { log(FunctionId.Debugging_EncSession_EditSession_RudeEdit, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["RudeEditKind"] = editKind; map["RudeEditSyntaxKind"] = syntaxKind; map["RudeEditBlocking"] = editSessionData.HadRudeEdits; })); } } } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly DebuggingSession _instance; public TestAccessor(DebuggingSession instance) => _instance = instance; public void SetNonRemappableRegions(ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> nonRemappableRegions) => _instance.NonRemappableRegions = nonRemappableRegions; public ImmutableHashSet<Guid> GetModulesPreparedForUpdate() { lock (_instance._modulesPreparedForUpdateGuard) { return _instance._modulesPreparedForUpdate.ToImmutableHashSet(); } } public EmitBaseline GetProjectEmitBaseline(ProjectId id) { lock (_instance._projectEmitBaselinesGuard) { return _instance._projectEmitBaselines[id]; } } public ImmutableArray<IDisposable> GetBaselineModuleReaders() => _instance.GetBaselineModuleReaders(); public PendingSolutionUpdate? GetPendingSolutionUpdate() => _instance._pendingUpdate; public void SetTelemetryLogger(Action<FunctionId, LogMessage> logger, Func<int> getNextId) => _instance._reportTelemetry = data => LogTelemetry(data, logger, getNextId); } } }
49.205572
271
0.616696
[ "MIT" ]
333fred/roslyn
src/Features/Core/Portable/EditAndContinue/DebuggingSession.cs
51,225
C#
using UnityEngine; using Antares.Vizio.Runtime; using System.Collections.Generic; using System.IO; using Unibill.Demo; [VisualLogicBlock("Less Than Test", "Smart Blocks/Tests")] public class LessThanTestNode : LogicBlock { [Parameter(VariableType.In, typeof(int))] public Variable Num1; [Parameter(VariableType.In, typeof(int))] public Variable Num2; [Parameter(VariableType.Out, typeof(int))] public Variable result; public override void OnInitializeDefaultData() { RegisterOutputTrigger("True"); RegisterOutputTrigger("False"); } [EntryTrigger] public void In() { if ((int) Num1.Value < (int) Num2.Value) { result.Value = true; ActivateTrigger("True"); } else { result.Value = false; ActivateTrigger("False"); } } }
19.325
58
0.708926
[ "Apache-2.0" ]
MatrixNAN/Unity-Antares-Universe-Nodes
LessThanTestNode.cs
773
C#
namespace SwedbankPay.Sdk.PaymentInstruments.Invoice { /// <summary> /// Object containing details needed for reversing a invoice payment. /// </summary> public class InvoicePaymentReversalRequest { /// <summary> /// Instantiates a new <see cref="InvoicePaymentReversalRequest"/> with the provided parameters. /// </summary> /// <param name="amount">The <seealso cref="Amount"/> to return to the payer.</param> /// <param name="vatAmount">The <seealso cref="Amount"/> to return from the VAT amount.</param> /// <param name="description">A textual description of the reversal.</param> /// <param name="payeeReference">The payeeReference is the receipt/invoice number if receiptReference is not defined, /// which is a unique reference with max 50 characters set by the merchant system. /// This must be unique for each operation and must follow the regex pattern [\w-]*.</param> /// <param name="receiptReference">The receiptReference is a reference from the merchant system. /// This reference is used as an invoice/receipt number.</param> public InvoicePaymentReversalRequest(Amount amount, Amount vatAmount, string description, string payeeReference,string receiptReference) { Transaction = new ReversalTransaction(amount, vatAmount, description, payeeReference, receiptReference); } /// <summary> /// Details about the invoice being reversed. /// </summary> public IReversalTransaction Transaction { get; } } }
55.965517
145
0.665434
[ "Apache-2.0" ]
Nacorpio/swedbank-pay-sdk-dotnet
src/SwedbankPay.Sdk/PaymentInstruments/Invoice/InvoicePaymentReversalRequest.cs
1,625
C#
using System; using System.Collections.Generic; using System.Text; namespace MetaDslx.CodeGeneration { public class CodeBuilder { private StringBuilder _sb; private string _indent; public CodeBuilder() { _sb = new StringBuilder(); _indent = ""; } public void IncIndent() { _indent += " "; } public void DecIndent() { if (_indent.Length >= 4) _indent = _indent.Substring(4); } public void WriteIndent() { _sb.Append(_indent); } public void Write(string text) { _sb.Append(text); } public void Write(string format, params object[] args) { _sb.Append(string.Format(format, args)); } public void WriteLine() { _sb.AppendLine(); } public void WriteLine(string text) { this.WriteIndent(); this.Write(text); this.WriteLine(); } public void WriteLine(string format, params object[] args) { this.WriteIndent(); this.Write(format, args); this.WriteLine(); } public override string ToString() { return _sb.ToString(); } } }
20.235294
68
0.486192
[ "Apache-2.0" ]
balazssimon/meta-cs
src/Main/MetaDslx.CodeAnalysis.Meta/CodeGeneration/CodeBuilder.cs
1,378
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace System.ComponentModel.Design { /// <summary> /// Provides access to get and set option values for a designer. /// </summary> public abstract class DesignerOptionService : IDesignerOptionService { private DesignerOptionCollection _options; /// <summary> /// Returns the options collection for this service. There is /// always a global options collection that contains child collections. /// </summary> public DesignerOptionCollection Options { get => _options ?? (_options = new DesignerOptionCollection(this, null, string.Empty, null)); } /// <summary> /// Creates a new DesignerOptionCollection with the given name, and adds it to /// the given parent. The "value" parameter specifies an object whose public /// properties will be used in the Properties collection of the option collection. /// The value parameter can be null if this options collection does not offer /// any properties. Properties will be wrapped in such a way that passing /// anything into the component parameter of the property descriptor will be /// ignored and the value object will be substituted. /// </summary> protected DesignerOptionCollection CreateOptionCollection(DesignerOptionCollection parent, string name, object value) { if (parent == null) { throw new ArgumentNullException(nameof(parent)); } if (name == null) { throw new ArgumentNullException(nameof(name)); } if (name.Length == 0) { throw new ArgumentException(SR.Format(SR.InvalidArgumentValue, "name.Length"), nameof(name)); } return new DesignerOptionCollection(this, parent, name, value); } /// <summary> /// Retrieves the property descriptor for the given page / value name. Returns /// null if the property couldn't be found. /// </summary> [RequiresUnreferencedCode("The Type of DesignerOptionCollection's value cannot be statically discovered.")] private PropertyDescriptor GetOptionProperty(string pageName, string valueName) { if (pageName == null) { throw new ArgumentNullException(nameof(pageName)); } if (valueName == null) { throw new ArgumentNullException(nameof(valueName)); } string[] optionNames = pageName.Split('\\'); DesignerOptionCollection options = Options; foreach (string optionName in optionNames) { options = options[optionName]; if (options == null) { return null; } } return options.Properties[valueName]; } /// <summary> /// This method is called on demand the first time a user asks for child /// options or properties of an options collection. /// </summary> protected virtual void PopulateOptionCollection(DesignerOptionCollection options) { } /// <summary> /// This method must be implemented to show the options dialog UI for the given object. /// </summary> protected virtual bool ShowDialog(DesignerOptionCollection options, object optionObject) => false; /// <summary> /// Gets the value of an option defined in this package. /// </summary> [RequiresUnreferencedCode("The option value's Type cannot be statically discovered.")] object IDesignerOptionService.GetOptionValue(string pageName, string valueName) { PropertyDescriptor optionProp = GetOptionProperty(pageName, valueName); return optionProp?.GetValue(null); } /// <summary> /// Sets the value of an option defined in this package. /// </summary> [RequiresUnreferencedCode("The option value's Type cannot be statically discovered.")] void IDesignerOptionService.SetOptionValue(string pageName, string valueName, object value) { PropertyDescriptor optionProp = GetOptionProperty(pageName, valueName); optionProp?.SetValue(null, value); } /// <summary> /// The DesignerOptionCollection class is a collection that contains /// other DesignerOptionCollection objects. This forms a tree of options, /// with each branch of the tree having a name and a possible collection of /// properties. Each parent branch of the tree contains a union of the /// properties if all the branch's children. /// </summary> [TypeConverter(typeof(DesignerOptionConverter))] [Editor("", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public sealed class DesignerOptionCollection : IList { private readonly DesignerOptionService _service; private readonly object _value; private ArrayList _children; private PropertyDescriptorCollection _properties; /// <summary> /// Creates a new DesignerOptionCollection. /// </summary> internal DesignerOptionCollection(DesignerOptionService service, DesignerOptionCollection parent, string name, object value) { _service = service; Parent = parent; Name = name; _value = value; if (Parent != null) { parent._properties = null; if (Parent._children == null) { Parent._children = new ArrayList(1); } Parent._children.Add(this); } } /// <summary> /// The count of child options collections this collection contains. /// </summary> public int Count { get { EnsurePopulated(); return _children.Count; } } /// <summary> /// The name of this collection. Names are programmatic names and are not /// localized. A name search is case insensitive. /// </summary> public string Name { get; } /// <summary> /// Returns the parent collection object, or null if there is no parent. /// </summary> public DesignerOptionCollection Parent { get; } /// <summary> /// The collection of properties that this OptionCollection, along with all of /// its children, offers. PropertyDescriptors are taken directly from the /// value passed to CreateObjectCollection and wrapped in an additional property /// descriptor that hides the value object from the user. This means that any /// value may be passed into the "component" parameter of the various /// PropertyDescriptor methods. The value is ignored and is replaced with /// the correct value internally. /// </summary> public PropertyDescriptorCollection Properties { [RequiresUnreferencedCode("The Type of DesignerOptionCollection's value cannot be statically discovered.")] get { if (_properties == null) { ArrayList propList; if (_value != null) { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(_value); propList = new ArrayList(props.Count); foreach (PropertyDescriptor prop in props) { propList.Add(new WrappedPropertyDescriptor(prop, _value)); } } else { propList = new ArrayList(1); } EnsurePopulated(); foreach (DesignerOptionCollection child in _children) { propList.AddRange(child.Properties); } PropertyDescriptor[] propArray = (PropertyDescriptor[])propList.ToArray(typeof(PropertyDescriptor)); _properties = new PropertyDescriptorCollection(propArray, true); } return _properties; } } /// <summary> /// Retrieves the child collection at the given index. /// </summary> public DesignerOptionCollection this[int index] { get { EnsurePopulated(); if (index < 0 || index >= _children.Count) { throw new IndexOutOfRangeException(nameof(index)); } return (DesignerOptionCollection)_children[index]; } } /// <summary> /// Retrieves the child collection at the given name. The name search is case /// insensitive. /// </summary> public DesignerOptionCollection this[string name] { get { EnsurePopulated(); foreach (DesignerOptionCollection child in _children) { if (string.Compare(child.Name, name, true, CultureInfo.InvariantCulture) == 0) { return child; } } return null; } } /// <summary> /// Copies this collection to an array. /// </summary> public void CopyTo(Array array, int index) { EnsurePopulated(); _children.CopyTo(array, index); } /// <summary> /// Called before any access to our collection to force it to become populated. /// </summary> private void EnsurePopulated() { if (_children == null) { _service.PopulateOptionCollection(this); if (_children == null) { _children = new ArrayList(1); } } } /// <summary> /// Returns an enumerator that can be used to iterate this collection. /// </summary> public IEnumerator GetEnumerator() { EnsurePopulated(); return _children.GetEnumerator(); } /// <summary> /// Returns the numerical index of the given value. /// </summary> public int IndexOf(DesignerOptionCollection value) { EnsurePopulated(); return _children.IndexOf(value); } /// <summary> /// Locates the value object to use for getting or setting a property. /// </summary> private static object RecurseFindValue(DesignerOptionCollection options) { if (options._value != null) { return options._value; } foreach (DesignerOptionCollection child in options) { object value = RecurseFindValue(child); if (value != null) { return value; } } return null; } /// <summary> /// Displays a dialog-based user interface that allows the user to /// configure the various options. /// </summary> public bool ShowDialog() { object value = RecurseFindValue(this); if (value == null) { return false; } return _service.ShowDialog(this, value); } /// <summary> /// Private ICollection implementation. /// </summary> bool ICollection.IsSynchronized => false; /// <summary> /// Private ICollection implementation. /// </summary> object ICollection.SyncRoot => this; /// <summary> /// Private IList implementation. /// </summary> bool IList.IsFixedSize => true; /// <summary> /// Private IList implementation. /// </summary> bool IList.IsReadOnly => true; /// <summary> /// Private IList implementation. /// </summary> object IList.this[int index] { get => this[index]; set => throw new NotSupportedException(); } /// <summary> /// Private IList implementation. /// </summary> int IList.Add(object value) => throw new NotSupportedException(); /// <summary> /// Private IList implementation. /// </summary> void IList.Clear() => throw new NotSupportedException(); /// <summary> /// Private IList implementation. /// </summary> bool IList.Contains(object value) { EnsurePopulated(); return _children.Contains(value); } /// <summary> /// Private IList implementation. /// </summary> int IList.IndexOf(object value) { EnsurePopulated(); return _children.IndexOf(value); } /// <summary> /// Private IList implementation. /// </summary> void IList.Insert(int index, object value) => throw new NotSupportedException(); /// <summary> /// Private IList implementation. /// </summary> void IList.Remove(object value) => throw new NotSupportedException(); /// <summary> /// Private IList implementation. /// </summary> void IList.RemoveAt(int index) => throw new NotSupportedException(); /// <summary> /// A special property descriptor that forwards onto a base /// property descriptor but allows any value to be used for the /// "component" parameter. /// </summary> private sealed class WrappedPropertyDescriptor : PropertyDescriptor { private readonly object _target; private readonly PropertyDescriptor _property; internal WrappedPropertyDescriptor(PropertyDescriptor property, object target) : base(property.Name, null) { _property = property; _target = target; } public override AttributeCollection Attributes => _property.Attributes; public override Type ComponentType => _property.ComponentType; public override bool IsReadOnly => _property.IsReadOnly; public override Type PropertyType => _property.PropertyType; public override bool CanResetValue(object component) => _property.CanResetValue(_target); public override object GetValue(object component) => _property.GetValue(_target); public override void ResetValue(object component) => _property.ResetValue(_target); public override void SetValue(object component, object value) => _property.SetValue(_target, value); public override bool ShouldSerializeValue(object component) => _property.ShouldSerializeValue(_target); } } /// <summary> /// The type converter for the designer option collection. /// </summary> internal sealed class DesignerOptionConverter : TypeConverter { public override bool GetPropertiesSupported(ITypeDescriptorContext cxt) => true; [RequiresUnreferencedCode("The Type of value cannot be statically discovered. " + AttributeCollection.FilterRequiresUnreferencedCodeMessage)] public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext cxt, object value, Attribute[] attributes) { PropertyDescriptorCollection props = new PropertyDescriptorCollection(null); if (!(value is DesignerOptionCollection options)) { return props; } foreach (DesignerOptionCollection option in options) { props.Add(new OptionPropertyDescriptor(option)); } foreach (PropertyDescriptor p in options.Properties) { props.Add(p); } return props; } public override object ConvertTo(ITypeDescriptorContext cxt, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string)) { return SR.CollectionConverterText; } return base.ConvertTo(cxt, culture, value, destinationType); } private class OptionPropertyDescriptor : PropertyDescriptor { private readonly DesignerOptionCollection _option; internal OptionPropertyDescriptor(DesignerOptionCollection option) : base(option.Name, null) { _option = option; } public override Type ComponentType => _option.GetType(); public override bool IsReadOnly => true; public override Type PropertyType => _option.GetType(); public override bool CanResetValue(object component) => false; public override object GetValue(object component) => _option; public override void ResetValue(object component) { } public override void SetValue(object component, object value) { } public override bool ShouldSerializeValue(object component) => false; } } } }
37.473988
153
0.528716
[ "MIT" ]
C-xC-c/runtime
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs
19,449
C#
using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; using System; public class Main : MonoBehaviour, IPointerClickHandler { // Transform and Rigidbody Variables [SerializeField] private GameObject Object; [SerializeField] private Rigidbody[] RigidbodyPlayer = new Rigidbody[2]; [SerializeField] private Transform[] TransformPlayer = new Transform[2]; [SerializeField] private Transform[] DieFace1 = new Transform[6]; [SerializeField] private Transform[] DieFace2 = new Transform[6]; [SerializeField] private Transform[] BoardLocation = new Transform[28]; // 28 total properties [SerializeField] private Transform[] Chance = new Transform[16]; // 16 chance cards [SerializeField] private Transform[] Community = new Transform[16]; // 16 community chest cards // Buttons Variables [SerializeField] private Button PlayBtn; [SerializeField] private Button JailFreeBtn; [SerializeField] private Button BailBtn; [SerializeField] private Button BuyBtn; [SerializeField] private Button ExitBtn; // Text Variables [SerializeField] private TextMeshProUGUI PropertyDetailsText; [SerializeField] private TextMeshProUGUI CashText; [SerializeField] private TextMeshProUGUI LogText; [SerializeField] private TextMeshProUGUI PropertiesText; // Panel [SerializeField] private PopupCard PropertyPopup; // Private variables private string propertyName = ""; private string propertyPrice = ""; private string logString = ""; private int[] Cash = new int[2]; private int[] rollValue = new int[2]; private int[] doublesCounter = new int[2]; private int[] jailTurnCounter = new int[2]; private int[] currentIndex = new int[2]; private int[] destinationIndex = new int[2]; private int[] getOutOfJailFree = new int[2]; private int currentPlayer; private float[] lastSqrMagnitude = new float[2]; private float movementSpeed = 6f; private bool[] isInJail = new bool[2]; private bool[] playerTurn = new bool[2]; private bool[] inTransit = new bool[2]; private bool[] rollForRent = new bool[2]; private bool spaceKeyWasPressed; private Vector3[] destinationCoordinates = new Vector3[2]; private Position position; private DieRoll dieRoll; private Positions destinationPosition; private Properties destinationProperty; private Properties selectedProperty; private Property property; private LuckCards luckCards; private Money money; // Start is called before the first frame update void Start() { position = Object.AddComponent<Position>(); dieRoll = Object.AddComponent<DieRoll>(); property = Object.AddComponent<Property>(); luckCards = Object.AddComponent<LuckCards>(); money = Object.AddComponent<Money>(); PlayBtn.onClick.AddListener(PlayBtnOnClick); JailFreeBtn.onClick.AddListener(JailFreeBtnOnClick); BailBtn.onClick.AddListener(BailBtnOnClick); BuyBtn.onClick.AddListener(BuyBtnOnClick); BuyBtn.interactable = false; ExitBtn.onClick.AddListener(ExitBtnOnClick); logString = "Press the Play button or SPACE key to start."; playerTurn[0] = true; // Initialise start of game for (int i = 0; i < 2; i++) { currentIndex[i] = 0; destinationIndex[i] = 0; getOutOfJailFree[i] = 0; Cash[i] = 1500; lastSqrMagnitude[i] = Mathf.Infinity; } } // Update is called once per frame void Update() { triggerPlay(); // Set property detail text string propertyDetails = "Property Name: " + propertyName + "\nProperty Price: " + propertyPrice; PropertyDetailsText.text = propertyDetails; // Set player cash count text CashText.text = "Cash\nPlayer 1: $" + Cash[0] + "\nPlayer 2: $" + Cash[1]; // Check for jail options position.JailOptions(playerTurn, isInJail, getOutOfJailFree, JailFreeBtn, Cash, BailBtn); // Update log LogText.text = "Log:\n" + logString; checkForNegativeCash(); showPropertiesText(); checkTransit(); checkRollForRent(); } // Update for any physics aspects for the game private void FixedUpdate() { if (spaceKeyWasPressed) { resetCardVectors(); getDieResult(); getPlayer(); // Reset space bar pressed for next turn spaceKeyWasPressed = false; } } // Pointer Click Event Handler public void OnPointerClick(PointerEventData eventData) { if (eventData.button == PointerEventData.InputButton.Left) { int linkIndex = TMP_TextUtilities.FindIntersectingLink(PropertiesText, Input.mousePosition, null); if (linkIndex > -1) { selectedProperty = property.FindPropertyByIndex(Int16.Parse(PropertiesText.textInfo.linkInfo[linkIndex].GetLinkID())); PropertyPopup.Show(property, selectedProperty, Cash); } } } // Play Button onClick function void PlayBtnOnClick() { spaceKeyWasPressed = true; if (GameObject.Find("PlayButton").GetComponentInChildren<Text>().text == "Play") { GameObject.Find("PlayButton").GetComponentInChildren<Text>().text = "Roll Dice"; } } // Get out of Jail Button onClick function void JailFreeBtnOnClick() { if (playerTurn[0]) { getOutOfJailFree[0]--; isInJail[0] = false; logString = "Player 1 used Get out of Jail card! "; } else if (playerTurn[1]) { getOutOfJailFree[1]--; isInJail[1] = false; logString = "Player 2 used Get out of Jail card! "; } JailFreeBtn.interactable = false; } // Bail from jail Button onClick function void BailBtnOnClick() { if (playerTurn[0]) { Cash[0] -= 50; isInJail[0] = false; logString = "Player 1 paid for bail! "; } else if (playerTurn[1]) { Cash[1] -= 50; isInJail[1] = false; logString = "Player 2 paid for bail! "; } BailBtn.interactable = false; } // Buy property Button onClick function void BuyBtnOnClick() { int index = property.GetPropertyIndex(destinationIndex[currentPlayer]); property.PropertyList[index].IsOwned = true; property.PropertyList[index].OwnedPlayer = currentPlayer; if (Cash[currentPlayer] >= property.PropertyList[index].BaseAmount) Cash[currentPlayer] -= property.PropertyList[index].BaseAmount; GameObject.Find("BuyButton").GetComponentInChildren<Text>().text = "Buy"; BuyBtn.interactable = false; logString = "Player " + (currentPlayer + 1) + " bought " + property.PropertyList[index].Name + "! "; } // Exit Button onClick function void ExitBtnOnClick() { Application.Quit(); } // Trigger spaceKeyWasPressed boolean and change button text "Play" to "Roll Dice" private void triggerPlay() { if (Input.GetKeyDown(KeyCode.Space)) { spaceKeyWasPressed = true; if (GameObject.Find("PlayButton").GetComponentInChildren<Text>().text == "Play") { GameObject.Find("PlayButton").GetComponentInChildren<Text>().text = "Roll Dice"; } } } // Check for player negative cash private void checkForNegativeCash() { if (playerTurn[0] && money.CheckForNegativeCash(playerTurn[0], Cash[0])) { logString = "Player 1 has negative cash, sell houses, properties or mortgage to avoid bankruptcy! "; } if (playerTurn[1] && money.CheckForNegativeCash(playerTurn[1], Cash[1])) { logString = "Player 2 has negative cash, sell houses, properties or mortgage to avoid bankruptcy! "; } } // Print list of properties owned by players private void showPropertiesText() { // Set property summary for both players; string[] playerProperties = new string[2]; playerProperties[0] = ""; playerProperties[1] = ""; foreach (Properties p in property.PropertyList) { if (p.IsOwned) { // All properties will be displayed in the format <link><color>propertyName</link></link> playerProperties[p.OwnedPlayer] += "<link=" + p.PositionIndex + "><color=" + p.Colour + ">" + p.Name + "</color></link>\n"; } } PropertiesText.text = "Player 1's Properties:\n" + playerProperties[0] + "\nPlayer 2's Properties:\n" + playerProperties[1]; } // Check whether piece is in transit, stop move if token reaches its destination private void checkTransit() { float sqrMagnitude; if (inTransit[0]) { sqrMagnitude = (destinationCoordinates[0] - TransformPlayer[0].position).sqrMagnitude; if (sqrMagnitude > lastSqrMagnitude[0]) { RigidbodyPlayer[0].velocity = Vector3.zero; lastSqrMagnitude[0] = Mathf.Infinity; inTransit[0] = false; actionsAfterMove(0); } else { lastSqrMagnitude[0] = sqrMagnitude; } } if (inTransit[1]) { sqrMagnitude = (destinationCoordinates[1] - TransformPlayer[1].position).sqrMagnitude; if (sqrMagnitude > lastSqrMagnitude[1]) { RigidbodyPlayer[1].velocity = Vector3.zero; lastSqrMagnitude[1] = Mathf.Infinity; inTransit[1] = false; actionsAfterMove(1); } else { lastSqrMagnitude[1] = sqrMagnitude; } } } // If a player lands on a chance, goes to the nearest utility and needs to roll for rent, give them an extra turn to roll private void checkRollForRent() { if (spaceKeyWasPressed) { if (rollForRent[0]) { rollValue[0] = 0; rollValue[1] = 0; rollValue[0] += dieRoll.getDieResult(DieFace1); rollValue[1] += dieRoll.getDieResult(DieFace2); int rentAmount = 10 * (rollValue[0] + rollValue[1]); // Pay owner of property money.TransferCash(Cash, 0, 1, rentAmount); rollForRent[0] = false; playerTurn[0] = false; playerTurn[1] = true; spaceKeyWasPressed = false; } if (rollForRent[1]) { rollValue[0] = 0; rollValue[1] = 0; rollValue[0] += dieRoll.getDieResult(DieFace1); rollValue[1] += dieRoll.getDieResult(DieFace2); int rentAmount = 10 * (rollValue[0] + rollValue[1]); // Pay owner of property money.TransferCash(Cash, 1, 0, rentAmount); rollForRent[1] = false; playerTurn[1] = false; playerTurn[0] = true; spaceKeyWasPressed = false; } } } // Reset all the card vectors from previous turns private void resetCardVectors() { foreach (Transform card in BoardLocation) { card.position = new Vector3(0, 0, -90); } foreach (Transform card in Chance) { card.position = new Vector3(0, 0, -50); } foreach (Transform card in Community) { card.position = new Vector3(0, 0, -50); } } // Get die results private void getDieResult() { rollValue[0] = 0; rollValue[1] = 0; rollValue[0] += dieRoll.getDieResult(DieFace1); rollValue[1] += dieRoll.getDieResult(DieFace2); } // Get current player private void getPlayer() { if (playerTurn[0]) { // Player 1 move setPlayer(0, 1); } else if (playerTurn[1]) { // Player 2 move setPlayer(1, 0); } } // Make player's turn, check who's turn it is and whether they are in jail private void setPlayer(int player, int otherPlayer) { if (playerTurn[player] && !isInJail[player]) { // check for consecutive doubles if (rollValue[0] == rollValue[1]) { doublesCounter[player]++; if (doublesCounter[player] == 3) { playerTurn[player] = false; playerTurn[otherPlayer] = true; logString = "Player " + (player + 1) + " rolled 3 doubles in a row. Go to jail! "; } else { logString = "Doubles rolled! Player " + (player + 1) + " gets an extra roll. "; } } else { doublesCounter[player] = 0; playerTurn[player] = false; playerTurn[otherPlayer] = true; logString = ""; } destinationIndex[player] = currentIndex[player] + rollValue[0] + rollValue[1]; playerMove(player); } // If player is in jail, roll double to get out or after 3 turns and pay $50 fine else if (playerTurn[player] && isInJail[player]) { if (rollValue[0] == rollValue[1]) { jailTurnCounter[player] = 0; isInJail[player] = false; logString = "Player " + (player + 1) + " broke out of jail with a double! "; destinationIndex[player] = currentIndex[player] + rollValue[0] + rollValue[1]; playerMove(player); } else { jailTurnCounter[player]++; if (jailTurnCounter[player] == 3) { jailTurnCounter[player] = 0; Cash[player] -= 50; isInJail[player] = false; logString = "Player " + (player + 1) + " paid a $50 fine and got out of jail. "; destinationIndex[player] = currentIndex[player] + rollValue[0] + rollValue[1]; playerMove(player); } else { logString = "Player " + (player + 1) + " did not roll a double and is still in jail. " + (3 - jailTurnCounter[player]) + " more turns until freed. "; } } doublesCounter[player] = 0; playerTurn[player] = false; playerTurn[otherPlayer] = true; } } // Check for move and if they land on special squares, i.e. GO, pay tax, jail, etc. private void playerMove(int playerIndex) { // Pass GO if (destinationIndex[playerIndex] > 39) { destinationIndex[playerIndex] -= 40; Cash[playerIndex] += 200; logString = "Player " + (playerIndex + 1) + " passed GO, collect $200. "; } // Income Tax position else if (destinationIndex[playerIndex] == 4) { Cash[playerIndex] -= 200; logString = "Player " + (playerIndex + 1) + " paid a $200 tax. "; } // Luxury Tax position else if (destinationIndex[playerIndex] == 38) { Cash[playerIndex] -= 100; logString = "Player " + (playerIndex + 1) + " paid a $100 tax. "; } // Go to Jail if player rolled 3 doubles in a row if (doublesCounter[playerIndex] == 3) { logString = "Player " + (playerIndex + 1) + " got caught! "; destinationIndex[playerIndex] = 10; isInJail[playerIndex] = true; // Even if player rolls a double, end player's turn if they land in jail doublesCounter[playerIndex] = 0; if (playerIndex == 0) { playerTurn[0] = false; playerTurn[1] = true; } else { playerTurn[1] = false; playerTurn[0] = true; } } destinationPosition = position.FindPositionByIndex(destinationIndex[playerIndex]); logString += "Player " + (playerIndex + 1) + " went to " + destinationPosition.PositionName + ". "; // Move to destination point destinationCoordinates[playerIndex] = new Vector3(destinationPosition.X, destinationPosition.Y, destinationPosition.Z); RigidbodyPlayer[playerIndex].velocity = (destinationCoordinates[playerIndex] - TransformPlayer[playerIndex].position).normalized * movementSpeed; inTransit[playerIndex] = true; currentIndex[playerIndex] = destinationIndex[playerIndex]; } // Actions after a move is made, i.e. buy property, landed on chance/community chest, etc private void actionsAfterMove(int playerIndex) { // display card, option to buy title deed if not already owned destinationProperty = property.FindPropertyByIndex(destinationIndex[playerIndex]); if ((destinationProperty.Type == "property" || destinationProperty.Type == "station" || destinationProperty.Type == "utility") && !destinationProperty.IsOwned) { int index = property.GetPropertyIndex(destinationIndex[playerIndex]); if ((index != 0 && destinationIndex[playerIndex] != 1) || (index == 0 && destinationIndex[playerIndex] == 1)) { BoardLocation[index].position = new Vector3(0, 0, 100); currentPlayer = playerIndex; if (Cash[playerIndex] >= destinationProperty.BaseAmount) { BuyBtn.interactable = true; GameObject.Find("BuyButton").GetComponentInChildren<Text>().text = "Buy ($" + destinationProperty.BaseAmount + ")"; logString += "You can buy or roll to pass. "; propertyName = destinationProperty.Name; propertyPrice = "$" + destinationProperty.BaseAmount; } } } else if (destinationProperty.IsOwned && destinationProperty.OwnedPlayer != playerIndex && !destinationProperty.IsMortgaged) { // Disable button if player is not an a purchaseable property BuyBtn.interactable = false; GameObject.Find("BuyButton").GetComponentInChildren<Text>().text = "Can't Buy"; // Rent taken when on other player's property if (destinationProperty.Type == "property" && !destinationProperty.IsMortgaged) { if (!destinationProperty.IsHotel) { // if the property is unimproved but the player owns all properties in the colour group, rent is doubled if (destinationProperty.Houses == 0 && property.CheckForMonopoly(destinationProperty.Colour, destinationProperty.OwnedPlayer)) { money.TransferCash(Cash, playerIndex, destinationProperty.OwnedPlayer, 2 * destinationProperty.Rent[destinationProperty.Houses]); } else { money.TransferCash(Cash, playerIndex, destinationProperty.OwnedPlayer, destinationProperty.Rent[destinationProperty.Houses]); } } else { money.TransferCash(Cash, playerIndex, destinationProperty.OwnedPlayer, destinationProperty.Rent[5]); } } // If on utility, times result from die roll else if (destinationProperty.Type == "utility" && !destinationProperty.IsMortgaged) { int utilitiesOwned = property.NumberOfUtilitiesOwned(destinationProperty.OwnedPlayer); money.TransferCash(Cash, playerIndex, destinationProperty.OwnedPlayer, destinationProperty.Rent[utilitiesOwned - 1] * (rollValue[0] + rollValue[1])); } // If on station, pay rent based on how many stations the other player has else if (destinationProperty.Type == "station" && !destinationProperty.IsMortgaged) { int stationsOwned = property.NumberOfStationsOwned(destinationProperty.OwnedPlayer); money.TransferCash(Cash, playerIndex, destinationProperty.OwnedPlayer, destinationProperty.Rent[stationsOwned - 1]); } } // Disable buy button if player is not on a property if (destinationIndex[playerIndex] == 7 || destinationIndex[playerIndex] == 22 || destinationIndex[playerIndex] == 36 || destinationIndex[playerIndex] == 2 || destinationIndex[playerIndex] == 17 || destinationIndex[playerIndex] == 33 || destinationIndex[playerIndex] == 4 || destinationIndex[playerIndex] == 38 || destinationIndex[playerIndex] % 10 == 0) { GameObject.Find("BuyButton").GetComponentInChildren<Text>().text = "Buy"; BuyBtn.interactable = false; propertyName = ""; propertyPrice = ""; } if (destinationIndex[playerIndex] == 30) { isInJail[playerIndex] = true; doublesCounter[playerIndex] = 0; if (playerIndex == 0) { playerTurn[0] = false; playerTurn[1] = true; } else { playerTurn[1] = false; playerTurn[0] = true; } destinationIndex[playerIndex] = 10; playerMove(playerIndex); } // Chance positions if (destinationIndex[playerIndex] == 7 || destinationIndex[playerIndex] == 22 || destinationIndex[playerIndex] == 36) { int cardIndex = luckCards.GetRandomIndex(); Cards selectedCard = luckCards.ChanceCardList[cardIndex]; Chance[cardIndex].position = new Vector3(0, 0, 100); if (!selectedCard.IsOther) { basicLuckCards(selectedCard, playerIndex); } else { // ADVANCE TOKEN TO NEAREST UTILITY. IF UNOWNED YOU MAY BUY IT FROM BANK. IF OWNED, THROW DICE AND PAY OWNER A TOTAL TEN TIMES THE AMOUNT THROWN if (cardIndex == 3) { currentIndex[playerIndex] = destinationIndex[playerIndex]; // Bottom Chance goes to Electric Company (Index 12) if (currentIndex[playerIndex] == 7) { destinationIndex[playerIndex] = 12; } // Top Chance goes to Water Works (Index 28) else if (currentIndex[playerIndex] == 22) { destinationIndex[playerIndex] = 28; } // Right Chance goes to Electric Company (Index 12) and passes GO else if (currentIndex[playerIndex] == 36) { Cash[playerIndex] += 200; destinationIndex[playerIndex] = 12; } playerMove(playerIndex); destinationProperty = property.FindPropertyByIndex(destinationIndex[playerIndex]); // if property is owned by other player, roll to determine rent if (destinationProperty.IsOwned && destinationProperty.OwnedPlayer != playerIndex) { // Give player an extra "turn" to roll for rent playerTurn[destinationProperty.OwnedPlayer] = false; playerTurn[playerIndex] = true; rollForRent[playerIndex] = true; } } // ADVANCE TOKEN TO THE NEAREST RAILROAD AND PAY OWNER TWICE THE RENTAL TO WHICH HE IS OTHERWISE ENTITLED. IF RAILROAD IS UNOWNED, YOU MAY BUY IT FROM THE BANK // 2 in the set else if (cardIndex == 7 || cardIndex == 13) { currentIndex[playerIndex] = destinationIndex[playerIndex]; // Bottom Chance goes to Pennsylvania RR (Index 15) if (currentIndex[playerIndex] == 7) { destinationIndex[playerIndex] = 15; } // Top Chance goes to B.&O. RR (Index 25) else if (currentIndex[playerIndex] == 22) { destinationIndex[playerIndex] = 25; } // Right Chance goes to Reading RR (Index 5) and passes GO else if (currentIndex[playerIndex] == 36) { Cash[playerIndex] += 200; destinationIndex[playerIndex] = 5; } playerMove(playerIndex); destinationProperty = property.FindPropertyByIndex(destinationIndex[playerIndex]); // if property is owned by other player, pay 2* usual rent if (destinationProperty.IsOwned && destinationProperty.OwnedPlayer != playerIndex && !destinationProperty.IsMortgaged) { money.TransferCash(Cash, playerIndex, destinationProperty.OwnedPlayer, 2 * destinationProperty.Rent[property.NumberOfStationsOwned(destinationProperty.OwnedPlayer) - 1]); } } // THIS CARD MAY BE KEPT UNTIL NEEDED OR SOLD. GET OUT OF JAIL FREE else if (cardIndex == 10) { getOutOfJailFree[playerIndex]++; } // MAKE GENERAL REPAIRS ON ALL YOUR PROPERTY. FOR EACH HOUSE PAY $25, FOR EACH HOTEL $100 else if (cardIndex == 11) { int houseCount = property.GetHouseCount(playerIndex); int hotelCount = property.GetHotelCount(playerIndex); Cash[playerIndex] -= (25 * houseCount) + (100 * hotelCount); } // YOU HAVE BEEN ELECTED CHAIRMAN OF THE BOARD. PAY EACH PLAYER $50 else if (cardIndex == 14) { int otherPlayerIndex; if (playerIndex == 0) { otherPlayerIndex = 1; } else { otherPlayerIndex = 0; } money.TransferCash(Cash, playerIndex, otherPlayerIndex, 50); } // GO BACK 3 SPACES else if (cardIndex == 15) { // Since the closest chance from GO is 7 positions away, it won't go back past GO currentIndex[playerIndex] = destinationIndex[playerIndex]; destinationIndex[playerIndex] -= 3; playerMove(playerIndex); } } } // Community Card positions if (destinationIndex[playerIndex] == 2 || destinationIndex[playerIndex] == 17 || destinationIndex[playerIndex] == 33) { int cardIndex = luckCards.GetRandomIndex(); Cards selectedCard = luckCards.CommunityCardList[cardIndex]; Community[cardIndex].position = new Vector3(0, 0, 100); if (!selectedCard.IsOther) { basicLuckCards(selectedCard, playerIndex); } else { // GRAND OPERA OPENING. COLLECT $50 FROM EVERY PLAYER if (cardIndex == 6) { int otherPlayerIndex; if (playerIndex == 0) { otherPlayerIndex = 1; } else { otherPlayerIndex = 0; } money.TransferCash(Cash, otherPlayerIndex, playerIndex, 50); } // YOU ARE ASSESSED FOR STREET REAPAIRS. $40 PER HOUSE, $115 PER HOTEL else if (cardIndex == 7) { int houseCount = property.GetHouseCount(playerIndex); int hotelCount = property.GetHotelCount(playerIndex); Cash[playerIndex] -= (40 * houseCount) + (115 * hotelCount); } // GET OUT OF JAIL, FREE. THIS CARD MAY BE KEPT UNTIL NEEDED OR SOLD else if (cardIndex == 10) { getOutOfJailFree[playerIndex]++; } } } } // This is for simple chance/community cards where the features are simple, i.e. collect/give xxx amount, move to location, etc. private void basicLuckCards(Cards selectedCard, int playerIndex) { if (selectedCard.IsDebit && !selectedCard.IsMove) { Cash[playerIndex] += selectedCard.DebitAmount; } else if (selectedCard.IsDebit && selectedCard.IsMove) { // If the move to position is less than current position, then it must go through GO for that position if (selectedCard.MoveToIndexPosition < currentIndex[playerIndex]) { Cash[playerIndex] += selectedCard.DebitAmount; } destinationIndex[playerIndex] = selectedCard.MoveToIndexPosition; // Even if player rolls a double, end player's turn if they land in jail doublesCounter[playerIndex] = 0; if (playerIndex == 0) { playerTurn[0] = false; playerTurn[1] = true; } else { playerTurn[1] = false; playerTurn[0] = true; } playerMove(playerIndex); } else if (!selectedCard.IsDebit && selectedCard.IsMove) { if (selectedCard.Tag == "Go to Jail") { isInJail[playerIndex] = true; doublesCounter[playerIndex] = 0; if (playerIndex == 0) { playerTurn[0] = false; playerTurn[1] = true; } else { playerTurn[1] = false; playerTurn[0] = true; } } destinationIndex[playerIndex] = selectedCard.MoveToIndexPosition; playerMove(playerIndex); } else if (selectedCard.IsCredit) { Cash[playerIndex] -= selectedCard.CreditAmount; } } }
37.064403
194
0.542571
[ "MIT" ]
davidli731/Monopoly-Unity-Game
Assets/Scripts/Main.cs
31,653
C#
using System; using System.Linq; using Sanicball.Data; using Sanicball.Gameplay; using SanicballCore; using SanicballCore.MatchMessages; using UnityEngine; namespace Sanicball.Logic { public class RaceFinishReport { /// <summary> /// Finishing with this position means the player has been disqualified. /// </summary> public const int DISQUALIFIED_POS = -1; private TimeSpan time; private int position; public int Position { get { return position; } } public TimeSpan Time { get { return time; } } public bool Disqualified { get { return position == DISQUALIFIED_POS; } } public RaceFinishReport(int position, TimeSpan time) { this.position = position; this.time = time; } public void SetPosition(int pos){ this.position = pos; } } public class NextCheckpointPassArgs : EventArgs { public int IndexOfPreviousCheckpoint { get; private set; } public TimeSpan CurrentLapTime { get; private set; } public NextCheckpointPassArgs(int indexOfPreviousCheckpoint, TimeSpan currentLapTime) { IndexOfPreviousCheckpoint = indexOfPreviousCheckpoint; CurrentLapTime = currentLapTime; } } [Serializable] //This is so the list if race players can be viewed in the inspector public class RacePlayer { [System.NonSerialized] public Ball ball; private IBallCamera ballCamera; private RaceFinishReport finishReport; //Race progress private int lap; private int currentCheckpointIndex; //Checkpoint related stuff private Vector3 currentCheckpointPos; private Checkpoint nextCheckpoint; //Time private float lapTime; public float rawTime; private float[] checkpointTimes; private float timeout; //Cache of the scene's StageReferences object (Because it's used often) private StageReferences sr; //Associated logic [System.NonSerialized] public MatchMessenger matchMessenger; [System.NonSerialized] public MatchPlayer associatedMatchPlayer; private bool waitingForCheckpointMessage; //Events public event EventHandler<NextCheckpointPassArgs> NextCheckpointPassed; public event EventHandler<bool> Respawned; public event EventHandler FinishLinePassed; public event EventHandler Destroyed; //Readonly properties that get stuff from the player's ball public Ball Ball { get { return ball; } } public bool IsPlayer { get { return ball.Type == BallType.Player; } } public string Name { get { return ball.Nickname; } } public ControlType CtrlType { get { return ball.CtrlType; } } public int Character { get { return ball.CharacterId; } } public Transform Transform { get { return ball.transform; } } public float Speed { get { return ball.GetComponent<Rigidbody>().velocity.magnitude; } } public IBallCamera Camera { get { return ballCamera; } } public Powerup[] Powerups { get { return ball.powerups; } } //Race progress properties public int Lap { get { return lap; } } public bool RaceFinished { get { return finishReport != null; } set {} } public RaceFinishReport FinishReport { get { return finishReport; } } public float Timeout { get { return timeout; } } //Misc properties public MatchPlayer AssociatedMatchPlayer { get { return associatedMatchPlayer; } } public bool LapRecordsEnabled { get; set; } public int Position { get; set; } public Checkpoint NextCheckpoint { get { return nextCheckpoint; } } public RacePlayer(Ball ball, MatchMessenger matchMessenger, MatchPlayer associatedMatchPlayer) { sr = StageReferences.Active; this.matchMessenger = matchMessenger; this.associatedMatchPlayer = associatedMatchPlayer; matchMessenger.CreateListener<CheckpointPassedMessage>(CheckpointPassedHandler); matchMessenger.CreateListener<RaceTimeoutMessage>(RaceTimeoutHandler); matchMessenger.CreateListener<PlayerZappedMessage>(PlayerZappedHandler); matchMessenger.CreateListener<PlayerConfusedMessage>(PlayerConfusedHandler); //matchMessenger.CreateListener<PlayerForcedRespawnMessage>(PlayerForcedRespawnHandler); lap = 1; ball.CanMove = false; ball.AutoBrake = true; ball.CheckpointPassed += Ball_CheckpointPassed; ball.RespawnRequested += Ball_RespawnRequested; currentCheckpointPos = sr.checkpoints[0].transform.position; this.ball = ball; ball.CameraCreated += (sender, e) => { ballCamera = e.CameraCreated; ballCamera.SetDirection(sr.checkpoints[0].transform.rotation); }; checkpointTimes = new float[StageReferences.Active.checkpoints.Length]; SetNextCheckpoint(); } public void StartRace() { ball.CanMove = true; ball.AutoBrake = false; } public void FinishRace(RaceFinishReport report) { if (finishReport == null) { finishReport = report; //Stop movement of AI balls, or disable powerups if (ball.Type == BallType.AI) ball.CanMove = false; else ball.canUsePowerups = false; //Set layer to Racer Ghost to block collision with racing players ball.gameObject.layer = LayerMask.NameToLayer("Racer Ghost"); } else { throw new InvalidOperationException("RacePlayer tried to finish a race twice for some reason"); } } public float CalculateRaceProgress() { //This function returns race progress as laps done (1..*) + progress to next lap (0..1) //If the race is finished, ignore lap progress and just return the current lap (Which would be 1 above the number of laps in the race) if (RaceFinished) { return Lap; } float progPerCheckpoint = 1f / sr.checkpoints.Length; Vector3 nextPos = nextCheckpoint.transform.position; float ballToNext = Vector3.Distance(ball.transform.position, nextPos); float currToNext = Vector3.Distance(currentCheckpointPos, nextPos); float distToNextPercentile = 1f - Mathf.Clamp(ballToNext / currToNext, 0f, 1f); float distToNextProg = distToNextPercentile * progPerCheckpoint; float lapProg = currentCheckpointIndex * progPerCheckpoint + distToNextProg; return Lap + lapProg; } private void Ball_CheckpointPassed(object sender, CheckpointPassArgs e) { if (e.CheckpointPassed == nextCheckpoint) { if (ball.Type == BallType.Player && ball.CtrlType != ControlType.None) { if (!waitingForCheckpointMessage) { //Send a match message for local players waitingForCheckpointMessage = true; matchMessenger.SendMessage(new CheckpointPassedMessage(associatedMatchPlayer.ClientGuid, ball.CtrlType, lapTime)); } } else if (ball.Type == BallType.AI) { //Invoke PassNextCheckpoint directly for AI balls PassNextCheckpoint(lapTime); } } } private void CheckpointPassedHandler(CheckpointPassedMessage msg, float travelTime) { if (associatedMatchPlayer != null && msg.ClientGuid == associatedMatchPlayer.ClientGuid && msg.CtrlType == associatedMatchPlayer.CtrlType) { PassNextCheckpoint(msg.LapTime); waitingForCheckpointMessage = false; } } private void RaceTimeoutHandler(RaceTimeoutMessage msg, float travelTime) { if (associatedMatchPlayer != null && msg.ClientGuid == associatedMatchPlayer.ClientGuid && msg.CtrlType == associatedMatchPlayer.CtrlType) { timeout = msg.Time - travelTime; } } private void PlayerZappedHandler(PlayerZappedMessage msg, float travelTime) { if ((msg.ClientGuid == associatedMatchPlayer.ClientGuid && msg.CtrlType == associatedMatchPlayer.CtrlType) || ball.Type == BallType.AI) { Debug.Log("Player zapped (RacePlayer): " + ball.Nickname); ball.zapped = true; } } private void PlayerConfusedHandler(PlayerConfusedMessage msg, float travelTime) { if ((msg.ClientGuid == associatedMatchPlayer.ClientGuid && msg.CtrlType == associatedMatchPlayer.CtrlType) || ball.Type == BallType.AI) { Debug.Log("Player confused (RacePlayer): " + ball.Nickname); ball.confused = true; } } //private void PlayerForcedRespawnHandler(PlayerForcedRespawnMessage msg, float travelTime) //{ // if(associatedMatchPlayer != null){ // if (msg.ClientGuid == associatedMatchPlayer.ClientGuid && msg.CtrlType == associatedMatchPlayer.CtrlType) // { // Debug.Log("Player respawned (RacePlayer): " + ball.Nickname); // ball.RequestRespawn(); // } // }else if(ball.Type == BallType.AI){ // Debug.Log("Player respawned (RacePlayer): " + ball.Nickname); // ball.RequestRespawn(); // } //} private void PassNextCheckpoint(float lapTime) { checkpointTimes[currentCheckpointIndex] = lapTime; //Call NextCheckpointPassed BEFORE doing anything else. This ensures things like lap records work correctly. if (NextCheckpointPassed != null) NextCheckpointPassed(this, new NextCheckpointPassArgs(currentCheckpointIndex, TimeSpan.FromSeconds(lapTime))); currentCheckpointIndex = (currentCheckpointIndex + 1) % sr.checkpoints.Length; currentCheckpointPos = nextCheckpoint.transform.position; if (currentCheckpointIndex == 0) { lap++; if (FinishLinePassed != null) FinishLinePassed(this, EventArgs.Empty); if (LapRecordsEnabled) { CharacterTier tier = ActiveData.Characters[Character].tier; string sceneName = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name; int stage = ActiveData.Stages.Where(a => a.sceneName == sceneName).First().id; ActiveData.RaceRecords.Add(new RaceRecord( tier, lapTime, rawTime, DateTime.Now, stage, Character, checkpointTimes, GameVersion.AS_FLOAT, GameVersion.IS_TESTING, ActiveData.MatchSettings.PowerupsEnabled )); Debug.Log("Saved lap record (" + TimeSpan.FromSeconds(lapTime) + ")"); } //Reset lap time this.lapTime = 0 + (this.lapTime - lapTime); rawTime = 0; checkpointTimes = new float[StageReferences.Active.checkpoints.Length]; } SetNextCheckpoint(); //Set next target node if this is an AI ball TrySetAITarget(); } private void Ball_RespawnRequested(object sender, bool penalty) { if (Respawned != null) { Respawned(this, penalty); } ball.transform.position = sr.checkpoints[currentCheckpointIndex].GetRespawnPoint() + Vector3.up * ball.transform.localScale.x * 0.5f; ball.GetComponent<Rigidbody>().velocity = Vector3.zero; ball.GetComponent<Rigidbody>().angularVelocity = Vector3.zero; if (ballCamera != null) { ballCamera.SetDirection(sr.checkpoints[currentCheckpointIndex].transform.rotation); } Debug.Log("Apply penalty = " + penalty); //Time penalty if(penalty) lapTime += 5; //Set next target node if this is an AI ball TrySetAITarget(); } private void TrySetAITarget() { BallControlAI ai = ball.GetComponent<BallControlAI>(); if (ai) { Checkpoint activeCheckpoint = StageReferences.Active.checkpoints[currentCheckpointIndex]; ai.Target = activeCheckpoint.FirstAINode; } } private void SetNextCheckpoint() { if (RaceFinished) { nextCheckpoint = null; } else if (currentCheckpointIndex == sr.checkpoints.Length - 1) { nextCheckpoint = sr.checkpoints[0]; } else { nextCheckpoint = sr.checkpoints[currentCheckpointIndex + 1]; } } public void UpdateTimer(float dt) { lapTime += dt; rawTime += dt; //This is also a good time to decrement the timeout timer if it's above 0 if (timeout > 0) { timeout = Mathf.Max(0, timeout - Time.deltaTime); } } public void Destroy() { matchMessenger.RemoveListener<CheckpointPassedMessage>(CheckpointPassedHandler); if (Destroyed != null) Destroyed(this, EventArgs.Empty); } public static RacePlayer GetByBall(Ball referenceBall) { object[] gameobjects = GameObject.FindSceneObjectsOfType(typeof(GameObject)); foreach (object obj in gameobjects) { RacePlayer player = ((GameObject) obj).GetComponent<RacePlayer>() as RacePlayer; if(player != null) { if(player.ball == referenceBall){ return player; } } } return null; } } }
37.136709
150
0.587566
[ "MIT" ]
migouche/SanicBall-Custom
Assets/Scripts/Logic/RacePlayer.cs
14,671
C#
using System.Collections.Generic; using System.Data; using System.Threading.Tasks; using DapperExtensionsReloaded.Internal.Sql; using DapperExtensionsReloaded.Predicates; namespace DapperExtensionsReloaded.Internal { internal interface IDapperImplementor { ISqlGenerator SqlGenerator { get; } Task InsertAsync<T>(IDbConnection connection, IEnumerable<T> entities, IDbTransaction transaction, int? commandTimeout) where T : class; Task<dynamic> InsertAsync<T>(IDbConnection connection, T entity, IDbTransaction transaction, int? commandTimeout) where T : class; Task<bool> UpdateAsync<T>(IDbConnection connection, T entity, IDbTransaction transaction, int? commandTimeout) where T : class; Task<bool> UpdateSetAsync<T>(IDbConnection connection, object values, IPredicate predicate, IDbTransaction transaction, int? commandTimeout) where T : class; Task<bool> DeleteAsync<T>(IDbConnection connection, T entity, IDbTransaction transaction, int? commandTimeout) where T : class; Task<bool> DeleteSetAsync<T>(IDbConnection connection, IPredicate predicate, IDbTransaction transaction, int? commandTimeout) where T : class; Task<IMultipleResultReader> GetMultipleAsync(IDbConnection connection, GetMultiplePredicate predicate, IDbTransaction transaction, int? commandTimeout); Task<T> GetAsync<T>(IDbConnection connection, object id, IDbTransaction transaction = null, int? commandTimeout = null) where T : class; Task<T> GetAsync<T>(IDbConnection connection, IPredicate predicate, IDbTransaction transaction = null, int? commandTimeout = null) where T : class; Task<IEnumerable<T>> GetListAsync<T>(IDbConnection connection, IPredicate predicate = null, IList<ISort> sort = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class; Task<IEnumerable<T>> GetPageAsync<T>(IDbConnection connection, IPredicate predicate = null, IList<ISort> sort = null, int page = 0, int itemsPerPage = 10, int resultsToReturn = 10, IDbTransaction transaction = null, int? commandTimeout = null) where T : class; Task<IEnumerable<T>> GetSetAsync<T>(IDbConnection connection, IPredicate predicate = null, IList<ISort> sort = null, int firstResult = 1, int maxResults = 10, IDbTransaction transaction = null, int? commandTimeout = null) where T : class; Task<int> CountAsync<T>(IDbConnection connection, IPredicate predicate = null, IDbTransaction transaction = null, int? commandTimeout = null) where T : class; } }
97.769231
268
0.764359
[ "MIT" ]
MisterGoodcat/Dapper-Extensions
DapperExtensionsReloaded/Internal/IDapperImplementor.cs
2,544
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. // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. using System.Collections.Generic; using System.Runtime.Serialization; using Xunit; using System.Text.Json.Serialization; namespace System.Text.Json.Tests { public class EnumConverterTests { [Fact] public static void SerializeEnumClass() { EnumClass enumClass = new EnumClass() { StoreColor = StoreColor.Red, NullableStoreColor1 = StoreColor.White, NullableStoreColor2 = null }; string json = JsonSerializer.Serialize(enumClass, new JsonSerializerOptions { WriteIndented = true }); Assert.Equal(@"{ ""StoreColor"": 2, ""NullableStoreColor1"": 8, ""NullableStoreColor2"": null }".NormalizeLineEndings(), json); } [Fact] public static void SerializeEnumClassUndefined() { EnumClass enumClass = new EnumClass() { StoreColor = (StoreColor)1000, NullableStoreColor1 = (StoreColor)1000, NullableStoreColor2 = null }; string json = JsonSerializer.Serialize(enumClass, new JsonSerializerOptions { WriteIndented = true }); Assert.Equal(@"{ ""StoreColor"": 1000, ""NullableStoreColor1"": 1000, ""NullableStoreColor2"": null }".NormalizeLineEndings(), json); } [Fact] public static void SerializeFlagEnum() { EnumClass enumClass = new EnumClass() { StoreColor = StoreColor.Red | StoreColor.White, NullableStoreColor1 = StoreColor.White & StoreColor.Yellow, NullableStoreColor2 = StoreColor.Red | StoreColor.White | StoreColor.Black }; string json = JsonSerializer.Serialize(enumClass, new JsonSerializerOptions { WriteIndented = true }); Assert.Equal(@"{ ""StoreColor"": 10, ""NullableStoreColor1"": 0, ""NullableStoreColor2"": 11 }".NormalizeLineEndings(), json); } [Fact] public static void SerializeNegativeFlagsEnum() { NegativeFlagsEnumClass negativeEnumClass = new NegativeFlagsEnumClass(); negativeEnumClass.Value1 = NegativeFlagsEnum.NegativeFour | NegativeFlagsEnum.NegativeTwo; negativeEnumClass.Value2 = NegativeFlagsEnum.Two | NegativeFlagsEnum.Four; string json = JsonSerializer.Serialize(negativeEnumClass, new JsonSerializerOptions { WriteIndented = true }); Assert.Equal(@"{ ""Value1"": -2, ""Value2"": 6 }".NormalizeLineEndings(), json); } [Fact] public static void SerializeNegativeEnum() { NegativeEnumClass negativeEnumClass = new NegativeEnumClass() { Value1 = NegativeEnum.Negative, Value2 = (NegativeEnum)int.MinValue }; string json = JsonSerializer.Serialize(negativeEnumClass, new JsonSerializerOptions { WriteIndented = true }); Assert.Equal(@"{ ""Value1"": -1, ""Value2"": -2147483648 }".NormalizeLineEndings(), json); } [Fact] public static void EnumMemberPlusFlags() { List<Foo> lfoo = new List<Foo> { Foo.Bat | Foo.SerializeAsBaz, Foo.FooBar, Foo.Bat, Foo.SerializeAsBaz, Foo.FooBar | Foo.SerializeAsBaz, (Foo)int.MaxValue }; string json1 = JsonSerializer.Serialize(lfoo, new JsonSerializerOptions { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); Assert.Equal(@"[ 6, 1, 2, 4, 5, 2147483647 ]".NormalizeLineEndings(), json1); IList<Foo> foos = JsonSerializer.Deserialize<List<Foo>>(json1); Assert.Equal(6, foos.Count); Assert.Equal(Foo.Bat | Foo.SerializeAsBaz, foos[0]); Assert.Equal(Foo.FooBar, foos[1]); Assert.Equal(Foo.Bat, foos[2]); Assert.Equal(Foo.SerializeAsBaz, foos[3]); Assert.Equal(Foo.FooBar | Foo.SerializeAsBaz, foos[4]); Assert.Equal((Foo)int.MaxValue, foos[5]); List<Bar> lbar = new List<Bar>() { Bar.FooBar, Bar.Bat, Bar.SerializeAsBaz }; string json2 = JsonSerializer.Serialize(lbar, new JsonSerializerOptions { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); Assert.Equal(@"[ 0, 1, 2 ]".NormalizeLineEndings(), json2); IList<Bar> bars = JsonSerializer.Deserialize<List<Bar>>(json2); Assert.Equal(3, bars.Count); Assert.Equal(Bar.FooBar, bars[0]); Assert.Equal(Bar.Bat, bars[1]); Assert.Equal(Bar.SerializeAsBaz, bars[2]); } [Fact] public static void TestValidIntegerValue() { StoreColor c = JsonSerializer.Deserialize<StoreColor>("1"); Assert.Equal(StoreColor.Black, c); } [Fact] public static void DuplicateNameEnumTest() { JsonException e = Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<DuplicateNameEnum>("\"foo_bar\"")); } [Fact] public static void InvalidValueStringNumber() { JsonException ex = Assert.Throws<JsonException>(() => { StoreColor s = JsonSerializer.Deserialize<StoreColor>("\"1\""); }); } [Fact] public static void SerializeEnumWithDifferentCases() { string json = JsonSerializer.Serialize(EnumWithDifferentCases.M); Assert.Equal("0", json); json = JsonSerializer.Serialize(EnumWithDifferentCases.m); Assert.Equal("1", json); } [Fact] public static void DeserializeEnumWithDifferentCases() { EnumWithDifferentCases e = JsonSerializer.Deserialize<EnumWithDifferentCases>("0"); Assert.Equal(EnumWithDifferentCases.M, e); e = JsonSerializer.Deserialize<EnumWithDifferentCases>("1"); Assert.Equal(EnumWithDifferentCases.m, e); } [Fact] public static void SerializeEnumMemberWithDifferentCases() { string json = JsonSerializer.Serialize(EnumMemberWithDifferentCases.Month); Assert.Equal("0", json); json = JsonSerializer.Serialize(EnumMemberWithDifferentCases.Minute); Assert.Equal("1", json); } [Fact] public static void InvalidValueDash() { JsonException ex = Assert.Throws<JsonException>(() => { JsonSerializer.Deserialize<StoreColor>("\"-\""); }); } [Fact] public static void DeserializeNegativeEnum() { string json = @"{ ""Value1"": -1, ""Value2"": -2147483648 }"; NegativeEnumClass negativeEnumClass = JsonSerializer.Deserialize<NegativeEnumClass>(json); Assert.Equal(NegativeEnum.Negative, negativeEnumClass.Value1); Assert.Equal((NegativeEnum)int.MinValue, negativeEnumClass.Value2); } [Fact] public static void DeserializeEnumClass() { string json = @"{ ""StoreColor"": 2, ""NullableStoreColor1"": 8, ""NullableStoreColor2"": null }"; EnumClass enumClass = JsonSerializer.Deserialize<EnumClass>(json); Assert.Equal(StoreColor.Red, enumClass.StoreColor); Assert.Equal(StoreColor.White, enumClass.NullableStoreColor1); Assert.Null(enumClass.NullableStoreColor2); } [Fact] public static void DeserializeFlagEnum() { string json = @"{ ""StoreColor"": 10, ""NullableStoreColor1"": 0, ""NullableStoreColor2"": 11 }"; EnumClass enumClass = JsonSerializer.Deserialize<EnumClass>(json); Assert.Equal(StoreColor.Red | StoreColor.White, enumClass.StoreColor); Assert.Equal((StoreColor)0, enumClass.NullableStoreColor1); Assert.Equal(StoreColor.Red | StoreColor.White | StoreColor.Black, enumClass.NullableStoreColor2); } } [Flags] internal enum Foo { FooBar = 0x01, Bat = 0x02, SerializeAsBaz = 0x4, } internal enum Bar { FooBar, Bat, SerializeAsBaz } internal enum NegativeEnum { Negative = -1, Zero = 0, Positive = 1 } [Flags] internal enum NegativeFlagsEnum { NegativeFour = -4, NegativeTwo = -2, NegativeOne = -1, Zero = 0, One = 1, Two = 2, Four = 4 } internal enum EnumWithDifferentCases { M, m } internal enum EnumMemberWithDifferentCases { Month, Minute } internal class NegativeEnumClass { public NegativeEnum Value1 { get; set; } public NegativeEnum Value2 { get; set; } } internal class NegativeFlagsEnumClass { public NegativeFlagsEnum Value1 { get; set; } public NegativeFlagsEnum Value2 { get; set; } } [Flags] internal enum StoreColor { Black = 1, Red = 2, Yellow = 4, White = 8, DarkGoldenrod = 16 } internal class EnumClass { public StoreColor StoreColor { get; set; } public StoreColor NullableStoreColor1 { get; set; } public StoreColor? NullableStoreColor2 { get; set; } } internal enum DuplicateNameEnum { [EnumMember] first = 0, [EnumMember] foo_bar = 1, [EnumMember(Value = "foo_bar")] FooBar = 2, [EnumMember] foo_bar_NOT_USED = 3 } }
29.93617
161
0.598525
[ "MIT" ]
939481896/dotnet-corefx
src/System.Text.Json/tests/NewtonsoftTests/EnumConverterTests.cs
11,258
C#
namespace XCLCMS.FileManager.Common { /// <summary> /// 公共方法 /// </summary> public class Library { /// <summary> /// 文件管理中的文件上传目录 /// </summary> public const string FileManager_UploadPath = "~/Upload/Files/"; /// <summary> /// 文件管理器中的临时文件上传路径 /// </summary> public const string FileManager_UploadPathTemp = "~/Upload/Temp/"; } }
23.222222
74
0.54067
[ "Apache-2.0" ]
jiangnanwoniu/XCLCMS_asp.net
XCLCMS.FileManager/Common/Library.cs
482
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.ApiManagement.V20201201.Outputs { /// <summary> /// Properties controlling TLS Certificate Validation. /// </summary> [OutputType] public sealed class BackendTlsPropertiesResponse { /// <summary> /// Flag indicating whether SSL certificate chain validation should be done when using self-signed certificates for this backend host. /// </summary> public readonly bool? ValidateCertificateChain; /// <summary> /// Flag indicating whether SSL certificate name validation should be done when using self-signed certificates for this backend host. /// </summary> public readonly bool? ValidateCertificateName; [OutputConstructor] private BackendTlsPropertiesResponse( bool? validateCertificateChain, bool? validateCertificateName) { ValidateCertificateChain = validateCertificateChain; ValidateCertificateName = validateCertificateName; } } }
34.358974
142
0.691791
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/ApiManagement/V20201201/Outputs/BackendTlsPropertiesResponse.cs
1,340
C#