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
// *** 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.WafV2.Inputs { public sealed class RuleGroupRuleStatementOrStatementStatementXssMatchStatementFieldToMatchArgs : Pulumi.ResourceArgs { /// <summary> /// Inspect all query arguments. /// </summary> [Input("allQueryArguments")] public Input<Inputs.RuleGroupRuleStatementOrStatementStatementXssMatchStatementFieldToMatchAllQueryArgumentsArgs>? AllQueryArguments { get; set; } /// <summary> /// Inspect the request body, which immediately follows the request headers. /// </summary> [Input("body")] public Input<Inputs.RuleGroupRuleStatementOrStatementStatementXssMatchStatementFieldToMatchBodyArgs>? Body { get; set; } /// <summary> /// Inspect the HTTP method. The method indicates the type of operation that the request is asking the origin to perform. /// </summary> [Input("method")] public Input<Inputs.RuleGroupRuleStatementOrStatementStatementXssMatchStatementFieldToMatchMethodArgs>? Method { get; set; } /// <summary> /// Inspect the query string. This is the part of a URL that appears after a `?` character, if any. /// </summary> [Input("queryString")] public Input<Inputs.RuleGroupRuleStatementOrStatementStatementXssMatchStatementFieldToMatchQueryStringArgs>? QueryString { get; set; } /// <summary> /// Inspect a single header. See Single Header below for details. /// </summary> [Input("singleHeader")] public Input<Inputs.RuleGroupRuleStatementOrStatementStatementXssMatchStatementFieldToMatchSingleHeaderArgs>? SingleHeader { get; set; } /// <summary> /// Inspect a single query argument. See Single Query Argument below for details. /// </summary> [Input("singleQueryArgument")] public Input<Inputs.RuleGroupRuleStatementOrStatementStatementXssMatchStatementFieldToMatchSingleQueryArgumentArgs>? SingleQueryArgument { get; set; } /// <summary> /// Inspect the request URI path. This is the part of a web request that identifies a resource, for example, `/images/daily-ad.jpg`. /// </summary> [Input("uriPath")] public Input<Inputs.RuleGroupRuleStatementOrStatementStatementXssMatchStatementFieldToMatchUriPathArgs>? UriPath { get; set; } public RuleGroupRuleStatementOrStatementStatementXssMatchStatementFieldToMatchArgs() { } } }
45.274194
158
0.701461
[ "ECL-2.0", "Apache-2.0" ]
Otanikotani/pulumi-aws
sdk/dotnet/WafV2/Inputs/RuleGroupRuleStatementOrStatementStatementXssMatchStatementFieldToMatchArgs.cs
2,807
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.InlineDeclaration; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseImplicitType; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.InlineDeclaration { public partial class CSharpInlineDeclarationTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, CodeFixProvider>( new CSharpInlineDeclarationDiagnosticAnalyzer(), new CSharpInlineDeclarationCodeFixProvider()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariable1() { await TestAsync( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i)) { } } }", @"class C { void M() { if (int.TryParse(v, out int i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineInNestedCall() { await TestAsync( @"class C { void M() { [|int|] i; if (Foo(int.TryParse(v, out i))) { } } }", @"class C { void M() { if (Foo(int.TryParse(v, out int i))) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariableWithConstructor1() { await TestAsync( @"class C { void M() { [|int|] i; if (new C1(v, out i)) { } } }", @"class C { void M() { if (new C1(v, out int i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariableMissingWithIndexer1() { await TestMissingAsync( @"class C { void M() { [|int|] i; if (this[out i]) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariableIntoFirstOut1() { await TestAsync( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i, out i)) { } } }", @"class C { void M() { if (int.TryParse(v, out int i, out i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariableIntoFirstOut2() { await TestAsync( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i)) { } if (int.TryParse(v, out i)) { } } }", @"class C { void M() { if (int.TryParse(v, out int i)) { } if (int.TryParse(v, out i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInCSharp6() { await TestMissingAsync( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i)) { } } }", parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariablePreferVar1() { await TestAsync( @"class C { void M(string v) { [|int|] i; if (int.TryParse(v, out i)) { } } }", @"class C { void M(string v) { if (int.TryParse(v, out var i)) { } } }", options: new UseImplicitTypeTests().ImplicitTypeEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariablePreferVarExceptForPredefinedTypes1() { await TestAsync( @"class C { void M(string v) { [|int|] i; if (int.TryParse(v, out i)) { } } }", @"class C { void M(string v) { if (int.TryParse(v, out int i)) { } } }", options: new UseImplicitTypeTests().ImplicitTypeButKeepIntrinsics()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestAvailableWhenWrittenAfter1() { await TestAsync( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i)) { } i = 0; } }", @"class C { void M() { if (int.TryParse(v, out int i)) { } i = 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingWhenWrittenBetween1() { await TestMissingAsync( @"class C { void M() { [|int|] i; i = 0; if (int.TryParse(v, out i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingWhenReadBetween1() { await TestMissingAsync( @"class C { void M() { [|int|] i = 0; M1(i); if (int.TryParse(v, out i)) { } } void M1(int i) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingWithComplexInitializer() { await TestMissingAsync( @"class C { void M() { [|int|] i = M1(); if (int.TryParse(v, out i)) { } } int M1() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestAvailableInOuterScopeIfNotWrittenOutside() { await TestMissingAsync( @"class C { void M() { [|int|] i = 0; { if (int.TryParse(v, out i)) { } i = 1; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingIfWrittenAfterInOuterScope() { await TestMissingAsync( @"class C { void M() { [|int|] i = 0; { if (int.TryParse(v, out i)) { } } i = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingIfWrittenBetweenInOuterScope() { await TestMissingAsync( @"class C { void M() { [|int|] i = 0; { i = 1; if (int.TryParse(v, out i)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInNonOut() { await TestMissingAsync( @"class C { void M() { [|int|] i; if (int.TryParse(v, i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInField() { await TestMissingAsync( @"class C { [|int|] i; void M() { if (int.TryParse(v, out this.i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInField2() { await TestMissingAsync( @"class C { [|int|] i; void M() { if (int.TryParse(v, out i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInNonLocalStatement() { await TestMissingAsync( @"class C { void M() { foreach ([|int|] i in e) { if (int.TryParse(v, out i)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInEmbeddedStatementWithWriteAfterwards() { await TestMissingAsync( @"class C { void M() { [|int|] i; while (true) if (int.TryParse(v, out i)) { } i = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInEmbeddedStatement() { await TestAsync( @"class C { void M() { [|int|] i; while (true) if (int.TryParse(v, out i)) { i = 1; } } }", @"class C { void M() { while (true) if (int.TryParse(v, out int i)) { i = 1; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestAvailableInNestedBlock() { await TestAsync( @"class C { void M() { [|int|] i; while (true) { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { while (true) { if (int.TryParse(v, out int i)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestOverloadResolutionDoNotUseVar1() { await TestAsync( @"class C { void M() { [|int|] i; if (M2(out i)) { } } void M2(out int i) { } void M2(out string s) { } }", @"class C { void M() { if (M2(out int i)) { } } void M2(out int i) { } void M2(out string s) { } }", options: new UseImplicitTypeTests().ImplicitTypeEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestOverloadResolutionDoNotUseVar2() { await TestAsync( @"class C { void M() { [|var|] i = 0; if (M2(out i)) { } } void M2(out int i) { } void M2(out string s) { } }", @"class C { void M() { if (M2(out int i)) { } } void M2(out int i) { } void M2(out string s) { } }", options: new UseImplicitTypeTests().ImplicitTypeEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestGenericInferenceDoNotUseVar3() { await TestAsync( @"class C { void M() { [|int|] i; if (M2(out i)) { } } void M2<T>(out T i) { } }", @"class C { void M() { if (M2(out int i)) { } } void M2<T>(out T i) { } }", options: new UseImplicitTypeTests().ImplicitTypeEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments1() { await TestAsync( @"class C { void M() { // prefix comment [|int|] i; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { { // prefix comment if (int.TryParse(v, out int i)) { } } } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments2() { await TestAsync( @"class C { void M() { [|int|] i; // suffix comment { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { { // suffix comment if (int.TryParse(v, out int i)) { } } } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments3() { await TestAsync( @"class C { void M() { // prefix comment [|int|] i; // suffix comment { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { { // prefix comment // suffix comment if (int.TryParse(v, out int i)) { } } } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments4() { await TestAsync( @"class C { void M() { int [|i|] /*suffix*/, j; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int j; { if (int.TryParse(v, out int i /*suffix*/)) { } } } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments5() { await TestAsync( @"class C { void M() { int /*prefix*/ [|i|], j; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int j; { if (int.TryParse(v, out int /*prefix*/ i)) { } } } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments6() { await TestAsync( @"class C { void M() { int /*prefix*/ [|i|] /*suffix*/, j; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int j; { if (int.TryParse(v, out int /*prefix*/ i /*suffix*/)) { } } } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments7() { await TestAsync( @"class C { void M() { int j, /*prefix*/ [|i|] /*suffix*/; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int j; { if (int.TryParse(v, out int /*prefix*/ i /*suffix*/)) { } } } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments8() { await TestAsync( @"class C { void M() { // prefix int j, [|i|]; // suffix { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { // prefix int j; // suffix { if (int.TryParse(v, out int i)) { } } } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments9() { await TestAsync( @"class C { void M() { int /*int comment*/ /*prefix*/ [|i|] /*suffix*/, j; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int /*int comment*/ j; { if (int.TryParse(v, out int /*prefix*/ i /*suffix*/)) { } } } }", compareTokens: false); } } }
18.304536
160
0.471327
[ "Apache-2.0" ]
hamish-milne/roslyn-OHDL
src/EditorFeatures/CSharpTest/InlineDeclaration/CSharpInlineDeclarationTests.cs
16,950
C#
namespace OmniXaml { using System; public interface IConverterContextFactory { ConverterValueContext CreateConverterContext(Type type, object value, BuildContext buildContext); } }
22.777778
105
0.746341
[ "MIT" ]
JPTIZ/OmniXAML
OmniXaml/IConverterContextFactory.cs
205
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; public class Spy { public string StealFieldInfo(string className, params string[] fieldsNames) { StringBuilder sb = new StringBuilder(); Type type = Type.GetType(className); var fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); Object classInstance = Activator.CreateInstance(type, new object[] { }); sb.AppendLine($"Class under investigation: {className}"); foreach (var field in fields.Where(f => fieldsNames.Contains(f.Name))) { sb.AppendLine($"{field.Name} = {field.GetValue(classInstance)}"); } string result = sb.ToString().TrimEnd(); return result; } public string AnalyzeAcessModifiers(string className) { StringBuilder sb = new StringBuilder(); var classType = Type.GetType(className); var fields = classType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static); var classPublicMethods = classType.GetMethods(BindingFlags.Instance | BindingFlags.Public); var classNonPublicMethods = classType.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic); foreach (var field in fields) { if (!field.IsPrivate) { sb.AppendLine($"{field.Name} must be private!"); } } foreach (var method in classNonPublicMethods.Where(m => m.Name.StartsWith("get"))) { sb.AppendLine($"{method.Name} have to be public!"); } foreach (var method in classPublicMethods.Where(m => m.Name.StartsWith("set"))) { sb.AppendLine($"{method.Name} have to be private!"); } string result = sb.ToString().TrimEnd(); return result; } public string RevealPrivateMethods(string className) { StringBuilder sb = new StringBuilder(); var classType = Type.GetType(className); var methods = classType.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance); sb.AppendLine($"All Private Methods of Class: {classType}"); sb.AppendLine($"Base Class: {classType.BaseType.Name}"); foreach (var method in methods) { sb.AppendLine(method.Name); } string result = sb.ToString().TrimEnd(); return result; } public string CollectGettersAndSetters(string className) { StringBuilder sb = new StringBuilder(); var classType = Type.GetType(className); var methods = classType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (var method in methods.Where(m => m.Name.StartsWith("get"))) { sb.AppendLine($"{method.Name} will return {method.ReturnType}"); } foreach (var method in methods.Where(m => m.Name.StartsWith("set"))) { sb.AppendLine($"{method.Name} will set field of {method.GetParameters().First().ParameterType}"); } string result = sb.ToString().TrimEnd(); return result; } }
29.963303
128
0.627679
[ "MIT" ]
TodorNikolov89/SoftwareUniversity
CSharp_OOP_Advanced/ReflectionAndAttributes_Lab/Stealer/Spy.cs
3,268
C#
using System; using Microsoft.Xna.Framework; using SpaceCore.Interface; using SpaceShared; using StardewValley; using StardewValley.Events; using StardewValley.Network; using SObject = StardewValley.Object; namespace SpaceCore.Events { public class SpaceEvents { /// <summary>This occurs before loading starts.</summary> /// Locations should be added here so that SaveData.loadDataToLocations picks them up public static event EventHandler OnBlankSave; /// <summary>When the shipping menu pops up, level up menus, ...</summary> public static event EventHandler<EventArgsShowNightEndMenus> ShowNightEndMenus; /// <summary>Lets you hook into Utillity.pickFarmEvent</summary> public static event EventHandler<EventArgsChooseNightlyFarmEvent> ChooseNightlyFarmEvent; /// <summary>When the player is done eating an item.</summary> /// Check what item using player.itemToEat public static event EventHandler OnItemEaten; /// <summary>When a tile "Action" is activated</summary> public static event EventHandler<EventArgsAction> ActionActivated; /// <summary>When a tile "TouchAction" is activated</summary> public static event EventHandler<EventArgsAction> TouchActionActivated; /// <summary>Server side, when a client joins</summary> public static event EventHandler<EventArgsServerGotClient> ServerGotClient; /// <summary>Right before a gift is given to someone. Sender is farmer.</summary> public static event EventHandler<EventArgsBeforeReceiveObject> BeforeGiftGiven; /// <summary>When a gift is given to someone. Sender is farmer.</summary> public static event EventHandler<EventArgsGiftGiven> AfterGiftGiven; /// B<summary>efore the player is about to warp. Can cancel warping or change the target location.</summary> public static event EventHandler<EventArgsBeforeWarp> BeforeWarp; /// <summary>When a bomb explodes</summary> public static event EventHandler<EventArgsBombExploded> BombExploded; /// <summary>When an event finishes. Use Game1.CurrentEvent to check which one.</summary> public static event EventHandler OnEventFinished; /// <summary>Event for adding wallet items to NewSkillsPage, before the controller-pickable logic needs to run</summary> public static event EventHandler AddWalletItems; internal static void InvokeOnBlankSave() { Log.Trace("Event: OnBlankSave"); if (SpaceEvents.OnBlankSave == null) return; Util.InvokeEvent("SpaceEvents.OnBlankSave", SpaceEvents.OnBlankSave.GetInvocationList(), null); } internal static void InvokeShowNightEndMenus(EventArgsShowNightEndMenus args) { Log.Trace("Event: ShowNightEndMenus"); if (SpaceEvents.ShowNightEndMenus == null) return; Util.InvokeEvent("SpaceEvents.ShowNightEndMenus", SpaceEvents.ShowNightEndMenus.GetInvocationList(), null, args); } internal static FarmEvent InvokeChooseNightlyFarmEvent(FarmEvent vanilla) { var args = new EventArgsChooseNightlyFarmEvent { NightEvent = vanilla }; Log.Trace("Event: ChooseNightlyFarmEvent"); if (SpaceEvents.ChooseNightlyFarmEvent == null) return args.NightEvent; Util.InvokeEvent("SpaceEvents.ChooseNightlyFarmEvent", SpaceEvents.ChooseNightlyFarmEvent.GetInvocationList(), null, args); return args.NightEvent; } internal static void InvokeOnItemEaten(Farmer farmer) { Log.Trace("Event: OnItemEaten"); if (SpaceEvents.OnItemEaten == null || !farmer.IsLocalPlayer) return; Util.InvokeEvent("SpaceEvents.OnItemEaten", SpaceEvents.OnItemEaten.GetInvocationList(), farmer); } internal static bool InvokeActionActivated(Farmer who, string action, xTile.Dimensions.Location pos) { Log.Trace("Event: ActionActivated"); if (SpaceEvents.ActionActivated == null || !who.IsLocalPlayer) return false; var arg = new EventArgsAction(false, action, pos); return Util.InvokeEventCancelable("SpaceEvents.ActionActivated", SpaceEvents.ActionActivated.GetInvocationList(), who, arg); } internal static bool InvokeTouchActionActivated(Farmer who, string action, xTile.Dimensions.Location pos) { Log.Trace("Event: TouchActionActivated"); if (SpaceEvents.TouchActionActivated == null || !who.IsLocalPlayer) return false; var arg = new EventArgsAction(true, action, pos); return Util.InvokeEventCancelable("SpaceEvents.TouchActionActivated", SpaceEvents.TouchActionActivated.GetInvocationList(), who, arg); } internal static void InvokeServerGotClient(GameServer server, long peer) { var args = new EventArgsServerGotClient { FarmerID = peer }; Log.Trace("Event: ServerGotClient"); if (SpaceEvents.ServerGotClient == null) return; Util.InvokeEvent("SpaceEvents.ServerGotClient", SpaceEvents.ServerGotClient.GetInvocationList(), server, args); } internal static bool InvokeBeforeReceiveObject(NPC npc, SObject obj, Farmer farmer) { Log.Trace("Event: BeforeReceiveObject"); if (SpaceEvents.BeforeGiftGiven == null) return false; var arg = new EventArgsBeforeReceiveObject(npc, obj); return Util.InvokeEventCancelable("SpaceEvents.BeforeReceiveObject", SpaceEvents.BeforeGiftGiven.GetInvocationList(), farmer, arg); } // Public for use in DGA public static void InvokeAfterGiftGiven(NPC npc, SObject obj, Farmer farmer) { Log.Trace("Event: AfterGiftGiven"); if (SpaceEvents.AfterGiftGiven == null) return; var arg = new EventArgsGiftGiven(npc, obj); Util.InvokeEvent("SpaceEvents.AfterGiftGiven", SpaceEvents.AfterGiftGiven.GetInvocationList(), farmer, arg); } internal static bool InvokeBeforeWarp(ref LocationRequest req, ref int targetX, ref int targetY, ref int facing) { Log.Trace("Event: BeforeWarp"); if (SpaceEvents.BeforeWarp == null) return false; var arg = new EventArgsBeforeWarp(req, targetX, targetY, facing); bool ret = Util.InvokeEventCancelable("SpaceEvents.BeforeWarp", SpaceEvents.BeforeWarp.GetInvocationList(), Game1.player, arg); req = arg.WarpTargetLocation; targetX = arg.WarpTargetX; targetY = arg.WarpTargetY; facing = arg.WarpTargetFacing; return ret; } internal static void InvokeBombExploded(Farmer who, Vector2 tileLocation, int radius) { Log.Trace("Event: BombExploded"); if (SpaceEvents.BombExploded == null) return; var arg = new EventArgsBombExploded(tileLocation, radius); Util.InvokeEvent("SpaceEvents.BombExploded", SpaceEvents.BombExploded.GetInvocationList(), who, arg); } internal static void InvokeOnEventFinished() { Log.Trace("Event: OnEventFinished"); if (SpaceEvents.OnEventFinished == null) return; Util.InvokeEvent("SpaceEvents.OnEventFinished", SpaceEvents.OnEventFinished.GetInvocationList(), null); } internal static void InvokeAddWalletItems( NewSkillsPage page ) { Log.Trace( "Event: AddWalletItems" ); if ( SpaceEvents.AddWalletItems == null ) return; Util.InvokeEvent( "SpaceEvents.AddWalletItems", SpaceEvents.AddWalletItems.GetInvocationList(), page ); } internal static bool HasAddWalletItemEventHandlers() { return AddWalletItems != null; } } }
43.819149
146
0.655013
[ "MIT" ]
Goldenrevolver/StardewValleyMods-1
SpaceCore/Events/SpaceEvents.cs
8,238
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Popups; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.Web.Http; using OwncloudUniversal.Synchronization; using OwncloudUniversal.OwnCloud.Model; namespace OwncloudUniversal.Services { static class ExceptionHandlerService { public static async void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) { e.Handled = true; var exception = e.Exception; await HandleException(exception, e.Message); } public static async Task HandleException(Exception exception, string message) { ContentDialog dia = new ContentDialog(); dia.Content = App.ResourceLoader.GetString("UnhandledExceptionMessage"); dia.Title = App.ResourceLoader.GetString("Oops"); dia.PrimaryButtonText = App.ResourceLoader.GetString("ok"); if ((uint)exception.HResult == 0x80072EE7)//server not found { dia.Content = App.ResourceLoader.GetString("ServerNotFound"); } else if (exception.GetType() == typeof(WebDavException))//-2146233088 { var ex = (WebDavException)exception; switch (ex.HttpStatusCode) { case HttpStatusCode.Unauthorized: dia.Content = App.ResourceLoader.GetString("UnauthorizedMessage"); break; case HttpStatusCode.NotFound: dia.Content = App.ResourceLoader.GetString("NotFoundMessage"); break; case HttpStatusCode.InternalServerError: dia.Content = App.ResourceLoader.GetString("InternalServerErrorMessage"); break; case HttpStatusCode.Forbidden: dia.Content = App.ResourceLoader.GetString("ForbiddenErrorMessage"); break; default: dia.Content = App.ResourceLoader.GetString("ServiceUnavailableMessage"); break; } if (ex.Message == HttpStatusCode.Forbidden.ToString()) dia.Content = App.ResourceLoader.GetString("ForbiddenErrorMessage"); } await LogHelper.Write($"{exception.GetType()}: {message} \r\n{exception.StackTrace}"); IndicatorService.GetDefault().HideBar(); await dia.ShowAsync(); } } }
40.69697
100
0.591214
[ "Apache-2.0" ]
DeepDiver1975/OwncloudUniversal
src/OwncloudUniversal/Services/ExceptionHandlerService.cs
2,688
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.RecoveryServices.Outputs { /// <summary> /// Current scenario details of the protected entity. /// </summary> [OutputType] public sealed class CurrentScenarioDetailsResponse { /// <summary> /// ARM Id of the job being executed. /// </summary> public readonly string? JobId; /// <summary> /// Scenario name. /// </summary> public readonly string? ScenarioName; /// <summary> /// Start time of the workflow. /// </summary> public readonly string? StartTime; [OutputConstructor] private CurrentScenarioDetailsResponse( string? jobId, string? scenarioName, string? startTime) { JobId = jobId; ScenarioName = scenarioName; StartTime = startTime; } } }
26.23913
81
0.600663
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/RecoveryServices/Outputs/CurrentScenarioDetailsResponse.cs
1,207
C#
 using System.Collections.Generic; namespace Framework.Library.ObjectPool { public class FastReferenceCountWrapper<T> : IReferenceTrack where T : class { public T Target { get; private set; } public virtual int RetainCount { get; private set; } private int _RetainCount = 0; public FastReferenceCountWrapper(T obj) { Target = obj; } public virtual void Retain(object owner) { RetainCount++; } public virtual void Release(object owner) { RetainCount--; CheckAndReleaseResource(); } protected void CheckAndReleaseResource() { if (RetainCount == 0) { ReleaseResource(); } } protected virtual void ReleaseResource() { } } public class SafeReferenceCountWrapper<T> : FastReferenceCountWrapper<T> where T : class { public SafeReferenceCountWrapper(T obj) : base(obj) { } public override int RetainCount { get{ return owners.Count;} } HashSet<object> owners = new HashSet<object>(); public override void Retain(object owner) { owners.Add(owner); } public override void Release(object owner) { owners.Remove(owner); CheckAndReleaseResource(); } } }
18.238095
89
0.694517
[ "MIT" ]
kedlly/XDFramework
Assets/Scripts/Framework/Library/ObjectPool/ReferenceTrack.cs
1,151
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the iotwireless-2020-11-22.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.IoTWireless.Model { /// <summary> /// WirelessMetadata object. /// </summary> public partial class WirelessMetadata { private LoRaWANSendDataToDevice _loRaWAN; private SidewalkSendDataToDevice _sidewalk; /// <summary> /// Gets and sets the property LoRaWAN. /// <para> /// LoRaWAN device info. /// </para> /// </summary> public LoRaWANSendDataToDevice LoRaWAN { get { return this._loRaWAN; } set { this._loRaWAN = value; } } // Check to see if LoRaWAN property is set internal bool IsSetLoRaWAN() { return this._loRaWAN != null; } /// <summary> /// Gets and sets the property Sidewalk. /// <para> /// The Sidewalk account credentials. /// </para> /// </summary> public SidewalkSendDataToDevice Sidewalk { get { return this._sidewalk; } set { this._sidewalk = value; } } // Check to see if Sidewalk property is set internal bool IsSetSidewalk() { return this._sidewalk != null; } } }
28.763158
110
0.596981
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/IoTWireless/Generated/Model/WirelessMetadata.cs
2,186
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("hbehr.recaptcha")] [assembly: AssemblyDescription("Recaptcha simplified for ASP.NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Henrique Borba Behr")] [assembly: AssemblyProduct("hbehr.recaptcha")] [assembly: AssemblyCopyright("Copyright © 2015 - 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("33058f83-ee77-460e-a1d0-edf030013bdb")] // 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.5.1.*")] [assembly: AssemblyFileVersion("1.5.1.0")]
40.571429
84
0.745775
[ "MIT" ]
AlexEndris/ReCaptcha-Asp-Net
src/hbehr.recaptcha/Properties/AssemblyInfo.cs
1,423
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("RemoteApp.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RemoteApp.Tests")] [assembly: AssemblyCopyright("Copyright © 2014")] [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("837c1b33-e6f1-45ac-bdff-f4eae60b38ee")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.918919
84
0.744833
[ "Apache-2.0" ]
CerebralMischief/azure-sdk-for-net
src/ServiceManagement/RemoteApp/RemoteApp.Tests/Properties/AssemblyInfo.cs
1,406
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; /** * Class dedicated to control da behavior of the bar that is intended to graphically illustrate the * received values from the PLUX device. */ public class BarScript : MonoBehaviour { // Internal instance of the BarScript class. public static BarScript Instance; // Class global variables. private float fillAmount; public Image bar; private int maxValue = -1; /** * <summary>Awake is called when the script instance is being loaded. * Awake is used to initialize any variables or game state before the game starts. Awake is called only once during the lifetime of the script instance, * being always invoked before Start().</summary> * <see>https://docs.unity3d.com/ScriptReference/MonoBehaviour.Awake.html</see> */ void Awake() { //Check if instance already exists if (Instance == null) //if not, set instance to this Instance = this; } /** * Set of instruction responsible for controlling the fraction of the bar that should be filled * accordingly to the value under analysis. */ public int Value { set { // Initializing the bar value. if(value == -1) { fillAmount = 0; return; } // Baseline removal. int newValue = Mathf.Abs(value - 32767); // Dealing with out of bound values. maxValue = newValue > maxValue ? newValue : maxValue; // Define the new fillAmount value. fillAmount = newValue * 1f/maxValue; } } /** * <summary>Unity callback that is invoked when the script is enabled (is only executed one time).</summary> * <see>https://docs.unity3d.com/ScriptReference/MonoBehaviour.Start.html</see> */ void Start () { } /** * <summary>Unity callback called once per frame.</summary> * <see>https://docs.unity3d.com/ScriptReference/MonoBehaviour.Update.html</see> */ void Update () { HandleBar(); } /** * <summary>Method responsible for setting the size of the bar parcel that should be filled (accordingly to the value * under analysis)</summary> */ private void HandleBar() { // Update the bar only if the current value is different from the previous one. if(fillAmount == bar.fillAmount) { return; } // Update bar value. bar.fillAmount = fillAmount; } }
28.73913
156
0.611195
[ "Apache-2.0" ]
biosignalsplux/unity-android-sample
Assets/Scripts/Utils/BarScript.cs
2,646
C#
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using Microsoft.Maui.Controls.Internals; using Microsoft.Maui.Graphics; namespace Microsoft.Maui.Controls { /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="Type[@FullName='Microsoft.Maui.Controls.Label']/Docs" /> [ContentProperty(nameof(Text))] public partial class Label : View, IFontElement, ITextElement, ITextAlignmentElement, ILineHeightElement, IElementConfiguration<Label>, IDecorableTextElement, IPaddingElement { /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='HorizontalTextAlignmentProperty']/Docs" /> public static readonly BindableProperty HorizontalTextAlignmentProperty = TextAlignmentElement.HorizontalTextAlignmentProperty; /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='VerticalTextAlignmentProperty']/Docs" /> public static readonly BindableProperty VerticalTextAlignmentProperty = BindableProperty.Create("VerticalTextAlignment", typeof(TextAlignment), typeof(Label), TextAlignment.Start); /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='TextColorProperty']/Docs" /> public static readonly BindableProperty TextColorProperty = TextElement.TextColorProperty; /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='CharacterSpacingProperty']/Docs" /> public static readonly BindableProperty CharacterSpacingProperty = TextElement.CharacterSpacingProperty; /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='TextProperty']/Docs" /> public static readonly BindableProperty TextProperty = BindableProperty.Create(nameof(Text), typeof(string), typeof(Label), default(string), propertyChanged: OnTextPropertyChanged); /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='FontFamilyProperty']/Docs" /> public static readonly BindableProperty FontFamilyProperty = FontElement.FontFamilyProperty; /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='FontSizeProperty']/Docs" /> public static readonly BindableProperty FontSizeProperty = FontElement.FontSizeProperty; /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='FontAttributesProperty']/Docs" /> public static readonly BindableProperty FontAttributesProperty = FontElement.FontAttributesProperty; /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='FontAutoScalingEnabledProperty']/Docs" /> public static readonly BindableProperty FontAutoScalingEnabledProperty = FontElement.FontAutoScalingEnabledProperty; /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='TextTransformProperty']/Docs" /> public static readonly BindableProperty TextTransformProperty = TextElement.TextTransformProperty; /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='TextDecorationsProperty']/Docs" /> public static readonly BindableProperty TextDecorationsProperty = DecorableTextElement.TextDecorationsProperty; /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='FormattedTextProperty']/Docs" /> public static readonly BindableProperty FormattedTextProperty = BindableProperty.Create(nameof(FormattedText), typeof(FormattedString), typeof(Label), default(FormattedString), propertyChanging: (bindable, oldvalue, newvalue) => { if (oldvalue != null) { var formattedString = ((FormattedString)oldvalue); var label = ((Label)bindable); formattedString.SpansCollectionChanged -= label.Span_CollectionChanged; formattedString.PropertyChanged -= label.OnFormattedTextChanged; formattedString.PropertyChanging -= label.OnFormattedTextChanging; formattedString.Parent = null; label.RemoveSpans(formattedString.Spans); } }, propertyChanged: (bindable, oldvalue, newvalue) => { var label = ((Label)bindable); if (newvalue != null) { var formattedString = (FormattedString)newvalue; formattedString.Parent = label; formattedString.PropertyChanging += label.OnFormattedTextChanging; formattedString.PropertyChanged += label.OnFormattedTextChanged; formattedString.SpansCollectionChanged += label.Span_CollectionChanged; label.SetupSpans(formattedString.Spans); } label.InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged); if (newvalue != null) label.Text = null; }); /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='TextTransform']/Docs" /> public TextTransform TextTransform { get { return (TextTransform)GetValue(TextTransformProperty); } set { SetValue(TextTransformProperty, value); } } /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='UpdateFormsText']/Docs" /> public virtual string UpdateFormsText(string source, TextTransform textTransform) => TextTransformUtilites.GetTransformedText(source, textTransform); /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='LineBreakModeProperty']/Docs" /> public static readonly BindableProperty LineBreakModeProperty = BindableProperty.Create(nameof(LineBreakMode), typeof(LineBreakMode), typeof(Label), LineBreakMode.WordWrap, propertyChanged: (bindable, oldvalue, newvalue) => ((Label)bindable).InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged)); /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='LineHeightProperty']/Docs" /> public static readonly BindableProperty LineHeightProperty = LineHeightElement.LineHeightProperty; /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='MaxLinesProperty']/Docs" /> public static readonly BindableProperty MaxLinesProperty = BindableProperty.Create(nameof(MaxLines), typeof(int), typeof(Label), -1, propertyChanged: (bindable, oldvalue, newvalue) => { if (bindable != null) { ((Label)bindable).InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged); } }); /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='PaddingProperty']/Docs" /> public static readonly BindableProperty PaddingProperty = PaddingElement.PaddingProperty; /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='TextTypeProperty']/Docs" /> public static readonly BindableProperty TextTypeProperty = BindableProperty.Create(nameof(TextType), typeof(TextType), typeof(Label), TextType.Text, propertyChanged: (bindable, oldvalue, newvalue) => ((Label)bindable).InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged)); readonly Lazy<PlatformConfigurationRegistry<Label>> _platformConfigurationRegistry; /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='.ctor']/Docs" /> public Label() { _platformConfigurationRegistry = new Lazy<PlatformConfigurationRegistry<Label>>(() => new PlatformConfigurationRegistry<Label>(this)); } protected override void OnBindingContextChanged() { base.OnBindingContextChanged(); if (FormattedText != null) SetInheritedBindingContext(FormattedText, this.BindingContext); } /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='FormattedText']/Docs" /> public FormattedString FormattedText { get { return (FormattedString)GetValue(FormattedTextProperty); } set { SetValue(FormattedTextProperty, value); } } /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='HorizontalTextAlignment']/Docs" /> public TextAlignment HorizontalTextAlignment { get { return (TextAlignment)GetValue(TextAlignmentElement.HorizontalTextAlignmentProperty); } set { SetValue(TextAlignmentElement.HorizontalTextAlignmentProperty, value); } } /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='LineBreakMode']/Docs" /> public LineBreakMode LineBreakMode { get { return (LineBreakMode)GetValue(LineBreakModeProperty); } set { SetValue(LineBreakModeProperty, value); } } /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='Text']/Docs" /> public string Text { get { return (string)GetValue(TextProperty); } set { SetValue(TextProperty, value); } } /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='TextColor']/Docs" /> public Color TextColor { get { return (Color)GetValue(TextElement.TextColorProperty); } set { SetValue(TextElement.TextColorProperty, value); } } /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='CharacterSpacing']/Docs" /> public double CharacterSpacing { get { return (double)GetValue(TextElement.CharacterSpacingProperty); } set { SetValue(TextElement.CharacterSpacingProperty, value); } } /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='VerticalTextAlignment']/Docs" /> public TextAlignment VerticalTextAlignment { get { return (TextAlignment)GetValue(VerticalTextAlignmentProperty); } set { SetValue(VerticalTextAlignmentProperty, value); } } /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='FontAttributes']/Docs" /> public FontAttributes FontAttributes { get { return (FontAttributes)GetValue(FontAttributesProperty); } set { SetValue(FontAttributesProperty, value); } } /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='TextDecorations']/Docs" /> public TextDecorations TextDecorations { get { return (TextDecorations)GetValue(TextDecorationsProperty); } set { SetValue(TextDecorationsProperty, value); } } /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='FontFamily']/Docs" /> public string FontFamily { get { return (string)GetValue(FontFamilyProperty); } set { SetValue(FontFamilyProperty, value); } } /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='FontSize']/Docs" /> [System.ComponentModel.TypeConverter(typeof(FontSizeConverter))] public double FontSize { get { return (double)GetValue(FontSizeProperty); } set { SetValue(FontSizeProperty, value); } } /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='FontAutoScalingEnabled']/Docs" /> public bool FontAutoScalingEnabled { get => (bool)GetValue(FontAutoScalingEnabledProperty); set => SetValue(FontAutoScalingEnabledProperty, value); } /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='LineHeight']/Docs" /> public double LineHeight { get { return (double)GetValue(LineHeightProperty); } set { SetValue(LineHeightProperty, value); } } /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='MaxLines']/Docs" /> public int MaxLines { get => (int)GetValue(MaxLinesProperty); set => SetValue(MaxLinesProperty, value); } /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='Padding']/Docs" /> public Thickness Padding { get { return (Thickness)GetValue(PaddingProperty); } set { SetValue(PaddingProperty, value); } } /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='TextType']/Docs" /> public TextType TextType { get => (TextType)GetValue(TextTypeProperty); set => SetValue(TextTypeProperty, value); } double IFontElement.FontSizeDefaultValueCreator() => this.GetDefaultFontSize(); void IFontElement.OnFontAttributesChanged(FontAttributes oldValue, FontAttributes newValue) => HandleFontChanged(); void IFontElement.OnFontFamilyChanged(string oldValue, string newValue) => HandleFontChanged(); void IFontElement.OnFontSizeChanged(double oldValue, double newValue) => HandleFontChanged(); void IFontElement.OnFontChanged(Font oldValue, Font newValue) => HandleFontChanged(); void IFontElement.OnFontAutoScalingEnabledChanged(bool oldValue, bool newValue) => HandleFontChanged(); void HandleFontChanged() { InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged); } void ILineHeightElement.OnLineHeightChanged(double oldValue, double newValue) => InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged); void OnFormattedTextChanging(object sender, PropertyChangingEventArgs e) { OnPropertyChanging("FormattedText"); } void ITextElement.OnTextTransformChanged(TextTransform oldValue, TextTransform newValue) => InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged); void OnFormattedTextChanged(object sender, PropertyChangedEventArgs e) { OnPropertyChanged("FormattedText"); InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged); } void SetupSpans(IEnumerable spans) { foreach (Span span in spans) { span.GestureRecognizersCollectionChanged += Span_GestureRecognizer_CollectionChanged; SetupSpanGestureRecognizers(span.GestureRecognizers); } } void SetupSpanGestureRecognizers(IEnumerable gestureRecognizers) { foreach (GestureRecognizer gestureRecognizer in gestureRecognizers) GestureController.CompositeGestureRecognizers.Add(new ChildGestureRecognizer() { GestureRecognizer = gestureRecognizer }); } void RemoveSpans(IEnumerable spans) { foreach (Span span in spans) { RemoveSpanGestureRecognizers(span.GestureRecognizers); span.GestureRecognizersCollectionChanged -= Span_GestureRecognizer_CollectionChanged; } } void RemoveSpanGestureRecognizers(IEnumerable gestureRecognizers) { foreach (GestureRecognizer gestureRecognizer in gestureRecognizers) foreach (var spanRecognizer in GestureController.CompositeGestureRecognizers.ToList()) if (spanRecognizer is ChildGestureRecognizer childGestureRecognizer && childGestureRecognizer.GestureRecognizer == gestureRecognizer) GestureController.CompositeGestureRecognizers.Remove(spanRecognizer); } void Span_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: SetupSpans(e.NewItems); break; case NotifyCollectionChangedAction.Remove: RemoveSpans(e.OldItems); break; case NotifyCollectionChangedAction.Replace: RemoveSpans(e.OldItems); SetupSpans(e.NewItems); break; case NotifyCollectionChangedAction.Reset: // Is never called, because the clear command is overridden. break; } } void Span_GestureRecognizer_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: SetupSpanGestureRecognizers(e.NewItems); break; case NotifyCollectionChangedAction.Remove: RemoveSpanGestureRecognizers(e.OldItems); break; case NotifyCollectionChangedAction.Replace: RemoveSpanGestureRecognizers(e.OldItems); SetupSpanGestureRecognizers(e.NewItems); break; case NotifyCollectionChangedAction.Reset: // is never called, because the clear command is overridden. break; } } void ITextAlignmentElement.OnHorizontalTextAlignmentPropertyChanged(TextAlignment oldValue, TextAlignment newValue) { } static void OnTextPropertyChanged(BindableObject bindable, object oldvalue, object newvalue) { var label = (Label)bindable; LineBreakMode breakMode = label.LineBreakMode; bool isVerticallyFixed = (label.Constraint & LayoutConstraint.VerticallyFixed) != 0; bool isSingleLine = !(breakMode == LineBreakMode.CharacterWrap || breakMode == LineBreakMode.WordWrap); if (!isVerticallyFixed || !isSingleLine) ((Label)bindable).InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged); if (newvalue != null) ((Label)bindable).FormattedText = null; } /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='On']/Docs" /> public IPlatformElementConfiguration<T, Label> On<T>() where T : IConfigPlatform { return _platformConfigurationRegistry.Value.On<T>(); } void ITextElement.OnTextColorPropertyChanged(Color oldValue, Color newValue) { } void ITextElement.OnCharacterSpacingPropertyChanged(double oldValue, double newValue) { InvalidateMeasure(); } internal bool HasFormattedTextSpans => (FormattedText?.Spans?.Count ?? 0) > 0; /// <include file="../../docs/Microsoft.Maui.Controls/Label.xml" path="//Member[@MemberName='GetChildElements']/Docs" /> public override IList<GestureElement> GetChildElements(Point point) { if (FormattedText?.Spans == null || FormattedText?.Spans.Count == 0) return null; var spans = new List<GestureElement>(); for (int i = 0; i < FormattedText.Spans.Count; i++) { Span span = FormattedText.Spans[i]; if (span.GestureRecognizers.Count > 0 && (((ISpatialElement)span).Region.Contains(point) || point.IsEmpty)) spans.Add(span); } if (!point.IsEmpty && spans.Count > 1) // More than 2 elements overlapping, deflate to see which one is actually hit. for (var i = spans.Count - 1; i >= 0; i--) if (!((ISpatialElement)spans[i]).Region.Deflate().Contains(point)) spans.RemoveAt(i); return spans; } Thickness IPaddingElement.PaddingDefaultValueCreator() { return default(Thickness); } void IPaddingElement.OnPaddingPropertyChanged(Thickness oldValue, Thickness newValue) { InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged); } } }
42.672131
185
0.747434
[ "MIT" ]
APopatanasov/maui
src/Controls/src/Core/Label.cs
18,221
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _05.Snowflake { class Program { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); int promenliva = 0; int promenliva2 = 0; int hight = 2 * n + 1; int width = 2 * n + 3; for (int i = 0; i < n-1; i++) { Console.WriteLine("{0}*{1}*{1}*{0}", new string('.', i), new string('.', n - i)); promenliva = i; promenliva2 = n - i; } Console.WriteLine("{0}*****{0}", new string('.', promenliva+1)); Console.WriteLine("{0}", new string('*', width)); Console.WriteLine("{0}*****{0}", new string('.', promenliva + 1)); for (int i = 0; i < n - 1; i++) { Console.WriteLine("{0}*{1}*{1}*{0}", new string('.', promenliva-i), new string('.', promenliva2 + i)); } } } }
25.023256
118
0.452602
[ "MIT" ]
kavier/Programing-Basic-Csharp
08-ProgrammingBasicsExercises/15-ProgrammingBasicsExam-03September2017/05-Snowflake.cs
1,076
C#
using Cash.Core.Enums; using Cash.Core.Providers; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Cash.Core.Tests.Providers { [TestClass] public class NullCacheKeyProviderTests : BaseCacheKeyProviderTests<NullCacheKeyProvider> { public override object[] GetSuccessArguments() => new object[] { null }; public override object[] GetFailureArguments() => new object[] { 1, "test", new Models.TestModelDefinition() }; public override CacheKeyProviderExecutionOrder GetExecutionOrder() => CacheKeyProviderExecutionOrder.Null; } }
32.444444
119
0.744863
[ "MIT" ]
asmorger/cash
src/Cash.Core.Tests/Providers/NullCacheKeyProviderTests.cs
586
C#
using Piksel.LogViewer.Helpers; using System; using System.Diagnostics; using System.Globalization; using System.Text; namespace Piksel.LogViewer.Logging { /// <summary> /// Represents a log message from a log input source /// </summary> public class LogMessage { // Exception and message cannot be null private string exception = string.Empty; private string message = string.Empty; /// <summary> /// Message part of log message, guaranteed to not be null /// </summary> public string Message { get => message; set => message = value ?? string.Empty; } /// <summary> /// Exception part of log message, guaranteed to not be null /// </summary> public string Exception { get => exception; set => exception = value ?? string.Empty; } /// <summary> /// Returns whether <see cref="Exception"/> equals <see cref="string.Empty"/> /// </summary> public bool HasException => exception == string.Empty; public string Source { get; set; } public LogLevel LogLevel { get; set; } public DateTime Time { get; set; } public string RawTime { get; set; } protected bool hasTime = true; public string FormatLocalTime(string format, IFormatProvider provider) => hasTime ? Time.ToString(format, provider) : EmptyDateTime.ToString(format, provider); public string FormatLocalTime(string format) => FormatLocalTime(format, CultureInfo.CurrentCulture); public string FormattedTime => RawTime ?? FormatLocalTime("yyyy-MM-dd HH:mm:ss"); [Obsolete("LogMessage.Builder should be used instead")] public LogMessage(LogLevel logLevel, string source, string message, string exception) { LogLevel = logLevel; Source = source; Message = message; Exception = exception; } protected LogMessage() { } public class Builder { private LogMessage lm = new LogMessage(); private StringBuilder messageBuilder = new StringBuilder(); private StringBuilder exceptionBuilder = new StringBuilder(); // Note: Time offsets are specifed in the amount of time to be subtracted from the input time to make it UTC private TimeSpan timeOffset = TimeSpan.Zero; private static TimeSpan localOffset; protected DateTimeOffset? utcTime; public bool IsEmpty => messageBuilder.Length == 0; static Builder() { var localNow = DateTime.Now; localOffset = localNow.ToUniversalTime() - localNow; } public Builder() {} /// <summary> /// Sets the log message <see cref="LogLevel"/> /// </summary> /// <param name="logLevel"></param> /// <returns>Returns the builder instance</returns> public Builder WithLevel(LogLevel logLevel) { Debug.Assert(logLevel != LogLevel.None); lm.LogLevel = logLevel; return this; } /// <summary> /// Sets the log message <see cref="Source"/> /// </summary> /// <param name="source"></param> /// <returns>Returns the builder instance</returns> public Builder WithSource(string source) { lm.Source = source; return this; } /// <summary> /// /// </summary> /// <param name="time"></param> /// <returns>Returns the builder instance</returns> public Builder WithTime(DateTimeOffset time) { utcTime = time; lm.RawTime = null; return this; } /// <summary> /// Sets the time to a raw string that is not processed further /// </summary> /// <param name="time"></param> /// <returns>Returns the builder instance</returns> public Builder WithRawTime(string time) { lm.RawTime = time; return this; } /// <summary> /// Sets the log message <see cref="Time"/> from <paramref name="time"/> using current local time zone /// </summary> /// <param name="time"></param> /// <returns>Returns the builder instance</returns> public Builder WithLocalTime(DateTime time) => WithTime(new DateTimeOffset(time, localOffset)); /// <summary> /// Sets the log message <see cref="Time"/> from <paramref name="time"/> using current local time zone /// </summary> /// <param name="time"></param> /// <returns>Returns the builder instance</returns> public Builder WithCustomTime(DateTime time) => WithTime(new DateTimeOffset(time, timeOffset)); public Builder WithUniversalTime(DateTime time) => WithTime(new DateTimeOffset(time, TimeSpan.Zero)); /// <summary> /// Sets the log message time offset from <paramref name="ts"/> and updates the <see cref="Time"/> accordingly /// </summary> /// <param name="ts">The time offset of the log input source</param> /// <remarks>If the input source uses UTC this should be <see cref="TimeSpan.Zero"/></remarks> /// <returns>Returns the builder instance</returns> public Builder UsingTimezone(TimeSpan ts) { // Only update the time if we actually change the timespan to avoid problems with timezone set inside loops if (ts != timeOffset) { timeOffset = ts; utcTime.HasValue(value => utcTime = value.ToOffset(ts)); } return this; } /// <summary> /// Sets the log message time offset from <paramref name="tzi"/> and updates the <see cref="Time"/> accordingly /// </summary> /// <param name="tzi">The time zone used in the log input source</param> /// <returns>Returns the builder instance</returns> public Builder UsingTimezone(TimeZoneInfo tzi) => UsingTimezone(tzi.BaseUtcOffset); /// <summary> /// Appends <paramref name="exception"/> to the <see cref="Exception"/> builder /// </summary> /// <param name="exception"></param> /// <returns>Returns the builder instance</returns> public Builder WithExceptionLine(string exception) { if (exceptionBuilder.Length > 0) exceptionBuilder.AppendLine(); exceptionBuilder.Append(exception); return this; } /// <summary> /// Appends <paramref name="message"/> to the <see cref="Message"/> builder /// </summary> /// <param name="message"></param> /// <returns>Returns the builder instance</returns> public Builder WithMessageLine(string message) { if (messageBuilder.Length > 0) messageBuilder.AppendLine(); messageBuilder.Append(message); return this; } /// <summary> /// Builds the LogMessage and resets the message and exception values /// </summary> /// <returns></returns> public LogMessage Build() => Build(true); /// <summary> /// Builds the LogMessage and resets the message and exception values if <paramref name="resetLines"/> is <c>true</c> /// </summary> /// <param name="resetLines">Whether the message and exception values should be reset</param> /// <returns></returns> public LogMessage Build(bool resetLines) { lm.Message = messageBuilder.ToString(); lm.Exception = exceptionBuilder.ToString(); lm.Time = utcTime?.LocalDateTime ?? DateTime.Now; lm.hasTime = utcTime.HasValue; var result = lm; if (resetLines) { messageBuilder.Clear(); exceptionBuilder.Clear(); lm = new LogMessage() { LogLevel = result.LogLevel, Source = result.Source, Time = result.Time, RawTime = result.RawTime }; } return result; } public Builder WithoutTime() { utcTime = null; return this; } } } }
36.503968
129
0.523318
[ "MIT" ]
piksel/LogViewer
src/Piksel.LogViewer/Logging/LogMessage.cs
9,201
C#
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using CookComputing.XmlRpc; namespace XenAPI { public partial class VIF_metrics : XenObject<VIF_metrics> { public VIF_metrics() { } public VIF_metrics(string uuid, double io_read_kbs, double io_write_kbs, DateTime last_updated, Dictionary<string, string> other_config) { this.uuid = uuid; this.io_read_kbs = io_read_kbs; this.io_write_kbs = io_write_kbs; this.last_updated = last_updated; this.other_config = other_config; } /// <summary> /// Creates a new VIF_metrics from a Proxy_VIF_metrics. /// </summary> /// <param name="proxy"></param> public VIF_metrics(Proxy_VIF_metrics proxy) { this.UpdateFromProxy(proxy); } public override void UpdateFrom(VIF_metrics update) { uuid = update.uuid; io_read_kbs = update.io_read_kbs; io_write_kbs = update.io_write_kbs; last_updated = update.last_updated; other_config = update.other_config; } internal void UpdateFromProxy(Proxy_VIF_metrics proxy) { uuid = proxy.uuid == null ? null : (string)proxy.uuid; io_read_kbs = Convert.ToDouble(proxy.io_read_kbs); io_write_kbs = Convert.ToDouble(proxy.io_write_kbs); last_updated = proxy.last_updated; other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); } public Proxy_VIF_metrics ToProxy() { Proxy_VIF_metrics result_ = new Proxy_VIF_metrics(); result_.uuid = (uuid != null) ? uuid : ""; result_.io_read_kbs = io_read_kbs; result_.io_write_kbs = io_write_kbs; result_.last_updated = last_updated; result_.other_config = Maps.convert_to_proxy_string_string(other_config); return result_; } /// <summary> /// Creates a new VIF_metrics from a Hashtable. /// </summary> /// <param name="table"></param> public VIF_metrics(Hashtable table) { uuid = Marshalling.ParseString(table, "uuid"); io_read_kbs = Marshalling.ParseDouble(table, "io_read_kbs"); io_write_kbs = Marshalling.ParseDouble(table, "io_write_kbs"); last_updated = Marshalling.ParseDateTime(table, "last_updated"); other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(VIF_metrics other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._io_read_kbs, other._io_read_kbs) && Helper.AreEqual2(this._io_write_kbs, other._io_write_kbs) && Helper.AreEqual2(this._last_updated, other._last_updated) && Helper.AreEqual2(this._other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, VIF_metrics server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { if (!Helper.AreEqual2(_other_config, server._other_config)) { VIF_metrics.set_other_config(session, opaqueRef, _other_config); } return null; } } public static VIF_metrics get_record(Session session, string _vif_metrics) { return new VIF_metrics((Proxy_VIF_metrics)session.proxy.vif_metrics_get_record(session.uuid, (_vif_metrics != null) ? _vif_metrics : "").parse()); } public static XenRef<VIF_metrics> get_by_uuid(Session session, string _uuid) { return XenRef<VIF_metrics>.Create(session.proxy.vif_metrics_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse()); } public static string get_uuid(Session session, string _vif_metrics) { return (string)session.proxy.vif_metrics_get_uuid(session.uuid, (_vif_metrics != null) ? _vif_metrics : "").parse(); } public static double get_io_read_kbs(Session session, string _vif_metrics) { return Convert.ToDouble(session.proxy.vif_metrics_get_io_read_kbs(session.uuid, (_vif_metrics != null) ? _vif_metrics : "").parse()); } public static double get_io_write_kbs(Session session, string _vif_metrics) { return Convert.ToDouble(session.proxy.vif_metrics_get_io_write_kbs(session.uuid, (_vif_metrics != null) ? _vif_metrics : "").parse()); } public static DateTime get_last_updated(Session session, string _vif_metrics) { return session.proxy.vif_metrics_get_last_updated(session.uuid, (_vif_metrics != null) ? _vif_metrics : "").parse(); } public static Dictionary<string, string> get_other_config(Session session, string _vif_metrics) { return Maps.convert_from_proxy_string_string(session.proxy.vif_metrics_get_other_config(session.uuid, (_vif_metrics != null) ? _vif_metrics : "").parse()); } public static void set_other_config(Session session, string _vif_metrics, Dictionary<string, string> _other_config) { session.proxy.vif_metrics_set_other_config(session.uuid, (_vif_metrics != null) ? _vif_metrics : "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } public static void add_to_other_config(Session session, string _vif_metrics, string _key, string _value) { session.proxy.vif_metrics_add_to_other_config(session.uuid, (_vif_metrics != null) ? _vif_metrics : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse(); } public static void remove_from_other_config(Session session, string _vif_metrics, string _key) { session.proxy.vif_metrics_remove_from_other_config(session.uuid, (_vif_metrics != null) ? _vif_metrics : "", (_key != null) ? _key : "").parse(); } public static List<XenRef<VIF_metrics>> get_all(Session session) { return XenRef<VIF_metrics>.Create(session.proxy.vif_metrics_get_all(session.uuid).parse()); } public static Dictionary<XenRef<VIF_metrics>, VIF_metrics> get_all_records(Session session) { return XenRef<VIF_metrics>.Create<Proxy_VIF_metrics>(session.proxy.vif_metrics_get_all_records(session.uuid).parse()); } private string _uuid; public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private double _io_read_kbs; public virtual double io_read_kbs { get { return _io_read_kbs; } set { if (!Helper.AreEqual(value, _io_read_kbs)) { _io_read_kbs = value; Changed = true; NotifyPropertyChanged("io_read_kbs"); } } } private double _io_write_kbs; public virtual double io_write_kbs { get { return _io_write_kbs; } set { if (!Helper.AreEqual(value, _io_write_kbs)) { _io_write_kbs = value; Changed = true; NotifyPropertyChanged("io_write_kbs"); } } } private DateTime _last_updated; public virtual DateTime last_updated { get { return _last_updated; } set { if (!Helper.AreEqual(value, _last_updated)) { _last_updated = value; Changed = true; NotifyPropertyChanged("last_updated"); } } } private Dictionary<string, string> _other_config; public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; Changed = true; NotifyPropertyChanged("other_config"); } } } } }
43.038298
185
0.62715
[ "BSD-2-Clause" ]
ChrisH4rding/xenadmin
XenModel/XenAPI/VIF_metrics.cs
10,114
C#
using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Middleware; using JsonApiDotNetCore.Resources; using JsonApiDotNetCore.Resources.Annotations; using JsonApiDotNetCoreTests.IntegrationTests.Microservices.Messages; using Microsoft.EntityFrameworkCore; namespace JsonApiDotNetCoreTests.IntegrationTests.Microservices; public abstract class MessagingUserDefinition : HitCountingResourceDefinition<DomainUser, Guid> { private readonly DbSet<DomainUser> _userSet; private readonly List<OutgoingMessage> _pendingMessages = new(); private string? _beforeLoginName; private string? _beforeDisplayName; protected override ResourceDefinitionExtensibilityPoints ExtensibilityPointsToTrack => ResourceDefinitionExtensibilityPoints.Writing; protected MessagingUserDefinition(IResourceGraph resourceGraph, DbSet<DomainUser> userSet, ResourceDefinitionHitCounter hitCounter) : base(resourceGraph, hitCounter) { _userSet = userSet; } public override async Task OnPrepareWriteAsync(DomainUser user, WriteOperationKind writeOperation, CancellationToken cancellationToken) { await base.OnPrepareWriteAsync(user, writeOperation, cancellationToken); if (writeOperation == WriteOperationKind.CreateResource) { user.Id = Guid.NewGuid(); } else if (writeOperation == WriteOperationKind.UpdateResource) { _beforeLoginName = user.LoginName; _beforeDisplayName = user.DisplayName; } } public override async Task<IIdentifiable?> OnSetToOneRelationshipAsync(DomainUser user, HasOneAttribute hasOneRelationship, IIdentifiable? rightResourceId, WriteOperationKind writeOperation, CancellationToken cancellationToken) { await base.OnSetToOneRelationshipAsync(user, hasOneRelationship, rightResourceId, writeOperation, cancellationToken); if (hasOneRelationship.Property.Name == nameof(DomainUser.Group)) { var afterGroupId = (Guid?)rightResourceId?.GetTypedId(); IMessageContent? content = null; if (user.Group != null && afterGroupId == null) { content = new UserRemovedFromGroupContent(user.Id, user.Group.Id); } else if (user.Group == null && afterGroupId != null) { content = new UserAddedToGroupContent(user.Id, afterGroupId.Value); } else if (user.Group != null && afterGroupId != null && user.Group.Id != afterGroupId) { content = new UserMovedToGroupContent(user.Id, user.Group.Id, afterGroupId.Value); } if (content != null) { var message = OutgoingMessage.CreateFromContent(content); _pendingMessages.Add(message); } } return rightResourceId; } protected async Task FinishWriteAsync(DomainUser user, WriteOperationKind writeOperation, CancellationToken cancellationToken) { if (writeOperation == WriteOperationKind.CreateResource) { var content = new UserCreatedContent(user.Id, user.LoginName, user.DisplayName); var message = OutgoingMessage.CreateFromContent(content); await FlushMessageAsync(message, cancellationToken); } else if (writeOperation == WriteOperationKind.UpdateResource) { if (_beforeLoginName != user.LoginName) { var content = new UserLoginNameChangedContent(user.Id, _beforeLoginName!, user.LoginName); var message = OutgoingMessage.CreateFromContent(content); await FlushMessageAsync(message, cancellationToken); } if (_beforeDisplayName != user.DisplayName) { var content = new UserDisplayNameChangedContent(user.Id, _beforeDisplayName!, user.DisplayName); var message = OutgoingMessage.CreateFromContent(content); await FlushMessageAsync(message, cancellationToken); } } else if (writeOperation == WriteOperationKind.DeleteResource) { DomainUser? userToDelete = await GetUserToDeleteAsync(user.Id, cancellationToken); if (userToDelete?.Group != null) { var content = new UserRemovedFromGroupContent(user.Id, userToDelete.Group.Id); var message = OutgoingMessage.CreateFromContent(content); await FlushMessageAsync(message, cancellationToken); } var deleteMessage = OutgoingMessage.CreateFromContent(new UserDeletedContent(user.Id)); await FlushMessageAsync(deleteMessage, cancellationToken); } foreach (OutgoingMessage nextMessage in _pendingMessages) { await FlushMessageAsync(nextMessage, cancellationToken); } } protected abstract Task FlushMessageAsync(OutgoingMessage message, CancellationToken cancellationToken); protected virtual async Task<DomainUser?> GetUserToDeleteAsync(Guid userId, CancellationToken cancellationToken) { return await _userSet.Include(domainUser => domainUser.Group).FirstOrDefaultAsync(domainUser => domainUser.Id == userId, cancellationToken); } }
42.396825
159
0.683265
[ "MIT" ]
damien-rousseau/JsonApiDotNetCore_Polymorphism
test/JsonApiDotNetCoreTests/IntegrationTests/Microservices/MessagingUserDefinition.cs
5,342
C#
// Copyright (c) Stride contributors (https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System.Collections.Generic; using Stride.Core; using Stride.Core.Annotations; using Stride.Core.Quantum; using Stride.Assets.Rendering; using Stride.Rendering.Compositing; namespace Stride.Assets.Presentation.AssetEditors.GraphicsCompositorEditor.ViewModels { public class SharedRendererBlockViewModel : SharedRendererBlockBaseViewModel { private readonly Dictionary<SharedRendererReferenceKey, IGraphicsCompositorSlotViewModel> outputSlotMap = new Dictionary<SharedRendererReferenceKey, IGraphicsCompositorSlotViewModel>(); private readonly IObjectNode sharedRendererNode; private readonly ISharedRenderer sharedRenderer; public SharedRendererBlockViewModel([NotNull] GraphicsCompositorEditorViewModel editor, ISharedRenderer sharedRenderer) : base(editor) { this.sharedRenderer = sharedRenderer; sharedRendererNode = editor.Session.AssetNodeContainer.GetOrCreateNode(sharedRenderer); InputSlots.Add(new SharedRendererInputSlotViewModel(this)); } /// <inheritdoc/> public override string Title => DisplayAttribute.GetDisplayName(sharedRenderer?.GetType()); public ISharedRenderer GetSharedRenderer() => sharedRenderer; /// <inheritdoc/> protected override IEnumerable<IGraphNode> GetNodesContainingReferences() { yield return sharedRendererNode; } /// <inheritdoc/> public override IObjectNode GetRootNode() => sharedRendererNode; /// <inheritdoc /> protected override GraphNodePath GetNodePath() { var path = new GraphNodePath(Editor.Session.AssetNodeContainer.GetNode(Editor.Asset.Asset)); path.PushMember(nameof(GraphicsCompositorAsset.SharedRenderers)); path.PushTarget(); path.PushIndex(new NodeIndex(Editor.Asset.Asset.SharedRenderers.IndexOf(sharedRenderer))); return path; } } }
43.92
193
0.728597
[ "MIT" ]
Aggror/Stride
sources/editor/Stride.Assets.Presentation/AssetEditors/GraphicsCompositorEditor/ViewModels/SharedRendererBlockViewModel.cs
2,196
C#
/* Yet Another Forum.NET * Copyright (C) 2003-2005 Bjørnar Henden * Copyright (C) 2006-2013 Jaben Cargman * Copyright (C) 2014-2022 Ingo Herbote * https://www.yetanotherforum.net/ * * 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 * https://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 YAF.Controls { #region Using using System; using System.Globalization; using YAF.Core.BaseControls; using YAF.Core.BoardSettings; using YAF.Types; using YAF.Types.Extensions; #endregion /// <summary> /// The forum welcome control which shows the current Time and the Last Visit Time of the Current User. /// </summary> public partial class BoardAnnouncement : BaseUserControl { #region Methods /// <summary> /// The on pre render. /// </summary> /// <param name="e"> /// The e. /// </param> protected override void OnPreRender([NotNull] EventArgs e) { if (this.PageContext.BoardSettings.BoardAnnouncement.IsNotSet()) { this.Visible = false; return; } var dateTime = Convert.ToDateTime( this.PageContext.BoardSettings.BoardAnnouncementUntil, CultureInfo.InvariantCulture); if (dateTime <= DateTime.Now) { var boardSettings = this.PageContext.BoardSettings; boardSettings.BoardAnnouncementUntil = DateTime.MinValue.ToString(CultureInfo.InvariantCulture); boardSettings.BoardAnnouncement = string.Empty; // save the settings to the database ((LoadBoardSettings)boardSettings).SaveRegistry(); // delete no show this.Visible = false; return; } this.Badge.CssClass = $"badge bg-{this.PageContext.BoardSettings.BoardAnnouncementType} me-1"; this.Announcement.CssClass = $"alert alert-{this.PageContext.BoardSettings.BoardAnnouncementType} alert-dismissible"; this.Message.Text = this.PageContext.BoardSettings.BoardAnnouncement; this.DataBind(); base.OnPreRender(e); } #endregion } }
33.977778
130
0.623283
[ "Apache-2.0" ]
correaAlex/YAFNET
yafsrc/YetAnotherForum.NET/Controls/BoardAnnouncement.ascx.cs
2,970
C#
namespace appSesion_1 { partial class Form1 { /// <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() { this.components = new System.ComponentModel.Container(); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Text = "Form1"; } #endregion } }
28.35
107
0.556437
[ "Apache-2.0" ]
Ricardo9711/FundamentoSIUPC
Sesion_1/appSesion_1/appSesion_1/Form1.Designer.cs
1,136
C#
 namespace WindowsFormsApp1.Week5 { partial class Image_Processing_to_Black_And_White_ComboBox { /// <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() { this.components = new System.ComponentModel.Container(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.button3 = new System.Windows.Forms.Button(); this.imageBox1 = new Emgu.CV.UI.ImageBox(); this.imageBox2 = new Emgu.CV.UI.ImageBox(); this.imageBox3 = new Emgu.CV.UI.ImageBox(); this.comboBox1 = new System.Windows.Forms.ComboBox(); ((System.ComponentModel.ISupportInitialize)(this.imageBox1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.imageBox2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.imageBox3)).BeginInit(); this.SuspendLayout(); // // button1 // this.button1.Location = new System.Drawing.Point(743, 350); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(86, 57); this.button1.TabIndex = 0; this.button1.Text = "Open"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // button2 // this.button2.Location = new System.Drawing.Point(873, 350); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(86, 57); this.button2.TabIndex = 0; this.button2.Text = "Save"; this.button2.UseVisualStyleBackColor = true; this.button2.Click += new System.EventHandler(this.button2_Click); // // button3 // this.button3.Location = new System.Drawing.Point(1002, 350); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(86, 57); this.button3.TabIndex = 0; this.button3.Text = "Exit"; this.button3.UseVisualStyleBackColor = true; this.button3.Click += new System.EventHandler(this.button3_Click); // // imageBox1 // this.imageBox1.Location = new System.Drawing.Point(13, 13); this.imageBox1.Name = "imageBox1"; this.imageBox1.Size = new System.Drawing.Size(575, 308); this.imageBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.imageBox1.TabIndex = 2; this.imageBox1.TabStop = false; this.imageBox1.Click += new System.EventHandler(this.imageBox1_Click); // // imageBox2 // this.imageBox2.Location = new System.Drawing.Point(623, 13); this.imageBox2.Name = "imageBox2"; this.imageBox2.Size = new System.Drawing.Size(575, 308); this.imageBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.imageBox2.TabIndex = 2; this.imageBox2.TabStop = false; this.imageBox2.Click += new System.EventHandler(this.imageBox2_Click); // // imageBox3 // this.imageBox3.Location = new System.Drawing.Point(12, 336); this.imageBox3.Name = "imageBox3"; this.imageBox3.Size = new System.Drawing.Size(575, 308); this.imageBox3.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.imageBox3.TabIndex = 2; this.imageBox3.TabStop = false; this.imageBox3.Click += new System.EventHandler(this.imageBox3_Click); // // comboBox1 // this.comboBox1.Font = new System.Drawing.Font("Phetsarath OT", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.comboBox1.FormattingEnabled = true; this.comboBox1.Items.AddRange(new object[] { "Binary", "Binary Invert", "OT\'Su", "Gussian", "Mean"}); this.comboBox1.Location = new System.Drawing.Point(743, 441); this.comboBox1.Name = "comboBox1"; this.comboBox1.Size = new System.Drawing.Size(345, 41); this.comboBox1.TabIndex = 3; this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged); // // Image_Processing_to_Black_And_White_ComboBox // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1215, 655); this.Controls.Add(this.comboBox1); this.Controls.Add(this.imageBox3); this.Controls.Add(this.imageBox2); this.Controls.Add(this.imageBox1); this.Controls.Add(this.button3); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Name = "Image_Processing_to_Black_And_White_ComboBox"; this.Text = "Image_Processing_to_Black_And_White_ComboBox"; ((System.ComponentModel.ISupportInitialize)(this.imageBox1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.imageBox2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.imageBox3)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button3; private Emgu.CV.UI.ImageBox imageBox1; private Emgu.CV.UI.ImageBox imageBox2; private Emgu.CV.UI.ImageBox imageBox3; private System.Windows.Forms.ComboBox comboBox1; } }
45.210526
165
0.593423
[ "MIT" ]
mindset-tt/image_processing_Lab_Mr.Khampaserth_Xayyavong_3CS2
Image_Processing/Week5/Image_Processing_to_Black_And_White_ComboBox.Designer.cs
6,874
C#
#pragma checksum "..\..\..\MainWindow.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "CEEC98ED5C90CC9374A59CC19CB97361233AD569" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using Botkub.Desktop; using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Controls.Ribbon; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; namespace Botkub.Desktop { /// <summary> /// MainWindow /// </summary> public partial class MainWindow : System.Windows.Window, System.Windows.Markup.IComponentConnector { private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "5.0.2.0")] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Uri resourceLocater = new System.Uri("/Botkub.Desktop;V1.0.0.0;component/mainwindow.xaml", System.UriKind.Relative); #line 1 "..\..\..\MainWindow.xaml" System.Windows.Application.LoadComponent(this, resourceLocater); #line default #line hidden } [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "5.0.2.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { this._contentLoaded = true; } } }
39.116883
141
0.668659
[ "MIT" ]
zhamppx97/Botkub
src/Botkub.Desktop/obj/Debug/netcoreapp3.1/MainWindow.g.i.cs
3,014
C#
using System; using NavigationViewWinUI.ViewModels; using Windows.Media.Playback; using Windows.System.Display; using Windows.UI.Core; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace NavigationViewWinUI.Views { public sealed partial class MediaPlayerWithMarginsPage : Page { public MediaPlayerWithMarginsViewModel ViewModel { get; } = new MediaPlayerWithMarginsViewModel(); // For more on the MediaPlayer and adjusting controls and behavior see https://docs.microsoft.com/en-us/windows/uwp/controls-and-patterns/media-playback // The DisplayRequest is used to stop the screen dimming while watching for extended periods private DisplayRequest _displayRequest = new DisplayRequest(); private bool _isRequestActive = false; public MediaPlayerWithMarginsPage() { InitializeComponent(); } protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); mpe.MediaPlayer.PlaybackSession.PlaybackStateChanged += PlaybackSession_PlaybackStateChanged; } protected override void OnNavigatedFrom(NavigationEventArgs e) { base.OnNavigatedFrom(e); mpe.MediaPlayer.Pause(); mpe.MediaPlayer.PlaybackSession.PlaybackStateChanged -= PlaybackSession_PlaybackStateChanged; } private async void PlaybackSession_PlaybackStateChanged(MediaPlaybackSession sender, object args) { if (sender is MediaPlaybackSession playbackSession && playbackSession.NaturalVideoHeight != 0) { if (playbackSession.PlaybackState == MediaPlaybackState.Playing) { if (!_isRequestActive) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { _displayRequest.RequestActive(); _isRequestActive = true; }); } } else { if (_isRequestActive) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { _displayRequest.RequestRelease(); _isRequestActive = false; }); } } } } } }
36.214286
160
0.580671
[ "Apache-2.0" ]
mvegaca/PoC
WTS/ProjectType/BehaviorPoC/NavigationViewWinUI/Views/MediaPlayerWithMarginsPage.xaml.cs
2,537
C#
using System.Linq; using BenchmarkDotNet.Attributes; namespace LinqFasterer.Benchmarks.Benchmarks { public class ZipBenchmark : Benchmarkable { [Benchmark(Baseline = true)] public (int, int)[] ZipLinq() { return Data.Zip(DataSecondary).ToArray(); } [Benchmark] public (int, int)[] ZipFaster() { return Data.ZipF(DataSecondary).ToArrayF(); } } public class ZipSelectorBenchmark : Benchmarkable { [Benchmark(Baseline = true)] public int[] ZipSelectorLinq() { return Data.ToList().Zip(DataSecondary, (l, r) => l + r).ToArray(); } [Benchmark] public int[] ZipSelectorFaster() { return Data.ToList().ZipF(DataSecondary, (l, r) => l + r).ToArrayF(); } } }
24.514286
81
0.550117
[ "MIT" ]
Zaczero/LinqFaster
LinqFasterer.Benchmark/Benchmarks/ZipBenchmark.cs
860
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Net3_Proxy { public static class Extensions { public static T GetCustomAttribute<T>(this ParameterInfo element) where T : Attribute => (T)GetCustomAttribute(element, typeof(T)); public static T GetCustomAttribute<T>(this MethodInfo element) where T : Attribute => (T)GetCustomAttribute(element, typeof(T)); public static T GetCustomAttribute<T>(this ConstructorInfo element) where T : Attribute => (T)GetCustomAttribute(element, typeof(T)); public static T GetCustomAttribute<T>(this Type element) where T : Attribute => (T)GetCustomAttribute(element, typeof(T)); public static Attribute GetCustomAttribute(this MemberInfo element, Type attributeType) => Attribute.GetCustomAttribute(element, attributeType); public static Attribute GetCustomAttribute(this ConstructorInfo element, Type attributeType) => Attribute.GetCustomAttribute(element, attributeType); public static Attribute GetCustomAttribute(this ParameterInfo element, Type attributeType) => Attribute.GetCustomAttribute(element, attributeType); public static Attribute GetCustomAttribute(this Type element, Type attributeType) => Attribute.GetCustomAttribute(element, attributeType); public static StringBuilder Clear(this StringBuilder sb) => sb.Remove(0, sb.Length); public static bool HasFlag<E>(this E e, E o) where E : Enum { var ei = Convert.ToUInt64(e); var oi = Convert.ToUInt64(o); return (ei & oi) == oi; } } public static class DirectoryInfoExtensions { public static IEnumerable<FileInfo> EnumerateFiles(this DirectoryInfo self) { return self.EnumerateFiles("*", SearchOption.TopDirectoryOnly); } public static IEnumerable<FileInfo> EnumerateFiles(this DirectoryInfo self, string searchPattern) { return self.EnumerateFiles(searchPattern, SearchOption.TopDirectoryOnly); } public static IEnumerable<FileInfo> EnumerateFiles(this DirectoryInfo self, string searchPattern, SearchOption searchOption) { if (searchPattern == null) { throw new ArgumentNullException(nameof(searchPattern)); } return CreateEnumerateFilesIterator(self, searchPattern, searchOption); } private static IEnumerable<FileInfo> CreateEnumerateFilesIterator(DirectoryInfo self, string searchPattern, SearchOption searchOption) { foreach (string fileName in Directory.GetFiles(self.FullName, searchPattern, searchOption)) yield return new FileInfo(fileName); yield break; } } public static class StreamExtensions { [ComVisible(false)] [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)] public static Task CopyToAsync(this Stream src, Stream destination) => CopyToAsync(src, destination, 81920); [ComVisible(false)] [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)] public static Task CopyToAsync(this Stream src, Stream destination, int bufferSize) => CopyToAsync(src, destination, bufferSize, CancellationToken.None); [ComVisible(false)] [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)] public static Task CopyToAsync(this Stream src, Stream destination, int bufferSize, CancellationToken cancellationToken) { if (destination == null) { throw new ArgumentNullException(nameof(destination)); } if (bufferSize <= 0) { throw new ArgumentOutOfRangeException(nameof(bufferSize), "Positive number required."); } if (!src.CanRead && !src.CanWrite) { throw new ObjectDisposedException(null, "Cannot access a closed Stream."); } if (!destination.CanRead && !destination.CanWrite) { throw new ObjectDisposedException("destination", "Cannot access a closed Stream."); } if (!src.CanRead) { throw new NotSupportedException("Stream does not support reading."); } if (!destination.CanWrite) { throw new NotSupportedException("Stream does not support writing."); } return CopyToAsyncInternal(src, destination, bufferSize, cancellationToken); } private static async Task CopyToAsyncInternal(Stream src, Stream destination, int bufferSize, CancellationToken cancellationToken) { byte[] buffer = new byte[bufferSize]; int bytesRead; while ((bytesRead = await src.ReadAsync(buffer, 0, buffer.Length, cancellationToken)) != 0) { await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken); } } [ComVisible(false)] [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)] public static Task<int> ReadAsync(this Stream src, byte[] buffer, int offset, int count) { return ReadAsync(src, buffer, offset, count, CancellationToken.None); } [ComVisible(false)] [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)] public static Task<int> ReadAsync(this Stream src, byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (!cancellationToken.IsCancellationRequested) { return BeginEndReadAsync(src, buffer, offset, count); } return new Task<int>(() => 0, cancellationToken); } private static Task<int> BeginEndReadAsync(Stream src, byte[] buffer, int offset, int count) => Task<int>.Factory.FromAsync( (byte[] buffer_, int offset_, int count_, AsyncCallback callback, object state) => src.BeginRead(buffer_, offset_, count_, callback, state), (IAsyncResult asyncResult) => src.EndRead(asyncResult), buffer, offset, count, new object()); [ComVisible(false)] [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)] public static Task WriteAsync(this Stream src, byte[] buffer, int offset, int count) { return WriteAsync(src, buffer, offset, count, CancellationToken.None); } [ComVisible(false)] [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)] public static Task WriteAsync(this Stream src, byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (!cancellationToken.IsCancellationRequested) { return BeginEndWriteAsync(src, buffer, offset, count); } return new Task<int>(() => 0, cancellationToken); } private static Task BeginEndWriteAsync(Stream src, byte[] buffer, int offset, int count) => Task.Factory.FromAsync( (byte[] buffer_, int offset_, int count_, AsyncCallback callback, object state) => src.BeginWrite(buffer_, offset_, count_, callback, state), (IAsyncResult asyncResult) => src.EndWrite(asyncResult), buffer, offset, count, new object()); } public static class SemaphoreSlimExtesnions { // TODO: finish the WaitAsync members /*public static Task WaitAsync(this SemaphoreSlim self) { return null; }*/ } }
43.453125
162
0.618602
[ "MIT" ]
aokiyusuke/BeatSaber-IPA-Reloaded
Net3-Proxy/Extensions.cs
8,345
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using HotChocolate.Configuration.Bindings; using HotChocolate.Properties; using HotChocolate.Resolvers; using HotChocolate.Types; using HotChocolate.Types.Descriptors; namespace HotChocolate.Configuration { internal class BindingCompiler : IBindingCompiler { private readonly HashSet<Type> _supportedBindings = new() { typeof(ComplexTypeBindingInfo), typeof(ResolverBindingInfo), typeof(ResolverTypeBindingInfo), }; private readonly List<IBindingInfo> _bindings = new(); public bool CanHandle(IBindingInfo binding) { return binding != null && _supportedBindings.Contains(binding.GetType()); } public void AddBinding(IBindingInfo binding) { if (binding is null) { throw new ArgumentNullException(nameof(binding)); } if (!CanHandle(binding)) { throw new ArgumentException( TypeResources.BindingCompiler_AddBinding_BindingCannotBeHandled, nameof(binding)); } _bindings.Add(binding); } public IBindingLookup Compile( IDescriptorContext descriptorContext) { if (descriptorContext is null) { throw new ArgumentNullException(nameof(descriptorContext)); } CompleteComplexTypeBindings(descriptorContext.Naming); CompleteResolverTypeBindings(descriptorContext.TypeInspector, descriptorContext.Naming); CompleteResolverBindings(descriptorContext.Naming); IEnumerable<TypeBindingInfo> bindings = CreateTypeBindingInfos(descriptorContext); return new BindingLookup(descriptorContext, bindings); } private void CompleteComplexTypeBindings( INamingConventions naming) { foreach (ComplexTypeBindingInfo binding in _bindings.OfType<ComplexTypeBindingInfo>()) { if (binding.Name.IsEmpty) { binding.Name = naming.GetTypeName(binding.Type); } foreach (ComplexTypeFieldBindingInfo field in binding.Fields) { if (field.Name.IsEmpty) { field.Name = naming.GetMemberName( field.Member, MemberKind.Field); } } } } private void CompleteResolverTypeBindings( ITypeInspector inspector, INamingConventions naming) { foreach (ResolverTypeBindingInfo binding in _bindings.OfType<ResolverTypeBindingInfo>() .ToList()) { ComplexTypeBindingInfo typeBinding; binding.SourceType ??= typeof(object); if (binding.SourceType != null && binding.TypeName.IsEmpty) { typeBinding = _bindings.OfType<ComplexTypeBindingInfo>() .FirstOrDefault(t => t.Type == binding.SourceType); if (typeBinding is null) { binding.TypeName = naming.GetTypeName( binding.SourceType, TypeKind.Object); } else { binding.TypeName = typeBinding.Name; } } typeBinding = _bindings.OfType<ComplexTypeBindingInfo>() .FirstOrDefault(t => t.Name.Equals(binding.TypeName)); if (typeBinding is null) { _bindings.Add(new ComplexTypeBindingInfo { Name = binding.TypeName, Type = binding.SourceType }); } else if (binding.SourceType == typeof(object)) { binding.SourceType = typeBinding.Type; } foreach (ResolverFieldBindingInfo field in binding.Fields) { if (field.FieldName.IsEmpty) { field.FieldName = naming.GetMemberName( field.FieldMember, MemberKind.ObjectField); } } if (binding.BindingBehavior == BindingBehavior.Implicit) { AddImplicitResolverBindings(inspector, naming, binding); } } } private static void AddImplicitResolverBindings( ITypeInspector inspector, INamingConventions naming, ResolverTypeBindingInfo binding) { var names = new HashSet<NameString>( binding.Fields.Select(t => t.FieldName)); foreach (MemberInfo member in inspector.GetMembers(binding.ResolverType)) { NameString fieldName = naming.GetMemberName(member, MemberKind.ObjectField); if (names.Add(fieldName)) { var builder = ResolverFieldBindingBuilder.New(); builder.SetResolver(member); builder.SetField(fieldName); binding.Fields = binding.Fields.Add(builder.Create()); } } } private void CompleteResolverBindings(INamingConventions naming) { foreach (ResolverBindingInfo binding in _bindings.OfType<ResolverBindingInfo>() .ToList()) { if (binding.TypeName.IsEmpty) { ComplexTypeBindingInfo typeBinding = _bindings.OfType<ComplexTypeBindingInfo>() .FirstOrDefault(t => t.Type == binding.SourceType); binding.TypeName = typeBinding?.Name ?? naming.GetTypeName(binding.SourceType); } if (binding.FieldName.IsEmpty) { binding.FieldName = naming.GetMemberName( binding.Member, MemberKind.ObjectField); } if (!_bindings.OfType<ComplexTypeBindingInfo>() .Any(t => t.Name.Equals(binding.TypeName))) { _bindings.Add(new ComplexTypeBindingInfo { Name = binding.TypeName, Type = binding.SourceType }); } } } private IEnumerable<TypeBindingInfo> CreateTypeBindingInfos( IDescriptorContext context) { var bindings = new List<TypeBindingInfo>(); foreach (ComplexTypeBindingInfo binding in _bindings.OfType<ComplexTypeBindingInfo>()) { bindings.Add(CreateTypeBindingInfo(context, binding)); } return bindings; } private TypeBindingInfo CreateTypeBindingInfo( IDescriptorContext context, ComplexTypeBindingInfo binding) { var registeredResolvers = new Dictionary<NameString, RegisteredResolver>(); var members = new Dictionary<NameString, MemberInfo>(); RegisterResolvers(binding, registeredResolvers); foreach (ResolverTypeBindingInfo resolverBinding in _bindings.OfType<ResolverTypeBindingInfo>() .Where(t => t.TypeName.Equals(binding.Name))) { RegisterResolverFields( binding.Name, resolverBinding, registeredResolvers, members); } RegisterFields(binding, registeredResolvers, members); return new TypeBindingInfo( context, binding.Name, binding.Type, binding.BindingBehavior, registeredResolvers, members); } private static void RegisterResolverFields( NameString typeName, ResolverTypeBindingInfo resolverBinding, IDictionary<NameString, RegisteredResolver> registeredResolvers, IDictionary<NameString, MemberInfo> members) { foreach (ResolverFieldBindingInfo field in resolverBinding.Fields) { if (!registeredResolvers.ContainsKey(field.FieldName)) { IFieldReference fieldReference = field.ResolverMember is null ? (IFieldReference)new FieldResolver( typeName, field.FieldName, field.ResolverDelegate) : new FieldMember( typeName, field.FieldName, field.ResolverMember); registeredResolvers.Add(field.FieldName, new RegisteredResolver( resolverBinding.ResolverType, resolverBinding.SourceType, fieldReference)); } if (!members.ContainsKey(field.FieldName)) { members.Add(field.FieldName, field.FieldMember); } } } private void RegisterResolvers( ComplexTypeBindingInfo binding, IDictionary<NameString, RegisteredResolver> registeredResolvers) { foreach (ResolverBindingInfo resolver in _bindings.OfType<ResolverBindingInfo>() .Where(t => t.TypeName.Equals(binding.Name))) { if (!registeredResolvers.ContainsKey(resolver.FieldName)) { registeredResolvers.Add(resolver.FieldName, new RegisteredResolver( null, binding.Type ?? typeof(object), new FieldResolver( binding.Name, resolver.FieldName, resolver.Resolver))); } } } private static void RegisterFields( ComplexTypeBindingInfo binding, Dictionary<NameString, RegisteredResolver> registeredResolvers, Dictionary<NameString, MemberInfo> members) { foreach (ComplexTypeFieldBindingInfo field in binding.Fields) { if (!members.ContainsKey(field.Name) && !members.ContainsValue(field.Member)) { members.Add(field.Name, field.Member); if (!registeredResolvers.ContainsKey(field.Name)) { registeredResolvers.Add(field.Name, new RegisteredResolver( binding.Type, binding.Type, new FieldMember( binding.Name, field.Name, field.Member))); } } } } } }
36.048632
100
0.500253
[ "MIT" ]
BaptisteGirard/hotchocolate
src/HotChocolate/Core/src/Types/Configuration/BindingCompiler.cs
11,860
C#
using Chinese.Options; using NStandard; using System; using System.Text.RegularExpressions; namespace Chinese { public static class ChineseCurrency { private static readonly string[] UpperLevels = new[] { "圆", "角", "分" }; private static readonly string[] LowerLevels = new[] { "元", "角", "分" }; /// <summary> /// 获取数值的货币读法。 /// </summary> /// <param name="money"></param> /// <returns></returns> public static string GetString(decimal money) => GetString(money, ChineseNumberOptions.Default); /// <summary> /// 获取数值的货币读法。 /// </summary> /// <param name="money"></param> /// <param name="setOptions"></param> /// <returns></returns> public static string GetString(decimal money, Action<ChineseNumberOptions> setOptions) { var options = new ChineseNumberOptions(); setOptions(options); return GetString(money, options); } /// <summary> /// 获取数值的货币读法。 /// </summary> /// <param name="money"></param> /// <param name="options"></param> /// <returns></returns> public static string GetString(decimal money, ChineseNumberOptions options) { var fractional100 = (int)(money % 1 * 100 % 100); string[] numberValues; string[] levels; if (options.Upper) { numberValues = ChineseNumber.UpperNumberValues; levels = UpperLevels; } else { numberValues = ChineseNumber.LowerNumberValues; levels = LowerLevels; } var yuan = ChineseNumber.GetString(money, options); string ret; if (fractional100 == 0) ret = $"{yuan}{levels[0]}整"; else if (fractional100 % 10 == 0) ret = $"{yuan}{levels[0]}{numberValues[fractional100 / 10]}{levels[1]}整"; else { var jiao = fractional100 / 10; ret = $"{yuan}{levels[0]}{(jiao > 0 ? $"{numberValues[jiao]}{levels[1]}" : numberValues[0])}{numberValues[fractional100 % 10]}{levels[2]}"; } return ret; } /// <summary> /// 获取货币读法的数值。 /// </summary> /// <param name="chineseCurrency"></param> /// <returns></returns> public static decimal GetNumber(string chineseCurrency) { var regex = new Regex(@"(.+)(?:圆|元)(?:整|(.)角整|(.)角(.)分|零(.)分)"); var match = regex.Match(chineseCurrency); if (!match.Success) throw new ArgumentException("不是合法的中文货币描述。"); var yuan = match.Groups[1].Value.For(x => ChineseNumber.GetNumber(x)); var jiao = (match.Groups[2].Value.For(x => x.IsWhiteSpace() ? null : x) ?? match.Groups[3].Value.For(x => x.IsWhiteSpace() ? null : x)) ?.For(x => ChineseNumber.GetNumber(x)) ?? 0m; var fen = (match.Groups[4].Value.For(x => x.IsWhiteSpace() ? null : x) ?? match.Groups[5].Value.For(x => x.IsWhiteSpace() ? null : x)) ?.For(x => ChineseNumber.GetNumber(x)) ?? 0m; return yuan + (jiao * 0.1m) + (fen * 0.01m); } } }
35.913978
155
0.515569
[ "MIT" ]
Kaven-Fork/Chinese
Chinese/ChineseCurrency.cs
3,480
C#
using System; using System.Linq; using System.Threading.Tasks; using Windows.UI.Core; using Windows.UI.Xaml.Controls; namespace AllJoynVoice { class Setup { private static readonly int MSEC_WAIT_FOR_SPEECH_OUTPUT = 5000; static private bool ledAvailable = false; public async static Task Start(CoreDispatcher uiDispatcher, MediaElement audioMedia) { try { LEDController.Init(); LEDController.TurnOn(StatusLED.Idle); ledAvailable = true; } catch { // Ignore if LED control is not availale ledAvailable = false; } Task configReady = Config.Load(); // ----- Logger.LogInfo("Setting up speech synthesizer."); EasySpeechSynthesizer synthesizer = new EasySpeechSynthesizer(uiDispatcher, audioMedia); if (ledAvailable) { synthesizer.StartedSpeaking += () => LEDController.TurnOn(StatusLED.Speaking); synthesizer.StoppedSpeaking += () => LEDController.TurnOff(StatusLED.Speaking); } synthesizer.StartSpeaking(); // ----- Logger.LogInfo("Waiting for the configuration to be loaded."); try { await configReady; } catch (Exception ex) { await synthesizer.ClearQueue(); await synthesizer.Speak("Something went wrong... Couldn't load the config file."); await Task.Delay(MSEC_WAIT_FOR_SPEECH_OUTPUT); Logger.LogException("Setup", ex); throw; } // ----- Config.Notifier.OnNotification += async s => await synthesizer.Speak(s); // ----- Logger.LogInfo("Setting up speech recognition."); CodewordSpeechRecognizer speechRecognizer = null; try { speechRecognizer = new CodewordSpeechRecognizer(Config.Codeword, Config.Actions); await speechRecognizer.CompileConstraintsAsync(); if (ledAvailable) { speechRecognizer.StateChanged += state => { if (state == CodewordSpeechRecognizerState.Idle) { LEDController.TurnOn(StatusLED.Idle); LEDController.TurnOff(StatusLED.Listening); } else if (state == CodewordSpeechRecognizerState.Listening) { LEDController.TurnOff(StatusLED.Idle); LEDController.TurnOn(StatusLED.Listening); } }; } speechRecognizer.WordRecognized += async word => { try { Logger.LogInfo("Executing action: " + word); Task actionTask = Config.Actions.First(x => x.Id == word).RunAsync(); // Stop speaking and clear the queue when something is recognized. await synthesizer.ClearQueue(); await actionTask; await synthesizer.Speak("Done!"); } catch (InvalidOperationException ex) { await synthesizer.Speak("Something went wrong..."); await synthesizer.Speak(ex.Message); Logger.LogException(word, ex); }; }; await speechRecognizer.StartAsync(); } catch (Exception ex) { await synthesizer.StopSpeaking(); synthesizer.StartSpeaking(); await synthesizer.Speak("Something went wrong... Couldn't start speech recognition."); await Task.Delay(MSEC_WAIT_FOR_SPEECH_OUTPUT); Logger.LogException("Setup: SpeechRecognizer", ex); throw; } } } }
33.061538
102
0.491159
[ "MIT" ]
2swathi/samples
AllJoyn/Samples/AllJoynVoice/AllJoynVoice/Source Files/Setup.cs
4,300
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; namespace BMW.Frameworks.JsonHelper { public class JsonGridData { public long total { get; set; } public IEnumerable data { get; set; } } }
18.866667
45
0.689046
[ "Apache-2.0" ]
gongzhw/BmwTools
BMW.Frameworks/JsonHelper/JsonGirdData.cs
285
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace printServer.actions { class Action { protected static void WriteToResponseStream(HttpListenerResponse response, string data) { byte[] buffer = System.Text.Encoding.UTF8.GetBytes(data); response.ContentLength64 = buffer.Length; System.IO.Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); } public virtual void Run(HttpListenerRequest request, HttpListenerResponse response, Form1 frm) { throw new NotImplementedException(); } } }
30.304348
143
0.698709
[ "MIT" ]
AsafY/Crosphera-Local-Print-Server
printServer/actions/Action.cs
699
C#
using System; using System.Collections.Generic; using System.ComponentModel; using NewLife.Cube; using NewLife.Web; using xLink.Entity; namespace xLink.Web.Areas.Devices.Controllers { [DevicesArea] [DisplayName("子设备")] public class SubDeviceController : EntityController<SubDevice> { static SubDeviceController() => MenuOrder = 58; protected override IEnumerable<SubDevice> Search(Pager p) { var deviceId = p["deviceId"].ToInt(-1); var productId = p["productId"].ToInt(-1); var enable = p["enable"]?.ToBoolean(); var start = p["dtStart"].ToDateTime(); var end = p["dtEnd"].ToDateTime(); return SubDevice.Search(deviceId, productId, enable, start, end, p["Q"], p); } } }
27.551724
88
0.624531
[ "MIT" ]
NewLifeX/XLink
xLink.Web/Areas/Devices/Controllers/SubDeviceController.cs
807
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using SharedService; using System; using System.IO; using PictureStorage.SQL.Contexts; using SharedService.Configuration; namespace PictureService { class Program { static void Main(string[] args) { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddEnvironmentVariables(); var configuration = builder.Build(); string secret = configuration.GetSection("secret").Value; string defaultConnection = configuration.GetConnectionString("DefaultConnection"); Bootstrapper.RegisterSingleton(new AppSettings(secret)); Bootstrapper.RegisterSingleton(new PictureContext(defaultConnection)); new HostBuilder<Startup>("http://*:8888").Run(); } } }
28.125
85
0.746667
[ "MIT" ]
Monnick/Bequest
BackEnd/Bequest/PictureManagement/PictureService/Program.cs
902
C#
/* * Copyright (c) 2014, Firely (info@fire.ly) and contributors * See the file CONTRIBUTORS for details. * * This file is licensed under the BSD 3-Clause license * available at https://raw.githubusercontent.com/FirelyTeam/firely-net-sdk/master/LICENSE */ using Hl7.Fhir.Model; using Hl7.Fhir.Serialization; using Hl7.Fhir.Specification.Source; using Hl7.Fhir.Utility; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using T = System.Threading.Tasks; using ssac = System.Security.AccessControl; namespace Hl7.Fhir.Specification.Tests { [TestClass] public class ArtifactSourceTests { private static string _testPath; [ClassInitialize] public static void SetupExampleDir(TestContext _) { _testPath = prepareExampleDirectory(out int _); } private static string prepareExampleDirectory(out int numFiles) { var zipFile = Path.Combine(Directory.GetCurrentDirectory(), "specification.zip"); var zip = new ZipCacher(zipFile); var zipPath = zip.GetContentDirectory(); var testPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(testPath); copy(zipPath, "extension-definitions.xml", testPath); copy(zipPath, "flag.xsd", testPath); copy(zipPath, "patient.sch", testPath); copy(@"TestData", "TestPatient.xml", testPath); File.WriteAllText(Path.Combine(testPath, "bla.dll"), "This is text, acting as a dll"); File.WriteAllText(Path.Combine(testPath, "nonfhir.xml"), "<root>this is not a valid FHIR xml resource.</root>"); File.WriteAllText(Path.Combine(testPath, "invalid.xml"), "<root>this is invalid xml"); var subPath = Path.Combine(testPath, "sub"); Directory.CreateDirectory(subPath); copy(@"TestData", "TestPatient.json", subPath); // If you add or remove files, please correct the numFiles here below numFiles = 8 - 1; // 8 files - 1 binary (which should be ignored) return testPath; } private static void copy(string dir, string file, string outputDir) { File.Copy(Path.Combine(dir, file), Path.Combine(outputDir, file)); } [TestMethod] public void ZipCacherShouldCache() { var cacheKey = Guid.NewGuid().ToString(); var zipFile = Path.Combine(Directory.GetCurrentDirectory(), "specification.zip"); var fa = new ZipCacher(zipFile, cacheKey); Assert.IsFalse(fa.IsActual()); var sw = new Stopwatch(); sw.Start(); fa.GetContents(); sw.Stop(); var firstRun = sw.ElapsedMilliseconds; Assert.IsTrue(fa.IsActual()); sw.Restart(); fa.GetContents(); sw.Stop(); var secondRun = sw.ElapsedMilliseconds; Assert.IsTrue(firstRun > secondRun); fa = new ZipCacher(zipFile, cacheKey); Assert.IsTrue(fa.IsActual()); sw.Start(); fa.GetContents(); sw.Stop(); var thirdRun = sw.ElapsedMilliseconds; Assert.IsTrue(thirdRun < firstRun); fa.Clear(); Assert.IsFalse(fa.IsActual()); sw.Restart(); fa.GetContents(); sw.Stop(); var fourthRun = sw.ElapsedMilliseconds; Assert.IsTrue(fourthRun > secondRun); // Something fishy going on here. // if I do not wait before the statement File.SetLastWriteTimeUtc fa.IsActual returns true Thread.Sleep(500); File.SetLastWriteTimeUtc(zipFile, DateTimeOffset.UtcNow.DateTime); Assert.IsFalse(fa.IsActual()); } [TestMethod] public void UseFileArtifactSource() { var fa = new DirectorySource(_testPath) { Mask = "*.xml|*.xsd" }; var names = fa.ListArtifactNames(); Assert.AreEqual(5, names.Count()); Assert.IsTrue(names.Contains("extension-definitions.xml")); Assert.IsTrue(names.Contains("flag.xsd")); Assert.IsFalse(names.Contains("patient.sch")); Assert.IsTrue(names.Contains("TestPatient.xml")); Assert.IsTrue(names.Contains("nonfhir.xml")); Assert.IsTrue(names.Contains("invalid.xml")); using (var stream = fa.LoadArtifactByName("TestPatient.xml")) { var pat = new FhirXmlParser().Parse<Resource>(SerializationUtil.XmlReaderFromStream(stream)); Assert.IsNotNull(pat); } } [TestMethod] public void UseIncludeExcludeFilter() { var fa = new DirectorySource(_testPath) { Includes = new[] { "*.xml", "pa*.sch" }, Excludes = new[] { "nonfhir*.*" } }; var names = fa.ListArtifactNames(); Assert.AreEqual(4, names.Count()); Assert.IsTrue(names.Contains("extension-definitions.xml")); Assert.IsTrue(names.Contains("TestPatient.xml")); Assert.IsFalse(names.Contains("nonfhir.xml")); Assert.IsTrue(names.Contains("invalid.xml")); Assert.IsTrue(names.Contains("patient.sch")); } [TestMethod] public void ExcludeSubdirectory() { var fa = new DirectorySource(_testPath) { Includes = new[] { "*.json" }, IncludeSubDirectories = true }; var names = fa.ListArtifactNames(); Assert.AreEqual(1, names.Count()); fa.Excludes = new[] { "/sub/" }; names = fa.ListArtifactNames(); Assert.AreEqual(0, names.Count()); } [TestMethod] public async T.Task FileSourceSkipsInvalidXml() { var fa = new DirectorySource(_testPath) { Mask = "*.xml" }; var names = fa.ListArtifactNames(); Assert.AreEqual(4, names.Count()); Assert.IsTrue(names.Contains("extension-definitions.xml")); Assert.IsTrue(names.Contains("TestPatient.xml")); Assert.IsTrue(names.Contains("nonfhir.xml")); Assert.IsTrue(names.Contains("invalid.xml")); //[WMR 20171020] TODO: Use ArtifactSummary.Error //Assert.AreEqual(0, fa.Errors.Length); // Call a method on the IConformanceSource interface to trigger prepareResources var sd = await fa.FindStructureDefinitionAsync("http://hl7.org/fhir/StructureDefinition/patient-birthTime"); Assert.IsNotNull(sd); var errors = fa.ListSummaryErrors().ToList(); Assert.AreEqual(1, errors.Count); var error = errors[0]; Debug.Print($"Error in file '{error.Origin}': {error.Error.Message}"); Assert.AreEqual("invalid.xml", Path.GetFileName(error.Origin)); } [TestMethod] public void FileSourceSkipsExecutables() { var fa = new DirectorySource(_testPath); Assert.IsFalse(fa.ListArtifactNames().Any(name => name.EndsWith(".dll"))); Assert.IsFalse(fa.ListArtifactNames().Any(name => name.EndsWith(".exe"))); } [TestMethod] public void ReadsSubdirectories() { var testPath = prepareExampleDirectory(out int numFiles); var fa = new DirectorySource(testPath, new DirectorySourceSettings() { IncludeSubDirectories = true }); var names = fa.ListArtifactNames(); Assert.AreEqual(numFiles, names.Count()); Assert.IsTrue(names.Contains("TestPatient.json")); } [TestMethod] public void GetSomeBundledArtifacts() { var za = ZipSource.CreateValidationSource(); using (var a = za.LoadArtifactByName("patient.sch")) { Assert.IsNotNull(a); } using (var a = za.LoadArtifactByName("v3-codesystems.xml")) { Assert.IsNotNull(a); } using (var a = za.LoadArtifactByName("patient.xsd")) { Assert.IsNotNull(a); } } [TestMethod] public void TestZipSourceMask() { var zipFile = Path.Combine(Directory.GetCurrentDirectory(), "specification.zip"); Assert.IsTrue(File.Exists(zipFile), "Error! specification.zip is not available."); var za = new ZipSource(zipFile) { Mask = "profiles-types.xml" }; var artifacts = za.ListArtifactNames().ToArray(); Assert.AreEqual(1, artifacts.Length); Assert.AreEqual("profiles-types.xml", artifacts[0]); var resourceIds = za.ListResourceUris(ResourceType.StructureDefinition).ToList(); Assert.IsNotNull(resourceIds); Assert.IsTrue(resourceIds.Count > 0); Assert.IsTrue(resourceIds.All(url => url.StartsWith("http://hl7.org/fhir/StructureDefinition/"))); resourceIds.Remove("http://hl7.org/fhir/StructureDefinition/SimpleQuantity"); resourceIds.Remove("http://hl7.org/fhir/StructureDefinition/MoneyQuantity"); // + total number of known FHIR core types // - total number of known (concrete) resources // - 1 for abstract type Resource // - 1 for abstract type DomainResource // - 4 for abstract R5 base types not present as R3 structuredefs // ======================================= // total number of known FHIR (complex & primitive) datatypes var coreDataTypes = ModelInfo.FhirCsTypeToString.Where(kvp => !ModelInfo.IsKnownResource(kvp.Key) && kvp.Value != "Resource" && kvp.Value != "DomainResource" && kvp.Value != "BackboneType" && kvp.Value != "Base" && kvp.Value != "DataType" && kvp.Value != "PrimitiveType" ) .Select(kvp => kvp.Value); var numCoreDataTypes = coreDataTypes.Count(); Assert.AreEqual(resourceIds.Count, numCoreDataTypes); // Assert.IsTrue(resourceIds.All(url => ModelInfo.CanonicalUriForFhirCoreType)); var coreTypeUris = coreDataTypes.Select(typeName => ModelInfo.CanonicalUriForFhirCoreType(typeName)).ToArray(); // Boths arrays should contains same urls, possibly in different order Assert.AreEqual(coreTypeUris.Length, resourceIds.Count); Assert.IsTrue(coreTypeUris.All(url => resourceIds.Contains(url))); Assert.IsTrue(resourceIds.All(url => coreTypeUris.Contains(url))); } // [WMR 20170817] NEW // https://github.com/FirelyTeam/firely-net-sdk/issues/410 // DirectorySource should gracefully handle insufficient access permissions // i.e. silently ignore all inaccessible files & folders // Can we modify access permissions on the CI build environment...? [TestMethod, TestCategory("IntegrationTest")] public void TestAccessPermissions() { var testPath = prepareExampleDirectory(out int numFiles); // Additional temporary folder without read permissions var subPath2 = Path.Combine(testPath, "sub2"); var forbiddenDir = Directory.CreateDirectory(subPath2); // Additional temporary folder with ordinary permissions var subPath3 = Path.Combine(testPath, "sub3"); Directory.CreateDirectory(subPath3); string srcPath = Path.Combine("TestData", "snapshot-test", "WMR"); const string srcFile1 = "MyBasic.structuredefinition.xml"; const string srcFile2 = "MyBundle.structuredefinition.xml"; const string profileUrl1 = @"http://example.org/fhir/StructureDefinition/MyBasic"; const string profileUrl2 = @"http://example.org/fhir/StructureDefinition/MyBundle"; // Create test file in inaccessible subfolder; should be ignored copy(srcPath, srcFile1, subPath2); // Create hidden test file in accessible subfolder; should also be ignored copy(srcPath, srcFile1, subPath3); var filePath = Path.Combine(subPath3, srcFile1); var attr = File.GetAttributes(filePath); File.SetAttributes(filePath, attr | FileAttributes.Hidden); // Create regular test file in accessible subfolder; should be included copy(srcPath, srcFile2, subPath3); numFiles++; bool initialized = false; try { // Abort unit test if we can't access folder permissions var ds = forbiddenDir.GetAccessControl(); // Revoke folder read permissions for the current user string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; var rule = new ssac.FileSystemAccessRule(userName, ssac.FileSystemRights.Read, ssac.AccessControlType.Deny); ds.AddAccessRule(rule); Debug.Print($"Removing read permissions from folder: '{subPath2}' ..."); // Abort unit test if we can't modify file permissions forbiddenDir.SetAccessControl(ds); try { var forbiddenFile = new FileInfo(Path.Combine(subPath2, srcFile1)); // Abort unit test if we can't access file permissions var fs = forbiddenFile.GetAccessControl(); // Revoke file read permissions for the current user fs.AddAccessRule(rule); Debug.Print($"Removing read permissions from fole: '{forbiddenFile}' ..."); // Abort unit test if we can't modify file permissions forbiddenFile.SetAccessControl(fs); initialized = true; try { // Note: we still have write permissions... var dirSource = new DirectorySource(testPath, new DirectorySourceSettings() { IncludeSubDirectories = true }); // [WMR 20170823] Test ListArtifactNames => prepareFiles() var names = dirSource.ListArtifactNames(); Assert.AreEqual(numFiles, names.Count()); Assert.IsFalse(names.Contains(srcFile1)); Assert.IsTrue(names.Contains(srcFile2)); // [WMR 20170823] Also test ListResourceUris => prepareResources() var profileUrls = dirSource.ListResourceUris(ResourceType.StructureDefinition); // Materialize the sequence var urlList = profileUrls.ToList(); Assert.IsFalse(urlList.Contains(profileUrl1)); Assert.IsTrue(urlList.Contains(profileUrl2)); } // API *should* grafecully handle security exceptions catch (UnauthorizedAccessException ex) { Assert.Fail($"Failed! Unexpected UnauthorizedAccessException: {ex.Message}"); } finally { var result = fs.RemoveAccessRule(rule); Assert.IsTrue(result); Debug.Print($"Restoring file read permissions..."); forbiddenFile.SetAccessControl(fs); Debug.Print($"Succesfully restored file read permissions."); // We should be able to delete the file File.Delete(forbiddenFile.FullName); } } finally { var result = ds.RemoveAccessRule(rule); Assert.IsTrue(result); Debug.Print($"Restoring folder read permissions..."); forbiddenDir.SetAccessControl(ds); Debug.Print($"Succesfully restored folder read permissions."); // We should be able to delete the subdirectory Directory.Delete(subPath2, true); } } // If acl initialization failed, then consume the exception and return success // Preferably, skip this unit test / return unknown result - how? catch (Exception ex) when (!initialized) { Debug.Print($"[{nameof(TestAccessPermissions)}] Could not modify directory access permissions: '{ex.Message}'. Skip unit test..."); } } // LoadByName should handle duplicate filenames in (different subfolders of) the contentdirectory // https://github.com/FirelyTeam/firely-net-sdk/issues/875 [TestMethod] public void OpenDuplicateFileNames() { var testPath = prepareExampleDirectory(out int _); // Additional temporary folder without read permissions const string subFolderName = "sub"; var fullSubFolderPath = Path.Combine(testPath, subFolderName); Directory.CreateDirectory(fullSubFolderPath); string srcPath = Path.Combine("TestData", "snapshot-test", "WMR"); const string srcFile = "MyBasic.structuredefinition.xml"; // Create duplicate files in content directory and subfolder copy(srcPath, srcFile, testPath); copy(srcPath, srcFile, fullSubFolderPath); var dirSource = new DirectorySource(testPath, new DirectorySourceSettings() { IncludeSubDirectories = true }); Resource OpenStream(string filePath) { using (var stream = dirSource.LoadArtifactByName(filePath)) { return new FhirXmlParser().Parse<Resource>(SerializationUtil.XmlReaderFromStream(stream)); } } // Retrieve artifacts by full path var rootFilePath = Path.Combine(testPath, srcFile); Assert.IsTrue(File.Exists(rootFilePath)); var res = OpenStream(rootFilePath); Assert.IsNotNull(res); // Modify the resource id and save back var dupId = res.Id; var rootId = Guid.NewGuid().ToString(); res.Id = rootId; _ = new FhirXmlSerializer().SerializeToString(res); var dupFilePath = Path.Combine(fullSubFolderPath, srcFile); Assert.IsTrue(File.Exists(dupFilePath)); res = OpenStream(dupFilePath); Assert.IsNotNull(res); // Verify that we received the duplicate file from subfolder, // not the modified file in the root content directory Assert.AreEqual(dupId, res.Id); Assert.AreNotEqual(rootId, res.Id); // Retrieve artifact by file name // Should return nearest match, i.e. from content directory res = OpenStream(srcFile); Assert.IsNotNull(res); Assert.AreEqual(dupId, res.Id); // Retrieve artifact by relative path // Should return duplicate from subfolder var relPath = Path.Combine(subFolderName, srcFile); res = OpenStream(relPath); Assert.IsNotNull(res); Assert.AreEqual(dupId, res.Id); } } }
41.443548
147
0.560664
[ "BSD-3-Clause" ]
Influential-Software/firely-net-sdk
src/Hl7.Fhir.Specification.Tests/Source/ArtifactSourceTests.cs
20,558
C#
// // System.Reflection.Assembly Test Cases // // Authors: // Gonzalo Paniagua Javier (gonzalo@ximian.com) // Philippe Lavoie (philippe.lavoie@cactus.ca) // Sebastien Pouliot (sebastien@ximian.com) // // (c) 2003 Ximian, Inc. (http://www.ximian.com) // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using NUnit.Framework; using System; using System.Configuration.Assemblies; using System.Globalization; using System.IO; using System.Reflection; #if !MONOTOUCH using System.Reflection.Emit; #endif using System.Threading; using System.Runtime.Serialization; using System.Security; using System.Linq; namespace MonoTests.System.Reflection { [TestFixture] public class AssemblyTest { static string TempFolder = Path.Combine (Path.GetTempPath (), "MonoTests.System.Reflection.AssemblyTest"); [SetUp] public void SetUp () { while (Directory.Exists (TempFolder)) TempFolder = Path.Combine (TempFolder, "2"); Directory.CreateDirectory (TempFolder); } [TearDown] public void TearDown () { try { // This throws an exception under MS.NET, since the directory contains loaded // assemblies. Directory.Delete (TempFolder, true); } catch (Exception) { } } [Test] public void CreateInstance() { Type type = typeof (AssemblyTest); Object obj = type.Assembly.CreateInstance ("MonoTests.System.Reflection.AssemblyTest"); Assert.IsNotNull (obj, "#01"); Assert.AreEqual (GetType (), obj.GetType (), "#02"); } [Test] public void CreateInvalidInstance() { Type type = typeof (AssemblyTest); Object obj = type.Assembly.CreateInstance("NunitTests.ThisTypeDoesNotExist"); Assert.IsNull (obj, "#03"); } [Test] // bug #49114 [Category ("NotWorking")] [ExpectedException (typeof (ArgumentException))] public void GetType_TypeName_Invalid () { typeof (int).Assembly.GetType ("&blabla", true, true); } [Test] // bug #334203 public void GetType_TypeName_AssemblyName () { Assembly a = typeof (int).Assembly; string typeName = typeof (string).AssemblyQualifiedName; try { a.GetType (typeName, true, false); Assert.Fail ("#A1"); } catch (ArgumentException ex) { Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#A2"); Assert.IsNull (ex.InnerException, "#A3"); Assert.IsNotNull (ex.Message, "#A4"); Assert.IsNull (ex.ParamName, "#A5"); } Type type = a.GetType (typeName, false); Assert.IsNull (type, "#B1"); type = a.GetType (typeName, false, true); Assert.IsNull (type, "#B2"); } [Test] public void GetEntryAssembly () { // note: only available in default appdomain // http://weblogs.asp.net/asanto/archive/2003/09/08/26710.aspx // Not sure we should emulate this behavior. string fname = AppDomain.CurrentDomain.FriendlyName; if (fname.EndsWith (".dll")) { // nunit-console Assert.IsNull (Assembly.GetEntryAssembly (), "GetEntryAssembly"); Assert.IsFalse (AppDomain.CurrentDomain.IsDefaultAppDomain (), "!default appdomain"); } else { // gnunit Assert.IsNotNull (Assembly.GetEntryAssembly (), "GetEntryAssembly"); Assert.IsTrue (AppDomain.CurrentDomain.IsDefaultAppDomain (), "!default appdomain"); } } #if !MONOTOUCH // Reflection.Emit is not supported. [Test] public void GetModules_MissingFile () { AssemblyName newName = new AssemblyName (); newName.Name = "AssemblyTest"; AssemblyBuilder ab = Thread.GetDomain().DefineDynamicAssembly (newName, AssemblyBuilderAccess.RunAndSave, TempFolder); ModuleBuilder mb = ab.DefineDynamicModule ("myDynamicModule1", "myDynamicModule.dll", true); ab.Save ("test_assembly.dll"); File.Delete (Path.Combine (TempFolder, "myDynamicModule.dll")); Assembly ass = Assembly.LoadFrom (Path.Combine (TempFolder, "test_assembly.dll")); try { ass.GetModules (); Assert.Fail (); } catch (FileNotFoundException ex) { Assert.AreEqual ("myDynamicModule.dll", ex.FileName); } } #endif [Category ("NotWorking")] [Test] public void Corlib () { Assembly corlib = typeof (int).Assembly; Assert.IsTrue (corlib.CodeBase.EndsWith ("mscorlib.dll"), "CodeBase"); Assert.IsNull (corlib.EntryPoint, "EntryPoint"); Assert.IsTrue (corlib.EscapedCodeBase.EndsWith ("mscorlib.dll"), "EscapedCodeBase"); Assert.IsNotNull (corlib.Evidence, "Evidence"); Assert.IsTrue (corlib.Location.EndsWith ("mscorlib.dll"), "Location"); // corlib doesn't reference anything Assert.AreEqual (0, corlib.GetReferencedAssemblies ().Length, "GetReferencedAssemblies"); Assert.AreEqual ("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", corlib.FullName, "FullName"); // not really "true" but it's even more trusted so... Assert.IsTrue (corlib.GlobalAssemblyCache, "GlobalAssemblyCache"); Assert.AreEqual (0, corlib.HostContext, "HostContext"); Assert.AreEqual ("v2.0.50727", corlib.ImageRuntimeVersion, "ImageRuntimeVersion"); Assert.IsFalse (corlib.ReflectionOnly, "ReflectionOnly"); Assert.AreEqual (0x1, corlib.ManifestModule.MetadataToken); } [Test] public void Corlib_test () { Assembly corlib_test = Assembly.GetExecutingAssembly (); #if MOBILE Assert.IsNotNull (corlib_test.EntryPoint, "EntryPoint"); Assert.IsNull (corlib_test.Evidence, "Evidence"); #else Assert.IsNull (corlib_test.EntryPoint, "EntryPoint"); Assert.IsNotNull (corlib_test.Evidence, "Evidence"); #endif Assert.IsFalse (corlib_test.GlobalAssemblyCache, "GlobalAssemblyCache"); Assert.IsTrue (corlib_test.GetReferencedAssemblies ().Length > 0, "GetReferencedAssemblies"); Assert.AreEqual (0, corlib_test.HostContext, "HostContext"); #if NET_4_0 && !MOBILE Assert.AreEqual ("v4.0.30319", corlib_test.ImageRuntimeVersion, "ImageRuntimeVersion"); #else Assert.AreEqual ("v2.0.50727", corlib_test.ImageRuntimeVersion, "ImageRuntimeVersion"); #endif Assert.IsNotNull (corlib_test.ManifestModule, "ManifestModule"); Assert.IsFalse (corlib_test.ReflectionOnly, "ReflectionOnly"); } [Test] public void GetAssembly () { Assert.IsTrue (Assembly.GetAssembly (typeof (int)).FullName.StartsWith ("mscorlib"), "GetAssembly(int)"); Assert.AreEqual (this.GetType ().Assembly.FullName, Assembly.GetAssembly (this.GetType ()).FullName, "GetAssembly(this)"); } [Test] public void GetFile_Null () { try { Assembly.GetExecutingAssembly ().GetFile (null); Assert.Fail ("#1"); } catch (ArgumentNullException ex) { Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2"); Assert.IsNull (ex.InnerException, "#3"); Assert.IsNotNull (ex.Message, "#4"); Assert.IsNull (ex.ParamName, "#5"); } } [Test] public void GetFile_Empty () { try { Assembly.GetExecutingAssembly ().GetFile ( String.Empty); Assert.Fail ("#1"); } catch (ArgumentException ex) { Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2"); Assert.IsNull (ex.InnerException, "#3"); Assert.IsNotNull (ex.Message, "#4"); Assert.IsNull (ex.ParamName, "#5"); } } [Test] public void GetFiles_False () { Assembly corlib = typeof (int).Assembly; FileStream[] fss = corlib.GetFiles (); Assert.AreEqual (fss.Length, corlib.GetFiles (false).Length, "corlib.GetFiles (false)"); Assembly corlib_test = Assembly.GetExecutingAssembly (); fss = corlib_test.GetFiles (); Assert.AreEqual (fss.Length, corlib_test.GetFiles (false).Length, "test.GetFiles (false)"); } [Test] public void GetFiles_True () { Assembly corlib = typeof (int).Assembly; FileStream[] fss = corlib.GetFiles (); Assert.IsTrue (fss.Length <= corlib.GetFiles (true).Length, "corlib.GetFiles (true)"); Assembly corlib_test = Assembly.GetExecutingAssembly (); fss = corlib_test.GetFiles (); Assert.IsTrue (fss.Length <= corlib_test.GetFiles (true).Length, "test.GetFiles (true)"); } [Test] public void GetManifestResourceStream_Name_Empty () { Assembly corlib = typeof (int).Assembly; try { corlib.GetManifestResourceStream (string.Empty); Assert.Fail ("#A1"); } catch (ArgumentException ex) { // String cannot have zero length Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#A2"); Assert.IsNull (ex.InnerException, "#A3"); Assert.IsNotNull (ex.Message, "#A4"); } corlib.GetManifestResourceStream (typeof (int), string.Empty); try { corlib.GetManifestResourceStream ((Type) null, string.Empty); Assert.Fail ("#B1"); } catch (ArgumentException ex) { // String cannot have zero length Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#B2"); Assert.IsNull (ex.InnerException, "#B3"); Assert.IsNotNull (ex.Message, "#B4"); } } [Test] public void GetManifestResourceStream_Name_Null () { Assembly corlib = typeof (int).Assembly; try { corlib.GetManifestResourceStream ((string) null); Assert.Fail ("#A1"); } catch (ArgumentNullException ex) { Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#A2"); Assert.IsNull (ex.InnerException, "#A3"); Assert.IsNotNull (ex.Message, "#A4"); } corlib.GetManifestResourceStream (typeof (int), (string) null); try { corlib.GetManifestResourceStream ((Type) null, (string) null); Assert.Fail ("#B1"); } catch (ArgumentNullException ex) { Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#B2"); Assert.IsNull (ex.InnerException, "#B3"); Assert.IsNotNull (ex.Message, "#B4"); Assert.IsNotNull (ex.ParamName, "#B5"); Assert.AreEqual ("type", ex.ParamName, "#B6"); } } [Test] public void IsDefined_AttributeType_Null () { Assembly corlib = typeof (int).Assembly; try { corlib.IsDefined ((Type) null, false); Assert.Fail ("#1"); } catch (ArgumentNullException ex) { Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2"); Assert.IsNull (ex.InnerException, "#3"); Assert.IsNotNull (ex.Message, "#4"); Assert.IsNotNull (ex.ParamName, "#5"); Assert.AreEqual ("attributeType", ex.ParamName, "#6"); } } [Test] // bug #78517 public void LoadFrom_Empty_Assembly () { string tempFile = Path.GetTempFileName (); try { Assembly.LoadFrom (tempFile); Assert.Fail ("#1"); } catch (BadImageFormatException ex) { Assert.IsNull (ex.InnerException, "#2"); } finally { File.Delete (tempFile); } } [Test] // bug #78517 public void LoadFrom_Invalid_Assembly () { string tempFile = Path.GetTempFileName (); using (StreamWriter sw = File.CreateText (tempFile)) { sw.WriteLine ("foo"); sw.Close (); } try { Assembly.LoadFrom (tempFile); Assert.Fail ("#1"); } catch (BadImageFormatException ex) { Assert.IsNull (ex.InnerException, "#2"); } finally { File.Delete (tempFile); } } [Test] public void LoadFrom_NonExisting_Assembly () { string tempFile = Path.GetTempFileName (); File.Delete (tempFile); try { Assembly.LoadFrom (tempFile); Assert.Fail ("#1"); } catch (FileNotFoundException ex) { Assert.IsNull (ex.InnerException, "#2"); } finally { File.Delete (tempFile); } } [Test] public void LoadWithPartialName () { string [] names = { "corlib_test_net_1_1", "corlib_test_net_2_0", "corlib_test_net_4_0", "corlib_test_net_4_5", "corlib_plattest", "mscorlibtests" }; foreach (string s in names) if (Assembly.LoadWithPartialName (s) != null) return; Assert.Fail ("Was not able to load any corlib test"); } [Test] public void GetObjectData_Info_Null () { Assembly corlib = typeof (int).Assembly; try { corlib.GetObjectData (null, new StreamingContext ( StreamingContextStates.All)); Assert.Fail ("#1"); } catch (ArgumentNullException ex) { Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2"); Assert.IsNull (ex.InnerException, "#3"); Assert.IsNotNull (ex.Message, "#4"); Assert.IsNotNull (ex.ParamName, "#5"); Assert.AreEqual ("info", ex.ParamName, "#6"); } } [Test] public void GetReferencedAssemblies () { Assembly corlib_test = Assembly.GetExecutingAssembly (); AssemblyName[] names = corlib_test.GetReferencedAssemblies (); foreach (AssemblyName an in names) { Assert.IsNull (an.CodeBase, "CodeBase"); Assert.IsNotNull (an.CultureInfo, "CultureInfo"); Assert.IsNull (an.EscapedCodeBase, "EscapedCodeBase"); Assert.AreEqual (AssemblyNameFlags.None, an.Flags, "Flags"); Assert.IsNotNull (an.FullName, "FullName"); Assert.AreEqual (AssemblyHashAlgorithm.SHA1, an.HashAlgorithm, "HashAlgorithm"); Assert.IsNull (an.KeyPair, "KeyPair"); Assert.IsNotNull (an.Name, "Name"); Assert.IsNotNull (an.Version, "Version"); Assert.AreEqual (AssemblyVersionCompatibility.SameMachine, an.VersionCompatibility, "VersionCompatibility"); } } #if !MONOTOUCH // Reflection.Emit is not supported. [Test] public void Location_Empty() { string assemblyFileName = Path.Combine ( Path.GetTempPath (), "AssemblyLocation.dll"); try { AssemblyName assemblyName = new AssemblyName (); assemblyName.Name = "AssemblyLocation"; AssemblyBuilder ab = AppDomain.CurrentDomain .DefineDynamicAssembly (assemblyName, AssemblyBuilderAccess.Save, Path.GetTempPath (), AppDomain.CurrentDomain.Evidence); ab.Save (Path.GetFileName (assemblyFileName)); using (FileStream fs = File.OpenRead (assemblyFileName)) { byte[] buffer = new byte[fs.Length]; fs.Read (buffer, 0, buffer.Length); Assembly assembly = Assembly.Load (buffer); Assert.AreEqual (string.Empty, assembly.Location); fs.Close (); } } finally { File.Delete (assemblyFileName); } } [Test] [Category ("NotWorking")] public void bug78464 () { string assemblyFileName = Path.Combine ( Path.GetTempPath (), "bug78464.dll"); try { // execute test in separate appdomain to allow assembly to be unloaded AppDomain testDomain = CreateTestDomain (AppDomain.CurrentDomain.BaseDirectory, false); CrossDomainTester crossDomainTester = CreateCrossDomainTester (testDomain); try { crossDomainTester.bug78464 (assemblyFileName); } finally { AppDomain.Unload (testDomain); } } finally { File.Delete (assemblyFileName); } } [Test] public void bug78465 () { string assemblyFileName = Path.Combine ( Path.GetTempPath (), "bug78465.dll"); try { AssemblyName assemblyName = new AssemblyName (); assemblyName.Name = "bug78465"; AssemblyBuilder ab = AppDomain.CurrentDomain .DefineDynamicAssembly (assemblyName, AssemblyBuilderAccess.Save, Path.GetDirectoryName (assemblyFileName), AppDomain.CurrentDomain.Evidence); ab.Save (Path.GetFileName (assemblyFileName)); using (FileStream fs = File.OpenRead (assemblyFileName)) { byte[] buffer = new byte[fs.Length]; fs.Read (buffer, 0, buffer.Length); Assembly assembly = Assembly.Load (buffer); Assert.AreEqual (string.Empty, assembly.Location, "#1"); fs.Close (); } AppDomain testDomain = CreateTestDomain (AppDomain.CurrentDomain.BaseDirectory, false); CrossDomainTester crossDomainTester = CreateCrossDomainTester (testDomain); try { crossDomainTester.bug78465 (assemblyFileName); } finally { AppDomain.Unload (testDomain); } } finally { File.Delete (assemblyFileName); } } [Test] public void bug78468 () { string assemblyFileNameA = Path.Combine (Path.GetTempPath (), "bug78468a.dll"); string resourceFileName = Path.Combine (Path.GetTempPath (), "readme.txt"); using (StreamWriter sw = File.CreateText (resourceFileName)) { sw.WriteLine ("FOO"); sw.Close (); } try { AssemblyName assemblyName = new AssemblyName (); assemblyName.Name = "bug78468a"; AssemblyBuilder ab = AppDomain.CurrentDomain .DefineDynamicAssembly (assemblyName, AssemblyBuilderAccess.Save, Path.GetTempPath (), AppDomain.CurrentDomain.Evidence); ab.AddResourceFile ("read", "readme.txt"); ab.Save (Path.GetFileName (assemblyFileNameA)); Assembly assembly; using (FileStream fs = File.OpenRead (assemblyFileNameA)) { byte[] buffer = new byte[fs.Length]; fs.Read (buffer, 0, buffer.Length); assembly = Assembly.Load (buffer); fs.Close (); } Assert.AreEqual (string.Empty, assembly.Location, "#A1"); string[] resNames = assembly.GetManifestResourceNames (); Assert.IsNotNull (resNames, "#A2"); Assert.AreEqual (1, resNames.Length, "#A3"); Assert.AreEqual ("read", resNames[0], "#A4"); ManifestResourceInfo resInfo = assembly.GetManifestResourceInfo ("read"); Assert.IsNotNull (resInfo, "#A5"); Assert.AreEqual ("readme.txt", resInfo.FileName, "#A6"); Assert.IsNull (resInfo.ReferencedAssembly, "#A7"); Assert.AreEqual ((ResourceLocation) 0, resInfo.ResourceLocation, "#A8"); try { assembly.GetManifestResourceStream ("read"); Assert.Fail ("#A9"); } catch (FileNotFoundException) { } try { assembly.GetFile ("readme.txt"); Assert.Fail ("#A10"); } catch (FileNotFoundException) { } string assemblyFileNameB = Path.Combine (Path.GetTempPath (), "bug78468b.dll"); AppDomain testDomain = CreateTestDomain (AppDomain.CurrentDomain.BaseDirectory, false); CrossDomainTester crossDomainTester = CreateCrossDomainTester (testDomain); try { crossDomainTester.bug78468 (assemblyFileNameB); } finally { AppDomain.Unload (testDomain); File.Delete (assemblyFileNameB); } } finally { File.Delete (assemblyFileNameA); File.Delete (resourceFileName); } } [Test] [Category ("NotWorking")] public void ReflectionOnlyLoad () { Assembly assembly = Assembly.ReflectionOnlyLoad (typeof (AssemblyTest).Assembly.FullName); Assert.IsNotNull (assembly); Assert.IsTrue (assembly.ReflectionOnly); } [Test] public void ReflectionOnlyLoadFrom () { string loc = typeof (AssemblyTest).Assembly.Location; string filename = Path.GetFileName (loc); Assembly assembly = Assembly.ReflectionOnlyLoadFrom (filename); Assert.IsNotNull (assembly); Assert.IsTrue (assembly.ReflectionOnly); } [Test] [ExpectedException (typeof (ArgumentException))] public void CreateInstanceOnRefOnly () { Assembly assembly = Assembly.ReflectionOnlyLoad (typeof (AssemblyTest).Assembly.FullName); assembly.CreateInstance ("MonoTests.System.Reflection.AssemblyTest"); } [Test] [Category ("NotWorking")] // patch for bug #79720 must be committed first public void Load_Culture () { string tempDir = Path.Combine (Path.GetTempPath (), "MonoTests.System.Reflection.AssemblyTest"); string cultureTempDir = Path.Combine (tempDir, "nl-BE"); if (!Directory.Exists (cultureTempDir)) Directory.CreateDirectory (cultureTempDir); cultureTempDir = Path.Combine (tempDir, "en-US"); if (!Directory.Exists (cultureTempDir)) Directory.CreateDirectory (cultureTempDir); AppDomain ad = CreateTestDomain (tempDir, true); try { CrossDomainTester cdt = CreateCrossDomainTester (ad); // PART A AssemblyName aname = new AssemblyName (); aname.Name = "culturea"; cdt.GenerateAssembly (aname, Path.Combine (tempDir, "culturea.dll")); aname = new AssemblyName (); aname.Name = "culturea"; Assert.IsTrue (cdt.AssertLoad(aname), "#A1"); aname = new AssemblyName (); aname.Name = "culturea"; aname.CultureInfo = new CultureInfo ("nl-BE"); Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#A2"); aname = new AssemblyName (); aname.Name = "culturea"; aname.CultureInfo = CultureInfo.InvariantCulture; Assert.IsTrue (cdt.AssertLoad(aname), "#A3"); // PART B aname = new AssemblyName (); aname.Name = "cultureb"; aname.CultureInfo = new CultureInfo ("nl-BE"); cdt.GenerateAssembly (aname, Path.Combine (tempDir, "cultureb.dll")); aname = new AssemblyName (); aname.Name = "cultureb"; aname.CultureInfo = new CultureInfo ("nl-BE"); Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#B1"); aname = new AssemblyName (); aname.Name = "cultureb"; Assert.IsTrue (cdt.AssertLoad (aname), "#B2"); aname = new AssemblyName (); aname.Name = "cultureb"; aname.CultureInfo = new CultureInfo ("en-US"); Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#B3"); // PART C aname = new AssemblyName (); aname.Name = "culturec"; aname.CultureInfo = new CultureInfo ("nl-BE"); cdt.GenerateAssembly (aname, Path.Combine (tempDir, "nl-BE/culturec.dll")); aname = new AssemblyName (); aname.Name = "culturec"; aname.CultureInfo = new CultureInfo ("nl-BE"); Assert.IsTrue (cdt.AssertLoad (aname), "#C1"); aname = new AssemblyName (); aname.Name = "culturec"; Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#C2"); aname = new AssemblyName (); aname.Name = "culturec"; aname.CultureInfo = CultureInfo.InvariantCulture; Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#C3"); // PART D aname = new AssemblyName (); aname.Name = "cultured"; aname.CultureInfo = new CultureInfo ("nl-BE"); cdt.GenerateAssembly (aname, Path.Combine (tempDir, "en-US/cultured.dll")); aname = new AssemblyName (); aname.Name = "cultured"; aname.CultureInfo = new CultureInfo ("nl-BE"); Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#D1"); aname = new AssemblyName (); aname.Name = "cultured"; Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#D2"); aname = new AssemblyName (); aname.Name = "cultured"; aname.CultureInfo = CultureInfo.InvariantCulture; Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#D3"); } finally { AppDomain.Unload (ad); if (Directory.Exists (tempDir)) Directory.Delete (tempDir, true); } } [Test] // bug #79712 [Category ("NotWorking")] // in non-default domain, MS throws FileNotFoundException public void Load_Culture_Mismatch () { string tempDir = Path.Combine (Path.GetTempPath (), "MonoTests.System.Reflection.AssemblyTest"); string cultureTempDir = Path.Combine (tempDir, "en-US"); if (!Directory.Exists (cultureTempDir)) Directory.CreateDirectory (cultureTempDir); AppDomain ad = CreateTestDomain (tempDir, true); try { CrossDomainTester cdt = CreateCrossDomainTester (ad); // PART A AssemblyName aname = new AssemblyName (); aname.Name = "bug79712a"; aname.CultureInfo = new CultureInfo ("nl-BE"); cdt.GenerateAssembly (aname, Path.Combine (tempDir, "bug79712a.dll")); aname = new AssemblyName (); aname.Name = "bug79712a"; aname.CultureInfo = CultureInfo.InvariantCulture; Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#A1"); // PART B aname = new AssemblyName (); aname.Name = "bug79712b"; aname.CultureInfo = new CultureInfo ("nl-BE"); cdt.GenerateAssembly (aname, Path.Combine (tempDir, "en-US/bug79712b.dll")); aname = new AssemblyName (); aname.Name = "bug79712b"; aname.CultureInfo = new CultureInfo ("en-US"); Assert.IsTrue (cdt.AssertFileNotFoundException (aname), "#B1"); } finally { AppDomain.Unload (ad); if (Directory.Exists (tempDir)) Directory.Delete (tempDir, true); } } [Test] // bug #79715 public void Load_PartialVersion () { string tempDir = Path.Combine (Path.GetTempPath (), "MonoTests.System.Reflection.AssemblyTest"); if (!Directory.Exists (tempDir)) Directory.CreateDirectory (tempDir); AppDomain ad = CreateTestDomain (tempDir, true); try { CrossDomainTester cdt = CreateCrossDomainTester (ad); AssemblyName aname = new AssemblyName (); aname.Name = "bug79715"; aname.Version = new Version (1, 2, 3, 4); cdt.GenerateAssembly (aname, Path.Combine (tempDir, "bug79715.dll")); aname = new AssemblyName (); aname.Name = "bug79715"; aname.Version = new Version (1, 2); Assert.IsTrue (cdt.AssertLoad (aname), "#A1"); Assert.IsTrue (cdt.AssertLoad (aname.FullName), "#A2"); aname = new AssemblyName (); aname.Name = "bug79715"; aname.Version = new Version (1, 2, 3); Assert.IsTrue (cdt.AssertLoad (aname), "#B1"); Assert.IsTrue (cdt.AssertLoad (aname.FullName), "#B2"); aname = new AssemblyName (); aname.Name = "bug79715"; aname.Version = new Version (1, 2, 3, 4); Assert.IsTrue (cdt.AssertLoad (aname), "#C1"); Assert.IsTrue (cdt.AssertLoad (aname.FullName), "#C2"); } finally { AppDomain.Unload (ad); if (Directory.Exists (tempDir)) Directory.Delete (tempDir, true); } } private static AppDomain CreateTestDomain (string baseDirectory, bool assemblyResolver) { AppDomainSetup setup = new AppDomainSetup (); setup.ApplicationBase = baseDirectory; setup.ApplicationName = "testdomain"; AppDomain ad = AppDomain.CreateDomain ("testdomain", AppDomain.CurrentDomain.Evidence, setup); if (assemblyResolver) { Assembly ea = Assembly.GetExecutingAssembly (); ad.CreateInstanceFrom (ea.CodeBase, typeof (AssemblyResolveHandler).FullName, false, BindingFlags.Public | BindingFlags.Instance, null, new object [] { ea.Location, ea.FullName }, CultureInfo.InvariantCulture, null, null); } return ad; } private static CrossDomainTester CreateCrossDomainTester (AppDomain domain) { Type testerType = typeof (CrossDomainTester); return (CrossDomainTester) domain.CreateInstanceAndUnwrap ( testerType.Assembly.FullName, testerType.FullName, false, BindingFlags.Public | BindingFlags.Instance, null, new object[0], CultureInfo.InvariantCulture, new object[0], null); } private class CrossDomainTester : MarshalByRefObject { public void GenerateAssembly (AssemblyName aname, string path) { AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly ( aname, AssemblyBuilderAccess.Save, Path.GetDirectoryName (path)); ab.Save (Path.GetFileName (path)); } public void Load (AssemblyName assemblyRef) { Assembly.Load (assemblyRef); } public void LoadFrom (string assemblyFile) { Assembly.LoadFrom (assemblyFile); } public bool AssertLoad (AssemblyName assemblyRef) { try { Assembly.Load (assemblyRef); return true; } catch { return false; } } public bool AssertLoad (string assemblyString) { try { Assembly.Load (assemblyString); return true; } catch { return false; } } public bool AssertFileLoadException (AssemblyName assemblyRef) { try { Assembly.Load (assemblyRef); return false; } catch (FileLoadException) { return true; } } public bool AssertFileNotFoundException (AssemblyName assemblyRef) { try { Assembly.Load (assemblyRef); return false; } catch (FileNotFoundException) { return true; } } public void bug78464 (string assemblyFileName) { AssemblyName assemblyName = new AssemblyName (); assemblyName.Name = "bug78464"; AssemblyBuilder ab = AppDomain.CurrentDomain .DefineDynamicAssembly (assemblyName, AssemblyBuilderAccess.Save, Path.GetDirectoryName (assemblyFileName), AppDomain.CurrentDomain.Evidence); ab.Save (Path.GetFileName (assemblyFileName)); Assembly assembly; using (FileStream fs = File.OpenRead (assemblyFileName)) { byte[] buffer = new byte[fs.Length]; fs.Read (buffer, 0, buffer.Length); assembly = Assembly.Load (buffer); fs.Close (); } Assert.AreEqual (string.Empty, assembly.Location, "#1"); assembly = Assembly.LoadFrom (assemblyFileName, AppDomain.CurrentDomain.Evidence); Assert.IsFalse (assembly.Location == string.Empty, "#2"); Assert.AreEqual (Path.GetFileName (assemblyFileName), Path.GetFileName(assembly.Location), "#3"); // note: we cannot check if directory names match, as MS.NET seems to // convert directory part of assembly location to lowercase Assert.IsFalse (Path.GetDirectoryName(assembly.Location) == string.Empty, "#4"); } public void bug78465 (string assemblyFileName) { Assembly assembly = Assembly.LoadFrom (assemblyFileName, AppDomain.CurrentDomain.Evidence); Assert.IsFalse (assembly.Location == string.Empty, "#2"); Assert.AreEqual (Path.GetFileName (assemblyFileName), Path.GetFileName (assembly.Location), "#3"); // note: we cannot check if directory names match, as MS.NET seems to // convert directory part of assembly location to lowercase Assert.IsFalse (Path.GetDirectoryName (assembly.Location) == string.Empty, "#4"); } public void bug78468 (string assemblyFileName) { AssemblyName assemblyName = new AssemblyName (); assemblyName.Name = "bug78468b"; AssemblyBuilder ab = AppDomain.CurrentDomain .DefineDynamicAssembly (assemblyName, AssemblyBuilderAccess.Save, Path.GetDirectoryName (assemblyFileName), AppDomain.CurrentDomain.Evidence); ab.AddResourceFile ("read", "readme.txt"); ab.Save (Path.GetFileName (assemblyFileName)); Assembly assembly = Assembly.LoadFrom (assemblyFileName, AppDomain.CurrentDomain.Evidence); Assert.IsTrue (assembly.Location != string.Empty, "#B1"); string[] resNames = assembly.GetManifestResourceNames (); Assert.IsNotNull (resNames, "#B2"); Assert.AreEqual (1, resNames.Length, "#B3"); Assert.AreEqual ("read", resNames[0], "#B4"); ManifestResourceInfo resInfo = assembly.GetManifestResourceInfo ("read"); Assert.IsNotNull (resInfo, "#B5"); Assert.AreEqual ("readme.txt", resInfo.FileName, "#B6"); Assert.IsNull (resInfo.ReferencedAssembly, "#B7"); Assert.AreEqual ((ResourceLocation) 0, resInfo.ResourceLocation, "#B8"); Stream s = assembly.GetManifestResourceStream ("read"); Assert.IsNotNull (s, "#B9"); s.Close (); s = assembly.GetFile ("readme.txt"); Assert.IsNotNull (s, "#B10"); s.Close (); } } [Test] public void bug79872 () { Random rnd = new Random (); string outdir; int tries = 0; retry: outdir = Path.Combine (Path.GetTempPath (), "bug79872-" + rnd.Next (10000, 99999)); if (Directory.Exists (outdir)) { try { Directory.Delete (outdir, true); } catch { if (++tries <= 100) goto retry; } } Directory.CreateDirectory (outdir); AssemblyName an = new AssemblyName (); an.Name = "bug79872"; AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Save, outdir); string dllname = "bug79872.dll"; ModuleBuilder mb1 = ab.DefineDynamicModule ("bug79872", dllname); string netmodule = "bug79872.netmodule"; ModuleBuilder mb2 = ab.DefineDynamicModule (netmodule, netmodule); TypeBuilder a1 = mb2.DefineType ("A"); a1.CreateType (); ab.Save (dllname); bool ok = true; try { Assembly.LoadFrom (Path.Combine (outdir, dllname)); } catch { ok = false; } Assert.IsTrue (ok, "Should load a .NET metadata file with an assembly manifest"); ok = false; try { Assembly.LoadFrom (Path.Combine (outdir, netmodule)); } catch (BadImageFormatException) { ok = true; // mono and .net 2.0 throw this } catch (FileLoadException) { ok = true; // .net 1.1 throws this } catch { // swallow the rest } Assert.IsTrue (ok, "Complain on loading a .NET metadata file without an assembly manifest"); Directory.Delete (outdir, true); } #endif [Test] public void ManifestModule () { Assembly assembly = typeof (int).Assembly; Module module = assembly.ManifestModule; Assert.IsNotNull (module, "#1"); #if NET_4_0 Assert.AreEqual ("MonoModule", module.GetType ().Name, "#2"); #else Assert.AreEqual (typeof (Module), module.GetType (), "#2"); #endif #if !MONOTOUCH Assert.AreEqual ("mscorlib.dll", module.Name, "#3"); #endif Assert.IsFalse (module.IsResource (), "#4"); Assert.IsTrue (assembly.GetModules ().Length > 0, "#5"); Assert.AreSame (module, assembly.GetModules () [0], "#6"); Assert.AreSame (module, assembly.ManifestModule, "#7"); } [Serializable ()] private class AssemblyResolveHandler { public AssemblyResolveHandler (string assemblyFile, string assemblyName) { _assemblyFile = assemblyFile; _assemblyName = assemblyName; AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler (ResolveAssembly); } private Assembly ResolveAssembly (Object sender, ResolveEventArgs args) { if (args.Name == _assemblyName) return Assembly.LoadFrom (_assemblyFile); return null; } private readonly string _assemblyFile; private readonly string _assemblyName; } protected internal class Bug328812_NestedFamORAssem { }; [Test] public void bug328812 () { Assembly corlib_test = Assembly.GetExecutingAssembly (); Assert.IsNull (corlib_test.GetType ("Bug328812_NestedFamORAssem")); // Just a sanity check, in case the above passed for some other reason Assert.IsNotNull (corlib_test.GetType ("MonoTests.System.Reflection.AssemblyTest+Bug328812_NestedFamORAssem")); } [Test] public void GetCustomAttributes_AttributeType_Null () { Assembly a = typeof (int).Assembly; try { a.GetCustomAttributes (null, false); Assert.Fail ("#1"); } catch (ArgumentNullException ex) { Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2"); Assert.IsNull (ex.InnerException, "#3"); Assert.IsNotNull (ex.Message, "#4"); Assert.IsNotNull (ex.ParamName, "#5"); Assert.AreEqual ("attributeType", ex.ParamName, "#6"); } } [Test] public void GetTypeWithEmptyStringShouldThrow () { try { typeof (string).Assembly.GetType (""); Assert.Fail ("#1"); } catch (ArgumentException) {} } #if NET_4_5 [Test] public void DefinedTypes_Equality () { var x1 = Assembly.GetExecutingAssembly ().DefinedTypes.Where (l => l.FullName == "MonoTests.System.Reflection.TestDefinedTypes").Single (); var x2 = Assembly.GetExecutingAssembly ().GetTypes ().Where (l => l.FullName == "MonoTests.System.Reflection.TestDefinedTypes").Single (); Assert.AreSame (x1, x2, "#1"); } #endif } public class TestDefinedTypes { } }
31.32807
152
0.684157
[ "Apache-2.0" ]
Distrotech/mono
mcs/class/corlib/Test/System.Reflection/AssemblyTest.cs
35,714
C#
// Project: Aguafrommars/TheIdServer // Copyright (c) 2020 @Olivier Lefebvre namespace Aguacongas.IdentityServer.Store.Entity { /// <summary> /// Represents a remote identity provider /// </summary> public class IdentityProvider { /// <summary> /// Gets or sets the Id. /// </summary> /// <value> /// The name. /// </value> public string Id { get; set; } /// <summary> /// Gets or sets the display name. /// </summary> /// <value> /// The display name. /// </value> public string DisplayName { get; set; } } }
24
48
0.515432
[ "Apache-2.0" ]
markjohnnah/TheIdServer
src/IdentityServer/Aguacongas.IdentityServer.Store/Entity/IdentityProvider.cs
650
C#
using diil.web.DataBase; using System; namespace diil.web.Domain { /// <summary> /// System_PermissionUser表实体类 /// </summary> public partial class SystemPermissionUser : BaseEntity { /// <summary> /// 人员归属类型:角色0,组织机构1,岗位2,组3,人员4(用于查询某用户具有哪些岗位、组等) /// </summary> public short PrivilegeMaster { get; set; } /// <summary> /// 对应类型Id(角色Id,岗位Id,组Id,人员Id) /// </summary> public Guid PrivilegeMasterValue { get; set; } /// <summary> /// 人员Id /// </summary> public Guid PrivilegeMasterUserId { get; set; } } }
24.230769
58
0.553968
[ "MIT" ]
BJDIIL/DiiL
DiiL.Core/Domain/SystemPermissionUser.cs
730
C#
using System; using System.Collections.Generic; // Code scaffolded by EF Core assumes nullable reference types (NRTs) are not used or disabled. // If you have enabled NRTs for your project, then un-comment the following line: // #nullable disable namespace Assimalign.Employees.SqlServer.Models { public partial class EmployeesTypesEntity { public EmployeesTypesEntity() { Employees = new HashSet<EmployeesEntity>(); } public int TypeId { get; set; } public string TypeName { get; set; } public DateTime DateCreated { get; set; } public DateTime DateUpdated { get; set; } public string CreatedBy { get; set; } public string UpdatedBy { get; set; } public virtual ICollection<EmployeesEntity> Employees { get; set; } } }
30.703704
95
0.664656
[ "Apache-2.0" ]
Assimalign-LLC/asal-erp
src/web/domains/core/Assimalign.Employees/Assimalign.Employees.SqlServer/Models/EmployeesTypesEntity.cs
831
C#
namespace Sdl.Tridion.Api.GraphQL.Client.Response { /// <summary> /// Typed GraphQL response for deserialization of results to strongly typed content model. /// </summary> /// <typeparam name="T">Type to deserialize results</typeparam> public interface IGraphQLTypedResponse<T> : IGraphQLResponse { /// <summary> /// Get typed response data from GraphQL request. /// </summary> T TypedResponseData { get; set; } } }
31.8
94
0.643606
[ "Apache-2.0" ]
RWS/graphql-client-dotnet
net/src/Sdl.Tridion.Api.Client/GraphQLClient/Response/IGraphQLTypedResponse.cs
479
C#
using System; using Xunit; using Util; using System.Text; namespace LongestCommonPrefix { public class Solution { public string LongestCommonPrefix(string[] strs) { if (strs.Length == 0) { return ""; } if (strs.Length == 1) { return strs[0]; } int min = strs[0].Length; for (var i = 1; i < strs.Length; i++) { if (strs[i].Length < min) min = strs[i].Length; } for (var i = 0; i < min; i++) { char c = strs[0][i]; for (var j = 1; j < strs.Length; j++) { if (strs[j][i] != c) { return strs[0].Substring(0, i); } } } return strs[0].Substring(0, min); } } public class Test { static public void Run() { Console.WriteLine("LongestCommonPrefix"); string[] input; string exp, res; using (new Timeit()) { input = new string[] { "flower", "flow", "flight" }; exp = "fl"; res = new Solution().LongestCommonPrefix(input); Assert.Equal(exp, res); } using (new Timeit()) { input = new string[] { "dog", "racecar", "car" }; exp = ""; res = new Solution().LongestCommonPrefix(input); Assert.Equal(exp, res); } using (new Timeit()) { input = new string[] { "dog", "dogracecar", "dogcar" }; exp = "dog"; res = new Solution().LongestCommonPrefix(input); Assert.Equal(exp, res); } using (new Timeit()) { input = new string[] { "dogracecar", "dog", "dogcar" }; exp = "dog"; res = new Solution().LongestCommonPrefix(input); Assert.Equal(exp, res); } using (new Timeit()) { input = new string[] { }; exp = ""; res = new Solution().LongestCommonPrefix(input); Assert.Equal(exp, res); } using (new Timeit()) { input = new string[] { "a" }; exp = "a"; res = new Solution().LongestCommonPrefix(input); Assert.Equal(exp, res); } } } }
28.463158
71
0.379808
[ "MIT" ]
beingj/LeetCode
0014-LongestCommonPrefix.cs
2,704
C#
using System; using Core.AutoCode; namespace Metadata.Raw { class ListMember: MemberBase { public override void WriteLoad (CodeWriter writer) { Type elementType = _type.GetGenericArguments() [0]; string elementTypeName = EditorMetaCommon.GetNestedClassName(elementType); writer.WriteLine ("int {0}Count = reader.ReadInt32();", _name); writer.WriteLine ("if (null == {0}) {{ {0} = new List<{1}>({0}Count); }} else {{ {0}.Clear(); }}", _name, elementTypeName); writer.WriteLine ("for (int index= 0; index < {0}Count; ++index)", _name); using (CodeScope.CreateCSharpScope(writer)) { writer.WriteLine ("{0}.Add (default({1}));", _name, elementTypeName); _WriteLoadType (writer, elementType, _name + "[index]"); } } public override void WriteSave(CodeWriter writer) { writer.WriteLine("int {0}Count = null != {0} ? {0}.Count : 0 ;", _name); writer.WriteLine("writer.Write ({0}Count);", _name); writer.WriteLine("for (int index= 0; index < {0}Count; ++index)", _name); using (CodeScope.CreateCSharpScope(writer)) { writer.WriteLine("var item = {0}[index];", _name); var elementType = _type.GetGenericArguments()[0]; _WriteSaveType(writer, elementType, "item"); } } public override void WriteNotEqualsReturn (CodeWriter writer) { writer.WriteLine ("int {0}Count1 = null != {0} ? {0}.Count : 0 ;", _name); writer.WriteLine ("int {0}Count2 = null != that.{0} ? that.{0}.Count : 0 ;", _name); writer.WriteLine("if ({0}Count1 != {0}Count2)", _name); using (CodeScope.CreateCSharpScope(writer)) { writer.WriteLine("return false;"); } writer.WriteLine("for (int i{1}= 0; i{1} < {0}Count1; ++i{1})", _name, writer.Indent); using (CodeScope.CreateCSharpScope(writer)) { var elementType = _type.GetGenericArguments() [0]; var itemName = string.Format("{0}[i{1}]", _name, writer.Indent - 1); _WriteNotEqualsReturn(writer, elementType, itemName); } } } }
38.086207
126
0.580353
[ "Apache-2.0" ]
rusmass/wealthland_client
arpg_prg/Fantasy/Assets/Code/Core/Editor/Metadata/Members/ListMember.cs
2,209
C#
using Day03Task1Solution; using Shared.Helpers; namespace Day03Task1Result { class Program { static void Main(string[] args) { var commands1 = Solution.CreateCommandsList(Data.Wire1); var commands2 = Solution.CreateCommandsList(Data.Wire2); var path1 = Solution.CreatePaths(commands1); var path2 = Solution.CreatePaths(commands2); ConsoleHelper.PrintResult(Solution.FindIntersections(path1, path2).FindClosest().GetDistance()); } } }
29.555556
108
0.656015
[ "MIT" ]
sowiszcze/AdventOfCode2019
Day03Task1Result/Program.cs
534
C#
// WARNING - AUTOGENERATED - DO NOT EDIT // // Generated using `sharpie urho` // // BorderImage.cs // // Copyright 2015 Xamarin Inc. All rights reserved. using System; using System.Runtime.InteropServices; using System.Collections.Generic; using Urho.Urho2D; using Urho.Gui; using Urho.Resources; using Urho.IO; using Urho.Navigation; using Urho.Network; namespace Urho.Gui { /// <summary> /// %Image %UI element with optional border. /// </summary> public unsafe partial class BorderImage : UIElement { unsafe partial void OnBorderImageCreated (); [Preserve] public BorderImage (IntPtr handle) : base (handle) { OnBorderImageCreated (); } [Preserve] protected BorderImage (UrhoObjectFlag emptyFlag) : base (emptyFlag) { OnBorderImageCreated (); } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern int BorderImage_GetType (IntPtr handle); private StringHash UrhoGetType () { Runtime.ValidateRefCounted (this); return new StringHash (BorderImage_GetType (handle)); } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr BorderImage_GetTypeName (IntPtr handle); private string GetTypeName () { Runtime.ValidateRefCounted (this); return Marshal.PtrToStringAnsi (BorderImage_GetTypeName (handle)); } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern int BorderImage_GetTypeStatic (); private static StringHash GetTypeStatic () { Runtime.Validate (typeof(BorderImage)); return new StringHash (BorderImage_GetTypeStatic ()); } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr BorderImage_GetTypeNameStatic (); private static string GetTypeNameStatic () { Runtime.Validate (typeof(BorderImage)); return Marshal.PtrToStringAnsi (BorderImage_GetTypeNameStatic ()); } [Preserve] public BorderImage () : this (Application.CurrentContext) { } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr BorderImage_BorderImage (IntPtr context); [Preserve] public BorderImage (Context context) : base (UrhoObjectFlag.Empty) { Runtime.Validate (typeof(BorderImage)); handle = BorderImage_BorderImage ((object)context == null ? IntPtr.Zero : context.Handle); Runtime.RegisterObject (this); OnBorderImageCreated (); } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern void BorderImage_RegisterObject (IntPtr context); /// <summary> /// Register object factory. /// </summary> public new static void RegisterObject (Context context) { Runtime.Validate (typeof(BorderImage)); BorderImage_RegisterObject ((object)context == null ? IntPtr.Zero : context.Handle); } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern void BorderImage_SetTexture (IntPtr handle, IntPtr texture); /// <summary> /// Set texture. /// </summary> private void SetTexture (Texture texture) { Runtime.ValidateRefCounted (this); BorderImage_SetTexture (handle, (object)texture == null ? IntPtr.Zero : texture.Handle); } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern void BorderImage_SetImageRect (IntPtr handle, ref Urho.IntRect rect); /// <summary> /// Set part of texture to use as the image. /// </summary> private void SetImageRect (Urho.IntRect rect) { Runtime.ValidateRefCounted (this); BorderImage_SetImageRect (handle, ref rect); } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern void BorderImage_SetFullImageRect (IntPtr handle); /// <summary> /// Use whole texture as the image. /// </summary> public void SetFullImageRect () { Runtime.ValidateRefCounted (this); BorderImage_SetFullImageRect (handle); } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern void BorderImage_SetBorder (IntPtr handle, ref Urho.IntRect rect); /// <summary> /// Set border dimensions on the screen. /// </summary> private void SetBorder (Urho.IntRect rect) { Runtime.ValidateRefCounted (this); BorderImage_SetBorder (handle, ref rect); } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern void BorderImage_SetImageBorder (IntPtr handle, ref Urho.IntRect rect); /// <summary> /// Set border dimensions on the image. If zero (default) uses the screen dimensions, resulting in pixel-perfect borders. /// </summary> private void SetImageBorder (Urho.IntRect rect) { Runtime.ValidateRefCounted (this); BorderImage_SetImageBorder (handle, ref rect); } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern void BorderImage_SetHoverOffset (IntPtr handle, ref Urho.IntVector2 offset); /// <summary> /// Set offset to image rectangle used on hover. /// </summary> private void SetHoverOffset (Urho.IntVector2 offset) { Runtime.ValidateRefCounted (this); BorderImage_SetHoverOffset (handle, ref offset); } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern void BorderImage_SetHoverOffset0 (IntPtr handle, int x, int y); /// <summary> /// Set offset to image rectangle used on hover. /// </summary> public void SetHoverOffset (int x, int y) { Runtime.ValidateRefCounted (this); BorderImage_SetHoverOffset0 (handle, x, y); } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern void BorderImage_SetDisabledOffset (IntPtr handle, ref Urho.IntVector2 offset); /// <summary> /// Set offset to image rectangle used when disabled. /// </summary> private void SetDisabledOffset (Urho.IntVector2 offset) { Runtime.ValidateRefCounted (this); BorderImage_SetDisabledOffset (handle, ref offset); } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern void BorderImage_SetDisabledOffset1 (IntPtr handle, int x, int y); /// <summary> /// Set offset to image rectangle used when disabled. /// </summary> public void SetDisabledOffset (int x, int y) { Runtime.ValidateRefCounted (this); BorderImage_SetDisabledOffset1 (handle, x, y); } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern void BorderImage_SetBlendMode (IntPtr handle, BlendMode mode); /// <summary> /// Set blend mode. /// </summary> private void SetBlendMode (BlendMode mode) { Runtime.ValidateRefCounted (this); BorderImage_SetBlendMode (handle, mode); } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern void BorderImage_SetTiled (IntPtr handle, bool enable); /// <summary> /// Set tiled mode. /// </summary> private void SetTiled (bool enable) { Runtime.ValidateRefCounted (this); BorderImage_SetTiled (handle, enable); } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern void BorderImage_SetMaterial (IntPtr handle, IntPtr material); /// <summary> /// Set material for custom rendering. /// </summary> private void SetMaterial (Material material) { Runtime.ValidateRefCounted (this); BorderImage_SetMaterial (handle, (object)material == null ? IntPtr.Zero : material.Handle); } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr BorderImage_GetTexture (IntPtr handle); /// <summary> /// Return texture. /// </summary> private Texture GetTexture () { Runtime.ValidateRefCounted (this); return Runtime.LookupObject<Texture> (BorderImage_GetTexture (handle)); } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern Urho.IntRect BorderImage_GetImageRect (IntPtr handle); /// <summary> /// Return image rectangle. /// </summary> private Urho.IntRect GetImageRect () { Runtime.ValidateRefCounted (this); return BorderImage_GetImageRect (handle); } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern Urho.IntRect BorderImage_GetBorder (IntPtr handle); /// <summary> /// Return border screen dimensions. /// </summary> private Urho.IntRect GetBorder () { Runtime.ValidateRefCounted (this); return BorderImage_GetBorder (handle); } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern Urho.IntRect BorderImage_GetImageBorder (IntPtr handle); /// <summary> /// Return border image dimensions. Zero rect uses border screen dimensions. /// </summary> private Urho.IntRect GetImageBorder () { Runtime.ValidateRefCounted (this); return BorderImage_GetImageBorder (handle); } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern Urho.IntVector2 BorderImage_GetHoverOffset (IntPtr handle); /// <summary> /// Return offset to image rectangle used on hover. /// </summary> private Urho.IntVector2 GetHoverOffset () { Runtime.ValidateRefCounted (this); return BorderImage_GetHoverOffset (handle); } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern Urho.IntVector2 BorderImage_GetDisabledOffset (IntPtr handle); /// <summary> /// Return offset to image rectangle used when disabled. /// </summary> private Urho.IntVector2 GetDisabledOffset () { Runtime.ValidateRefCounted (this); return BorderImage_GetDisabledOffset (handle); } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern BlendMode BorderImage_GetBlendMode (IntPtr handle); /// <summary> /// Return blend mode. /// </summary> private BlendMode GetBlendMode () { Runtime.ValidateRefCounted (this); return BorderImage_GetBlendMode (handle); } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern bool BorderImage_IsTiled (IntPtr handle); /// <summary> /// Return whether is tiled. /// </summary> private bool IsTiled () { Runtime.ValidateRefCounted (this); return BorderImage_IsTiled (handle); } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr BorderImage_GetMaterial (IntPtr handle); /// <summary> /// Get material used for custom rendering. /// </summary> private Material GetMaterial () { Runtime.ValidateRefCounted (this); return Runtime.LookupObject<Material> (BorderImage_GetMaterial (handle)); } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern ResourceRef BorderImage_GetTextureAttr (IntPtr handle); /// <summary> /// Return texture attribute. /// </summary> private ResourceRef GetTextureAttr () { Runtime.ValidateRefCounted (this); return BorderImage_GetTextureAttr (handle); } [DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern ResourceRef BorderImage_GetMaterialAttr (IntPtr handle); /// <summary> /// Get material attribute. /// </summary> private ResourceRef GetMaterialAttr () { Runtime.ValidateRefCounted (this); return BorderImage_GetMaterialAttr (handle); } public override StringHash Type { get { return UrhoGetType (); } } public override string TypeName { get { return GetTypeName (); } } [Preserve] public new static StringHash TypeStatic { get { return GetTypeStatic (); } } public new static string TypeNameStatic { get { return GetTypeNameStatic (); } } /// <summary> /// Return texture. /// Or /// Set texture. /// </summary> public Texture Texture { get { return GetTexture (); } set { SetTexture (value); } } /// <summary> /// Return image rectangle. /// Or /// Set part of texture to use as the image. /// </summary> public Urho.IntRect ImageRect { get { return GetImageRect (); } set { SetImageRect (value); } } /// <summary> /// Return border screen dimensions. /// Or /// Set border dimensions on the screen. /// </summary> public Urho.IntRect Border { get { return GetBorder (); } set { SetBorder (value); } } /// <summary> /// Return border image dimensions. Zero rect uses border screen dimensions. /// Or /// Set border dimensions on the image. If zero (default) uses the screen dimensions, resulting in pixel-perfect borders. /// </summary> public Urho.IntRect ImageBorder { get { return GetImageBorder (); } set { SetImageBorder (value); } } /// <summary> /// Return offset to image rectangle used on hover. /// Or /// Set offset to image rectangle used on hover. /// </summary> public Urho.IntVector2 HoverOffset { get { return GetHoverOffset (); } set { SetHoverOffset (value); } } /// <summary> /// Return offset to image rectangle used when disabled. /// Or /// Set offset to image rectangle used when disabled. /// </summary> public Urho.IntVector2 DisabledOffset { get { return GetDisabledOffset (); } set { SetDisabledOffset (value); } } /// <summary> /// Return blend mode. /// Or /// Set blend mode. /// </summary> public BlendMode BlendMode { get { return GetBlendMode (); } set { SetBlendMode (value); } } /// <summary> /// Return whether is tiled. /// Or /// Set tiled mode. /// </summary> public bool Tiled { get { return IsTiled (); } set { SetTiled (value); } } /// <summary> /// Get material used for custom rendering. /// Or /// Set material for custom rendering. /// </summary> public Material Material { get { return GetMaterial (); } set { SetMaterial (value); } } /// <summary> /// Return texture attribute. /// </summary> public ResourceRef TextureAttr { get { return GetTextureAttr (); } } /// <summary> /// Get material attribute. /// </summary> public ResourceRef MaterialAttr { get { return GetMaterialAttr (); } } } }
26.77677
123
0.708689
[ "MIT" ]
sweep3r/urho
Bindings/Portable/Generated/BorderImage.cs
14,754
C#
using Bunit; using FluentAssertions; using LinkDotNet.Blog.Web.Shared; using Xunit; namespace LinkDotNet.Blog.IntegrationTests.Web.Shared; public class ConfirmDialogTests { [Fact] public void ShouldInvokeEventOnOkClick() { var okWasClicked = false; using var ctx = new TestContext(); var cut = ctx.RenderComponent<ConfirmDialog>( b => b .Add(p => p.OnYesPressed, _ => okWasClicked = true)); cut.Instance.Open(); cut.Find("#ok").Click(); okWasClicked.Should().BeTrue(); } }
22.8
69
0.626316
[ "MIT" ]
linkdotnet/Blog
tests/LinkDotNet.Blog.IntegrationTests/Web/Shared/ConfirmDialogTests.cs
572
C#
using System; using System.Collections.Generic; using System.Diagnostics.Eventing.Reader; using System.Linq; using System.Text; using System.Threading.Tasks; namespace winPEAS.TaskScheduler { /// <summary> /// Changes to tasks and the engine that cause events. /// </summary> public enum StandardTaskEventId { /// <summary>Task Scheduler started an instance of a task for a user.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd348558(v=ws.10).aspx">Event ID 100</a> on TechNet.</remarks> JobStart = 100, /// <summary>Task Scheduler failed to start a task for a user.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315710(v=ws.10).aspx">Event ID 101</a> on TechNet.</remarks> JobStartFailed = 101, /// <summary>Task Scheduler successfully finished an instance of a task for a user.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd348530(v=ws.10).aspx">Event ID 102</a> on TechNet.</remarks> JobSuccess = 102, /// <summary>Task Scheduler failed to start an instance of a task for a user.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315643(v=ws.10).aspx">Event ID 103</a> on TechNet.</remarks> JobFailure = 103, /// <summary>Task Scheduler failed to log on the user.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/cc727217(v=ws.10).aspx">Event ID 104</a> on TechNet.</remarks> LogonFailure = 104, /// <summary>Task Scheduler failed to impersonate a user.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd348541(v=ws.10).aspx">Event ID 105</a> on TechNet.</remarks> ImpersonationFailure = 105, /// <summary>The a user registered the Task Scheduler a task.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363640(v=ws.10).aspx">Event ID 106</a> on TechNet.</remarks> JobRegistered = 106, /// <summary>Task Scheduler launched an instance of a task due to a time trigger.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd348590(v=ws.10).aspx">Event ID 107</a> on TechNet.</remarks> TimeTrigger = 107, /// <summary>Task Scheduler launched an instance of a task due to an event trigger.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/cc727031(v=ws.10).aspx">Event ID 108</a> on TechNet.</remarks> EventTrigger = 108, /// <summary>Task Scheduler launched an instance of a task due to a registration trigger.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363702(v=ws.10).aspx">Event ID 109</a> on TechNet.</remarks> ImmediateTrigger = 109, /// <summary>Task Scheduler launched an instance of a task for a user.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363721(v=ws.10).aspx">Event ID 110</a> on TechNet.</remarks> Run = 110, /// <summary>Task Scheduler terminated an instance of a task due to exceeding the time allocated for execution, as configured in the task definition.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315549(v=ws.10).aspx">Event ID 111</a> on TechNet.</remarks> JobTermination = 111, /// <summary>Task Scheduler could not start a task because the network was unavailable. Ensure the computer is connected to the required network as specified in the task.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363779(v=ws.10).aspx">Event ID 112</a> on TechNet.</remarks> JobNoStartWithoutNetwork = 112, /// <summary>The Task Scheduler registered the a task, but not all the specified triggers will start the task. Ensure all the task triggers are valid.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315656(v=ws.10).aspx">Event ID 113</a> on TechNet.</remarks> TaskRegisteredWithoutSomeTriggers = 113, /// <summary>Task Scheduler could not launch a task as scheduled. Instance is started now as required by the configuration option to start the task when available, if the scheduled time is missed.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/cc775066(v=ws.10).aspx">Event ID 114</a> on TechNet.</remarks> MissedTaskLaunched = 114, /// <summary>Task Scheduler failed to roll back a transaction when updating or deleting a task.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315711(v=ws.10).aspx">Event ID 115</a> on TechNet.</remarks> TransactionRollbackFailure = 115, /// <summary>Task Scheduler saved the configuration for a task, but the credentials used to run the task could not be stored.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363682(v=ws.10).aspx">Event ID 116</a> on TechNet.</remarks> TaskRegisteredWithoutCredentials = 116, /// <summary>Task Scheduler launched an instance of a task due to an idle condition.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315755(v=ws.10).aspx">Event ID 117</a> on TechNet.</remarks> IdleTrigger = 117, /// <summary>Task Scheduler launched an instance of a task due to system startup.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/cc775107(v=ws.10).aspx">Event ID 118</a> on TechNet.</remarks> BootTrigger = 118, /// <summary>Task Scheduler launched an instance of a task due to a user logon.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315498(v=ws.10).aspx">Event ID 119</a> on TechNet.</remarks> LogonTrigger = 119, /// <summary>Task Scheduler launched an instance of a task due to a user connecting to the console.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315609(v=ws.10).aspx">Event ID 120</a> on TechNet.</remarks> ConsoleConnectTrigger = 120, /// <summary>Task Scheduler launched an instance of a task due to a user disconnecting from the console.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363748(v=ws.10).aspx">Event ID 121</a> on TechNet.</remarks> ConsoleDisconnectTrigger = 121, /// <summary>Task Scheduler launched an instance of a task due to a user remotely connecting.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/cc774994(v=ws.10).aspx">Event ID 122</a> on TechNet.</remarks> RemoteConnectTrigger = 122, /// <summary>Task Scheduler launched an instance of a task due to a user remotely disconnecting.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/cc775034(v=ws.10).aspx">Event ID 123</a> on TechNet.</remarks> RemoteDisconnectTrigger = 123, /// <summary>Task Scheduler launched an instance of a task due to a user locking the computer.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315499(v=ws.10).aspx">Event ID 124</a> on TechNet.</remarks> SessionLockTrigger = 124, /// <summary>Task Scheduler launched an instance of a task due to a user unlocking the computer.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/cc727048(v=ws.10).aspx">Event ID 125</a> on TechNet.</remarks> SessionUnlockTrigger = 125, /// <summary>Task Scheduler failed to execute a task. Task Scheduler is attempting to restart the task.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363647(v=ws.10).aspx">Event ID 126</a> on TechNet.</remarks> FailedTaskRestart = 126, /// <summary>Task Scheduler failed to execute a task due to a shutdown race condition. Task Scheduler is attempting to restart the task.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/cc726976(v=ws.10).aspx">Event ID 127</a> on TechNet.</remarks> RejectedTaskRestart = 127, /// <summary>Task Scheduler did not launch a task because the current time exceeds the configured task end time.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315638(v=ws.10).aspx">Event ID 128</a> on TechNet.</remarks> IgnoredTaskStart = 128, /// <summary>Task Scheduler launched an instance of a task in a new process.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315544(v=ws.10).aspx">Event ID 129</a> on TechNet.</remarks> CreatedTaskProcess = 129, /// <summary>The Task Scheduler service failed to start a task due to the service being busy.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315521(v=ws.10).aspx">Event ID 130</a> on TechNet.</remarks> TaskNotRunServiceBusy = 130, /// <summary>Task Scheduler failed to start a task because the number of tasks in the task queue exceeds the quota currently configured.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363733(v=ws.10).aspx">Event ID 131</a> on TechNet.</remarks> TaskNotStartedTaskQueueQuotaExceeded = 131, /// <summary>The Task Scheduler task launching queue quota is approaching its preset limit of tasks currently configured.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363705(v=ws.10).aspx">Event ID 132</a> on TechNet.</remarks> TaskQueueQuotaApproaching = 132, /// <summary>Task Scheduler failed to start a task in the task engine for a user.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315645(v=ws.10).aspx">Event ID 133</a> on TechNet.</remarks> TaskNotStartedEngineQuotaExceeded = 133, /// <summary>Task Engine for a user is approaching its preset limit of tasks.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/cc774865(v=ws.10).aspx">Event ID 134</a> on TechNet.</remarks> EngineQuotaApproaching = 134, /// <summary>Task Scheduler did not launch a task because launch condition not met, machine not idle.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363654(v=ws.10).aspx">Event ID 135</a> on TechNet.</remarks> NotStartedWithoutIdle = 135, /// <summary>A user updated Task Scheduler a task</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363717(v=ws.10).aspx">Event ID 140</a> on TechNet.</remarks> TaskUpdated = 140, /// <summary>A user deleted Task Scheduler a task</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd348535(v=ws.10).aspx">Event ID 141</a> on TechNet.</remarks> TaskDeleted = 141, /// <summary>A user disabled Task Scheduler a task</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363727(v=ws.10).aspx">Event ID 142</a> on TechNet.</remarks> TaskDisabled = 142, /// <summary>Task Scheduler woke up the computer to run a task.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/cc775065(v=ws.10).aspx">Event ID 145</a> on TechNet.</remarks> TaskStartedOnComputerWakeup = 145, /// <summary>Task Scheduler failed to subscribe the event trigger for a task.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315495(v=ws.10).aspx">Event ID 150</a> on TechNet.</remarks> TaskEventSubscriptionFailed = 150, /// <summary>Task Scheduler launched an action in an instance of a task.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/cc775088(v=ws.10).aspx">Event ID 200</a> on TechNet.</remarks> ActionStart = 200, /// <summary>Task Scheduler successfully completed a task instance and action.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd348568(v=ws.10).aspx">Event ID 201</a> on TechNet.</remarks> ActionSuccess = 201, /// <summary>Task Scheduler failed to complete an instance of a task with an action.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315592(v=ws.10).aspx">Event ID 202</a> on TechNet.</remarks> ActionFailure = 202, /// <summary>Task Scheduler failed to launch an action in a task instance.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363729(v=ws.10).aspx">Event ID 203</a> on TechNet.</remarks> ActionLaunchFailure = 203, /// <summary>Task Scheduler failed to retrieve the event triggering values for a task . The event will be ignored.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd348579(v=ws.10).aspx">Event ID 204</a> on TechNet.</remarks> EventRenderFailed = 204, /// <summary>Task Scheduler failed to match the pattern of events for a task. The events will be ignored.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363661(v=ws.10).aspx">Event ID 205</a> on TechNet.</remarks> EventAggregateFailed = 205, /// <summary>Task Scheduler is shutting down the a task engine.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd348583(v=ws.10).aspx">Event ID 301</a> on TechNet.</remarks> SessionExit = 301, /// <summary>Task Scheduler is shutting down the a task engine due to an error. </summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/cc727080(v=ws.10).aspx">Event ID 303</a> on TechNet.</remarks> SessionError = 303, /// <summary>Task Scheduler sent a task to a task engine.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315534(v=ws.10).aspx">Event ID 304</a> on TechNet.</remarks> SessionSentJob = 304, /// <summary>Task Scheduler did not send a task to a task engine.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363776(v=ws.10).aspx">Event ID 305</a> on TechNet.</remarks> SessionSentJobFailed = 305, /// <summary>For a Task Scheduler task engine, the thread pool failed to process the message.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315525(v=ws.10).aspx">Event ID 306</a> on TechNet.</remarks> SessionFailedToProcessMessage = 306, /// <summary>The Task Scheduler service failed to connect to a task engine process.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315605(v=ws.10).aspx">Event ID 307</a> on TechNet.</remarks> SessionManagerConnectFailed = 307, /// <summary>Task Scheduler connected to a task engine process.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315746(v=ws.10).aspx">Event ID 308</a> on TechNet.</remarks> SessionConnected = 308, /// <summary>There are Task Scheduler tasks orphaned during a task engine shutdown.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd348580(v=ws.10).aspx">Event ID 309</a> on TechNet.</remarks> SessionJobsOrphaned = 309, /// <summary>Task Scheduler started a task engine process.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315668(v=ws.10).aspx">Event ID 310</a> on TechNet.</remarks> SessionProcessStarted = 310, /// <summary>Task Scheduler failed to start a task engine process due to an error.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363691(v=ws.10).aspx">Event ID 311</a> on TechNet.</remarks> SessionProcessLaunchFailed = 311, /// <summary>Task Scheduler created the Win32 job object for a task engine.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/cc775071(v=ws.10).aspx">Event ID 312</a> on TechNet.</remarks> SessionWin32ObjectCreated = 312, /// <summary>The Task Scheduler channel is ready to send and receive messages.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363685(v=ws.10).aspx">Event ID 313</a> on TechNet.</remarks> SessionChannelReady = 313, /// <summary>Task Scheduler has no tasks running for a task engine, and the idle timer has started.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315517(v=ws.10).aspx">Event ID 314</a> on TechNet.</remarks> SessionIdle = 314, /// <summary>A task engine process failed to connect to the Task Scheduler service.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363798(v=ws.10).aspx">Event ID 315</a> on TechNet.</remarks> SessionProcessConnectFailed = 315, /// <summary>A task engine failed to send a message to the Task Scheduler service.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315748(v=ws.10).aspx">Event ID 316</a> on TechNet.</remarks> SessionMessageSendFailed = 316, /// <summary>Task Scheduler started a task engine process.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315663(v=ws.10).aspx">Event ID 317</a> on TechNet.</remarks> SessionProcessMainStarted = 317, /// <summary>Task Scheduler shut down a task engine process.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/cc727204(v=ws.10).aspx">Event ID 318</a> on TechNet.</remarks> SessionProcessMainShutdown = 318, /// <summary>A task engine received a message from the Task Scheduler service requesting to launch a task.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363712(v=ws.10).aspx">Event ID 319</a> on TechNet.</remarks> SessionProcessReceivedStartJob = 319, /// <summary>A task engine received a message from the Task Scheduler service requesting to stop a task instance.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/cc774993(v=ws.10).aspx">Event ID 320</a> on TechNet.</remarks> SessionProcessReceivedStopJob = 320, /// <summary>Task Scheduler did not launch a task because an instance of the same task is already running.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315618(v=ws.10).aspx">Event ID 322</a> on TechNet.</remarks> NewInstanceIgnored = 322, /// <summary>Task Scheduler stopped an instance of a task in order to launch a new instance.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315542(v=ws.10).aspx">Event ID 323</a> on TechNet.</remarks> RunningInstanceStopped = 323, /// <summary>Task Scheduler queued an instance of a task and will launch it as soon as another instance completes.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363759(v=ws.10).aspx">Event ID 324</a> on TechNet.</remarks> NewInstanceQueued = 324, /// <summary>Task Scheduler queued an instance of a task that will launch immediately.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363654(v=ws.10).aspx">Event ID 325</a> on TechNet.</remarks> InstanceQueued = 325, /// <summary>Task Scheduler did not launch a task because the computer is running on batteries. If launching the task on batteries is required, change the respective flag in the task configuration.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315644(v=ws.10).aspx">Event ID 326</a> on TechNet.</remarks> NoStartOnBatteries = 326, /// <summary>Task Scheduler stopped an instance of a task because the computer is switching to battery power.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd348611(v=ws.10).aspx">Event ID 327</a> on TechNet.</remarks> StoppingOnBatteries = 327, /// <summary>Task Scheduler stopped an instance of a task because the computer is no longer idle.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363732(v=ws.10).aspx">Event ID 328</a> on TechNet.</remarks> StoppingOffIdle = 328, /// <summary>Task Scheduler stopped an instance of a task because the task timed out.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd348536(v=ws.10).aspx">Event ID 329</a> on TechNet.</remarks> StoppingOnTimeout = 329, /// <summary>Task Scheduler stopped an instance of a task as request by a user .</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd348610(v=ws.10).aspx">Event ID 330</a> on TechNet.</remarks> StoppingOnRequest = 330, /// <summary>Task Scheduler will continue to execute an instance of a task even after the designated timeout, due to a failure to create the timeout mechanism.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315673(v=ws.10).aspx">Event ID 331</a> on TechNet.</remarks> TimeoutWontWork = 331, /// <summary>Task Scheduler did not launch a task because a user was not logged on when the launching conditions were met. Ensure the user is logged on or change the task definition to allow the task to launch when the user is logged off.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315612(v=ws.10).aspx">Event ID 332</a> on TechNet.</remarks> NoStartUserNotLoggedOn = 332, /// <summary>The Task Scheduler service has started.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315626(v=ws.10).aspx">Event ID 400</a> on TechNet.</remarks> ScheduleServiceStart = 400, /// <summary>The Task Scheduler service failed to start due to an error.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363598(v=ws.10).aspx">Event ID 401</a> on TechNet.</remarks> ScheduleServiceStartFailed = 401, /// <summary>Task Scheduler service is shutting down.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363724(v=ws.10).aspx">Event ID 402</a> on TechNet.</remarks> ScheduleServiceStop = 402, /// <summary>The Task Scheduler service has encountered an error.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315744(v=ws.10).aspx">Event ID 403</a> on TechNet.</remarks> ScheduleServiceError = 403, /// <summary>The Task Scheduler service has encountered an RPC initialization error.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363713(v=ws.10).aspx">Event ID 404</a> on TechNet.</remarks> ScheduleServiceRpcInitError = 404, /// <summary>The Task Scheduler service has failed to initialize COM.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363728(v=ws.10).aspx">Event ID 405</a> on TechNet.</remarks> ScheduleServiceComInitError = 405, /// <summary>The Task Scheduler service failed to initialize the credentials store.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315727(v=ws.10).aspx">Event ID 406</a> on TechNet.</remarks> ScheduleServiceCredStoreInitError = 406, /// <summary>Task Scheduler service failed to initialize LSA.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315580(v=ws.10).aspx">Event ID 407</a> on TechNet.</remarks> ScheduleServiceLsaInitError = 407, /// <summary>Task Scheduler service failed to initialize idle state detection module. Idle tasks may not be started as required.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315523(v=ws.10).aspx">Event ID 408</a> on TechNet.</remarks> ScheduleServiceIdleServiceInitError = 408, /// <summary>The Task Scheduler service failed to initialize a time change notification. System time updates may not be picked by the service and task schedules may not be updated.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/cc774954(v=ws.10).aspx">Event ID 409</a> on TechNet.</remarks> ScheduleServiceTimeChangeInitError = 409, /// <summary>Task Scheduler service received a time system change notification.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315633(v=ws.10).aspx">Event ID 411</a> on TechNet.</remarks> ScheduleServiceTimeChangeSignaled = 411, /// <summary>Task Scheduler service failed to launch tasks triggered by computer startup. Restart the Task Scheduler service.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315637(v=ws.10).aspx">Event ID 412</a> on TechNet.</remarks> ScheduleServiceRunBootJobsFailed = 412, /// <summary>Task Scheduler service started Task Compatibility module.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/cc727087(v=ws.10).aspx">Event ID 700</a> on TechNet.</remarks> CompatStart = 700, /// <summary>Task Scheduler service failed to start Task Compatibility module. Tasks may not be able to register on previous Window versions.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315530(v=ws.10).aspx">Event ID 701</a> on TechNet.</remarks> CompatStartFailed = 701, /// <summary>Task Scheduler failed to initialize the RPC server for starting the Task Compatibility module. Tasks may not be able to register on previous Window versions.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315721(v=ws.10).aspx">Event ID 702</a> on TechNet.</remarks> CompatStartRpcFailed = 702, /// <summary>Task Scheduler failed to initialize Net Schedule API for starting the Task Compatibility module. Tasks may not be able to register on previous Window versions.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd348604(v=ws.10).aspx">Event ID 703</a> on TechNet.</remarks> CompatStartNetscheduleFailed = 703, /// <summary>Task Scheduler failed to initialize LSA for starting the Task Compatibility module. Tasks may not be able to register on previous Window versions.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315572(v=ws.10).aspx">Event ID 704</a> on TechNet.</remarks> CompatStartLsaFailed = 704, /// <summary>Task Scheduler failed to start directory monitoring for the Task Compatibility module.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/cc727147(v=ws.10).aspx">Event ID 705</a> on TechNet.</remarks> CompatDirectoryMonitorFailed = 705, /// <summary>Task Compatibility module failed to update a task to the required status.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315682(v=ws.10).aspx">Event ID 706</a> on TechNet.</remarks> CompatTaskStatusUpdateFailed = 706, /// <summary>Task Compatibility module failed to delete a task.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd348545(v=ws.10).aspx">Event ID 707</a> on TechNet.</remarks> CompatTaskDeleteFailed = 707, /// <summary>Task Compatibility module failed to set a security descriptor for a task.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315719(v=ws.10).aspx">Event ID 708</a> on TechNet.</remarks> CompatTaskSetSdFailed = 708, /// <summary>Task Compatibility module failed to update a task.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363614(v=ws.10).aspx">Event ID 709</a> on TechNet.</remarks> CompatTaskUpdateFailed = 709, /// <summary>Task Compatibility module failed to upgrade existing tasks. Upgrade will be attempted again next time 'Task Scheduler' service starts.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363608(v=ws.10).aspx">Event ID 710</a> on TechNet.</remarks> CompatUpgradeStartFailed = 710, /// <summary>Task Compatibility module failed to upgrade NetSchedule account.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd348554(v=ws.10).aspx">Event ID 711</a> on TechNet.</remarks> CompatUpgradeNsAccountFailed = 711, /// <summary>Task Compatibility module failed to read existing store to upgrade tasks.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315519(v=ws.10).aspx">Event ID 712</a> on TechNet.</remarks> CompatUpgradeStoreEnumFailed = 712, /// <summary>Task Compatibility module failed to load a task for upgrade.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315728(v=ws.10).aspx">Event ID 713</a> on TechNet.</remarks> CompatUpgradeTaskLoadFailed = 713, /// <summary>Task Compatibility module failed to register a task for upgrade.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd363701(v=ws.10).aspx">Event ID 714</a> on TechNet.</remarks> CompatUpgradeTaskRegistrationFailed = 714, /// <summary>Task Compatibility module failed to delete LSA store for upgrade.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd348581(v=ws.10).aspx">Event ID 715</a> on TechNet.</remarks> CompatUpgradeLsaCleanupFailed = 715, /// <summary>Task Compatibility module failed to upgrade existing scheduled tasks.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315624(v=ws.10).aspx">Event ID 716</a> on TechNet.</remarks> CompatUpgradeFailed = 716, /// <summary>Task Compatibility module failed to determine if upgrade is needed.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd315731(v=ws.10).aspx">Event ID 717</a> on TechNet.</remarks> CompatUpgradeNeedNotDetermined = 717, /// <summary>Task scheduler was unable to upgrade the credential store from the Beta 2 version. You may need to re-register any tasks that require passwords.</summary> /// <remarks>For detailed information, see the documentation for <a href="https://technet.microsoft.com/en-us/library/dd348576(v=ws.10).aspx">Event ID 718</a> on TechNet.</remarks> VistaBeta2CredstoreUpgradeFailed = 718, /// <summary>A unknown value.</summary> Unknown = -2 } /// <summary> /// Historical event information for a task. This class wraps and extends the <see cref="EventRecord"/> class. /// </summary> /// <remarks> /// For events on systems prior to Windows Vista, this class will only have information for the TaskPath, TimeCreated and EventId properties. /// </remarks> [PublicAPI] public sealed class TaskEvent : IComparable<TaskEvent> { internal TaskEvent([NotNull] EventRecord rec) { EventId = rec.Id; EventRecord = rec; Version = rec.Version; TaskCategory = rec.TaskDisplayName; OpCode = rec.OpcodeDisplayName; TimeCreated = rec.TimeCreated; RecordId = rec.RecordId; ActivityId = rec.ActivityId; Level = rec.LevelDisplayName; UserId = rec.UserId; ProcessId = rec.ProcessId; TaskPath = rec.Properties.Count > 0 ? rec.Properties[0]?.Value?.ToString() : null; DataValues = new EventDataValues(rec as EventLogRecord); } internal TaskEvent([NotNull] string taskPath, StandardTaskEventId id, DateTime time) { EventId = (int)id; TaskPath = taskPath; TimeCreated = time; } /// <summary> /// Gets the activity id. This value is <c>null</c> for V1 events. /// </summary> public Guid? ActivityId { get; internal set; } /// <summary> /// An indexer that gets the value of each of the data item values. This value is <c>null</c> for V1 events. /// </summary> /// <value> /// The data values. /// </value> public EventDataValues DataValues { get; } /// <summary> /// Gets the event id. /// </summary> public int EventId { get; internal set; } /// <summary> /// Gets the underlying <see cref="EventRecord"/>. This value is <c>null</c> for V1 events. /// </summary> public EventRecord EventRecord { get; internal set; } /// <summary> /// Gets the <see cref="StandardTaskEventId"/> from the <see cref="EventId"/>. /// </summary> /// <value> /// The <see cref="StandardTaskEventId"/>. If not found, returns <see cref="StandardTaskEventId.Unknown"/>. /// </value> public StandardTaskEventId StandardEventId { get { if (Enum.IsDefined(typeof(StandardTaskEventId), EventId)) return (StandardTaskEventId)EventId; return StandardTaskEventId.Unknown; } } /// <summary> /// Gets the level. This value is <c>null</c> for V1 events. /// </summary> public string Level { get; internal set; } /// <summary> /// Gets the op code. This value is <c>null</c> for V1 events. /// </summary> public string OpCode { get; internal set; } /// <summary> /// Gets the process id. This value is <c>null</c> for V1 events. /// </summary> public int? ProcessId { get; internal set; } /// <summary> /// Gets the record id. This value is <c>null</c> for V1 events. /// </summary> public long? RecordId { get; internal set; } /// <summary> /// Gets the task category. This value is <c>null</c> for V1 events. /// </summary> public string TaskCategory { get; internal set; } /// <summary> /// Gets the task path. /// </summary> public string TaskPath { get; internal set; } /// <summary> /// Gets the time created. /// </summary> public DateTime? TimeCreated { get; internal set; } /// <summary> /// Gets the user id. This value is <c>null</c> for V1 events. /// </summary> public System.Security.Principal.SecurityIdentifier UserId { get; internal set; } /// <summary> /// Gets the version. This value is <c>null</c> for V1 events. /// </summary> public byte? Version { get; internal set; } /// <summary> /// Gets the data value from the task specific event data item list. /// </summary> /// <param name="name">The name of the data element.</param> /// <returns>Contents of the requested data element if found. <c>null</c> if no value found.</returns> [Obsolete("Use the DataVales property instead.")] public string GetDataValue(string name) => DataValues?[name]; /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() => EventRecord?.FormatDescription() ?? TaskPath; /// <summary> /// Compares the current object with another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the other parameter.Zero This object is equal to other. Greater than zero This object is greater than other. /// </returns> public int CompareTo(TaskEvent other) { int i = string.Compare(TaskPath, other.TaskPath, StringComparison.Ordinal); if (i == 0 && EventRecord != null) { i = string.Compare(ActivityId.ToString(), other.ActivityId.ToString(), StringComparison.Ordinal); if (i == 0) i = Convert.ToInt32(RecordId - other.RecordId); } return i; } /// <summary> /// Get indexer class for <see cref="EventLogRecord"/> data values. /// </summary> public class EventDataValues { private readonly EventLogRecord rec; internal EventDataValues(EventLogRecord eventRec) { rec = eventRec; } /// <summary> /// Gets the <see cref="System.String"/> value of the specified property name. /// </summary> /// <value> /// The value. /// </value> /// <param name="propertyName">Name of the property.</param> /// <returns>Value of the specified property name. <c>null</c> if property does not exist.</returns> public string this[string propertyName] { get { var propsel = new EventLogPropertySelector(new[] { $"Event/EventData/Data[@Name='{propertyName}']" }); try { var logEventProps = rec.GetPropertyValues(propsel); return logEventProps[0].ToString(); } catch { } return null; } } } } /// <summary> /// An enumerator over a task's history of events. /// </summary> public sealed class TaskEventEnumerator : IEnumerator<TaskEvent> { private EventRecord curRec; private EventLogReader log; internal TaskEventEnumerator([NotNull] EventLogReader log) { this.log = log; } /// <summary> /// Gets the element in the collection at the current position of the enumerator. /// </summary> /// <returns> /// The element in the collection at the current position of the enumerator. /// </returns> public TaskEvent Current => new TaskEvent(curRec); /// <summary> /// Gets the element in the collection at the current position of the enumerator. /// </summary> /// <returns> /// The element in the collection at the current position of the enumerator. /// </returns> object System.Collections.IEnumerator.Current => Current; /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { log.CancelReading(); log.Dispose(); log = null; } /// <summary> /// Advances the enumerator to the next element of the collection. /// </summary> /// <returns> /// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection. /// </returns> /// <exception cref="T:System.InvalidOperationException"> /// The collection was modified after the enumerator was created. /// </exception> public bool MoveNext() => (curRec = log.ReadEvent()) != null; /// <summary> /// Sets the enumerator to its initial position, which is before the first element in the collection. /// </summary> /// <exception cref="T:System.InvalidOperationException"> /// The collection was modified after the enumerator was created. /// </exception> public void Reset() { log.Seek(System.IO.SeekOrigin.Begin, 0L); } /// <summary> /// Seeks the specified bookmark. /// </summary> /// <param name="bookmark">The bookmark.</param> /// <param name="offset">The offset.</param> public void Seek(EventBookmark bookmark, long offset = 0L) { log.Seek(bookmark, offset); } /// <summary> /// Seeks the specified origin. /// </summary> /// <param name="origin">The origin.</param> /// <param name="offset">The offset.</param> public void Seek(System.IO.SeekOrigin origin, long offset) { log.Seek(origin, offset); } } /// <summary> /// Historical event log for a task. Only available for Windows Vista and Windows Server 2008 and later systems. /// </summary> /// <remarks>Many applications have the need to audit the execution of the tasks they supply. To enable this, the library provides the TaskEventLog class that allows for TaskEvent instances to be enumerated. This can be done for single tasks or the entire system. It can also be filtered by specific events or criticality.</remarks> /// <example><code lang="cs"><![CDATA[ /// // Create a log instance for the Maint task in the root directory /// TaskEventLog log = new TaskEventLog(@"\Maint", /// // Specify the event id(s) you want to enumerate /// new int[] { 141 /* TaskDeleted */, 201 /* ActionSuccess */ }, /// // Specify the start date of the events to enumerate. Here, we look at the last week. /// DateTime.Now.AddDays(-7)); /// /// // Tell the enumerator to expose events 'newest first' /// log.EnumerateInReverse = false; /// /// // Enumerate the events /// foreach (TaskEvent ev in log) /// { /// // TaskEvents can interpret event ids into a well known, readable, enumerated type /// if (ev.StandardEventId == StandardTaskEventId.TaskDeleted) /// output.WriteLine($" Task '{ev.TaskPath}' was deleted"); /// /// // TaskEvent exposes a number of properties regarding the event /// else if (ev.EventId == 201) /// output.WriteLine($" Completed action '{ev.DataValues["ActionName"]}', /// ({ev.DataValues["ResultCode"]}) at {ev.TimeCreated.Value}."); /// } /// ]]></code></example> public sealed class TaskEventLog : IEnumerable<TaskEvent> { private const string TSEventLogPath = "Microsoft-Windows-TaskScheduler/Operational"; private static readonly bool IsVistaOrLater = Environment.OSVersion.Version.Major >= 6; /// <summary> /// Initializes a new instance of the <see cref="TaskEventLog"/> class. /// </summary> /// <param name="taskPath">The task path. This can be retrieved using the <see cref="Task.Path"/> property.</param> /// <exception cref="NotSupportedException">Thrown when instantiated on an OS prior to Windows Vista.</exception> public TaskEventLog([CanBeNull] string taskPath) : this(".", taskPath) { Initialize(".", BuildQuery(taskPath), true); } /// <summary> /// Initializes a new instance of the <see cref="TaskEventLog" /> class. /// </summary> /// <param name="machineName">Name of the machine.</param> /// <param name="taskPath">The task path. This can be retrieved using the <see cref="Task.Path" /> property.</param> /// <param name="domain">The domain.</param> /// <param name="user">The user.</param> /// <param name="password">The password.</param> /// <exception cref="NotSupportedException">Thrown when instantiated on an OS prior to Windows Vista.</exception> public TaskEventLog([NotNull] string machineName, [CanBeNull] string taskPath, string domain = null, string user = null, string password = null) { Initialize(machineName, BuildQuery(taskPath), true, domain, user, password); } /// <summary> /// Initializes a new instance of the <see cref="TaskEventLog" /> class that looks at all task events from a specified time. /// </summary> /// <param name="startTime">The start time.</param> /// <param name="taskName">Name of the task.</param> /// <param name="machineName">Name of the machine (optional).</param> /// <param name="domain">The domain.</param> /// <param name="user">The user.</param> /// <param name="password">The password.</param> public TaskEventLog(DateTime startTime, string taskName = null, string machineName = null, string domain = null, string user = null, string password = null) { int[] numArray = new int[] { 100, 102, 103, 107, 108, 109, 111, 117, 118, 119, 120, 121, 122, 123, 124, 125 }; Initialize(machineName, BuildQuery(taskName, numArray, startTime), false, domain, user, password); } /// <summary> /// Initializes a new instance of the <see cref="TaskEventLog"/> class. /// </summary> /// <param name="taskName">Name of the task.</param> /// <param name="eventIDs">The event ids.</param> /// <param name="startTime">The start time.</param> /// <param name="machineName">Name of the machine (optional).</param> /// <param name="domain">The domain.</param> /// <param name="user">The user.</param> /// <param name="password">The password.</param> public TaskEventLog(string taskName = null, int[] eventIDs = null, DateTime? startTime = null, string machineName = null, string domain = null, string user = null, string password = null) { Initialize(machineName, BuildQuery(taskName, eventIDs, startTime), true, domain, user, password); } /// <summary> /// Initializes a new instance of the <see cref="TaskEventLog" /> class. /// </summary> /// <param name="taskName">Name of the task.</param> /// <param name="eventIDs">The event ids.</param> /// <param name="levels">The levels.</param> /// <param name="startTime">The start time.</param> /// <param name="machineName">Name of the machine (optional).</param> /// <param name="domain">The domain.</param> /// <param name="user">The user.</param> /// <param name="password">The password.</param> public TaskEventLog(string taskName = null, int[] eventIDs = null, int[] levels = null, DateTime? startTime = null, string machineName = null, string domain = null, string user = null, string password = null) { Initialize(machineName, BuildQuery(taskName, eventIDs, startTime, levels), true, domain, user, password); } internal static string BuildQuery(string taskName = null, int[] eventIDs = null, DateTime? startTime = null, int[] levels = null) { const string queryString = "<QueryList>" + " <Query Id=\"0\" Path=\"" + TSEventLogPath + "\">" + " <Select Path=\"" + TSEventLogPath + "\">{0}</Select>" + " </Query>" + "</QueryList>"; const string OR = " or "; const string AND = " and "; System.Text.StringBuilder sb = new System.Text.StringBuilder("*"); if (eventIDs != null && eventIDs.Length > 0) { if (sb.Length > 1) sb.Append(AND); sb.AppendFormat("({0})", string.Join(OR, Array.ConvertAll(eventIDs, i => $"EventID={i}"))); } if (levels != null && levels.Length > 0) { if (sb.Length > 1) sb.Append(AND); sb.AppendFormat("({0})", string.Join(OR, Array.ConvertAll(levels, i => $"Level={i}"))); } if (startTime.HasValue) { if (sb.Length > 1) sb.Append(AND); sb.AppendFormat("TimeCreated[@SystemTime>='{0}']", System.Xml.XmlConvert.ToString(startTime.Value, System.Xml.XmlDateTimeSerializationMode.RoundtripKind)); } if (sb.Length > 1) { sb.Insert(1, "[System[Provider[@Name='Microsoft-Windows-TaskScheduler'] and "); sb.Append(']'); } if (!string.IsNullOrEmpty(taskName)) { if (sb.Length == 1) sb.Append('['); else sb.Append("]" + AND + "*["); sb.AppendFormat("EventData[Data[@Name='TaskName']='{0}']", taskName); } if (sb.Length > 1) sb.Append(']'); return string.Format(queryString, sb); } private void Initialize(string machineName, string query, bool revDir, string domain = null, string user = null, string password = null) { if (!IsVistaOrLater) throw new NotSupportedException("Enumeration of task history not available on systems prior to Windows Vista and Windows Server 2008."); System.Security.SecureString spwd = null; if (password != null) { spwd = new System.Security.SecureString(); foreach (char c in password) spwd.AppendChar(c); } Query = new EventLogQuery(TSEventLogPath, PathType.LogName, query) { ReverseDirection = revDir }; if (machineName != null && machineName != "." && !machineName.Equals(Environment.MachineName, StringComparison.InvariantCultureIgnoreCase)) Query.Session = new EventLogSession(machineName, domain, user, spwd, SessionAuthentication.Default); } /// <summary> /// Gets the total number of events for this task. /// </summary> public long Count { get { using (EventLogReader log = new EventLogReader(Query)) { long seed = 64L, l = 0L, h = seed; while (log.ReadEvent() != null) log.Seek(System.IO.SeekOrigin.Begin, l += seed); bool foundLast = false; while (l > 0L && h >= 1L) { if (foundLast) l += (h /= 2L); else l -= (h /= 2L); log.Seek(System.IO.SeekOrigin.Begin, l); foundLast = (log.ReadEvent() != null); } return foundLast ? l + 1L : l; } } } /// <summary> /// Gets or sets a value indicating whether this <see cref="TaskEventLog" /> is enabled. /// </summary> /// <value> /// <c>true</c> if enabled; otherwise, <c>false</c>. /// </value> public bool Enabled { get { if (!IsVistaOrLater) return false; using (var cfg = new EventLogConfiguration(TSEventLogPath, Query.Session)) return cfg.IsEnabled; } set { if (!IsVistaOrLater) throw new NotSupportedException("Task history not available on systems prior to Windows Vista and Windows Server 2008."); using (var cfg = new EventLogConfiguration(TSEventLogPath, Query.Session)) { if (cfg.IsEnabled != value) { cfg.IsEnabled = value; cfg.SaveChanges(); } } } } /// <summary> /// Gets or sets a value indicating whether to enumerate in reverse when calling the default enumerator (typically with foreach statement). /// </summary> /// <value> /// <c>true</c> if enumerates in reverse (newest to oldest) by default; otherwise, <c>false</c> to enumerate oldest to newest. /// </value> [System.ComponentModel.DefaultValue(false)] public bool EnumerateInReverse { get; set; } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> IEnumerator<TaskEvent> IEnumerable<TaskEvent>.GetEnumerator() => GetEnumerator(EnumerateInReverse); /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <param name="reverse">if set to <c>true</c> reverse.</param> /// <returns> /// A <see cref="TaskEventEnumerator" /> that can be used to iterate through the collection. /// </returns> [NotNull] public TaskEventEnumerator GetEnumerator(bool reverse) { Query.ReverseDirection = !reverse; return new TaskEventEnumerator(new EventLogReader(Query)); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(false); internal EventLogQuery Query { get; private set; } } }
62.153584
333
0.715941
[ "MIT" ]
0rlixxx/PEASS-ng
winPEAS/winPEASexe/winPEAS/TaskScheduler/TaskEvent.cs
54,635
C#
using Orchard.Environment.Extensions; using Orchard.Localization; using Orchard.UI.Navigation; namespace Piedone.ContentTypes { [OrchardFeature("Piedone.ContentTypes.ContentLinks")] public class ContentLinksAdminMenu : INavigationProvider { public Localizer T { get; set; } public string MenuName { get { return "admin"; } } public void GetNavigation(NavigationBuilder builder) { builder.AddImageSet("content-link"); } } }
28.333333
61
0.660784
[ "BSD-3-Clause" ]
Lombiq/Orchard-Content-Types
ContentLinksAdminMenu.cs
512
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Mvc; using Microsoft.Data.Entity; using Microsoft.Extensions.Caching.Memory; using MusicStore.Models; namespace MusicStore.Controllers { public class HomeController : Controller { [FromServices] public MusicStoreContext DbContext { get; set; } [FromServices] public IMemoryCache Cache { get; set; } // // GET: /Home/ public async Task<IActionResult> Index() { // Get most popular albums var cacheKey = "topselling"; List<Album> albums; if(!Cache.TryGetValue(cacheKey, out albums)) { albums = await GetTopSellingAlbumsAsync(6); if (albums != null && albums.Count > 0) { // Refresh it every 10 minutes. // Let this be the last item to be removed by cache if cache GC kicks in. Cache.Set( cacheKey, albums, new MemoryCacheEntryOptions() .SetAbsoluteExpiration(TimeSpan.FromMinutes(10)) .SetPriority(CacheItemPriority.High)); } } return View(albums); } public IActionResult Error() { return View("~/Views/Shared/Error.cshtml"); } public IActionResult StatusCodePage() { return View("~/Views/Shared/StatusCodePage.cshtml"); } public IActionResult AccessDenied() { return View("~/Views/Shared/AccessDenied.cshtml"); } private async Task<List<Album>> GetTopSellingAlbumsAsync(int count) { // Group the order details by album and return // the albums with the highest count // TODO [EF] We don't query related data as yet, so the OrderByDescending isn't doing anything return await DbContext.Albums .OrderByDescending(a => a.OrderDetails.Count()) .Take(count) .ToListAsync(); } } }
30.418919
106
0.54287
[ "Apache-2.0" ]
abdelrahmansaeedhassan/angularv2pro
src/MusicStore/Controllers/HomeController.cs
2,251
C#
#region License /* The MIT License * * Copyright (c) 2011 Red Badger Consulting * * 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 //------------------------------------------------------------------------------------------------- // <auto-generated> // Marked as auto-generated so StyleCop will ignore BDD style tests // </auto-generated> //------------------------------------------------------------------------------------------------- #pragma warning disable 169 // ReSharper disable InconsistentNaming // ReSharper disable UnusedMember.Global // ReSharper disable UnusedMember.Local namespace RedBadger.Xpf.Specs.VectorSpecs { using System; using Machine.Specifications; [Subject(typeof(Vector))] public class when_a_vector_is_asked_for_its_length { private static double result; private static Vector subject; private Establish context = () => subject = new Vector(20, 30); private Because of = () => result = subject.Length; private It should_return_the_correct_length = () => result.ShouldEqual(Math.Sqrt(subject.X * subject.X + subject.Y * subject.Y)); } [Subject(typeof(Vector))] public class when_a_vector_is_asked_for_its_length_squared { private static double result; private static Vector subject; private Establish context = () => subject = new Vector(20, 30); private Because of = () => result = subject.LengthSquared; private It should_return_the_correct_length = () => result.ShouldEqual(subject.X * subject.X + subject.Y * subject.Y); } [Subject(typeof(Vector))] public class when_a_vector_is_multiplied { private static Vector result; private static Vector subject; private Establish context = () => subject = new Vector(20, 30); private Because of = () => result = subject * 5d; private It should_have_the_correct_X_component = () => result.X.ShouldEqual(100d); private It should_have_the_correct_Y_component = () => result.Y.ShouldEqual(150d); } [Subject(typeof(Vector))] public class when_a_vector_is_divided { private static Vector result; private static Vector subject; private Establish context = () => subject = new Vector(20, 30); private Because of = () => result = subject / 5d; private It should_have_the_correct_X_component = () => result.X.ShouldEqual(4d); private It should_have_the_correct_Y_component = () => result.Y.ShouldEqual(6d); } [Subject(typeof(Vector))] public class when_a_vector_is_normalized { private static Vector subject; private Establish context = () => subject = new Vector(20, 30); private Because of = () => subject.Normalize(); private It should_have_a_unit_length = () => subject.Length.ShouldEqual(1); } [Subject(typeof(Vector))] public class when_caluculating_the_cross_product { private static double result; private static Vector vector1; private static Vector vector2; private Establish context = () => { vector1 = new Vector(20, 30); vector2 = new Vector(15, 25); }; private Because of = () => result = Vector.CrossProduct(vector1, vector2); private It should_give_the_correct_result = () => result.ShouldEqual(vector1.X * vector2.Y - vector1.Y * vector2.X); } [Subject(typeof(Vector))] public class when_caluculating_the_dot_product { private static double result; private static Vector vector1; private static Vector vector2; private Establish context = () => { vector1 = new Vector(20, 30); vector2 = new Vector(15, 25); }; private Because of = () => result = Vector.DotProduct(vector1, vector2); private It should_give_the_correct_result = () => result.ShouldEqual(vector1.X * vector2.X + vector1.Y * vector2.Y); } [Subject(typeof(Vector))] public class when_caluculating_the_angle_between_two_right_angle_vectors { private static double result; private static Vector vector1; private static Vector vector2; private Establish context = () => { vector1 = new Vector(1, 0); vector2 = new Vector(0, 1); }; private Because of = () => result = Vector.AngleBetween(vector1, vector2); private It should_give_the_correct_result = () => result.ShouldEqual(90); } [Subject(typeof(Vector))] public class when_caluculating_the_angle_between_two_vectors_at_45_degrees { private static double result; private static Vector vector1; private static Vector vector2; private Establish context = () => { vector1 = new Vector(1, 0); vector2 = new Vector(1, 1); }; private Because of = () => result = Vector.AngleBetween(vector1, vector2); private It should_give_the_correct_result = () => result.ShouldEqual(45); } }
32.58794
100
0.612336
[ "MIT" ]
Halofreak1990/XPF
XPF/RedBadger.Xpf.Specs/VectorSpecs/VectorSpecs.cs
6,485
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Threading; using Azure.Messaging.EventHubs.Tests.Infrastructure; namespace Azure.Messaging.EventHubs.Tests { /// <summary> /// Represents the ambient environment in which the test suite is /// being run, offering access to information such as environment /// variables. /// </summary> /// public static class TestEnvironment { /// <summary>The environment variable value for the Event Hubs subscription name, lazily evaluated.</summary> private static readonly Lazy<string> EventHubsSubscriptionInstance = new Lazy<string>(() => ReadAndVerifyEnvironmentVariable("EVENT_HUBS_SUBSCRIPTION"), LazyThreadSafetyMode.PublicationOnly); /// <summary>The environment variable value for the Event Hubs resource group name, lazily evaluated.</summary> private static readonly Lazy<string> EventHubsResourceGroupInstance = new Lazy<string>(() => ReadAndVerifyEnvironmentVariable("EVENT_HUBS_RESOURCEGROUP"), LazyThreadSafetyMode.PublicationOnly); /// <summary>The environment variable value for the Azure Active Directory tenant that holds the service principal, lazily evaluated.</summary> private static readonly Lazy<string> EventHubsTenantInstance = new Lazy<string>(() => ReadAndVerifyEnvironmentVariable("EVENT_HUBS_TENANT"), LazyThreadSafetyMode.PublicationOnly); /// <summary>The environment variable value for the Azure Active Directory client identifier of the service principal, lazily evaluated.</summary> private static readonly Lazy<string> EventHubsClientInstance = new Lazy<string>(() => ReadAndVerifyEnvironmentVariable("EVENT_HUBS_CLIENT"), LazyThreadSafetyMode.PublicationOnly); /// <summary>The environment variable value for the Azure Active Directory client secret of the service principal, lazily evaluated.</summary> private static readonly Lazy<string> EventHubsSecretInstance = new Lazy<string>(() => ReadAndVerifyEnvironmentVariable("EVENT_HUBS_SECRET"), LazyThreadSafetyMode.PublicationOnly); /// <summary>The active Event Hubs namespace for this test run, lazily created.</summary> private static readonly Lazy<EventHubScope.NamespaceProperties> ActiveEventHubsNamespace = new Lazy<EventHubScope.NamespaceProperties>(() => EventHubScope.CreateNamespaceAsync().GetAwaiter().GetResult(), LazyThreadSafetyMode.ExecutionAndPublication); /// <summary>The name of the shared access key to be used for accessing an Event Hubs namespace.</summary> public const string EventHubsDefaultSharedAccessKey = "RootManageSharedAccessKey"; /// <summary> /// Indicates whether or not an ephemeral namespace was created for the current test execution. /// </summary> /// /// <value><c>true</c> if an Event Hubs namespace was created; otherwise, <c>false</c>.</value> /// public static bool WasEventHubsNamespaceCreated => ActiveEventHubsNamespace.IsValueCreated; /// <summary> /// The connection string for the Event Hubs namespace instance to be used for /// Live tests. /// </summary> /// /// <value>The connection string will be determined by creating an ephemeral Event Hubs namespace for the test execution.</value> /// public static string EventHubsConnectionString => ActiveEventHubsNamespace.Value.ConnectionString; /// <summary> /// The name of the Event Hubs namespace to be used for Live tests. /// </summary> /// /// <value>The name will be determined by creating an ephemeral Event Hubs namespace for the test execution.</value> /// public static string EventHubsNamespace => ActiveEventHubsNamespace.Value.Name; /// <summary> /// The name of the Azure subscription containing the Event Hubs namespace instance to be used for /// Live tests. /// </summary> /// /// <value>The name of the namespace is read from the "EVENT_HUBS_SUBSCRIPTION" environment variable.</value> /// public static string EventHubsSubscription => EventHubsSubscriptionInstance.Value; /// <summary> /// The name of the resource group containing the Event Hubs namespace instance to be used for /// Live tests. /// </summary> /// /// <value>The name of the namespace is read from the "EVENT_HUBS_RESOURCEGROUP" environment variable.</value> /// public static string EventHubsResourceGroup => EventHubsResourceGroupInstance.Value; /// <summary> /// The name of the Azure Active Directory tenant that holds the service principal to use for management /// of the Event Hubs namespace during Live tests. /// </summary> /// /// <value>The name of the namespace is read from the "EVENT_HUBS_TENANT" environment variable.</value> /// public static string EventHubsTenant => EventHubsTenantInstance.Value; /// <summary> /// The name of the Azure Active Directory client identifier of the service principal to use for management /// of the Event Hubs namespace during Live tests. /// </summary> /// /// <value>The name of the namespace is read from the "EVENT_HUBS_CLIENT" environment variable.</value> /// public static string EventHubsClient => EventHubsClientInstance.Value; /// <summary> /// The name of the Azure Active Directory client secret of the service principal to use for management /// of the Event Hubs namespace during Live tests. /// </summary> /// /// <value>The name of the namespace is read from the "EVENT_HUBS_SECRET" environment variable.</value> /// public static string EventHubsSecret => EventHubsSecretInstance.Value; /// <summary> /// Builds a connection string for a specific Event Hub instance under the Event Hubs namespace used for /// Live tests. /// </summary> /// /// <value>The namepsace connection string is read from the "EVENT_HUBS_CONNECTION_STRING" environment variable.</value> /// public static string BuildConnectionStringForEventHub(string eventHubName) => $"{ EventHubsConnectionString };EntityPath={eventHubName}"; /// <summary> /// Reads an environment variable, ensuring that it is populated. /// </summary> /// /// <param name="variableName">The name of the environment variable to read.</param> /// /// <returns>The value of the environment variable, if present and populated; otherwise, a <see cref="InvalidOperationException" /> is thrown.</returns> /// private static string ReadAndVerifyEnvironmentVariable(string variableName) { var environmentValue = Environment.GetEnvironmentVariable(variableName); if (String.IsNullOrWhiteSpace(environmentValue)) { throw new InvalidOperationException($"The environment variable '{ variableName }' was not found or was not populated."); } return environmentValue; } } }
51.482759
171
0.674883
[ "MIT" ]
bainian12345/azure-sdk-for-net
sdk/eventhub/Azure.Messaging.EventHubs/tests/Infrastructure/TestEnvironment.cs
7,467
C#
using System; using System.Collections.Generic; using NHibernate.Mapping.ByCode; namespace Breeze.NHibernate.Tests.Models { public class Order : VersionedEntity { public Order() { CreatedDate = DateTime.UtcNow; } public virtual void SetId(long id) { Id = id; } public virtual OrderStatus Status { get; set; } public virtual string Name { get; set; } public virtual decimal TotalPrice { get; set; } public virtual bool Active { get; set; } public virtual Address Address { get; set; } = new Address(); public virtual ISet<OrderProduct> Products { get; set; } = new HashSet<OrderProduct>(); public virtual ISet<OrderProductFk> FkProducts { get; set; } = new HashSet<OrderProductFk>(); } public class OrderMapping : VersionedEntityMapping<Order> { public OrderMapping() : this(Cascade.All, Cascade.All) { } public OrderMapping(Cascade productsCascade, Cascade fkProductsCascade) { Property(o => o.Status, o => o.NotNullable(true)); Property(o => o.Name, o => { o.NotNullable(true); o.Length(20); }); Property(o => o.TotalPrice, o => o.NotNullable(true)); Property(o => o.Active, o => o.NotNullable(true)); Component(o => o.Address, o => { o.Property(c => c.City); o.Property(c => c.Country); o.Property(c => c.HouseNumber); o.Property(c => c.Street); }); Set(o => o.Products, o => { o.Key(k => k.Column("OrderId")); o.Inverse(true); o.Cascade(productsCascade); o.Lazy(CollectionLazy.Extra); }, o => o.OneToMany()); Set(o => o.FkProducts, o => { o.Key(k => k.Column("OrderId")); o.Inverse(true); o.Cascade(fkProductsCascade); o.Lazy(CollectionLazy.Extra); }, o => o.OneToMany()); } } }
29.702703
101
0.505914
[ "MIT" ]
maca88/Breeze.NHibernate
Source/Breeze.NHibernate.Tests.Models/Order.cs
2,200
C#
using System; using System.Collections.Generic; using System.Diagnostics; namespace UberStrok.Core { public class StateMachine<T> where T : struct, IConvertible { private State _current; private readonly Stack<T> _states; private readonly Dictionary<T, State> _registeredStates; public StateMachine() { _states = new Stack<T>(); _registeredStates = new Dictionary<T, State>(); } public T Current => _states.Count > 0 ? _states.Peek() : default(T); public void Register(T stateId, State state) { if (_registeredStates.ContainsKey(stateId)) throw new Exception("Already contains a state handler for the specified state ID."); _registeredStates.Add(stateId, state); } public void Set(T stateId) { var state = default(State); if (!_registeredStates.TryGetValue(stateId, out state)) throw new Exception("No state handler registered for the specified state ID."); if (!Current.Equals(stateId)) { _current?.OnExit(); _current = state; _states.Push(stateId); _current?.OnEnter(); } } public void Previous() { _current?.OnExit(); _states.Pop(); var stateId = _states.Peek(); var exists = _registeredStates.TryGetValue(stateId, out State state); Debug.Assert(exists); _current = state; _current?.OnResume(); } public void Reset() { while (_states.Count > 0) Previous(); } public void Update() { _current?.OnUpdate(); } } }
26.273973
101
0.514077
[ "MIT" ]
recreationx/uberstrok
src/UberStrok.Core/StateMachine.cs
1,920
C#
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Pregunta.Me.Plugin.Contracts.DataTransferObjects; using Pregunta.Me.Core.Administration; using Pregunta.Me.Core.ValueObjects; namespace Pregunta.Me.UnitTests.Core.Administration { [TestClass] public class ExpertInfoTests { [TestMethod] public void Should_BeCorrect_When_SettingUpBillingRate() { // arrange... int expectedId = 1000; string expCur = "USD"; double expRate = 4.5; var dto = new ExpertInfoDto(expectedId) { AreaOfExpertise = "Neurology", BillingCurrency = expCur, BillingRate = expRate, FirstName = "Silvia", LastName = "Velarde" }; var expectedBillingRate = new BillingRate(expRate, expCur); // act... var expert = ExpertInfo.Fetch(dto); // assert... Assert.IsInstanceOfType(expert.BillingRate, typeof(BillingRate)); Assert.AreEqual(expectedBillingRate, expert.BillingRate); } } }
35.37931
179
0.665692
[ "MIT" ]
anibalvelarde/Pregunta.Me
src/Pregunta.Me/Pregunta.Me.UnitTests/Core/Administration/ExpertInfoTests.cs
1,028
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace Proje_1 { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FrmGirisler()); } } }
22.26087
65
0.613281
[ "MIT" ]
YasinBulut/Hastane-Otomasyon-Sistemi
Proje-1/Program.cs
514
C#
using SimpleWebServer; CancellationTokenSource cts = new CancellationTokenSource(); var server = new Server(8080); var serverTask = server.StartAsync(cts.Token); Console.WriteLine("Press any key."); Console.ReadKey(); cts.Cancel(); await serverTask; Console.ReadKey();
27
60
0.777778
[ "MIT" ]
orlfi/SimpleWebServer
Program.cs
272
C#
namespace Battle { using System; using LittleBaby.Framework.Core; using LittleBaby.Framework.FixedMathematics; using UnityEngine; public abstract class InputCmdManagerBase { public BattleManager BattleManager; public UInt32 LogicFrameCount; public Byte PlayerIndex; public Boolean Start; public Boolean Pause; public Boolean Stop; public Boolean Runing { get { return this.Start && !this.Pause && !this.Stop; } } public virtual void Initialize(BattleManager battleManager, UInt32 logicFrameCount, Byte playerIndex) { this.BattleManager = battleManager; this.LogicFrameCount = logicFrameCount; this.PlayerIndex = playerIndex; this.Start = false; this.Pause = false; this.Stop = false; EventBindManager.Instance.Bind(this); } public virtual void Destroy() { EventBindManager.Instance.Unbind(this); } public void Update(Single deltaTime, Single unscaledDeltaTime) { if (this.Runing) { this.OnUpdate(deltaTime, unscaledDeltaTime); } } public void StartBattle() { if (this.Start) { return; } this.Start = true; this.OnStartBattle(); } public void PauseBattle() { if (this.Pause) { return; } this.Pause = true; this.OnPauseBattle(); } public void ResumeBattle() { if (!this.Pause) { return; } this.Pause = false; this.OnResumeBattle(); } public void StopBattle() { if (this.Stop) { return; } this.Stop = true; this.OnStartBattle(); } public virtual void OnUpdate(Single deltaTime, Single unscaledDeltaTime) { } public virtual void OnStartBattle() { } public virtual void OnPauseBattle() { } public virtual void OnResumeBattle() { } public virtual void OnStopBattle() { } public abstract void SendFrameMessage(InputCmd inputCmd); public void SyncButtonState(EButtonType buttonType, Boolean touched, Vector2 direction, Single distance) { var inputCmd = new InputCmd() { CmdType = EInputCmdType.SyncButtonState, PlayerIndex = this.PlayerIndex, SyncButtonState_ButtonType = buttonType, SyncButtonState_Touched = touched, SyncButtonState_Direction = (ffloat2)direction, SyncButtonState_Distance = (ffloat)distance, }; this.SendFrameMessage(inputCmd); } } }
29.73
112
0.538177
[ "MIT" ]
zengliugen/LittleBaby.Framework
UnityProject/Assets/Battle/Runtime/Core/Manager/InputCmdManagerBase.cs
2,975
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Azmyth { public static class Strings { public static string Article(string word) { char first = word[0]; char last = word[word.Length - 1]; string article = "a"; string vowels = "aeiouAEIOU"; string special = "hH"; string plural = "sS"; if(vowels.Contains(first) || special.Contains(first)) { article = "an"; } if (plural.Contains(last)) { article = "some"; } return article; } } }
21.176471
65
0.472222
[ "Unlicense", "MIT" ]
GalacticSoft/Azmyth
Azmyth/Strings.cs
722
C#
/* Copyright (c) 2014, Lars Brubaker All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using System.Diagnostics; using System.Threading; using MatterControl.Printing; namespace MatterHackers.MatterControl.PrinterCommunication.Io { public class WaitForTempStream : GCodeStreamProxy { /// <summary> /// Gets or sets the number of seconds to wait after reaching the target temp before continuing. Analogous to /// firmware dwell time for temperature stabilization /// </summary> public static double WaitAfterReachTempTime { get; set; } = 3; private double extruderIndex; private readonly double ignoreRequestIfBelowTemp = 20; private readonly double sameTempRangeBed = 3; private readonly double sameTempRangeHotend = 1; private State state = State.Passthrough; private double targetTemp = 0; private readonly Stopwatch timeHaveBeenAtTemp = new Stopwatch(); private bool waitWhenCooling = false; public WaitForTempStream(PrinterConfig printer, GCodeStream internalStream) : base(printer, internalStream) { state = State.Passthrough; } private enum State { Passthrough, WaitingForBedTemp, WaitingForT0Temp, WaitingForT1Temp } public bool HeatingBed { get { return state == State.WaitingForBedTemp; } } public bool HeatingT0 { get { return state == State.WaitingForT0Temp; } } public bool HeatingT1 { get { return state == State.WaitingForT1Temp; } } public override string DebugInfo => ""; public void Cancel() { state = State.Passthrough; } public override string ReadLine() { switch (state) { case State.Passthrough: { string lineToSend = base.ReadLine(); if (lineToSend == null) { return null; } if (lineToSend.EndsWith("; NO_PROCESSING")) { return lineToSend; } if (lineToSend.StartsWith("M")) { // initial test is just to see if it is an M109 if (lineToSend.StartsWith("M109")) // extruder set and wait temp { var lineNoComment = lineToSend.Split(';')[0]; if (lineNoComment.Contains("F") // If it has a control character F (auto temp) || !lineNoComment.Contains("S")) // if it is a reset (has no S temperature) { // don't replace it return lineToSend; } // send an M104 instead waitWhenCooling = false; lineToSend = "M104" + lineToSend.Substring(4); GCodeFile.GetFirstNumberAfter("S", lineToSend, ref targetTemp); extruderIndex = printer.Connection.ActiveExtruderIndex; GCodeFile.GetFirstNumberAfter("T", lineToSend, ref extruderIndex); if (targetTemp > ignoreRequestIfBelowTemp) { if (extruderIndex == 1) { state = State.WaitingForT1Temp; } else { state = State.WaitingForT0Temp; } timeHaveBeenAtTemp.Reset(); } else { Thread.Sleep(100); // sleep .1 second while waiting for temp return ""; // return nothing until we reach temp } } else if (lineToSend.StartsWith("M190")) // bed set and wait temp { // send an M140 instead bool gotR = GCodeFile.GetFirstNumberAfter("R", lineToSend, ref targetTemp); bool gotS = GCodeFile.GetFirstNumberAfter("S", lineToSend, ref targetTemp); if (gotR || gotS) { if (targetTemp > ignoreRequestIfBelowTemp) { waitWhenCooling = gotR; lineToSend = "M140 S" + targetTemp.ToString(); state = State.WaitingForBedTemp; timeHaveBeenAtTemp.Reset(); } else { Thread.Sleep(100); // sleep .1 second while waiting for temp return ""; // return nothing until we reach temp } } else { Thread.Sleep(100); // sleep .1 second while waiting for temp return ""; // return nothing until we reach temp } } } return lineToSend; } case State.WaitingForT0Temp: case State.WaitingForT1Temp: { double extruderTemp = printer.Connection.GetActualHotendTemperature((int)extruderIndex); bool tempWithinRange = extruderTemp >= targetTemp - sameTempRangeHotend && extruderTemp <= targetTemp + sameTempRangeHotend; if (tempWithinRange && !timeHaveBeenAtTemp.IsRunning) { timeHaveBeenAtTemp.Start(); } if (timeHaveBeenAtTemp.Elapsed.TotalSeconds > WaitAfterReachTempTime || printer.Connection.PrintWasCanceled) { // switch to pass through and continue state = State.Passthrough; return ""; } else { // send a wait command Thread.Sleep(100); // sleep .1 second while waiting for temp return ""; // return nothing until we reach temp } } case State.WaitingForBedTemp: { double bedTemp = printer.Connection.ActualBedTemperature; bool tempWithinRange; if (waitWhenCooling) { tempWithinRange = bedTemp >= targetTemp - sameTempRangeBed && bedTemp <= targetTemp + sameTempRangeBed; } else { tempWithinRange = bedTemp >= targetTemp - sameTempRangeBed; } // Added R code for M190 if (tempWithinRange && !timeHaveBeenAtTemp.IsRunning) { timeHaveBeenAtTemp.Start(); } if (timeHaveBeenAtTemp.Elapsed.TotalSeconds > WaitAfterReachTempTime || printer.Connection.PrintWasCanceled) { // switch to pass through and continue state = State.Passthrough; return ""; } else { // send a wait command Thread.Sleep(100); // sleep .1 second while waiting for temp return ""; // return nothing until we reach temp } } } return null; } } }
31.25641
111
0.661334
[ "BSD-2-Clause" ]
Bhalddin/MatterControl
MatterControlLib/PrinterCommunication/Io/WaitForTempStream.cs
7,316
C#
using System; using Stride.Core; using Stride.Core.Mathematics; using Stride.Engine; using Stride.Input; namespace StrideProceduralModel { /// <summary> /// A script that allows to move and rotate an entity through keyboard, mouse and touch input to provide basic camera navigation. /// </summary> /// <remarks> /// The entity can be moved using W, A, S, D, Q and E, arrow keys, a gamepad's left stick or dragging/scaling using multi-touch. /// Rotation is achieved using the Numpad, the mouse while holding the right mouse button, a gamepad's right stick, or dragging using single-touch. /// </remarks> public class BasicCameraController : SyncScript { private const float MaximumPitch = MathUtil.PiOverTwo * 0.99f; private Vector3 upVector; private Vector3 translation; private float yaw; private float pitch; public bool Gamepad { get; set; } = false; public Vector3 KeyboardMovementSpeed { get; set; } = new Vector3(5.0f); public Vector3 TouchMovementSpeed { get; set; } = new Vector3(0.7f, 0.7f, 0.3f); public float SpeedFactor { get; set; } = 5.0f; public Vector2 KeyboardRotationSpeed { get; set; } = new Vector2(3.0f); public Vector2 MouseRotationSpeed { get; set; } = new Vector2(1.0f, 1.0f); public Vector2 TouchRotationSpeed { get; set; } = new Vector2(1.0f, 0.7f); public override void Start() { base.Start(); // Default up-direction upVector = Vector3.UnitY; // Configure touch input if (!Platform.IsWindowsDesktop) { Input.Gestures.Add(new GestureConfigDrag()); Input.Gestures.Add(new GestureConfigComposite()); } } public override void Update() { ProcessInput(); UpdateTransform(); } private void ProcessInput() { float deltaTime = (float)Game.UpdateTime.Elapsed.TotalSeconds; translation = Vector3.Zero; yaw = 0f; pitch = 0f; // Keyboard and Gamepad based movement { // Our base speed is: one unit per second: // deltaTime contains the duration of the previous frame, let's say that in this update // or frame it is equal to 1/60, that means that the previous update ran 1/60 of a second ago // and the next will, in most cases, run in around 1/60 of a second from now. Knowing that, // we can move 1/60 of a unit on this frame so that in around 60 frames(1 second) // we will have travelled one whole unit in a second. // If you don't use deltaTime your speed will be dependant on the amount of frames rendered // on screen which often are inconsistent, meaning that if the player has performance issues, // this entity will move around slower. float speed = 1f * deltaTime; Vector3 dir = Vector3.Zero; if (Gamepad && Input.HasGamePad) { GamePadState padState = Input.DefaultGamePad.State; // LeftThumb can be positive or negative on both axis (pushed to the right or to the left) dir.Z += padState.LeftThumb.Y; dir.X += padState.LeftThumb.X; // Triggers are always positive, in this case using one to increase and the other to decrease dir.Y -= padState.LeftTrigger; dir.Y += padState.RightTrigger; // Increase speed when pressing A, LeftShoulder or RightShoulder // Here:does the enum flag 'Buttons' has one of the flag ('A','LeftShoulder' or 'RightShoulder') set if ((padState.Buttons & (GamePadButton.A | GamePadButton.LeftShoulder | GamePadButton.RightShoulder)) != 0) { speed *= SpeedFactor; } } if (Input.HasKeyboard) { // Move with keyboard // Forward/Backward if (Input.IsKeyDown(Keys.W) || Input.IsKeyDown(Keys.Up)) { dir.Z += 1; } if (Input.IsKeyDown(Keys.S) || Input.IsKeyDown(Keys.Down)) { dir.Z -= 1; } // Left/Right if (Input.IsKeyDown(Keys.A) || Input.IsKeyDown(Keys.Left)) { dir.X -= 1; } if (Input.IsKeyDown(Keys.D) || Input.IsKeyDown(Keys.Right)) { dir.X += 1; } // Down/Up if (Input.IsKeyDown(Keys.Q)) { dir.Y -= 1; } if (Input.IsKeyDown(Keys.E)) { dir.Y += 1; } // Increase speed when pressing shift if (Input.IsKeyDown(Keys.LeftShift) || Input.IsKeyDown(Keys.RightShift)) { speed *= SpeedFactor; } // If the player pushes down two or more buttons, the direction and ultimately the base speed // will be greater than one (vector(1, 1) is farther away from zero than vector(0, 1)), // normalizing the vector ensures that whichever direction the player chooses, that direction // will always be at most one unit in length. // We're keeping dir as is if isn't longer than one to retain sub unit movement: // a stick not entirely pushed forward should make the entity move slower. if (dir.Length() > 1f) { dir = Vector3.Normalize(dir); } } // Finally, push all of that to the translation variable which will be used within UpdateTransform() translation += dir * KeyboardMovementSpeed * speed; } // Keyboard and Gamepad based Rotation { // See Keyboard & Gamepad translation's deltaTime usage float speed = 1f * deltaTime; Vector2 rotation = Vector2.Zero; if (Gamepad && Input.HasGamePad) { GamePadState padState = Input.DefaultGamePad.State; rotation.X += padState.RightThumb.Y; rotation.Y += -padState.RightThumb.X; } if (Input.HasKeyboard) { if (Input.IsKeyDown(Keys.NumPad2)) { rotation.X += 1; } if (Input.IsKeyDown(Keys.NumPad8)) { rotation.X -= 1; } if (Input.IsKeyDown(Keys.NumPad4)) { rotation.Y += 1; } if (Input.IsKeyDown(Keys.NumPad6)) { rotation.Y -= 1; } // See Keyboard & Gamepad translation's Normalize() usage if (rotation.Length() > 1f) { rotation = Vector2.Normalize(rotation); } } // Modulate by speed rotation *= KeyboardRotationSpeed * speed; // Finally, push all of that to pitch & yaw which are going to be used within UpdateTransform() pitch += rotation.X; yaw += rotation.Y; } // Mouse movement and gestures { // This type of input should not use delta time at all, they already are frame-rate independent. // Lets say that you are going to move your finger/mouse for one second over 40 units, it doesn't matter // the amount of frames occuring within that time frame, each frame will receive the right amount of delta: // a quarter of a second -> 10 units, half a second -> 20 units, one second -> your 40 units. if (Input.HasMouse) { // Rotate with mouse if (Input.IsMouseButtonDown(MouseButton.Right)) { Input.LockMousePosition(); Game.IsMouseVisible = false; yaw -= Input.MouseDelta.X * MouseRotationSpeed.X; pitch -= Input.MouseDelta.Y * MouseRotationSpeed.Y; } else { Input.UnlockMousePosition(); Game.IsMouseVisible = true; } } // Handle gestures foreach (var gestureEvent in Input.GestureEvents) { switch (gestureEvent.Type) { // Rotate by dragging case GestureType.Drag: var drag = (GestureEventDrag)gestureEvent; var dragDistance = drag.DeltaTranslation; yaw = -dragDistance.X * TouchRotationSpeed.X; pitch = -dragDistance.Y * TouchRotationSpeed.Y; break; // Move along z-axis by scaling and in xy-plane by multi-touch dragging case GestureType.Composite: var composite = (GestureEventComposite)gestureEvent; translation.X = -composite.DeltaTranslation.X * TouchMovementSpeed.X; translation.Y = -composite.DeltaTranslation.Y * TouchMovementSpeed.Y; translation.Z = (float)Math.Log(composite.DeltaScale + 1) * TouchMovementSpeed.Z; break; } } } } private void UpdateTransform() { // Get the local coordinate system var rotation = Matrix.RotationQuaternion(Entity.Transform.Rotation); // Enforce the global up-vector by adjusting the local x-axis var right = Vector3.Cross(rotation.Forward, upVector); var up = Vector3.Cross(right, rotation.Forward); // Stabilize right.Normalize(); up.Normalize(); // Adjust pitch. Prevent it from exceeding up and down facing. Stabilize edge cases. var currentPitch = MathUtil.PiOverTwo - (float)Math.Acos(Vector3.Dot(rotation.Forward, upVector)); pitch = MathUtil.Clamp(currentPitch + pitch, -MaximumPitch, MaximumPitch) - currentPitch; Vector3 finalTranslation = translation; finalTranslation.Z = -finalTranslation.Z; finalTranslation = Vector3.TransformCoordinate(finalTranslation, rotation); // Move in local coordinates Entity.Transform.Position += finalTranslation; // Yaw around global up-vector, pitch and roll in local space Entity.Transform.Rotation *= Quaternion.RotationAxis(right, pitch) * Quaternion.RotationAxis(upVector, yaw); } } }
43.166667
151
0.488705
[ "MIT" ]
tebjan/Stride.ProceduralModel
StrideProceduralModel/BasicCameraController.cs
12,175
C#
using GAPPSF.Core.Data; using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; using System.Xml.Serialization; namespace GAPPSF.Core { public class ApplicationData: INotifyPropertyChanged { private static ApplicationData _uniqueInstance = null; public event PropertyChangedEventHandler PropertyChanged; public MainWindow MainWindow { get; set; } public Storage.DatabaseCollection Databases { get; private set; } public GeocacheTypeCollection GeocacheTypes { get; private set; } public GeocacheContainerCollection GeocacheContainers { get; private set; } public LogTypeCollection LogTypes { get; private set; } public WaypointTypeCollection WaypointTypes { get; private set; } public Data.Location HomeLocation { get; private set; } public Data.Location CenterLocation { get; private set; } public AccountInfoCollection AccountInfos { get; private set; } public GeocacheAttributeCollection GeocacheAttributes { get; private set; } public Logger Logger { get; private set; } private bool _switchingDatabase = false; private Storage.Database _activeDatabase = null; public Storage.Database ActiveDatabase { get { return _activeDatabase; } set { if (_activeDatabase != value) { _switchingDatabase = true; Core.Settings.Default.ActiveDatabase = value == null ? null : value.FileName; ActiveGeocache = null; SetProperty(ref _activeDatabase, value); if (_activeDatabase!=null) { string gcCode = _activeDatabase.LastActiveGeocacheCode; if (!string.IsNullOrEmpty(gcCode)) { ActiveGeocache = _activeDatabase.GeocacheCollection.GetGeocache(gcCode); } } _switchingDatabase = false; } } } private Data.Geocache _activeGeocache = null; public Data.Geocache ActiveGeocache { get { return _activeGeocache; } set { Core.Settings.Default.ActiveGeocache = value == null ? null : value.Code; if (!_switchingDatabase && ActiveDatabase != null) { ActiveDatabase.LastActiveGeocacheCode = value == null ? "" : value.Code; } SetProperty(ref _activeGeocache, value); } } private int _activityCounter = 0; public void BeginActiviy() { _activityCounter++; if (_activityCounter==1) { UIIsIdle = false; } } public void EndActiviy() { _activityCounter--; if (_activityCounter == 0) { UIIsIdle = true; } } private bool _uiIsIdle = true; public bool UIIsIdle { get { return _uiIsIdle; } set { if (_uiIsIdle != value) { SetProperty(ref _uiIsIdle, value); CommandManager.InvalidateRequerySuggested(); } } } public ApplicationData() { #if DEBUG if (_uniqueInstance != null) { //you used the wrong binding //use: //<properties:ApplicationData x:Key="ApplicationData" /> //{Binding Databases, Source={x:Static p:ApplicationData.Instance}} //{Binding Source={x:Static p:ApplicationData.Instance}, Path=ActiveDatabase.GeocacheCollection} System.Diagnostics.Debugger.Break(); } #endif this.Logger = new Core.Logger(); string s = Settings.Default.AccountInfos; //s = ""; if (string.IsNullOrEmpty(s)) { AccountInfos = new AccountInfoCollection(); } else { Type[] itemTypes = { typeof(AccountInfo) }; XmlSerializer serializer = new XmlSerializer(typeof(AccountInfoCollection), itemTypes); using (StringReader r = new StringReader(s)) { AccountInfos = serializer.Deserialize(r) as AccountInfoCollection; } } GeocacheAttributes = new GeocacheAttributeCollection(); Databases = new Storage.DatabaseCollection(); GeocacheTypes = new GeocacheTypeCollection(); GeocacheContainers = new GeocacheContainerCollection(); WaypointTypes = new WaypointTypeCollection(); LogTypes = new LogTypeCollection(); HomeLocation = new Location(Settings.Default.HomeLocationLat, Settings.Default.HomeLocationLon); CenterLocation = new Location(Settings.Default.CenterLocationLat, Settings.Default.CenterLocationLon); HomeLocation.PropertyChanged += HomeLocation_PropertyChanged; CenterLocation.PropertyChanged += CenterLocation_PropertyChanged; AccountInfos.CollectionChanged += AccountInfos_CollectionChanged; string[] accountPrefixes = new string[] { "GC", "OX", "OB", "OC", "MZ", "OU", "OP"}; foreach (string acc in accountPrefixes) { if (AccountInfos.GetAccountInfo(acc) == null) { AccountInfos.Add(new AccountInfo(acc, "")); } } addCacheType(0, "Not present"); addCacheType(2, "Traditional Cache"); addCacheType(3, "Multi-cache"); addCacheType(4, "Virtual Cache"); addCacheType(5, "Letterbox Hybrid"); addCacheType(6, "Event Cache"); addCacheType(8, "Unknown (Mystery) Cache", "Unknown Cache"); addCacheType(9, "Project APE Cache"); addCacheType(11, "Webcam Cache"); addCacheType(12, "Locationless (Reverse) Cache"); addCacheType(13, "Cache In Trash Out Event"); addCacheType(137, "Earthcache"); addCacheType(453, "Mega-Event Cache"); addCacheType(605, "Geocache Course"); addCacheType(1304, "GPS Adventures Exhibit"); addCacheType(1858, "Wherigo Cache"); addCacheType(3653, "Lost and Found Event Cache"); addCacheType(3773, "Groundspeak HQ"); addCacheType(3774, "Groundspeak Lost and Found Celebration"); addCacheType(4738, "Groundspeak Block Party"); addCacheType(95342, "Munzee", Core.Settings.Default.MunzeeGPXTagMunzee); addCacheType(95343, "Virtual Munzee", Core.Settings.Default.MunzeeGPXTagVirtual); addCacheType(95344, "Maintenance Munzee", Core.Settings.Default.MunzeeGPXTagMaintenance); addCacheType(95345, "Business Munzee", Core.Settings.Default.MunzeeGPXTagBusiness); addCacheType(95346, "Mystery Munzee", Core.Settings.Default.MunzeeGPXTagMystery); addCacheType(95347, "NFC Munzee", Core.Settings.Default.MunzeeGPXTagNFC); addCacheType(95348, "Premium Munzee", Core.Settings.Default.MunzeeGPXTagPremium); addCacheType(96001, "OC Traditional Cache", "Traditional Cache"); addCacheType(96002, "OC Multi-cache", "Multi-cache"); addCacheType(96003, "OC Virtual Cache", "Virtual Cache"); addCacheType(96004, "OC Event Cache", "Event Cache"); addCacheType(96005, "OC Unknown (Mystery) Cache", "Unknown Cache"); addCacheType(96006, "OC Webcam Cache", "Webcam Cache"); addCacheType(96007, "OC Moving Cache", "Locationless (Reverse) Cache"); addCacheType(96008, "OC Quiz Cache", "Unknown Cache"); addCacheType(96009, "OC Drive-in Cache", "Traditional Cache"); addCacheContainer(0, "Unknown"); addCacheContainer(1, "Not chosen"); addCacheContainer(2, "Micro"); addCacheContainer(3, "Regular"); addCacheContainer(4, "Large"); addCacheContainer(5, "Virtual"); addCacheContainer(6, "Other"); addCacheContainer(8, "Small"); addLogType(0, "Unknown", false); addLogType(1, "Unarchive", false); addLogType(2, "Found it", true); addLogType(3, "Didn't find it", false); addLogType(4, "Write note", false); addLogType(5, "Archive", false); addLogType(6, "Archive", false); addLogType(7, "Needs Archived", false); addLogType(8, "Mark Destroyed", false); addLogType(9, "Will Attend", false); addLogType(10, "Attended", true); addLogType(11, "Webcam Photo Taken", true); addLogType(12, "Unarchive", false); addLogType(13, "Retrieve It from a Cache", false); addLogType(14, "Dropped Off", false); addLogType(15, "Transfer", false); addLogType(16, "Mark Missing", false); addLogType(17, "Recovered", false); addLogType(18, "Post Reviewer Note", false); addLogType(19, "Grab It (Not from a Cache)", false); addLogType(20, "Write Jeep 4x4 Contest Essay", false); addLogType(21, "Upload Jeep 4x4 Contest Photo", false); addLogType(22, "Temporarily Disable Listing", false); addLogType(23, "Enable Listing", false); addLogType(24, "Publish Listing", false); addLogType(25, "Retract Listing", false); addLogType(30, "Uploaded Goal Photo for \"A True Original\"", false); addLogType(31, "Uploaded Goal Photo for \"Yellow Jeep Wrangler\"", false); addLogType(32, "Uploaded Goal Photo for \"Construction Site\"", false); addLogType(33, "Uploaded Goal Photo for \"State Symbol\"", false); addLogType(34, "Uploaded Goal Photo for \"American Flag\"", false); addLogType(35, "Uploaded Goal Photo for \"Landmark/Memorial\"", false); addLogType(36, "Uploaded Goal Photo for \"Camping\"", false); addLogType(37, "Uploaded Goal Photo for \"Peaks and Valleys\"", false); addLogType(38, "Uploaded Goal Photo for \"Hiking\"", false); addLogType(39, "Uploaded Goal Photo for \"Ground Clearance\"", false); addLogType(40, "Uploaded Goal Photo for \"Water Fording\"", false); addLogType(41, "Uploaded Goal Photo for \"Traction\"", false); addLogType(42, "Uploaded Goal Photo for \"Tow Package\"", false); addLogType(43, "Uploaded Goal Photo for \"Ultimate Makeover\"", false); addLogType(44, "Uploaded Goal Photo for \"Paint Job\"", false); addLogType(45, "Needs Maintenance", false); addLogType(46, "Owner Maintenance", false); addLogType(47, "Update Coordinates", false); addLogType(48, "Discovered It", false); addLogType(49, "Uploaded Goal Photo for \"Discovery\"", false); addLogType(50, "Uploaded Goal Photo for \"Freedom\"", false); addLogType(51, "Uploaded Goal Photo for \"Adventure\"", false); addLogType(52, "Uploaded Goal Photo for \"Camaraderie\"", false); addLogType(53, "Uploaded Goal Photo for \"Heritage\"", false); addLogType(54, "Reviewer Note", false); addLogType(55, "Lock User (Ban)", false); addLogType(56, "Unlock User (Unban)", false); addLogType(57, "Groundspeak Note", false); addLogType(58, "Uploaded Goal Photo for \"Fun\"", false); addLogType(59, "Uploaded Goal Photo for \"Fitness\"", false); addLogType(60, "Uploaded Goal Photo for \"Fighting Diabetes\"", false); addLogType(61, "Uploaded Goal Photo for \"American Heritage\"", false); addLogType(62, "Uploaded Goal Photo for \"No Boundaries\"", false); addLogType(63, "Uploaded Goal Photo for \"Only in a Jeep\"", false); addLogType(64, "Uploaded Goal Photo for \"Discover New Places\"", false); addLogType(65, "Uploaded Goal Photo for \"Definition of Freedom\"", false); addLogType(66, "Uploaded Goal Photo for \"Adventure Starts Here\"", false); addLogType(67, "Needs Attention", false); addLogType(68, "Post Reviewer Note", false); addLogType(69, "Move To Collection", false); addLogType(70, "Move To Inventory", false); addLogType(71, "Throttle User", false); addLogType(72, "Enter CAPTCHA", false); addLogType(73, "Change Username", false); addLogType(74, "Announcement", false); addLogType(75, "Visited", false); addWaypointType(0, "Unknown"); addWaypointType(217, "Parking Area"); addWaypointType(220, "Final Location"); addWaypointType(218, "Question to Answer"); addWaypointType(452, "Reference Point"); addWaypointType(219, "Stages of a Multicache"); addWaypointType(221, "Trailhead"); addCacheAttribute(0, "Unknown"); addCacheAttribute(1, "Dogs"); addCacheAttribute(2, "Access or parking fee"); addCacheAttribute(3, "Climbing gear"); addCacheAttribute(4, "Boat"); addCacheAttribute(5, "Scuba gear"); addCacheAttribute(6, "Recommended for kids"); addCacheAttribute(7, "Takes less than an hour"); addCacheAttribute(8, "Scenic view"); addCacheAttribute(9, "Significant Hike"); addCacheAttribute(10, "Difficult climbing"); addCacheAttribute(11, "May require wading"); addCacheAttribute(12, "May require swimming"); addCacheAttribute(13, "Available at all times"); addCacheAttribute(14, "Recommended at night"); addCacheAttribute(15, "Available during winter"); addCacheAttribute(16, "Cactus"); addCacheAttribute(17, "Poison plants"); addCacheAttribute(18, "Dangerous Animals"); addCacheAttribute(19, "Ticks"); addCacheAttribute(20, "Abandoned mines"); addCacheAttribute(21, "Cliff / falling rocks"); addCacheAttribute(22, "Hunting"); addCacheAttribute(23, "Dangerous area"); addCacheAttribute(24, "Wheelchair accessible"); addCacheAttribute(25, "Parking available"); addCacheAttribute(26, "Public transportation"); addCacheAttribute(27, "Drinking water nearby"); addCacheAttribute(28, "Public restrooms nearby"); addCacheAttribute(29, "Telephone nearby"); addCacheAttribute(30, "Picnic tables nearby"); addCacheAttribute(31, "Camping available"); addCacheAttribute(32, "Bicycles"); addCacheAttribute(33, "Motorcycles"); addCacheAttribute(34, "Quads"); addCacheAttribute(35, "Off-road vehicles"); addCacheAttribute(36, "Snowmobiles"); addCacheAttribute(37, "Horses"); addCacheAttribute(38, "Campfires"); addCacheAttribute(39, "Thorns"); addCacheAttribute(40, "Stealth required"); addCacheAttribute(41, "Stroller accessible"); addCacheAttribute(42, "Needs maintenance"); addCacheAttribute(43, "Watch for livestock"); addCacheAttribute(44, "Flashlight required"); addCacheAttribute(45, "Lost And Found Tour"); addCacheAttribute(46, "Truck Driver/RV"); addCacheAttribute(47, "Field Puzzle"); addCacheAttribute(48, "UV Light Required"); addCacheAttribute(49, "Snowshoes"); addCacheAttribute(50, "Cross Country Skis"); addCacheAttribute(51, "Special Tool Required"); addCacheAttribute(52, "Night Cache"); addCacheAttribute(53, "Park and Grab"); addCacheAttribute(54, "Abandoned Structure"); addCacheAttribute(55, "Short hike (less than 1km)"); addCacheAttribute(56, "Medium hike (1km-10km)"); addCacheAttribute(57, "Long Hike (+10km)"); addCacheAttribute(58, "Fuel Nearby"); addCacheAttribute(59, "Food Nearby"); addCacheAttribute(60, "Wireless Beacon"); addCacheAttribute(61, "Partnership Cache"); addCacheAttribute(62, "Seasonal Access"); addCacheAttribute(63, "Tourist Friendly"); addCacheAttribute(64, "Tree Climbing"); addCacheAttribute(65, "Front Yard (Private Residence)"); addCacheAttribute(66, "Teamwork Required"); addCacheAttribute(106, "Only loggable at Opencaching"); addCacheAttribute(108, "Letterbox (needs stamp)"); addCacheAttribute(123, "First aid available"); addCacheAttribute(125, "Long walk"); addCacheAttribute(127, "Hilly area"); addCacheAttribute(130, "Point of interest"); addCacheAttribute(132, "Webcam"); addCacheAttribute(133, "Within enclosed rooms (caves, buildings etc."); addCacheAttribute(134, "In the water"); addCacheAttribute(135, "Without GPS (letterboxes, cistes, compass juggling ...)"); addCacheAttribute(137, "Overnight stay necessary"); addCacheAttribute(139, "Only available at specified times"); addCacheAttribute(140, "By day only"); addCacheAttribute(141, "Tide"); addCacheAttribute(142, "All seasons"); addCacheAttribute(143, "Breeding season / protected nature"); addCacheAttribute(147, "Compass"); addCacheAttribute(150, "Cave equipment"); addCacheAttribute(153, "Aircraft"); addCacheAttribute(154, "Investigation"); addCacheAttribute(156, "Arithmetical problem"); addCacheAttribute(157, "Other cache type"); addCacheAttribute(158, "Ask owner for start conditions"); List<Core.Data.GeocacheAttribute> attrs = (from a in this.GeocacheAttributes select a).ToList(); foreach (Core.Data.GeocacheAttribute a in attrs) { if (a.ID > 0) { addCacheAttribute(-a.ID, a.Name); } } } void AccountInfos_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { Type[] itemTypes = { typeof(AccountInfo) }; XmlSerializer serializer = new XmlSerializer(typeof(AccountInfoCollection), itemTypes); using (StringWriter w = new StringWriter()) { serializer.Serialize(w, AccountInfos); Settings.Default.AccountInfos = w.ToString(); } if (PropertyChanged!=null) { PropertyChanged(this, new PropertyChangedEventArgs("AccountInfos")); } } void CenterLocation_PropertyChanged(object sender, PropertyChangedEventArgs e) { Data.Location ll = sender as Data.Location; if (ll != null) { if (e.PropertyName == "Lat") { Settings.Default.CenterLocationLat = ll.Lat; } else if (e.PropertyName == "Lon") { Settings.Default.CenterLocationLon = ll.Lon; } if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("CenterLocation")); } } } void HomeLocation_PropertyChanged(object sender, PropertyChangedEventArgs e) { Data.Location ll = sender as Data.Location; if (ll != null) { if (e.PropertyName == "Lat") { Settings.Default.HomeLocationLat = ll.Lat; } else if (e.PropertyName == "Lon") { Settings.Default.HomeLocationLon = ll.Lon; } if (PropertyChanged!=null) { PropertyChanged(this, new PropertyChangedEventArgs("HomeLocation")); } } } public static ApplicationData Instance { get { if (_uniqueInstance==null) { _uniqueInstance = new ApplicationData(); } return _uniqueInstance; } } protected void SetProperty<T>(ref T field, T value, [CallerMemberName] string name = "") { if (!EqualityComparer<T>.Default.Equals(field, value)) { field = value; var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } } private void addCacheType(int id, string name) { GeocacheType ct = new GeocacheType(); ct.ID = id; ct.Name = name; GeocacheTypes.Add(ct); } private void addCacheType(int id, string name, string gpxTag) { GeocacheType ct = new GeocacheType(gpxTag); ct.ID = id; ct.Name = name; GeocacheTypes.Add(ct); } private void addCacheContainer(int id, string name) { Data.GeocacheContainer attr = new Data.GeocacheContainer(); attr.ID = id; attr.Name = name; GeocacheContainers.Add(attr); } protected void addLogType(int id, string name, bool asFound) { Data.LogType lt = new Data.LogType(); lt.ID = id; lt.Name = name; lt.AsFound = asFound; LogTypes.Add(lt); } protected void addWaypointType(int id, string name) { Data.WaypointType attr = new Data.WaypointType(); attr.ID = id; attr.Name = name; WaypointTypes.Add(attr); } protected void addCacheAttribute(int id, string name) { Data.GeocacheAttribute attr = new Data.GeocacheAttribute(); attr.ID = id; attr.Name = name; GeocacheAttributes.Add(attr); } } }
44.564299
125
0.568524
[ "MIT" ]
RH-Code/GAPP
GAPPSF/Core/Application.cs
23,220
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace TestEventProcessor.Service { using Autofac; using Autofac.Extensions.DependencyInjection; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using BusinessLogic; public class Startup { public Startup(IHostEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfiguration Configuration { get; } public ILifetimeScope AutofacContainer { get; private set; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddOptions(); services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true)); services.Configure<ValidatorConfiguration>(Configuration.GetSection("ValidatorConfiguration")); } public void ConfigureContainer(ContainerBuilder builder) { builder.RegisterType<TelemetryValidator>().As<ITelemetryValidator>().SingleInstance(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/error"); } AutofacContainer = app.ApplicationServices.GetAutofacRoot(); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
34.592105
107
0.600989
[ "MIT" ]
Azure/Industrial-IoT
tools/e2etesting/TestEventProcessor/TestEventProcessor.Service/Startup.cs
2,629
C#
namespace SyncPro.UnitTests { public static class GlobalTestSettings { /// <summary> /// Indicates whether tests requiring network calls should be run. /// </summary> /// <remarks> /// A number of unit tests will communicate with a service's network API (usually HTTP) to test the /// functionality of various methods. These tests require that an account exist with the given service /// provider, and will use a certain amount of bandwith to perform the tests. Before enabling this flag, /// be sure to read and understand what is required to run the test. /// </remarks> public static bool RunNetworkTests = true; /// <summary> /// Message used to indicate that network-based unit tests are disabled. /// </summary> public static string NetworkTestsDisabledMessage = "Network-based tests are disabled. See the code comments for the " + nameof(GlobalTestSettings) + "." + nameof(RunNetworkTests) + " variable so see how to enable network tests that require network communication."; } }
49.391304
123
0.65757
[ "MIT" ]
HighEncryption/SyncPro
SyncPro.UnitTests/GlobalTestSettings.cs
1,136
C#
using LagoVista.Drone; using LagoVista.DroneBaseStation.Core.Interfaces; using System; using System.Linq; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using static MAVLink; using System.Security.Cryptography; using System.Diagnostics; namespace LagoVista.DroneBaseStation.Core.Services { public class MissionPlanner : IMissionPlanner { public MissionPlanner() { } private void _link_MessageParsed(object sender, MAVLinkMessage e) { } public async Task GetWayPoints(IDrone drone, ISerialTelemetryLink link) { var req = new mavlink_mission_request_list_t(); req.target_system = drone.SystemId; req.target_component = drone.ComponentId; var result = await link.RequestDataAsync<mavlink_mission_count_t>(drone, MAVLINK_MSG_ID.MISSION_REQUEST_LIST, req, MAVLINK_MSG_ID.MISSION_COUNT, TimeSpan.FromSeconds(1000)); if (result.Successful) { for (ushort idx = 0; idx < result.Result.count; ++idx) { var reqf = new mavlink_mission_request_int_t(); reqf.target_system = drone.SystemId; reqf.target_component = drone.ComponentId; reqf.seq = idx; var wpResult = await link.RequestDataAsync<mavlink_mission_item_t>(drone, MAVLINK_MSG_ID.MISSION_REQUEST_INT, reqf, MAVLINK_MSG_ID.MISSION_ITEM, TimeSpan.FromSeconds(1000)); if (wpResult.Successful) { Debug.WriteLine(wpResult.Result.x + " " + wpResult.Result.y + " " + wpResult.Result.z); } else { Debug.WriteLine($"No joy on {idx}"); } } Debug.WriteLine($"Get go our response {result.Result.count}"); } else { Debug.WriteLine($"No joy"); } } } }
31.477612
193
0.569464
[ "MIT" ]
LagoVista/DroneBaseStation
src/common/LagoVista.DroneBaseStation.Core/Services/MissionPlanner.cs
2,111
C#
using System; namespace ExRam.Gremlinq.Core { public interface IInEdgeGremlinQueryBase : IEdgeGremlinQueryBase { new IEdgeGremlinQuery<object> Lower(); } public interface IInEdgeGremlinQueryBase<TEdge, TInVertex> : IInEdgeGremlinQueryBase, IEdgeGremlinQueryBase<TEdge> { IEdgeGremlinQuery<TEdge, TOutVertex, TInVertex> From<TOutVertex>(Func<IVertexGremlinQuery<TInVertex>, IVertexGremlinQueryBase<TOutVertex>> fromVertexTraversal); new IVertexGremlinQuery<TInVertex> InV(); new IEdgeGremlinQuery<TEdge> Lower(); } public interface IInEdgeGremlinQueryBaseRec<TSelf> : IInEdgeGremlinQueryBase, IEdgeGremlinQueryBaseRec<TSelf> where TSelf : IInEdgeGremlinQueryBaseRec<TSelf> { } public interface IInEdgeGremlinQueryBaseRec<TEdge, TInVertex, TSelf> : IInEdgeGremlinQueryBaseRec<TSelf>, IInEdgeGremlinQueryBase<TEdge, TInVertex>, IEdgeGremlinQueryBaseRec<TEdge, TSelf> where TSelf : IInEdgeGremlinQueryBaseRec<TEdge, TInVertex, TSelf> { } public interface IInEdgeGremlinQuery<TEdge, TInVertex> : IInEdgeGremlinQueryBaseRec<TEdge, TInVertex, IInEdgeGremlinQuery<TEdge, TInVertex>> { } }
28.266667
168
0.713836
[ "MIT" ]
BlacktopSoftwareStudios/ExRam.Gremlinq
src/ExRam.Gremlinq.Core/Queries/Interfaces/IInEdgeGremlinQuery.cs
1,274
C#
//----------------------------------------------------------------------- // <copyright file="EventBus.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.Collections.Concurrent; using System.Collections.Generic; using System.Linq; namespace Akka.Event { /// <summary> /// This class provides base publish/subscribe functionality for working with events inside the system. /// </summary> /// <typeparam name="TEvent">The type of event published to the bus.</typeparam> /// <typeparam name="TClassifier">The type of classifier used to classify events.</typeparam> /// <typeparam name="TSubscriber">The type of the subscriber that listens for events.</typeparam> public abstract class EventBus<TEvent, TClassifier, TSubscriber> { private readonly Dictionary<TClassifier, List<Subscription<TSubscriber, TClassifier>>> _classifiers = new Dictionary<TClassifier, List<Subscription<TSubscriber, TClassifier>>>(); private volatile ConcurrentDictionary<TClassifier, List<TSubscriber>> _cache = new ConcurrentDictionary<TClassifier, List<TSubscriber>>(); /// <summary> /// Retrieves the simplified type name (the class name without the namespace) of a given object. /// </summary> /// <param name="source">The object that is being queried.</param> /// <returns>The simplified type name of the given object.</returns> protected string SimpleName(object source) { return SimpleName(source.GetType()); } /// <summary> /// Retrieves the simplified type name (the class name without the namespace) of a given type. /// </summary> /// <param name="source">The object that is being queried.</param> /// <returns>The simplified type name of the given type.</returns> protected string SimpleName(Type source) { return source.Name; } /// <summary> /// Adds the specified subscriber to the list of subscribers that listen for particular events on the bus. /// </summary> /// <param name="subscriber">The subscriber that is being added.</param> /// <param name="classifier">The classifier of the event that the subscriber wants.</param> /// <returns><c>true</c> if the subscription succeeds; otherwise <c>false</c>.</returns> public virtual bool Subscribe(TSubscriber subscriber, TClassifier classifier) { lock (_classifiers) { if (!_classifiers.TryGetValue(classifier, out var subscribers)) { subscribers = new List<Subscription<TSubscriber, TClassifier>>(); _classifiers.Add(classifier, subscribers); } //already subscribed if (subscribers.Any(s => s.Subscriber.Equals(subscriber))) return false; var subscription = new Subscription<TSubscriber, TClassifier>(subscriber); subscribers.Add(subscription); ClearCache(); return true; } } /// <summary> /// Removes the specified subscriber from the list of subscribers that listen for particular events on the bus. /// </summary> /// <param name="subscriber">The subscriber that is being removed.</param> /// <returns><c>true</c> if the subscription cancellation succeeds; otherwise <c>false</c>.</returns> public virtual bool Unsubscribe(TSubscriber subscriber) { lock (_classifiers) { var res = false; foreach (var classifier in _classifiers.Keys) { if (!_classifiers.TryGetValue(classifier, out var subscribers)) continue; if (subscribers.RemoveAll(s => s.Subscriber.Equals(subscriber)) > 0) res = true; } ClearCache(); return res; } } /// <summary> /// Removes the specified subscriber from the list of subscribers that listen for particular events on the bus. /// </summary> /// <param name="subscriber">The subscriber that is being removed.</param> /// <param name="classifier">The classifier of the event that the subscriber wants.</param> /// <returns><c>true</c> if the subscription cancellation succeeds; otherwise <c>false</c>.</returns> public virtual bool Unsubscribe(TSubscriber subscriber, TClassifier classifier) { lock (_classifiers) { var res = false; if (_classifiers.TryGetValue(classifier, out var subscribers)) { if (subscribers.RemoveAll(s => s.Subscriber.Equals(subscriber)) > 0) res = true; } else { foreach (var kvp in _classifiers) { if (!IsSubClassification(kvp.Key, classifier)) continue; var subscriptions = kvp.Value.Where(ss => ss.Subscriber.Equals(subscriber)).ToList(); foreach (var existingSubscriber in subscriptions) { existingSubscriber.Unsubscriptions.Add(classifier); res = true; } } } ClearCache(); return res; } } private void ClearCache() { _cache = new ConcurrentDictionary<TClassifier, List<TSubscriber>>(); } /// <summary> /// Determines whether a specified classifier, <paramref name="child"/>, is a subclass of another classifier, <paramref name="parent"/>. /// </summary> /// <param name="parent">The potential parent of the classifier that is being checked.</param> /// <param name="child">The classifier that is being checked.</param> /// <returns><c>true</c> if the <paramref name="child"/> classifier is a subclass of <paramref name="parent"/>; otherwise <c>false</c>.</returns> protected abstract bool IsSubClassification(TClassifier parent, TClassifier child); /// <summary> /// Publishes the specified event directly to the specified subscriber. /// </summary> /// <param name="event">The event that is being published.</param> /// <param name="subscriber">The subscriber that receives the event.</param> protected abstract void Publish(TEvent @event, TSubscriber subscriber); /// <summary> /// Classifies the specified event using the specified classifier. /// </summary> /// <param name="event">The event that is being classified.</param> /// <param name="classifier">The classifier used to classify the event.</param> /// <returns><c>true</c> if the classification succeeds; otherwise <c>false</c>.</returns> protected abstract bool Classify(TEvent @event, TClassifier classifier); /// <summary> /// Retrieves the classifier used to classify the specified event. /// </summary> /// <param name="event">The event for which to retrieve the classifier.</param> /// <returns>The classifier used to classify the event.</returns> protected abstract TClassifier GetClassifier(TEvent @event); /// <summary> /// Publishes the specified event to the bus. /// </summary> /// <param name="event">The event that is being published.</param> public virtual void Publish(TEvent @event) { var eventClass = GetClassifier(@event); if (_cache.TryGetValue(eventClass, out var cachedSubscribers)) PublishToSubscribers(@event, cachedSubscribers); else { cachedSubscribers = UpdateCacheForEventClassifier(@event, eventClass); PublishToSubscribers(@event, cachedSubscribers); } } private void PublishToSubscribers(TEvent @event, List<TSubscriber> cachedSubscribers) { foreach (var subscriber in cachedSubscribers) { Publish(@event, subscriber); } } private List<TSubscriber> UpdateCacheForEventClassifier(TEvent @event, TClassifier eventClass) { lock (_classifiers) { var cachedSubscribers = new HashSet<TSubscriber>(); foreach (var kvp in _classifiers) { var classifier = kvp.Key; var set = kvp.Value; if (!Classify(@event, classifier)) continue; foreach (var subscriber in set) { if (subscriber.Unsubscriptions.Any(u => IsSubClassification(u, eventClass))) continue; cachedSubscribers.Add(subscriber.Subscriber); } } //finds a distinct list of subscribers for the given event type var list = cachedSubscribers.ToList(); _cache[eventClass] = list; return list; } } } }
42.63913
153
0.564291
[ "Apache-2.0" ]
IgorFedchenko/akka.net
src/core/Akka/Event/EventBus.cs
9,809
C#
namespace Grynwald.Extensions.Statiq.DocsTemplate.Modules { /// <summary> /// Enumerates option how links are resolved by the <see cref="MarkNavbarItemsAsActive"/> module. /// </summary> /// <seealso cref="ResolveDocumentReferences" /> public enum LinkMode { /// <summary> /// Use the input documents' source path /// </summary> Destination = 0, /// <summary> /// Use the input documents' destination path /// </summary> Source = 1 } }
26.5
101
0.581132
[ "MIT" ]
ap0llo/extensions-statiq
src/Extensions.Statiq.DocsTemplate/Modules/LinkMode.cs
532
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/MsHTML.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="DOMMSAnimationEvent" /> struct.</summary> public static unsafe partial class DOMMSAnimationEventTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="DOMMSAnimationEvent" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(DOMMSAnimationEvent).GUID, Is.EqualTo(IID_DOMMSAnimationEvent)); } /// <summary>Validates that the <see cref="DOMMSAnimationEvent" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<DOMMSAnimationEvent>(), Is.EqualTo(sizeof(DOMMSAnimationEvent))); } /// <summary>Validates that the <see cref="DOMMSAnimationEvent" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(DOMMSAnimationEvent).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="DOMMSAnimationEvent" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(DOMMSAnimationEvent), Is.EqualTo(1)); } } }
39.288889
145
0.670814
[ "MIT" ]
DaZombieKiller/terrafx.interop.windows
tests/Interop/Windows/um/MsHTML/DOMMSAnimationEventTests.cs
1,770
C#
using Microsoft.AspNet.Identity; using Microsoft.Owin.Security; using System; using System.Configuration; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; namespace Auth0OwinTest.Controllers { public class Auth0AccountController : Controller { private IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; } } // // GET: /Auth0Account/ExternalLoginCallback [AllowAnonymous] public async Task<ActionResult> ExternalLoginCallback(string returnUrl) { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); var externalIdentity = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie); if (externalIdentity == null) { throw new Exception("Could not get the external identity. Please check your Auth0 configuration settings and ensure that " + "you configured UseCookieAuthentication and UseExternalSignInCookie in the OWIN Startup class. " + "Also make sure you are not calling setting the callbackOnLocationHash option on the JavaScript login widget."); } AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = false }, CreateIdentity(externalIdentity)); return RedirectToLocal(returnUrl); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult LogOff(string returnUrl) { var appTypes = AuthenticationManager.GetAuthenticationTypes().Select(at => at.AuthenticationType).ToArray(); AuthenticationManager.SignOut(appTypes); var absoluteReturnUrl = string.IsNullOrEmpty(returnUrl) ? this.Url.Action("Index", "Home", new { }, this.Request.Url.Scheme) : this.Url.IsLocalUrl(returnUrl) ? new Uri(this.Request.Url, returnUrl).AbsoluteUri : returnUrl; return Redirect( string.Format("https://{0}/v2/logout?returnTo={1}", ConfigurationManager.AppSettings["auth0:Domain"], absoluteReturnUrl)); } private static ClaimsIdentity CreateIdentity(ClaimsIdentity externalIdentity) { var identity = new ClaimsIdentity(externalIdentity.Claims, DefaultAuthenticationTypes.ApplicationCookie); // This claim is required for the ASP.NET Anti-Forgery Token to function. // See http://msdn.microsoft.com/en-us/library/system.web.helpers.antiforgeryconfig.uniqueclaimtypeidentifier(v=vs.111).aspx identity.AddClaim( new Claim( "http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string")); return identity; } private ActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction("Index", "Home"); } } } }
39.689655
148
0.624964
[ "MIT" ]
Amialc/auth0-aspnet-owin
test/Auth0OwinTest/Controllers/Auth0AccountController.cs
3,455
C#
using System.ComponentModel; using DevExpress.ExpressApp; using DevExpress.Persistent.Base; using DevExpress.Persistent.BaseImpl; using DevExpress.Xpo; namespace Xpand.TestsLib.Common.BO{ [DefaultClassOptions] public class Order : BaseObject,IObjectSpaceLink{ private Accessory _accessory; private Product _product; public Order(Session session) : base(session){ } long _orderID; public long OrderID{ get => _orderID; set => SetPropertyValue(nameof(OrderID), ref _orderID, value); } public Product Product{ get => _product; set => SetPropertyValue(nameof(Product), ref _product, value); } public Accessory Accessory{ get => _accessory; set => SetPropertyValue(nameof(Accessory), ref _accessory, value); } [Association("Order-AggregatedOrders")] [Aggregated] public XPCollection<Order> AggregatedOrders => GetCollection<Order>(nameof(AggregatedOrders)); Order _aggregatedOrder; [Association("Order-AggregatedOrders")][VisibleInListView(false)][VisibleInDetailView(false)][VisibleInLookupListView(false)] public Order AggregatedOrder{ get => _aggregatedOrder; set => SetPropertyValue(nameof(AggregatedOrder), ref _aggregatedOrder, value); } [Browsable(false)][NonPersistent] public IObjectSpace ObjectSpace{ get; set; } } }
32.413043
133
0.657277
[ "Apache-2.0" ]
aois-dev/Reactive.XAF
src/Tests/TestsLib.Common/BO/Order.cs
1,493
C#
// Instance generated by TankLibHelper.InstanceBuilder // ReSharper disable All namespace TankLib.STU.Types { [STUAttribute(0xED45C5E8)] public class STU_ED45C5E8 : STU_1361E674 { [STUFieldAttribute(0xB2ABF4FF, ReaderType = typeof(EmbeddedInstanceFieldReader))] public STUConfigVar m_B2ABF4FF; [STUFieldAttribute(0x5912C8DF, ReaderType = typeof(EmbeddedInstanceFieldReader))] public STUConfigVar m_5912C8DF; [STUFieldAttribute(0xC9E6F46B, ReaderType = typeof(EmbeddedInstanceFieldReader))] public STUConfigVar m_C9E6F46B; [STUFieldAttribute(0x5A72EEF5, ReaderType = typeof(EmbeddedInstanceFieldReader))] public STUConfigVar m_5A72EEF5; [STUFieldAttribute(0x2BA6230F, ReaderType = typeof(EmbeddedInstanceFieldReader))] public STUConfigVar m_2BA6230F; } }
37
89
0.748531
[ "MIT" ]
Mike111177/OWLib
TankLib/STU/Types/STU_ED45C5E8.cs
851
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using DotNetCoreDecorators; using MyJetWallet.Sdk.ServiceBus; using Newtonsoft.Json; using Service.CandleMigration.Domain.Models; using SimpleTrading.Abstraction.Candles; using SimpleTrading.CandlesHistory.Grpc; using SimpleTrading.ServiceBus.Contracts; using SimpleTrading.ServiceBus.Models; namespace Service.CandleMigration.Domain { public class CandleImporter { private readonly ISimpleTradingCandlesHistoryGrpc _candleGrpc; private static HttpClient _http = new(); private readonly IServiceBusPublisher<CandleMigrationServiceBusContract> _publisher; public CandleImporter(ISimpleTradingCandlesHistoryGrpc candleGrpc, IServiceBusPublisher<CandleMigrationServiceBusContract> publisher) { _candleGrpc = candleGrpc; _publisher = publisher; } public async Task ImportInstrumentFromBinance(string symbol, string source, int digits, bool isRevert = false, int deph = 45000) { Console.WriteLine(); Console.WriteLine($"========= Load {symbol} from {source} ======="); var candle = CandleType.Minute; await LoadInterval(candle, source, symbol, digits, isRevert, deph); if (source.Contains("BUSD")) await LoadInterval(candle, source.Replace("BUSD", "USDC"), symbol, digits, isRevert, deph); candle = CandleType.Hour; await LoadInterval(candle, source, symbol, digits, isRevert, deph); if (source.Contains("BUSD")) await LoadInterval(candle, source.Replace("BUSD", "USDC"), symbol, digits, isRevert, deph); candle = CandleType.Day; await LoadInterval(candle, source, symbol, digits, isRevert, deph); if (source.Contains("BUSD")) await LoadInterval(candle, source.Replace("BUSD", "USDC"), symbol, digits, isRevert, deph); candle = CandleType.Month; await LoadInterval(candle, source, symbol, digits, isRevert, deph); if (source.Contains("BUSD")) await LoadInterval(candle, source.Replace("BUSD", "USDC"), symbol, digits, isRevert, deph); // var reloadResult = await _candleGrpc.ReloadInstrumentAsync(new ReloadInstrumentContract() // { // InstrumentId = symbol // }); Console.WriteLine($"Instrument {symbol} is imported."); } private async Task LoadInterval(CandleType candle, string source, string symbol, int digits, bool isRevert, int depth) { Console.WriteLine(); Console.WriteLine($"----- {candle.ToString()} --------"); var interval = ""; switch (candle) { case CandleType.Minute: interval = "1m"; break; case CandleType.Hour: interval = "1h"; break; case CandleType.Day: interval = "1d"; break; case CandleType.Month: interval = "1M"; break; } var data = await GetCandles(source, 1000, interval, 0, isRevert, digits); var count = 0; while (data.Any() && count < depth) { Console.WriteLine($"{DateTime.UtcNow:HH:mm:ss} Read {data.Count} items from Binance [handled: {count}] ... "); var senditerations = 0; foreach (var items in data.Chunk(100)) { var iterations = 10; while (iterations > 0) { iterations--; senditerations++; try { await _publisher.PublishAsync(data.Select(binanceCandle => new CandleMigrationServiceBusContract() { Symbol = symbol, IsBid = true, Digits = digits, Candle = candle, Data = new MigrationCandle { DateTime = binanceCandle.DateTime, Open = binanceCandle.Open, High = binanceCandle.High, Low = binanceCandle.Low, Close = binanceCandle.Close } })); await _publisher.PublishAsync(data.Select(binanceCandle => new CandleMigrationServiceBusContract { Symbol = symbol, IsBid = false, Digits = digits, Candle = candle, Data = new MigrationCandle { DateTime = binanceCandle.DateTime, Open = binanceCandle.Open, High = binanceCandle.High, Low = binanceCandle.Low, Close = binanceCandle.Close } })); iterations = 0; } catch (Exception ex) { Console.WriteLine($"{DateTime.UtcNow:HH:mm:ss} Cannot send messages to SB: {ex}"); await Task.Delay(5000); } } } Console.WriteLine($"{DateTime.UtcNow:HH:mm:ss} Save {data.Count} items to bids and ask [{senditerations}]"); var lastTime = data.Min(e => e.DateTime).UnixTime(); count += data.Count; data = await GetCandles(source, 1000, interval, lastTime - 1, isRevert, digits); } } public static async Task<List<BinanceCandle>> GetCandles(string symbol, int limit, string interval, long endtime, bool isRevert, int digit) { try { var url = "https://api.binance.com/api/v3/klines"; if (endtime > 0) url += $"?symbol={symbol}&limit={limit}&interval={interval}&endTime={endtime}"; else url += $"?symbol={symbol}&limit={limit}&interval={interval}"; Console.WriteLine(url); //_http.Timeout = TimeSpan.FromSeconds(10); var cts = new CancellationTokenSource(); cts.CancelAfter(10000); var json = await _http.GetStringAsync(url, cts.Token); if (json.Contains("Invalid symbol")) { Console.WriteLine("Invalid symbol"); return new List<BinanceCandle>(); } else { Console.WriteLine("Receive data from binance"); } var data = JsonConvert.DeserializeObject<string[][]>(json); //Console.WriteLine(url); return data.Select(e => BinanceCandle.Create(e, isRevert, digit)).ToList(); //https://api.binance.com/api/v3/klines?symbol=BTCUSD&limit=10&interval=1m //https://api.binance.com/api/v3/klines?symbol=BTCBUSD&limit=2&interval=1m&endTime=1629381839999 } catch (Exception ex) { Console.WriteLine($"cannot read date: {ex.Message}"); return new List<BinanceCandle>(); } } } }
40.359223
141
0.477869
[ "MIT" ]
MyJetWallet/Service.CandleMigration
src/Service.CandleMigration.Domain/CandleImporter.cs
8,314
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Tanneryd.BulkInsert.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Tanneryd.BulkInsert.Tests")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("1ed7fcfd-93f9-46a2-8426-aa0e9c18ba6a")] // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
30.952381
56
0.758462
[ "Apache-2.0" ]
Chralex/ef6-bulk-operations
Tanneryd.BulkOperations.EF6/Tanneryd.BulkOperations.EF6.Tests/Properties/AssemblyInfo.cs
651
C#
/* * Generated code file by Il2CppInspector - http://www.djkaty.com - https://github.com/djkaty */ using System; using System.Diagnostics; using System.Runtime.CompilerServices; using UnityEngine; // Image 66: Assembly-CSharp.dll - Assembly: Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null - Types 8552-8785 namespace SciFiArsenal { public class SciFiProjectileScript : MonoBehaviour // TypeDefIndex: 8775 { // Fields public GameObject impactParticle; // 0x18 public GameObject projectileParticle; // 0x20 public GameObject muzzleParticle; // 0x28 public GameObject[] trailParticles; // 0x30 [HideInInspector] // 0x0000000180014D50-0x0000000180014D60 public Vector3 impactNormal; // 0x38 private bool hasCollided; // 0x44 // Constructors public SciFiProjectileScript(); // 0x0000000180265240-0x0000000180265250 // Methods private void Start(); // 0x0000000180B512F0-0x0000000180B515A0 private void OnCollisionEnter(Collision hit); // 0x0000000180B50E70-0x0000000180B512F0 } }
31.454545
133
0.768786
[ "MIT" ]
TotalJTM/PrimitierModdingFramework
Dumps/PrimitierDumpV1.0.1/SciFiArsenal/SciFiProjectileScript.cs
1,040
C#
// Copyright (c) Pixel Crushers. All rights reserved. using UnityEngine; using System.Collections; namespace PixelCrushers { /// <summary> /// Invokes a callback method when an animator has entered and then exited a /// specified trigger state. /// </summary> public class UIAnimatorMonitor { public static float MaxWaitDuration = 10; private MonoBehaviour m_target; private bool m_lookedForAnimator = false; private Animator m_animator = null; private Animation m_animation = null; private Coroutine m_coroutine = null; public string currentTrigger { get; private set; } public UIAnimatorMonitor(GameObject target) { m_target = (target != null) ? target.GetComponent<MonoBehaviour>() : null; currentTrigger = string.Empty; } public UIAnimatorMonitor(MonoBehaviour target) { m_target = target; currentTrigger = string.Empty; } public void SetTrigger(string triggerName, System.Action callback, bool wait = true) { if (m_target == null) return; m_target.gameObject.SetActive(true); CancelCurrentAnimation(); if (!m_target.gameObject.activeInHierarchy) return; // May still be inactive if quitting application. m_coroutine = m_target.StartCoroutine(WaitForAnimation(triggerName, callback, wait)); } private IEnumerator WaitForAnimation(string triggerName, System.Action callback, bool wait) { if (HasAnimator() && !string.IsNullOrEmpty(triggerName)) { if (m_animator != null) { // Run Animator and wait: CheckAnimatorModeAndTimescale(triggerName); m_animator.SetTrigger(triggerName); currentTrigger = triggerName; float timeout = Time.realtimeSinceStartup + MaxWaitDuration; var goalHashID = Animator.StringToHash(triggerName); var oldHashId = UIUtility.GetAnimatorNameHash(m_animator.GetCurrentAnimatorStateInfo(0)); var currentHashID = oldHashId; if (wait) { while ((currentHashID != goalHashID) && (currentHashID == oldHashId) && (Time.realtimeSinceStartup < timeout)) { yield return null; currentHashID = (m_animator != null) ? UIUtility.GetAnimatorNameHash(m_animator.GetCurrentAnimatorStateInfo(0)) : 0; } if (Time.realtimeSinceStartup < timeout && m_animator != null) { var clipLength = m_animator.GetCurrentAnimatorStateInfo(0).length; if (Mathf.Approximately(0, Time.timeScale)) { timeout = Time.realtimeSinceStartup + clipLength; while (Time.realtimeSinceStartup < timeout) { yield return null; } } else { yield return new WaitForSeconds(clipLength); } } } } else if (m_animation != null) { m_animation.Play(triggerName); if (wait) { var clip = m_animation.GetClip(triggerName); if (clip != null) { yield return new WaitForSeconds(clip.length); } } } } currentTrigger = string.Empty; m_coroutine = null; if (callback != null) callback.Invoke(); } private bool HasAnimator() { if (m_animator == null && m_animation == null && !m_lookedForAnimator) { m_lookedForAnimator = true; if (m_target != null) { m_animator = m_target.GetComponent<Animator>(); if (m_animator == null) { m_animation = m_target.GetComponent<Animation>(); if (m_animation == null) { m_animator = m_target.GetComponentInChildren<Animator>(); if (m_animator == null) { m_animation = m_target.GetComponentInChildren<Animation>(); } } } } } return (m_animator != null || m_animation != null); } private void CheckAnimatorModeAndTimescale(string triggerName) { if (m_animator == null) return; if (Mathf.Approximately(0, Time.timeScale) && (m_animator.updateMode != AnimatorUpdateMode.UnscaledTime)) { m_animator.updateMode = AnimatorUpdateMode.UnscaledTime; } } public void CancelCurrentAnimation() { if (m_coroutine == null || m_target == null) return; currentTrigger = string.Empty; m_target.StopCoroutine(m_coroutine); m_coroutine = null; } } }
38.431373
145
0.47415
[ "MIT" ]
HBot106/Bounty
Assets/Plugins/Pixel Crushers/Common/Scripts/UI/UIAnimatorMonitor.cs
5,882
C#
using System; using System.Drawing; using System.ComponentModel; using System.Windows.Forms; using System.Drawing.Imaging; using System.Runtime.InteropServices; using System.IO; using System.Drawing.Printing; using ESolutions.Win32; using EverydaySolutions.Windows.Forms; namespace ESolutions.Windows.Forms { /// <summary> /// Summary description for MyPictureBox. /// </summary> public class PictureBox : System.Windows.Forms.PictureBox { #region uncorrectedImage /// <summary> /// The original color uncorrected image. /// </summary> private Image originalImage; #endregion #region correctedImage /// <summary> /// The color corrected image when ebaleICM is true. /// </summary> private Image correctedImage; #endregion #region enableICM /// <summary> /// Bacling field of EnableICM property. /// </summary> private bool enableICM = false; #endregion #region EnableICM /// <summary> /// Get or sets a value indicating wether the picture box uses color correction mode or not. /// </summary> /// <remarks>Set the SourceICMProfiles and TargetICMProfiles before you set this property to true.</remarks> /// <exception cref="Exception">If the SourceICMProfile or the TargetICMProfiles (or both) are not set. You can not enable ICM</exception> [Browsable (true)] [Category ("ColorCorrection")] [Description ("Enables or Disables ICM mode")] public bool EnableICM { get { return this.enableICM; } set { if (value == true) { if ( this.sourceICMProfile == null || this.targetICMProfile == null || this.sourceICMProfile.Exists == false || this.targetICMProfile.Exists == false) { throw new Exception (PictureBoxExceptions.CantEnableICM); } this.enableICM = true; this.OnEnableICMChanged (); SetImage (); } else { this.enableICM = false; this.OnEnableICMChanged (); SetImage (); } } } #endregion #region sourceICMProfile /// <summary> /// Backing field of SourceICMProfile property. /// </summary> private FileInfo sourceICMProfile; #endregion #region SourceICMProfile /// <summary> /// The ICM Profle of the displaying device /// </summary> [Browsable (true)] [Category ("ColorCorrection")] [Description ("Gets or sets the SourceICMProfile")] public String SourceICMProfile { get { String result = String.Empty; if (this.sourceICMProfile != null) { result = this.sourceICMProfile.FullName; } return result; } set { if (value == null || value == String.Empty) { this.sourceICMProfile = null; } else { this.sourceICMProfile = new FileInfo (value); } if (this.sourceICMProfile == null || this.sourceICMProfile.Exists == false) { this.enableICM = false; this.OnEnableICMChanged (); } SetImage (); } } #endregion #region EnableICMChanged /// <summary> /// Occurs when the EnableICM property changes /// </summary> public event EventHandler EnableICMChanged; #endregion #region OnEnableICMChanged /// <summary> /// Fires the EnableICMChanged event. /// </summary> protected void OnEnableICMChanged () { if (EnableICMChanged != null) { this.EnableICMChanged ( this, new EventArgs ()); } } #endregion #region targetICMProfile /// <summary> /// Backing field of the TargetICMProfile property. /// </summary> private FileInfo targetICMProfile; #endregion #region TargetICMProfile /// <summary> /// The ICM Profile of the target device. For example your printer. /// </summary> [Browsable (true)] [Category ("ColorCorrection")] [Description ("Gets or sets the TargetICMProfile")] public String TargetICMProfile { get { String result = String.Empty; if (this.targetICMProfile != null) { result = this.targetICMProfile.FullName; ; } return result; } set { if (value == null || value == String.Empty) { this.targetICMProfile = null; } else { this.targetICMProfile = new FileInfo (value); } if (this.targetICMProfile == null || this.targetICMProfile.Exists == false) { this.enableICM = false; this.OnEnableICMChanged (); } SetImage (); } } #endregion #region Image /// <summary> /// The image that shall be displayed be the picture box. /// </summary> [Browsable (true)] [Description ("Gets or sets the displayed image")] public new System.Drawing.Image Image { get { return base.Image; } set { this.originalImage = value; SetImage (); } } #endregion #region SetImage /// <summary> /// If enableICM is true the corrected image is shown. Otherwise the original uncorrected. /// </summary> private void SetImage () { if (this.originalImage == null) { this.correctedImage = null; } else { if (enableICM) { this.correctedImage = Gdi32.PerformColorMatching ( this.originalImage, sourceICMProfile, targetICMProfile); base.Image = this.correctedImage; } else { base.Image = this.originalImage; } } } #endregion } }
20.936508
140
0.642911
[ "MIT" ]
everyday-solution/ESolutions.Windows.Forms
ESolutions.Windows.Forms/PictureBox/PictureBox.cs
5,276
C#
using Lucene.Net.Util; using Lucene.Net.Util.Automaton; using System; using System.Collections.Generic; using System.IO; using Console = Lucene.Net.Util.SystemConsole; namespace Lucene.Net.Analysis { /* * 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. */ /// <summary> /// Analyzer for testing. /// <para/> /// This analyzer is a replacement for Whitespace/Simple/KeywordAnalyzers /// for unit tests. If you are testing a custom component such as a queryparser /// or analyzer-wrapper that consumes analysis streams, its a great idea to test /// it with this analyzer instead. MockAnalyzer has the following behavior: /// <list type="bullet"> /// <item> /// <description> /// By default, the assertions in <see cref="MockTokenizer"/> are turned on for extra /// checks that the consumer is consuming properly. These checks can be disabled /// with <see cref="EnableChecks"/>. /// </description> /// </item> /// <item> /// <description> /// Payload data is randomly injected into the stream for more thorough testing /// of payloads. /// </description> /// </item> /// </list> /// </summary> /// <seealso cref="MockTokenizer"/> public sealed class MockAnalyzer : Analyzer { private readonly CharacterRunAutomaton runAutomaton; private readonly bool lowerCase; private readonly CharacterRunAutomaton filter; private int positionIncrementGap; private int? offsetGap; private readonly Random random; private IDictionary<string, int?> previousMappings = new Dictionary<string, int?>(); private bool enableChecks = true; private int maxTokenLength = MockTokenizer.DEFAULT_MAX_TOKEN_LENGTH; /// <summary> /// Creates a new <see cref="MockAnalyzer"/>. /// </summary> /// <param name="random"> Random for payloads behavior </param> /// <param name="runAutomaton"> DFA describing how tokenization should happen (e.g. [a-zA-Z]+) </param> /// <param name="lowerCase"> true if the tokenizer should lowercase terms </param> /// <param name="filter"> DFA describing how terms should be filtered (set of stopwords, etc) </param> public MockAnalyzer(Random random, CharacterRunAutomaton runAutomaton, bool lowerCase, CharacterRunAutomaton filter) : base(PER_FIELD_REUSE_STRATEGY) { // TODO: this should be solved in a different way; Random should not be shared (!). this.random = new Random(random.Next()); this.runAutomaton = runAutomaton; this.lowerCase = lowerCase; this.filter = filter; } /// <summary> /// Calls <c>MockAnalyzer(random, runAutomaton, lowerCase, MockTokenFilter.EMPTY_STOPSET, false)</c>. /// </summary> public MockAnalyzer(Random random, CharacterRunAutomaton runAutomaton, bool lowerCase) : this(random, runAutomaton, lowerCase, MockTokenFilter.EMPTY_STOPSET) { } /// <summary> /// Create a Whitespace-lowercasing analyzer with no stopwords removal. /// <para/> /// Calls <c>MockAnalyzer(random, MockTokenizer.WHITESPACE, true, MockTokenFilter.EMPTY_STOPSET, false)</c>. /// </summary> public MockAnalyzer(Random random) : this(random, MockTokenizer.WHITESPACE, true) { } protected internal override TokenStreamComponents CreateComponents(string fieldName, TextReader reader) { MockTokenizer tokenizer = new MockTokenizer(reader, runAutomaton, lowerCase, maxTokenLength); tokenizer.EnableChecks = enableChecks; MockTokenFilter filt = new MockTokenFilter(tokenizer, filter); return new TokenStreamComponents(tokenizer, MaybePayload(filt, fieldName)); } private TokenFilter MaybePayload(TokenFilter stream, string fieldName) { lock (this) { int? val; previousMappings.TryGetValue(fieldName, out val); if (val == null) { val = -1; // no payloads if (LuceneTestCase.Rarely(random)) { switch (random.Next(3)) { case 0: // no payloads val = -1; break; case 1: // variable length payload val = int.MaxValue; break; case 2: // fixed length payload val = random.Next(12); break; } } if (LuceneTestCase.VERBOSE) { if (val == int.MaxValue) { Console.WriteLine("MockAnalyzer: field=" + fieldName + " gets variable length payloads"); } else if (val != -1) { Console.WriteLine("MockAnalyzer: field=" + fieldName + " gets fixed length=" + val + " payloads"); } } previousMappings[fieldName] = val; // save it so we are consistent for this field } if (val == -1) { return stream; } else if (val == int.MaxValue) { return new MockVariableLengthPayloadFilter(random, stream); } else { return new MockFixedLengthPayloadFilter(random, stream, (int)val); } } } public void SetPositionIncrementGap(int positionIncrementGap) { this.positionIncrementGap = positionIncrementGap; } public override int GetPositionIncrementGap(string fieldName) { return positionIncrementGap; } /// <summary> /// Sets an offset gap which will then be added to the offset when several fields with the same name are indexed </summary> public void SetOffsetGap(int offsetGap) { this.offsetGap = offsetGap; } /// <summary> /// Get the offset gap between tokens in fields if several fields with the same name were added. </summary> /// <param name="fieldName"> Currently not used, the same offset gap is returned for each field. </param> public override int GetOffsetGap(string fieldName) { return offsetGap == null ? base.GetOffsetGap(fieldName) : offsetGap.Value; } /// <summary> /// Toggle consumer workflow checking: if your test consumes tokenstreams normally you /// should leave this enabled. /// </summary> public bool EnableChecks { get => enableChecks; // LUCENENET specific - added getter (to follow MSDN property guidelines) set => enableChecks = value; } /// <summary> /// Toggle maxTokenLength for <see cref="MockTokenizer"/>. /// </summary> public int MaxTokenLength { get => maxTokenLength; // LUCENENET specific - added getter (to follow MSDN property guidelines) set => maxTokenLength = value; } } }
41.639024
131
0.564667
[ "Apache-2.0" ]
bongohrtech/lucenenet
src/Lucene.Net.TestFramework/Analysis/MockAnalyzer.cs
8,536
C#
using CryptoExchange.Net.Attributes; using CryptoExchange.Net.Converters; using Okex.Net.Converters; using Newtonsoft.Json; using System; using System.Collections.Generic; using Okex.Net.Enums; namespace Okex.Net.RestObjects { public class OkexSpotOrderBook { [JsonProperty("instrument_id"), JsonOptionalProperty] public string Symbol { get; set; } = ""; [JsonProperty("checksum"), JsonOptionalProperty] public long Checksum { get; set; } [JsonOptionalProperty, JsonConverter(typeof(SpotOrderBookDataTypeConverter))] public OkexSpotOrderBookDataType DataType { get; set; } = OkexSpotOrderBookDataType.Api; /// <summary> /// Selling side /// </summary> [JsonProperty("asks")] public IEnumerable<OkexSpotOrderBookEntry> Asks { get; set; } = new List<OkexSpotOrderBookEntry>(); /// <summary> /// Buying side /// </summary> [JsonProperty("bids")] public IEnumerable<OkexSpotOrderBookEntry> Bids { get; set; } = new List<OkexSpotOrderBookEntry>(); /// <summary> /// Timestamp /// </summary> [JsonProperty("timestamp")] public DateTime Timestamp { get; set; } } [JsonConverter(typeof(ArrayConverter))] public class OkexSpotOrderBookEntry { /// <summary> /// The price for this entry /// </summary> [ArrayProperty(0)] public decimal Price { get; set; } /// <summary> /// The quantity for this entry /// </summary> [ArrayProperty(1)] public decimal Quantity { get; set; } /// <summary> /// Number of orders at the price /// </summary> [ArrayProperty(2)] public decimal OrdersCount { get; set; } } }
28.84127
107
0.605394
[ "MIT" ]
always-awaken/OKEx.Net
Okex.Net/RestObjects/Spot/OkexSpotOrderBook.cs
1,819
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 opsworks-2013-02-18.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.OpsWorks.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.OpsWorks.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for RegisterElasticIp operation /// </summary> public class RegisterElasticIpResponseUnmarshaller : 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) { RegisterElasticIpResponse response = new RegisterElasticIpResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("ElasticIp", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.ElasticIp = 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) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException")) { return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ValidationException")) { return ValidationExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonOpsWorksException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static RegisterElasticIpResponseUnmarshaller _instance = new RegisterElasticIpResponseUnmarshaller(); internal static RegisterElasticIpResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static RegisterElasticIpResponseUnmarshaller Instance { get { return _instance; } } } }
37.675439
191
0.648894
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/OpsWorks/Generated/Model/Internal/MarshallTransformations/RegisterElasticIpResponseUnmarshaller.cs
4,295
C#
using Windows.UI.Xaml.Navigation; namespace WorkingWithListview.WinPhone81 { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage { public MainPage() { this.InitializeComponent(); this.NavigationCacheMode = NavigationCacheMode.Required; this.LoadApplication(new WorkingWithListview.App()); } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. /// This parameter is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { // TODO: Prepare page for display here. // TODO: If your application contains multiple pages, ensure that you are // handling the hardware Back button by registering for the // Windows.Phone.UI.Input.HardwareButtons.BackPressed event. // If you are using the NavigationHelper provided by some templates, // this event is handled for you. } } }
36.705882
85
0.627404
[ "Apache-2.0" ]
Alshaikh-Abdalrahman/jedoo
WorkingWithListview/WinPhone81/MainPage.xaml.cs
1,250
C#
// <copyright file="KeyboardServiceTests.cs" company="Automate The Planet Ltd."> // Copyright 2020 Automate The Planet Ltd. // 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. // </copyright> // <author>Anton Angelov</author> // <site>https://bellatrix.solutions/</site> using Microsoft.VisualStudio.TestTools.UnitTesting; using OpenQA.Selenium.Appium.Android; using OpenQA.Selenium.Appium.Android.Enums; using BA = Bellatrix.Assertions; namespace Bellatrix.Mobile.Android.Tests { [TestClass] [Android(Constants.AndroidNativeAppPath, Constants.AndroidDefaultAndroidVersion, Constants.AndroidDefaultDeviceName, Constants.AndroidNativeAppAppExamplePackage, ".app.CustomTitle", Lifecycle.ReuseIfStarted)] [AllureSuite("Services")] [AllureFeature("KeyboardService")] public class KeyboardServiceTests : MSTest.AndroidTest { [TestMethod] [TestCategory(Categories.CI)] public void TestHideKeyBoard() { var textField = App.ElementCreateService.CreateByIdContaining<TextField>("left_text_edit"); textField.SetText(string.Empty); App.KeyboardService.HideKeyboard(); } [TestMethod] [TestCategory(Categories.CI)] public void PressKeyCodeTest() { App.KeyboardService.PressKeyCode(AndroidKeyCode.Home); } [TestMethod] [TestCategory(Categories.CI)] public void PressKeyCodeWithMetastateTest() { App.KeyboardService.PressKeyCode(AndroidKeyCode.Space, AndroidKeyMetastate.Meta_Shift_On); } [TestMethod] [TestCategory(Categories.CI)] public void LongPressKeyCodeTest() { App.KeyboardService.LongPressKeyCode(AndroidKeyCode.Home); } [TestMethod] [TestCategory(Categories.CI)] public void LongPressKeyCodeWithMetastateTest() { App.KeyboardService.LongPressKeyCode(AndroidKeyCode.Space, AndroidKeyMetastate.Meta_Shift_On); } } }
36.028169
106
0.694292
[ "Apache-2.0" ]
alexandrejulien/BELLATRIX
tests/Bellatrix.Mobile.Android.Tests/Services/KeyboardServiceTests.cs
2,560
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: IEntityCollectionReferencesRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; /// <summary> /// The interface IDeviceAndAppManagementRoleAssignmentRoleScopeTagsCollectionReferencesRequest. /// </summary> public partial interface IDeviceAndAppManagementRoleAssignmentRoleScopeTagsCollectionReferencesRequest : IBaseRequest { /// <summary> /// Adds the specified RoleScopeTag to the collection via POST. /// </summary> /// <param name="roleScopeTag">The RoleScopeTag to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> System.Threading.Tasks.Task AddAsync(RoleScopeTag roleScopeTag, CancellationToken cancellationToken = default); /// <summary> /// Adds the specified RoleScopeTag to the collection via POST and returns a <see cref="GraphResponse{RoleScopeTag}"/> object of the request. /// </summary> /// <param name="roleScopeTag">The RoleScopeTag to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> System.Threading.Tasks.Task<GraphResponse> AddResponseAsync(RoleScopeTag roleScopeTag, CancellationToken cancellationToken = default); } }
48.184211
153
0.654833
[ "MIT" ]
ScriptBox99/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/IDeviceAndAppManagementRoleAssignmentRoleScopeTagsCollectionReferencesRequest.cs
1,831
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20160401 { public static class GetZone { /// <summary> /// Describes a DNS zone. /// </summary> public static Task<GetZoneResult> InvokeAsync(GetZoneArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetZoneResult>("azure-native:network/v20160401:getZone", args ?? new GetZoneArgs(), options.WithVersion()); } public sealed class GetZoneArgs : Pulumi.InvokeArgs { /// <summary> /// The name of the resource group. The name is case insensitive. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the DNS zone (without a terminating dot). /// </summary> [Input("zoneName", required: true)] public string ZoneName { get; set; } = null!; public GetZoneArgs() { } } [OutputType] public sealed class GetZoneResult { /// <summary> /// The etag of the zone. /// </summary> public readonly string? Etag; /// <summary> /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} /// </summary> public readonly string Id; /// <summary> /// The geo-location where the resource lives /// </summary> public readonly string Location; /// <summary> /// The maximum number of record sets that can be created in this DNS zone. This is a read-only property and any attempt to set this value will be ignored. /// </summary> public readonly double? MaxNumberOfRecordSets; /// <summary> /// The maximum number of records per record set that can be created in this DNS zone. This is a read-only property and any attempt to set this value will be ignored. /// </summary> public readonly double MaxNumberOfRecordsPerRecordSet; /// <summary> /// The name of the resource /// </summary> public readonly string Name; /// <summary> /// The name servers for this DNS zone. This is a read-only property and any attempt to set this value will be ignored. /// </summary> public readonly ImmutableArray<string> NameServers; /// <summary> /// The current number of record sets in this DNS zone. This is a read-only property and any attempt to set this value will be ignored. /// </summary> public readonly double? NumberOfRecordSets; /// <summary> /// Resource tags. /// </summary> public readonly ImmutableDictionary<string, string>? Tags; /// <summary> /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" /// </summary> public readonly string Type; /// <summary> /// The type of this DNS zone (Public or Private). /// </summary> public readonly string? ZoneType; [OutputConstructor] private GetZoneResult( string? etag, string id, string location, double? maxNumberOfRecordSets, double maxNumberOfRecordsPerRecordSet, string name, ImmutableArray<string> nameServers, double? numberOfRecordSets, ImmutableDictionary<string, string>? tags, string type, string? zoneType) { Etag = etag; Id = id; Location = location; MaxNumberOfRecordSets = maxNumberOfRecordSets; MaxNumberOfRecordsPerRecordSet = maxNumberOfRecordsPerRecordSet; Name = name; NameServers = nameServers; NumberOfRecordSets = numberOfRecordSets; Tags = tags; Type = type; ZoneType = zoneType; } } }
34.648438
197
0.60451
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Network/V20160401/GetZone.cs
4,435
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the snowball-2016-06-30.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.Snowball.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Snowball.Model.Internal.MarshallTransformations { /// <summary> /// DescribeJob Request Marshaller /// </summary> public class DescribeJobRequestMarshaller : IMarshaller<IRequest, DescribeJobRequest> , 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((DescribeJobRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(DescribeJobRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.Snowball"); string target = "AWSIESnowballJobManagementService.DescribeJob"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2016-06-30"; request.HttpMethod = "POST"; request.ResourcePath = "/"; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetJobId()) { context.Writer.WritePropertyName("JobId"); context.Writer.Write(publicRequest.JobId); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static DescribeJobRequestMarshaller _instance = new DescribeJobRequestMarshaller(); internal static DescribeJobRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DescribeJobRequestMarshaller Instance { get { return _instance; } } } }
34.786408
137
0.629919
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/Snowball/Generated/Model/Internal/MarshallTransformations/DescribeJobRequestMarshaller.cs
3,583
C#
using System; using NHapi.Base; using NHapi.Base.Parser; using NHapi.Base.Model; using NHapi.Model.V231.Datatype; using NHapi.Base.Log; namespace NHapi.Model.V231.Segment{ ///<summary> /// Represents an HL7 DSC message segment. /// This segment has the following fields:<ol> ///<li>DSC-1: Continuation Pointer (ST)</li> ///</ol> /// The get...() methods return data from individual fields. These methods /// do not throw exceptions and may therefore have to handle exceptions internally. /// If an exception is handled internally, it is logged and null is returned. /// This is not expected to happen - if it does happen this indicates not so much /// an exceptional circumstance as a bug in the code for this class. ///</summary> [Serializable] public class DSC : AbstractSegment { /** * Creates a DSC (DSC - Continuation pointer segment) segment object that belongs to the given * message. */ public DSC(IGroup parent, IModelClassFactory factory) : base(parent,factory) { IMessage message = Message; try { this.add(typeof(ST), false, 1, 180, new System.Object[]{message}, "Continuation Pointer"); } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Can't instantiate " + GetType().Name, he); } } ///<summary> /// Returns Continuation Pointer(DSC-1). ///</summary> public ST ContinuationPointer { get{ ST ret = null; try { IType t = this.GetField(1, 0); ret = (ST)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } }}
32.52459
112
0.669859
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
afaonline/nHapi
src/NHapi.Model.V231/Segment/DSC.cs
1,984
C#
using MonoTouch.UIKit; using System.Drawing; using System; using MonoTouch.Foundation; namespace AppPrefs { public partial class AppPrefsViewController : UIViewController { NSObject observer; public AppPrefsViewController (IntPtr handle) : base (handle) { } #region View lifecycle public override void ViewDidLoad () { base.ViewDidLoad (); TableView.Source = new MyUITableViewSource (); observer = NSNotificationCenter.DefaultCenter.AddObserver ((NSString)"NSUserDefaultsDidChangeNotification", UpdateSettings); } public override void ViewDidUnload () { base.ViewDidUnload (); if (observer != null) { NSNotificationCenter.DefaultCenter.RemoveObserver (observer); observer = null; } } public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); UpdateSettings (null); } #endregion public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation) { // Return true for supported orientations return (toInterfaceOrientation != UIInterfaceOrientation.PortraitUpsideDown); } void UpdateSettings (NSNotification obj) { // set table view background color switch (Settings.BackgroundColor) { case BackgroundColors.Black: this.TableView.BackgroundColor = UIColor.Black; break; case BackgroundColors.White: this.TableView.BackgroundColor = UIColor.White; break; case BackgroundColors.Blue: this.TableView.BackgroundColor = UIColor.Blue; break; case BackgroundColors.Pattern: this.TableView.BackgroundColor = UIColor.GroupTableViewBackgroundColor; break; } TableView.ReloadData (); } #region UITableViewDataSource class MyUITableViewSource : UITableViewSource { public override int NumberOfSections (UITableView tableView) { return 1; } public override int RowsInSection (UITableView tableview, int section) { return 1; } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { var kCellIdentifier = new NSString ("MyIdentifier"); var cell = tableView.DequeueReusableCell (kCellIdentifier); if (cell == null) { cell = new UITableViewCell (UITableViewCellStyle.Default, kCellIdentifier); cell.SelectionStyle = UITableViewCellSelectionStyle.None; } // Get the user settings from the app delegate. var firstNameStr = Settings.FirstName; var lastNameStr = Settings.LastName; cell.TextLabel.Text = firstNameStr + " " + lastNameStr; cell.BackgroundColor = UIView.Appearance.BackgroundColor; switch (Settings.TextColor) { case TextColors.Blue: cell.TextLabel.TextColor = UIColor.Blue; break; case TextColors.Green: cell.TextLabel.TextColor = UIColor.Green; break; case TextColors.Red: cell.TextLabel.TextColor = UIColor.Red; break; } return cell; } } #endregion } }
25.641026
127
0.715667
[ "Apache-2.0" ]
Acidburn0zzz/monotouch-samples
AppPrefs/AppPrefsViewController.cs
3,000
C#
using System; namespace EDrinks.QueryHandlers.Model { public class Spending { public Guid Id { get; set; } public Guid TabId { get; set; } public Guid ProductId { get; set; } public int Quantity { get; set; } public int Current { get; set; } } }
17.764706
43
0.572848
[ "MIT" ]
EDrinks/WebApi
EDrinks/EDrinks.QueryHandlers/Model/Spending.cs
302
C#
using System.Linq; using System.Threading.Tasks; using Content.Server.Construction.Components; using Content.Shared.Construction; using JetBrains.Annotations; using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.Log; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.Construction.Completions { [UsedImplicitly] [DataDefinition] public class BuildMachine : IGraphAction { public void PerformAction(EntityUid uid, EntityUid? userUid, IEntityManager entityManager) { if (!entityManager.TryGetComponent(uid, out ContainerManagerComponent? containerManager)) { Logger.Warning($"Machine frame entity {uid} did not have a container manager! Aborting build machine action."); return; } if (!entityManager.TryGetComponent(uid, out MachineFrameComponent? machineFrame)) { Logger.Warning($"Machine frame entity {uid} did not have a machine frame component! Aborting build machine action."); return; } if (!machineFrame.IsComplete) { Logger.Warning($"Machine frame entity {uid} doesn't have all required parts to be built! Aborting build machine action."); return; } if (!containerManager.TryGetContainer(MachineFrameComponent.BoardContainer, out var entBoardContainer)) { Logger.Warning($"Machine frame entity {uid} did not have the '{MachineFrameComponent.BoardContainer}' container! Aborting build machine action."); return; } if (!containerManager.TryGetContainer(MachineFrameComponent.PartContainer, out var entPartContainer)) { Logger.Warning($"Machine frame entity {uid} did not have the '{MachineFrameComponent.PartContainer}' container! Aborting build machine action."); return; } if (entBoardContainer.ContainedEntities.Count != 1) { Logger.Warning($"Machine frame entity {uid} did not have exactly one item in the '{MachineFrameComponent.BoardContainer}' container! Aborting build machine action."); } var board = entBoardContainer.ContainedEntities[0]; if (!board.TryGetComponent(out MachineBoardComponent? boardComponent)) { Logger.Warning($"Machine frame entity {uid} had an invalid entity in container \"{MachineFrameComponent.BoardContainer}\"! Aborting build machine action."); return; } entBoardContainer.Remove(board); var transform = entityManager.GetComponent<TransformComponent>(uid); var machine = entityManager.SpawnEntity(boardComponent.Prototype, transform.Coordinates); machine.Transform.LocalRotation = transform.LocalRotation; var boardContainer = machine.EnsureContainer<Container>(MachineFrameComponent.BoardContainer, out var existed); if (existed) { // Clean that up... boardContainer.CleanContainer(); } var partContainer = machine.EnsureContainer<Container>(MachineFrameComponent.PartContainer, out existed); if (existed) { // Clean that up, too... partContainer.CleanContainer(); } boardContainer.Insert(board); // Now we insert all parts. foreach (var part in entPartContainer.ContainedEntities.ToArray()) { entPartContainer.ForceRemove(part); partContainer.Insert(part); } var constructionSystem = entityManager.EntitySysManager.GetEntitySystem<ConstructionSystem>(); if (machine.TryGetComponent(out ConstructionComponent? construction)) { // We only add these two container. If some construction needs to take other containers into account, fix this. constructionSystem.AddContainer(machine.Uid, MachineFrameComponent.BoardContainer, construction); constructionSystem.AddContainer(machine.Uid, MachineFrameComponent.PartContainer, construction); } if (machine.TryGetComponent(out MachineComponent? machineComp)) { machineComp.RefreshParts(); } entityManager.DeleteEntity(uid); } } }
41.509091
182
0.635129
[ "MIT" ]
AJCM-git/space-station-14
Content.Server/Construction/Completions/BuildMachine.cs
4,566
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using MHO.Extensions; /// <summary> /// Inherit from this base class to create a singleton. /// Based off: http://wiki.unity3d.com/index.php/Singleton /// </summary> /// <typeparam name="T">MonoBehaviour that inherits this class.</typeparam> public class Singleton<T> : MonoBehaviour where T : MonoBehaviour { /// <summary> /// Thread lock object. /// </summary> private static object m_ThreadLocker = new object(); /// <summary> /// GameObject with manager components. /// </summary> private static GameObject m_Manager; /// <summary> /// Singleton instance. /// </summary> private static T m_Instance; /// <summary> /// Manager GameObject. /// </summary> protected static GameObject Manager { get { if (!m_Manager) { // If null, search for tagged object. GameObject[] managers = GameObject.FindGameObjectsWithTag("Manager"); for(int i = 0; i < managers.Length; i++) { if (managers[i].GetComponent<T>()) { // If component exists on object, we can keep it. m_Manager = managers[i]; break; } } // If still null, create and tag the object. if (!m_Manager) { // Create and tag the Manager object. m_Manager = new GameObject($"{typeof(T)}") { tag = "Manager" }; } } // Return the reference. return m_Manager; } } /// <summary> /// Accessor to the Singleton. /// </summary> public static T Instance { get { lock (m_ThreadLocker) { if (!m_Instance) { // If instance is null, search for instance. m_Instance = (T)FindObjectOfType(typeof(T)); // If instance doesn't exist, create a new one. if (!m_Instance) { // Find tagged manager GameObject to attach Singleton to. m_Instance = Manager.GetOrAddComponent<T>(); } } // Return reference. return m_Instance; } } } /// <summary> /// Return the Singleton{T} name. /// </summary> protected virtual string Name { get { return $"'{typeof(T)}' [Singleton]"; } } }
26.036697
85
0.462297
[ "MIT" ]
mwh2719/igme450-prototype-2
GAME02_IGME450/Assets/Scripts/Managers/Singleton.cs
2,840
C#
/* * UBI - Unique Body Identifier * Copyright (c) 2018 Interstellar Consortium * This file is licensed under the MIT license * * UBI is a system for referencing bodies in Kerbal Space Program without * using the internal name. It does not impose the same restrictions, like * having fixed names for homeworld ("Kerbin") and center of the universe ("Sun"). * It uses a different structure than normal names, it has to be a "system name" * and a "body name", combined with a forward slash "/". * * * This file is a reference implementation for UBI. Feel free to include and use * this file in your mods to make them compatible with UBI references. * It includes backwards compatibility with the internal names to maintain * config comatibility. * * In case a internal name gets queried the functions can log a warning that they * encountered a non-UBI name. If you want to enable that warning, * uncomment the line after this block */ // #define LOG_FALLBACK_NAME using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text.RegularExpressions; using UnityEngine; using Object = UnityEngine.Object; [SuppressMessage("ReSharper", "InconsistentNaming")] [SuppressMessage("ReSharper", "CheckNamespace")] [SuppressMessage("ReSharper", "MemberCanBePrivate.Global")] public static class UBI { private static readonly Regex Parser = new Regex(@"^.+/.+$"); /// <summary> /// Returns the name of the first found body implementing a UBI /// </summary> public static String GetName(String ubi, CelestialBody[] localBodies = null) { return GetNames(ubi, localBodies).FirstOrDefault(); } /// <summary> /// Returns the first found body impementing a UBI /// </summary> public static CelestialBody GetBody(String ubi, CelestialBody[] localBodies = null) { return GetBodies(ubi, localBodies).FirstOrDefault(); } /// <summary> /// Returns the names of all found bodies implementing a UBI /// </summary> public static String[] GetNames(String ubi, CelestialBody[] localBodies = null) { return GetBodies(ubi, localBodies).Select(b => b.transform.name).ToArray(); } /// <summary> /// Returns all found bodies implementing a UBI /// </summary> public static CelestialBody[] GetBodies(String ubi, CelestialBody[] localBodies = null) { if (localBodies == null) { localBodies = PSystemManager.Instance.localBodies.ToArray(); } List<CelestialBody> bodies = new List<CelestialBody>(); // Check if the UBI is valid #if LOG_FALLBACK_NAME if (String.IsNullOrEmpty(ubi) || !Parser.IsMatch(ubi)) { Debug.Log("[UBI] Encountered invalid UBI \"" + ubi + "\". Falling back to internal name."); } #endif for (Int32 i = 0; i < localBodies.Length; i++) { CelestialBody body = localBodies[i]; UBIIdent[] idents = FetchUBIs(body); for (Int32 j = 0; j < idents.Length; j++) { if (idents[j].UBI == ubi) { if (!idents[j].IsAbstract) { bodies.Insert(0, body); } else { bodies.Add(body); } } } } // Fallback to the internal name for compatibility reasons for (Int32 i = 0; i < localBodies.Length; i++) { CelestialBody body = localBodies[i]; if (body.transform.name == ubi) { bodies.Add(body); } } return bodies.ToArray(); } /// <summary> /// Connects a UBI to a body. /// </summary> public static void RegisterUBI(CelestialBody body, String ubi, Boolean isAbstract = false, CelestialBody[] localBodies = null) { if (String.IsNullOrEmpty(ubi) || !Parser.IsMatch(ubi)) { throw new InvalidOperationException("The specified UBI is invalid! It needs to be SystemName/PlanetName."); } if (!isAbstract) { // The UBI isn't abstract, so it has to be unique. We don't have some kind of // web API to check it for the entire world, but we can check the local solar system CelestialBody[] bodies = GetBodies(ubi, localBodies); for (Int32 i = 0; i < bodies.Length; i++) { UBIIdent[] idents = FetchUBIs(bodies[i]); for (Int32 j = 0; j < idents.Length; j++) { if (idents[j].UBI == ubi && !idents[j].IsAbstract) { throw new InvalidOperationException("The specified UBI already exists!"); } } } } // Check if the UBI is already assigned if (GetBodies(ubi, localBodies).Contains(body)) { throw new InvalidOperationException("The specified UBI was already assigned to this body!"); } // Check if the body already has a primary UBI if (!FetchUBIs(body).All(u => u.IsAbstract) && isAbstract) { throw new InvalidOperationException("The body has no primary UBI assigned to it!"); } // This is probably the most hacky way to do this, but still easier than to reflect and combine multiple // UBIIdent Components from multiple assemblies String[] split = ubi.Split('/'); GameObject ubiParent = body.gameObject.GetChild("UBI"); if (!ubiParent) { ubiParent = new GameObject("UBI"); ubiParent.transform.parent = body.transform; } GameObject ident = new GameObject(split[0] + ";" + split[1] + ";" + isAbstract); ident.transform.parent = ubiParent.transform; } /// <summary> /// Removes the connection between a UBI and a body /// </summary> public static void UnregisterUBI(CelestialBody body, String ubi) { if (String.IsNullOrEmpty(ubi) || !Parser.IsMatch(ubi)) { throw new InvalidOperationException("The specified UBI is invalid! It needs to be SystemName/PlanetName."); } UBIIdent[] idents = FetchUBIs(body); for (Int32 i = 0; i < idents.Length; i++) { if (idents[i].UBI == ubi) { Object.Destroy(idents[i].Object); } } } /// <summary> /// Gets the first UBI assigned to a body /// </summary> public static String GetUBI(CelestialBody body) { return GetUBIs(body).FirstOrDefault(); } /// <summary> /// Gets all UBIs assigned to a body /// </summary> public static String[] GetUBIs(CelestialBody body) { List<String> idents = FetchUBIs(body).OrderBy(u => u.IsAbstract ? 1 : 0).Select(u => u.UBI).ToList(); // Add the internal name at the end for compatiblity reasons idents.Add(body.transform.name); return idents.ToArray(); } /// <summary> /// Grabs a list of UBIIdents from a given body /// </summary> private static UBIIdent[] FetchUBIs(CelestialBody body) { GameObject ubiParent = body.gameObject.GetChild("UBI"); List<UBIIdent> idents = new List<UBIIdent>(); if (ubiParent) { foreach (Transform ident in ubiParent.transform) { String[] split = ident.name.Split(';'); idents.Add(new UBIIdent { System = split[0], Body = split[1], IsAbstract = Boolean.Parse(split[2]), Object = ident.gameObject }); } } return idents.ToArray(); } private struct UBIIdent { public String UBI { get { return System + "/" + Body; } } /// <summary> /// The name of the system the body is assigned to /// </summary> public String System; /// <summary> /// The name of the body /// </summary> public String Body; /// <summary> /// Whether this UBI is an abstract one. When this is set to false, the UBI must be unique in the loaded /// solar system, preferably unique in all planets ever made. If it is set to true the body implements the /// specified UBI and can take over configuration that was made for it. /// </summary> public Boolean IsAbstract; /// <summary> /// The game object that contains this UBI definition /// </summary> public GameObject Object; } }
33.73384
130
0.574729
[ "MIT" ]
StollD/SciRev
src/UBI.cs
8,874
C#
using System; using System.Linq; using System.Threading.Tasks; using AspnetRunBasics.ApiCollection.Interfaces; using AspnetRunBasics.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace AspnetRunBasics { public class CartModel : PageModel { private readonly IBasketRepository _basketRepository; public CartModel(IBasketRepository basketRepository) { _basketRepository = basketRepository ?? throw new ArgumentNullException(nameof(basketRepository)); } public BasketRepositoryModel Cart { get; set; } = new BasketRepositoryModel(); //public async Task<string> GetImageFileAsync(string id) //{ // return (await _catalogApi.GetCatalog(id)).ImageFile; //} public async Task<IActionResult> OnGetAsync() { Cart = _basketRepository.GetAllBasket(); return Page(); } public async Task<IActionResult> OnPostRemoveToCartAsync(string productId) { var basket = _basketRepository.GetAllBasket(); var item = basket.Items.Where(x => x.ProductId == productId).FirstOrDefault(); basket.Items.Remove(item); _basketRepository.Update(basket); return RedirectToPage(); } public async Task<IActionResult> OnPostUpdateAsync(string productId, string qty) { var basket = _basketRepository.GetAllBasket(); var item = basket.Items.Where(x => x.ProductId == productId).FirstOrDefault().Quantity=int.Parse(qty); _basketRepository.Update(basket); return RedirectToPage(); } } }
28.932203
116
0.651435
[ "MIT" ]
naimyurek/run-aspnetcore-microservices
src/WebApp/AspnetRunBasics/Pages/Cart.cshtml.cs
1,709
C#
using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using ProAgil.Domain; using ProAgil.Respository; namespace ProAgil.Repository { public class ProAgilRepository : IProAgilRepository { private readonly ProAgilContext _context; public ProAgilRepository(ProAgilContext context) { _context = context; _context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; } //GERAIS public void Add<T>(T entity) where T : class { _context.Add(entity); } public void Update<T>(T entity) where T : class { _context.Update(entity); } public void Delete<T>(T entity) where T : class { _context.Remove(entity); } public async Task<bool> SaveChangesAsync() { return (await _context.SaveChangesAsync()) > 0; } //EVENTO public async Task<Evento[]> GetAllEventoAsync(bool includePalestrantes = false) { IQueryable<Evento> query = _context.Eventos .Include(c => c.Lotes) .Include(c => c.RedesSociais); if(includePalestrantes) { query = query .Include(pe => pe.PalestrantesEventos) .ThenInclude(p => p.Palestrante); } query = query.AsNoTracking() .OrderBy(c => c.Id); return await query.ToArrayAsync(); } public async Task<Evento[]> GetAllEventoAsyncByTema(string tema, bool includePalestrantes) { IQueryable<Evento> query = _context.Eventos .Include(c => c.Lotes) .Include(c => c.RedesSociais); if(includePalestrantes) { query = query .Include(pe => pe.PalestrantesEventos) .ThenInclude(p => p.Palestrante); } query = query.AsNoTracking() .OrderByDescending(c => c.DataEvento) .Where(c => c.Tema.ToLower().Contains(tema.ToLower())); return await query.ToArrayAsync(); } public async Task<Evento> GetEventoAsyncById(int EventoId, bool includePalestrantes) { IQueryable<Evento> query = _context.Eventos .Include(c => c.Lotes) .Include(c => c.RedesSociais); if(includePalestrantes) { query = query .Include(pe => pe.PalestrantesEventos) .ThenInclude(p => p.Palestrante); } query = query.AsNoTracking() .OrderBy(c => c.Id) .Where(c => c.Id == EventoId); return await query.FirstOrDefaultAsync(); } //PALESTRANTE public async Task<Palestrante> GetPalestranteAsync(int PalestranteId, bool includeEventos = false) { IQueryable<Palestrante> query = _context.Palestrantes .Include(c => c.RedesSociais); if(includeEventos) { query = query .Include(pe => pe.PalestrantesEventos) .ThenInclude(e => e.Evento); } query = query.AsNoTracking() .OrderBy(p => p.Nome) .Where(p => p.Id == PalestranteId); return await query.FirstOrDefaultAsync(); } public async Task<Palestrante[]> GetAllPalestrantesAsyncByName(string name, bool includeEventos = false) { IQueryable<Palestrante> query = _context.Palestrantes .Include(c => c.RedesSociais); if(includeEventos) { query = query .Include(pe => pe.PalestrantesEventos) .ThenInclude(e => e.Evento); } query = query.AsNoTracking() .Where(p => p.Nome.ToLower().Contains(name.ToLower())); return await query.ToArrayAsync(); } } }
32.465649
112
0.514696
[ "MIT" ]
tabaesso/PrimeiroProjeto.NETApi
ProAgil.Repository/ProAgilRepository.cs
4,253
C#
using Exiled.API.Interfaces; using System.ComponentModel; namespace Scp069.System { public class Config : IConfig { public bool IsEnabled { get; set; } = true; [Description("True to disable the ASCII logo on the console, in case one should bother you")] public bool NotLogo { get; set; } = false; [Description("Show some Logs.Debug, you should turn this on if something doesn't work properly.")] public bool Debug { get; set; } = false; public BroadcastSetting Broadcasting { get; set; } = new BroadcastSetting(); public Scp069Config Scp069 { get; set; } = new Scp069Config(); public CommandTranslate TranslateCommand { get; set; } = new CommandTranslate(); } }
35.380952
106
0.66218
[ "MIT" ]
SrLicht/SCP-069
SCP-069/Scp069/System/Config.cs
745
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace Screenshoter { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public void CaptureApplication(string procName, int i) { var proc = Process.GetProcessesByName(procName)[0]; var rect = new User32.Rect(); User32.GetWindowRect(proc.MainWindowHandle, ref rect); int width = rect.right - rect.left; int height = rect.bottom - rect.top; var bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb); Graphics graphics = Graphics.FromImage(bmp); graphics.CopyFromScreen(rect.left, rect.top, 0, 0, new Size(width, height), CopyPixelOperation.SourceCopy); bmp.Save("frame" + i + ".png", ImageFormat.Png); } private class User32 { [StructLayout(LayoutKind.Sequential)] public struct Rect { public int left; public int top; public int right; public int bottom; } [DllImport("user32.dll")] public static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect); } protected override void OnLoad(EventArgs e) { int i = 0; while (true) { i++; CaptureApplication("VLC", i); Thread.Sleep(500); SendKeys.Send("e"); Thread.Sleep(500); } base.OnLoad(e); } } }
27.528571
119
0.562013
[ "MIT" ]
mihaid-b/CyberSakura
Gathered CTF writeups/2015-12-05-seccon/seccon_wars_100/Form1.cs
1,929
C#
using System; using System.Globalization; namespace Lykke.Service.Stellar.Api.Core.Domain { public class Asset { public Asset(string id, string address, string name, string typeName, int accuracy) => (Id, Address, Name, TypeName, Accuracy) = (id, address, name, typeName, accuracy); public string Id { get; } public string Address { get; } public string Name { get; } public string TypeName { get; } public int Accuracy { get; } public static Asset Stellar { get; } = new Asset("XLM", "", "Stellar Lumen", "native", 7); public long ParseDecimal(string value) { var pow = Convert.ToDecimal(Math.Pow(10, Accuracy)); var dec = decimal.Parse(value, CultureInfo.InvariantCulture); var mul = decimal.Round(dec * pow); var res = Convert.ToInt64(mul); return res; } } }
29.882353
98
0.544291
[ "MIT" ]
LykkeCity/Lykke.Service.Stellar.API
src/Lykke.Service.Stellar.Api.Core/Domain/Asset.cs
1,018
C#
namespace Microsoft.Extensions.DependencyInjection { using EasyCaching.Core; using EasyCaching.Core.Configurations; using EasyCaching.Memcached; using Microsoft.Extensions.Configuration; using System; /// <summary> /// EasyCaching options extensions. /// </summary> public static class EasyCachingOptionsExtensions { /// <summary> /// Uses the memcached provider (specify the config via hard code). /// </summary> /// <param name="options">Options.</param> /// <param name="configure">Configure provider settings.</param> /// <param name="name">The name of this provider instance.</param> public static EasyCachingOptions UseMemcached( this EasyCachingOptions options , Action<MemcachedOptions> configure , string name = EasyCachingConstValue.DefaultMemcachedName ) { ArgumentCheck.NotNull(configure, nameof(configure)); options.RegisterExtension(new MemcachedOptionsExtension(name, configure)); return options; } /// <summary> /// Uses the memcached provider (read config from configuration file). /// </summary> /// <param name="options">Options.</param> /// <param name="configuration">The configuration.</param> /// <param name="name">The name of this provider instance.</param> /// <param name="sectionName">The section name in the configuration file.</param> public static EasyCachingOptions UseMemcached( this EasyCachingOptions options , IConfiguration configuration , string name = EasyCachingConstValue.DefaultMemcachedName , string sectionName = EasyCachingConstValue.MemcachedSection ) { var dbConfig = configuration.GetSection(sectionName); var mOptions = new MemcachedOptions(); dbConfig.Bind(mOptions); void configure(MemcachedOptions x) { x.EnableLogging = mOptions.EnableLogging; x.MaxRdSecond = mOptions.MaxRdSecond; x.DBConfig = mOptions.DBConfig; } options.RegisterExtension(new MemcachedOptionsExtension(name, configure)); return options; } } }
38.16129
89
0.620879
[ "MIT" ]
KostaVlev/EasyCaching
src/EasyCaching.Memcached/Configurations/EasyCachingOptionsExtensions.cs
2,368
C#
using Myra.Graphics2D.UI; namespace Jord.MapEditor.UI { public class Pane: ScrollViewer { } }
11
32
0.727273
[ "MIT" ]
rds1983/Jord
src/Jord.MapEditor/UI/Pane.cs
101
C#
using Caasiope.Protocol.Types; namespace Caasiope.Explorer.JSON.API.Internals { public class VendingMachine : TxAddressDeclaration { public string Owner; public string CurrencyIn; public string CurrencyOut; public decimal Rate; public VendingMachine(string owner, string currencyIn, string currencyOut, decimal rate, string address) : this() { Owner = owner; CurrencyIn = currencyIn; CurrencyOut = currencyOut; Rate = rate; Address = address; } public VendingMachine() : base((byte)DeclarationType.VendingMachine) { } } }
28.73913
121
0.626324
[ "MIT" ]
caasiope/caasiope-blockchain
Caasiope.Explorer.JSON.API/Internals/VendingMachine.cs
663
C#
using System; using System.Linq; using System.IO; using System.Collections.Generic; using System.Text.RegularExpressions; using Newtonsoft.Json.Linq; using Npgsql; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; namespace Common { public enum Databases { AnalyticsPlatform, LakeYouTubeData, LakeYouTubeAnalytics, LakeAdWords, LakeLogging, LakeFacebook, } public enum YearDatabase { DataLakeDatabase } public static class DatabaseOperations { public static void Drop(Databases db) { string settingsField; switch (db) { case Databases.LakeYouTubeData: case Databases.LakeYouTubeAnalytics: case Databases.LakeAdWords: case Databases.LakeLogging: settingsField = "DataLakeDatabase"; break; case Databases.LakeFacebook: settingsField = "DataLakeDatabase"; break; default: throw new Exception("Invalid database"); } var(conn, databaseName) = ConnectionStringHelper.GetNoDbConnection(settingsField); conn.Open(); using (var cmd = conn.CreateCommand()) { cmd.CommandText = $"DROP DATABASE IF EXISTS \"{databaseName}\""; cmd.ExecuteNonQuery(); } conn.Close(); } public static void Migrate<T>() where T : DbContext, new() { using (var context = new T()) { context.Database.Migrate(); } } } public static class ConnectionStringHelper { static string AppsettingsPath = "appsettings.json"; public static string GetConnStr(string database) { using (StreamReader r = new StreamReader(AppsettingsPath)) { var json = JObject.Parse(r.ReadToEnd()); return (string) json["ConnectionStrings"][database]; } } public static NpgsqlConnection GetDbConnection(YearDatabase database) { return GetDbConnection(database.ToString()); } public static NpgsqlConnection GetDbConnection(string database) { var connectionString = GetConnStr(database); return new NpgsqlConnection(connectionString); } public static (NpgsqlConnection, string) GetNoDbConnection(string database) { var connectionString = GetConnStr(database); var dbNameRegex = new Regex(@"Database=(?<dbName>\w+)"); return ( new NpgsqlConnection(dbNameRegex.Replace(connectionString, "Database=postgres")), dbNameRegex.Match(connectionString).Groups["dbName"].Value ); } } public static class ContextIntrospection { public static (string schema, string table, List<string> keys) GetDatabaseInfo(IEntityType entity) { return ( schema : entity.Relational().Schema, table : entity.Relational().TableName, keys : entity.FindPrimaryKey().Properties.Select(x => x.Name).ToList() ); } public static (string schema, string table, List<string> keys) GetDatabaseInfo(DbContext context, Type modelClass) { var entity = context.Model.FindEntityType(modelClass); return GetDatabaseInfo(entity); } } public static class TableOperations { public static int DeleteFromTable(YearDatabase database, string schemaName, string tableName) { using (var connection = ConnectionStringHelper.GetDbConnection(database)) { connection.Open(); var cmd = connection.CreateCommand(); cmd.CommandText = $@"DELETE FROM {schemaName}.""{tableName}"""; return cmd.ExecuteNonQuery(); } } } }
33.272727
124
0.593393
[ "Apache-2.0" ]
leonardo-brickabode/jellyfish
src/Common/DatabaseHelper.cs
4,026
C#
// Copyright 2017 Google LLC. // Copyright 2020 James Przybylinski // // 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. // // NOTICE: This file was modified by James Przybylinski to be C#. using Iesi.Collections.Generic; using Fib.Net.Core.Api; using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; namespace Fib.Net.Core.Images { /** Holds the layers for an image. */ public sealed class ImageLayers : IEnumerable<ILayer> { public class Builder { private readonly IList<ILayer> layers = new List<ILayer>(); private readonly ImmutableHashSet<DescriptorDigest>.Builder layerDigestsBuilder = ImmutableHashSet.CreateBuilder<DescriptorDigest>(); private bool _removeDuplicates = false; /** * Adds a layer. Removes any prior occurrences of the same layer. * * <p>Note that only subclasses of {@link Layer} that implement {@code equals/hashCode} will be * guaranteed to not be duplicated. * * @param layer the layer to add * @return this * @throws LayerPropertyNotFoundException if adding the layer fails */ public Builder Add(ILayer layer) { layer = layer ?? throw new ArgumentNullException(nameof(layer)); layerDigestsBuilder.Add(layer.GetBlobDescriptor().GetDigest()); layers.Add(layer); return this; } /** * Adds all layers in {@code layers}. * * @param layers the layers to add * @return this * @throws LayerPropertyNotFoundException if adding a layer fails */ public Builder AddAll(ImageLayers layers) { layers = layers ?? throw new ArgumentNullException(nameof(layers)); foreach (ILayer layer in layers) { Add(layer); } return this; } /** * Remove any duplicate layers, keeping the last occurrence of the layer. * * @return this */ public Builder RemoveDuplicates() { _removeDuplicates = true; return this; } public ImageLayers Build() { if (!_removeDuplicates) { return new ImageLayers(ImmutableArray.CreateRange(layers), layerDigestsBuilder.ToImmutable()); } // LinkedHashSet maintains the order but keeps the first occurrence. Keep last occurrence by // adding elements in reverse, and then reversing the result ISet<ILayer> dedupedButReversed = new LinkedHashSet<ILayer>(layers.Reverse()); ImmutableArray<ILayer> deduped = ImmutableArray.CreateRange(dedupedButReversed.Reverse()); return new ImageLayers(deduped, layerDigestsBuilder.ToImmutable()); } } public static Builder CreateBuilder() { return new Builder(); } /** The layers of the image, in the order in which they are applied. */ private readonly ImmutableArray<ILayer> layers; /** Keeps track of the layers already added. */ private readonly ImmutableHashSet<DescriptorDigest> layerDigests; private ImageLayers(ImmutableArray<ILayer> layers, ImmutableHashSet<DescriptorDigest> layerDigests) { this.layers = layers; this.layerDigests = layerDigests; } /** @return a read-only view of the image layers. */ public ImmutableArray<ILayer> GetLayers() { return layers; } /** @return the layer count */ public int Size() { return layers.Length; } public bool IsEmpty() { return layers.Length == 0; } /** * @param index the index of the layer to get * @return the layer at the specified index */ public ILayer Get(int index) { return layers[index]; } /** * @param digest the digest used to retrieve the layer * @return the layer found, or {@code null} if not found * @throws LayerPropertyNotFoundException if getting the layer's blob descriptor fails */ public ILayer Get(DescriptorDigest digest) { if (!Has(digest)) { return null; } foreach (ILayer layer in layers) { if (layer.GetBlobDescriptor().GetDigest().Equals(digest)) { return layer; } } throw new InvalidOperationException(Resources.ImageLayersMissingLayerExceptionMessage); } /** * @param digest the digest to check for * @return true if the layer with the specified digest exists; false otherwise */ public bool Has(DescriptorDigest digest) { return layerDigests.Contains(digest); } public Enumerator GetEnumerator() { return new Enumerator(GetLayers().GetEnumerator()); } IEnumerator<ILayer> IEnumerable<ILayer>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public struct Enumerator : IEnumerator<ILayer> { private ImmutableArray<ILayer>.Enumerator inner; public Enumerator(ImmutableArray<ILayer>.Enumerator inner) { this.inner = inner; } public ILayer Current => inner.Current; object IEnumerator.Current => Current; public void Dispose() { } public bool MoveNext() { return inner.MoveNext(); } void IEnumerator.Reset() { throw new NotSupportedException(); } } } }
31.655963
114
0.559484
[ "Apache-2.0" ]
ILMTitan/FibDotNet
Fib.Net.Core/Images/ImageLayers.cs
6,901
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("CirclesIntersection")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CirclesIntersection")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4ba74d28-201e-46fa-981a-e9a1441c956a")] // 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" ]
AscenKeeprov/Programming-Fundamentals
Exercise9-ObjectsAndClasses/CirclesIntersection/Properties/AssemblyInfo.cs
1,409
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.ContainerService.Fluent.ContainerServiceAgentPool.Definition { using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition; /// <summary> /// The stage of a container service agent pool definition allowing to specify the agent pool ports to be exposed. /// </summary> /// <typeparam name="ParentT">The stage of the container service definition to return to after attaching this definition.</typeparam> public interface IWithPorts<ParentT> { /// <summary> /// Ports to be exposed on this agent pool. /// The default exposed ports are different based on your choice of orchestrator. /// </summary> /// <param name="ports">Port numbers that will be exposed on this agent pool.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.ContainerService.Fluent.ContainerServiceAgentPool.Definition.IWithAttach<ParentT> WithPorts(params int[] ports); } /// <summary> /// The stage of a container service agent pool definition allowing to specify the agent pool OS type. /// </summary> /// <typeparam name="ParentT">The stage of the container service definition to return to after attaching this definition.</typeparam> public interface IWithOSType<ParentT> { /// <summary> /// OS type to be used for every machine in the agent pool. /// Default is Linux. /// </summary> /// <param name="osType">OS type to be used for every machine in the agent pool.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.ContainerService.Fluent.ContainerServiceAgentPool.Definition.IWithAttach<ParentT> WithOSType(ContainerServiceOSTypes osType); } /// <summary> /// The stage of a container service agent pool definition allowing to specify the DNS prefix. /// </summary> /// <typeparam name="ParentT">The stage of the container service definition to return to after attaching this definition.</typeparam> public interface IWithLeafDomainLabel<ParentT> { /// <summary> /// Specify the DNS prefix to be used in the FQDN for the agent pool. /// </summary> /// <param name="dnsPrefix">The DNS prefix.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.ContainerService.Fluent.ContainerServiceAgentPool.Definition.IWithAttach<ParentT> WithDnsPrefix(string dnsPrefix); } /// <summary> /// The stage of a container service agent pool definition allowing to specify the agent pool OS disk size. /// </summary> /// <typeparam name="ParentT">The stage of the container service definition to return to after attaching this definition.</typeparam> public interface IWithOSDiskSize<ParentT> { /// <summary> /// OS Disk Size in GB to be used for every machine in the agent pool. /// </summary> /// <param name="osDiskSizeInGB">OS disk size in GB to be used for each virtual machine in the agent pool.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.ContainerService.Fluent.ContainerServiceAgentPool.Definition.IWithAttach<ParentT> WithOSDiskSizeInGB(int osDiskSizeInGB); } /// <summary> /// The stage of a container service agent pool definition allowing to specify the agent virtual machine size. /// </summary> /// <typeparam name="ParentT">The stage of the container service definition to return to after attaching this definition.</typeparam> public interface IWithVMSize<ParentT> { /// <summary> /// Specifies the size of the agent virtual machines. /// </summary> /// <param name="vmSize">The size of the virtual machine.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.ContainerService.Fluent.ContainerServiceAgentPool.Definition.IWithLeafDomainLabel<ParentT> WithVirtualMachineSize(ContainerServiceVirtualMachineSizeTypes vmSize); } /// <summary> /// The entirety of a container service agent pool definition as a part of a parent definition. /// </summary> /// <typeparam name="ParentT">The stage of the container service definition to return to after attaching this definition.</typeparam> public interface IDefinition<ParentT> : Microsoft.Azure.Management.ContainerService.Fluent.ContainerServiceAgentPool.Definition.IWithAttach<ParentT>, Microsoft.Azure.Management.ContainerService.Fluent.ContainerServiceAgentPool.Definition.IBlank<ParentT>, Microsoft.Azure.Management.ContainerService.Fluent.ContainerServiceAgentPool.Definition.IWithVMSize<ParentT>, Microsoft.Azure.Management.ContainerService.Fluent.ContainerServiceAgentPool.Definition.IWithLeafDomainLabel<ParentT> { } /// <summary> /// The stage of a container service agent pool definition allowing to specify the subnet to be used by the machines in the agent pool. /// </summary> /// <typeparam name="ParentT">The stage of the container service definition to return to after attaching this definition.</typeparam> public interface IWithSubnet<ParentT> { /// <summary> /// Specifies the subnet to be used for each virtual machine in the agent pool. /// The subnet must be in the same virtual network as specified for the master. By default, the master subnet will be used. /// </summary> /// <param name="subnetName">The name of the subnet to be used for each virtual machine in the agent pool.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.ContainerService.Fluent.ContainerServiceAgentPool.Definition.IWithAttach<ParentT> WithSubnetName(string subnetName); } /// <summary> /// The stage of a container service agent pool definition allowing to specify the agent pool storage kind. /// </summary> /// <typeparam name="ParentT">The stage of the container service definition to return to after attaching this definition.</typeparam> public interface IWithStorageProfile<ParentT> { /// <summary> /// Specifies the storage kind to be used for each virtual machine in the agent pool. /// </summary> /// <param name="storageProfile">The storage kind to be used for each virtual machine in the agent pool.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.ContainerService.Fluent.ContainerServiceAgentPool.Definition.IWithAttach<ParentT> WithStorageProfile(StorageProfileTypes storageProfile); } /// <summary> /// The first stage of a container service agent pool definition. /// </summary> /// <typeparam name="ParentT">The stage of the container service definition to return to after attaching this definition.</typeparam> public interface IBlank<ParentT> { /// <summary> /// Specifies the number of agents (virtual machines) to host docker containers. /// </summary> /// <param name="count">A number between 1 and 100.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.ContainerService.Fluent.ContainerServiceAgentPool.Definition.IWithVMSize<ParentT> WithVirtualMachineCount(int count); } /// <summary> /// The final stage of a container service agent pool definition. /// At this stage, any remaining optional settings can be specified, or the container service agent pool /// can be attached to the parent container service definition. /// </summary> /// <typeparam name="ParentT">The stage of the container service definition to return to after attaching this definition.</typeparam> public interface IWithAttach<ParentT> : Microsoft.Azure.Management.ContainerService.Fluent.ContainerServiceAgentPool.Definition.IWithOSType<ParentT>, Microsoft.Azure.Management.ContainerService.Fluent.ContainerServiceAgentPool.Definition.IWithOSDiskSize<ParentT>, Microsoft.Azure.Management.ContainerService.Fluent.ContainerServiceAgentPool.Definition.IWithPorts<ParentT>, Microsoft.Azure.Management.ContainerService.Fluent.ContainerServiceAgentPool.Definition.IWithStorageProfile<ParentT>, Microsoft.Azure.Management.ContainerService.Fluent.ContainerServiceAgentPool.Definition.IWithSubnet<ParentT>, Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition.IInDefinition<ParentT> { } }
59.489933
197
0.718412
[ "MIT" ]
abharath27/azure-libraries-for-net
src/ResourceManagement/ContainerService/Domain/ContainerServiceAgentPool/Definition/IDefinition.cs
8,864
C#