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
namespace KraftWrapper.Interfaces.Fields { public interface ISitecoreLinkField : ISitecoreBaseCustomField { string Text { get; } string FriendlyUrl { get; } } }
21.111111
66
0.668421
[ "MIT" ]
yakonstantine/Kraft-Wrapper
KraftWrapper/KraftWrapper/Interfaces/Fields/ISitecoreLinkField.cs
192
C#
using System; using System.Collections.Generic; using Microsoft.Practices.ServiceLocation; using Ninject; namespace Purchasing.Jobs.Common { // from: https://github.com/ninject/Ninject/blob/master/src/CommonServiceLocator.NinjectAdapter/NinjectServiceLocator.cs public class NinjectServiceLocator : ServiceLocatorImplBase { public IKernel Kernel { get; private set; } public NinjectServiceLocator(IKernel kernel) { Kernel = kernel; } protected override object DoGetInstance(Type serviceType, string key) { // key == null must be specifically handled as not asking for a specific keyed instance // http://commonservicelocator.codeplex.com/wikipage?title=API%20Reference&referringTitle=Home // The implementation should be designed to expect a null for the string key parameter, // and MUST interpret this as a request to get the "default" instance for the requested // type. This meaning of default varies from locator to locator. if (key == null) { return Kernel.Get(serviceType); } return Kernel.Get(serviceType, key); } protected override IEnumerable<object> DoGetAllInstances(Type serviceType) { return Kernel.GetAll(serviceType); } } }
36.025641
125
0.650534
[ "MIT" ]
ucdavis/Purchasing
Purchasing.Jobs.Common/NinjectServiceLocator.cs
1,407
C#
// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using System.IO; using Tea; namespace AntChain.SDK.Deps.Models { public class SaveAppbaselineSidecarResponse : TeaModel { [NameInMap("req_msg_id")] [Validation(Required=false)] public string ReqMsgId { get; set; } [NameInMap("result_code")] [Validation(Required=false)] public string ResultCode { get; set; } [NameInMap("result_msg")] [Validation(Required=false)] public string ResultMsg { get; set; } // 应用基线ID [NameInMap("appbaseline_id")] [Validation(Required=false)] public string AppbaselineId { get; set; } } }
23.125
60
0.635135
[ "MIT" ]
alipay/antchain-openapi-prod-sdk
deps/csharp/core/Models/SaveAppbaselineSidecarResponse.cs
748
C#
using System; using System.Collections.Generic; namespace SchoolSystem.Framework.Core { public class SchoolSystemDataCollection<T> : ISchoolSystemDataCollection<T> { private readonly IDictionary<int, T> entities; public SchoolSystemDataCollection() { this.entities = new Dictionary<int, T>(); } public void Add(int id, T entity) { if (entity == null) { throw new ArgumentNullException(nameof(entity)); } this.entities.Add(id, entity); } public bool ContainsKey(int id) { return this.entities.ContainsKey(id); } public T GetById(int id) { return this.entities[id]; } public void Remove(int id) { this.entities.Remove(id); } } }
21.634146
79
0.537768
[ "MIT" ]
shakuu/Exams
DesignPatternsExam/DesignPatternsExam/Exam/SchoolSystem.Framework/Core/SchoolSystemDataCollection.cs
889
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Portions derived from React Native: // Copyright (c) 2015-present, Facebook, Inc. // Licensed under the MIT License. using Newtonsoft.Json.Linq; using ReactNative.UIManager; using ReactNative.UIManager.Annotations; #if WINDOWS_UWP using ReactNative.Accessibility; using ReactNative.Reflection; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; #else using System.Windows; using System.Windows.Controls; using System.Windows.Media; #endif namespace ReactNative.Views.View { /// <summary> /// View manager for React view instances. /// </summary> public class ReactViewManager : ViewParentManager<BorderedCanvas> { private readonly ViewKeyedDictionary<BorderedCanvas, CornerRadiusManager> _borderedCanvasToRadii = new ViewKeyedDictionary<BorderedCanvas, CornerRadiusManager>(); private readonly ViewKeyedDictionary<BorderedCanvas, ThicknessManager> _borderedCanvasToThickness = new ViewKeyedDictionary<BorderedCanvas, ThicknessManager>(); /// <summary> /// The name of this view manager. This will be the name used to /// reference this view manager from JavaScript. /// </summary> public override string Name => ViewProps.ViewClassName; /// <summary> /// Creates a new view instance of type <see cref="Canvas"/>. /// </summary> /// <param name="reactContext">The React context.</param> /// <returns>The view instance.</returns> protected override BorderedCanvas CreateViewInstance(ThemedReactContext reactContext) { return new BorderedCanvas(); } /// <summary> /// Sets whether the view is collapsible. /// </summary> /// <param name="view">The view instance.</param> /// <param name="collapsible">The flag.</param> [ReactProp(ViewProps.Collapsible)] public void SetCollapsible(BorderedCanvas view, bool collapsible) { // no-op: it's here only so that "collapsable" prop is exported to JS. The value is actually // handled in NativeViewHierarchyOptimizer } /// <summary> /// Sets whether or not the view is an accessibility element. /// </summary> /// <param name="view">The view.</param> /// <param name="accessible">A flag indicating whether or not the view is an accessibility element.</param> [ReactProp("accessible")] public void SetAccessible(BorderedCanvas view, bool accessible) { // TODO: #557 Provide implementation for View's accessible prop // We need to have this stub for this prop so that Views which // specify the accessible prop aren't considered to be layout-only. // The proper implementation is still to be determined. } #if WINDOWS_UWP /// <summary> /// Set accessibility traits for the view. /// </summary> /// <param name="view">The view.</param> /// <param name="accessibilityTraitsValue">Can be <see cref="JArray"/> of objects or a single object. /// String representation of the object(s) is parsed as <see cref="AccessibilityTrait"/>.</param> [ReactProp(ViewProps.AccessibilityTraits)] public void SetAccessibilityTraits(BorderedCanvas view, object accessibilityTraitsValue) { AccessibilityHelper.SetAccessibilityTraits(view, accessibilityTraitsValue); } /// <summary> /// Sets <see cref="ImportantForAccessibility"/> for the BorderedCanvas. /// </summary> /// <param name="view">The view.</param> /// <param name="importantForAccessibilityValue">The string to be parsed as <see cref="ImportantForAccessibility"/>.</param> [ReactProp(ViewProps.ImportantForAccessibility)] public void SetImportantForAccessibility(BorderedCanvas view, string importantForAccessibilityValue) { var importantForAccessibility = EnumHelpers.ParseNullable<ImportantForAccessibility>(importantForAccessibilityValue) ?? ImportantForAccessibility.Auto; AccessibilityHelper.SetImportantForAccessibility(view, importantForAccessibility); } #endif /// <summary> /// Enum values correspond to positions of prop names in ReactPropGroup attribute /// applied to <see cref="SetBorderRadius(BorderedCanvas, int, double?)"/> /// </summary> private enum Radius { All, TopLeft, TopRight, BottomLeft, BottomRight, } /// <summary> /// Sets the border radius of the view. /// </summary> /// <param name="view">The view panel.</param> /// <param name="index">The prop index.</param> /// <param name="radius">The border radius value.</param> [ReactPropGroup( ViewProps.BorderRadius, ViewProps.BorderTopLeftRadius, ViewProps.BorderTopRightRadius, ViewProps.BorderBottomLeftRadius, ViewProps.BorderBottomRightRadius)] public void SetBorderRadius(BorderedCanvas view, int index, double? radius) { if (!_borderedCanvasToRadii.TryGetValue(view, out var cornerRadiusManager)) { cornerRadiusManager = new CornerRadiusManager(); _borderedCanvasToRadii.AddOrUpdate(view, cornerRadiusManager); } switch ((Radius)index) { case Radius.All: cornerRadiusManager.Set(CornerRadiusManager.All, radius); break; case Radius.TopLeft: cornerRadiusManager.Set(CornerRadiusManager.TopLeft, radius); break; case Radius.TopRight: cornerRadiusManager.Set(CornerRadiusManager.TopRight, radius); break; case Radius.BottomLeft: cornerRadiusManager.Set(CornerRadiusManager.BottomLeft, radius); break; case Radius.BottomRight: cornerRadiusManager.Set(CornerRadiusManager.BottomRight, radius); break; } view.CornerRadius = cornerRadiusManager.AsCornerRadius(); } /// <summary> /// Sets the background color of the view. /// </summary> /// <param name="view">The view panel.</param> /// <param name="color">The masked color value.</param> [ReactProp( ViewProps.BackgroundColor, CustomType = "Color")] public void SetBackgroundColor(BorderedCanvas view, uint? color) { view.Background = color.HasValue ? new SolidColorBrush(ColorHelpers.Parse(color.Value)) : null; } /// <summary> /// Set the border color of the view. /// </summary> /// <param name="view">The view panel.</param> /// <param name="color">The color hex code.</param> [ReactProp("borderColor", CustomType = "Color")] public void SetBorderColor(BorderedCanvas view, uint? color) { view.BorderBrush = color.HasValue ? new SolidColorBrush(ColorHelpers.Parse(color.Value)) : null; } /// <summary> /// Enum values correspond to positions of prop names in ReactPropGroup attribute /// applied to <see cref="SetBorderWidth(BorderedCanvas, int, double?)"/> /// </summary> private enum Width { All, Left, Right, Top, Bottom, } /// <summary> /// Sets the border thickness of the view. /// </summary> /// <param name="view">The view panel.</param> /// <param name="index">The prop index.</param> /// <param name="width">The border width in pixels.</param> [ReactPropGroup( ViewProps.BorderWidth, ViewProps.BorderLeftWidth, ViewProps.BorderRightWidth, ViewProps.BorderTopWidth, ViewProps.BorderBottomWidth)] public void SetBorderWidth(BorderedCanvas view, int index, double? width) { if (!_borderedCanvasToThickness.TryGetValue(view, out var thicknessManager)) { thicknessManager = new ThicknessManager(); _borderedCanvasToThickness.AddOrUpdate(view, thicknessManager); } switch ((Width)index) { case Width.All: thicknessManager.Set(ThicknessManager.All, width); break; case Width.Left: thicknessManager.Set(ThicknessManager.Left, width); break; case Width.Right: thicknessManager.Set(ThicknessManager.Right, width); break; case Width.Top: thicknessManager.Set(ThicknessManager.Top, width); break; case Width.Bottom: thicknessManager.Set(ThicknessManager.Bottom, width); break; } view.BorderThickness = thicknessManager.AsThickness(); } /// <summary> /// Called when view is detached from view hierarchy and allows for /// additional cleanup. /// </summary> /// <param name="reactContext">The React context.</param> /// <param name="view">The view.</param> public override void OnDropViewInstance(ThemedReactContext reactContext, BorderedCanvas view) { base.OnDropViewInstance(reactContext, view); _borderedCanvasToRadii.Remove(view); _borderedCanvasToThickness.Remove(view); } /// <summary> /// Adds a child at the given index. /// </summary> /// <param name="parent">The parent view.</param> /// <param name="child">The child view.</param> /// <param name="index">The index.</param> public override void AddView(BorderedCanvas parent, DependencyObject child, int index) { parent.Children.Insert(index, child.As<UIElement>()); } /// <summary> /// Gets the child at the given index. /// </summary> /// <param name="parent">The parent view.</param> /// <param name="index">The index.</param> /// <returns>The child view.</returns> public override DependencyObject GetChildAt(BorderedCanvas parent, int index) { return parent.Children[index]; } /// <summary> /// Gets the number of children in the view parent. /// </summary> /// <param name="parent">The view parent.</param> /// <returns>The number of children.</returns> public override int GetChildCount(BorderedCanvas parent) { return parent.Children.Count; } /// <summary> /// Removes all children from the view parent. /// </summary> /// <param name="parent">The view parent.</param> public override void RemoveAllChildren(BorderedCanvas parent) { parent.Children.Clear(); } /// <summary> /// Removes the child at the given index. /// </summary> /// <param name="parent">The view parent.</param> /// <param name="index">The index.</param> public override void RemoveChildAt(BorderedCanvas parent, int index) { parent.Children.RemoveAt(index); } } }
38.862745
132
0.591322
[ "MIT" ]
MikeHillberg/react-native-windows
ReactWindows/ReactNative.Shared/Views/View/ReactViewManager.cs
11,892
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("WxStationNode")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WxStationNode")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: ComVisible(false)]
35.965517
84
0.74209
[ "Apache-2.0" ]
PervasiveDigital/AcuriteWxStation
src/WxStationNode/Properties/AssemblyInfo.cs
1,046
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the logs-2014-03-28.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.CloudWatchLogs.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.CloudWatchLogs.Model.Internal.MarshallTransformations { /// <summary> /// DisassociateKmsKey Request Marshaller /// </summary> public class DisassociateKmsKeyRequestMarshaller : IMarshaller<IRequest, DisassociateKmsKeyRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((DisassociateKmsKeyRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(DisassociateKmsKeyRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.CloudWatchLogs"); string target = "Logs_20140328.DisassociateKmsKey"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.HttpMethod = "POST"; string uriResourcePath = "/"; request.ResourcePath = uriResourcePath; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetLogGroupName()) { context.Writer.WritePropertyName("logGroupName"); context.Writer.Write(publicRequest.LogGroupName); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } } }
35.988636
151
0.649511
[ "Apache-2.0" ]
Murcho/aws-sdk-net
sdk/src/Services/CloudWatchLogs/Generated/Model/Internal/MarshallTransformations/DisassociateKmsKeyRequestMarshaller.cs
3,167
C#
//----------------------------------------------------------------------- // <copyright file="ActorLifeCycleSpec.cs" company="Akka.NET Project"> // Copyright (C) 2009-2019 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2019 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Akka.Actor; using Akka.TestKit; using Akka.Tests.TestUtils; using Akka.Util.Internal; using Xunit; namespace Akka.Tests { public class ActorLifeCycleSpec : AkkaSpec { public class LifeCycleTestActor : UntypedActor { private AtomicCounter generationProvider; private string id; private IActorRef testActor; private int CurrentGeneration; public LifeCycleTestActor(IActorRef testActor,string id,AtomicCounter generationProvider) { this.testActor = testActor; this.id = id; this.generationProvider = generationProvider; this.CurrentGeneration = generationProvider.Next(); } private void Report(object message) { testActor.Tell(((string)message,id,CurrentGeneration)); } protected override void OnReceive(object message) { if (message is string && (string)message == "status") { testActor.Tell(("OK",id,CurrentGeneration)); } } protected override void PostStop() { Report("postStop"); } protected override void PreStart() { Report("preStart"); } protected override void PreRestart(Exception cause, object message) { Report("preRestart"); } protected override void PostRestart(Exception cause) { Report("postRestart"); } } public class LifeCycleTest2Actor : UntypedActor { private AtomicCounter generationProvider; private string id; private IActorRef testActor; private int CurrentGeneration; public LifeCycleTest2Actor(IActorRef testActor, string id, AtomicCounter generationProvider) { this.testActor = testActor; this.id = id; this.generationProvider = generationProvider; this.CurrentGeneration = generationProvider.Next(); } private void Report(object message) { testActor.Tell(((string)message, id, CurrentGeneration)); } protected override void OnReceive(object message) { if (message is string && (string)message == "status") { testActor.Tell(("OK", id, CurrentGeneration)); } } protected override void PostStop() { Report("postStop"); } protected override void PreStart() { Report("preStart"); } } [Fact(DisplayName = "invoke preRestart, preStart, postRestart when using OneForOneStrategy")] public void Actor_lifecycle_test1() { var generationProvider = new AtomicCounter(); string id = Guid.NewGuid().ToString(); var supervisor = Sys.ActorOf(Props.Create(() => new Supervisor(new OneForOneStrategy(3, TimeSpan.FromSeconds(1000), x => Directive.Restart)))); var restarterProps = Props.Create(() => new LifeCycleTestActor(TestActor, id, generationProvider)); var restarter = supervisor.Ask<IActorRef>(restarterProps).Result; ExpectMsg(("preStart", id, 0)); restarter.Tell(Kill.Instance); ExpectMsg(("preRestart", id, 0)); ExpectMsg(("postRestart", id, 1)); restarter.Tell("status"); ExpectMsg(("OK", id, 1)); restarter.Tell(Kill.Instance); ExpectMsg(("preRestart", id, 1)); ExpectMsg(("postRestart", id, 2)); restarter.Tell("status"); ExpectMsg(("OK", id, 2)); restarter.Tell(Kill.Instance); ExpectMsg(("preRestart", id, 2)); ExpectMsg(("postRestart", id, 3)); restarter.Tell("status"); ExpectMsg(("OK", id, 3)); restarter.Tell(Kill.Instance); ExpectMsg(("postStop", id, 3)); ExpectNoMsg(TimeSpan.FromSeconds(1)); Sys.Stop(supervisor); } [Fact(DisplayName="default for preRestart and postRestart is to call postStop and preStart respectively")] public void Actor_lifecycle_test2() { var generationProvider = new AtomicCounter(); string id = Guid.NewGuid().ToString(); var supervisor = Sys.ActorOf(Props.Create(() => new Supervisor(new OneForOneStrategy(3, TimeSpan.FromSeconds(1000), x => Directive.Restart)))); var restarterProps = Props.Create(() => new LifeCycleTest2Actor(TestActor, id, generationProvider)); var restarter = supervisor.Ask<IActorRef>(restarterProps).Result; ExpectMsg(("preStart", id, 0)); restarter.Tell(Kill.Instance); ExpectMsg(("postStop", id, 0)); ExpectMsg(("preStart", id, 1)); restarter.Tell("status"); ExpectMsg(("OK", id, 1)); restarter.Tell(Kill.Instance); ExpectMsg(("postStop", id, 1)); ExpectMsg(("preStart", id, 2)); restarter.Tell("status"); ExpectMsg(("OK", id, 2)); restarter.Tell(Kill.Instance); ExpectMsg(("postStop", id, 2)); ExpectMsg(("preStart", id, 3)); restarter.Tell("status"); ExpectMsg(("OK", id, 3)); restarter.Tell(Kill.Instance); ExpectMsg(("postStop", id, 3)); ExpectNoMsg(TimeSpan.FromSeconds(1)); Sys.Stop(supervisor); } [Fact(DisplayName="not invoke preRestart and postRestart when never restarted using OneForOneStrategy")] public void Actor_lifecycle_test3() { var generationProvider = new AtomicCounter(); string id = Guid.NewGuid().ToString(); var supervisor = Sys.ActorOf(Props.Create(() => new Supervisor(new OneForOneStrategy(3, TimeSpan.FromSeconds(1000), x => Directive.Restart)))); var restarterProps = Props.Create(() => new LifeCycleTest2Actor(TestActor, id, generationProvider)); var restarter = supervisor.Ask<IInternalActorRef>(restarterProps).Result; ExpectMsg(("preStart", id, 0)); restarter.Tell("status"); ExpectMsg(("OK", id, 0)); restarter.Stop(); ExpectMsg(("postStop", id, 0)); ExpectNoMsg(TimeSpan.FromSeconds(1)); } public class EmptyActor : UntypedActor { protected override void OnReceive(object message) { } protected override void PostStop() { throw new Exception("hurrah"); } } [Fact(DisplayName="log failures in postStop")] public void Log_failures_in_PostStop() { var a = Sys.ActorOf<EmptyActor>(); EventFilter.Exception<Exception>(message: "hurrah").ExpectOne(() => { a.Tell(PoisonPill.Instance); }); } public class Become { } public class BecomeActor : UntypedActor { private IActorRef testActor; public BecomeActor(IActorRef testActor) { this.testActor = testActor; } protected override void PreRestart(Exception cause, object message) { base.PreRestart(cause, message); } protected override void PostRestart(Exception cause) { base.PostRestart(cause); } protected override void OnReceive(object message) { if (message is Become) { Context.Become(OnBecome); testActor.Tell("ok"); } else { testActor.Tell(42); } } protected void OnBecome(object message) { if (message.ToString() == "fail") { throw new Exception("buh"); } else { testActor.Tell(43); } } } [Fact] public void Clear_behavior_stack_upon_restart() { var a = Sys.ActorOf(Props.Create(() => new BecomeActor(TestActor))); a.Tell("hello"); ExpectMsg(42); a.Tell(new Become()); ExpectMsg("ok"); a.Tell("hello"); ExpectMsg(43); EventFilter.Exception<Exception>("buh").ExpectOne(() => a.Tell("fail")); a.Tell("hello"); ExpectMsg(42); } public class SupervisorTestActor : UntypedActor { private IActorRef testActor; public SupervisorTestActor(IActorRef testActor) { this.testActor = testActor; } protected override void OnReceive(object message) { PatternMatch.Match(message) .With<Spawn>(m => { Context.ActorOf(Props.Create(() => new KillableActor(testActor)), m.Name); testActor.Tell(("Created", m.Name)); }) .With<ContextStop>(m => { var child = Context.Child(m.Name); Context.Stop(child); }) .With<Stop>(m => { var child = Context.Child(m.Name); ((IInternalActorRef)child).Stop(); }) .With<Count>(m => testActor.Tell(Context.GetChildren().Count())); } public class Spawn { public string Name { get; set; } } public class ContextStop { public string Name { get; set; } } public class Stop { public string Name { get; set; } } public class Count { } } public class KillableActor : UntypedActor { private IActorRef testActor; public KillableActor(IActorRef testActor) { this.testActor = testActor; } protected override void PostStop() { Debug.WriteLine("inside poststop"); testActor.Tell(("Terminated", Self.Path.Name)); } protected override void OnReceive(object message) { } } [Fact(DisplayName="If a parent receives a Terminated event for a child actor, the parent should no longer supervise it")] public void Clear_child_upon_terminated() { var names = new[] {"Bob", "Jameson", "Natasha"}; var supervisor = Sys.ActorOf(Props.Create(() => new SupervisorTestActor(TestActor))); supervisor.Tell(new SupervisorTestActor.Spawn(){ Name = names[0] }); ExpectMsg(("Created",names[0])); supervisor.Tell(new SupervisorTestActor.Count()); ExpectMsg(1); supervisor.Tell(new SupervisorTestActor.Spawn() { Name = names[1] }); ExpectMsg(("Created", names[1])); supervisor.Tell(new SupervisorTestActor.Count()); ExpectMsg(2); supervisor.Tell(new SupervisorTestActor.ContextStop() { Name = names[1] }); ExpectMsg(("Terminated", names[1])); //we need to wait for the child actor to unregister itself from the parent. //this is done after PostStop so we have no way to wait for it //ideas? Task.Delay(100).Wait(); supervisor.Tell(new SupervisorTestActor.Count()); ExpectMsg(1); supervisor.Tell(new SupervisorTestActor.Spawn() { Name = names[2] }); ExpectMsg(("Created", names[2])); Task.Delay(100).Wait(); supervisor.Tell(new SupervisorTestActor.Count()); ExpectMsg(2); supervisor.Tell(new SupervisorTestActor.Stop() { Name = names[0] }); ExpectMsg(("Terminated", names[0])); supervisor.Tell(new SupervisorTestActor.Stop() { Name = names[2] }); ExpectMsg(("Terminated", names[2])); Task.Delay(100).Wait(); supervisor.Tell(new SupervisorTestActor.Count()); ExpectMsg(0); } class MyCustomException : Exception {} [Fact(DisplayName="PreRestart should receive correct cause, message and sender")] public void Call_PreStart_with_correct_message_and_sender() { var broken = ActorOf(c => { c.Receive<string>((m, context) => { throw new MyCustomException(); }); c.OnPreRestart = (ex, mess, context) => { TestActor.Tell(ex); TestActor.Tell(mess); TestActor.Tell(context.Sender); }; }); const string message = "hello"; broken.Tell(message); ExpectMsg<MyCustomException>(); ExpectMsg(message); ExpectMsg(TestActor); } } }
35.121951
155
0.508333
[ "Apache-2.0" ]
chrillejb/akka.net
src/core/Akka.Tests/Actor/ActorLifeCycleSpec.cs
14,402
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ConvertToVector128SingleDouble() { var test = new SimpleUnaryOpTest__ConvertToVector128SingleDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ConvertToVector128SingleDouble { private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Double[] _data = new Double[Op1ElementCount]; private static Vector256<Double> _clsVar; private Vector256<Double> _fld; private SimpleUnaryOpTest__DataTable<Single, Double> _dataTable; static SimpleUnaryOpTest__ConvertToVector128SingleDouble() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned( ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar), ref Unsafe.As<Double, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Double>>() ); } public SimpleUnaryOpTest__ConvertToVector128SingleDouble() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned( ref Unsafe.As<Vector256<Double>, byte>(ref _fld), ref Unsafe.As<Double, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Double>>() ); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (double)(random.NextDouble()); } _dataTable = new SimpleUnaryOpTest__DataTable<Single, Double>( _data, new Single[RetElementCount], LargestVectorSize ); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx.ConvertToVector128Single( Unsafe.Read<Vector256<Double>>(_dataTable.inArrayPtr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx.ConvertToVector128Single( Avx.LoadVector256((Double*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx.ConvertToVector128Single( Avx.LoadAlignedVector256((Double*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx) .GetMethod( nameof(Avx.ConvertToVector128Single), new Type[] { typeof(Vector256<Double>) } ) .Invoke( null, new object[] { Unsafe.Read<Vector256<Double>>(_dataTable.inArrayPtr) } ); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx) .GetMethod( nameof(Avx.ConvertToVector128Single), new Type[] { typeof(Vector256<Double>) } ) .Invoke(null, new object[] { Avx.LoadVector256((Double*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx) .GetMethod( nameof(Avx.ConvertToVector128Single), new Type[] { typeof(Vector256<Double>) } ) .Invoke( null, new object[] { Avx.LoadAlignedVector256((Double*)(_dataTable.inArrayPtr)) } ); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx.ConvertToVector128Single(_clsVar); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector256<Double>>(_dataTable.inArrayPtr); var result = Avx.ConvertToVector128Single(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Avx.LoadVector256((Double*)(_dataTable.inArrayPtr)); var result = Avx.ConvertToVector128Single(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Avx.LoadAlignedVector256((Double*)(_dataTable.inArrayPtr)); var result = Avx.ConvertToVector128Single(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__ConvertToVector128SingleDouble(); var result = Avx.ConvertToVector128Single(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx.ConvertToVector128Single(_fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult( Vector256<Double> firstOp, void* result, [CallerMemberName] string method = "" ) { Double[] inArray = new Double[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned( ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>() ); ValidateResult(inArray, outArray, method); } private void ValidateResult( void* firstOp, void* result, [CallerMemberName] string method = "" ) { Double[] inArray = new Double[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned( ref Unsafe.As<Double, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<Double>>() ); Unsafe.CopyBlockUnaligned( ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>() ); ValidateResult(inArray, outArray, method); } private void ValidateResult( Double[] firstOp, Single[] result, [CallerMemberName] string method = "" ) { if (result[0] != (Single)(firstOp[0])) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (Single)(firstOp[i])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine( $"{nameof(Avx)}.{nameof(Avx.ConvertToVector128Single)}(Vector256<Double>): {method} failed:" ); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
34.449315
112
0.539685
[ "MIT" ]
belav/runtime
src/tests/JIT/HardwareIntrinsics/X86/Avx/ConvertToVector128Single.Double.cs
12,574
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.Mq.Inputs { public sealed class BrokerLdapServerMetadataGetArgs : Pulumi.ResourceArgs { [Input("hosts")] private InputList<string>? _hosts; /// <summary> /// List of a fully qualified domain name of the LDAP server and an optional failover server. /// </summary> public InputList<string> Hosts { get => _hosts ?? (_hosts = new InputList<string>()); set => _hosts = value; } /// <summary> /// Fully qualified name of the directory to search for a user’s groups. /// </summary> [Input("roleBase")] public Input<string>? RoleBase { get; set; } /// <summary> /// Specifies the LDAP attribute that identifies the group name attribute in the object returned from the group membership query. /// </summary> [Input("roleName")] public Input<string>? RoleName { get; set; } /// <summary> /// Search criteria for groups. /// </summary> [Input("roleSearchMatching")] public Input<string>? RoleSearchMatching { get; set; } /// <summary> /// Whether the directory search scope is the entire sub-tree. /// </summary> [Input("roleSearchSubtree")] public Input<bool>? RoleSearchSubtree { get; set; } /// <summary> /// Service account password. /// </summary> [Input("serviceAccountPassword")] public Input<string>? ServiceAccountPassword { get; set; } /// <summary> /// Service account username. /// </summary> [Input("serviceAccountUsername")] public Input<string>? ServiceAccountUsername { get; set; } /// <summary> /// Fully qualified name of the directory where you want to search for users. /// </summary> [Input("userBase")] public Input<string>? UserBase { get; set; } /// <summary> /// Specifies the name of the LDAP attribute for the user group membership. /// </summary> [Input("userRoleName")] public Input<string>? UserRoleName { get; set; } /// <summary> /// Search criteria for users. /// </summary> [Input("userSearchMatching")] public Input<string>? UserSearchMatching { get; set; } /// <summary> /// Whether the directory search scope is the entire sub-tree. /// </summary> [Input("userSearchSubtree")] public Input<bool>? UserSearchSubtree { get; set; } public BrokerLdapServerMetadataGetArgs() { } } }
32.369565
137
0.585964
[ "ECL-2.0", "Apache-2.0" ]
RafalSumislawski/pulumi-aws
sdk/dotnet/Mq/Inputs/BrokerLdapServerMetadataGetArgs.cs
2,980
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.polardb.Transform; using Aliyun.Acs.polardb.Transform.V20170801; namespace Aliyun.Acs.polardb.Model.V20170801 { public class TransformDBClusterPayTypeRequest : RpcAcsRequest<TransformDBClusterPayTypeResponse> { public TransformDBClusterPayTypeRequest() : base("polardb", "2017-08-01", "TransformDBClusterPayType", "polardb", "openAPI") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Aliyun.Acs.polardb.Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Aliyun.Acs.polardb.Endpoint.endpointRegionalType, null); } Method = MethodType.POST; } private long? resourceOwnerId; private string clientToken; private string resourceGroupId; private string period; private string resourceOwnerAccount; private string dBClusterId; private string ownerAccount; private long? ownerId; private string usedTime; private string payType; public long? ResourceOwnerId { get { return resourceOwnerId; } set { resourceOwnerId = value; DictionaryUtil.Add(QueryParameters, "ResourceOwnerId", value.ToString()); } } public string ClientToken { get { return clientToken; } set { clientToken = value; DictionaryUtil.Add(QueryParameters, "ClientToken", value); } } public string ResourceGroupId { get { return resourceGroupId; } set { resourceGroupId = value; DictionaryUtil.Add(QueryParameters, "ResourceGroupId", value); } } public string Period { get { return period; } set { period = value; DictionaryUtil.Add(QueryParameters, "Period", value); } } public string ResourceOwnerAccount { get { return resourceOwnerAccount; } set { resourceOwnerAccount = value; DictionaryUtil.Add(QueryParameters, "ResourceOwnerAccount", value); } } public string DBClusterId { get { return dBClusterId; } set { dBClusterId = value; DictionaryUtil.Add(QueryParameters, "DBClusterId", value); } } public string OwnerAccount { get { return ownerAccount; } set { ownerAccount = value; DictionaryUtil.Add(QueryParameters, "OwnerAccount", value); } } public long? OwnerId { get { return ownerId; } set { ownerId = value; DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString()); } } public string UsedTime { get { return usedTime; } set { usedTime = value; DictionaryUtil.Add(QueryParameters, "UsedTime", value); } } public string PayType { get { return payType; } set { payType = value; DictionaryUtil.Add(QueryParameters, "PayType", value); } } public override bool CheckShowJsonItemName() { return false; } public override TransformDBClusterPayTypeResponse GetResponse(UnmarshallerContext unmarshallerContext) { return TransformDBClusterPayTypeResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
21.877451
137
0.651132
[ "Apache-2.0" ]
aliyun/aliyun-openapi-net-sdk
aliyun-net-sdk-polardb/Polardb/Model/V20170801/TransformDBClusterPayTypeRequest.cs
4,463
C#
// <auto-generated> /* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Text.Json; using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; namespace Org.OpenAPITools.Model { /// <summary> /// Banana /// </summary> public partial class Banana : IEquatable<Banana>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="Banana" /> class. /// </summary> /// <param name="lengthCm">lengthCm</param> public Banana(decimal lengthCm = default) { LengthCm = lengthCm; } /// <summary> /// Gets or Sets LengthCm /// </summary> [JsonPropertyName("lengthCm")] public decimal LengthCm { get; set; } /// <summary> /// Gets or Sets additional properties /// </summary> [JsonExtensionData] public Dictionary<string, JsonElement> AdditionalProperties { get; set; } = new Dictionary<string, JsonElement>(); /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Banana {\n"); sb.Append(" LengthCm: ").Append(LengthCm).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return OpenAPIClientUtils.compareLogic.Compare(this, input as Banana).AreEqual; } /// <summary> /// Returns true if Banana instances are equal /// </summary> /// <param name="input">Instance of Banana to be compared</param> /// <returns>Boolean</returns> public bool Equals(Banana input) { return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; hashCode = (hashCode * 59) + this.LengthCm.GetHashCode(); if (this.AdditionalProperties != null) { hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); } return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
32.336134
159
0.593295
[ "Apache-2.0" ]
BitCaesar/openapi-generator
samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Banana.cs
3,848
C#
using RestWithASPNET.Model.Base; using System.Collections.Generic; namespace RestWithASPNET.Repository { public interface IRepository<T> where T : BaseEntity { T Create(T item); T FindByID(long id); List<T> FindAll(); T Update(T item); void Delete(long id); bool Exists(long id); List<T> FindPaged(string query); int GetCount(string query); } }
24.823529
56
0.623223
[ "Apache-2.0" ]
dschaly/RESTWithASP-NET5
02_RestWithASPNET_Person/RestWithASPNET/RestWithASPNET/Repository/Generic/IRepository.cs
424
C#
using System.Diagnostics; using Summer.Base.Model; using Spring.Util; using UnityEditor; using UnityEngine; namespace Summer.Editor.Misc { /// <summary> /// 打开文件夹相关的实用函数。 /// </summary> public class OpenFolderTools { /// <summary> /// 打开 Data Path 文件夹。 /// </summary> [MenuItem("Summer/Open Folder/Data Path", false, 10)] public static void OpenFolderDataPath() { Execute(Application.dataPath); } /// <summary> /// 打开 Persistent Data Path 文件夹。 /// </summary> [MenuItem("Summer/Open Folder/Persistent Data Path", false, 11)] public static void OpenFolderPersistentDataPath() { Execute(Application.persistentDataPath); } /// <summary> /// 打开 Streaming Assets Path 文件夹。 /// </summary> [MenuItem("Summer/Open Folder/Streaming Assets Path", false, 12)] public static void OpenFolderStreamingAssetsPath() { Execute(Application.streamingAssetsPath); } /// <summary> /// 打开 Temporary Cache Path 文件夹。 /// </summary> [MenuItem("Summer/Open Folder/Temporary Cache Path", false, 13)] public static void OpenFolderTemporaryCachePath() { Execute(Application.temporaryCachePath); } /// <summary> /// 打开 Console Log Path 文件夹。 /// </summary> [MenuItem("Summer/Open Folder/Console Log Path", false, 14)] public static void OpenFolderConsoleLogPath() { Execute(System.IO.Path.GetDirectoryName(Application.consoleLogPath)); } /// <summary> /// 打开指定路径的文件夹。 /// </summary> /// <param name="folder">要打开的文件夹的路径。</param> public static void Execute(string folder) { folder = StringUtils.Format("\"{}\"", folder); switch (Application.platform) { case RuntimePlatform.WindowsEditor: Process.Start("Explorer.exe", folder.Replace('/', '\\')); break; case RuntimePlatform.OSXEditor: Process.Start("open", folder); break; default: throw new GameFrameworkException(StringUtils.Format("Not support open folder on '{}' platform.", Application.platform.ToString())); } } } }
29.891566
151
0.545748
[ "MIT" ]
Mu-L/Tank
Assets/Summer/Editor/Misc/OpenFolderTools.cs
2,613
C#
using System; namespace VoxViewer.DesktopGL { /// <summary> /// The main class. /// </summary> public static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { using (var game = new VoxViewer()) game.Run(); } } }
18.857143
53
0.479798
[ "MIT" ]
Jjagg/Bawx
VoxViewer.DesktopGL/Program.cs
398
C#
using IndicoInterface.NET.SimpleAgendaDataModel; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace t_IndicoInterface { /// <summary> /// Summary description for t_SimpleAgendaDataModel /// </summary> [TestClass] public class t_SimpleAgendaDataModel { [TestMethod] public void TestTalkEquivalence() { Talk t1 = new Talk(); Talk t2 = new Talk(); t1.ID = "s1234"; t2.ID = "s1234"; t1.SlideURL = "hithere"; t2.SlideURL = "hithere"; Assert.IsTrue(t1.Equals(t2), "Expected explicit call to Equals to show things are the same!"); bool temp = t1 == t2; Assert.IsTrue(t1 == t2, "The talks should be equal, but they aren't"); Assert.IsFalse(t1 != t2, "The talks are equal, so != should have failed!"); t1.SlideURL = "bogus"; Assert.IsFalse(t1 == t2, "The talks should not be equal, but they are!"); Assert.IsTrue(t1 != t2, "The talks are not equal, so != should have been fine!"); t1.SlideURL = t2.SlideURL; t1.ID = "freak"; Assert.IsFalse(t1 == t2, "The talks should not be equal, but they are!"); Assert.IsTrue(t1 != t2, "The talks slide URL are not equal, should have != been true!"); } } }
35.025641
106
0.57101
[ "MIT" ]
gordonwatts/IndicoInterface.NET
IndicoInterface.NET.Test/t_SimpleAgendaDataModel.cs
1,368
C#
using PipServices.Commons.Config; using PipServices.Commons.Validate; using System; using System.Collections.Generic; using System.Text; namespace PipServices.Settings.Data.Version1 { public class SettingsV1Schema : ObjectSchema { public SettingsV1Schema() { WithOptionalProperty("id", TypeCode.String); WithOptionalProperty("update_time", TypeCode.DateTime); WithOptionalProperty("parameters", null); // Dictionary<string, dynamic> } } }
27
84
0.693957
[ "MIT" ]
pip-services-infrastructure/pip-services-settings-dotnet
src/Data/Version1/SettingsV1Schema.cs
515
C#
// ---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // ---------------------------------------------------------------------------- using System; namespace Microsoft.WindowsAzure.MobileServices { /// <summary> /// Attribute applied to a member of a type to specify that it represents /// the createdAt system property. /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] public class CreatedAtAttribute : Attribute, ISystemPropertyAttribute { /// <summary> /// Initializes a new instance of the CreatedAtAttribute class. /// </summary> public CreatedAtAttribute() { } /// <summary> /// Gets the system property the attribute represents. /// </summary> MobileServiceSystemProperties ISystemPropertyAttribute.SystemProperty { get { return MobileServiceSystemProperties.CreatedAt; } } } }
31.228571
80
0.53065
[ "Apache-2.0" ]
AndreyMitsyk/azure-mobile-apps-net-client
src/Microsoft.Azure.Mobile.Client/Table/Serialization/CreatedAtAttribute.cs
1,095
C#
using Abstractions; using Abstractions.Navigation; using Abstractions.Stores.Content.Safety; using DataObjects; using DataObjects.DTOS.TreePlanting; using EDCORE.Helpers; using MvvmHelpers; using INavigation = Abstractions.Navigation.INavigation; namespace EDCORE.ViewModel { public class TreePlantingSearchModel : SearchModelBase<TreePlantingSearchDto>, IGeneralManagementPlanSearchModel<TreePlantingSearchDto> { private ITreePlantingStore _treePlantingStore; public TreePlantingSearchModel(IWTTimer iWTimer, ITreePlantingStore treePlantingStore, IPlatformEventHandling iPlatformEventHandling, INavigation iNavigation, IPageMessageBus iPageMessageBus, ILinkContainer iLinkContainer, ITelerikConvertors iTelerikConvertors, ICache iCache) : base(iPlatformEventHandling, iWTimer, iNavigation,iPageMessageBus, iTelerikConvertors,iCache) { GetData(treePlantingStore, iCache); _treePlantingStore = treePlantingStore; LoadData = new RelayCommand((x) => { _iNavigation.Navigate(iLinkContainer.TreePlantingEditor.Editor(), StateContainer.Create(SelectedRecord.ManagementUnitID, false)); }); } private void GetData(ITreePlantingStore treePlantingStore, ICache iCache) { SearchData = new ObservableRangeCollection<TreePlantingSearchDto>(); SearchData.AddRange(treePlantingStore.GetTreePlantingDtos(iCache.CurrentUserRole(),iCache.CurrentUser(), iCache.GetApplication(), iCache.CurrentUserRegion())); OnPropertyChanged("SearchData"); } public override void HandleMessage(EdMessage message) { if (IsDisposed) return; if (message.EdEvent == EdEvent.ApplicationChanged) { if (MessageFilter.FilterHandledMessages(message, InstanceID)) return; GetData(_treePlantingStore, _iCache); } else { base.HandleMessage(message); } } } }
33.746032
145
0.681562
[ "MIT" ]
GeorgeThackrayWT/GraphQLSample
ED/EDCORE/ViewModel/TreePlanting/TreePlantingSearchModel.cs
2,128
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { //code to call feature1 Program p = new Program(); Console.WriteLine(p.add(10, 5)); } public int add(int x, int y) { return x + y+10; } } }
18.375
44
0.544218
[ "MIT" ]
supreethbks26/gitvisiual
ConsoleApp1/ConsoleApp1/Program.cs
443
C#
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using WForest.Interactions; using WForest.Props.Interfaces; using WForest.Rendering; using WForest.Utilities.Collections; using WForest.Widgets.Interfaces; namespace WForest.Utilities.WidgetUtils { public abstract class WidgetDecorator : IWidget { private readonly IWidget _widget; protected WidgetDecorator(IWidget widget) { _widget = widget; } /// <inheritdoc/> public RectangleF Space { get => _widget.Space; set => _widget.Space = value; } /// <inheritdoc/> public MarginValues Margins { get => _widget.Margins; set => _widget.Margins = value; } /// <inheritdoc/> public Color Color { get => _widget.Color; set => _widget.Color = value; } /// <inheritdoc/> public ICollection<Action<IRenderer>> PostDrawActions => _widget.PostDrawActions; /// <inheritdoc/> public PropCollection Props => _widget.Props; /// <inheritdoc/> public IPropHolder WithProp(IProp prop) => _widget.WithProp(prop); internal void ApplyProps() => _widget.ApplyProps(); /// <inheritdoc/> public Interaction CurrentInteraction { get => _widget.CurrentInteraction; set => _widget.CurrentInteraction = value; } /// <inheritdoc/> public virtual void Draw(IRenderer renderer) => _widget.Draw(renderer); /// <inheritdoc/> public IWidget? Parent { get => _widget.Parent; set => _widget.Parent = value; } /// <inheritdoc/> public ICollection<IWidget> Children => _widget.Children; /// <inheritdoc/> public IWidget AddChild(IWidget widget) => _widget.AddChild(widget); } }
26.039474
89
0.578575
[ "MIT" ]
giusdp/MG-WForest
WForest/src/Utilities/WidgetUtils/WidgetDecorator.cs
1,981
C#
#region License // TableDependency, SqlTableDependency // Copyright (c) 2015-2018 Christian Del Bianco. All rights reserved. // // 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; namespace TableDependency.EventArgs { public class ErrorEventArgs : BaseEventArgs { #region Properties public string Message { get; } public Exception Error { get; protected set; } #endregion #region Constructors internal ErrorEventArgs( Exception e, string server, string database, string sender) : this("TableDependency stopped working", e, server, database, sender) { } internal ErrorEventArgs( string message, Exception e, string server, string database, string sender) : base(server, database, sender) { this.Message = message; this.Error = e; } #endregion } }
31.646154
97
0.672825
[ "MIT" ]
GeorgeR/monitor-table-change-with-sqltabledependency
TableDependency/EventArgs/ErrorEventArgs.cs
2,059
C#
 using System; namespace StatelessIdentity.UserProviders.Discord.RestClient { public static class Defaults { public static TimeSpan HttpClientTimeout = TimeSpan.FromSeconds(10); public static string TokenUrl = "https://discord.com/api/oauth2/token"; public static string GetUserUrl = "https://discord.com/api/users/@me"; } }
27.923077
79
0.710744
[ "MIT" ]
shawntoffel/StatelessIdentity
StatelessIdentity.UserProviders.Discord/RestClient/Defaults.cs
365
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Dayu.V20180709.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class DescribeUnBlockStatisResponse : AbstractModel { /// <summary> /// 解封总配额数 /// </summary> [JsonProperty("Total")] public ulong? Total{ get; set; } /// <summary> /// 已使用次数 /// </summary> [JsonProperty("Used")] public ulong? Used{ get; set; } /// <summary> /// 统计起始时间 /// </summary> [JsonProperty("BeginTime")] public string BeginTime{ get; set; } /// <summary> /// 统计结束时间 /// </summary> [JsonProperty("EndTime")] public string EndTime{ get; set; } /// <summary> /// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 /// </summary> [JsonProperty("RequestId")] public string RequestId{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "Total", this.Total); this.SetParamSimple(map, prefix + "Used", this.Used); this.SetParamSimple(map, prefix + "BeginTime", this.BeginTime); this.SetParamSimple(map, prefix + "EndTime", this.EndTime); this.SetParamSimple(map, prefix + "RequestId", this.RequestId); } } }
30.291667
81
0.601559
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Dayu/V20180709/Models/DescribeUnBlockStatisResponse.cs
2,285
C#
// // Copyright (c) Seal Report (sealreport@gmail.com), http://www.sealreport.org. // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. http://www.apache.org/licenses/LICENSE-2.0.. // using System; using System.Collections.Generic; using System.Text; using System.Reflection; using System.ComponentModel; using Seal.Model; using System.Data.OleDb; using System.Text.RegularExpressions; using System.Web; using RazorEngine.Templating; using System.IO; using System.Diagnostics; using System.Security.Principal; using System.Data; using System.Data.Common; using System.Data.Odbc; using System.Xml.Serialization; using System.Globalization; using System.Net.Mail; using System.Data.SqlClient; using System.Linq; using System.Runtime.InteropServices; using Oracle.ManagedDataAccess.Client; using System.Xml; namespace Seal.Helpers { /// <summary> /// Helper Objects /// </summary> internal class NamespaceDoc { } public partial class Helper { public static string GetEnumDescription(Type type, Object value) { FieldInfo fi = type.GetField(Enum.GetName(type, value)); DescriptionAttribute dna = (DescriptionAttribute)Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute)); if (dna != null) return dna.Description; else return value.ToString(); } static public void CopyProperties(object src, object dest, string[] skipNames = null) { var xmlIgnore = new XmlIgnoreAttribute(); foreach (PropertyDescriptor item in TypeDescriptor.GetProperties(src)) { if (skipNames != null && skipNames.Contains(item.Name)) continue; if (item.Attributes.Contains(xmlIgnore)) continue; item.SetValue(dest, item.GetValue(src)); } } static public bool ArePropertiesIdentical(object obj1, object obj2, string skipEmptySuffix = "") { bool result = true; foreach (PropertyDescriptor item in TypeDescriptor.GetProperties(obj1)) { if (item.IsReadOnly) continue; if (!string.IsNullOrEmpty(skipEmptySuffix) && string.IsNullOrEmpty(item.GetValue(obj1).ToString()) && item.Name.EndsWith(skipEmptySuffix)) continue; if (item.GetValue(obj1).ToString() != item.GetValue(obj2).ToString()) { result = false; break; } } return result; } static public void CopyPropertiesDifferentObjects(object src, object dest) { var propSource = TypeDescriptor.GetProperties(src); var propDest = TypeDescriptor.GetProperties(dest); foreach (PropertyDescriptor itemDest in propDest) { var itemSource = propSource.Find(itemDest.Name, true); if (itemSource != null) { try { itemDest.SetValue(dest, itemSource.GetValue(src)); } catch (Exception ex) { Console.WriteLine(itemDest.Name + " " + ex.Message); } } } } static public void CopyPropertiesFromReference(object defaultObject, object referenceObject, object destObject) { foreach (PropertyDescriptor item in TypeDescriptor.GetProperties(defaultObject)) { if (item.GetValue(destObject) == item.GetValue(defaultObject)) item.SetValue(destObject, item.GetValue(referenceObject)); } } static public void SetPropertyValue(object item, string propertyName, string propertyValue) { PropertyInfo prop = item.GetType().GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance); if (null != prop && prop.CanWrite) { if (prop.PropertyType.IsEnum) { var propertyVals = propertyValue.Split(' '); prop.SetValue(item, Enum.Parse(prop.PropertyType, propertyVals[0])); } else if (prop.PropertyType.Name == "Boolean" && !string.IsNullOrWhiteSpace(propertyValue)) { prop.SetValue(item, bool.Parse(propertyValue)); } else if (prop.PropertyType.Name == "Int32") { prop.SetValue(item, int.Parse(propertyValue)); } else { prop.SetValue(item, propertyValue); } } } static public string NewGUID() { return Guid.NewGuid().ToString().Replace("-", ""); } static public string QuoteDouble(string input) { if (input == null) input = ""; return string.Format("\"{0}\"", input.Replace("\"", "\"\"")); } static public string QuoteSingle(string input) { if (input == null) input = ""; return string.Format("'{0}'", input.Replace("'", "''")); } static public string RemoveWhitespace(string input) { return new string(input.ToCharArray() .Where(c => !Char.IsWhiteSpace(c)) .ToArray()); } static public string FirstNotEmpty(string str1, string str2 = null, string str3 = null, string str4 = null, string str5 = null) { if (!string.IsNullOrEmpty(str1)) return str1; if (!string.IsNullOrEmpty(str2)) return str2; if (!string.IsNullOrEmpty(str3)) return str3; if (!string.IsNullOrEmpty(str4)) return str4; if (!string.IsNullOrEmpty(str5)) return str5; return ""; } static public string AddAttribute(string name, string value) { if (!string.IsNullOrWhiteSpace(value)) return string.Format("{0}='{1}'", name, value); return ""; } static public string AddIfNotNull(string prefix, object input, string suffix) { if (input != null && input.ToString() != "") return prefix + input.ToString() + suffix; return ""; } static public string AddIfNotEmpty(string prefix, string input, string suffix) { if (!string.IsNullOrEmpty(input)) return prefix + input + suffix; return ""; } static public string AddNotEmpty(string separator, string input) { if (!string.IsNullOrEmpty(input)) return separator + input; return ""; } static public string AddNotEmpty2(string input, string separator) { if (!string.IsNullOrEmpty(input)) return input + separator; return ""; } static public void AddValue(ref string input, string separator, string value) { if (!string.IsNullOrEmpty(input)) input += separator + value; else input = value; } static public void AddValue(ref StringBuilder input, string separator, string value) { if (input.Length > 0) input.Append(separator + value); else input = new StringBuilder(value); } static public bool CompareTrim(string s1, string s2) { if (string.IsNullOrEmpty(s1) && string.IsNullOrEmpty(s2)) return true; if (s1 != null && s2 != null) return s1.Trim() == s2.Trim(); return false; } static public List<string> GetStringList(string listInput) { var result = new List<string>(); if (!string.IsNullOrEmpty(listInput)) { foreach (var input in listInput.Replace("\r\n", "§").Replace("\r", "§").Replace("\n", "§").Split('§')) { if (!string.IsNullOrEmpty(input)) result.Add(input); } } return result; } static public bool ValidateNumeric(string value, out Double d) { bool result = false; if (Double.TryParse(value, out d)) { result = true; } else { if (value.Contains(".")) value = value.Replace(".", ","); else if (value.Contains(",")) value = value.Replace(",", "."); if (Double.TryParse(value, out d)) result = true; } return result; } static public string ConcatCellValues(ResultCell[] cells, string separator) { string result = ""; foreach (var cell in cells) Helper.AddValue(ref result, separator, cell.DisplayValue); return result; } static public string IfNullOrEmpty(string value, string defaultValue) { if (string.IsNullOrEmpty(value)) return defaultValue; return value; } static public string ToHtml(string value) { if (value != null) return HttpUtility.HtmlEncode(value).Replace("\r\n", "<br>").Replace("\n", "<br>"); return ""; } static public string ToJS(bool value) { return value.ToString().ToLower(); } static public string ToJS(string value) { if (string.IsNullOrEmpty(value)) return ""; return HttpUtility.JavaScriptStringEncode(value); } static public string ToMomentJSFormat(CultureInfo culture, string datetimeFormat) { string format = datetimeFormat; if (datetimeFormat == "d") format = culture.DateTimeFormat.ShortDatePattern; else if (datetimeFormat == "D") format = culture.DateTimeFormat.LongDatePattern; else if (datetimeFormat == "t") format = culture.DateTimeFormat.ShortTimePattern; else if (datetimeFormat == "T") format = culture.DateTimeFormat.LongTimePattern; else if (datetimeFormat == "g") format = culture.DateTimeFormat.ShortDatePattern + " " + culture.DateTimeFormat.ShortTimePattern; else if (datetimeFormat == "G") format = culture.DateTimeFormat.ShortDatePattern + " " + culture.DateTimeFormat.LongTimePattern; else if (datetimeFormat == "f") format = culture.DateTimeFormat.LongDatePattern + " " + culture.DateTimeFormat.ShortTimePattern; else if (datetimeFormat == "F") format = culture.DateTimeFormat.LongDatePattern + " " + culture.DateTimeFormat.LongTimePattern; return format.Replace("y", "Y").Replace("d", "D").Replace("tt", "A").Replace("z", "Z").Replace("/", culture.DateTimeFormat.DateSeparator); } static public string RemoveHTMLTags(string value) { return Regex.Replace(value, @"<[^>]+>|&nbsp;", "").Trim(); } static public string GetUniqueName(string name, List<string> entities) { string result; int i = 1; while (true) { result = name; if (i != 1) result += i.ToString(); if (!entities.Contains(result)) break; i++; } return result; } static public string DBNameToDisplayName(string name) { string result = name; result = string.Join(" ", Regex.Split(result, @"([A-Z][a-z]+)")); result = result.Replace('_', ' ').Trim(); result = result.Replace(" ", " "); result = result.Replace(" ", " "); result = result.Replace(" ", " "); if (result.Length > 0) result = result.Substring(0, 1).ToUpper() + result.Substring(1); return result.Trim(); } static public ColumnType DatabaseToNetTypeConverter(object dbValue) { ColumnType result = ColumnType.Text; try { int intValue; if (Int32.TryParse(dbValue.ToString(), out intValue)) { OleDbType columnType = (OleDbType)intValue; result = Helper.NetTypeConverter(Helper.OleDbToNetTypeConverter(columnType)); if (columnType == OleDbType.WChar || columnType == OleDbType.VarWChar || columnType == OleDbType.LongVarWChar) result = ColumnType.UnicodeText; } else { var dbValueString = dbValue.ToString().ToLower(); if (dbValueString.Contains("number") || dbValueString.Contains("double") || dbValueString.Contains("numeric")) result = ColumnType.Numeric; else if (dbValueString.Contains("date")) result = ColumnType.DateTime; } } catch (Exception ex) { Console.WriteLine(ex.Message); } return result; } static public ColumnType ODBCToNetTypeConverter(string odbcType) { ColumnType result = ColumnType.Text; try { result = Helper.OdbcTypeConverter(odbcType); } catch (Exception ex) { Console.WriteLine(ex.Message); } return result; } static public ColumnType OdbcTypeConverter(string dbType) { string t = dbType.ToLower(); if (t == "char" || t == "varchar" || t == "varchar2" || t == "text" || t == "uniqueidentifier") return ColumnType.Text; if (t == "nchar" || t == "ntext" || t == "nvarchar") return ColumnType.UnicodeText; if (t == "date" || t == "datetime" || t == "datetime2" || t == "smalldatetime" || t == "timestamp") return ColumnType.DateTime; return ColumnType.Numeric; } static public Type OleDbToNetTypeConverter(OleDbType oleDbTypeNumber) { switch ((int)oleDbTypeNumber) { case 0: return typeof(Nullable); case 2: return typeof(Int16); case 3: return typeof(Int32); case 4: return typeof(Single); case 5: return typeof(Double); case 6: return typeof(Decimal); case 7: return typeof(DateTime); case 8: return typeof(String); case 9: return typeof(Object); case 10: return typeof(Exception); case 11: return typeof(Boolean); case 12: return typeof(Object); case 13: return typeof(Object); case 14: return typeof(Decimal); case 16: return typeof(SByte); case 17: return typeof(Byte); case 18: return typeof(UInt16); case 19: return typeof(UInt32); case 20: return typeof(Int64); case 21: return typeof(UInt64); case 64: return typeof(DateTime); case 72: return typeof(Guid); case 128: return typeof(Byte[]); case 129: return typeof(String); case 130: return typeof(String); case 131: return typeof(Decimal); case 133: return typeof(DateTime); case 134: return typeof(TimeSpan); case 135: return typeof(DateTime); case 138: return typeof(Object); case 139: return typeof(Decimal); case 200: return typeof(String); case 201: return typeof(String); case 202: return typeof(String); case 203: return typeof(String); case 204: return typeof(Byte[]); case 205: return typeof(Byte[]); } throw (new Exception("DataType Not Supported")); } static public ColumnType NetTypeConverter(Type netType) { if (netType == typeof(string) || netType == typeof(Guid)) return ColumnType.Text; if (netType == typeof(DateTime)) return ColumnType.DateTime; return ColumnType.Numeric; } public static List<String> GetSystemDriverList() { List<string> names = new List<string>(); // get system dsn's Microsoft.Win32.RegistryKey reg = (Microsoft.Win32.Registry.LocalMachine).OpenSubKey("Software"); if (reg != null) { reg = reg.OpenSubKey("ODBC"); if (reg != null) { reg = reg.OpenSubKey("ODBCINST.INI"); if (reg != null) { reg = reg.OpenSubKey("ODBC Drivers"); if (reg != null) { // Get all DSN entries defined in DSN_LOC_IN_REGISTRY. foreach (string sName in reg.GetValueNames()) { names.Add(sName); } } try { reg.Close(); } catch { /* ignore this exception if we couldn't close */ } } } } return names; } static public string ConvertNumericStandardFormat(NumericStandardFormat format) { if (format == NumericStandardFormat.Numeric0) return "N0"; else if (format == NumericStandardFormat.Numeric1) return "N1"; else if (format == NumericStandardFormat.Numeric2) return "N2"; else if (format == NumericStandardFormat.Numeric3) return "N3"; else if (format == NumericStandardFormat.Numeric4) return "N4"; else if (format == NumericStandardFormat.Percentage0) return "P0"; else if (format == NumericStandardFormat.Percentage1) return "P1"; else if (format == NumericStandardFormat.Percentage2) return "P2"; else if (format == NumericStandardFormat.Currency0) return "C0"; else if (format == NumericStandardFormat.Currency2) return "C2"; else if (format == NumericStandardFormat.Decimal) return "D"; else if (format == NumericStandardFormat.Decimal0) return "D0"; else if (format == NumericStandardFormat.Decimal1) return "D1"; else if (format == NumericStandardFormat.Decimal2) return "D2"; else if (format == NumericStandardFormat.Decimal3) return "D3"; else if (format == NumericStandardFormat.Decimal4) return "D4"; else if (format == NumericStandardFormat.Exponential) return "E"; else if (format == NumericStandardFormat.Exponential2) return "E2"; else if (format == NumericStandardFormat.Fixedpoint) return "F"; else if (format == NumericStandardFormat.Fixedpoint2) return "F2"; else if (format == NumericStandardFormat.General) return "G"; else if (format == NumericStandardFormat.General2) return "G2"; else if (format == NumericStandardFormat.General5) return "G5"; else if (format == NumericStandardFormat.Hexadecimal) return "H"; else if (format == NumericStandardFormat.Hexadecimal8) return "H8"; return "0"; } static public string ConvertDateTimeStandardFormat(DateTimeStandardFormat format) { if (format == DateTimeStandardFormat.ShortDate) return "d"; else if (format == DateTimeStandardFormat.LongDate) return "D"; else if (format == DateTimeStandardFormat.ShortTime) return "t"; else if (format == DateTimeStandardFormat.LongTime) return "T"; else if (format == DateTimeStandardFormat.ShortDateTime) return "g"; else if (format == DateTimeStandardFormat.LongDateTime) return "G"; else if (format == DateTimeStandardFormat.FullShortDateTime) return "f"; else if (format == DateTimeStandardFormat.FullLongDateTime) return "F"; return "0"; } static public string GetExceptionMessage(TemplateCompilationException ex) { var result = new StringBuilder(""); var firstError = ""; foreach (var err in ex.CompilerErrors) { if (string.IsNullOrEmpty(firstError) && err.Line > 0) firstError = err.ErrorText + "\r\n\r\n"; result.AppendFormat("{0}\r\nLine {1} Column {2} Error Number {3}\r\n", err.ErrorText, err.Line, err.Column, err.ErrorNumber); } return firstError + result.ToString(); } static public void ExecutePrePostSQL(DbConnection connection, string sql, object model, bool ignoreErrors) { try { if (!string.IsNullOrEmpty(sql)) { string finalSql = RazorHelper.CompileExecute(sql, model); if (!string.IsNullOrEmpty(sql)) { var command = connection.CreateCommand(); command.CommandText = finalSql; command.ExecuteNonQuery(); } } } catch { if (!ignoreErrors) throw; } } public static string FormatMessage(string message) { return string.Format("[{0} {1}] {2} ", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString(), message); } public static string CleanFileName(string s) { foreach (char character in Path.GetInvalidFileNameChars()) { s = s.Replace(character.ToString(), string.Empty); } foreach (char character in Path.GetInvalidPathChars()) { s = s.Replace(character.ToString(), string.Empty); } return s; } static DateTime NextDailyPuge = DateTime.MinValue; const string TaskSchedulerEntry = "Seal Task Scheduler"; public const string DailyLogExecutions = "executions"; public const string DailyLogEvents = "events"; public const string DailyLogSchedules = "schedules"; public static void WriteDailyLog(string prefix, string logsFolder, int logDays, string message) { try { if (logDays <= 0) return; if (!Directory.Exists(logsFolder)) Directory.CreateDirectory(logsFolder); lock (TaskSchedulerEntry) { string logFileName = Path.Combine(logsFolder, string.Format("{0}_{1:yyyy_MM_dd}.txt", prefix, DateTime.Now)); File.AppendAllText(logFileName, message); if (NextDailyPuge < DateTime.Now) { NextDailyPuge = DateTime.Now.AddDays(1); foreach (var file in Directory.GetFiles(logsFolder, "*")) { //purge old files... if (File.GetLastWriteTime(file).AddDays(logDays) < DateTime.Now) { try { File.Delete(file); } catch (Exception ex) { Console.WriteLine(message + "\r\n" + ex.Message); }; } } } } } catch (Exception ex) { Console.WriteLine(message + "\r\n" + ex.Message); } } public static void WriteLogException(string context, Exception ex) { WriteDailyLog(DailyLogEvents, Repository.Instance.LogsFolder, Repository.Instance.Configuration.LogDays, $"Exception got in {context}\r\n{ex.Message}\r\n{ex.StackTrace}\r\n"); if (ex.InnerException != null) WriteDailyLog(DailyLogEvents, Repository.Instance.LogsFolder, Repository.Instance.Configuration.LogDays, $"Inner Exception:\r\n{ex.InnerException.Message}\r\n{ex.InnerException.StackTrace}"); Console.WriteLine(ex.Message); } public static void WriteLogEntry(string source, EventLogEntryType type, string message, params object[] args) { string msg = message; try { if (args.Length != 0) msg = string.Format(message, args); } catch (Exception ex) { Console.WriteLine(ex.Message); } try { Console.WriteLine(msg); var fullMessage = string.Format("**********\r\n{0} {1}\r\n{2}\r\n\r\n", DateTime.Now, type.ToString(), msg); WriteDailyLog(source == TaskSchedulerEntry ? DailyLogSchedules : DailyLogEvents, Repository.Instance.LogsFolder, Repository.Instance.Configuration.LogDays, fullMessage); if (msg.Length > 25000) { msg = msg.Substring(0, 25000) + "\r\n...\r\nMessage truncated, check the event log files in the Logs Repository sub-folder."; } } catch (Exception ex) { Console.WriteLine(ex.Message); try { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) EventLog.WriteEntry(source, ex.Message, EventLogEntryType.Error); } catch { } } finally { try { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) EventLog.WriteEntry(source, msg, type); } catch { } } } public static void WriteLogEntryScheduler(EventLogEntryType type, string message, params object[] args) { WriteLogEntry(TaskSchedulerEntry, type, message, args); } public static bool IsMachineAdministrator() { try { WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); if (!principal.IsInRole(WindowsBuiltInRole.Administrator)) { return false; } } catch (Exception ex) { Debug.WriteLine("Couldn't determine user account status: " + ex.Message); return false; } return true; } public static bool IsValidOS() { int major = Environment.OSVersion.Version.Major; return (major >= 6); } public static void DisplayDataTable(DataTable table) { foreach (System.Data.DataRow row in table.Rows) { foreach (System.Data.DataColumn col in table.Columns) { Debug.WriteLine("{0} = {1}", col.ColumnName, row[col]); } Debug.WriteLine("============================"); } } public static DataTable GetDataTable(DbConnection connection, string sql) { DataTable result = new DataTable(); DbDataAdapter adapter = null; if (connection is OdbcConnection) { OdbcCommand command = ((OdbcConnection)connection).CreateCommand(); command.CommandTimeout = 0; command.CommandText = sql; adapter = new OdbcDataAdapter(command); } else if (connection is SqlConnection) { SqlCommand command = ((SqlConnection)connection).CreateCommand(); command.CommandTimeout = 0; command.CommandText = sql; adapter = new SqlDataAdapter(command); } else if (connection is Microsoft.Data.SqlClient.SqlConnection) { Microsoft.Data.SqlClient.SqlCommand command = ((Microsoft.Data.SqlClient.SqlConnection)connection).CreateCommand(); command.CommandTimeout = 0; command.CommandText = sql; adapter = new Microsoft.Data.SqlClient.SqlDataAdapter(command); } else if (connection is MySql.Data.MySqlClient.MySqlConnection) { MySql.Data.MySqlClient.MySqlCommand command = ((MySql.Data.MySqlClient.MySqlConnection)connection).CreateCommand(); command.CommandTimeout = 0; command.CommandText = sql; adapter = new MySql.Data.MySqlClient.MySqlDataAdapter(command); } else if (connection is OracleConnection) { OracleCommand command = ((OracleConnection)connection).CreateCommand(); command.CommandTimeout = 0; command.CommandText = sql; adapter = new OracleDataAdapter(command); } else { OleDbCommand command = ((OleDbConnection)connection).CreateCommand(); command.CommandTimeout = 0; command.CommandText = sql; adapter = new OleDbDataAdapter(command); } adapter.Fill(result); return result; } public static bool FindReplacePattern(string source, ref int index, string pattern, string replace, StringBuilder result) { if (index + pattern.Length <= source.Length && source.Substring(index, pattern.Length) == pattern) { result.Append(replace); index += pattern.Length - 1; return true; } return false; } public static object Clone(Object source) { XmlSerializer serializer = new XmlSerializer(source.GetType()); MemoryStream ms = new MemoryStream(); serializer.Serialize(ms, source); ms.Position = 0; return serializer.Deserialize(ms); } public static void Serialize(string path, object obj, XmlSerializer serializer = null) { if (serializer == null) serializer = new XmlSerializer(obj.GetType()); using (var tw = new FileStream(path, FileMode.Create)) { using (var writer = new XmlTextWriter(tw, null) { Formatting = Formatting.Indented, Indentation = 2 }) { serializer.Serialize(writer, obj); writer.Close(); } tw.Close(); } } public static DbConnection DbConnectionFromConnectionString(ConnectionType connectionType, string connectionString) { DbConnection connection; if (connectionType == ConnectionType.MSSQLServer) { connection = new SqlConnection(connectionString); } else if (connectionType == ConnectionType.MSSQLServerMicrosoft) { connection = new Microsoft.Data.SqlClient.SqlConnection(connectionString); } else if (connectionType == ConnectionType.Odbc) { connection = new OdbcConnection(connectionString); } else if (connectionType == ConnectionType.MySQL) { connection = new MySql.Data.MySqlClient.MySqlConnection(connectionString); } else if (connectionType == ConnectionType.Oracle) { connection = new OracleConnection(connectionString); } else { OleDbConnectionStringBuilder builder = new OleDbConnectionStringBuilder(connectionString); string provider = builder["Provider"].ToString(); if (provider.StartsWith("MSDASQL")) { //Provider=MSDASQL.1;Persist Security Info=False;Extended Properties="DSN=mysql2;SERVER=localhost;UID=root;DATABASE=sakila;PORT=3306";Initial Catalog=sakila //Provider=MSDASQL.1;Persist Security Info=True;Data Source=mysql;Initial Catalog=sakila //Provider=MSDASQL.1;Persist Security Info=False;Extended Properties="DSN=brCRM;DBQ=C:\tem\adb.mdb;DriverId=25;FIL=MS Access;MaxBufferSize=2048;PageTimeout=5;UID=admin;" //Extract the real ODBC connection string...to be able to use the OdbcConnection string odbcConnectionString = ""; if (builder.ContainsKey("Extended Properties")) odbcConnectionString = builder["Extended Properties"].ToString(); else if (builder.ContainsKey("Data Source") && !string.IsNullOrEmpty(builder["Data Source"].ToString())) odbcConnectionString = "DSN=" + builder["Data Source"].ToString(); if (odbcConnectionString != "" && builder.ContainsKey("Initial Catalog")) odbcConnectionString += ";DATABASE=" + builder["Initial Catalog"].ToString(); if (odbcConnectionString != "" && builder.ContainsKey("User ID")) odbcConnectionString += ";UID=" + builder["User ID"].ToString(); if (odbcConnectionString != "" && builder.ContainsKey("Password")) odbcConnectionString += ";PWD=" + builder["Password"].ToString(); connection = new OdbcConnection(odbcConnectionString); } else { connection = new OleDbConnection(connectionString); } } return connection; } static public DatabaseType GetDatabaseType(string connectionString) { DatabaseType result = DatabaseType.Standard; if (connectionString.ToLower().Contains("oracle")) { result = DatabaseType.Oracle; } else if (connectionString.ToLower().Contains(".mdb") || connectionString.ToLower().Contains(".accdb")) { result = DatabaseType.MSAccess; } else if (connectionString.ToLower().Contains(".xls") || connectionString.ToLower().Contains("excel driver")) { result = DatabaseType.MSExcel; } else if (connectionString.ToLower().Contains("sqlncli")) { result = DatabaseType.MSSQLServer; } return result; } static public string GetOleDbConnectionString(string input, string userName, string password) { string result = input; if (input != null && !input.Contains("User ID=") && !string.IsNullOrEmpty(userName)) result += string.Format(";User ID={0}", userName); if (input != null && !input.Contains("Password=") && !string.IsNullOrEmpty(password)) result += string.Format(";Password={0}", password); return result; } static public string GetOdbcConnectionString(string input, string userName, string password) { string result = input; if (input != null && !input.Contains("UID=") && !string.IsNullOrEmpty(userName)) result += string.Format(";UID={0}", userName); if (input != null && !input.Contains("PWD=") && !string.IsNullOrEmpty(password)) result += string.Format(";PWD={0}", password); return result; } static public string GetMongoConnectionString(string input, string userName, string password) { string result = input; try { if (result != null && result.Contains("%USER%")) result = string.Format(result.Replace("%USER%", "{0}"), userName); if (result != null && result.Contains("%PASSWORD%")) result = string.Format(result.Replace("%PASSWORD%", "{0}"), password); } catch { } return result; } static public string GetMySQLConnectionString(string input, string userName, string password) { string result = input; if (input != null && !input.Contains("UID=") && !string.IsNullOrEmpty(userName)) result += string.Format(";UID={0}", userName); if (input != null && !input.Contains("PWD=") && !string.IsNullOrEmpty(password)) result += string.Format(";PWD={0}", password); return result; } public static string HtmlMakeImageSrcData(string path) { FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); byte[] filebytes = new byte[fs.Length]; fs.Read(filebytes, 0, Convert.ToInt32(fs.Length)); var ext = Path.GetExtension(path); string type; if (ext == ".ico") type = "x-icon"; else type = ext.Replace(".", ""); if (type.ToLower() == "svg") type += "+xml"; return "data:image/" + type + ";base64," + Convert.ToBase64String(filebytes, Base64FormattingOptions.None); } public static string HtmlGetFilePath(string path) { return "file:///" + HttpUtility.HtmlEncode(path.Replace(Path.DirectorySeparatorChar.ToString(), "/")); } static public bool HasTimeFormat(DateTimeStandardFormat formatType, string format) { if (formatType.ToString().Contains("Time")) return true; return ((formatType == DateTimeStandardFormat.Custom || formatType == DateTimeStandardFormat.Default) && (format.ToLower().Contains("t") || format.Contains("H") || format.Contains("m") || format.Contains("s"))); } /// <summary> /// Add email address to a MailAddressCollection /// </summary> static public void AddEmailAddresses(MailAddressCollection collection, string input) { if (!string.IsNullOrEmpty(input)) { string[] addresses = input.Replace(";", "\r\n").Replace("\r\n", "\n").Replace("\r", "\n").Split('\n'); foreach (string address in addresses) { if (!string.IsNullOrWhiteSpace(address)) collection.Add(address); } } } //SQL Keywords management public static string ClearAllSQLKeywords(string sql, ReportModel model = null) { sql = ClearSQLKeywords(sql, Repository.EnumFilterKeyword, "filter"); sql = ClearSQLKeywords(sql, Repository.EnumValuesKeyword, "NULL"); if (model != null) sql = model.ParseCommonRestrictions(sql); sql = ClearSQLKeywords(sql, Repository.CommonRestrictionKeyword, "1=1"); sql = ClearSQLKeywords(sql, Repository.CommonValueKeyword, "NULL"); return sql; } //SQL Keywords management public static string ClearAllLINQKeywords(string script) { script = ClearSQLKeywords(script, Repository.EnumFilterKeyword, "null"); script = ClearSQLKeywords(script, Repository.EnumValuesKeyword, "null"); return script; } public static string ClearSQLKeywords(string sql, string keyword, string replacedBy) { if (string.IsNullOrEmpty(sql)) return ""; //Replace keyword by 1=1 int index = 0; do { index = sql.IndexOf(keyword, index); if (index > 0) { index += keyword.Length; for (int i = index; i < sql.Length; i++) { if (sql[i] == '}') { sql = sql.Replace(keyword + sql.Substring(index, i - index) + "}", replacedBy); index -= keyword.Length; break; } } } } while (index > 0 && index < sql.Length); return sql; } public static string AddCTE(string current, string CTE) { var result = current; if (!string.IsNullOrEmpty(result)) { if (CTE != null && CTE.Length > 5 && CTE.ToLower().Trim().StartsWith("with")) { var startIndex = CTE.ToLower().IndexOf("with"); if (startIndex >= 0) result += "," + CTE.Substring(startIndex + 5); } } else result = CTE; return result; } public static List<string> GetSQLKeywordNames(string sql, string keyword) { var result = new List<string>(); //Get keywords int index = 0; do { index = sql.IndexOf(keyword, index); if (index > 0) { index += keyword.Length; string restrictionName = ""; for (int i = index; i < sql.Length; i++) { if (sql[i] == '}') { restrictionName = sql.Substring(index, i - index); ; break; } } if (!string.IsNullOrEmpty(restrictionName)) result.Add(restrictionName); } } while (index > 0); return result; } public static string GetApplicationDirectory() { var assembly = Assembly.GetEntryAssembly(); if (assembly == null) assembly = Assembly.GetCallingAssembly(); if (assembly == null) assembly = new StackTrace().GetFrames().Last().GetMethod().Module.Assembly; return Path.GetDirectoryName(assembly.Location); } public static string FromTimeSpan(TimeSpan val, string def, Repository repository) { string result = ""; string secStr = repository == null ? "second" : repository.TranslateWebJS("second").ToLower(); string minStr = repository == null ? "minute" : repository.TranslateWebJS("minute").ToLower(); string hourStr = repository == null ? "hour" : repository.TranslateWebJS("hour").ToLower(); string dayStr = repository == null ? "day" : repository.TranslateWebJS("day").ToLower(); string secStr2 = repository == null ? "seconds" : repository.TranslateWebJS("seconds").ToLower(); string minStr2 = repository == null ? "minutes" : repository.TranslateWebJS("minutes").ToLower(); string hourStr2 = repository == null ? "hours" : repository.TranslateWebJS("hours").ToLower(); string dayStr2 = repository == null ? "days" : repository.TranslateWebJS("days").ToLower(); if (val.Seconds > 0) result = val.Seconds.ToString() + " " + (val.Seconds > 1 ? secStr2 : secStr); else if (val.Minutes > 0) result = val.Minutes.ToString() + " " + (val.Minutes > 1 ? minStr2 : minStr); else if (val.Hours > 0) result = val.Hours.ToString() + " " + (val.Hours > 1 ? hourStr2 : hourStr); else if (val.Days > 0) result = val.Days.ToString() + " " + (val.Days > 1 ? dayStr2 : dayStr); else result = def; return result; } public static TimeSpan ToTimeSpan(string str, Repository repository) { string secStr = repository == null ? "second" : repository.TranslateWebJS("second").ToLower(); string minStr = repository == null ? "minute" : repository.TranslateWebJS("minute").ToLower(); string hourStr = repository == null ? "hour" : repository.TranslateWebJS("hour").ToLower(); string dayStr = repository == null ? "day" : repository.TranslateWebJS("day").ToLower(); TimeSpan result = new TimeSpan(0, 0, 0); if (!string.IsNullOrEmpty(str)) { int val; str = str.ToLower(); if (str.Contains(secStr)) { if (int.TryParse(str.Replace(" ", "").Replace(secStr, "").Replace("s", "").Replace("e", ""), out val)) result = new TimeSpan(0, 0, val); else throw new Exception("Invalid interval"); } else if (str.Contains(minStr)) { if (int.TryParse(str.Replace(" ", "").Replace(minStr, "").Replace("s", "").Replace("e", ""), out val)) result = new TimeSpan(0, val, 0); else throw new Exception("Invalid interval"); } else if (str.Contains(hourStr)) { if (int.TryParse(str.Replace(" ", "").Replace(hourStr, "").Replace("s", "").Replace("e", ""), out val)) result = new TimeSpan(val, 0, 0); else throw new Exception("Invalid interval"); } else if (str.Contains(dayStr)) { if (int.TryParse(str.Replace(" ", "").Replace(dayStr, "").Replace("s", ""), out val)) result = new TimeSpan(val, 0, 0, 0); else throw new Exception("Invalid interval"); } } return result; } /// <summary> /// Convert an objet to a string, handling DBNull value /// </summary> static public string ToString(object obj) { if (obj != null && obj == DBNull.Value) obj = null; return Convert.ToString(obj); } /// <summary> /// Convert an objet to a datetime, handling DBNull value /// </summary> static public DateTime? ToDateTime(object obj) { if (obj != null && obj == DBNull.Value) obj = null; return obj == null ? (DateTime?)null : Convert.ToDateTime(obj, CultureInfo.InvariantCulture); } /// <summary> /// Convert an objet to a double, handling DBNull value /// </summary> static public double? ToDouble(object obj) { if (obj != null && obj == DBNull.Value) obj = null; return obj == null ? (double?)null : Convert.ToDouble(obj, CultureInfo.InvariantCulture); } } }
42.022321
234
0.537894
[ "Apache-2.0" ]
Superdrug-innovation/Seal-Report
Projects/SealLibraryWin/Helpers/Helper.cs
47,071
C#
using System; using System.IO; namespace Bing.Utils.Helpers { /// <summary> /// 常用公共操作 /// </summary> public static class Common { /// <summary> /// 获取类型 /// </summary> /// <typeparam name="T">类型</typeparam> /// <returns></returns> public static Type GetType<T>() { return GetType(typeof(T)); } /// <summary> /// 获取类型 /// </summary> /// <param name="type">类型</param> /// <returns></returns> public static Type GetType(Type type) { return Nullable.GetUnderlyingType(type) ?? type; } /// <summary> /// 换行符 /// </summary> public static string Line => Environment.NewLine; /// <summary> /// 获取物理路径 /// </summary> /// <param name="relativePath">相对路径</param> /// <returns></returns> public static string GetPhysicalPath(string relativePath) { if (string.IsNullOrWhiteSpace(relativePath)) { return string.Empty; } var rootPath = Web.WebRootPath; if (string.IsNullOrWhiteSpace(rootPath)) { return Path.GetFullPath(relativePath); } return $"{Web.RootPath}\\{relativePath.Replace("/", "\\").TrimStart('\\')}"; } /// <summary> /// 获取wwwroot路径 /// </summary> /// <param name="relativePath">相对路径</param> /// <returns></returns> public static string GetWebRootPath(string relativePath) { if (string.IsNullOrWhiteSpace(relativePath)) { return string.Empty; } var rootPath = Web.WebRootPath; if (string.IsNullOrWhiteSpace(rootPath)) { return Path.GetFullPath(relativePath); } return $"{Web.WebRootPath}\\{relativePath.Replace("/", "\\").TrimStart('\\')}"; } } }
26.075949
91
0.482039
[ "MIT" ]
ivivioutlookcom/Bing.NetCore
src/Bing.Utils/Helpers/Common.cs
2,140
C#
namespace Ding.Ui.Builders { /// <summary> /// 表单生成器 /// </summary> public class FormBuilder : TagBuilder { /// <summary> /// 初始化表单生成器 /// </summary> public FormBuilder() : base( "form" ) { } } }
19.769231
47
0.470817
[ "MIT" ]
EnhWeb/DC.Framework
src/Ding.Ui.Core/Builders/FormBuilder.cs
285
C#
using System; using CMS.FormEngine; using CMS.FormEngine.Web.UI; using CMS.Helpers; using CMS.UIControls; public partial class CMSModules_AdminControls_Controls_Class_FieldEditor_CSSsettings : CMSUserControl { #region "Variables" private FormFieldInfo ffi; #endregion #region "Parameters" /// <summary> /// FormFieldInfo of given field. /// </summary> public FormFieldInfo FieldInfo { get { return ffi; } set { ffi = value; } } /// <summary> /// Sets value indicating if control is enabled. /// </summary> public bool Enabled { set { pnlCss.Enabled = value; } } /// <summary> /// Gets or sets macroresolver used in macro editor. /// </summary> public string ResolverName { get; set; } #endregion #region "Methods" protected override void OnInit(EventArgs e) { base.OnInit(e); txtFieldCssClass.IsLiveSite = IsLiveSite; txtCaptionCellCssClass.IsLiveSite = IsLiveSite; txtCaptionCssClass.IsLiveSite = IsLiveSite; txtCaptionStyle.IsLiveSite = IsLiveSite; txtControlCellCssClass.IsLiveSite = IsLiveSite; txtControlCssClass.IsLiveSite = IsLiveSite; txtInputStyle.IsLiveSite = IsLiveSite; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); txtFieldCssClass.ResolverName = ResolverName; txtCaptionCellCssClass.ResolverName = ResolverName; txtCaptionCssClass.ResolverName = ResolverName; txtCaptionStyle.ResolverName = ResolverName; txtControlCellCssClass.ResolverName = ResolverName; txtControlCssClass.ResolverName = ResolverName; txtInputStyle.ResolverName = ResolverName; } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); lblFieldCssClass.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtFieldCssClass.NestedControl.Controls); lblCaptionCellCssClass.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtCaptionCellCssClass.NestedControl.Controls); lblCaptionCssClass.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtCaptionCssClass.NestedControl.Controls); lblCaptionStyle.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtCaptionStyle.NestedControl.Controls); lblControlCellCssClass.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtControlCellCssClass.NestedControl.Controls); lblControlCssClass.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtControlCssClass.NestedControl.Controls); lblInputStyle.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtInputStyle.NestedControl.Controls); } /// <summary> /// Load field. /// </summary> public void Reload() { if (ffi != null) { bool isMacro; txtCaptionStyle.SetValue(ffi.GetPropertyValue(FormFieldPropertyEnum.CaptionStyle, out isMacro), isMacro); txtCaptionCssClass.SetValue(ffi.GetPropertyValue(FormFieldPropertyEnum.CaptionCssClass, out isMacro), isMacro); txtCaptionCellCssClass.SetValue(ffi.GetPropertyValue(FormFieldPropertyEnum.CaptionCellCssClass, out isMacro), isMacro); txtInputStyle.SetValue(ffi.GetPropertyValue(FormFieldPropertyEnum.InputControlStyle, out isMacro), isMacro); txtControlCssClass.SetValue(ffi.GetPropertyValue(FormFieldPropertyEnum.ControlCssClass, out isMacro), isMacro); txtControlCellCssClass.SetValue(ffi.GetPropertyValue(FormFieldPropertyEnum.ControlCellCssClass, out isMacro), isMacro); txtFieldCssClass.SetValue(ffi.GetPropertyValue(FormFieldPropertyEnum.FieldCssClass, out isMacro), isMacro); pnlCss.Enabled = ffi.Visible; } else { txtCaptionStyle.SetValue(null, false); txtCaptionCssClass.SetValue(null, false); txtCaptionCellCssClass.SetValue(null, false); txtInputStyle.SetValue(null, false); txtControlCssClass.SetValue(null, false); txtControlCellCssClass.SetValue(null, false); txtFieldCssClass.SetValue(null, false); pnlCss.Enabled = true; } } /// <summary> /// Save the properties to form field info. /// </summary> /// <returns>True if success</returns> public bool Save() { if (ffi != null) { ffi.SetPropertyValue(FormFieldPropertyEnum.CaptionStyle, ValidationHelper.GetString(txtCaptionStyle.Value, String.Empty), txtCaptionStyle.IsMacro); ffi.SetPropertyValue(FormFieldPropertyEnum.CaptionCssClass, ValidationHelper.GetString(txtCaptionCssClass.Value, String.Empty), txtCaptionCssClass.IsMacro); ffi.SetPropertyValue(FormFieldPropertyEnum.CaptionCellCssClass, ValidationHelper.GetString(txtCaptionCellCssClass.Value, String.Empty), txtCaptionCellCssClass.IsMacro); ffi.SetPropertyValue(FormFieldPropertyEnum.InputControlStyle, ValidationHelper.GetString(txtInputStyle.Value, String.Empty), txtInputStyle.IsMacro); ffi.SetPropertyValue(FormFieldPropertyEnum.ControlCssClass, ValidationHelper.GetString(txtControlCssClass.Value, String.Empty), txtControlCssClass.IsMacro); ffi.SetPropertyValue(FormFieldPropertyEnum.ControlCellCssClass, ValidationHelper.GetString(txtControlCellCssClass.Value, String.Empty), txtControlCellCssClass.IsMacro); ffi.SetPropertyValue(FormFieldPropertyEnum.FieldCssClass, ValidationHelper.GetString(txtFieldCssClass.Value, String.Empty), txtFieldCssClass.IsMacro); return true; } return false; } #endregion }
37.814103
180
0.708764
[ "MIT" ]
BryanSoltis/KenticoMVCWidgetShowcase
CMS/CMSModules/AdminControls/Controls/Class/FieldEditor/CSSsettings.ascx.cs
5,901
C#
// ********************************************************************* // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License // ********************************************************************* using System; using System.Collections.Generic; using System.Linq.Expressions; using Microsoft.StreamProcessing; using Microsoft.StreamProcessing.Aggregates; namespace RulesEngine { internal sealed class RulesAggregate<TRulesKey, TData, TOutput> : IAggregate<ValueTuple<TRulesKey, TData>, ValueTuple<TRulesKey, SortedMultiSet<TData>>, IEnumerable<ValueTuple<string, TOutput>>> { private readonly Func<TRulesKey, SortedMultiSet<TData>, IEnumerable<ValueTuple<string, TOutput>>> func; public RulesAggregate(Func<TRulesKey, SortedMultiSet<TData>, IEnumerable<ValueTuple<string, TOutput>>> func) => this.func = func; public Expression<Func< ValueTuple<TRulesKey, SortedMultiSet<TData>>, long, ValueTuple<TRulesKey, TData>, ValueTuple<TRulesKey, SortedMultiSet<TData>>>> Accumulate() => (state, time, input) => ValueTuple.Create(input.Item1, state.Item2.Add(input.Item2)); public Expression<Func< ValueTuple<TRulesKey, SortedMultiSet<TData>>, IEnumerable<ValueTuple<string, TOutput>>>> ComputeResult() => (state) => this.func(state.Item1, state.Item2); public Expression<Func< ValueTuple<TRulesKey, SortedMultiSet<TData>>, long, ValueTuple<TRulesKey, TData>, ValueTuple<TRulesKey, SortedMultiSet<TData>>>> Deaccumulate() => (state, time, input) => ValueTuple.Create(input.Item1, state.Item2.Remove(input.Item2)); public Expression<Func< ValueTuple<TRulesKey, SortedMultiSet<TData>>, ValueTuple<TRulesKey, SortedMultiSet<TData>>, ValueTuple<TRulesKey, SortedMultiSet<TData>>>> Difference() => (left, right) => ValueTuple.Create(left.Item1, left.Item2.RemoveAll(right.Item2)); public Expression<Func< ValueTuple<TRulesKey, SortedMultiSet<TData>>>> InitialState() => () => ValueTuple.Create(default(TRulesKey), new SortedMultiSet<TData>()); } }
45.156863
136
0.626574
[ "MIT" ]
Bhaskers-Blu-Org2/TrillSamples
TrillSamples/RulesEngine/RulesAggregate.cs
2,305
C#
using Newtonsoft.Json; namespace Discord.API { public class VoiceState { [JsonProperty("guild_id")] public ulong? GuildId { get; set; } [JsonProperty("channel_id")] public ulong? ChannelId { get; set; } [JsonProperty("user_id")] public ulong UserId { get; set; } [JsonProperty("session_id")] public string SessionId { get; set; } [JsonProperty("deaf")] public bool Deaf { get; set; } [JsonProperty("mute")] public bool Mute { get; set; } [JsonProperty("self_deaf")] public bool SelfDeaf { get; set; } [JsonProperty("self_mute")] public bool SelfMute { get; set; } [JsonProperty("suppress")] public bool Suppress { get; set; } } }
29.185185
45
0.568528
[ "MIT" ]
Joe4evr/Discord.Net
src/Discord.Net/API/Common/VoiceState.cs
790
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.Collections; using System.Drawing; using System.Drawing.Imaging; using System.Globalization; using Xunit; namespace System.ComponentModel.TypeConverterTests { public class ImageFormatConverterTest { private readonly ImageFormat _imageFmt; private readonly ImageFormatConverter _imgFmtConv; private readonly ImageFormatConverter _imgFmtConvFrmTD; private readonly string _imageFmtStr; public ImageFormatConverterTest() { _imageFmt = ImageFormat.Bmp; _imageFmtStr = _imageFmt.ToString(); _imgFmtConv = new ImageFormatConverter(); _imgFmtConvFrmTD = (ImageFormatConverter)TypeDescriptor.GetConverter(_imageFmt); } [ConditionalFact(Helpers.GdiplusIsAvailable)] public void TestCanConvertFrom() { Assert.True(_imgFmtConv.CanConvertFrom(typeof(string)), "string (no context)"); Assert.True(_imgFmtConv.CanConvertFrom(null, typeof(string)), "string"); Assert.False(_imgFmtConv.CanConvertFrom(null, typeof(ImageFormat)), "ImageFormat"); Assert.False(_imgFmtConv.CanConvertFrom(null, typeof(Guid)), "Guid"); Assert.False(_imgFmtConv.CanConvertFrom(null, typeof(object)), "object"); Assert.False(_imgFmtConv.CanConvertFrom(null, typeof(int)), "int"); Assert.True(_imgFmtConvFrmTD.CanConvertFrom(typeof(string)), "TD string (no context)"); Assert.True(_imgFmtConvFrmTD.CanConvertFrom(null, typeof(string)), "TD string"); Assert.False(_imgFmtConvFrmTD.CanConvertFrom(null, typeof(ImageFormat)), "TD ImageFormat"); Assert.False(_imgFmtConvFrmTD.CanConvertFrom(null, typeof(Guid)), "TD Guid"); Assert.False(_imgFmtConvFrmTD.CanConvertFrom(null, typeof(object)), "TD object"); Assert.False(_imgFmtConvFrmTD.CanConvertFrom(null, typeof(int)), "TD int"); } [ConditionalFact(Helpers.GdiplusIsAvailable)] public void TestCanConvertTo() { Assert.True(_imgFmtConv.CanConvertTo(typeof(string)), "string (no context)"); Assert.True(_imgFmtConv.CanConvertTo(null, typeof(string)), "string"); Assert.False(_imgFmtConv.CanConvertTo(null, typeof(ImageFormat)), "ImageFormat"); Assert.False(_imgFmtConv.CanConvertTo(null, typeof(Guid)), "Guid"); Assert.False(_imgFmtConv.CanConvertTo(null, typeof(object)), "object"); Assert.False(_imgFmtConv.CanConvertTo(null, typeof(int)), "int"); Assert.True(_imgFmtConvFrmTD.CanConvertTo(typeof(string)), "TD string (no context)"); Assert.True(_imgFmtConvFrmTD.CanConvertTo(null, typeof(string)), "TD string"); Assert.False(_imgFmtConvFrmTD.CanConvertTo(null, typeof(ImageFormat)), "TD ImageFormat"); Assert.False(_imgFmtConvFrmTD.CanConvertTo(null, typeof(Guid)), "TD Guid"); Assert.False(_imgFmtConvFrmTD.CanConvertTo(null, typeof(object)), "TD object"); Assert.False(_imgFmtConvFrmTD.CanConvertTo(null, typeof(int)), "TD int"); } [ConditionalFact(Helpers.GdiplusIsAvailable)] public void TestConvertFrom_ImageFormatToString() { Assert.Equal(_imageFmt, (ImageFormat)_imgFmtConv.ConvertFrom(null, CultureInfo.InvariantCulture, ImageFormat.Bmp.ToString())); Assert.Equal(_imageFmt, (ImageFormat)_imgFmtConvFrmTD.ConvertFrom(null, CultureInfo.InvariantCulture, ImageFormat.Bmp.ToString())); } [ConditionalFact(Helpers.GdiplusIsAvailable)] public void TestConvertFrom_ThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => _imgFmtConv.ConvertFrom(null, CultureInfo.InvariantCulture, ImageFormat.Bmp)); Assert.Throws<NotSupportedException>(() => _imgFmtConv.ConvertFrom(null, CultureInfo.InvariantCulture, ImageFormat.Bmp.Guid)); Assert.Throws<NotSupportedException>(() => _imgFmtConv.ConvertFrom(null, CultureInfo.InvariantCulture, new object())); Assert.Throws<NotSupportedException>(() => _imgFmtConv.ConvertFrom(null, CultureInfo.InvariantCulture, 10)); Assert.Throws<NotSupportedException>(() => _imgFmtConvFrmTD.ConvertFrom(null, CultureInfo.InvariantCulture, ImageFormat.Bmp)); Assert.Throws<NotSupportedException>(() => _imgFmtConvFrmTD.ConvertFrom(null, CultureInfo.InvariantCulture, ImageFormat.Bmp.Guid)); Assert.Throws<NotSupportedException>(() => _imgFmtConvFrmTD.ConvertFrom(null, CultureInfo.InvariantCulture, new object())); Assert.Throws<NotSupportedException>(() => _imgFmtConvFrmTD.ConvertFrom(null, CultureInfo.InvariantCulture, 10)); } private ImageFormat ConvertFromName(string imgFormatName) { return (ImageFormat)_imgFmtConvFrmTD.ConvertFrom(null, CultureInfo.InvariantCulture, imgFormatName); } [ConditionalFact(Helpers.GdiplusIsAvailable)] public void ConvertFrom_ShortName() { Assert.Equal(ImageFormat.Bmp, ConvertFromName("Bmp")); Assert.Equal(ImageFormat.Emf, ConvertFromName("Emf")); Assert.Equal(ImageFormat.Exif, ConvertFromName("Exif")); Assert.Equal(ImageFormat.Gif, ConvertFromName("Gif")); Assert.Equal(ImageFormat.Tiff, ConvertFromName("Tiff")); Assert.Equal(ImageFormat.Png, ConvertFromName("Png")); Assert.Equal(ImageFormat.MemoryBmp, ConvertFromName("MemoryBmp")); Assert.Equal(ImageFormat.Icon, ConvertFromName("Icon")); Assert.Equal(ImageFormat.Jpeg, ConvertFromName("Jpeg")); Assert.Equal(ImageFormat.Wmf, ConvertFromName("Wmf")); } [ConditionalFact(Helpers.GdiplusIsAvailable)] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Support to convert image format from long name was added to .NET Core directly.")] public void ConvertFrom_LongName() { Guid testGuid = Guid.NewGuid(); ImageFormat imageformat = ConvertFromName($"[ImageFormat: {testGuid}]"); Assert.Equal(testGuid, imageformat.Guid); } [ConditionalFact(Helpers.GdiplusIsAvailable)] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Support to convert image format from long name was added to .NET Core directly.")] public void ConvertFrom_ThrowsFormatExceptionOnInvalidFormatString() { Assert.Throws<FormatException>(() => _imgFmtConv.ConvertFrom("System.Drawing.String")); Assert.Throws<FormatException>(() => _imgFmtConv.ConvertFrom(null, CultureInfo.InvariantCulture, "System.Drawing.String")); Assert.Throws<FormatException>(() => _imgFmtConv.ConvertFrom("[ImageFormat: abcdefgh-ijkl-mnop-qrst-uvwxyz012345]")); Assert.Throws<FormatException>(() => _imgFmtConvFrmTD.ConvertFrom("System.Drawing.String")); Assert.Throws<FormatException>(() => _imgFmtConvFrmTD.ConvertFrom(null, CultureInfo.InvariantCulture, "System.Drawing.String")); Assert.Throws<FormatException>(() => _imgFmtConvFrmTD.ConvertFrom("[ImageFormat: abcdefgh-ijkl-mnop-qrst-uvwxyz012345]")); } [ConditionalFact(Helpers.GdiplusIsAvailable)] public void TestConvertTo_String() { Assert.Equal(_imageFmtStr, (string)_imgFmtConv.ConvertTo(null, CultureInfo.InvariantCulture, _imageFmt, typeof(string))); Assert.Equal(_imageFmtStr, (string)_imgFmtConv.ConvertTo(_imageFmt, typeof(string))); Assert.Equal(_imageFmtStr, (string)_imgFmtConvFrmTD.ConvertTo(null, CultureInfo.InvariantCulture, _imageFmt, typeof(string))); Assert.Equal(_imageFmtStr, (string)_imgFmtConvFrmTD.ConvertTo(_imageFmt, typeof(string))); } [ConditionalFact(Helpers.GdiplusIsAvailable)] public void TestConvertTo_ThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => _imgFmtConv.ConvertTo(null, CultureInfo.InvariantCulture, _imageFmt, typeof(ImageFormat))); Assert.Throws<NotSupportedException>(() => _imgFmtConv.ConvertTo(null, CultureInfo.InvariantCulture, _imageFmt, typeof(Guid))); Assert.Throws<NotSupportedException>(() => _imgFmtConv.ConvertTo(null, CultureInfo.InvariantCulture, _imageFmt, typeof(object))); Assert.Throws<NotSupportedException>(() => _imgFmtConv.ConvertTo(null, CultureInfo.InvariantCulture, _imageFmt, typeof(int))); Assert.Throws<NotSupportedException>(() => _imgFmtConvFrmTD.ConvertTo(null, CultureInfo.InvariantCulture, _imageFmt, typeof(ImageFormat))); Assert.Throws<NotSupportedException>(() => _imgFmtConvFrmTD.ConvertTo(null, CultureInfo.InvariantCulture, _imageFmt, typeof(Guid))); Assert.Throws<NotSupportedException>(() => _imgFmtConvFrmTD.ConvertTo(null, CultureInfo.InvariantCulture, _imageFmt, typeof(object))); Assert.Throws<NotSupportedException>(() => _imgFmtConvFrmTD.ConvertTo(null, CultureInfo.InvariantCulture, _imageFmt, typeof(int))); } [ConditionalFact(Helpers.GdiplusIsAvailable)] public void GetStandardValuesSupported() { Assert.True(_imgFmtConv.GetStandardValuesSupported(), "GetStandardValuesSupported()"); Assert.True(_imgFmtConv.GetStandardValuesSupported(null), "GetStandardValuesSupported(null)"); } private void CheckStandardValues(ICollection values) { bool memorybmp = false; bool bmp = false; bool emf = false; bool wmf = false; bool gif = false; bool jpeg = false; bool png = false; bool tiff = false; bool exif = false; bool icon = false; foreach (ImageFormat iformat in values) { switch (iformat.Guid.ToString()) { case "b96b3caa-0728-11d3-9d7b-0000f81ef32e": memorybmp = true; break; case "b96b3cab-0728-11d3-9d7b-0000f81ef32e": bmp = true; break; case "b96b3cac-0728-11d3-9d7b-0000f81ef32e": emf = true; break; case "b96b3cad-0728-11d3-9d7b-0000f81ef32e": wmf = true; break; case "b96b3cb0-0728-11d3-9d7b-0000f81ef32e": gif = true; break; case "b96b3cae-0728-11d3-9d7b-0000f81ef32e": jpeg = true; break; case "b96b3caf-0728-11d3-9d7b-0000f81ef32e": png = true; break; case "b96b3cb1-0728-11d3-9d7b-0000f81ef32e": tiff = true; break; case "b96b3cb2-0728-11d3-9d7b-0000f81ef32e": exif = true; break; case "b96b3cb5-0728-11d3-9d7b-0000f81ef32e": icon = true; break; default: throw new InvalidOperationException($"Unknown GUID {iformat.Guid}."); } } Assert.True(memorybmp, "MemoryBMP"); Assert.True(bmp, "Bmp"); Assert.True(emf, "Emf"); Assert.True(wmf, "Wmf"); Assert.True(gif, "Gif"); Assert.True(jpeg, "Jpeg"); Assert.True(png, "Png"); Assert.True(tiff, "Tiff"); Assert.True(exif, "Exif"); Assert.True(icon, "Icon"); } [ConditionalFact(Helpers.GdiplusIsAvailable)] public void GetStandardValues() { CheckStandardValues(_imgFmtConv.GetStandardValues()); CheckStandardValues(_imgFmtConv.GetStandardValues(null)); } } }
53.826087
152
0.640711
[ "MIT" ]
Adam25T/corefx
src/System.Windows.Extensions/tests/System/Drawing/ImageFormatConverterTests.cs
12,380
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for Calculator /// </summary> public class Calculator { public double Add(double a, double b) { return a + b; } public double Subtract(double a, double b) { return a - b; } public double Multiply(double a, double b) { return a * b; } public double Divide(double a, double b) { return a / b; } }
15.4
44
0.640693
[ "MIT" ]
lizhen325/ASP.NET
ch06/App_Code/Calculator.cs
464
C#
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Collections.Generic; using System.Windows; using System.Windows.Media; namespace WinIO.AvalonEdit.Rendering { /// <summary> /// The control that contains the text. /// /// This control is used to allow other UIElements to be placed inside the TextView but /// behind the text. /// The text rendering process (VisualLine creation) is controlled by the TextView, this /// class simply displays the created Visual Lines. /// </summary> /// <remarks> /// This class does not contain any input handling and is invisible to hit testing. Input /// is handled by the TextView. /// This allows UIElements that are displayed behind the text, but still can react to mouse input. /// </remarks> sealed class TextLayer : Layer { /// <summary> /// the index of the text layer in the layers collection /// </summary> internal int index; public TextLayer(TextView textView) : base(textView, KnownLayer.Text) { } List<VisualLineDrawingVisual> visuals = new List<VisualLineDrawingVisual>(); internal void SetVisualLines(ICollection<VisualLine> visualLines) { foreach (VisualLineDrawingVisual v in visuals) { if (v.VisualLine.IsDisposed) RemoveVisualChild(v); } visuals.Clear(); foreach (VisualLine newLine in visualLines) { VisualLineDrawingVisual v = newLine.Render(); if (!v.IsAdded) { AddVisualChild(v); v.IsAdded = true; } visuals.Add(v); } InvalidateArrange(); } protected override int VisualChildrenCount { get { return visuals.Count; } } protected override Visual GetVisualChild(int index) { return visuals[index]; } protected override void ArrangeCore(Rect finalRect) { textView.ArrangeTextLayer(visuals); } } }
34.238095
99
0.732267
[ "Apache-2.0" ]
sak9188/WinIO2
WinIO/WinIO/AvalonEdit/Rendering/TextLayer.cs
2,876
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace SAF.MM.Api { /// <summary> /// 经验值管理 /// </summary> [RoutePrefix("api/mm/exppoints")] public class ExppointsController : ApiController { } }
17.333333
52
0.669872
[ "Apache-2.0" ]
ericzzhou/SAF
SAF.MM/SAF.MM.Api/ExppointsController.cs
324
C#
using Newtonsoft.Json; using System.Collections.Generic; using System.Linq; using Wox.Plugin.Program.Programs; namespace Wox.Plugin.Program { public class Settings { [JsonIgnore] public IEnumerable<IProgramSource> ProgramSources => Sources.Cast<IProgramSource>().ToList(); public List<ProgramSource> Sources { get; set; } = new List<ProgramSource>(); public string[] ProgramSuffixes { get; set; } = {"bat", "appref-ms", "exe", "lnk"}; public bool EnableStartMenuSource { get; set; } = true; public bool EnableRegistrySource { get; set; } = true; internal const char SuffixSeperator = ';'; public class ProgramSource : IProgramSource { public string Location { get; set; } } } }
26.62069
95
0.654145
[ "MIT" ]
lord-executor/Wox
Plugins/Wox.Plugin.Program/Settings.cs
774
C#
namespace AVLTree { using System; public class AVL<T> where T : IComparable<T> { private Node<T> root; public Node<T> Root { get; private set; } public bool Contains(T item) { var node = this.Search(this.Root, item); return node != null; } public void Insert(T item) { this.Root = this.Insert(this.Root, item); } public void EachInOrder(Action<T> action) { this.EachInOrder(this.Root, action); } private Node<T> Insert(Node<T> node, T item) { if (node == null) { return new Node<T>(item); } int cmp = item.CompareTo(node.Value); if (cmp < 0) { node.Left = this.Insert(node.Left, item); } else if (cmp > 0) { node.Right = this.Insert(node.Right, item); } node = Balance(node); UpdateHeight(node); return node; } private Node<T> Search(Node<T> node, T item) { if (node == null) { return null; } int cmp = item.CompareTo(node.Value); if (cmp < 0) { return Search(node.Left, item); } else if (cmp > 0) { return Search(node.Right, item); } return node; } private void EachInOrder(Node<T> node, Action<T> action) { if (node == null) { return; } this.EachInOrder(node.Left, action); action(node.Value); this.EachInOrder(node.Right, action); } private static int Height(Node<T> node) { if (node == null) { return 0; } return node.Height; } private static void UpdateHeight(Node<T> node) { node.Height = Math.Max(Height(node.Left), Height(node.Right)) + 1; } private static Node<T> RotateLeft(Node<T> node) { var right = node.Right; node.Right = node.Right.Left; right.Left = node; UpdateHeight(node); return right; } private static Node<T> RotateRight(Node<T> node) { var left = node.Left; node.Left = node.Left.Right; left.Right = node; UpdateHeight(node); return left; } private static Node<T> Balance(Node<T> node) { int balance = Height(node.Left) - Height(node.Right); if (balance < -1) // right child is heavy { // Rotate node left balance = Height(node.Right.Left) - Height(node.Right.Right); if (balance <= 0) // single left { return RotateLeft(node); } else // double left { node.Right = RotateRight(node.Right); return RotateLeft(node); } } else if (balance > 1) // left child is heavy { // Rotate node right balance = Height(node.Left.Right) - Height(node.Left.Left); if (balance <= 0) // single right { return RotateRight(node); } else // double right { node.Left = RotateLeft(node.Left); return RotateRight(node); } } return node; } } }
24.675159
78
0.419205
[ "MIT" ]
marinakolova/CSharp-Courses
Data-Structures-Advanced-with-CSharp-October-2020/01-B-Trees-2-3-Trees-and-AVL-Trees-Lab/AVLTree/AVL.cs
3,876
C#
using System; using Aragas.Core.Data; using Aragas.Core.IO; using Aragas.Core.Packets; using ProtocolModern.Enum; namespace ProtocolModern.Packets.Client.Play { public class EntityEffectPacket : ProtobufPacket { public Int32 EntityID; public SByte EffectID; public SByte Amplifier; public Int16 Duration; public override VarInt ID => ClientPlayPacketTypes.EntityEffect; public override ProtobufPacket ReadPacket(ProtobufDataReader reader) { EntityID = reader.Read(EntityID); EffectID = reader.Read(EffectID); Amplifier = reader.Read(Amplifier); Duration = reader.Read(Duration); return this; } public override ProtobufPacket WritePacket(ProtobufStream stream) { stream.Write(EntityID); stream.Write(EffectID); stream.Write(Amplifier); stream.Write(Duration); return this; } } }
22.439024
76
0.68587
[ "MIT" ]
MineLib/ProtocolModern_1.7.10
Packets/Client/Play/0x1D_EntityEffectPacket.cs
920
C#
using NUnit.Framework; using System; namespace Azure.ApplicationModel.Configuration.Tests { public static class TestEnvironment { public static ConfigurationClient GetClient() { var connectionString = Environment.GetEnvironmentVariable("APP_CONFIG_CONNECTION"); Assert.NotNull(connectionString, "Set APP_CONFIG_CONNECTION environment variable to the connection string"); return new ConfigurationClient(connectionString); } } }
31.3125
120
0.718563
[ "MIT" ]
HanLiMS/azure-sdk-for-net
src/SDKs/Azure.ApplicationModel.Configuration/data-plane/Azure.ApplicationModel.Configuration.Tests/TestEnvironment.cs
503
C#
using System; using System.Collections.Generic; using System.Linq; using FPCSharpUnity.unity.Data; using FPCSharpUnity.core.exts; using FPCSharpUnity.unity.Functional; using FPCSharpUnity.core.reactive; using NUnit.Framework; using FPCSharpUnity.core.concurrent; using FPCSharpUnity.core.data; using FPCSharpUnity.core.functional; using FPCSharpUnity.core.test_framework; namespace FPCSharpUnity.unity.Concurrent { static class FT { public static readonly Func<int, Either<int, string>> left = F.left<int, string>; public static readonly Func<string, Either<int, string>> right = F.right<int, string>; public static IEnumerable<Future<A>> addUnfulfilled<A>(this IEnumerable<Future<A>> futures) { return futures.Concat(Future<A>.unfulfilled.yield()); } } public class FutureTestEquality : TestBase { [Test] public void Equals() { var asyncF = Future.async<int>(out var asyncP); var unfullfilled = Future.unfulfilled; var completed = Future.successful(3); shouldNotEqualSymmetrical(unfullfilled, completed); shouldBeIdentical(unfullfilled, asyncF); shouldNotEqualSymmetrical(asyncF, completed); asyncP.complete(3); shouldNotEqualSymmetrical(unfullfilled, asyncF); shouldBeIdentical(asyncF, completed); } } public class FutureTestOnComplete { const int value = 1; [Test] public void WhenSuccessful() { var f = Future.successful(value); var result = 0; f.onComplete(i => result = i); result.shouldEqual(value, "it should run the function immediately"); } [Test] public void WhenUnfulfilled() { var f = Future<int>.unfulfilled; var result = 0; f.onComplete(i => result = i); result.shouldEqual(0, "it should not run the function"); } [Test] public void WhenASync() { var f = Future.async<int>(out var p); var result = 0; f.onComplete(i => result = i); result.shouldEqual(0, "it should not run the function immediately"); p.complete(value); result.shouldEqual(value, "it run the function after completion"); } } public class FutureTestNowAndOnComplete { [Test] public void WhenSuccessful() { var f = Future.successful(1); var result = 0; f.nowAndOnComplete(iOpt => result += iOpt.fold(-1, _ => _)); result.shouldEqual(1, "it should run the function once"); } [Test] public void WhenUnfulfilled() { var f = Future<int>.unfulfilled; var result = 0; f.nowAndOnComplete(iOpt => result += iOpt.fold(-1, _ => _)); result.shouldEqual(-1, "it should run the function once"); } [Test] public void WhenASync() { var f = Future.async<int>(out var p); var result = 0; f.nowAndOnComplete(iOpt => result += iOpt.fold(-1, _ => _)); result.shouldEqual(-1, "it should run the function immediately"); p.complete(2); result.shouldEqual(1, "it run the function after completion again"); } } public class FutureTestMap { readonly Func<int, int> mapper = i => i * 2; [Test] public void WhenSuccessful() { Future.successful(1).map(mapper).shouldBeOfSuccessfulType(2); } [Test] public void WhenUnfulfilled() { Future<int>.unfulfilled.map(mapper).shouldBeOfUnfulfilledType(); } [Test] public void WhenASync() { var f = Future.async(out Promise<int> p); var f2 = f.map(mapper); f2.type.shouldEqual(FutureType.ASync); f2.value.shouldBeNone("it should not have value before original future completion"); p.complete(1); f2.value.shouldBeSome(2, "it should have value after original future completion"); } } public class FutureTestFlatMap { readonly Func<int, Future<int>> successfulMapper = i => Future.successful(i * 2); readonly Func<int, Future<int>> unfulfilledMapper = i => Future<int>.unfulfilled; readonly Future<int> successful = Future.successful(1), unfulfilled = Future<int>.unfulfilled; [Test] public void SuccessfulToSuccessful() { successful.flatMap(successfulMapper).shouldBeOfSuccessfulType(2); } [Test] public void SuccessfulToUnfulfilled() { successful.flatMap(unfulfilledMapper).shouldBeOfUnfulfilledType(); } [Test] public void SuccessfulToASync() { var f2 = Future.async<int>(out var p2); var f = successful.flatMap(_ => f2); f.type.shouldEqual(FutureType.ASync); f.value.shouldBeNone("it should be uncompleted if source future is incomplete"); p2.complete(2); f.value.shouldBeSome(2, "it should complete after completing the source future"); } [Test] public void UnfulfilledToSuccessful() { unfulfilledShouldNotCallMapper(successfulMapper); } [Test] public void UnfulfilledToUnfulfilled() { unfulfilledShouldNotCallMapper(unfulfilledMapper); } [Test] public void UnfulfilledToASync() { unfulfilledShouldNotCallMapper(i => Future.a<int>(p => {})); } void unfulfilledShouldNotCallMapper<A>(Func<int, Future<A>> mapper) { var called = false; unfulfilled.flatMap(i => { called = true; return mapper(i); }).shouldBeOfUnfulfilledType(); called.shouldBeFalse("it should not call the mapper"); } [Test] public void ASyncToSuccessful() { var f = Future.async<int>(out var p); var called = false; var f2 = f.flatMap(i => { called = true; return Future.successful(i); }); f2.type.shouldEqual(FutureType.ASync); f2.value.shouldBeNone(); called.shouldBeFalse("it should not call function until completion of a source promise"); p.complete(1); called.shouldBeTrue(); f2.value.shouldBeSome(1); } [Test] public void ASyncToUnfulfilled() { var f = Future.async<int>(out var p); var called = false; var f2 = f.flatMap(_ => { called = true; return Future<int>.unfulfilled; }); f2.type.shouldEqual(FutureType.ASync); f2.value.shouldBeNone(); called.shouldBeFalse(); p.complete(1); called.shouldBeTrue(); f2.value.shouldBeNone("it shouldn't complete even if source future is completed"); } [Test] public void ASyncToASync() { Promise<int> p1; var f1 = Future.async<int>(out p1); Promise<int> p2; var f2 = Future.async<int>(out p2); var called = false; var f = f1.flatMap(_ => { called = true; return f2; }); f.type.shouldEqual(FutureType.ASync); f.value.shouldBeNone("it should be not completed at start"); called.shouldBeFalse(); p1.complete(1); called.shouldBeTrue(); f.value.shouldBeNone("it should be not completed if source future completes"); p2.complete(2); f.value.shouldBeSome(2, "it should be completed"); } } public class FutureTestZip { [Test] public void WhenEitherSideUnfulfilled() { foreach (var t in new[] { Tpl.a("X-O", Future<int>.unfulfilled, Future.successful(1)), Tpl.a("O-X", Future.successful(1), Future<int>.unfulfilled) }) { var (name, fa, fb) = t; fa.zip(fb).shouldBeOfUnfulfilledType(name); } } [Test] public void WhenBothSidesSuccessful() { Future.successful(1).zip(Future.successful(2)).shouldBeOfSuccessfulType((1, 2)); } [Test] public void WhenASync() { whenASync(true); whenASync(false); } static void whenASync(bool completeFirst) { Promise<int> p1, p2; var f1 = Future.async<int>(out p1); var f2 = Future.async<int>(out p2); var f = f1.zip(f2); f.type.shouldEqual(FutureType.ASync); f.value.shouldBeNone(); (completeFirst ? p1 : p2).complete(completeFirst ? 1 : 2); f.value.shouldBeNone("it should not complete just from one side"); (completeFirst ? p2 : p1).complete(completeFirst ? 2 : 1); f.value.shouldBeSome((1, 2), "it should complete from both sides"); } } public class FutureTestFirstOf { [Test] public void WhenHasCompleted() { new[] { Future.unfulfilled, Future.unfulfilled, Future.successful(1), Future.unfulfilled, Future.unfulfilled }.firstOf().value.__unsafeGet.shouldEqual(1); } [Test] public void WhenHasMultipleCompleted() { new[] { Future.unfulfilled, Future.unfulfilled, Future.successful(1), Future.unfulfilled, Future.successful(2), Future.unfulfilled }.firstOf().value.__unsafeGet.shouldEqual(1); } [Test] public void WhenNoCompleted() { new[] { Future<int>.unfulfilled, Future<int>.unfulfilled, Future<int>.unfulfilled, Future<int>.unfulfilled }.firstOf().value.shouldBeNone(); } } public class FutureTestFirstOfWhere { [Test] public void ItemFound() { new[] {1, 3, 5, 6, 7}. Select(Future.successful).firstOfWhere(i => (i % 2 == 0).opt(i)). value.__unsafeGet.shouldEqual(6.some()); } [Test] public void MultipleItemsFound() { new[] {1, 3, 5, 6, 7, 8}. Select(Future.successful).firstOfWhere(i => (i % 2 == 0).opt(i)). value.__unsafeGet.shouldEqual(6.some()); } [Test] public void ItemNotFound() { new[] {1, 3, 5, 7}. Select(Future.successful).firstOfWhere(i => (i % 2 == 0).opt(i)). value.__unsafeGet.shouldBeNone(); } [Test] public void ItemNotFoundNotCompleted() { new[] {1, 3, 5, 7}.Select(Future.successful).addUnfulfilled(). firstOfWhere(i => (i % 2 == 0).opt(i)). value.shouldBeNone(); } } public class FutureTestFirstOfSuccessful { [Test] public void RightFound() { new[] { FT.left(1), FT.left(3), FT.left(5), FT.right("6"), FT.left(7) }. Select(Future.successful).firstOfSuccessful(). value.__unsafeGet.shouldBeSome("6"); } [Test] public void MultipleRightsFound() { new[] { FT.left(1), FT.left(3), FT.left(5), FT.right("6"), FT.left(7), FT.right("8") }. Select(Future.successful).firstOfSuccessful(). value.__unsafeGet.shouldBeSome("6"); } [Test] public void RightNotFound() { new[] { FT.left(1), FT.left(3), FT.left(5), FT.left(7) }. Select(Future.successful).firstOfSuccessful(). value.__unsafeGet.shouldBeNone(); } [Test] public void RightNotFoundNoComplete() { new[] { FT.left(1), FT.left(3), FT.left(5), FT.left(7) }. Select(Future.successful).addUnfulfilled().firstOfSuccessful(). value.shouldBeNone(); } } public class FutureTestFirstOfSuccessfulCollect { [Test] public void ItemFound() { new [] { FT.left(1), FT.left(2), FT.right("a"), FT.left(3) }. Select(Future.successful).firstOfSuccessfulCollect().value.__unsafeGet. shouldEqual(F.right<int[], string>("a")); } [Test] public void MultipleItemsFound() { new [] { FT.left(1), FT.left(2), FT.right("a"), FT.left(3), FT.right("b") }. Select(Future.successful).firstOfSuccessfulCollect().value.__unsafeGet. shouldEqual(F.right<int[], string>("a")); } [Test] public void ItemNotFound() { new [] { FT.left(1), FT.left(2), FT.left(3), FT.left(4) }. Select(Future.successful).firstOfSuccessfulCollect().value.__unsafeGet. leftValue.get.asDebugString().shouldEqual(new[] { 1, 2, 3, 4 }.asDebugString()); } [Test] public void ItemNotFoundNoCompletion() { new [] { FT.left(1), FT.left(2), FT.left(3), FT.left(4) }. Select(Future.successful).addUnfulfilled().firstOfSuccessfulCollect().value.shouldBeNone(); } } public class FutureTestFilter { [Test] public void CompleteToNotComplete() { Future.successful(3).filter(i => false).shouldNotBeCompleted(); } [Test] public void CompleteToComplete() { Future.successful(3).filter(i => true).shouldBeCompleted(3); } [Test] public void NotCompleteToNotComplete() { Future<int>.unfulfilled.filter(i => false).shouldNotBeCompleted(); Future<int>.unfulfilled.filter(i => true).shouldNotBeCompleted(); } } public class FutureTestCollect { [Test] public void CompleteToNotComplete() { Future.successful(3).collect(i => F.none<int>()).shouldNotBeCompleted(); } [Test] public void CompleteToComplete() { Future.successful(3).collect(i => Some.a(i * 2)).shouldBeCompleted(6); } [Test] public void NotCompleteToNotComplete() { Future<int>.unfulfilled.collect(i => F.none<int>()).shouldNotBeCompleted(); Future<int>.unfulfilled.collect(Some.a).shouldNotBeCompleted(); } } public class FutureTestDelay { [Test] public void Test() { var d = Duration.fromSeconds(1); var tc = new TestTimeContext(); var f = Future.delay(d, 3, tc); f.value.shouldBeNone(); tc.timePassed = d / 2; f.value.shouldBeNone(); tc.timePassed = d; f.value.shouldBeSome(3); } } public class FutureTestDelayFrames { [Test] public void Test() => Assert.Ignore("TODO: test with integration tests"); } public class FutureTestDelayUntilSignal { [Test] public void NotCompletedThenSignal() { var t = Future<int>.unfulfilled.delayUntilSignal(); t.future.shouldNotBeCompleted(); t.sendSignal(); t.future.shouldNotBeCompleted(); } [Test] public void NotCompletedThenCompletionThenSignal() { var t = Future.async(out Promise<Unit> p).delayUntilSignal(); t.future.shouldNotBeCompleted(); p.complete(F.unit); t.future.shouldNotBeCompleted(); t.sendSignal(); t.future.shouldBeCompleted(F.unit); } [Test] public void NotCompletedThenSignalThenCompletion() { var t = Future.async<Unit>(out var p).delayUntilSignal(); t.future.shouldNotBeCompleted(); t.sendSignal(); t.future.shouldNotBeCompleted(); p.complete(F.unit); t.future.shouldBeCompleted(F.unit); } [Test] public void CompletedThenSignal() { var t = Future.successful(F.unit).delayUntilSignal(); t.future.shouldNotBeCompleted(); t.sendSignal(); t.future.shouldBeCompleted(F.unit); } } public class FutureTestToRxVal { [Test] public void WithUnknownType() { var f = Future.async(out Promise<int> promise); var rx = f.toRxVal(); rx.value.shouldBeNone(); promise.complete(10); rx.value.shouldBeSome(10); } [Test] public void WithRxValInside() { Promise<IRxVal<int>> p; var f = Future.async(out p); var rx = f.toRxVal(0); rx.value.shouldEqual(0); var rx2 = RxRef.a(100); p.complete(rx2); rx.value.shouldEqual(100); rx2.value = 200; rx.value.shouldEqual(200); } } public class FutureTestTimeout { Promise<int> promise; Future<int> sourceFuture; TestTimeContext tc; static readonly TimeSpan t = TimeSpan.FromMilliseconds(100); static readonly Duration d = t; [SetUp] public void setup() { sourceFuture = Future.async(out promise); tc = new TestTimeContext(); } [Test] public void WhenSourceCompletes() { var f = sourceFuture.timeout(d, tc); f.value.shouldBeNone(); tc.timePassed = d - new Duration(1); f.value.shouldBeNone(); promise.complete(5); f.value.shouldBeSome(Either<TimeSpan, int>.Right(5)); } [Test] public void WhenSourceCompletesOnFailure() { var f = sourceFuture.timeout(d, tc); var failureResult = new List<TimeSpan>(); f.onFailure(failureResult.Add); f.value.shouldBeNone(); tc.timePassed = d - new Duration(1); f.value.shouldBeNone(); promise.complete(5); f.value.shouldBeSome(Either<TimeSpan, int>.Right(5)); tc.timePassed += t; failureResult.shouldEqualEnum(); } [Test] public void WhenSourceDelaysOnFailure() { var f = sourceFuture.timeout(d, tc); var failureResult = new List<TimeSpan>(); f.onFailure(failureResult.Add); f.value.shouldBeNone(); tc.timePassed = d; f.value.shouldBeSome(F.left<TimeSpan, int>(d)); tc.timePassed += t; failureResult.shouldEqualEnum(t); } } public class OptionFutureTestExtract { [Test] public void WhenNone() => F.none<Future<int>>().extract().shouldBeOfUnfulfilledType(); [Test] public void WhenSome() { var f = Future.successful(3); Some.a(f).extract().shouldEqual(f); } } public class OptionFutureTestExtractOpt { [Test] public void WhenNone() => F.none<Future<int>>().extractOpt().shouldBeOfSuccessfulType(F.none<int>()); [Test] public void WhenSome() => Some.a(Future.successful(3)).extractOpt().shouldEqual(Future.successful(Some.a(3))); } }
29.735652
99
0.628495
[ "MIT" ]
FPCSharpUnity/FPCSharpUnity
parts/0000-library/Assets/Vendor/FPCSharpUnity/Test/Concurrent/FutureTest.cs
17,100
C#
using System; using UnityEngine; using UnityEngine.UI; using GameNet; using LitJson; namespace Client.UI { public partial class UIModifyWindow { private void _initCenter(GameObject go) { btn_sure = go.GetComponentEx<Button> (Layout.btn_sure); btn_getRegist = go.GetComponentEx<Button> (Layout.btn_getIndentify); btn_sureModify = go.GetComponentEx<Button> (Layout.btn_sureModify); input_phone = go.GetComponentEx<InputField> (Layout.inputPhone); input_identify = go.GetComponentEx<InputField> (Layout.inputIdentify); input_scret = go.GetComponentEx<InputField> (Layout.inputScret); btn_close = go.GetComponentEx<Button> (Layout.btn_close); lb_time = go.GetComponentEx<Text> (Layout.lb_count); // img_btnWord = go.GetComponentEx<Image> (Layout.btn_sure); // Console.WriteLine (img_btnWord); // img_uidisplay = new UIImageDisplay (img_btnWord); } private void _onShowCenter() { EventTriggerListener.Get (btn_sure.gameObject).onClick += _onBtnSureHandler; EventTriggerListener.Get (btn_sureModify.gameObject).onClick += _onBtnSureHandler; EventTriggerListener.Get (btn_getRegist.gameObject).onClick += _onBtnGetIdentifyHandler; EventTriggerListener.Get (btn_close.gameObject).onClick += _OnBtnCloseHandler; this._SetSureBtnWord (); if (_controller.isShowTime ()) { ShowTimeCount (); } else { HideTimeCount (); } } private void _onHideCenter() { EventTriggerListener.Get (btn_sure.gameObject).onClick -= _onBtnSureHandler; EventTriggerListener.Get (btn_sureModify.gameObject).onClick -= _onBtnSureHandler; EventTriggerListener.Get (btn_getRegist.gameObject).onClick -= _onBtnGetIdentifyHandler; EventTriggerListener.Get (btn_close.gameObject).onClick -= _OnBtnCloseHandler; } private void _onDisposeCenter() { // if (null != img_uidisplay) // { // img_uidisplay.Dispose (); // } } /// <summary> /// Shows the time count. 显示倒计时 /// </summary> public void ShowTimeCount() { btn_getRegist.SetActiveEx (false); lb_time.SetActiveEx (true); } /// <summary> /// Updates the time number. 跟新倒计时时间 /// </summary> /// <param name="vlaue">Vlaue.</param> public void UpdateTimeNum(string vlaue) { if (null != lb_time) { lb_time.text=vlaue; } } /// <summary> /// Hides the time count. 隐藏倒计时文本框 /// </summary> public void HideTimeCount() { btn_getRegist.SetActiveEx (true); lb_time.SetActiveEx (false); } private void _onBtnSureHandler(GameObject go) { if (input_identify.text == "") { Console.WriteLine ("请入验证码"); MessageHint.Show ("请入验证码"); return; } //input_phone.text == "" || input_phone.text.Length < 11 if (GameModel.IsTelephone(input_phone.text)==false) { Console.WriteLine ("请输入正确的手机号"); MessageHint.Show ("手机号错误,请重新输入"); input_phone.text = ""; return; } if(input_scret.text=="") { Console.WriteLine ("请输入密码"); MessageHint.Show ("请输入密码"); return; } var scretModel = new PlayerRegistVo (); scretModel.code = input_identify.text; scretModel.password = input_scret.text; scretModel.phone = input_phone.text; //var tpm = new JsonData (); //tpm["code"]=scretModel.code ; //tpm["password"]=scretModel.password; //tpm ["phone"] = scretModel.phone; //var newData = new JsonData (); //newData ["jsonString"] = tpm; var backdata = ""; var tmpG = Coding<PlayerRegistVo>.encode (scretModel); Console.WriteLine ("jsonString:"+tmpG); Console.WriteLine ("修改密码成功sssssssss"); HttpRequestManager.GetInstance ().GetModifyData (tmpG,_HandlerSuccess); Console.WriteLine (backdata); // var backdatavo = Coding<PlayerRegistBackVo>.decode (backdata); // // if(backdatavo.status==0)//chenggong // { // MessageHint.Show (backdatavo.msg); // } // else // { // MessageHint.Show (backdatavo.msg); // } } private void _HandlerSuccess() { var loginController = UIControllerManager.Instance.GetController<UILoginController> (); if (loginController.getVisible ()) { loginController.SetDefaultPhone (input_phone.text); } _controller.setVisible (false); } private void _OnBtnCloseHandler(GameObject go) { this._controller.setVisible (false); } /// <summary> /// Ons the button get identify handler. 获取验证码 /// </summary> /// <param name="go">Go.</param> private void _onBtnGetIdentifyHandler(GameObject go) { var phoneNum = input_phone.text; // if ( phoneNum== "" ||phoneNum.Length<11) // { // MessageHint.Show ("请输入正确的手机号"); // return; // } if (GameModel.IsTelephone (phoneNum) == false) { MessageHint.Show ("手机号错误,请重新输入"); input_phone.text = ""; return; } var getcodemodel = new PlayerGetCode (); getcodemodel.phone = phoneNum; LitJson.JsonData data = new LitJson.JsonData (); data ["phone"] = getcodemodel.phone; HttpRequestManager.GetInstance ().GetCheckCodeData(data.ToJson()); //HttpRequestManager.GetInstance ().GetCheckCodeData(data.ToJson()); // Console.WriteLine ("jsonString="+data.ToJson()); //Coding<PlayerGetCode>.encode (getcodemodel); // var getCodeStr = HttpRequestHelp.GetInstance ().GetCheckCodeData(data.ToJson()); // var getcodeback = Coding<PlayerGetCodeBackVo>.decode (getCodeStr); // // Console.WriteLine (getCodeStr); // // if(getcodeback.status==0)//成功 // { // identyCode = getcodeback.data.code; // MessageHint.Show ("已经发验证码,注意接收"); // } // else // { // Console.WriteLine (getcodeback.msg); // } } /// <summary> /// Sets the sure button word. 判断是修改秘吗还是注册账号 /// </summary> /// <param name="value">Value.</param> private void _SetSureBtnWord() { btn_sure.SetActiveEx(false); btn_sureModify.SetActiveEx (true); } //private readonly string path_regist = "share/atlas/battle/login/phoneRiegitbtn.ab"; //private readonly string path_modify = "share/atlas/battle/login/modifypassword.ab"; private Button btn_sure; private Button btn_getRegist; private Button btn_sureModify; private Text lb_time; private Button btn_close; private Image img_btnWord; // private UIImageDisplay img_uidisplay; private InputField input_phone; private InputField input_identify; private InputField input_scret; //private string identyCode=""; //private string phoneNum=""; //private InputField input_scretAgain; } }
25.920152
92
0.648086
[ "Apache-2.0" ]
rusmass/wealthland_client
arpg_prg/nativeclient_prg/Assets/Code/Client/UI/UIModify/UIModifyWindowCenter.cs
7,053
C#
namespace ResponsiveImagePicker.Models { public class Crop { public string Name { get; set; } public int Width { get; set; } public int Height { get; set; } public int BreakPoint { get; set; } public Coordinates Coordinates { get; set; } } }
26.727273
52
0.588435
[ "MIT" ]
ryanhelmn-co-uk/Umbraco-Responsive-Image-Picker
src/ResponsiveImagePicker/Models/Crop.cs
296
C#
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Globalization; using System.Linq; using Loretta.CodeAnalysis.Lua.Utilities; using Loretta.CodeAnalysis.Text; using static Tsu.Option; namespace Loretta.CodeAnalysis.Lua.Syntax.UnitTests.Lexical { internal static class LexicalTestData { private static double ParseNum(string str, int @base) => @base switch { 2 or 8 => Convert.ToInt64(str[2..].Replace("_", ""), @base), 10 => double.Parse(str.Replace("_", ""), NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, CultureInfo.InvariantCulture), 16 => HexFloat.DoubleFromHexString(str.Replace("_", "")), _ => throw new InvalidOperationException(), }; public static IEnumerable<ShortToken> GetTokens(LuaSyntaxOptions options) { foreach (var token in from kind in Enum.GetValues(typeof(SyntaxKind)).Cast<SyntaxKind>() let text = SyntaxFacts.GetText(kind) where !string.IsNullOrEmpty(text) && (kind != SyntaxKind.ContinueKeyword || options.ContinueType == ContinueType.Keyword) select new ShortToken(kind, text)) { yield return token; } #region Numbers // Binary foreach (var text in new[] { "0b10", "0b10_10", "0B10", "0B10_10" }) { yield return new ShortToken( SyntaxKind.NumericLiteralToken, text, Some(ParseNum(text, 2))); } // Octal foreach (var text in new[] { "0o77", "0o77_77", "0O77", "0O77_77" }) { yield return new ShortToken( SyntaxKind.NumericLiteralToken, text, Some(ParseNum(text, 8))); } // Decimal foreach (var text in new[] { "1", "1e10", "1.1", "1.1e10", ".1", ".1e10", "1_1", "1_1e1_0", "1_1.1_1", "1_1.1_1e1_0", ".1_1", ".1_1e1_0" }) { yield return new ShortToken( SyntaxKind.NumericLiteralToken, text, Some(ParseNum(text, 10))); } // Hexadecimal foreach (var text in new[] { "0xf", "0xfp10", "0xf.f", "0xf.fp10", "0x.f", "0x.fp10", "0xf_f", "0xf_f.f_f", "0xf_f.f_fp1_0", "0x.f_f", "0x.f_fp1_0", "0xf_fp1_0" }) { yield return new ShortToken( SyntaxKind.NumericLiteralToken, text, Some(ParseNum(text, 16))); } #endregion Numbers #region Strings const string shortStringContentText = "hi\\\n\\\r\\\r\n\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\\0\\10" + "\\255\\xF\\xFF\\z \t\t\r\n\\t\\r\\n\\u{F}\\u{FF}\\u{FFF}\\u{D800}\\u{10FFFF}"; const string shortStringContentValue = "hi\n\r\r\n\a\b\f\n\r\t\v\\'\"\0\xA" + "\xFF\xF\xFF\t\r\n\u000F\u00FF\u0FFF\uD800\U0010FFFF"; // Short strings foreach (var quote in new[] { '\'', '"' }) { yield return new ShortToken( SyntaxKind.StringLiteralToken, quote + shortStringContentText + quote, shortStringContentValue); } const string longStringContent = @"first line \n second line \r\n third line \r fourth line \xFF."; // Long Strings IEnumerable<string> separators = Enumerable.Range(0, 6) .Select(n => new string('=', n)) .ToImmutableArray(); foreach (var separator in separators) { yield return new ShortToken( SyntaxKind.StringLiteralToken, $"[{separator}[{longStringContent}]{separator}]", longStringContent); } #endregion Strings // Identifiers foreach (var identifier in new[] { "a", "abc", "_", "🅱", "\ufeff", /* ZERO WIDTH NO-BREAK SPACE */ "\u206b", /* ACTIVATE SYMMETRIC SWAPPING */ "\u202a", /* LEFT-TO-RIGHT EMBEDDING */ "\u206a", /* INHIBIT SYMMETRIC SWAPPING */ "\ufeff", /* ZERO WIDTH NO-BREAK SPACE */ "\u206a", /* INHIBIT SYMMETRIC SWAPPING */ "\u200e", /* LEFT-TO-RIGHT MARK */ "\u200c", /* ZERO WIDTH NON-JOINER */ "\u200e", /* LEFT-TO-RIGHT MARK */ }) { yield return new ShortToken(SyntaxKind.IdentifierToken, identifier); } } public static IEnumerable<ShortToken> GetTrivia() { return GetSeparators().Concat(new[] { new ShortToken ( SyntaxKind.SingleLineCommentTrivia, "-- hi" ), new ShortToken ( SyntaxKind.SingleLineCommentTrivia, "// hi" ), new ShortToken ( SyntaxKind.ShebangTrivia, "#!/bin/bash" ), }); } public static IEnumerable<ShortToken> GetSeparators() { return new[] { new ShortToken ( SyntaxKind.WhitespaceTrivia, " " ), new ShortToken ( SyntaxKind.WhitespaceTrivia, " " ), new ShortToken ( SyntaxKind.WhitespaceTrivia, "\t" ), new ShortToken ( SyntaxKind.EndOfLineTrivia, "\r" ), new ShortToken ( SyntaxKind.EndOfLineTrivia, "\n" ), new ShortToken ( SyntaxKind.EndOfLineTrivia, "\r\n" ), new ShortToken ( SyntaxKind.MultiLineCommentTrivia, "/**/" ), new ShortToken ( SyntaxKind.MultiLineCommentTrivia, @"/* aaa */" ), new ShortToken ( SyntaxKind.MultiLineCommentTrivia, "--[[]]" ), new ShortToken(SyntaxKind.MultiLineCommentTrivia, @"--[[ aaa ]]"), new ShortToken ( SyntaxKind.MultiLineCommentTrivia, "--[=[]=]" ), new ShortToken ( SyntaxKind.MultiLineCommentTrivia, @"--[=[ aaa ]=]" ), new ShortToken ( SyntaxKind.MultiLineCommentTrivia, "--[====[]====]" ), new ShortToken ( SyntaxKind.MultiLineCommentTrivia, @"--[====[ aaa ]====]" ), }; } public static IEnumerable<(ShortToken tokenA, ShortToken tokenB)> GetTokenPairs(LuaSyntaxOptions options) => from tokenA in GetTokens(options) from tokB in GetTokens(options) where !SyntaxFacts.RequiresSeparator(tokenA.Kind, tokenA.Text, tokB.Kind, tokB.Text) let tokenB = tokB.WithSpan(new TextSpan(tokenA.Span.End, tokB.Span.Length)) select (tokenA, tokenB); public static IEnumerable<(ShortToken tokenA, ShortToken separator, ShortToken tokenB)> GetTokenPairsWithSeparators(LuaSyntaxOptions options) => from tokenA in GetTokens(options) from tokB in GetTokens(options) where !SyntaxFacts.RequiresSeparator(tokenA.Kind, tokenA.Text, tokB.Kind, tokB.Text) from sep in GetSeparators() where !SyntaxFacts.RequiresSeparator(tokenA.Kind, tokenA.Text, sep.Kind, sep.Text) && !SyntaxFacts.RequiresSeparator(sep.Kind, sep.Text, tokB.Kind, tokB.Text) let separator = sep.WithSpan(new TextSpan(tokenA.Span.End, sep.Span.Length)) let tokenB = tokB.WithSpan(new TextSpan(separator.Span.End, tokB.Span.Length)) select (tokenA, separator, tokenB); } }
38.557078
170
0.488986
[ "MIT" ]
GGG-KILLER/Loretta
src/Compilers/Lua/Test/Syntax/Lexical/LexicalTestData.cs
8,449
C#
using System; namespace Tacto.Core { public class Category { public const string EtqCategoryAll = "all"; public Category(String name) { this.name = Decode( name ); } public static string Decode(string name) { name = name.Trim().ToLower(); if ( name.Length > 0 ) { name = name.Replace( '_', ' ' ); name = Char.ToUpper( name[ 0 ] ) + name.Substring( 1 ); } else { name = EtqCategoryAll; } return name; } public static string Encode(string name) { name = name.Trim().ToLower(); name = name.Replace( ' ', '_' ); return name; } private string name; public string Name { get { return name; } } } }
16.780488
59
0.577035
[ "MIT" ]
Baltasarq/Tacto
Core/Category.cs
688
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.AspNet.Mvc; using Microsoft.Framework.Caching.Memory; using Microsoft.Framework.Expiration.Interfaces; namespace MvcTagHelpersWebSite.Components { public class ProductsViewComponent : ViewComponent { [Activate] public ProductsService ProductsService { get; set; } public IViewComponentResult Invoke(string category) { IExpirationTrigger trigger; var products = ProductsService.GetProducts(category, out trigger); EntryLinkHelpers.ContextLink.AddExpirationTriggers(new[] { trigger }); ViewData["Products"] = products; return View(); } } }
34.16
111
0.699063
[ "Apache-2.0" ]
walkeeperY/ManagementSystem
test/WebSites/MvcTagHelpersWebSite/Components/ProductsViewComponent.cs
856
C#
using ControleDeAulas.Model.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ControleDeAulas.Model { public class Faixa { private IFaixa _faixa; public int Id { get; set; } public string NFaixa { get; set; } public string Descricao { get; set; } public Faixa(IFaixa f) { _faixa = f; } public List<Faixa> Get() { var faixas = new List<Faixa>(); faixas.AddRange(_faixa.Get()); return faixas; } } }
16.4375
40
0.686312
[ "MIT" ]
RodolfoGaspar/ControleDeAulas
Source/Movvimento.Model/Faixa.cs
528
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Crestron.SimplSharp; using Crestron.SimplSharpPro.EthernetCommunication; using PepperDash.Core; using PepperDash.Essentials.Core; namespace PepperDash.Essentials.Room.MobileControl { /// <summary> /// Represents a generic device connection through to and EISC for DDVC01 /// </summary> public class MobileControlDdvc01DeviceBridge : Device, IChannel, INumericKeypad { /// <summary> /// EISC used to talk to Simpl /// </summary> ThreeSeriesTcpIpEthernetIntersystemCommunications EISC; public MobileControlDdvc01DeviceBridge(string key, string name, ThreeSeriesTcpIpEthernetIntersystemCommunications eisc) : base(key, name) { EISC = eisc; } #region IChannel Members public void ChannelUp(bool pressRelease) { EISC.SetBool(1111, pressRelease); } public void ChannelDown(bool pressRelease) { EISC.SetBool(1111, pressRelease); } public void LastChannel(bool pressRelease) { EISC.SetBool(1111, pressRelease); } public void Guide(bool pressRelease) { EISC.SetBool(1111, pressRelease); } public void Info(bool pressRelease) { EISC.SetBool(1111, pressRelease); } public void Exit(bool pressRelease) { EISC.SetBool(1111, pressRelease); } #endregion #region INumericKeypad Members public void Digit0(bool pressRelease) { EISC.SetBool(1111, pressRelease); } public void Digit1(bool pressRelease) { EISC.SetBool(1111, pressRelease); } public void Digit2(bool pressRelease) { EISC.SetBool(1111, pressRelease); } public void Digit3(bool pressRelease) { EISC.SetBool(1111, pressRelease); } public void Digit4(bool pressRelease) { EISC.SetBool(1111, pressRelease); } public void Digit5(bool pressRelease) { EISC.SetBool(1111, pressRelease); } public void Digit6(bool pressRelease) { EISC.SetBool(1111, pressRelease); } public void Digit7(bool pressRelease) { EISC.SetBool(1111, pressRelease); } public void Digit8(bool pressRelease) { EISC.SetBool(1111, pressRelease); } public void Digit9(bool pressRelease) { EISC.SetBool(1111, pressRelease); } public bool HasKeypadAccessoryButton1 { get { throw new NotImplementedException(); } } public string KeypadAccessoryButton1Label { get { throw new NotImplementedException(); } } public void KeypadAccessoryButton1(bool pressRelease) { throw new NotImplementedException(); } public bool HasKeypadAccessoryButton2 { get { throw new NotImplementedException(); } } public string KeypadAccessoryButton2Label { get { throw new NotImplementedException(); } } public void KeypadAccessoryButton2(bool pressRelease) { throw new NotImplementedException(); } #endregion } }
19.22973
121
0.721363
[ "MIT" ]
JaytheSpazz/Essentials
PepperDashEssentials/AppServer/MobileControlDdvc01DeviceBridge.cs
2,848
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.Media.V20180601Preview.Outputs { [OutputType] public sealed class EnabledProtocolsResponse { /// <summary> /// Enable DASH protocol or not /// </summary> public readonly bool Dash; /// <summary> /// Enable Download protocol or not /// </summary> public readonly bool Download; /// <summary> /// Enable HLS protocol or not /// </summary> public readonly bool Hls; /// <summary> /// Enable SmoothStreaming protocol or not /// </summary> public readonly bool SmoothStreaming; [OutputConstructor] private EnabledProtocolsResponse( bool dash, bool download, bool hls, bool smoothStreaming) { Dash = dash; Download = download; Hls = hls; SmoothStreaming = smoothStreaming; } } }
25.58
81
0.585614
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Media/V20180601Preview/Outputs/EnabledProtocolsResponse.cs
1,279
C#
using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; using NetOffice.MSFormsApi; namespace NetOffice.MSFormsApi.Behind { /// <summary> /// DispatchInterface IWHTMLOption /// SupportByVersion MSForms, 2 /// </summary> [SupportByVersion("MSForms", 2)] [EntityType(EntityType.IsDispatchInterface), BaseType] public class IWHTMLOption : COMObject, NetOffice.MSFormsApi.IWHTMLOption { #pragma warning disable #region Type Information /// <summary> /// Contract Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type ContractType { get { if(null == _contractType) _contractType = typeof(NetOffice.MSFormsApi.IWHTMLOption); return _contractType; } } private static Type _contractType; /// <summary> /// Instance Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type InstanceType { get { return LateBindingApiWrapperType; } } private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(IWHTMLOption); return _type; } } #endregion #region Ctor /// <summary> /// Stub Ctor, not indented to use /// </summary> public IWHTMLOption() : base() { } #endregion #region Properties /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersion("MSForms", 2)] public virtual string HTMLName { get { return InvokerService.InvokeInternal.ExecuteStringPropertyGet(this, "HTMLName"); } set { InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "HTMLName", value); } } /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersion("MSForms", 2)] public virtual string Value { get { return InvokerService.InvokeInternal.ExecuteStringPropertyGet(this, "Value"); } set { InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "Value", value); } } /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersion("MSForms", 2)] public virtual bool Checked { get { return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "Checked"); } set { InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "Checked", value); } } /// <summary> /// SupportByVersion MSForms 2 /// Get/Set /// </summary> [SupportByVersion("MSForms", 2)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public virtual string HTMLType { get { return InvokerService.InvokeInternal.ExecuteStringPropertyGet(this, "HTMLType"); } set { InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "HTMLType", value); } } /// <summary> /// SupportByVersion MSForms 2 /// Get /// </summary> [SupportByVersion("MSForms", 2)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public virtual NetOffice.MSFormsApi.Enums.fmDisplayStyle DisplayStyle { get { return InvokerService.InvokeInternal.ExecuteEnumPropertyGet<NetOffice.MSFormsApi.Enums.fmDisplayStyle>(this, "DisplayStyle"); } } #endregion #region Methods #endregion #pragma warning restore } }
22.023392
129
0.647637
[ "MIT" ]
igoreksiz/NetOffice
Source/MSForms/Behind/DispatchInterfaces/IWHTMLOption.cs
3,768
C#
using System; using System.Collections.Generic; using System.Text; using System.Data.Sql; using System.Data.SqlClient; using System.Data.SqlTypes; using System.Transactions; using NUnit.Framework; using NW = alby.northwind.codegen; namespace alby.northwind.codegen.test.view { [TestFixture] public class TestAlphabetical_list_of_productsNoTransactions { string _connectionString ; public TestAlphabetical_list_of_productsNoTransactions() { _connectionString = Settings.ConnectionString() ; } [Test] public void TestLoadAll() { Console.WriteLine("LoadAll"); using (SqlConnection connection = new SqlConnection(_connectionString)) { connection.Open(); NW.view.Alphabetical_list_of_productsFactory factory = new NW.view.Alphabetical_list_of_productsFactory(); List<NW.view.Alphabetical_list_of_products> rowset = factory.Loadˡ(connection); Console.WriteLine(rowset.Count); Assert.Greater(rowset.Count, 0); // should get some rows back // test fields of first row NW.view.Alphabetical_list_of_products product = rowset[0]; Assert.AreEqual(product.ProductID, 1); Assert.AreEqual(product.ProductName, "Chai"); Assert.AreEqual(product.UnitPrice, 18.00m); Assert.AreEqual(product.Discontinued, false); } } [Test] public void TestLoadByProductName() { Console.WriteLine("LoadByProductName"); using (SqlConnection connection = new SqlConnection(_connectionString)) { connection.Open(); NW.view.Alphabetical_list_of_productsFactory factory = new NW.view.Alphabetical_list_of_productsFactory(); string productName = "NuNuCa Nuß-Nougat-Creme"; List<NW.view.Alphabetical_list_of_products> rowset = factory.LoadByProductName( connection, productName ) ; Console.WriteLine(rowset.Count); Assert.Greater(rowset.Count, 0); // should get some rows back // test fields of first row NW.view.Alphabetical_list_of_products product = rowset[0]; Assert.AreEqual(product.ProductID, 25); Assert.AreEqual(product.ProductName, productName); Assert.AreEqual(product.UnitPrice, 14.00m); Assert.AreEqual(product.Discontinued, false); } } [Test] public void TestLoadByProductNameAndDiscontinued() { Console.WriteLine("LoadByProductNameAndDiscontinued"); using (SqlConnection connection = new SqlConnection(_connectionString)) { connection.Open(); NW.view.Alphabetical_list_of_productsFactory factory = new NW.view.Alphabetical_list_of_productsFactory(); string productName = "NuNuCa Nuß-Nougat-Creme"; bool? discontinued = false ; List<NW.view.Alphabetical_list_of_products> rowset = factory.LoadByProductNameAndDiscontinued( connection, productName, discontinued ) ; Console.WriteLine(rowset.Count); Assert.Greater(rowset.Count, 0); // should get some rows back // test fields of first row NW.view.Alphabetical_list_of_products product = rowset[0]; Assert.AreEqual(product.ProductID, 25) ; Assert.AreEqual(product.ProductName, productName ) ; Assert.AreEqual(product.UnitPrice, 14.00m ) ; Assert.AreEqual(product.Discontinued, discontinued ) ; } } } }
30.766355
141
0.720231
[ "MIT" ]
casaletto/alby.northwind.2015
alby.northwind.codegen.test/view/Alphabetical_list_of_productsNoTransactions.cs
3,297
C#
namespace ClothingStore.Server.Data { using ClothingStore.Server.Models; using ClothingStore.Server.Data.Models; using ClothingStore.Server.Data.Configurations; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; public class ClothingStoreDbContext : IdentityDbContext<AppUser> { public ClothingStoreDbContext(DbContextOptions<ClothingStoreDbContext> options) : base(options) {} public DbSet<Category> Categories { get; set; } public DbSet<Product> Products { get; set; } public DbSet<Size> Sizes { get; set; } public DbSet<ProductSize> ProductSizes { get; set; } public DbSet<Color> Colors { get; set; } public DbSet<ProductColor> ProductColors { get; set; } public DbSet<Picture> Pictures { get; set; } public DbSet<ShoppingCart> ShoppingCarts { get; set; } public DbSet<ShoppingCartItem> ShoppingCartItems { get; set; } protected override void OnModelCreating(ModelBuilder builder) { builder.ApplyConfiguration(new CategoryConfig()); builder.ApplyConfiguration(new ProductConfig()); builder.ApplyConfiguration(new SizeConfig()); builder.ApplyConfiguration(new ProductSizeConfig()); builder.ApplyConfiguration(new ColorConfig()); builder.ApplyConfiguration(new ProductColorConfig()); builder.ApplyConfiguration(new PictureConfig()); builder.ApplyConfiguration(new ShoppingCartConfig()); builder.ApplyConfiguration(new ShoppingCartItemConfig()); base.OnModelCreating(builder); } } }
35.5625
87
0.678969
[ "MIT" ]
deyanstoyanov10/Clothes-Store
ClothingStore.Server/ClothingStore.Server/Data/ClothingStoreDbContext.cs
1,709
C#
using System.Net.Http; namespace Telegram.Bot.Requests { public class ParameterlessRequest<TResult> : RequestBase<TResult> { public ParameterlessRequest(string methodName) : base(methodName) { } public ParameterlessRequest(string methodName, HttpMethod method) : base(methodName, method) { } /// <inheritdoc cref="RequestBase{TResponse}.ToHttpContent"/> public override HttpContent ToHttpContent() => default; } }
26.421053
73
0.653386
[ "MIT" ]
Akshay-Gupta/Telegram.Bot
src/Telegram.Bot/Requests/ParameterlessRequest.cs
504
C#
public static class AssemblyLine { private const int ProductionRatePerHourForDefaultSpeed = 221; public static double ProductionRatePerHour(int speed) => ProductionRatePerHourForSpeed(speed) * SuccessRate(speed); private static int ProductionRatePerHourForSpeed(int speed) => ProductionRatePerHourForDefaultSpeed * speed; public static int WorkingItemsPerMinute(int speed) => (int)(ProductionRatePerHour(speed) / 60); private static double SuccessRate(int speed) { if (speed == 0) return 0.0; if (speed >= 9) return 0.77; if (speed < 5) return 1.0; return 0.9; } }
25.592593
66
0.642547
[ "MIT" ]
EarthlingRich/v3
languages/csharp/exercises/concept/numbers/.meta/Example.cs
691
C#
namespace Zinnia.Data.Type.Transformation.Conversion { using System; using UnityEngine; using UnityEngine.Events; /// <summary> /// Transforms a boolean value to the equivalent float value. /// </summary> /// <example> /// false = 0f /// true = 1f /// </example> public class BooleanToFloat : Transformer<bool, float, BooleanToFloat.UnityEvent> { /// <summary> /// Defines the event with the transformed <see cref="float"/> value. /// </summary> [Serializable] public class UnityEvent : UnityEvent<float> { } [Tooltip("The value to use if the boolean is false.")] [SerializeField] private float falseValue = 0f; /// <summary> /// The value to use if the boolean is false. /// </summary> public float FalseValue { get { return falseValue; } set { falseValue = value; } } [Tooltip("The value to use if the boolean is true.")] [SerializeField] private float trueValue = 1f; /// <summary> /// The value to use if the boolean is true. /// </summary> public float TrueValue { get { return trueValue; } set { trueValue = value; } } /// <summary> /// Transforms the given input <see cref="bool"/> to the <see cref="float"/> equivalent value. /// </summary> /// <param name="input">The value to transform.</param> /// <returns>The transformed value.</returns> protected override float Process(bool input) { return input ? TrueValue : FalseValue; } } }
27.850746
102
0.504287
[ "MIT" ]
ExtendRealityLtd/VRTK.Unity.Core
Runtime/Data/Type/Transformation/Conversion/BooleanToFloat.cs
1,868
C#
namespace Be.Vlaanderen.Basisregisters.Shaperon { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Albedo; using AutoFixture; using AutoFixture.Idioms; using Xunit; public class DbaseDoubleTests { private readonly Fixture _fixture; public DbaseDoubleTests() { _fixture = new Fixture(); _fixture.CustomizeDbaseFieldName(); _fixture.CustomizeDbaseFieldLength(DbaseDouble.MaximumLength); _fixture.CustomizeDbaseDecimalCount(DbaseDouble.MaximumDecimalCount); _fixture.CustomizeDbaseDouble(); _fixture.Register(() => new BinaryReader(new MemoryStream())); _fixture.Register(() => new BinaryWriter(new MemoryStream())); } [Fact] public void MaximumDecimalCountReturnsExpectedValue() { Assert.Equal(new DbaseDecimalCount(15), DbaseDouble.MaximumDecimalCount); } [Fact] public void MaximumIntegerDigitsReturnsExpectedValue() { Assert.Equal(new DbaseIntegerDigits(18), DbaseDouble.MaximumIntegerDigits); } [Fact] public void MaximumLengthReturnsExpectedValue() { Assert.Equal(new DbaseFieldLength(18), DbaseDouble.MaximumLength); } [Fact] public void PositiveValueMinimumLengthReturnsExpectedValue() { Assert.Equal(new DbaseFieldLength(3), DbaseDouble.PositiveValueMinimumLength); } [Fact] public void NegativeValueMinimumLengthReturnsExpectedValue() { Assert.Equal(new DbaseFieldLength(4), DbaseDouble.NegativeValueMinimumLength); } [Fact] public void CreateFailsIfFieldIsNull() { Assert.Throws<ArgumentNullException>( () => new DbaseDouble(null) ); } [Fact] public void CreateFailsIfFieldIsNotNumber() { var fieldType = new Generator<DbaseFieldType>(_fixture) .First(specimen => specimen != DbaseFieldType.Number); var length = _fixture.GenerateDbaseDoubleLength(); var decimalCount = _fixture.GenerateDbaseDoubleDecimalCount(length); Assert.Throws<ArgumentException>( () => new DbaseDouble( new DbaseField( _fixture.Create<DbaseFieldName>(), fieldType, _fixture.Create<ByteOffset>(), length, decimalCount ) ) ); } [Theory] [InlineData(1)] [InlineData(2)] [InlineData(19)] [InlineData(254)] public void CreateFailsIfFieldLengthIsOutOfRange(int outOfRange) { var length = new DbaseFieldLength(outOfRange); var decimalCount = new DbaseDecimalCount(0); Assert.Throws<ArgumentException>( () => new DbaseDouble( new DbaseField( _fixture.Create<DbaseFieldName>(), DbaseFieldType.Number, _fixture.Create<ByteOffset>(), length, decimalCount ) ) ); } [Fact] public void IsDbaseFieldValue() { Assert.IsAssignableFrom<DbaseFieldValue>(_fixture.Create<DbaseDouble>()); } [Fact] public void ReaderCanNotBeNull() { new GuardClauseAssertion(_fixture) .Verify(new Methods<DbaseDouble>().Select(instance => instance.Read(null))); } [Fact] public void WriterCanNotBeNull() { new GuardClauseAssertion(_fixture) .Verify(new Methods<DbaseDouble>().Select(instance => instance.Write(null))); } [Fact] public void LengthOfPositiveValueBeingSetCanNotExceedFieldLength() { var length = DbaseDouble.MaximumLength; var decimalCount = _fixture.GenerateDbaseDoubleDecimalCount(length); var sut = new DbaseDouble( new DbaseField( _fixture.Create<DbaseFieldName>(), DbaseFieldType.Number, _fixture.Create<ByteOffset>(), length, decimalCount ) ); Assert.Throws<ArgumentException>(() => sut.Value = double.MaxValue); } [Fact] public void LengthOfNegativeValueBeingSetCanNotExceedFieldLength() { var length = DbaseDouble.MaximumLength; var decimalCount = _fixture.GenerateDbaseDoubleDecimalCount(length); var sut = new DbaseDouble( new DbaseField( _fixture.Create<DbaseFieldName>(), DbaseFieldType.Number, _fixture.Create<ByteOffset>(), length, decimalCount ) ); Assert.Throws<ArgumentException>(() => sut.Value = double.MinValue); } [Fact] public void CanReadWriteNull() { _fixture.CustomizeDbaseDoubleWithoutValue(); var sut = _fixture.Create<DbaseDouble>(); using (var stream = new MemoryStream()) { using (var writer = new BinaryWriter(stream, Encoding.ASCII, true)) { sut.Write(writer); writer.Flush(); } stream.Position = 0; using (var reader = new BinaryReader(stream, Encoding.ASCII, true)) { var result = new DbaseDouble(sut.Field); result.Read(reader); Assert.Equal(sut.Field, result.Field); Assert.Throws<FormatException>(() => sut.Value); } } } [Fact] public void CanReadWriteNegative() { using (var random = new PooledRandom()) { var sut = new DbaseDouble( new DbaseField( _fixture.Create<DbaseFieldName>(), DbaseFieldType.Number, _fixture.Create<ByteOffset>(), DbaseDouble.NegativeValueMinimumLength, new DbaseDecimalCount(1) ) ); sut.Value = new DbaseFieldNumberGenerator(random) .GenerateAcceptableValue(sut); using (var stream = new MemoryStream()) { using (var writer = new BinaryWriter(stream, Encoding.ASCII, true)) { sut.Write(writer); writer.Flush(); } stream.Position = 0; using (var reader = new BinaryReader(stream, Encoding.ASCII, true)) { var result = new DbaseDouble(sut.Field); result.Read(reader); Assert.Equal(sut, result, new DbaseFieldValueEqualityComparer()); } } } } [Fact] public void CanReadWriteWithMaxDecimalCount() { var length = DbaseDouble.MaximumLength; var decimalCount = DbaseDouble.MaximumDecimalCount; var sut = new DbaseDouble( new DbaseField( _fixture.Create<DbaseFieldName>(), DbaseFieldType.Number, _fixture.Create<ByteOffset>(), length, decimalCount ) ); using (var random = new PooledRandom()) { sut.Value = new DbaseFieldNumberGenerator(random) .GenerateAcceptableValue(sut); using (var stream = new MemoryStream()) { using (var writer = new BinaryWriter(stream, Encoding.ASCII, true)) { sut.Write(writer); writer.Flush(); } stream.Position = 0; using (var reader = new BinaryReader(stream, Encoding.ASCII, true)) { var result = new DbaseDouble(sut.Field); result.Read(reader); Assert.Equal(sut.Field, result.Field); Assert.Equal(sut.Value, result.Value); } } } } [Fact] public void CanReadWrite() { var sut = _fixture.Create<DbaseDouble>(); using (var stream = new MemoryStream()) { using (var writer = new BinaryWriter(stream, Encoding.ASCII, true)) { sut.Write(writer); writer.Flush(); } stream.Position = 0; using (var reader = new BinaryReader(stream, Encoding.ASCII, true)) { var result = new DbaseDouble(sut.Field); result.Read(reader); Assert.Equal(sut.Field, result.Field); Assert.Equal(sut.Value, result.Value); } } } [Fact] public void CanNotReadPastEndOfStream() { var sut = _fixture.Create<DbaseDouble>(); using (var stream = new MemoryStream()) { using (var writer = new BinaryWriter(stream, Encoding.ASCII, true)) { writer.Write(_fixture.CreateMany<byte>(new Random().Next(0, sut.Field.Length.ToInt32())).ToArray()); writer.Flush(); } stream.Position = 0; using (var reader = new BinaryReader(stream, Encoding.ASCII, true)) { var result = new DbaseDouble(sut.Field); Assert.Throws<EndOfStreamException>(() => result.Read(reader)); } } } [Fact] public void WritesExcessDecimalsAsZero() { var length = _fixture.GenerateDbaseDoubleLength(); var decimalCount = _fixture.GenerateDbaseDoubleDecimalCount(length); var sut = new DbaseDouble( new DbaseField( _fixture.Create<DbaseFieldName>(), DbaseFieldType.Number, _fixture.Create<ByteOffset>(), length, decimalCount ), 0.0); using (var stream = new MemoryStream()) { using (var writer = new BinaryWriter(stream, Encoding.ASCII, true)) { sut.Write(writer); writer.Flush(); } stream.Position = 0; if (decimalCount.ToInt32() == 0) { Assert.Equal( "0".PadLeft(length.ToInt32()), Encoding.ASCII.GetString(stream.ToArray())); } else { Assert.Equal( new string(' ', length.ToInt32() - decimalCount.ToInt32() - 2) + "0." + new string('0', decimalCount.ToInt32()), Encoding.ASCII.GetString(stream.ToArray()) ); } } } [Fact] public void HasValueReturnsExpectedResultWhenWithValue() { var sut = _fixture.Create<DbaseDouble>(); Assert.True(sut.HasValue); } [Fact] public void HasValueReturnsExpectedResultWhenWithoutValue() { _fixture.CustomizeDbaseDoubleWithoutValue(); var sut = _fixture.Create<DbaseDouble>(); Assert.False(sut.HasValue); } [Fact] public void ResetHasExpectedResult() { using (var random = new PooledRandom()) { var sut = _fixture.Create<DbaseDouble>(); sut.Value = new DbaseFieldNumberGenerator(random).GenerateAcceptableValue(sut); sut.Reset(); Assert.False(sut.HasValue); Assert.Throws<FormatException>(() => sut.Value); } } } }
32.915423
120
0.477706
[ "MIT" ]
Informatievlaanderen/shaperon
test/Be.Vlaanderen.Basisregisters.Shaperon.Tests/DbaseDoubleTests.cs
13,232
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using WslManager.Models; namespace WslManager.External { static class DistroManager { public static WindowsVersionManager windowsVersionManager = new WindowsVersionManager(); public static LxRunOfflineInterface lxRunOfflineInterface = new LxRunOfflineInterface("External\\LxRunOffline.exe"); public static WslInterface wslInterface = new WslInterface(windowsVersionManager); public static List<WslDistro> wslDistroList = new List<WslDistro>(); public static void RefreshWslDistroData() { string[] distroNames = lxRunOfflineInterface.GetDistroList(); if (distroNames == null) return; string[] runningDistros = wslInterface.GetRunningDistros(); foreach (WslDistro distroItem in wslDistroList) { if (!distroNames.Any(distroItem.DistroName.Equals)) wslDistroList.Remove(distroItem); } for (int i = 0; i < distroNames.Length; i++) { if (wslDistroList.Any(d => d.DistroName == distroNames[i])) { WslDistro wslDistro = wslDistroList.Find(d => d.DistroName == distroNames[i]); wslDistro.WSLVersion = lxRunOfflineInterface.GetDistroWslVersion(distroNames[i]); if (windowsVersionManager.CurrentVersion >= WindowsVersions.V1903) { if (runningDistros.Any(distroNames[i].Equals)) wslDistro.DistroStatus = "Running"; else wslDistro.DistroStatus = "Stopped"; } else { wslDistro.DistroStatus = "Unknown"; } } else { WslDistro wslDistro = new WslDistro(); wslDistro.DistroName = distroNames[i]; wslDistro.WSLVersion = lxRunOfflineInterface.GetDistroWslVersion(distroNames[i]); if (windowsVersionManager.CurrentVersion >= WindowsVersions.V1903) { if (runningDistros.Any(distroNames[i].Equals)) wslDistro.DistroStatus = "Running"; else wslDistro.DistroStatus = "Stopped"; } else { wslDistro.DistroStatus = "Unknown"; } wslDistroList.Add(wslDistro); } } } public static void StartDistro(string distroName) { Process p = lxRunOfflineInterface.RunDistro(distroName, false, false); RefreshWslDistroData(); } public static void OpenDistroFolder(string distroName) { var startInfo = new ProcessStartInfo( System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "explorer.exe"), lxRunOfflineInterface.GetDistroDir(distroName)) { UseShellExecute = false, }; Process.Start(startInfo); } public static void ExploreDistro(string distroName) { if (windowsVersionManager.CurrentVersion >= WindowsVersions.V1903) { lxRunOfflineInterface.RunDistro(distroName, false, true); var startInfo = new ProcessStartInfo( System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "explorer.exe"), $@"\\wsl$\{distroName}") { UseShellExecute = false, }; Process.Start(startInfo); RefreshWslDistroData(); } else { OpenDistroFolder(distroName); } } public static void MountDistro(string distroName) { lxRunOfflineInterface.RunDistro(distroName, true, false); RefreshWslDistroData(); } public static void RenameDistro(string distroName, string newDistroName) { string path = lxRunOfflineInterface.GetDistroDir(distroName); wslInterface.TerminateAllDistros(); lxRunOfflineInterface.UnregisterDistro(distroName); lxRunOfflineInterface.RegisterDistro(newDistroName, path); RefreshWslDistroData(); } public static void MoveDistro(string distroName, string targetPath) { wslInterface.TerminateAllDistros(); lxRunOfflineInterface.MoveDistro(distroName, targetPath); RefreshWslDistroData(); } public static void DuplicateDistor(string distroName, string newDistroName, string path) { wslInterface.TerminateAllDistros(); lxRunOfflineInterface.DuplicateDistro(distroName, path, newDistroName); RefreshWslDistroData(); } public static void ExportDistro() { // todo } public static void SwitchDistroVersion(string distroName, int targetVer) { wslInterface.TerminateDistro(distroName); wslInterface.SetVersion(distroName, targetVer); RefreshWslDistroData(); } public static void UnregisterDistro(string distroName) { wslInterface.TerminateDistro(distroName); lxRunOfflineInterface.UnregisterDistro(distroName); RefreshWslDistroData(); } public static void TerminateDistro(string distroName) { wslInterface.TerminateDistro(distroName); RefreshWslDistroData(); } public static void DeleteDistro(string distroName) { wslInterface.TerminateAllDistros(); string path = lxRunOfflineInterface.GetDistroDir(distroName); System.IO.DirectoryInfo directory = new DirectoryInfo(path); lxRunOfflineInterface.UnregisterDistro(distroName); directory.Delete(true); } public static void ImportDistro() { // todo } public static void ShutdownWsl() { wslInterface.TerminateAllDistros(); RefreshWslDistroData(); } public static void RegisterDistro(string newDistroName, string path) { wslInterface.TerminateAllDistros(); lxRunOfflineInterface.RegisterDistro(newDistroName, path); RefreshWslDistroData(); } public static void OpenLxRunOfflineConsole() { lxRunOfflineInterface.OpenConsole(); } public static void OpenWslConsole() { wslInterface.OpenConsole(); } public static void SetCustomWindowsVersion(int targetVersion) { windowsVersionManager.CurrentVersion = targetVersion; } } }
31.995614
124
0.568197
[ "MIT" ]
anaymalpani/WSLMANAGER
src/WslManager/External/DistroManager.cs
7,297
C#
// // Etheria Emergent Behaviour Framework. // // Copyright (C) 2018 Isaac Dart (www.linkedin.com/in/isaacdart) // // 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 UnityEngine; namespace EmergentBehaviour { public class FlockingBehaviour : EmergentBehaviour { public float separationDistance = 10f; public float windMetersPerSecond = 10f; public float radiusOfNeighbourhood = 30f; public float velocityVariation = 7f; public int minGroupSize = 2; public float universalCohesionBias = 0.25f; public float alignmentWeight = 1f; public float cohesionWeight = 1f; public float separationWeight = 1f; protected float universalCohesion = 0.25f; protected Vector3 windDirection = default(Vector3); public override void Initialize(EmergentGroup group) { base.Initialize(group); Name = "Flocking"; } public override void UpdateAgent(EmergentAgent a) { List<EmergentAgent> ns = _group.GetNeighbours(a, radiusOfNeighbourhood); if (ns.Count > minGroupSize) { universalCohesion = Mathf.Sin(Time.time) + universalCohesionBias; Vector3 groupAlignment = Vector3.zero; Vector3 groupCenter = _group.transform.position; Vector3 groupSeparation = default(Vector3); Vector3 groupCohesion = default(Vector3); for (int i = 0; i < ns.Count; i++) { groupAlignment += ns[i].direction; groupCenter += ns[i].position; groupSeparation += CalcSeparation(a, ns[i]); } //Alignment: Average all neighbours direction groupAlignment /= ns.Count; groupAlignment.Normalize(); //Cohesion: Direction towards the center of mass groupCenter /= ns.Count; groupCenter += (_group.transform.position - groupCenter) * universalCohesion; groupCohesion = (groupCenter - a.position).normalized; a.direction += groupAlignment * Time.deltaTime * alignmentWeight + groupCohesion * Time.deltaTime * cohesionWeight + groupSeparation * Time.deltaTime * separationWeight; a.direction.Normalize(); } else { //if we don't have enough friends then make a sad and introspective journey towards the center of the universe.. a.direction = (_group.transform.position - a.position).normalized; } a.position += a.direction * a.speedMetersPerSecond * Time.deltaTime; if (a.transform != null) a.transform.position = a.position; } Vector3 CalcSeparation(EmergentAgent agent, EmergentAgent other) { Vector3 heading = agent.position - other.position; if (heading.magnitude < separationDistance) { float scale = heading.magnitude / separationDistance; return heading.normalized / scale; } else { return Vector3.zero; } } public override void Tick() { //add some motion to the center of the entire universe... windDirection = new Vector3( Mathf.PerlinNoise(Time.time, windMetersPerSecond) * 2.0f - 1.0f, Mathf.PerlinNoise(Time.time, windMetersPerSecond) * 2.0f - 1.0f, Mathf.PerlinNoise(Time.time, windMetersPerSecond) * 2.0f - 1.0f ) ; _group.transform.position += windDirection * velocityVariation * Time.deltaTime; } /// <summary> /// Called from menu when creating a new flocking scriptable asset /// </summary> /// <returns></returns> public static FlockingBehaviour CreateFlockingBehaviour() { FlockingBehaviour fb = ScriptableObject.CreateInstance<FlockingBehaviour>(); return fb; } } }
33.27439
127
0.596298
[ "MIT" ]
Mann1ng/EtheriaEmergentBehaviourFramework
Assets/Etheria/Scripts/FlockingBehaviour.cs
5,459
C#
using System; using System.Threading.Tasks; using System.Windows.Forms; using appInfo = Aneejian.PowerPoint.Downsizer.AddIn.Fickles.AppInfo; namespace Aneejian.PowerPoint.Downsizer.AddIn { public partial class AboutBox : Form { public AboutBox() { InitializeComponent(); Text = string.Format("About {0}", appInfo.Title); labelProductName.Text = appInfo.Product; labelVersion.Text = string.Format("Version {0}", appInfo.Version.Replace("v", "")); labelCopyright.Text = appInfo.Copyright; labelCompanyName.Text = appInfo.Company; rtbUsageStats.Text = new UsageStats().ToString(); } private async void AneejianLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { await Performer.HomePage().ConfigureAwait(false); ActiveForm.Close(); } private async void BmcLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { await Performer.Coffee().ConfigureAwait(false); ActiveForm.Close(); } private void LogoBox_Click(object sender, EventArgs e) { ActiveForm.Close(); _ = Task.Run(() => Reporter.ReportUsageStats()).ConfigureAwait(false); } } }
34.025641
99
0.628485
[ "MIT" ]
kannansuresh/PowerPoint-Downsizer-Add-In
src/Aneejian.PowerPoint.Downsizer.AddIn/AboutBox.cs
1,329
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Runner.Web")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Runner.Web")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0fbe2112-846e-4ea5-bd26-60fdd0b1fa4e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.583333
84
0.746489
[ "Apache-2.0" ]
mehrandvd/Tralus
Selonia/Selonia.Accounting/Runner.Web/Properties/AssemblyInfo.cs
1,356
C#
using System; using System.IO; using System.Linq; using System.Threading.Tasks; using DotNetOpen.FileService; using DotNetOpen.FileService.Configuration; namespace DotNetOpen.FileService { /// <inheritdoc/> public class FileService : IFileService { private readonly IFileServiceConfig _fileServiceConfig; /// <summary> /// The configuration for a File Handler / Service /// </summary> /// <param name="fileServiceConfig">The configuration to be used</param> public FileService(IFileServiceConfig fileServiceConfig) { this._fileServiceConfig = fileServiceConfig; } private void ValidateConfiguration() { if (_fileServiceConfig == null) throw new ArgumentNullException(nameof(_fileServiceConfig), "File Service configuration was not supplied"); else if(!_fileServiceConfig.IsValid()) throw new ArgumentException(nameof(_fileServiceConfig), "File Service configuration is not valid"); } #region Get /// <inheritdoc/> public IFileMetaData GetFile(string fileName, string fileType, bool throwOnException = true, bool throwOnNotFound = true) { try { string absolutePath = Path.Combine(_fileServiceConfig.RootDirectory, fileName); return new FileMetaData(_fileServiceConfig, fileName, fileType, throwOnException && throwOnNotFound); } catch (Exception ex) { if (ex is FileNotFoundException && !throwOnNotFound) return null; if (throwOnException) throw ex; return null; } } /// <inheritdoc/> public IFileMetaData[] GetAllFiles(string fileType, bool throwOnException = true, bool throwOnNotFound = true) { try { return Directory.EnumerateFiles(_fileServiceConfig.RootDirectory + Path.DirectorySeparatorChar + fileType)?.Select(x => new FileMetaData(_fileServiceConfig, x.Split(Path.DirectorySeparatorChar)?.LastOrDefault(), x.Split(Path.DirectorySeparatorChar)?.Reverse()?.Skip(1)?.FirstOrDefault(), throwOnException))?.ToArray(); } catch (Exception ex) { if (ex is FileNotFoundException && !throwOnNotFound) return null; if (throwOnException) throw ex; return null; } } /// <inheritdoc/> public IFileMetaData[] GetAllFiles(bool throwOnException = true, bool throwOnNotFound = true) { try { return Directory.EnumerateDirectories(_fileServiceConfig.RootDirectory)?.SelectMany(y => Directory.EnumerateFiles(y)?.Select(x => new FileMetaData(_fileServiceConfig, x.Split(Path.DirectorySeparatorChar)?.LastOrDefault(), x.Split(Path.DirectorySeparatorChar)?.Reverse()?.Skip(1)?.FirstOrDefault(), throwOnException)) )?.ToArray(); } catch (Exception ex) { if (ex is FileNotFoundException && !throwOnNotFound) return null; if (throwOnException) throw ex; return null; } } /// <inheritdoc/> public long GetNoOfFiles(string fileType, bool throwOnException = true, bool throwOnNotFound = true) { try { return Directory.EnumerateFileSystemEntries(_fileServiceConfig.RootDirectory + Path.DirectorySeparatorChar + fileType, $"*.{fileType}")?.LongCount() ?? 0; } catch (Exception ex) { if (ex is FileNotFoundException && !throwOnNotFound) return 0; if (throwOnException) throw ex; return 0; } } /// <inheritdoc/> public long GetNoOfFiles(bool throwOnException = true, bool throwOnNotFound = true) { try { return Directory.EnumerateFileSystemEntries(_fileServiceConfig.RootDirectory + Path.DirectorySeparatorChar)? .Select(x => Directory.EnumerateFileSystemEntries(x).LongCount())?.Sum() ?? 0; } catch (Exception ex) { if (ex is FileNotFoundException && !throwOnNotFound) return 0; if (throwOnException) throw ex; return 0; } } #endregion #region Create /// <inheritdoc/> public IFileMetaData Create(string fileType, byte[] bytes, bool throwOnException = true) { try { ValidateRules(_fileServiceConfig, bytes, fileType); string fileName = Guid.NewGuid().ToString(); IFileMetaData fileMetaData = new FileMetaData(_fileServiceConfig, fileName, fileType, false); if (!File.Exists(fileMetaData.AbsolutePath)) { new FileInfo(fileMetaData.AbsolutePath).Directory.Create(); File.WriteAllBytes(fileMetaData.AbsolutePath, bytes); fileMetaData.RefreshFileInfo(); } return fileMetaData; } catch (Exception ex) { if (throwOnException) throw ex; return null; } } /// <inheritdoc/> public async Task<IFileMetaData> CreateAsync(string fileType, byte[] bytes, bool throwOnException = true) { try { ValidateRules(_fileServiceConfig, bytes, fileType); string fileName = Guid.NewGuid().ToString(); IFileMetaData fileMetaData = new FileMetaData(_fileServiceConfig, fileName, fileType, false); if (!File.Exists(fileMetaData.AbsolutePath)) { new FileInfo(fileMetaData.AbsolutePath).Directory.Create(); await Task.Factory.StartNew(() => File.WriteAllBytes(fileMetaData.AbsolutePath, bytes)); fileMetaData.RefreshFileInfo(); } return fileMetaData; } catch (Exception ex) { if (throwOnException) throw ex; return null; } } /// <inheritdoc/> public IFileMetaData Create(string fileName, string fileType, byte[] bytes, bool throwOnException = true) { try { ValidateRules(_fileServiceConfig, bytes, fileType, fileName); var extension = Path.GetExtension(fileName); IFileMetaData fileMetaData = new FileMetaData(_fileServiceConfig, fileName, fileType, false); if (!fileMetaData.Exists) { new FileInfo(fileMetaData.AbsolutePath).Directory.Create(); File.WriteAllBytes(fileMetaData.AbsolutePath, bytes); fileMetaData.RefreshFileInfo(); } return fileMetaData; } catch (Exception ex) { if (throwOnException) throw ex; return null; } } /// <inheritdoc/> public async Task<IFileMetaData> CreateAsync(string fileName, string fileType, byte[] bytes, bool throwOnException = true) { try { ValidateRules(_fileServiceConfig, bytes, fileType, fileName); IFileMetaData fileMetaData = new FileMetaData(_fileServiceConfig, fileName, fileType, false); if (!fileMetaData.Exists) { new FileInfo(fileMetaData.AbsolutePath).Directory.Create(); await Task.Factory.StartNew(() => File.WriteAllBytes(fileMetaData.AbsolutePath, bytes)); fileMetaData.RefreshFileInfo(); } return fileMetaData; } catch (Exception ex) { if (throwOnException) throw ex; return null; } } /// <inheritdoc/> public IFileMetaData Create(string fileType, Stream stream, bool throwOnException = true) { try { ValidateRules(_fileServiceConfig, stream, fileType); string fileName = Guid.NewGuid().ToString(); IFileMetaData fileMetaData = new FileMetaData(_fileServiceConfig, stream, fileName, fileType, false); return fileMetaData; } catch (Exception ex) { if (throwOnException) throw ex; return null; } } /// <inheritdoc/> public async Task<IFileMetaData> CreateAsync(string fileType, Stream stream, bool throwOnException = true) { try { ValidateRules(_fileServiceConfig, stream, fileType); string fileName = Guid.NewGuid().ToString(); IFileMetaData fileMetaData = await Task.Factory.StartNew(() => new FileMetaData(_fileServiceConfig, stream, fileName, fileType, false)); return fileMetaData; } catch (Exception ex) { if (throwOnException) throw ex; return null; } } /// <inheritdoc/> public IFileMetaData Create(string fileName, string fileType, Stream stream, bool throwOnException = true) { try { ValidateRules(_fileServiceConfig, stream, fileType, fileName); IFileMetaData fileMetaData = new FileMetaData(_fileServiceConfig, stream, fileName, fileType, false); return fileMetaData; } catch (Exception ex) { if (throwOnException) throw ex; return null; } } /// <inheritdoc/> public async Task<IFileMetaData> CreateAsync(string fileName, string fileType, Stream stream, bool throwOnException = true) { try { ValidateRules(_fileServiceConfig, stream, fileType, fileName); IFileMetaData fileMetaData = await Task.Factory.StartNew(() => new FileMetaData(_fileServiceConfig, stream, fileName, fileType, false)); return fileMetaData; } catch (Exception ex) { if (throwOnException) throw ex; return null; } } #endregion #region Update /// <inheritdoc/> public IFileMetaData Update(string fileName, string fileType, byte[] bytes, bool throwOnException = true, bool throwOnNotFound = true) { try { ValidateRules(_fileServiceConfig, bytes, fileType, fileName); string absolutePath = _fileServiceConfig.RootDirectory + Path.DirectorySeparatorChar + fileType + Path.DirectorySeparatorChar + fileName; Delete(fileName, fileType, throwOnException, true); File.WriteAllBytes(absolutePath, bytes); IFileMetaData fileMetaData = new FileMetaData(_fileServiceConfig, fileName, fileType, false); return fileMetaData; } catch (Exception ex) { if (throwOnException) throw ex; return null; } } /// <inheritdoc/> public async Task<IFileMetaData> UpdateAsync(string fileName, string fileType, byte[] bytes, bool throwOnException = true, bool throwOnNotFound = true) { try { ValidateRules(_fileServiceConfig, bytes, fileType, fileName); string absolutePath = _fileServiceConfig.RootDirectory + Path.DirectorySeparatorChar + fileType + Path.DirectorySeparatorChar + fileName; Delete(fileName, fileType, throwOnException, true); await Task.Factory.StartNew(() => File.WriteAllBytes(absolutePath, bytes)); IFileMetaData fileMetaData = new FileMetaData(_fileServiceConfig, fileName, fileType, false); return fileMetaData; } catch (Exception ex) { if (throwOnException) throw ex; return null; } } /// <inheritdoc/> public IFileMetaData Update(string fileName, string fileType, Stream stream, bool throwOnException = true, bool throwOnNotFound = true) { try { ValidateRules(_fileServiceConfig, stream, fileType, fileName); string absolutePath = _fileServiceConfig.RootDirectory + Path.DirectorySeparatorChar + fileType + Path.DirectorySeparatorChar + fileName; Delete(fileName, fileType, throwOnException, true); using (var fstream = new FileStream(absolutePath, FileMode.Open, FileAccess.Write)) stream.CopyTo(fstream); IFileMetaData fileMetaData = new FileMetaData(_fileServiceConfig, fileName, fileType, false); return fileMetaData; } catch (Exception ex) { if (throwOnException) throw ex; return null; } } /// <inheritdoc/> public async Task<IFileMetaData> UpdateAsync(string fileName, string fileType, Stream stream, bool throwOnException = true, bool throwOnNotFound = true) { try { ValidateRules(_fileServiceConfig, stream, fileType, fileName); string absolutePath = _fileServiceConfig.RootDirectory + Path.DirectorySeparatorChar + fileType + Path.DirectorySeparatorChar + fileName; Delete(fileName, fileType, throwOnException, true); using (var fstream = new FileStream(absolutePath, FileMode.Open, FileAccess.Write)) await stream.CopyToAsync(fstream); IFileMetaData fileMetaData = new FileMetaData(_fileServiceConfig, fileName, fileType, false); return fileMetaData; } catch (Exception ex) { if (throwOnException) throw ex; return null; } } #endregion #region Move /// <inheritdoc/> public IFileMetaData Move(string fileName, string oldFileType, string newFileType, bool throwOnException = true, bool throwOnNotFound = true) { try { string absolutePath = _fileServiceConfig.RootDirectory + Path.DirectorySeparatorChar + oldFileType + Path.DirectorySeparatorChar + fileName; if (!File.Exists(absolutePath)) throw new FileNotFoundException($"The File \"{absolutePath}\" was not found."); File.Move(absolutePath, _fileServiceConfig.RootDirectory + Path.DirectorySeparatorChar + newFileType + Path.DirectorySeparatorChar + fileName); IFileMetaData fileMetaData = new FileMetaData(_fileServiceConfig, fileName, newFileType, throwOnException); return fileMetaData; } catch (Exception ex) { if (ex is FileNotFoundException) { if (throwOnNotFound) throw ex; return null; } if (throwOnException) throw ex; return null; } } public async Task<IFileMetaData> MoveAsync(string fileName, string oldFileType, string newFileType, bool throwOnException = true, bool throwOnNotFound = true) { try { string absolutePath = _fileServiceConfig.RootDirectory + Path.DirectorySeparatorChar + oldFileType + Path.DirectorySeparatorChar + fileName; if (!File.Exists(absolutePath)) throw new FileNotFoundException($"The File \"{absolutePath}\" was not found."); await Task.Factory.StartNew(() => File.Move(absolutePath, _fileServiceConfig.RootDirectory + Path.DirectorySeparatorChar + newFileType + Path.DirectorySeparatorChar + fileName)); IFileMetaData fileMetaData = new FileMetaData(_fileServiceConfig, fileName, newFileType, throwOnException); return fileMetaData; } catch (Exception ex) { if (ex is FileNotFoundException) { if (throwOnNotFound) throw ex; return null; } if (throwOnException) throw ex; return null; } } #endregion #region Delete /// <inheritdoc/> public void Delete(string fileName, string fileType, bool throwOnException = true, bool throwOnNotFound = false) { try { string absolutePath = _fileServiceConfig.RootDirectory + Path.DirectorySeparatorChar + fileType + Path.DirectorySeparatorChar + fileName; if (!File.Exists(absolutePath)) { if (throwOnNotFound) throw new FileNotFoundException($"The File \"{absolutePath}\" was not found."); return; } File.Delete(absolutePath); } catch (Exception ex) { if (ex is FileNotFoundException) { if (throwOnNotFound) throw ex; return; } if (throwOnException) throw ex; } } /// <inheritdoc/> public async Task DeleteAsync(string fileName, string fileType, bool throwOnException = true, bool throwOnNotFound = false) { try { string absolutePath = _fileServiceConfig.RootDirectory + Path.DirectorySeparatorChar + fileType + Path.DirectorySeparatorChar + fileName; if (!File.Exists(absolutePath)) { if (throwOnNotFound) throw new FileNotFoundException($"The File \"{absolutePath}\" was not found."); return; } await Task.Factory.StartNew(() => File.Delete(absolutePath)); } catch (Exception ex) { if (ex is FileNotFoundException) { if (throwOnNotFound) throw ex; return; } if (throwOnException) throw ex; } } #endregion private void ValidateRules(IFileServiceConfig fileServiceConfig, Stream inputStream, string fileType, string fileName = null) { fileServiceConfig?.Rules?.ExecuteAllRules(fileServiceConfig, inputStream, fileType, fileName); } private void ValidateRules(IFileServiceConfig fileServiceConfig, byte[] inputBytes, string fileType, string fileName = null) { fileServiceConfig?.Rules?.ExecuteAllRules(fileServiceConfig, inputBytes, fileType, fileName); } } }
41.926247
334
0.566691
[ "MIT" ]
DaniAsh551/DotNetOpen
FileService/DotNetOpen.FileService/FileService.cs
19,330
C#
// Ball.cs // A simple class to encapsulate the game ball using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; namespace Chapter13 { class Ball : GameObject { protected float m_DX; public float DX { get { return m_DX; } set { m_DX = value; } } protected float m_DY; public float DY { get { return m_DY; } set { m_DY = value; } } } }
17.9
47
0.506518
[ "MIT" ]
MoreOnCode/MyXnaBookSource
XNA-2.x/Part 2 - Genre Studies/CH13 - Ping Pong/Ball.cs
537
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. using System; using System.Collections.Generic; using System.Drawing; using BGSObjectDetector; namespace LineDetector { class DetectionLine { public static int MIN_BOX_SIZE = 1000;//smaller boxes than this will go. public static double DEFAULT_OCCUPANCY_THRESHOLD = 0.9; // default threhsold public int x1, y1, x2, y2; public double increment; public double overlapFractionThreshold = DEFAULT_OCCUPANCY_THRESHOLD; public DetectionLine(int a, int b, int c, int d) { x1 = a; y1 = b; x2 = c; y2 = d; double length = Math.Sqrt(Math.Pow((double)(y2 - y1), 2) + Math.Pow((double)(x2 - x1), 2)); increment = 1 / (2 * length); } public DetectionLine(int a, int b, int c, int d, double l_threshold) { x1 = a; y1 = b; x2 = c; y2 = d; double length = Math.Sqrt(Math.Pow((double)(y2 - y1), 2) + Math.Pow((double)(x2 - x1), 2)); increment = 1 / (2 * length); overlapFractionThreshold = l_threshold; } public double getFractionContainedInBox(Box b, Bitmap mask) { double eta = 0; double currentX = x1 + eta * (x2 - x1); double currentY = y1 + eta * (y2 - y1); double lastX = -1; double lastY = -1; int totalPixelCount = 0; int overlapCount = 0; do { if ((lastX == currentX) && (lastY == currentY)) continue; totalPixelCount++; bool isInside = b.IsPointInterior((int)currentX, (int)currentY); if (mask.GetPixel((int)currentX, (int)currentY).ToString() == "Color [A=255, R=255, G=255, B=255]") { overlapCount++; } lastX = currentX; lastY = currentY; eta += increment; currentX = x1 + eta * (x2 - x1); currentY = y1 + eta * (y2 - y1); } while (eta <= 1); double fraction = (double)overlapCount / (double)totalPixelCount; return fraction; } public double getFractionInForeground(Bitmap mask) { double eta = 0; double currentX = x1 + eta * (x2 - x1); double currentY = y1 + eta * (y2 - y1); double lastX = -1; double lastY = -1; int totalPixelCount = 0; int overlapCount = 0; do { if ((lastX == currentX) && (lastY == currentY)) continue; totalPixelCount++; if (mask.GetPixel((int)currentX, (int)currentY).ToString() == "Color [A=255, R=255, G=255, B=255]") { overlapCount++; } lastX = currentX; lastY = currentY; eta += increment; currentX = x1 + eta * (x2 - x1); currentY = y1 + eta * (y2 - y1); } while (eta <= 1); double fraction = (double)overlapCount / (double)totalPixelCount; return fraction; } public (double frac, Box b) getMaximumFractionContainedInAnyBox(List<Box> boxes, Bitmap mask) { double maxOverlapFraction = 0; Box maxB = null; for (int boxNo = 0; boxNo < boxes.Count; boxNo++) { Box b = boxes[boxNo]; if (b.Area < MIN_BOX_SIZE) continue; double overlapFraction = getFractionContainedInBox(b, mask); if (overlapFraction > maxOverlapFraction) { maxOverlapFraction = overlapFraction; maxB = b; } } return (maxOverlapFraction, maxB); } public (bool occupied, Box box) isOccupied(List<Box> boxes, Bitmap mask) { (double frac, Box b) = getMaximumFractionContainedInAnyBox(boxes, mask); if (frac >= overlapFractionThreshold) { return (true, b); } else { return (false, null); } } public bool isOccupied(Bitmap mask) { double frac = getFractionInForeground(mask); if (frac >= overlapFractionThreshold) { return true; } else { return false; } } public override string ToString() { return x1 + "\t" + y1 + "\t" + x2 + "\t" + y2 + "\t" + overlapFractionThreshold; } } }
30.954839
115
0.484368
[ "MIT" ]
AshishVale/live-video-analytics
ref-apps/rocket/csharp/src/VAP/LineDetector/DetectionLine.cs
4,800
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace lpubsppop01.AnyTextFilterVSIX { class FilterRunner : INotifyPropertyChanged { #region Constructor Func<IWpfTextView> getWpfTextView; public FilterRunner(Func<IWpfTextView> getWpfTextView) { this.getWpfTextView = getWpfTextView; } #endregion #region Properties bool hasUserInputVariables; public bool HasUserInputVariables { get { return hasUserInputVariables; } set { hasUserInputVariables = value; OnPropertyChanged(); } } string userInputText = ""; public string UserInputText { get { return userInputText; } set { userInputText = value; OnPropertyChanged(); } } UserInputPreviewDocument previewDocument; public UserInputPreviewDocument PreviewDocument { get { return previewDocument; } set { previewDocument = value; OnPropertyChanged(); } } bool m_ShowsDifference; public bool ShowsDifference { get { return m_ShowsDifference; } set { m_ShowsDifference = value; OnPropertyChanged(); } } bool m_IsRunning; public bool IsRunning { get { return m_IsRunning; } private set { m_IsRunning = value; OnPropertyChanged(); } } public FilterHistoryManager HistoryManager { get; private set; } = new FilterHistoryManager(); public string ViewText { get { var wpfTextView = getWpfTextView(); if (wpfTextView == null) return ""; return wpfTextView.TextSnapshot.GetText(); } } #endregion #region Start/Stop Filter filter; string envNLInputText; List<SnapshotSpan> targetSpans; NewLineKind srcNewLineKind, envNewLineKind; int tabSize; public void Start(Filter filter) { if (filter == null) return; var wpfTextView = getWpfTextView(); if (wpfTextView == null) return; // Set filter and parameters this.filter = filter; this.tabSize = wpfTextView.Options.GetOptionValue(DefaultOptions.TabSizeOptionId); ShowsDifference = filter.UserInputWindow_ShowsDifference; HasUserInputVariables = filter.ContainsVariable(FilterProcess.VariableName_UserInput, FilterProcess.VariableName_UserInputTempFilePath); // Set target spans SnapshotSpan? spanToVisible; UpdateTargetSpans(filter, wpfTextView, out spanToVisible); // Analyze input text string rawInputText = string.Join("", targetSpans.Select(s => s.GetText())); envNewLineKind = Environment.NewLine.ToNewLineKind(); srcNewLineKind = rawInputText.DetectNewLineKind() ?? envNewLineKind; envNLInputText = rawInputText.ConvertNewLine(srcNewLineKind, envNewLineKind); // Scroll main view to make target span visible if (spanToVisible.HasValue) { wpfTextView.ViewScroller.EnsureSpanVisible(spanToVisible.Value, EnsureSpanVisibleOptions.AlwaysCenter); } // Start first filtering TryStartFilteringTask(); // Start watching IsRunning = true; PropertyChanged += this_PropertyChanged; taskSupport.PropertyChanged += taskSupport_PropertyChanged; } void UpdateTargetSpans(Filter filter, IWpfTextView wpfTextView, out SnapshotSpan? spanToVisible) { spanToVisible = null; targetSpans = new List<SnapshotSpan>(); foreach (var span in wpfTextView.Selection.SelectedSpans.Where(s => s.Length > 0)) { targetSpans.Add(span); } if (targetSpans.Any()) { spanToVisible = targetSpans.First(); } else { if (filter.TargetSpanForNoSelection == TargetSpanForNoSelection.CaretPosition) { targetSpans.Add(new SnapshotSpan(wpfTextView.TextSnapshot, new Span(wpfTextView.Caret.Position.BufferPosition, 0))); var currLine = wpfTextView.TextViewLines.GetTextViewLineContainingBufferPosition(wpfTextView.Caret.Position.BufferPosition); spanToVisible = currLine.Extent; } else if (filter.TargetSpanForNoSelection == TargetSpanForNoSelection.CurrentLine) { var currLine = wpfTextView.TextViewLines.GetTextViewLineContainingBufferPosition(wpfTextView.Caret.Position.BufferPosition); targetSpans.Add(currLine.Extent); spanToVisible = currLine.Extent; } else if (filter.TargetSpanForNoSelection == TargetSpanForNoSelection.WholeDocument) { targetSpans.Add(new SnapshotSpan(wpfTextView.TextSnapshot, new Span(0, wpfTextView.TextSnapshot.Length))); } } } public void Stop() { // Stop watching PropertyChanged -= this_PropertyChanged; taskSupport.PropertyChanged -= taskSupport_PropertyChanged; IsRunning = false; } #endregion #region Event Handlers RepeatedAsyncTaskSupport taskSupport = new RepeatedAsyncTaskSupport(); IList<string> lastResult; void this_PropertyChanged(object sender, PropertyChangedEventArgs e) { // Start filtering task if (e.PropertyName == "UserInputText" || e.PropertyName == "ShowsDifference") { TryStartFilteringTask(); } // Save settings if (e.PropertyName == "ShowsDifference" && filter != null) { filter.UserInputWindow_ShowsDifference = ShowsDifference; AnyTextFilterSettings.SaveCurrent(); } } void taskSupport_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName != "IsRunning") return; IsRunning = taskSupport.IsRunning; } void TryStartFilteringTask() { if (!taskSupport.TryStart()) return; Task.Factory.StartNew(async () => { do { var resultTextBuf = new List<string>(); bool cancelled = false; foreach (var span in targetSpans) { string envNLSpanText = span.GetText().ConvertNewLine(srcNewLineKind, envNewLineKind); var filterResult = await FilterProcess.RunAsync(filter, envNLSpanText, UserInputText, taskSupport); if (filterResult.Kind == FilterResultKind.Cancelled) { cancelled = true; break; } resultTextBuf.Add(filterResult.OutputText); } if (cancelled) continue; lastResult = resultTextBuf.Select(s => s.ConvertNewLine(envNewLineKind, srcNewLineKind)).ToArray(); var previewText = string.Concat(resultTextBuf); PreviewDocument = new UserInputPreviewDocument(previewText, tabSize, ShowsDifference ? envNLInputText : null); } while (taskSupport.CheckRepeat()); taskSupport.Stop(); }); } #endregion #region Apply public void ApplyLastResult() { var wpfTextView = getWpfTextView(); var textEdit = wpfTextView.TextBuffer.CreateEdit(); int iSpan = 0; foreach (var span in targetSpans) { string resultText = lastResult[iSpan]; if (filter.InsertsAfterTargetSpan) { var currLine = wpfTextView.TextViewLines.GetTextViewLineContainingBufferPosition(span.End); textEdit.Insert(currLine.End, Environment.NewLine + resultText); } else { textEdit.Delete(span); textEdit.Insert(span.Start, resultText); } } textEdit.Apply(); HistoryManager.AddHistoryItem(new FilterHistoryItem { FilterID = filter.ID, UserInputText = UserInputText }); UserInputText = ""; } #endregion #region Relay to Main View public void EnsureMainViewLineVisible(int lineIndex) { // ref. http://stackoverflow.com/questions/6186925/visual-studio-extensibility-move-to-line-in-a-textdocument var wpfTextView = getWpfTextView(); if (wpfTextView == null) return; var startLine = wpfTextView.TextSnapshot.GetLineFromPosition(targetSpans.First().Start.Position); if (startLine == null) return; int lineNumber = lineIndex + startLine.LineNumber; var targetLine = wpfTextView.TextSnapshot.Lines.FirstOrDefault(l => l.LineNumber == lineNumber); if (targetLine == null) return; var span = Span.FromBounds(targetLine.Start.Position, targetLine.End.Position); var snapshotSpan = new SnapshotSpan(wpfTextView.TextSnapshot, span); wpfTextView.ViewScroller.EnsureSpanVisible(snapshotSpan, EnsureSpanVisibleOptions.AlwaysCenter); wpfTextView.Caret.MoveTo(snapshotSpan.Start); } #endregion #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged([CallerMemberName] string propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion } }
37.290657
149
0.56899
[ "MIT" ]
lpubsppop01/AnyFilterVSIX
AnyTextFilterVSIX/UserInput/FilterRunner.cs
10,779
C#
using System.Collections.Generic; using System; namespace ClassLibrary { public class clsCustomerCollection { //Private data member for the list List<clsCustomer> mCustomerList = new List<clsCustomer>(); //Private data member for ThisCustomer clsCustomer mThisCustomer = new clsCustomer(); //Class constructor public clsCustomerCollection() { //Object for data conneciton clsDataConnection DB = new clsDataConnection(); //Execute the stored procedure DB.Execute("sproc_tblCustomer_SelectAll"); //Populate the array list with the data table PopulateArray(DB); } public List<clsCustomer> CustomerList { get { //Return private data return mCustomerList; } set { //Set the private data mCustomerList = value; } } public int Count { get { //Return private data return mCustomerList.Count; } set { } } public clsCustomer ThisCustomer { get { //Return private data return mThisCustomer; } set { //Set the private data mThisCustomer = value; } } public int Add() { //Adds a new record to the database based on the values of mThisCustomer //Connect to the dayabase clsDataConnection DB = new clsDataConnection(); //set the parameters for the stored procedure DB.AddParameter("@TraderPassword", mThisCustomer.TraderPassword); DB.AddParameter("@BusinessName", mThisCustomer.BusinessName); DB.AddParameter("@ContactEmail", mThisCustomer.ContactEmail); DB.AddParameter("@DeliveryAddress", mThisCustomer.DeliveryAddress); DB.AddParameter("@AccountCreationDate", mThisCustomer.AccountCreationDate); DB.AddParameter("@IsSignedIn", mThisCustomer.IsSignedIn); DB.AddParameter("@NumberOfOrders", mThisCustomer.NumberOfOrders); //Execute the query returning the Primary Key Value return DB.Execute("sproc_tblCustomer_Insert"); } public void Update() { //Adds a new record to the database based on the values of mThisCustomer //Connect to the database clsDataConnection DB = new clsDataConnection(); //set the parameters for the stored procedure DB.AddParameter("@TraderID", mThisCustomer.TraderId); DB.AddParameter("@TraderPassword", mThisCustomer.TraderPassword); DB.AddParameter("@BusinessName", mThisCustomer.BusinessName); DB.AddParameter("@ContactEmail", mThisCustomer.ContactEmail); DB.AddParameter("@DeliveryAddress", mThisCustomer.DeliveryAddress); DB.AddParameter("@AccountCreationDate", mThisCustomer.AccountCreationDate); DB.AddParameter("@IsSignedIn", mThisCustomer.IsSignedIn); DB.AddParameter("@NumberOfOrders", mThisCustomer.NumberOfOrders); //Execute the query returning the Primary Key Value DB.Execute("sproc_tblCustomer_Update"); } public void Delete() { //Deletes a record pointed from mThisCustomer //Connect to the database clsDataConnection DB = new clsDataConnection(); //set the parameters for the stored procedure DB.AddParameter("@TraderID", mThisCustomer.TraderId); //Execute the stored procedure DB.Execute("sproc_tblCustomer_Delete"); } public void ReportByBusinessName(string BusinessName) { //Filters records based on the business name //Connect to the database clsDataConnection DB = new clsDataConnection(); //set the parameters for the stored procedure DB.AddParameter("@BusinessName", BusinessName); //Execute the stored procedure DB.Execute("sproc_tblCustomer_FilterByBusinessName"); //Populate the array list with the data table PopulateArray(DB); } void PopulateArray(clsDataConnection DB) { //Variable for the index Int32 Index = 0; //Variable to store record count Int32 RecordCount; //Get the count of records RecordCount = DB.Count; //Clear the private array list mCustomerList = new List<clsCustomer>(); //While there are records to process while (Index < RecordCount) { //Create a blank Customer clsCustomer customer = new clsCustomer(); //Read the fields in the current record customer.TraderId = Convert.ToInt32(DB.DataTable.Rows[Index]["TraderID"]); customer.TraderPassword = Convert.ToString(DB.DataTable.Rows[Index]["TraderPassword"]); customer.BusinessName = Convert.ToString(DB.DataTable.Rows[Index]["BusinessName"]); customer.ContactEmail = Convert.ToString(DB.DataTable.Rows[Index]["ContactEmail"]); customer.DeliveryAddress = Convert.ToString(DB.DataTable.Rows[Index]["DeliveryAddress"]); customer.AccountCreationDate = Convert.ToDateTime(DB.DataTable.Rows[Index]["AccountCreationDate"]); customer.IsSignedIn = Convert.ToBoolean(DB.DataTable.Rows[Index]["IsSignedIn"]); customer.NumberOfOrders = Convert.ToInt32(DB.DataTable.Rows[Index]["NumberOfOrders"]); //Add the record to the private object mCustomerList.Add(customer); Index++; } } } }
38.853503
115
0.58459
[ "Apache-2.0" ]
IMAT2207/Dawn-Johnston
ClassLibrary/clsCustomerCollection.cs
6,102
C#
using System; using System.Collections.Generic; using System.ComponentModel; using Windows.Foundation.Metadata; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using WBrush = Windows.UI.Xaml.Media.Brush; using WSolidColorBrush = Windows.UI.Xaml.Media.SolidColorBrush; namespace Xamarin.Forms.Platform.UWP { [Windows.UI.Xaml.Data.Bindable] public class ShellRenderer : Microsoft.UI.Xaml.Controls.NavigationView, IVisualElementRenderer, IAppearanceObserver, IFlyoutBehaviorObserver { public static readonly DependencyProperty FlyoutBackgroundColorProperty = DependencyProperty.Register( nameof(FlyoutBackgroundColor), typeof(Brush), typeof(ShellRenderer), new PropertyMetadata(default(Brush))); internal static readonly Windows.UI.Color DefaultBackgroundColor = Windows.UI.Color.FromArgb(255, 3, 169, 244); internal static readonly Windows.UI.Color DefaultForegroundColor = Windows.UI.Colors.White; internal static readonly Windows.UI.Color DefaultTitleColor = Windows.UI.Colors.White; internal static readonly Windows.UI.Color DefaultUnselectedColor = Windows.UI.Color.FromArgb(180, 255, 255, 255); const string TogglePaneButton = "TogglePaneButton"; const string NavigationViewBackButton = "NavigationViewBackButton"; internal const string ShellStyle = "ShellNavigationView"; Shell _shell; Brush _flyoutBackdrop; FlyoutBehavior _flyoutBehavior; List<List<Element>> _flyoutGrouping; ShellItemRenderer ItemRenderer { get; } IShellController ShellController => (IShellController)_shell; public ShellRenderer() { Xamarin.Forms.Shell.VerifyShellUWPFlagEnabled(nameof(ShellRenderer)); _flyoutBackdrop = Brush.Default; IsSettingsVisible = false; PaneDisplayMode = Microsoft.UI.Xaml.Controls.NavigationViewPaneDisplayMode.LeftMinimal; IsPaneOpen = false; Content = ItemRenderer = CreateShellItemRenderer(); MenuItemTemplateSelector = CreateShellFlyoutTemplateSelector(); Style = Windows.UI.Xaml.Application.Current.Resources["ShellNavigationView"] as Windows.UI.Xaml.Style; } async void OnBackRequested(Microsoft.UI.Xaml.Controls.NavigationView sender, Microsoft.UI.Xaml.Controls.NavigationViewBackRequestedEventArgs args) { try { await _shell.Navigation.PopAsync(); } catch (Exception exc) { Internals.Log.Warning(nameof(Shell), $"Failed to Navigate Back: {exc}"); } } public WBrush FlyoutBackgroundColor { get => (WBrush)GetValue(FlyoutBackgroundColorProperty); set => SetValue(FlyoutBackgroundColorProperty, value); } protected override void OnApplyTemplate() { base.OnApplyTemplate(); UpdatePaneButtonColor(TogglePaneButton, !IsPaneOpen); UpdatePaneButtonColor(NavigationViewBackButton, !IsPaneOpen); (GetTemplateChild(TogglePaneButton) as FrameworkElement)?.SetAutomationPropertiesAutomationId("OK"); } void OnPaneOpening(Microsoft.UI.Xaml.Controls.NavigationView sender, object args) { if (Shell != null) Shell.FlyoutIsPresented = true; UpdatePaneButtonColor(TogglePaneButton, false); UpdatePaneButtonColor(NavigationViewBackButton, false); UpdateFlyoutBackgroundColor(); UpdateFlyoutBackdrop(); UpdateFlyoutVerticalScrollMode(); } void OnPaneOpened(Microsoft.UI.Xaml.Controls.NavigationView sender, object args) { // UWP likes to sometimes set the back drop back to the // default color UpdateFlyoutBackdrop(); } void OnPaneClosing(Microsoft.UI.Xaml.Controls.NavigationView sender, Microsoft.UI.Xaml.Controls.NavigationViewPaneClosingEventArgs args) { args.Cancel = true; if (Shell != null) Shell.FlyoutIsPresented = false; UpdatePaneButtonColor(TogglePaneButton, true); UpdatePaneButtonColor(NavigationViewBackButton, true); } void OnMenuItemInvoked(Microsoft.UI.Xaml.Controls.NavigationView sender, Microsoft.UI.Xaml.Controls.NavigationViewItemInvokedEventArgs args) { var item = args.InvokedItemContainer?.DataContext as Element; if (item != null) ShellController.OnFlyoutItemSelected(item); } #region IVisualElementRenderer event EventHandler<VisualElementChangedEventArgs> _elementChanged; event EventHandler<VisualElementChangedEventArgs> IVisualElementRenderer.ElementChanged { add { _elementChanged += value; } remove { _elementChanged -= value; } } FrameworkElement IVisualElementRenderer.ContainerElement => this; VisualElement IVisualElementRenderer.Element => Element; SizeRequest IVisualElementRenderer.GetDesiredSize(double widthConstraint, double heightConstraint) { var constraint = new Windows.Foundation.Size(widthConstraint, heightConstraint); double oldWidth = Width; double oldHeight = Height; Height = double.NaN; Width = double.NaN; Measure(constraint); var result = new Size(Math.Ceiling(DesiredSize.Width), Math.Ceiling(DesiredSize.Height)); Width = oldWidth; Height = oldHeight; return new SizeRequest(result); } public UIElement GetNativeElement() => null; public void Dispose() { SetElement(null); } public void SetElement(VisualElement element) { if (Element != null && element != null) throw new NotSupportedException("Reuse of the Shell Renderer is not supported"); if (element != null) { if (ApiInformation.IsEventPresent("Windows.UI.Xaml.Controls.NavigationView", "PaneClosing")) PaneClosing += OnPaneClosing; if (ApiInformation.IsEventPresent("Windows.UI.Xaml.Controls.NavigationView", "PaneOpening")) PaneOpening += OnPaneOpening; if (ApiInformation.IsEventPresent("Windows.UI.Xaml.Controls.NavigationView", "PaneOpened")) PaneOpened += OnPaneOpened; ItemInvoked += OnMenuItemInvoked; BackRequested += OnBackRequested; Element = (Shell)element; Element.SizeChanged += OnElementSizeChanged; OnElementSet(Element); Element.PropertyChanged += OnElementPropertyChanged; ItemRenderer.SetShellContext(this); _elementChanged?.Invoke(this, new VisualElementChangedEventArgs(null, Element)); } else if (Element != null) { Element.SizeChanged -= OnElementSizeChanged; Element.PropertyChanged -= OnElementPropertyChanged; if (ApiInformation.IsEventPresent("Windows.UI.Xaml.Controls.NavigationView", "PaneClosing")) PaneClosing -= OnPaneClosing; if (ApiInformation.IsEventPresent("Windows.UI.Xaml.Controls.NavigationView", "PaneOpening")) PaneOpening -= OnPaneOpening; if (ApiInformation.IsEventPresent("Windows.UI.Xaml.Controls.NavigationView", "PaneOpened")) PaneOpened -= OnPaneOpened; ItemInvoked -= OnMenuItemInvoked; BackRequested -= OnBackRequested; } } #endregion IVisualElementRenderer ShellSplitView ShellSplitView => (ShellSplitView)GetTemplateChild("RootSplitView"); ScrollViewer ShellLeftNavScrollViewer => (ScrollViewer)GetTemplateChild("LeftNavScrollViewer"); protected internal Shell Element { get; set; } internal Shell Shell => Element; void OnElementSizeChanged(object sender, EventArgs e) { InvalidateMeasure(); } protected virtual void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == Shell.CurrentItemProperty.PropertyName) { SwitchShellItem(Element.CurrentItem); } else if (e.PropertyName == Shell.FlyoutIsPresentedProperty.PropertyName) { IsPaneOpen = Shell.FlyoutIsPresented; } else if (e.PropertyName == Shell.FlyoutBackgroundColorProperty.PropertyName) { UpdateFlyoutBackgroundColor(); } else if (e.PropertyName == Shell.FlyoutVerticalScrollModeProperty.PropertyName) { UpdateFlyoutVerticalScrollMode(); } } void UpdateFlyoutVerticalScrollMode() { var scrollViewer = ShellLeftNavScrollViewer; if (scrollViewer != null) { switch (Shell.FlyoutVerticalScrollMode) { case ScrollMode.Disabled: scrollViewer.VerticalScrollMode = Windows.UI.Xaml.Controls.ScrollMode.Disabled; scrollViewer.VerticalScrollBarVisibility = Windows.UI.Xaml.Controls.ScrollBarVisibility.Hidden; break; case ScrollMode.Enabled: scrollViewer.VerticalScrollMode = Windows.UI.Xaml.Controls.ScrollMode.Enabled; scrollViewer.VerticalScrollBarVisibility = Windows.UI.Xaml.Controls.ScrollBarVisibility.Visible; break; default: scrollViewer.VerticalScrollMode = Windows.UI.Xaml.Controls.ScrollMode.Auto; scrollViewer.VerticalScrollBarVisibility = Windows.UI.Xaml.Controls.ScrollBarVisibility.Auto; break; } } } void UpdateFlyoutBackdrop() { if (_flyoutBehavior != FlyoutBehavior.Flyout) return; var splitView = ShellSplitView; if (splitView != null) { splitView.FlyoutBackdrop = _flyoutBackdrop; if (IsPaneOpen) ShellSplitView.UpdateFlyoutBackdrop(); } } protected virtual void UpdateFlyoutBackgroundColor() { if (_shell.FlyoutBackgroundColor == Color.Default) { object color = null; if (IsPaneOpen) color = Resources["NavigationViewExpandedPaneBackground"]; else color = Resources["NavigationViewDefaultPaneBackground"]; if (color is WBrush brush) FlyoutBackgroundColor = brush; else if (color is Windows.UI.Color uiColor) new WSolidColorBrush(uiColor); } else FlyoutBackgroundColor = _shell.FlyoutBackgroundColor.ToBrush(); } protected virtual void OnElementSet(Shell shell) { if (_shell != null) { ShellController.ItemsCollectionChanged -= OnItemsCollectionChanged; } _shell = shell; if (shell == null) return; var shr = CreateShellHeaderRenderer(shell); PaneCustomContent = shr; PaneFooter = CreateShellFooterRenderer(shell); UpdateMenuItemSource(); SwitchShellItem(shell.CurrentItem, false); IsPaneOpen = Shell.FlyoutIsPresented; ShellController.AddFlyoutBehaviorObserver(this); ShellController.AddAppearanceObserver(this, shell); ShellController.ItemsCollectionChanged += OnItemsCollectionChanged; ShellController.StructureChanged += OnStructureChanged; UpdateFlyoutBackgroundColor(); _shell.Navigated += OnShellNavigated; UpdateToolBar(); } void OnShellNavigated(object sender, ShellNavigatedEventArgs e) { UpdateToolBar(); } void UpdateToolBar() { if (SelectedItem == null) return; if(_shell.Navigation.NavigationStack.Count > 1) { IsBackEnabled = true; IsBackButtonVisible = Microsoft.UI.Xaml.Controls.NavigationViewBackButtonVisible.Visible; } else { IsBackEnabled = false; IsBackButtonVisible = Microsoft.UI.Xaml.Controls.NavigationViewBackButtonVisible.Collapsed; } switch (_flyoutBehavior) { case FlyoutBehavior.Disabled: IsPaneToggleButtonVisible = false; IsPaneVisible = false; PaneDisplayMode = Microsoft.UI.Xaml.Controls.NavigationViewPaneDisplayMode.LeftMinimal; IsPaneOpen = false; break; case FlyoutBehavior.Flyout: IsPaneVisible = true; IsPaneToggleButtonVisible = !IsBackEnabled; bool shouldOpen = Shell.FlyoutIsPresented; PaneDisplayMode = Microsoft.UI.Xaml.Controls.NavigationViewPaneDisplayMode.LeftMinimal; //This will trigger opening the flyout IsPaneOpen = shouldOpen; break; case FlyoutBehavior.Locked: IsPaneVisible = true; IsPaneToggleButtonVisible = false; PaneDisplayMode = Microsoft.UI.Xaml.Controls.NavigationViewPaneDisplayMode.Left; break; } } void OnStructureChanged(object sender, EventArgs e) { UpdateMenuItemSource(); } void OnItemsCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { UpdateMenuItemSource(); } void UpdateMenuItemSource() { var newGrouping = ((IShellController)Shell).GenerateFlyoutGrouping(); if (_flyoutGrouping != newGrouping) { _flyoutGrouping = newGrouping; MenuItemsSource = IterateItems(newGrouping); } } IEnumerable<object> IterateItems(List<List<Element>> groups) { foreach (var group in groups) { if (group.Count > 0 && group != groups[0]) { yield return new MenuFlyoutSeparator(); // Creates a separator } foreach (var item in group) { yield return item; } } } void SwitchShellItem(ShellItem newItem, bool animate = true) { SelectedItem = newItem; ItemRenderer.NavigateToShellItem(newItem, animate); } void UpdatePaneButtonColor(string name, bool overrideColor) { var toggleButton = GetTemplateChild(name) as Control; if (toggleButton != null) { var titleBar = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().TitleBar; if (overrideColor) toggleButton.Foreground = new WSolidColorBrush(titleBar.ButtonForegroundColor.Value); else toggleButton.ClearValue(Control.ForegroundProperty); } } #region IAppearanceObserver void IAppearanceObserver.OnAppearanceChanged(ShellAppearance appearance) { Windows.UI.Color backgroundColor = DefaultBackgroundColor; Windows.UI.Color titleColor = DefaultTitleColor; if (appearance != null) { if (!appearance.BackgroundColor.IsDefault) backgroundColor = appearance.BackgroundColor.ToWindowsColor(); if (!appearance.TitleColor.IsDefault) titleColor = appearance.TitleColor.ToWindowsColor(); _flyoutBackdrop = appearance.FlyoutBackdrop; } var titleBar = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().TitleBar; titleBar.BackgroundColor = titleBar.ButtonBackgroundColor = backgroundColor; titleBar.ForegroundColor = titleBar.ButtonForegroundColor = titleColor; UpdatePaneButtonColor(TogglePaneButton, !IsPaneOpen); UpdatePaneButtonColor(NavigationViewBackButton, !IsPaneOpen); UpdateFlyoutBackdrop(); } #endregion IAppearanceObserver void IFlyoutBehaviorObserver.OnFlyoutBehaviorChanged(FlyoutBehavior behavior) { _flyoutBehavior = behavior; UpdateToolBar(); } public virtual ShellFlyoutTemplateSelector CreateShellFlyoutTemplateSelector() => new ShellFlyoutTemplateSelector(); public virtual ShellHeaderRenderer CreateShellHeaderRenderer(Shell shell) => new ShellHeaderRenderer(shell); public virtual ShellFooterRenderer CreateShellFooterRenderer(Shell shell) => new ShellFooterRenderer(shell); public virtual ShellItemRenderer CreateShellItemRenderer() => new ShellItemRenderer(this); public virtual ShellSectionRenderer CreateShellSectionRenderer() => new ShellSectionRenderer(); } }
32.288591
148
0.755699
[ "MIT" ]
BenLampson/maui
src/Platform.Renderers/src/Xamarin.Forms.Platform.UAP/Shell/ShellRenderer.cs
14,435
C#
namespace Jambo.Producer.UI.Filters { using Jambo.Domain.Exceptions; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; public class DomainExceptionFilter : IExceptionFilter { public void OnException(ExceptionContext context) { DomainException domainException = context.Exception as DomainException; if (domainException != null) { string json = JsonConvert.SerializeObject(domainException.BusinessMessage); context.Result = new BadRequestObjectResult(json); context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; } } } }
31.071429
91
0.664368
[ "Apache-2.0" ]
Baldotto/jambo-event-sourcing
source/Producer/Jambo.Producer.UI/Filters/DomainExceptionFilter.cs
872
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using Microsoft.Azure.Management.EventGrid; using Microsoft.Azure.Management.EventGrid.Models; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using EventGrid.Tests.TestHelper; using Xunit; namespace EventGrid.Tests.ScenarioTests { public partial class ScenarioTests { [Fact(Skip = "This is not yet enabled for the new API version, will re-record once it is enabled")] public void TopicTypeTests() { const string StorageTopicType = "Microsoft.Storage.StorageAccounts"; const string EventHubsTopicType = "Microsoft.EventHub.Namespaces"; using (MockContext context = MockContext.Start(this.GetType())) { InitializeClients(context); var location = this.ResourceManagementClient.GetLocationFromProvider(); IEnumerable<TopicTypeInfo> topicTypesList = this.EventGridManagementClient.TopicTypes.ListAsync().Result; Assert.NotNull(topicTypesList); Assert.Contains(topicTypesList, tt => string.Equals(tt.Name, StorageTopicType, StringComparison.OrdinalIgnoreCase)); Assert.Contains(topicTypesList, tt => string.Equals(tt.Name, EventHubsTopicType, StringComparison.OrdinalIgnoreCase)); TopicTypeInfo storageTopicType = this.EventGridManagementClient.TopicTypes.GetAsync(StorageTopicType).Result; Assert.Equal(storageTopicType.Name, StorageTopicType); IEnumerable<EventType> eventTypesList = this.EventGridManagementClient.TopicTypes.ListEventTypesAsync(StorageTopicType).Result; Assert.NotNull(eventTypesList); Assert.Contains(eventTypesList, et => string.Equals(et.Name, "Microsoft.Storage.BlobCreated", StringComparison.OrdinalIgnoreCase)); } } } }
46.409091
147
0.713026
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/eventgrid/Microsoft.Azure.Management.EventGrid/tests/Tests/ScenarioTests.TopicTypeTests.cs
2,042
C#
using UnityEngine; using System.Collections; public class Plank2 : MonoBehaviour { private bool mB; private int mDecr; // Use this for initialization void Start () { mB=false; } // Update is called once per frame void Update () { if (!mB) if (Light2.mL) { mB=true; mDecr=300; } if (mDecr>0) { transform.Translate(0,0.1f,0); mDecr--; } } }
15.83871
42
0.480652
[ "MIT" ]
Cosmin96/HackEscape
Assets/Plank2.cs
493
C#
namespace ClassLib109 { public class Class042 { public static string Property => "ClassLib109"; } }
15
55
0.633333
[ "MIT" ]
333fred/performance
src/scenarios/weblarge2.0/src/ClassLib109/Class042.cs
120
C#
/**********************************************************\ | | | XXTEA.cs | | | | XXTEA encryption algorithm library for .NET. | | | | Encryption Algorithm Authors: | | David J. Wheeler | | Roger M. Needham | | | | Code Author: Ma Bingyao <mabingyao@gmail.com> | | LastModified: Mar 10, 2015 | | | \**********************************************************/ namespace Xxtea { using System; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; public sealed class XXTEA { private static readonly UTF8Encoding utf8 = new UTF8Encoding(); private const UInt32 delta = 0x9E3779B9; private static UInt32 MX(UInt32 sum, UInt32 y, UInt32 z, Int32 p, UInt32 e, UInt32[] k) { return (z >> 5 ^ y << 2) + (y >> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z); } private XXTEA() { } public static Byte[] Encrypt(Byte[] data, Byte[] key) { if (data.Length == 0) { return data; } return ToByteArray(Encrypt(ToUInt32Array(data, true), ToUInt32Array(FixKey(key), false)), false); } public static Byte[] Encrypt(String data, Byte[] key) { return Encrypt(utf8.GetBytes(data), key); } public static Byte[] Encrypt(Byte[] data, String key) { return Encrypt(data, utf8.GetBytes(key)); } public static Byte[] Encrypt(String data, String key) { return Encrypt(utf8.GetBytes(data), utf8.GetBytes(key)); } public static String EncryptToBase64String(Byte[] data, Byte[] key) { return Convert.ToBase64String(Encrypt(data, key)); } public static String EncryptToBase64String(String data, Byte[] key) { return Convert.ToBase64String(Encrypt(data, key)); } public static String EncryptToBase64String(Byte[] data, String key) { return Convert.ToBase64String(Encrypt(data, key)); } public static String EncryptToBase64String(String data, String key) { return Convert.ToBase64String(Encrypt(data, key)); } public static Byte[] Decrypt(Byte[] data, Byte[] key) { if (data.Length == 0) { return data; } return ToByteArray(Decrypt(ToUInt32Array(data, false), ToUInt32Array(FixKey(key), false)), true); } public static Byte[] Decrypt(Byte[] data, String key) { return Decrypt(data, utf8.GetBytes(key)); } public static Byte[] DecryptBase64String(String data, Byte[] key) { return Decrypt(Convert.FromBase64String(data), key); } public static Byte[] DecryptBase64String(String data, String key) { return Decrypt(Convert.FromBase64String(data), key); } public static String DecryptToString(Byte[] data, Byte[] key) { return utf8.GetString(Decrypt(data, key)); } public static String DecryptToString(Byte[] data, String key) { return utf8.GetString(Decrypt(data, key)); } public static String DecryptBase64StringToString(String data, Byte[] key) { return utf8.GetString(DecryptBase64String(data, key)); } public static String DecryptBase64StringToString(String data, String key) { return utf8.GetString(DecryptBase64String(data, key)); } private static UInt32[] Encrypt(UInt32[] v, UInt32[] k) { Int32 n = v.Length - 1; if (n < 1) { return v; } UInt32 z = v[n], y, sum = 0, e; Int32 p, q = 6 + 52 / (n + 1); unchecked { while (0 < q--) { sum += delta; e = sum >> 2 & 3; for (p = 0; p < n; p++) { y = v[p + 1]; z = v[p] += MX(sum, y, z, p, e, k); } y = v[0]; z = v[n] += MX(sum, y, z, p, e, k); } } return v; } private static UInt32[] Decrypt(UInt32[] v, UInt32[] k) { Int32 n = v.Length - 1; if (n < 1) { return v; } UInt32 z, y = v[0], sum, e; Int32 p, q = 6 + 52 / (n + 1); unchecked { sum = (UInt32)(q * delta); while (sum != 0) { e = sum >> 2 & 3; for (p = n; p > 0; p--) { z = v[p - 1]; y = v[p] -= MX(sum, y, z, p, e, k); } z = v[n]; y = v[0] -= MX(sum, y, z, p, e, k); sum -= delta; } } return v; } private static Byte[] FixKey(Byte[] key) { if (key.Length == 16) return key; Byte[] fixedkey = new Byte[16]; if (key.Length < 16) { key.CopyTo(fixedkey, 0); } else { Array.Copy(key, 0, fixedkey, 0, 16); } return fixedkey; } private static UInt32[] ToUInt32Array(Byte[] data, Boolean includeLength) { Int32 length = data.Length; Int32 n = (((length & 3) == 0) ? (length >> 2) : ((length >> 2) + 1)); UInt32[] result; if (includeLength) { result = new UInt32[n + 1]; result[n] = (UInt32)length; } else { result = new UInt32[n]; } for (Int32 i = 0; i < length; i++) { result[i >> 2] |= (UInt32)data[i] << ((i & 3) << 3); } return result; } private static Byte[] ToByteArray(UInt32[] data, Boolean includeLength) { Int32 n = data.Length << 2; if (includeLength) { Int32 m = (Int32)data[data.Length - 1]; n -= 4; if ((m < n - 3) || (m > n)) { return null; } n = m; } Byte[] result = new Byte[n]; for (Int32 i = 0; i < n; i++) { result[i] = (Byte)(data[i >> 2] >> ((i & 3) << 3)); } return result; } } public static class nhelper { private static byte[] keyAndIvBytes; static nhelper() { // You'll need a more secure way of storing this, I hope this isn't // the real key keyAndIvBytes = UTF8Encoding.UTF8.GetBytes("zEv3ZTRZ352AtPNY"); } public static byte[] StringToByteArray(string hex) { return Enumerable.Range(0, hex.Length) .Where(x => x % 2 == 0) .Select(x => Convert.ToByte(hex.Substring(x, 2), 16)) .ToArray(); } public static string dd(string cipherText) { string DecodeAndDecrypt = ad(StringToByteArray(cipherText)); return (DecodeAndDecrypt); } public static string ad(Byte[] inputBytes) { Byte[] outputBytes = inputBytes; string plaintext = string.Empty; using (MemoryStream memoryStream = new MemoryStream(outputBytes)) { using (CryptoStream cryptoStream = new CryptoStream(memoryStream, GetCryptoAlgorithm().CreateDecryptor(keyAndIvBytes, keyAndIvBytes), CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(cryptoStream)) { plaintext = srDecrypt.ReadToEnd(); } } } return plaintext; } private static RijndaelManaged GetCryptoAlgorithm() { RijndaelManaged algorithm = new RijndaelManaged(); //set the mode, padding and block size algorithm.Padding = PaddingMode.PKCS7; algorithm.Mode = CipherMode.CBC; algorithm.KeySize = 128; algorithm.BlockSize = 128; return algorithm; } } }
31.505085
173
0.425651
[ "MIT" ]
FDKPIBC/Taiwu_Mods_Tools
unity-mod-manager/UnityModManager/xxtea.cs
9,296
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cognito-identity-2014-06-30.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.CognitoIdentity.Model { /// <summary> /// Container for the parameters to the UnlinkDeveloperIdentity operation. /// Unlinks a <code>DeveloperUserIdentifier</code> from an existing identity. Unlinked /// developer users will be considered new identities next time they are seen. If, for /// a given Cognito identity, you remove all federated identities as well as the developer /// user identifier, the Cognito identity becomes inaccessible. /// </summary> public partial class UnlinkDeveloperIdentityRequest : AmazonCognitoIdentityRequest { private string _developerProviderName; private string _developerUserIdentifier; private string _identityId; private string _identityPoolId; /// <summary> /// Gets and sets the property DeveloperProviderName. /// <para> /// The "domain" by which Cognito will refer to your users. /// </para> /// </summary> public string DeveloperProviderName { get { return this._developerProviderName; } set { this._developerProviderName = value; } } // Check to see if DeveloperProviderName property is set internal bool IsSetDeveloperProviderName() { return this._developerProviderName != null; } /// <summary> /// Gets and sets the property DeveloperUserIdentifier. A unique ID used by your backend /// authentication process to identify a user. /// </summary> public string DeveloperUserIdentifier { get { return this._developerUserIdentifier; } set { this._developerUserIdentifier = value; } } // Check to see if DeveloperUserIdentifier property is set internal bool IsSetDeveloperUserIdentifier() { return this._developerUserIdentifier != null; } /// <summary> /// Gets and sets the property IdentityId. /// <para> /// A unique identifier in the format REGION:GUID. /// </para> /// </summary> public string IdentityId { get { return this._identityId; } set { this._identityId = value; } } // Check to see if IdentityId property is set internal bool IsSetIdentityId() { return this._identityId != null; } /// <summary> /// Gets and sets the property IdentityPoolId. /// <para> /// An identity pool ID in the format REGION:GUID. /// </para> /// </summary> public string IdentityPoolId { get { return this._identityPoolId; } set { this._identityPoolId = value; } } // Check to see if IdentityPoolId property is set internal bool IsSetIdentityPoolId() { return this._identityPoolId != null; } } }
33.486957
114
0.632563
[ "Apache-2.0" ]
amazon-archives/aws-sdk-xamarin
AWS.XamarinSDK/AWSSDK_Android/Amazon.CognitoIdentity/Model/UnlinkDeveloperIdentityRequest.cs
3,851
C#
using System; using Bisner.Mobile.Core.ViewModels.Booking; using MvvmCross.Binding.iOS.Views; using UIKit; namespace Bisner.Mobile.iOS.Views.ItemViews { public partial class TimeLineItemView : MvxCollectionViewCell { public TimeLineItemView(IntPtr handle) : base(handle) { } public string TimeString { get { return this.lblTime.Text; } set { this.lblTime.Text = value; } } TimeBlockType _timeBlockType; public TimeBlockType TimeBlockType { get { return _timeBlockType; } set { _timeBlockType = value; if (_timeBlockType == TimeBlockType.FIFTEEN) { vw15.Hidden = false; vw30.Hidden = false; vw45.Hidden = false; } else if (_timeBlockType == TimeBlockType.THIRTY) { vw15.Hidden = true; vw30.Hidden = false; vw45.Hidden = true; } else { vw15.Hidden = true; vw30.Hidden = true; vw45.Hidden = true; } } } public void InitStyle() { } } }
23.571429
65
0.421549
[ "MIT" ]
phoenix214/BisnerXamarin
Bisner.Mobile.iOS/Views/ItemViews/TimeLineItemView.cs
1,485
C#
namespace ProgressBarDemos; public partial class App : Application { public App() { InitializeComponent(); MainPage = new NavigationPage(new MainPage()); } }
14
48
0.720238
[ "MIT" ]
davidbritch/dotnet-maui-samples
UserInterface/Views/ProgressBarDemos/ProgressBarDemos/App.xaml.cs
170
C#
namespace _5.Mordor_sCrueltyPlan.FoodModels { public class Other : Food { public Other() : base(-1) { } } }
14.272727
44
0.484076
[ "MIT" ]
V-Uzunov/Soft-Uni-Education
07.C#OOPBasic/03.Inheritance/05.MordorCrueltyPlan/FoodModels/Other.cs
159
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _01.SumOfAllElementsOfMatrix { class SumOfAllElementsOfMatrix { static void Main(string[] args) { var size = Console.ReadLine().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList(); int rows = size[0]; int cols = size[1]; int sum = 0; int[,] matrix = new int[rows, cols]; for (int row = 0; row < matrix.GetLength(0); row++) { var input = Console.ReadLine().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList(); for (int col = 0; col < matrix.GetLength(1); col++) { matrix[row, col] = input[col]; sum += matrix[row, col]; } } Console.WriteLine(matrix.GetLength(0)); Console.WriteLine(matrix.GetLength(1)); Console.WriteLine(sum); } } }
29.473684
134
0.529464
[ "MIT" ]
deathstardestoryer/Soft-Uni
C# Advanced/Multidimensional Arrays - Lab/01. SumOfAllElementsOfMatrix/SumOfAllElementsOfMatrix.cs
1,122
C#
using System; using System.Collections.Generic; using System.Text; namespace BlogDemo.Core.Interfaces { public interface IEntity { int Id { get; set; } } }
14.833333
34
0.668539
[ "Apache-2.0" ]
corewithharry/ASP.NETCoreWebAPI
BlogDemo/BlogDemo.Core/Interfaces/IEntity.cs
180
C#
namespace TheBookProject.Web { using System.Reflection; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using App_Start; using Infrastructure.Mapping; #pragma warning disable SA1649 // File name must match first type name public class MvcApplication : HttpApplication #pragma warning restore SA1649 // File name must match first type name { protected void Application_Start() { ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new RazorViewEngine()); DatabaseConfig.Initialize(); AutofacConfig.RegisterAutofac(); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); var autoMapperConfig = new AutoMapperConfig(); autoMapperConfig.Execute(Assembly.GetExecutingAssembly()); } } }
32.151515
70
0.679548
[ "MIT" ]
The-Book-Project/The-Book-Project
Web/TheBookProject.Web/Global.asax.cs
1,063
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.Text; using System.Reflection; using System.Diagnostics; using System.Globalization; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Reflection.Runtime.General; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.TypeInfos.NativeFormat; using System.Reflection.Runtime.MethodInfos; using System.Reflection.Runtime.MethodInfos.NativeFormat; using System.Reflection.Runtime.ParameterInfos; using System.Reflection.Runtime.CustomAttributes; using Internal.Reflection.Core; using Internal.Reflection.Core.Execution; using Internal.Reflection.Tracing; using Internal.Metadata.NativeFormat; using NativeFormatMethodSemanticsAttributes = global::Internal.Metadata.NativeFormat.MethodSemanticsAttributes; namespace System.Reflection.Runtime.PropertyInfos.NativeFormat { // // The runtime's implementation of PropertyInfo's // [DebuggerDisplay("{_debugName}")] internal sealed partial class NativeFormatRuntimePropertyInfo : RuntimePropertyInfo { // // propertyHandle - the "tkPropertyDef" that identifies the property. // definingType - the "tkTypeDef" that defined the field (this is where you get the metadata reader that created propertyHandle.) // contextType - the type that supplies the type context (i.e. substitutions for generic parameters.) Though you // get your raw information from "definingType", you report "contextType" as your DeclaringType property. // // For example: // // typeof(Foo<>).GetTypeInfo().DeclaredMembers // // The definingType and contextType are both Foo<> // // typeof(Foo<int,String>).GetTypeInfo().DeclaredMembers // // The definingType is "Foo<,>" // The contextType is "Foo<int,String>" // // We don't report any DeclaredMembers for arrays or generic parameters so those don't apply. // private NativeFormatRuntimePropertyInfo(PropertyHandle propertyHandle, NativeFormatRuntimeNamedTypeInfo definingTypeInfo, RuntimeTypeInfo contextTypeInfo, RuntimeTypeInfo reflectedType) : base(contextTypeInfo, reflectedType) { _propertyHandle = propertyHandle; _definingTypeInfo = definingTypeInfo; _reader = definingTypeInfo.Reader; _property = propertyHandle.GetProperty(_reader); } public sealed override PropertyAttributes Attributes { get { return _property.Flags; } } public sealed override IEnumerable<CustomAttributeData> CustomAttributes { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.PropertyInfo_CustomAttributes(this); #endif foreach (CustomAttributeData cad in RuntimeCustomAttributeData.GetCustomAttributes(_reader, _property.CustomAttributes)) yield return cad; foreach (CustomAttributeData cad in ReflectionCoreExecution.ExecutionEnvironment.GetPseudoCustomAttributes(_reader, _propertyHandle, _definingTypeInfo.TypeDefinitionHandle)) yield return cad; } } public sealed override bool Equals(Object obj) { NativeFormatRuntimePropertyInfo other = obj as NativeFormatRuntimePropertyInfo; if (other == null) return false; if (!(_reader == other._reader)) return false; if (!(_propertyHandle.Equals(other._propertyHandle))) return false; if (!(ContextTypeInfo.Equals(other.ContextTypeInfo))) return false; if (!(_reflectedType.Equals(other._reflectedType))) return false; return true; } public sealed override int GetHashCode() { return _propertyHandle.GetHashCode(); } public sealed override Object GetConstantValue() { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.PropertyInfo_GetConstantValue(this); #endif Object defaultValue; if (!ReflectionCoreExecution.ExecutionEnvironment.GetDefaultValueIfAny( _reader, _propertyHandle, this.PropertyType, this.CustomAttributes, out defaultValue)) { throw new InvalidOperationException(); } return defaultValue; } public sealed override int MetadataToken { get { throw new InvalidOperationException(SR.NoMetadataTokenAvailable); } } protected sealed override QTypeDefRefOrSpec PropertyTypeHandle { get { return new QTypeDefRefOrSpec(_reader, _property.Signature.GetPropertySignature(_reader).Type); } } protected sealed override RuntimeNamedMethodInfo GetPropertyMethod(PropertyMethodSemantics whichMethod) { NativeFormatMethodSemanticsAttributes localMethodSemantics; switch (whichMethod) { case PropertyMethodSemantics.Getter: localMethodSemantics = NativeFormatMethodSemanticsAttributes.Getter; break; case PropertyMethodSemantics.Setter: localMethodSemantics = NativeFormatMethodSemanticsAttributes.Setter; break; default: return null; } bool inherited = !_reflectedType.Equals(ContextTypeInfo); foreach (MethodSemanticsHandle methodSemanticsHandle in _property.MethodSemantics) { MethodSemantics methodSemantics = methodSemanticsHandle.GetMethodSemantics(_reader); if (methodSemantics.Attributes == localMethodSemantics) { MethodHandle methodHandle = methodSemantics.Method; if (inherited) { MethodAttributes flags = methodHandle.GetMethod(_reader).Flags; if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) continue; } return RuntimeNamedMethodInfo<NativeFormatMethodCommon>.GetRuntimeNamedMethodInfo(new NativeFormatMethodCommon(methodHandle, _definingTypeInfo, ContextTypeInfo), _reflectedType); } } return null; } protected sealed override string MetadataName { get { return _property.Name.GetString(_reader); } } protected sealed override RuntimeTypeInfo DefiningTypeInfo { get { return _definingTypeInfo; } } private readonly NativeFormatRuntimeNamedTypeInfo _definingTypeInfo; private readonly PropertyHandle _propertyHandle; private readonly MetadataReader _reader; private readonly Property _property; } }
36.870192
198
0.625896
[ "MIT" ]
LaudateCorpus1/corert
src/System.Private.Reflection.Core/src/System/Reflection/Runtime/PropertyInfos/NativeFormat/NativeFormatRuntimePropertyInfo.cs
7,671
C#
using System; class Program { static void Main(string[] args) { string expression = "(((3.5 * 4.5) / (1 + 2)) + 5)"; Console.WriteLine(string.Format("{0} = {1}", expression, new Expression.ExpressionTree(expression).Value)); Console.WriteLine("\nShow's over folks, press a key to exit"); Console.ReadKey(false); } } namespace Expression { // ------------------------------------------------------- abstract class NodeBase { public abstract double Value { get; } } // ------------------------------------------------------- class ValueNode : NodeBase { public ValueNode(double value) { _double = value; } private double _double; public override double Value { get { return _double; } } } // ------------------------------------------------------- abstract class ExpressionNodeBase : NodeBase { protected NodeBase GetNode(string expression) { // Remove parenthesis expression = RemoveParenthesis(expression); // Is expression just a number? double value = 0; if (double.TryParse(expression, out value)) { return new ValueNode(value); } else { int pos = ParseExpression(expression); if (pos > 0) { string leftExpression = expression.Substring(0, pos - 1).Trim(); string rightExpression = expression.Substring(pos).Trim(); switch (expression.Substring(pos - 1, 1)) { case "+": return new Add(leftExpression, rightExpression); case "-": return new Subtract(leftExpression, rightExpression); case "*": return new Multiply(leftExpression, rightExpression); case "/": return new Divide(leftExpression, rightExpression); default: throw new Exception("Unknown operator"); } } else { throw new Exception("Unable to parse expression"); } } } private string RemoveParenthesis(string expression) { if (expression.Contains("(")) { expression = expression.Trim(); int level = 0; int pos = 0; foreach (char token in expression.ToCharArray()) { pos++; switch (token) { case '(': level++; break; case ')': level--; break; } if (level == 0) { break; } } if (level == 0 && pos == expression.Length) { expression = expression.Substring(1, expression.Length - 2); expression = RemoveParenthesis(expression); } } return expression; } private int ParseExpression(string expression) { int winningLevel = 0; byte winningTokenWeight = 0; int winningPos = 0; int level = 0; int pos = 0; foreach (char token in expression.ToCharArray()) { pos++; switch (token) { case '(': level++; break; case ')': level--; break; } if (level <= winningLevel) { if (OperatorWeight(token) > winningTokenWeight) { winningLevel = level; winningTokenWeight = OperatorWeight(token); winningPos = pos; } } } return winningPos; } private byte OperatorWeight(char value) { switch (value) { case '+': case '-': return 3; case '*': return 2; case '/': return 1; default: return 0; } } } // ------------------------------------------------------- class ExpressionTree : ExpressionNodeBase { protected NodeBase _rootNode; public ExpressionTree(string expression) { _rootNode = GetNode(expression); } public override double Value { get { return _rootNode.Value; } } } // ------------------------------------------------------- abstract class OperatorNodeBase : ExpressionNodeBase { protected NodeBase _leftNode; protected NodeBase _rightNode; public OperatorNodeBase(string leftExpression, string rightExpression) { _leftNode = GetNode(leftExpression); _rightNode = GetNode(rightExpression); } } // ------------------------------------------------------- class Add : OperatorNodeBase { public Add(string leftExpression, string rightExpression) : base(leftExpression, rightExpression) { } public override double Value { get { return _leftNode.Value + _rightNode.Value; } } } // ------------------------------------------------------- class Subtract : OperatorNodeBase { public Subtract(string leftExpression, string rightExpression) : base(leftExpression, rightExpression) { } public override double Value { get { return _leftNode.Value - _rightNode.Value; } } } // ------------------------------------------------------- class Divide : OperatorNodeBase { public Divide(string leftExpression, string rightExpression) : base(leftExpression, rightExpression) { } public override double Value { get { return _leftNode.Value / _rightNode.Value; } } } // ------------------------------------------------------- class Multiply : OperatorNodeBase { public Multiply(string leftExpression, string rightExpression) : base(leftExpression, rightExpression) { } public override double Value { get { return _leftNode.Value * _rightNode.Value; } } } }
21.109541
111
0.490793
[ "MIT" ]
dockerian/go-shuati
ds/exp/eval.cs
5,974
C#
namespace Bitmischief.Meridios.SmugMug.Entities { public enum FlipEnum { None, Horizontal, Vertical } }
10.285714
47
0.576389
[ "MIT" ]
zurfluha/SmugMugApiV2
Bitmischief.Meridios.SmugMug.Entities/Enums/FlipEnum.cs
144
C#
using System; using System.Collections; using System.Collections.Generic; namespace rm.Extensions { /// <summary> /// Defines circular queue methods. /// </summary> public interface ICircularQueue<T> { /// <summary> /// Enqueues <paramref name="x"/> into queue. /// </summary> void Enqueue(T x); /// <summary> /// Dequeues head from queue. /// </summary> T Dequeue(); /// <summary> /// Peeks head of queue. /// </summary> T Peek(); /// <summary> /// Peeks tail of queue. /// </summary> T PeekTail(); /// <summary> /// Returns true if queue is empty. /// </summary> bool IsEmpty(); /// <summary> /// Returns count of queue. /// </summary> int Count(); /// <summary> /// Returns capacity of queue. /// </summary> int Capacity(); /// <summary> /// Clears queue. /// </summary> void Clear(); } /// <summary> /// Circular queue. /// </summary> /// <remarks>Uses array as backing store.</remarks> public class CircularQueue<T> : ICircularQueue<T>, IEnumerable<T> { #region members private readonly T[] store; private readonly int capacity; private int count; private int head; private int tail; #endregion #region ctors public CircularQueue(int capacity = 8) { capacity.ThrowIfArgumentOutOfRange(minRange: 1, exMessage: nameof(capacity)); store = new T[capacity]; this.capacity = capacity; head = tail = count = 0; } #endregion #region ICircularQueue<T> methods /// <summary> /// Enqueues <paramref name="x"/> into queue. /// </summary> public void Enqueue(T x) { store[tail] = x; tail = WrapIndex(tail + 1); if (count == capacity) { head = tail; } if (count < capacity) { count++; } } /// <summary> /// Dequeues head from queue. /// </summary> public T Dequeue() { if (IsEmpty()) { throw new InvalidOperationException("Queue is empty."); } var item = store[head]; head = WrapIndex(head + 1); count--; return item; } /// <summary> /// Peeks head of queue. /// </summary> public T Peek() { if (IsEmpty()) { throw new InvalidOperationException("Queue is empty."); } return store[head]; } /// <summary> /// Peeks tail of queue. /// </summary> public T PeekTail() { if (IsEmpty()) { throw new InvalidOperationException("Queue is empty."); } return store[WrapIndex(tail - 1)]; } /// <summary> /// Returns true if queue is empty. /// </summary> public bool IsEmpty() { return count == 0; } /// <summary> /// Returns count of queue. /// </summary> public int Count() { return count; } /// <summary> /// Returns capacity of queue. /// </summary> public int Capacity() { return capacity; } /// <summary> /// Clears queue. /// </summary> public void Clear() { head = tail = count = 0; } #endregion private int WrapIndex(int index) { var wIndex = index % capacity; if (wIndex < 0) { wIndex += capacity; } return wIndex; } #region IEnumerable<T> methods public IEnumerator<T> GetEnumerator() { var index = head; for (int c = 0; c < count; c++) { yield return store[index]; index = WrapIndex(index + 1); } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } }
16.650246
80
0.58284
[ "MIT" ]
SammyEnigma/csharp-extensions
src/rm.Extensions/CircularQueue.cs
3,382
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("programmingincsharp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("programmingincsharp")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("227043cb-b3fc-4e10-a13b-0ab71fc2c6b3")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38
84
0.750356
[ "MIT" ]
meviktor/Microsoft-Exam-Ref-70-483
programmingincsharp/programmingincsharp/Properties/AssemblyInfo.cs
1,409
C#
// Copyright 2017 DAIMTO ([Linda Lawton](https://twitter.com/LindaLawtonDK)) : [www.daimto.com](http://www.daimto.com/) // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on // an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by DAIMTO-Google-apis-Sample-generator 1.0.0 // Template File Name: methodTemplate.tt // Build date: 2017-10-08 // C# generater version: 1.0.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // About // // Unoffical sample for the Dlp v2beta1 API for C#. // This sample is designed to be used with the Google .Net client library. (https://github.com/google/google-api-dotnet-client) // // API Description: The Google Data Loss Prevention API provides methods for detection of privacy-sensitive fragments in text, images, and Google Cloud Platform storage repositories. // API Documentation Link https://cloud.google.com/dlp/docs/ // // Discovery Doc https://www.googleapis.com/discovery/v1/apis/Dlp/v2beta1/rest // //------------------------------------------------------------------------------ // Installation // // This sample code uses the Google .Net client library (https://github.com/google/google-api-dotnet-client) // // NuGet package: // // Location: https://www.nuget.org/packages/Google.Apis.Dlp.v2beta1/ // Install Command: PM> Install-Package Google.Apis.Dlp.v2beta1 // //------------------------------------------------------------------------------ using Google.Apis.Dlp.v2beta1; using Google.Apis.Dlp.v2beta1.Data; using System; namespace GoogleSamplecSharpSample.Dlpv2beta1.Methods { public static class ContentSample { /// <summary> /// De-identifies potentially sensitive info from a list of strings.This method has limits on input size and output size. /// Documentation https://developers.google.com/dlp/v2beta1/reference/content/deidentify /// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong. /// </summary> /// <param name="service">Authenticated Dlp service.</param> /// <param name="body">A valid Dlp v2beta1 body.</param> /// <returns>GooglePrivacyDlpV2beta1DeidentifyContentResponseResponse</returns> public static GooglePrivacyDlpV2beta1DeidentifyContentResponse Deidentify(DlpService service, GooglePrivacyDlpV2beta1DeidentifyContentRequest body) { try { // Initial validation. if (service == null) throw new ArgumentNullException("service"); if (body == null) throw new ArgumentNullException("body"); // Make the request. return service.Content.Deidentify(body).Execute(); } catch (Exception ex) { throw new Exception("Request Content.Deidentify failed.", ex); } } /// <summary> /// Finds potentially sensitive info in a list of strings.This method has limits on input size, processing time, and output size. /// Documentation https://developers.google.com/dlp/v2beta1/reference/content/inspect /// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong. /// </summary> /// <param name="service">Authenticated Dlp service.</param> /// <param name="body">A valid Dlp v2beta1 body.</param> /// <returns>GooglePrivacyDlpV2beta1InspectContentResponseResponse</returns> public static GooglePrivacyDlpV2beta1InspectContentResponse Inspect(DlpService service, GooglePrivacyDlpV2beta1InspectContentRequest body) { try { // Initial validation. if (service == null) throw new ArgumentNullException("service"); if (body == null) throw new ArgumentNullException("body"); // Make the request. return service.Content.Inspect(body).Execute(); } catch (Exception ex) { throw new Exception("Request Content.Inspect failed.", ex); } } /// <summary> /// Redacts potentially sensitive info from a list of strings.This method has limits on input size, processing time, and output size. /// Documentation https://developers.google.com/dlp/v2beta1/reference/content/redact /// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong. /// </summary> /// <param name="service">Authenticated Dlp service.</param> /// <param name="body">A valid Dlp v2beta1 body.</param> /// <returns>GooglePrivacyDlpV2beta1RedactContentResponseResponse</returns> public static GooglePrivacyDlpV2beta1RedactContentResponse Redact(DlpService service, GooglePrivacyDlpV2beta1RedactContentRequest body) { try { // Initial validation. if (service == null) throw new ArgumentNullException("service"); if (body == null) throw new ArgumentNullException("body"); // Make the request. return service.Content.Redact(body).Execute(); } catch (Exception ex) { throw new Exception("Request Content.Redact failed.", ex); } } } public static class SampleHelpers { /// <summary> /// Using reflection to apply optional parameters to the request. /// /// If the optonal parameters are null then we will just return the request as is. /// </summary> /// <param name="request">The request. </param> /// <param name="optional">The optional parameters. </param> /// <returns></returns> public static object ApplyOptionalParms(object request, object optional) { if (optional == null) return request; System.Reflection.PropertyInfo[] optionalProperties = (optional.GetType()).GetProperties(); foreach (System.Reflection.PropertyInfo property in optionalProperties) { // Copy value from optional parms to the request. They should have the same names and datatypes. System.Reflection.PropertyInfo piShared = (request.GetType()).GetProperty(property.Name); if (property.GetValue(optional, null) != null) // TODO Test that we do not add values for items that are null piShared.SetValue(request, property.GetValue(optional, null), null); } return request; } } }
45.957831
182
0.610958
[ "Apache-2.0" ]
AhmerRaza/Google-Dotnet-Samples
Samples/DLP API/v2beta1/ContentSample.cs
7,631
C#
using System; using System.Collections.Generic; using System.Linq; using System.ComponentModel; using System.Threading.Tasks; using System.Collections.Concurrent; namespace LionFire.Trading.Workspaces { public class SignalViewModelBase : INotifyPropertyChanged { public Session Session { get; set; } public SignalViewModelBase() { } #region DisplayName public string DisplayName { get { return displayName; } set { if (displayName == value) return; displayName = value; OnPropertyChanged(nameof(DisplayName)); } } private string displayName; #endregion public IEnumerable<string> UnderlyingSymbolCodes { get; private set; } #region INotifyPropertyChanged Implementation public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion ConcurrentDictionary<string, SignalChangeNotifier> dict = new ConcurrentDictionary<string, SignalChangeNotifier>(); public SignalChangeNotifier GetSignalChangeNotifier(TimeFrame timeFrame) { return dict.GetOrAdd(timeFrame.Name, tf => new SignalChangeNotifier(this, timeFrame)); } #region Misc public override string ToString() { return DisplayName ?? this.GetType().Name; } #endregion } }
24.712121
123
0.632128
[ "MIT" ]
LionFire/Trading
src/LionFire.Trading/Workspaces/Sessions/Signals/SignalViewModelBase.cs
1,633
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Build.Common { using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using YamlDotNet.Serialization; using YamlDotNet.Core; using YamlDotNet.Serialization.Utilities; using Microsoft.DocAsCode.Common; using Microsoft.DocAsCode.DataContracts.Common; using Microsoft.DocAsCode.Plugins; using Constants = Microsoft.DocAsCode.DataContracts.Common.Constants; using YamlDeserializer = Microsoft.DocAsCode.YamlSerialization.YamlDeserializer; public class OverwriteDocumentReader { public static FileModel Read(FileAndType file) { if (file == null) { throw new ArgumentNullException(nameof(file)); } if (file.Type != DocumentType.Overwrite) { throw new NotSupportedException(file.Type.ToString()); } return new FileModel(file, null, serializer: new BinaryFormatter()); } /// <summary> /// TODO: use Attributes to automatically markup and handle uid inside the model instead of pass in the itemBuilder action /// </summary> /// <typeparam name="T"></typeparam> /// <param name="model"></param> /// <param name="itemBuilder"></param> /// <returns></returns> public static IEnumerable<T> Transform<T>(FileModel model, string uid, Func<T, T> itemBuilder) where T : class, IOverwriteDocumentViewModel { if (model == null) { throw new ArgumentNullException(nameof(model)); } var overwrites = ((List<OverwriteDocumentModel>)model.Content).Where(s => s.Uid == uid); return overwrites.Select(s => { try { var item = s.ConvertTo<T>(); return ResolveContent(item, itemBuilder); } catch (YamlException ye) { var message = $"Unable to deserialize YAML header from \"{s.Documentation.Path}\" Line {s.Documentation.StartLine} to TYPE {typeof(T).Name}: {ye.Message}"; Logger.LogError(message, code: ErrorCodes.Overwrite.InvalidOverwriteDocument); throw new DocumentException(message, ye); } }); } private static T ResolveContent<T>(T item, Func<T, T> itemBuilder) where T : IOverwriteDocumentViewModel { if (itemBuilder != null) { item = itemBuilder(item); } using (var sw = new StringWriter()) { YamlUtility.Serialize(sw, item); using var sr = new StringReader(sw.ToString()); var serializer = new YamlDeserializer(ignoreUnmatched: true); var placeholderValueDeserializer = new PlaceholderValueDeserializer(serializer.ValueDeserializer, item.Conceptual); item = serializer.Deserialize<T>(sr, placeholderValueDeserializer); if (placeholderValueDeserializer.ContainPlaceholder) { item.Conceptual = null; } } return item; } private sealed class PlaceholderValueDeserializer : IValueDeserializer { private readonly IValueDeserializer _innerDeserializer; private readonly string _replacer; public bool ContainPlaceholder { get; private set; } public PlaceholderValueDeserializer(IValueDeserializer innerDeserializer, string replacer) { _innerDeserializer = innerDeserializer ?? throw new ArgumentNullException(nameof(innerDeserializer)); _replacer = replacer; } /// <summary> /// AWARENESS: not thread safe /// </summary> /// <param name="reader"></param> /// <param name="expectedType"></param> /// <param name="state"></param> /// <param name="nestedObjectDeserializer"></param> /// <returns></returns> public object DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer) { object value = _innerDeserializer.DeserializeValue(parser, expectedType, state, nestedObjectDeserializer); if (value is string str && str.Trim() == Constants.ContentPlaceholder) { ContainPlaceholder = true; return _replacer; } return value; } } } }
39.276923
176
0.568939
[ "MIT" ]
Algorithman/docfx
src/Microsoft.DocAsCode.Build.Common/Reference/OverwriteDocumentReader.cs
4,979
C#
using System.Collections.Generic; using System.Threading.Tasks; using WebWallet.ViewModels.Goal; namespace WebWallet.Services.GoalServices { public interface IGoalService { Task<bool> Create(GoalVM goalVM, string username); Task<bool> Update(GoalVM goalVM); Task<bool> Delete(string goalId); Task<GoalVM> GetById(string goalId); Task<IEnumerable<GoalVM>> GetAll(string username); } }
23.157895
58
0.702273
[ "MIT" ]
VangelHristov/WebWallet
WebWallet.Services/GoalServices/IGoalService.cs
440
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace QuestLike { public class CollectionManager: IHaveCollections { private List<ICollection> collections = new List<ICollection>(); private GameObject owner; public CollectionManager(GameObject owner) { this.owner = owner; } public CollectionManager() { } public GameObject Owner { get { return owner; } } public void AddCollection<T>() where T : Collectable { if (HasCollection<T>()) return; var collection = new Collection<T> { owner = owner }; collections.Add(collection); } public Collection<T> GetCollection<T>() where T : Collectable { foreach (var i in collections) { if (i is Collection<T>) return i as Collection<T>; } return null; } public bool HasCollection<T>() where T : Collectable { foreach (var i in collections) { if (i is Collection<T>) return true; } return false; } public ICollection[] GetAllCollections() { return collections.ToArray(); } } }
21.521127
72
0.498037
[ "MIT" ]
Liam-Harrison/QuestLike
QuestLike/Game/Collection System/CollectionManager.cs
1,530
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; namespace Daliboris.Slovniky.Svoboda { public class Heslar : Slovniky.Heslar { public void HeslarXml(string strVstupniSoubor, string strVystupniSoubor) { Dictionary<string, ZpracovatTagProHeslarXml> gdZpracovaniTagu = new Dictionary<string, ZpracovatTagProHeslarXml>(); gdZpracovaniTagu.Add("hwo", ZpracovatTagXml); //Daliboris.Slovniky.Heslar.HeslarXml(strVstupniSoubor, strVystupniSoubor, gdZpracovaniTagu); Daliboris.Slovniky.Heslar.HeslarXml(strVstupniSoubor, strVystupniSoubor, null); } internal static void ZpracovatTagXml(XmlReader xrVstup, XmlWriter xwVystup, PismenoInfo piPismeno, HeslovaStatInfo hsiHeslovaStat, HesloInfo hiHeslo) { string strNazevTagu = xrVstup.Name; if (xrVstup.NodeType == XmlNodeType.Element && strNazevTagu == "hwo") { if (hiHeslo == null) hiHeslo = new HesloInfo(); hiHeslo.ZpracujHesloveSlovo(xrVstup.ReadString(), null); xwVystup.WriteElementString("hw", hiHeslo.HesloveSlovo); } else if (xrVstup.NodeType == XmlNodeType.EndElement && strNazevTagu == "hwo") { } } } }
36.625
118
0.760239
[ "BSD-3-Clause" ]
RIDICS/ITJakub
UJCSystem/ITJakub.Xml.Conversion/Daliboris.Texty.Export.Slovniky.Svoboda/Heslar.cs
1,174
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using GeoAPI.Geometries; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using NetTopologySuite.IO; namespace Microsoft.EntityFrameworkCore.Sqlite.Storage.ValueConversion.Internal { /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public class GeometryValueConverter<TGeometry> : ValueConverter<TGeometry, byte[]> where TGeometry : IGeometry { /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public GeometryValueConverter(GaiaGeoReader reader, GaiaGeoWriter writer) : base( g => writer.Write(g), b => (TGeometry)reader.Read(b)) { } } }
40.896552
111
0.674536
[ "Apache-2.0" ]
Alecu100/EntityFrameworkCore
src/EFCore.Sqlite.NTS/Storage/ValueConversion/Internal/GeometryValueConverter.cs
1,188
C#
using ResultFunctional.Models.Enums; using ResultFunctional.Models.Interfaces.Errors.Base; namespace ResultFunctional.Models.Interfaces.Errors.DatabaseErrors { /// <summary> /// Ошибка таблицы базы данных /// </summary> public interface IDatabaseAccessErrorResult : IDatabaseErrorResult { } }
28.545455
70
0.757962
[ "MIT" ]
rubilnik4/ResultFunctional
ResultFunctional/Models/Interfaces/Errors/DatabaseErrors/IDatabaseAccessErrorResult.cs
339
C#
using App.Model.Base; using System.ComponentModel.DataAnnotations.Schema; namespace App.Model { [Table("Vacation.Availability")] public class VacationAvailability : EEntityBase { } }
20.777778
52
0.786096
[ "MIT" ]
zagorec92/VacationCalendar
API/App.Domain/VacationAvailability.cs
189
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls.Primitives; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using PWPlanner.TileTypes; namespace PWPlanner { public partial class MainWindow { //Logic is similar to search. private void PreviousTiles_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (isRendered && PreviousTiles.SelectedItem != null) { object selectedItem = PreviousTiles.SelectedItem; ComboBoxItem selectedPrevTile = PreviousTiles.ItemContainerGenerator.ContainerFromItem(selectedItem) as ComboBoxItem; PreviousTile entry = selectedPrevTile.Content as PreviousTile; TileCanvas.Children.Remove(selectBorder); SelectTile(entry.Name); //Index is changed in SelectTile. BitmapImage source = selectableTiles[index].Image.Source as BitmapImage; TileHover.Content = entry.Name; LabelImg.Source = source; FirstSelected = true; } } private void AddToPreviousTilesSelected(Tile tile) { foreach (var previous in PreviousTiles.Items) { var prev = previous as PreviousTile; //Check if the tile placed is different, so we don't add duplicates if (prev.Name == _selectedTile.TileName) { return; } } PreviousTile se = new PreviousTile(); se.Name = tile.TileName; se.Source = tile.Image.Source as BitmapImage; PreviousTiles.Items.Add(se); } public class PreviousTile { public string Name { get; set; } public BitmapSource Source { get; set; } } } }
30.397059
133
0.605225
[ "MIT" ]
ColdUnwanted/PWPlanner
PWPlanner/Core/TileHistory.cs
2,069
C#
namespace Buildings.Domain.Exceptions { public class BuildingTypeNotSetInPrefabException : BuildingException { public BuildingTypeNotSetInPrefabException(string message = null) : base(message) {} } }
31.428571
92
0.754545
[ "MIT" ]
ananttheant/dynamic-walls-demo
Assets/Scripts/Buildings/Domain/Exceptions/BuildingTypeNotSetInPrefabException.cs
222
C#
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using System.Linq; using System.Text; using Dexter.Analyzer.Tests.Helpers; namespace Dexter.Analyzer.Tests.Helpers { /// <summary> /// Superclass of all Unit Tests for DiagnosticAnalyzers /// </summary> public abstract partial class DiagnosticVerifier { #region To be implemented by Test classes /// <summary> /// Get the CSharp analyzer being tested - to be implemented in non-abstract class /// </summary> protected virtual DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return null; } /// <summary> /// Get the Visual Basic analyzer being tested (C#) - to be implemented in non-abstract class /// </summary> protected virtual DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return null; } #endregion #region Verifier wrappers /// <summary> /// Called to test a C# DiagnosticAnalyzer when applied on the single inputted string as a source /// Note: input a DiagnosticResult for each Diagnostic expected /// </summary> /// <param name="source">A class in the form of a string to run the analyzer on</param> /// <param name="expected"> DiagnosticResults that should appear after the analyzer is run on the source</param> protected void VerifyCSharpDiagnostic(string source, params DiagnosticResult[] expected) { VerifyDiagnostics(new[] { source }, LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer(), expected); } /// <summary> /// Called to test a VB DiagnosticAnalyzer when applied on the single inputted string as a source /// Note: input a DiagnosticResult for each Diagnostic expected /// </summary> /// <param name="source">A class in the form of a string to run the analyzer on</param> /// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the source</param> protected void VerifyBasicDiagnostic(string source, params DiagnosticResult[] expected) { VerifyDiagnostics(new[] { source }, LanguageNames.VisualBasic, GetBasicDiagnosticAnalyzer(), expected); } /// <summary> /// Called to test a C# DiagnosticAnalyzer when applied on the inputted strings as a source /// Note: input a DiagnosticResult for each Diagnostic expected /// </summary> /// <param name="sources">An array of strings to create source documents from to run the analyzers on</param> /// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the sources</param> protected void VerifyCSharpDiagnostic(string[] sources, params DiagnosticResult[] expected) { VerifyDiagnostics(sources, LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer(), expected); } /// <summary> /// Called to test a VB DiagnosticAnalyzer when applied on the inputted strings as a source /// Note: input a DiagnosticResult for each Diagnostic expected /// </summary> /// <param name="sources">An array of strings to create source documents from to run the analyzers on</param> /// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the sources</param> protected void VerifyBasicDiagnostic(string[] sources, params DiagnosticResult[] expected) { VerifyDiagnostics(sources, LanguageNames.VisualBasic, GetBasicDiagnosticAnalyzer(), expected); } /// <summary> /// General method that gets a collection of actual diagnostics found in the source after the analyzer is run, /// then verifies each of them. /// </summary> /// <param name="sources">An array of strings to create source documents from to run the analyzers on</param> /// <param name="language">The language of the classes represented by the source strings</param> /// <param name="analyzer">The analyzer to be run on the source code</param> /// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the sources</param> private void VerifyDiagnostics(string[] sources, string language, DiagnosticAnalyzer analyzer, params DiagnosticResult[] expected) { var diagnostics = GetSortedDiagnostics(sources, language, analyzer); VerifyDiagnosticResults(diagnostics, analyzer, expected); } #endregion #region Actual comparisons and verifications /// <summary> /// Checks each of the actual Diagnostics found and compares them with the corresponding DiagnosticResult in the array of expected results. /// Diagnostics are considered equal only if the DiagnosticResultLocation, Id, Severity, and Message of the DiagnosticResult match the actual diagnostic. /// </summary> /// <param name="actualResults">The Diagnostics found by the compiler after running the analyzer on the source code</param> /// <param name="analyzer">The analyzer that was being run on the sources</param> /// <param name="expectedResults">Diagnostic Results that should have appeared in the code</param> private static void VerifyDiagnosticResults(IEnumerable<Diagnostic> actualResults, DiagnosticAnalyzer analyzer, params DiagnosticResult[] expectedResults) { int expectedCount = expectedResults.Count(); int actualCount = actualResults.Count(); if (expectedCount != actualCount) { string diagnosticsOutput = actualResults.Any() ? FormatDiagnostics(analyzer, actualResults.ToArray()) : " NONE."; Assert.IsTrue(false, string.Format("Mismatch between number of diagnostics returned, expected \"{0}\" actual \"{1}\"\r\n\r\nDiagnostics:\r\n{2}\r\n", expectedCount, actualCount, diagnosticsOutput)); } for (int i = 0; i < expectedResults.Length; i++) { var actual = actualResults.ElementAt(i); var expected = expectedResults[i]; if (expected.Line == -1 && expected.Column == -1) { if (actual.Location != Location.None) { Assert.IsTrue(false, string.Format("Expected:\nA project diagnostic with No location\nActual:\n{0}", FormatDiagnostics(analyzer, actual))); } } else { VerifyDiagnosticLocation(analyzer, actual, actual.Location, expected.Locations.First()); var additionalLocations = actual.AdditionalLocations.ToArray(); if (additionalLocations.Length != expected.Locations.Length - 1) { Assert.IsTrue(false, string.Format("Expected {0} additional locations but got {1} for Diagnostic:\r\n {2}\r\n", expected.Locations.Length - 1, additionalLocations.Length, FormatDiagnostics(analyzer, actual))); } for (int j = 0; j < additionalLocations.Length; ++j) { VerifyDiagnosticLocation(analyzer, actual, additionalLocations[j], expected.Locations[j + 1]); } } if (actual.Id != expected.Id) { Assert.IsTrue(false, string.Format("Expected diagnostic id to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Id, actual.Id, FormatDiagnostics(analyzer, actual))); } if (actual.Severity != expected.Severity) { Assert.IsTrue(false, string.Format("Expected diagnostic severity to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Severity, actual.Severity, FormatDiagnostics(analyzer, actual))); } if (actual.GetMessage() != expected.Message) { Assert.IsTrue(false, string.Format("Expected diagnostic message to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Message, actual.GetMessage(), FormatDiagnostics(analyzer, actual))); } } } /// <summary> /// Helper method to VerifyDiagnosticResult that checks the location of a diagnostic and compares it with the location in the expected DiagnosticResult. /// </summary> /// <param name="analyzer">The analyzer that was being run on the sources</param> /// <param name="diagnostic">The diagnostic that was found in the code</param> /// <param name="actual">The Location of the Diagnostic found in the code</param> /// <param name="expected">The DiagnosticResultLocation that should have been found</param> private static void VerifyDiagnosticLocation(DiagnosticAnalyzer analyzer, Diagnostic diagnostic, Location actual, DiagnosticResultLocation expected) { var actualSpan = actual.GetLineSpan(); Assert.IsTrue(actualSpan.Path == expected.Path || (actualSpan.Path != null && actualSpan.Path.Contains("Test0.") && expected.Path.Contains("Test.")), string.Format("Expected diagnostic to be in file \"{0}\" was actually in file \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Path, actualSpan.Path, FormatDiagnostics(analyzer, diagnostic))); var actualLinePosition = actualSpan.StartLinePosition; // Only check line position if there is an actual line in the real diagnostic if (actualLinePosition.Line > 0) { if (actualLinePosition.Line + 1 != expected.Line) { Assert.IsTrue(false, string.Format("Expected diagnostic to be on line \"{0}\" was actually on line \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Line, actualLinePosition.Line + 1, FormatDiagnostics(analyzer, diagnostic))); } } // Only check column position if there is an actual column position in the real diagnostic if (actualLinePosition.Character > 0) { if (actualLinePosition.Character + 1 != expected.Column) { Assert.IsTrue(false, string.Format("Expected diagnostic to start at column \"{0}\" was actually at column \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Column, actualLinePosition.Character + 1, FormatDiagnostics(analyzer, diagnostic))); } } } #endregion #region Formatting Diagnostics /// <summary> /// Helper method to format a Diagnostic into an easily readable string /// </summary> /// <param name="analyzer">The analyzer that this verifier tests</param> /// <param name="diagnostics">The Diagnostics to be formatted</param> /// <returns>The Diagnostics formatted as a string</returns> private static string FormatDiagnostics(DiagnosticAnalyzer analyzer, params Diagnostic[] diagnostics) { var builder = new StringBuilder(); for (int i = 0; i < diagnostics.Length; ++i) { builder.AppendLine("// " + diagnostics[i].ToString()); var analyzerType = analyzer.GetType(); var rules = analyzer.SupportedDiagnostics; foreach (var rule in rules) { if (rule != null && rule.Id == diagnostics[i].Id) { var location = diagnostics[i].Location; if (location == Location.None) { builder.AppendFormat("GetGlobalResult({0}.{1})", analyzerType.Name, rule.Id); } else { Assert.IsTrue(location.IsInSource, $"Test base does not currently handle diagnostics in metadata locations. Diagnostic in metadata: {diagnostics[i]}\r\n"); string resultMethodName = diagnostics[i].Location.SourceTree.FilePath.EndsWith(".cs") ? "GetCSharpResultAt" : "GetBasicResultAt"; var linePosition = diagnostics[i].Location.GetLineSpan().StartLinePosition; builder.AppendFormat("{0}({1}, {2}, {3}.{4})", resultMethodName, linePosition.Line + 1, linePosition.Character + 1, analyzerType.Name, rule.Id); } if (i != diagnostics.Length - 1) { builder.Append(','); } builder.AppendLine(); break; } } } return builder.ToString(); } #endregion } }
50.970588
197
0.579919
[ "BSD-2-Clause" ]
SRPOL/Dexter
project/dexter-vs/Dexter/Analyzer/Tests/Helpers/DiagnosticVerifier.cs
13,866
C#
namespace KitchenGeeks { partial class frmPlayerResults { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmPlayerResults)); this.label1 = new System.Windows.Forms.Label(); this.lblName = new System.Windows.Forms.Label(); this.lstEvents = new System.Windows.Forms.ListView(); this.colDate = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.colName = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.colType = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.colLocation = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.colTP = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.colVP = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.colDiff = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.lstSelected = new System.Windows.Forms.ListView(); this.colRoundNum = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.colRoundTP = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.colRoundVP = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.colRoundDiff = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.colRoundOpponent = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.colOpponentTP = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.colOpponentVP = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.colOpponentDiff = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.label4 = new System.Windows.Forms.Label(); this.lblRecord = new System.Windows.Forms.Label(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Times New Roman", 20.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(12, 9); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(145, 31); this.label1.TabIndex = 0; this.label1.Text = "Results for: "; // // lblName // this.lblName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lblName.Font = new System.Drawing.Font("Times New Roman", 20.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblName.Location = new System.Drawing.Point(151, 9); this.lblName.Name = "lblName"; this.lblName.Size = new System.Drawing.Size(386, 31); this.lblName.TabIndex = 1; // // lstEvents // this.lstEvents.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lstEvents.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.colDate, this.colName, this.colType, this.colLocation, this.colTP, this.colVP, this.colDiff}); this.lstEvents.FullRowSelect = true; this.lstEvents.GridLines = true; this.lstEvents.HideSelection = false; this.lstEvents.Location = new System.Drawing.Point(12, 136); this.lstEvents.MultiSelect = false; this.lstEvents.Name = "lstEvents"; this.lstEvents.Size = new System.Drawing.Size(525, 181); this.lstEvents.TabIndex = 2; this.lstEvents.UseCompatibleStateImageBehavior = false; this.lstEvents.View = System.Windows.Forms.View.Details; this.lstEvents.SelectedIndexChanged += new System.EventHandler(this.lstTournaments_SelectedIndexChanged); // // colDate // this.colDate.Text = "Date"; this.colDate.Width = 65; // // colName // this.colName.Text = "Name"; this.colName.Width = 135; // // colType // this.colType.Text = "Type"; this.colType.Width = 66; // // colLocation // this.colLocation.Text = "Location"; this.colLocation.Width = 112; // // colTP // this.colTP.Text = "TPs"; this.colTP.Width = 40; // // colVP // this.colVP.Text = "VPs"; this.colVP.Width = 40; // // colDiff // this.colDiff.Text = "Diff"; this.colDiff.Width = 40; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Verdana", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(12, 110); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(148, 23); this.label2.TabIndex = 3; this.label2.Text = "Event Results:"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Verdana", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(11, 320); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(160, 23); this.label3.TabIndex = 4; this.label3.Text = "Selected Event:"; // // lstSelected // this.lstSelected.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lstSelected.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.colRoundNum, this.colRoundTP, this.colRoundVP, this.colRoundDiff, this.colRoundOpponent, this.colOpponentTP, this.colOpponentVP, this.colOpponentDiff}); this.lstSelected.GridLines = true; this.lstSelected.Location = new System.Drawing.Point(12, 346); this.lstSelected.MultiSelect = false; this.lstSelected.Name = "lstSelected"; this.lstSelected.Scrollable = false; this.lstSelected.Size = new System.Drawing.Size(525, 116); this.lstSelected.TabIndex = 5; this.lstSelected.UseCompatibleStateImageBehavior = false; this.lstSelected.View = System.Windows.Forms.View.Details; // // colRoundNum // this.colRoundNum.Text = "Round"; this.colRoundNum.Width = 45; // // colRoundTP // this.colRoundTP.Text = "TPs"; this.colRoundTP.Width = 40; // // colRoundVP // this.colRoundVP.Text = "VPs"; this.colRoundVP.Width = 40; // // colRoundDiff // this.colRoundDiff.Text = "Diff"; this.colRoundDiff.Width = 40; // // colRoundOpponent // this.colRoundOpponent.Text = "Opponent"; this.colRoundOpponent.Width = 235; // // colOpponentTP // this.colOpponentTP.Text = "TPs"; this.colOpponentTP.Width = 40; // // colOpponentVP // this.colOpponentVP.Text = "VPs"; this.colOpponentVP.Width = 40; // // colOpponentDiff // this.colOpponentDiff.Text = "Diff"; this.colOpponentDiff.Width = 40; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Verdana", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.Location = new System.Drawing.Point(12, 61); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(134, 18); this.label4.TabIndex = 6; this.label4.Text = "Overall Record:"; // // lblRecord // this.lblRecord.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lblRecord.Font = new System.Drawing.Font("Verdana", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblRecord.Location = new System.Drawing.Point(156, 61); this.lblRecord.Name = "lblRecord"; this.lblRecord.Size = new System.Drawing.Size(381, 49); this.lblRecord.TabIndex = 7; // // frmPlayerResults // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(549, 473); this.Controls.Add(this.lblRecord); this.Controls.Add(this.label4); this.Controls.Add(this.lstSelected); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.lstEvents); this.Controls.Add(this.lblName); this.Controls.Add(this.label1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MinimumSize = new System.Drawing.Size(538, 495); this.Name = "frmPlayerResults"; this.Text = "Player\'s Results"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label lblName; private System.Windows.Forms.ListView lstEvents; private System.Windows.Forms.ColumnHeader colDate; private System.Windows.Forms.ColumnHeader colName; private System.Windows.Forms.ColumnHeader colLocation; private System.Windows.Forms.ColumnHeader colTP; private System.Windows.Forms.ColumnHeader colVP; private System.Windows.Forms.ColumnHeader colDiff; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.ListView lstSelected; private System.Windows.Forms.ColumnHeader colRoundNum; private System.Windows.Forms.ColumnHeader colRoundTP; private System.Windows.Forms.ColumnHeader colRoundVP; private System.Windows.Forms.ColumnHeader colRoundDiff; private System.Windows.Forms.ColumnHeader colRoundOpponent; private System.Windows.Forms.ColumnHeader colOpponentTP; private System.Windows.Forms.ColumnHeader colOpponentVP; private System.Windows.Forms.ColumnHeader colOpponentDiff; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label lblRecord; private System.Windows.Forms.ColumnHeader colType; } }
46.930556
165
0.58501
[ "Apache-2.0" ]
DeusInnomen/LuciusIncidentLogbook
LuciusIncidentLogbook/frmPlayerResults.Designer.cs
13,518
C#
namespace ShowCastApi.Settings { public class FunctionSettings { public string CosmosDbAccountEndpoint { get; set; } public string CosmosDbAccountKey { get; set; } } }
21.888889
59
0.670051
[ "MIT" ]
evilpilaf/TvMaze
src/Hosts/ShowCastApi/Settings/FunctionSettings.cs
199
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the kinesisanalyticsv2-2018-05-23.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.KinesisAnalyticsV2.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.KinesisAnalyticsV2.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for AddApplicationOutput operation /// </summary> public class AddApplicationOutputResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { AddApplicationOutputResponse response = new AddApplicationOutputResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("ApplicationARN", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.ApplicationARN = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("ApplicationVersionId", targetDepth)) { var unmarshaller = LongUnmarshaller.Instance; response.ApplicationVersionId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("OutputDescriptions", targetDepth)) { var unmarshaller = new ListUnmarshaller<OutputDescription, OutputDescriptionUnmarshaller>(OutputDescriptionUnmarshaller.Instance); response.OutputDescriptions = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); if (errorResponse.Code != null && errorResponse.Code.Equals("ConcurrentModificationException")) { return new ConcurrentModificationException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidArgumentException")) { return new InvalidArgumentException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidRequestException")) { return new InvalidRequestException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceInUseException")) { return new ResourceInUseException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException")) { return new ResourceNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } return new AmazonKinesisAnalyticsV2Exception(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static AddApplicationOutputResponseUnmarshaller _instance = new AddApplicationOutputResponseUnmarshaller(); internal static AddApplicationOutputResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static AddApplicationOutputResponseUnmarshaller Instance { get { return _instance; } } } }
43.860465
175
0.65836
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/KinesisAnalyticsV2/Generated/Model/Internal/MarshallTransformations/AddApplicationOutputResponseUnmarshaller.cs
5,658
C#
using System.Collections.Generic; using Core.Entities.Products; namespace API.Dtos.Product { public class ProductToReturnDto { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public decimal Price { get; set; } public string PictureUrl { get; set; } public string ProductType { get; set; } public string ProductCategory { get; set; } public int Quantity { get; set; } public int WaitingCustomersCount { get; set; } public bool IsInStock { get; set; } public int ReviewsAverage { get; set; } public int ReviewsNumber { get; set; } public TechnicalSheetDto TechnicalSheet { get; set; } public IReadOnlyList<UserForWaitingDto> WaitingCustomers { get; set; } } }
36.347826
78
0.633971
[ "MIT" ]
ZakariaDjebbes/DzTechly
API/Dtos/Product/ProductToReturnDto.cs
838
C#
using System; namespace XP.SDK.XPLM { /// <summary> /// <para> /// XPLM Texture IDs name well-known textures in the sim for you to use. This /// allows you to recycle textures from X-Plane, saving VRAM. /// </para> /// <para> /// *Warning*: do not use these enums. The only remaining use they have is to /// access the legacy compatibility v10 UI texture; if you need this, get it /// via the Widgets library. /// </para> /// </summary> public enum TextureID { XplmTexGeneralInterface = 0 } }
26.809524
82
0.603908
[ "MIT" ]
fedarovich/xplane-dotnet
src/XP.SDK/XPLM/TextureID.Generated.cs
563
C#
// Copyright (c) Gregg Miskelly. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; namespace BaseballParser.Retrosheet { public enum EventLogRecordKind { /// <summary> /// Provides the game identifier /// </summary> Id, /// <summary> /// Version of the event log format /// </summary> /// Version, /// <summary> /// Game information record. For example: what was the home team /// </summary> Info, /// <summary> /// Starting lineup record /// </summary> [EnumSerializedName("start")] StartingLineup, /// <summary> /// Play record /// </summary> Play, /// <summary> /// Player substitution record /// </summary> [EnumSerializedName("sub")] Substitution, /// <summary> /// Commentary record /// </summary> [EnumSerializedName("com")] Commentary, /// <summary> /// Data record. Currently this is just used to indicate the earned runs for each pitcher /// </summary> Data, /// <summary> /// Batter adjustment record. Used when a batter hits from the right/left side when it would normally be expected /// for him to hit from the other side. /// </summary> [EnumSerializedName("badj")] BatterAdjustment, /// <summary> /// Pitcher adjustment record. Used when a pitcher throws from the right/left side when it would normally be expected /// for him to throw from the other side. /// </summary> [EnumSerializedName("padj")] PitcherAdjustment, /// <summary> /// Record to indicate that the team batted out of order /// </summary> [EnumSerializedName("ladj")] BattingOrderAdjustment } }
26.189873
125
0.559207
[ "MIT" ]
gregg-miskelly/baseball
src/BaseballParser/Retrosheet/EventLogRecordKind.cs
2,071
C#
using System; using System.Collections.Generic; using System.Text; using ProtoBuf; using UnityEngine; namespace NetWorkingCSharp { public enum EType : Int32 { Error = 0, WELCOME, MSG, UPDATENAME, BEGINPLAY, PLAYERREADY, DISCONNECT, PLAYERACTION } [ProtoContract] public class Header { [ProtoMember(1)] public ServerTCP.ClientData clientData; [ProtoMember(2)] public EType TypeData; [ProtoMember(3)] public int HeaderTime; public object Data; public static void SendHeader(System.Net.Sockets.NetworkStream stream, Header header) { header.HeaderTime = System.DateTime.Now.Millisecond; Serializer.SerializeWithLengthPrefix<Header>(stream, header, PrefixStyle.Fixed32); switch (header.TypeData) { case EType.Error: break; case EType.WELCOME: Serializer.SerializeWithLengthPrefix<ServerSend.WelcomeToServer>(stream, (ServerSend.WelcomeToServer)header.Data, PrefixStyle.Fixed32); break; case EType.MSG: Serializer.SerializeWithLengthPrefix<string>(stream, (string)header.Data, PrefixStyle.Fixed32); break; case EType.UPDATENAME: Serializer.SerializeWithLengthPrefix<string>(stream, (string)header.Data, PrefixStyle.Fixed32); break; case EType.BEGINPLAY: //Serializer. GameDataArray arr = new GameDataArray(); arr.gameDatas = (UnoNetworkingGameData.GameData[])header.Data; Serializer.SerializeWithLengthPrefix(stream, arr, PrefixStyle.Fixed32); //Debug.LogError("Server header begin Play"); break; case EType.PLAYERACTION: //Serializer.SerializeWithLengthPrefix(stream, (UnoNetworkingGameData.GameData)header.Data, PrefixStyle.Fixed32); ((HeaderGameData)header.Data).SendData(stream); break; } } public Header(object data, EType type, ServerTCP.ClientData id) { Data = data; TypeData = type; clientData = id; } // default constructor for the serialisation public Header() { } } }
32.924051
156
0.549404
[ "MIT" ]
natheu/UnoNetWorking
UnoNetWorkingJudicaelNathan/Assets/Script/Networking/Header.cs
2,603
C#