content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using HarmonyLib; using RimWorld; using System.Collections.Generic; using System.Linq; using System.Reflection; using Verse; namespace WallStuff { [StaticConstructorOnStartup] static class HarmonyPatches { // this static constructor runs to create a HarmonyInstance and install a patch. static HarmonyPatches() { Harmony harmony = new Harmony("rimworld.arcjc.wallstuff"); var originalLaunchThingsOfTypeMethod = typeof(TradeUtility).GetMethod("LaunchThingsOfType"); var patchedLaunchThingsOfTypeMethod = typeof(WallMountedTradeUtility).GetMethod("LaunchThingsOfType"); var originalAllLaunchableThingsForTradeMethod = typeof(TradeUtility).GetMethod("AllLaunchableThingsForTrade"); var patchedAllLaunchableThingsForTradeMethod = typeof(WallMountedTradeUtility).GetMethod("AllLaunchableThingsForTrade"); var originalAllPoweredMethod = typeof(Building_OrbitalTradeBeacon).GetMethod("AllPowered"); var patchedAllPoweredMethod = typeof(WallTradeBeacon).GetMethod("AllPoweredHarmonyPatch"); harmony.Patch(originalLaunchThingsOfTypeMethod, postfix: new HarmonyMethod(patchedLaunchThingsOfTypeMethod)); harmony.Patch(originalAllLaunchableThingsForTradeMethod, postfix: new HarmonyMethod(patchedAllLaunchableThingsForTradeMethod)); harmony.Patch(originalAllPoweredMethod, postfix: new HarmonyMethod(patchedAllPoweredMethod)); } } }
45.666667
139
0.751161
[ "Unlicense" ]
JohnCannon87/RimworldWallStuff
1.1/Source/HarmonyPatches.cs
1,509
C#
using System.Collections.Generic; using JetBrains.Annotations; using Newtonsoft.Json; namespace Modding { /// <summary> /// Class to hold GlobalSettings for the Modding API /// </summary> [PublicAPI] public class ModHooksGlobalSettings { // now used to serialize and deserialize the save data. Not updated until save. [JsonProperty] internal Dictionary<string, bool> ModEnabledSettings = new(); /// <summary> /// Logging Level to use. /// </summary> public LogLevel LoggingLevel = LogLevel.Info; /// <summary> /// All settings related to the the in game console /// </summary> public InGameConsoleSettings ConsoleSettings = new(); /// <summary> /// Determines if Debug Console (Which displays Messages from Logger) should be shown. /// </summary> public bool ShowDebugLogInGame; /// <summary> /// Determines for the preloading how many different scenes should be loaded at once. /// </summary> public int PreloadBatchSize = 5; } }
29.894737
98
0.610915
[ "MIT" ]
HollowKnight-Modding/HollowKnight.Modding
Assembly-CSharp/ModHooksGlobalSettings.cs
1,136
C#
using FoxTunes.Interfaces; using System; using System.Collections.Generic; using System.Linq; namespace FoxTunes { public class Core : BaseComponent, ICore { public static bool IsShuttingDown { get; set; } private Core() { ComponentRegistry.Instance.Clear(); IsShuttingDown = false; } public Core(ICoreSetup setup) : this() { this.Setup = setup; foreach (var slot in ComponentSlots.All) { if (!this.Setup.HasSlot(slot)) { ComponentResolver.Slots[slot] = ComponentSlots.Blocked; } } } public ICoreSetup Setup { get; private set; } public IStandardComponents Components { get { return StandardComponents.Instance; } } public IStandardManagers Managers { get { return StandardManagers.Instance; } } public IStandardFactories Factories { get { return StandardFactories.Instance; } } public void Load() { this.Load(Enumerable.Empty<IBaseComponent>()); } public void Load(IEnumerable<IBaseComponent> components) { try { this.LoadComponents(); this.LoadFactories(); this.LoadManagers(); this.LoadBehaviours(); ComponentRegistry.Instance.AddComponents(components); this.LoadConfiguration(); } catch (Exception e) { Logger.Write(this, LogLevel.Debug, "Failed to load the core, we will crash soon: {0}", e.Message); throw; } } public void Initialize() { try { this.InitializeComponents(); } catch (Exception e) { Logger.Write(this, LogLevel.Debug, "Failed to initialize the core, we will crash soon: {0}", e.Message); throw; } } protected virtual void LoadComponents() { ComponentRegistry.Instance.AddComponents(ComponentLoader.Instance.Load(this)); } protected virtual void LoadManagers() { ComponentRegistry.Instance.AddComponents(ManagerLoader.Instance.Load(this)); } protected virtual void LoadFactories() { ComponentRegistry.Instance.AddComponents(FactoryLoader.Instance.Load(this)); } protected virtual void LoadBehaviours() { ComponentRegistry.Instance.AddComponents(BehaviourLoader.Instance.Load(this)); } protected virtual void LoadConfiguration() { ComponentRegistry.Instance.ForEach<IConfigurableComponent>(component => { Logger.Write(this, LogLevel.Debug, "Registering configuration for component {0}.", component.GetType().Name); try { var sections = component.GetConfigurationSections(); foreach (var section in sections) { this.Components.Configuration.WithSection(section); } } catch (Exception e) { Logger.Write(this, LogLevel.Warn, "Failed to register configuration for component {0}: {1}", component.GetType().Name, e.Message); } }); this.Components.Configuration.Load(); this.Components.Configuration.ConnectDependencies(); } protected virtual void InitializeComponents() { ComponentRegistry.Instance.ForEach(component => { try { component.InitializeComponent(this); } catch (Exception e) { Logger.Write(this, LogLevel.Warn, "Failed to initialize component {0}: {1}", component.GetType().Name, e.Message); } }); } public void InitializeDatabase(IDatabaseComponent database, DatabaseInitializeType type) { ComponentRegistry.Instance.ForEach<IDatabaseInitializer>(component => { try { component.InitializeDatabase(database, type); } catch (Exception e) { Logger.Write(this, LogLevel.Warn, "Failed to initialize database {0}: {1}", component.GetType().Name, e.Message); } }); } public bool IsDisposed { get; private set; } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (this.IsDisposed || !disposing) { return; } this.OnDisposing(); this.IsDisposed = true; } protected virtual void OnDisposing() { ComponentRegistry.Instance.ForEach<IDisposable>(component => { if (object.ReferenceEquals(this, component)) { return; } try { component.Dispose(); } catch (Exception e) { Logger.Write(this, LogLevel.Warn, "Failed to dispose component {0}: {1}", component.GetType().Name, e.Message); } }); } ~Core() { Logger.Write(this, LogLevel.Error, "Component was not disposed: {0}", this.GetType().Name); try { this.Dispose(true); } catch { //Nothing can be done, never throw on GC thread. } } } }
30.097674
151
0.46917
[ "MIT" ]
DJCALIEND/FoxTunes
FoxTunes.Core/Core.cs
6,473
C#
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * ironruby@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ using System; using System.Diagnostics; using System.Reflection; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronRuby.Builtins; using IronRuby.Compiler; namespace IronRuby.Runtime.Calls { public class RubyMemberInfo { // Singleton used to undefine methods: stops method resolution internal static readonly RubyMemberInfo/*!*/ UndefinedMethod = new RubyMemberInfo(RubyMemberFlags.Empty); // Singleton used to hide CLR methods: method resolution skips all CLR methods since encountering a hidden method. internal static readonly RubyMemberInfo/*!*/ HiddenMethod = new RubyMemberInfo(RubyMemberFlags.Empty); // Singleton used to represent interop members (these are not in method tables). This includes foreign meta-object members and CLR members. // Interop member represents a Ruby-public method. internal static readonly RubyMemberInfo/*!*/ InteropMember = new RubyMemberInfo(RubyMemberFlags.Public); private readonly RubyMemberFlags _flags; // // A method body can be shared by multiple method definitions, one of them is the primary definition and the others are its copies. // Only three cases of sharing are allowed: // 1) The primary definition's declaring module is a super-class of the copied definition. // 2) The primary definition's declaring module was duplicated and method copies are defined in the duplicate. // 3) The primary definition's declaring module is not a class. // // We assume these restrictions in the super-call implementation and instance variable storage allocation. // See also: instance_method, method, define_method, module_function, private, protected, public. // // DeclaringModule is null for dummy methods. // private readonly RubyModule _declaringModule; #region Mutable state guarded by ClassHierarchyLock private bool _invalidateSitesOnOverride; private bool _invalidateGroupsOnRemoval; #endregion public RubyMethodVisibility Visibility { get { return (RubyMethodVisibility)(_flags & RubyMemberFlags.VisibilityMask); } } // // Notes on visibility // // Ruby visibility is orthogonal to CLR visibility. // Ruby visibility is mutable, CLR visibility is not. // A method group can comprise of methods of various CLR visibility. Ruby visibility applies on the group as a whole. // /// <summary> /// True if the member is Ruby-protected. /// </summary> /// <remarks> /// Ruby-protected members can only be called from a scope whose self immediate class is a descendant of the method owner. /// CLR-protected members can only be called if the receiver is a descendant of the method owner. /// </remarks> public bool IsProtected { get { return (_flags & RubyMemberFlags.Protected) != 0; } } /// <summary> /// True if the member is Ruby-private. /// </summary> /// <remarks> /// Ruby-private members can only be called with an implicit receiver (self). /// CLR-private members can only be called if in PrivateBinding mode, the receiver might be explicit or implicit. /// </remarks> public bool IsPrivate { get { return (_flags & RubyMemberFlags.Private) != 0; } } /// <summary> /// True if the member is Ruby-public. /// </summary> public bool IsPublic { get { return (_flags & RubyMemberFlags.Public) != 0; } } internal bool IsEmpty { get { return (_flags & RubyMemberFlags.Empty) != 0; } } internal virtual bool IsSuperForwarder { get { return false; } } /// <summary> /// True if the member is defined in Ruby or for undefined and hidden members. /// False for members representing CLR members. /// </summary> internal virtual bool IsRubyMember { get { return true; } } /// <summary> /// True if the member behaves like a property/field: GetMember invokes the member. /// Otherwise the member behaves like a method: GetMember returns the method. /// </summary> internal virtual bool IsDataMember { get { return false; } } /// <summary> /// True if the member can be permanently removed. /// True for attached CLR members, i.e. real CLR members and extension methods. /// False for detached CLR members and extension methods. /// If the member cannot be removed we hide it. /// </summary> internal bool IsRemovable { get { return IsRubyMember && !IsHidden && !IsUndefined && !IsInteropMember; } } internal RubyMemberFlags Flags { get { return _flags; } } /// <summary> /// True if the method should invalidate groups below it in the inheritance hierarchy. /// </summary> /// <remarks> /// Set when a Ruby method is defined that hides a CLR overload that is used in a method group below the definition. /// Set when an extension method is added above the Ruby method definition and the change isn't propagated below. /// Undefined and Hidden method singletons cannot be removed so they don't need to be marked. /// </remarks> [DebuggerDisplay("{_invalidateGroupsOnRemoval}")] internal bool InvalidateGroupsOnRemoval { get { Context.RequiresClassHierarchyLock(); return _invalidateGroupsOnRemoval; } set { Context.RequiresClassHierarchyLock(); Debug.Assert(IsRemovable); _invalidateGroupsOnRemoval = value; } } /// <summary> /// Method definition that replaces/overrides this method will cause version update of all dependent subclasses/modules, which /// triggers invalidation of sites that are bound to those classes. /// </summary> [DebuggerDisplay("{_invalidateSitesOnOverride}")] internal bool InvalidateSitesOnOverride { get { Context.RequiresClassHierarchyLock(); return _invalidateSitesOnOverride; } } internal virtual void SetInvalidateSitesOnOverride() { _invalidateSitesOnOverride = true; } internal static void SetInvalidateSitesOnOverride(RubyMemberInfo/*!*/ member) { member._invalidateSitesOnOverride = true; } public RubyModule/*!*/ DeclaringModule { get { Debug.Assert(_declaringModule != null); return _declaringModule; } } public RubyContext/*!*/ Context { get { Debug.Assert(_declaringModule != null); return _declaringModule.Context; } } // TODO: public virtual int GetArity() { return 0; } public bool IsUndefined { get { return ReferenceEquals(this, UndefinedMethod); } } public bool IsHidden { get { return ReferenceEquals(this, HiddenMethod); } } public bool IsInteropMember { get { return ReferenceEquals(this, InteropMember); } } // undefined, hidden, interop method: private RubyMemberInfo(RubyMemberFlags flags) { _flags = flags; } internal RubyMemberInfo(RubyMemberFlags flags, RubyModule/*!*/ declaringModule) { Assert.NotNull(declaringModule); Debug.Assert(flags != RubyMemberFlags.Invalid); _flags = flags; _declaringModule = declaringModule; } internal protected virtual RubyMemberInfo Copy(RubyMemberFlags flags, RubyModule/*!*/ module) { throw Assert.Unreachable; } public override string/*!*/ ToString() { return IsHidden ? "<hidden>" : IsUndefined ? "<undefined>" : (GetType().Name + " " + _flags.ToString() + " (" + _declaringModule.Name + ")"); } /// <summary> /// Gets all the CLR members represented by this member info. /// </summary> public virtual MemberInfo/*!*/[]/*!*/ GetMembers() { throw Assert.Unreachable; } /// <summary> /// Returns a Ruby array describing parameters of the method. /// </summary> public virtual RubyArray/*!*/ GetRubyParameterArray() { if (_declaringModule == null) { return new RubyArray(); } // TODO: quick approximation, we can do better var context = _declaringModule.Context; RubyArray result = new RubyArray(); int arity = GetArity(); int mandatoryCount = (arity < 0) ? -arity - 1 : arity; var reqSymbol = context.CreateAsciiSymbol("req"); for (int i = 0; i < mandatoryCount; i++) { result.Add(new RubyArray { reqSymbol }); } if (arity < 0) { result.Add(new RubyArray { context.CreateAsciiSymbol("rest") }); } return result; } /// <summary> /// Returns a copy of this member info that groups only those members of this member info that are generic /// and of generic arity equal to the length of the given array of type arguments. Returns null if there are no such generic members. /// All the members in the resulting info are constructed generic methods bound to the given type arguments. /// </summary> public virtual RubyMemberInfo TryBindGenericParameters(Type/*!*/[]/*!*/ typeArguments) { return null; } public virtual RubyMemberInfo TrySelectOverload(Type/*!*/[]/*!*/ parameterTypes) { throw Assert.Unreachable; } #region Dynamic Operations internal virtual MemberDispatcher GetDispatcher(Type/*!*/ delegateType, RubyCallSignature signature, object target, int version) { return null; } internal virtual void BuildCallNoFlow(MetaObjectBuilder/*!*/ metaBuilder, CallArguments/*!*/ args, string/*!*/ name) { throw Assert.Unreachable; } internal virtual void BuildMethodMissingCallNoFlow(MetaObjectBuilder/*!*/ metaBuilder, CallArguments/*!*/ args, string/*!*/ name) { args.InsertMethodName(name); BuildCallNoFlow(metaBuilder, args, Symbols.MethodMissing); } internal void BuildCall(MetaObjectBuilder/*!*/ metaBuilder, CallArguments/*!*/ args, string/*!*/ name) { BuildCallNoFlow(metaBuilder, args, name); metaBuilder.BuildControlFlow(args); } internal void BuildMethodMissingCall(MetaObjectBuilder/*!*/ metaBuilder, CallArguments/*!*/ args, string/*!*/ name) { BuildMethodMissingCallNoFlow(metaBuilder, args, name); metaBuilder.BuildControlFlow(args); } internal virtual void BuildSuperCallNoFlow(MetaObjectBuilder/*!*/ metaBuilder, CallArguments/*!*/ args, string/*!*/ name, RubyModule/*!*/ declaringModule) { BuildCallNoFlow(metaBuilder, args, name); } internal void BuildSuperCall(MetaObjectBuilder/*!*/ metaBuilder, CallArguments/*!*/ args, string/*!*/ name, RubyModule/*!*/ declaringModule) { BuildSuperCallNoFlow(metaBuilder, args, name, declaringModule); metaBuilder.BuildControlFlow(args); } #endregion } }
39.479751
164
0.607591
[ "MIT" ]
rifraf/IronRuby_Framework_4.7.2
Languages/Ruby/Ruby/Runtime/Calls/RubyMemberInfo.cs
12,673
C#
using EasyModular.Auth; using EasyModular.Utils; using Demo.Admin.Application; using Demo.Admin.Application.OrganizeService; using Demo.Admin.Domain; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Threading.Tasks; namespace Demo.Admin.Web { [Description("组织架构")] public class OrganizeController : ModuleController { private readonly IOrganizeService _service; public OrganizeController(ILoginInfo loginInfo,IOrganizeService OrganizeService) { _service = OrganizeService; } [HttpGet] [Description("查询")] public Task<IResultModel> Query([FromQuery]OrganizeQueryModel model) { return _service.Query(model); } [HttpPost] [Description("添加")] public Task<IResultModel> Add(OrganizeAddModel model) { return _service.Add(model); } [HttpGet] [Description("编辑")] public Task<IResultModel> Edit([BindRequired]string id) { return _service.Edit(id); } [HttpPost] [Description("更新")] public Task<IResultModel> Update(OrganizeUpdateModel model) { return _service.Update(model); } [HttpDelete] [Description("删除")] public Task<IResultModel> Delete([BindRequired]string id) { return _service.Delete(id); } [HttpPost] [Description("移动")] public Task<IResultModel> Move(OrganizeMoveModel model) { return _service.Move(model); } [HttpGet] [Description("组织架构树")] public Task<IResultModel> Tree() { return _service.GetTree(); } } }
24.125
89
0.612435
[ "MIT" ]
doordie1991/EasyModular
simple/01_Admin/Demo.Admin.Web/Controllers/OrganizeController.cs
1,972
C#
using System; using System.Collections.Generic; using System.Text; using ProtocolSharp.Types; namespace ProtocolSharp.Entities { public enum BoatType { Oak = 0, Spruce = 1, Birch = 2, Jungle = 3, Acacia = 4, DarkOak = 5 } }
13.388889
33
0.684647
[ "MIT" ]
CopperPenguin96/Redstone
ProtocolSharp/Entities/BoatType.cs
243
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // ANTLR Version: 4.7.2 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // Generated from FilterExpressionDsl.g4 by ANTLR 4.7.2 // Unreachable code detected #pragma warning disable 0162 // The variable '...' is assigned but its value is never used #pragma warning disable 0219 // Missing XML comment for publicly visible type or member '...' #pragma warning disable 1591 // Ambiguous reference in cref attribute #pragma warning disable 419 using System; using System.IO; using System.Text; using System.Diagnostics; using System.Collections.Generic; using Antlr4.Runtime; using Antlr4.Runtime.Atn; using Antlr4.Runtime.Misc; using Antlr4.Runtime.Tree; using DFA = Antlr4.Runtime.Dfa.DFA; [System.CodeDom.Compiler.GeneratedCode("ANTLR", "4.7.2")] [System.CLSCompliant(false)] public partial class FilterExpressionDslParser : Parser { protected static DFA[] decisionToDFA; protected static PredictionContextCache sharedContextCache = new PredictionContextCache(); public const int GreaterThan=1, GreaterThanEqual=2, LessThan=3, LessThanEqual=4, Equal=5, Or=6, And=7, IN=8, OpenParen=9, CloseParen=10, VARIABLE=11, NUMBER=12, STRING=13, WHITESPACE=14; public const int RULE_expr = 0, RULE_booleanOperator = 1, RULE_operator = 2, RULE_operand = 3; public static readonly string[] ruleNames = { "expr", "booleanOperator", "operator", "operand" }; private static readonly string[] _LiteralNames = { null, "'>'", "'>='", "'<'", "'<='", "'='", null, null, "'in'", "'('", "')'" }; private static readonly string[] _SymbolicNames = { null, "GreaterThan", "GreaterThanEqual", "LessThan", "LessThanEqual", "Equal", "Or", "And", "IN", "OpenParen", "CloseParen", "VARIABLE", "NUMBER", "STRING", "WHITESPACE" }; public static readonly IVocabulary DefaultVocabulary = new Vocabulary(_LiteralNames, _SymbolicNames); [NotNull] public override IVocabulary Vocabulary { get { return DefaultVocabulary; } } public override string GrammarFileName { get { return "FilterExpressionDsl.g4"; } } public override string[] RuleNames { get { return ruleNames; } } public override string SerializedAtn { get { return new string(_serializedATN); } } static FilterExpressionDslParser() { decisionToDFA = new DFA[_ATN.NumberOfDecisions]; for (int i = 0; i < _ATN.NumberOfDecisions; i++) { decisionToDFA[i] = new DFA(_ATN.GetDecisionState(i), i); } } public FilterExpressionDslParser(ITokenStream input) : this(input, Console.Out, Console.Error) { } public FilterExpressionDslParser(ITokenStream input, TextWriter output, TextWriter errorOutput) : base(input, output, errorOutput) { Interpreter = new ParserATNSimulator(this, _ATN, decisionToDFA, sharedContextCache); } public partial class ExprContext : ParserRuleContext { public ITerminalNode OpenParen() { return GetToken(FilterExpressionDslParser.OpenParen, 0); } public ExprContext[] expr() { return GetRuleContexts<ExprContext>(); } public ExprContext expr(int i) { return GetRuleContext<ExprContext>(i); } public ITerminalNode CloseParen() { return GetToken(FilterExpressionDslParser.CloseParen, 0); } public OperandContext[] operand() { return GetRuleContexts<OperandContext>(); } public OperandContext operand(int i) { return GetRuleContext<OperandContext>(i); } public OperatorContext @operator() { return GetRuleContext<OperatorContext>(0); } public BooleanOperatorContext booleanOperator() { return GetRuleContext<BooleanOperatorContext>(0); } public ExprContext(ParserRuleContext parent, int invokingState) : base(parent, invokingState) { } public override int RuleIndex { get { return RULE_expr; } } public override TResult Accept<TResult>(IParseTreeVisitor<TResult> visitor) { IFilterExpressionDslVisitor<TResult> typedVisitor = visitor as IFilterExpressionDslVisitor<TResult>; if (typedVisitor != null) return typedVisitor.VisitExpr(this); else return visitor.VisitChildren(this); } } [RuleVersion(0)] public ExprContext expr() { return expr(0); } private ExprContext expr(int _p) { ParserRuleContext _parentctx = Context; int _parentState = State; ExprContext _localctx = new ExprContext(Context, _parentState); ExprContext _prevctx = _localctx; int _startState = 0; EnterRecursionRule(_localctx, 0, RULE_expr, _p); try { int _alt; EnterOuterAlt(_localctx, 1); { State = 17; ErrorHandler.Sync(this); switch (TokenStream.LA(1)) { case OpenParen: { State = 9; Match(OpenParen); State = 10; expr(0); State = 11; Match(CloseParen); } break; case VARIABLE: case NUMBER: case STRING: { State = 13; operand(); State = 14; @operator(); State = 15; operand(); } break; default: throw new NoViableAltException(this); } Context.Stop = TokenStream.LT(-1); State = 25; ErrorHandler.Sync(this); _alt = Interpreter.AdaptivePredict(TokenStream,1,Context); while ( _alt!=2 && _alt!=global::Antlr4.Runtime.Atn.ATN.INVALID_ALT_NUMBER ) { if ( _alt==1 ) { if ( ParseListeners!=null ) TriggerExitRuleEvent(); _prevctx = _localctx; { { _localctx = new ExprContext(_parentctx, _parentState); PushNewRecursionContext(_localctx, _startState, RULE_expr); State = 19; if (!(Precpred(Context, 3))) throw new FailedPredicateException(this, "Precpred(Context, 3)"); State = 20; booleanOperator(); State = 21; expr(4); } } } State = 27; ErrorHandler.Sync(this); _alt = Interpreter.AdaptivePredict(TokenStream,1,Context); } } } catch (RecognitionException re) { _localctx.exception = re; ErrorHandler.ReportError(this, re); ErrorHandler.Recover(this, re); } finally { UnrollRecursionContexts(_parentctx); } return _localctx; } public partial class BooleanOperatorContext : ParserRuleContext { public ITerminalNode And() { return GetToken(FilterExpressionDslParser.And, 0); } public ITerminalNode Or() { return GetToken(FilterExpressionDslParser.Or, 0); } public BooleanOperatorContext(ParserRuleContext parent, int invokingState) : base(parent, invokingState) { } public override int RuleIndex { get { return RULE_booleanOperator; } } public override TResult Accept<TResult>(IParseTreeVisitor<TResult> visitor) { IFilterExpressionDslVisitor<TResult> typedVisitor = visitor as IFilterExpressionDslVisitor<TResult>; if (typedVisitor != null) return typedVisitor.VisitBooleanOperator(this); else return visitor.VisitChildren(this); } } [RuleVersion(0)] public BooleanOperatorContext booleanOperator() { BooleanOperatorContext _localctx = new BooleanOperatorContext(Context, State); EnterRule(_localctx, 2, RULE_booleanOperator); int _la; try { EnterOuterAlt(_localctx, 1); { State = 28; _la = TokenStream.LA(1); if ( !(_la==Or || _la==And) ) { ErrorHandler.RecoverInline(this); } else { ErrorHandler.ReportMatch(this); Consume(); } } } catch (RecognitionException re) { _localctx.exception = re; ErrorHandler.ReportError(this, re); ErrorHandler.Recover(this, re); } finally { ExitRule(); } return _localctx; } public partial class OperatorContext : ParserRuleContext { public ITerminalNode GreaterThan() { return GetToken(FilterExpressionDslParser.GreaterThan, 0); } public ITerminalNode GreaterThanEqual() { return GetToken(FilterExpressionDslParser.GreaterThanEqual, 0); } public ITerminalNode LessThan() { return GetToken(FilterExpressionDslParser.LessThan, 0); } public ITerminalNode LessThanEqual() { return GetToken(FilterExpressionDslParser.LessThanEqual, 0); } public ITerminalNode Equal() { return GetToken(FilterExpressionDslParser.Equal, 0); } public OperatorContext(ParserRuleContext parent, int invokingState) : base(parent, invokingState) { } public override int RuleIndex { get { return RULE_operator; } } public override TResult Accept<TResult>(IParseTreeVisitor<TResult> visitor) { IFilterExpressionDslVisitor<TResult> typedVisitor = visitor as IFilterExpressionDslVisitor<TResult>; if (typedVisitor != null) return typedVisitor.VisitOperator(this); else return visitor.VisitChildren(this); } } [RuleVersion(0)] public OperatorContext @operator() { OperatorContext _localctx = new OperatorContext(Context, State); EnterRule(_localctx, 4, RULE_operator); int _la; try { EnterOuterAlt(_localctx, 1); { State = 30; _la = TokenStream.LA(1); if ( !((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << GreaterThan) | (1L << GreaterThanEqual) | (1L << LessThan) | (1L << LessThanEqual) | (1L << Equal))) != 0)) ) { ErrorHandler.RecoverInline(this); } else { ErrorHandler.ReportMatch(this); Consume(); } } } catch (RecognitionException re) { _localctx.exception = re; ErrorHandler.ReportError(this, re); ErrorHandler.Recover(this, re); } finally { ExitRule(); } return _localctx; } public partial class OperandContext : ParserRuleContext { public ITerminalNode STRING() { return GetToken(FilterExpressionDslParser.STRING, 0); } public ITerminalNode NUMBER() { return GetToken(FilterExpressionDslParser.NUMBER, 0); } public ITerminalNode VARIABLE() { return GetToken(FilterExpressionDslParser.VARIABLE, 0); } public OperandContext(ParserRuleContext parent, int invokingState) : base(parent, invokingState) { } public override int RuleIndex { get { return RULE_operand; } } public override TResult Accept<TResult>(IParseTreeVisitor<TResult> visitor) { IFilterExpressionDslVisitor<TResult> typedVisitor = visitor as IFilterExpressionDslVisitor<TResult>; if (typedVisitor != null) return typedVisitor.VisitOperand(this); else return visitor.VisitChildren(this); } } [RuleVersion(0)] public OperandContext operand() { OperandContext _localctx = new OperandContext(Context, State); EnterRule(_localctx, 6, RULE_operand); int _la; try { EnterOuterAlt(_localctx, 1); { State = 32; _la = TokenStream.LA(1); if ( !((((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << VARIABLE) | (1L << NUMBER) | (1L << STRING))) != 0)) ) { ErrorHandler.RecoverInline(this); } else { ErrorHandler.ReportMatch(this); Consume(); } } } catch (RecognitionException re) { _localctx.exception = re; ErrorHandler.ReportError(this, re); ErrorHandler.Recover(this, re); } finally { ExitRule(); } return _localctx; } public override bool Sempred(RuleContext _localctx, int ruleIndex, int predIndex) { switch (ruleIndex) { case 0: return expr_sempred((ExprContext)_localctx, predIndex); } return true; } private bool expr_sempred(ExprContext _localctx, int predIndex) { switch (predIndex) { case 0: return Precpred(Context, 3); } return true; } private static char[] _serializedATN = { '\x3', '\x608B', '\xA72A', '\x8133', '\xB9ED', '\x417C', '\x3BE7', '\x7786', '\x5964', '\x3', '\x10', '%', '\x4', '\x2', '\t', '\x2', '\x4', '\x3', '\t', '\x3', '\x4', '\x4', '\t', '\x4', '\x4', '\x5', '\t', '\x5', '\x3', '\x2', '\x3', '\x2', '\x3', '\x2', '\x3', '\x2', '\x3', '\x2', '\x3', '\x2', '\x3', '\x2', '\x3', '\x2', '\x3', '\x2', '\x5', '\x2', '\x14', '\n', '\x2', '\x3', '\x2', '\x3', '\x2', '\x3', '\x2', '\x3', '\x2', '\a', '\x2', '\x1A', '\n', '\x2', '\f', '\x2', '\xE', '\x2', '\x1D', '\v', '\x2', '\x3', '\x3', '\x3', '\x3', '\x3', '\x4', '\x3', '\x4', '\x3', '\x5', '\x3', '\x5', '\x3', '\x5', '\x2', '\x3', '\x2', '\x6', '\x2', '\x4', '\x6', '\b', '\x2', '\x5', '\x3', '\x2', '\b', '\t', '\x3', '\x2', '\x3', '\a', '\x3', '\x2', '\r', '\xF', '\x2', '\"', '\x2', '\x13', '\x3', '\x2', '\x2', '\x2', '\x4', '\x1E', '\x3', '\x2', '\x2', '\x2', '\x6', ' ', '\x3', '\x2', '\x2', '\x2', '\b', '\"', '\x3', '\x2', '\x2', '\x2', '\n', '\v', '\b', '\x2', '\x1', '\x2', '\v', '\f', '\a', '\v', '\x2', '\x2', '\f', '\r', '\x5', '\x2', '\x2', '\x2', '\r', '\xE', '\a', '\f', '\x2', '\x2', '\xE', '\x14', '\x3', '\x2', '\x2', '\x2', '\xF', '\x10', '\x5', '\b', '\x5', '\x2', '\x10', '\x11', '\x5', '\x6', '\x4', '\x2', '\x11', '\x12', '\x5', '\b', '\x5', '\x2', '\x12', '\x14', '\x3', '\x2', '\x2', '\x2', '\x13', '\n', '\x3', '\x2', '\x2', '\x2', '\x13', '\xF', '\x3', '\x2', '\x2', '\x2', '\x14', '\x1B', '\x3', '\x2', '\x2', '\x2', '\x15', '\x16', '\f', '\x5', '\x2', '\x2', '\x16', '\x17', '\x5', '\x4', '\x3', '\x2', '\x17', '\x18', '\x5', '\x2', '\x2', '\x6', '\x18', '\x1A', '\x3', '\x2', '\x2', '\x2', '\x19', '\x15', '\x3', '\x2', '\x2', '\x2', '\x1A', '\x1D', '\x3', '\x2', '\x2', '\x2', '\x1B', '\x19', '\x3', '\x2', '\x2', '\x2', '\x1B', '\x1C', '\x3', '\x2', '\x2', '\x2', '\x1C', '\x3', '\x3', '\x2', '\x2', '\x2', '\x1D', '\x1B', '\x3', '\x2', '\x2', '\x2', '\x1E', '\x1F', '\t', '\x2', '\x2', '\x2', '\x1F', '\x5', '\x3', '\x2', '\x2', '\x2', ' ', '!', '\t', '\x3', '\x2', '\x2', '!', '\a', '\x3', '\x2', '\x2', '\x2', '\"', '#', '\t', '\x4', '\x2', '\x2', '#', '\t', '\x3', '\x2', '\x2', '\x2', '\x4', '\x13', '\x1B', }; public static readonly ATN _ATN = new ATNDeserializer().Deserialize(_serializedATN); }
34.997416
169
0.630759
[ "MIT" ]
andy-williams/FilterExpressionParser
src/FilterExpressionParser/Generated/FilterExpressionDslParser.cs
13,544
C#
using System.Threading.Tasks; using Bittrex.Net.Interfaces; using Bittrex.Net.Objects; using CryptoExchange.Net.Objects; using CryptoExchange.Net.OrderBook; using CryptoExchange.Net.Sockets; namespace Bittrex.Net { /// <summary> /// Order book implementation /// </summary> public class BittrexSymbolOrderBook: SymbolOrderBook { private readonly IBittrexSocketClient socketClient; /// <summary> /// Create a new order book instance /// </summary> /// <param name="symbol">The symbol the order book is for</param> /// <param name="options">Options for the order book</param> public BittrexSymbolOrderBook(string symbol, BittrexOrderBookOptions? options = null) : base(symbol, options ?? new BittrexOrderBookOptions()) { symbol.ValidateBittrexSymbol(); socketClient = options?.SocketClient ?? new BittrexSocketClient(); } /// <inheritdoc /> protected override async Task<CallResult<UpdateSubscription>> DoStart() { var subResult = await socketClient.SubscribeToOrderBookUpdatesAsync(Symbol, HandleUpdate).ConfigureAwait(false); if (!subResult.Success) return new CallResult<UpdateSubscription>(null, subResult.Error); Status = OrderBookStatus.Syncing; var queryResult = await socketClient.GetOrderBookAsync(Symbol).ConfigureAwait(false); if (!queryResult.Success) { await socketClient.UnsubscribeAll().ConfigureAwait(false); return new CallResult<UpdateSubscription>(null, queryResult.Error); } SetInitialOrderBook(queryResult.Data.Nonce, queryResult.Data.Buys, queryResult.Data.Sells); return new CallResult<UpdateSubscription>(subResult.Data, null); } private void HandleUpdate(BittrexStreamOrderBookUpdate data) { UpdateOrderBook(data.Nonce, data.Buys, data.Sells); } /// <inheritdoc /> protected override async Task<CallResult<bool>> DoResync() { var queryResult = await socketClient.GetOrderBookAsync(Symbol).ConfigureAwait(false); if (!queryResult.Success) return new CallResult<bool>(false, queryResult.Error); SetInitialOrderBook(queryResult.Data.Nonce, queryResult.Data.Buys, queryResult.Data.Sells); return new CallResult<bool>(true, null); } /// <inheritdoc /> public override void Dispose() { processBuffer.Clear(); asks.Clear(); bids.Clear(); socketClient?.Dispose(); } } }
36.864865
150
0.634531
[ "MIT" ]
ridicoulous/Bittrex.Net
Bittrex.Net/BittrexSymbolOrderBook.cs
2,730
C#
// ***************************************************** // Copyright 2007, Charlie Poole // // Licensed under the Open Software License version 3.0 // ***************************************************** using System; using NUnit.Framework; using NUnit.Framework.Constraints; namespace NUnitLite.Tests { [TestFixture] class GreaterThanTest : ConstraintTestBase { public GreaterThanTest(string name) : base(name) { } protected override void SetUp() { Matcher = new GreaterThanConstraint(5); GoodValues = new object[] { 6 }; BadValues = new object[] { 4, 5 }; Description = "greater than 5"; } } [TestFixture] class GreaterThanOrEqualTest : ConstraintTestBase { public GreaterThanOrEqualTest(string name) : base(name) { } protected override void SetUp() { Matcher = new GreaterThanOrEqualConstraint(5); GoodValues = new object[] { 6, 5 }; BadValues = new object[] { 4 }; Description = "greater than or equal to 5"; } } [TestFixture] class LessThanTest : ConstraintTestBase { public LessThanTest(string name) : base(name) { } protected override void SetUp() { Matcher = new LessThanConstraint(5); GoodValues = new object[] { 4 }; BadValues = new object[] { 6, 5 }; Description = "less than 5"; } } [TestFixture] class LessThanOrEqualTest : ConstraintTestBase { public LessThanOrEqualTest(string name) : base(name) { } protected override void SetUp() { Matcher = new LessThanOrEqualConstraint(5); GoodValues = new object[] { 4 , 5 }; BadValues = new object[] { 6 }; Description = "less than or equal to 5"; } } }
27.594203
67
0.537815
[ "MIT" ]
redarrowlabs/pubnub-c-sharp
pocketpc/PubNub-Messaging/NUnitLite-0.2.0/src/NUnitLiteTests/Constraints/ComparisonConstraintTests.cs
1,904
C#
// Licensed under the Apache 2.0 License. See LICENSE.txt in the project root for more information. using ElasticLinq.Logging; using ElasticLinq.Mapping; using ElasticLinq.Request; using ElasticLinq.Retry; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace ElasticLinq.Test { /// <summary> /// Provides an IElasticContext that can be used by unit tests. /// </summary> public class TestableElasticContext : IElasticContext { readonly Dictionary<Type, object> data = new Dictionary<Type, object>(); /// <summary> /// Initializes a new instance of the <see cref="TestableElasticContext"/> class. /// </summary> /// <param name="mapping">The <see cref="IElasticMapping"/> used to define mapping between the document and object.</param> /// <param name="log">The <see cref="ILog"/> instance to receive logging information.</param> /// <param name="maxAttempts">Maximum number of attempts to try before failing.</param> /// <param name="timeout">How long to wait before failing a request.</param> public TestableElasticContext(IElasticMapping mapping = null, ILog log = null, int maxAttempts = 1, TimeSpan timeout = default(TimeSpan)) { Connection = new ElasticConnection(new Uri("http://localhost/"), timeout: timeout); Mapping = mapping ?? new ElasticMapping(true,true,true); Provider = new TestableElasticQueryProvider(this); Requests = new List<QueryInfo>(); Log = log ?? NullLog.Instance; RetryPolicy = new RetryPolicy(Log, 0, maxAttempts, NullDelay.Instance); } /// <summary> /// Specifies the connection to the Elasticsearch server. /// </summary> public ElasticConnection Connection { get; private set; } /// <summary> /// The logging mechanism for diagnostics information. /// </summary> public ILog Log { get; } /// <summary> /// The mapping to describe how objects and their properties are mapped to Elasticsearch. /// </summary> public IElasticMapping Mapping { get; private set; } /// <summary> /// Access the underlying <see cref="TestableElasticQueryProvider" />. /// </summary> public TestableElasticQueryProvider Provider { get; private set; } /// <summary> /// Access the <see cref="QueryInfo"/> for the request made. /// </summary> public List<QueryInfo> Requests { get; private set; } /// <summary> /// The retry policy for handling networking issues. /// </summary> public IRetryPolicy RetryPolicy { get; private set; } /// <summary> /// The in-memory data to be used for results when performing queries. /// </summary> /// <typeparam name="T">Type of in-memory data to retrieve.</typeparam> /// <returns>The in-memory data of the given type that will be used to test queries against.</returns> public IEnumerable<T> Data<T>() { object result; if (!data.TryGetValue(typeof(T), out result)) result = Enumerable.Empty<T>(); return (IEnumerable<T>)result; } /// <summary> /// Set the in-memory data for the type given. /// </summary> /// <typeparam name="T">Type of in-memory data to store.</typeparam> /// <param name="values">The objects to use when testing queries against this type.</param> public void SetData<T>(IEnumerable<T> values) { data[typeof(T)] = values.ToList(); } /// <summary> /// Set the in-memory data for the type given. /// </summary> /// <typeparam name="T">Type of in-memory data to store.</typeparam> /// <param name="values">The objects to use when testing queries against this type.</param> public void SetData<T>(params T[] values) { SetData((IEnumerable<T>)values); } /// <inheritdoc/> public IQueryable<T> Query<T>() { return new TestableElasticQuery<T>(this); } ///<inheritdoc/> public IReadOnlyDictionary<TAggregate, int> ReadIndex<T, TAggregate>(Expression<Func<T, TAggregate>> fieldExpression) { throw new NotImplementedException(); } } }
39.418803
131
0.593018
[ "Apache-2.0" ]
tecan/ElasticLINQ
Source/ElasticLINQ/Test/TestableElasticContext.cs
4,614
C#
// Copyright (c) Kris Penner. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using KodeAid; using Microsoft.Extensions.Logging; namespace MultiTenancyServer.Stores.InMemory { /// <summary> /// Represents a new instance of a in-memory store for the specified tenant type. /// </summary> /// <typeparam name="TTenant">The type representing a tenant.</typeparam> /// <typeparam name="TKey">The type of the primary key for a tenant.</typeparam> public class InMemoryTenantStore<TTenant, TKey> : TenantStoreBase<TTenant, TKey>, IQueryableTenantStore<TTenant> where TTenant : TenancyTenant<TKey> where TKey : IEquatable<TKey> { private readonly List<TTenant> _tenants = new List<TTenant>(); /// <summary> /// Creates a new instance. /// </summary> /// <param name="describer">The <see cref="TenancyErrorDescriber"/> used to describe store errors.</param> public InMemoryTenantStore(IEnumerable<TTenant> tenants, TenancyErrorDescriber describer, ILogger<InMemoryTenantStore<TTenant, TKey>> logger) : base(describer, logger) { _tenants.AddRange(tenants ?? throw new ArgumentNullException(nameof(tenants))); } /// <summary> /// A navigation property for the tenants the store contains. /// </summary> public override IQueryable<TTenant> Tenants { get { return _tenants.AsQueryable(); } } /// <summary> /// Creates the specified <paramref name="tenant"/> in the tenant store. /// </summary> /// <param name="tenant">The tenant to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="TenancyResult"/> of the creation operation.</returns> public override Task<TenancyResult> CreateAsync(TTenant tenant, CancellationToken cancellationToken = default) { ArgCheck.NotNull(nameof(tenant), tenant); cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); _tenants.Add(tenant); Logger.LogDebug($"Tenant ID '{{{nameof(TenancyTenant.Id)}}}' created.", tenant.Id); return Task.FromResult(TenancyResult.Success); } /// <summary> /// Updates the specified <paramref name="tenant"/> in the tenant store. /// </summary> /// <param name="tenant">The tenant to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="TenancyResult"/> of the update operation.</returns> public override Task<TenancyResult> UpdateAsync(TTenant tenant, CancellationToken cancellationToken = default) { ArgCheck.NotNull(nameof(tenant), tenant); cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); Logger.LogDebug($"Tenant ID '{{{nameof(TenancyTenant.Id)}}}' updated.", tenant.Id); return Task.FromResult(TenancyResult.Success); } /// <summary> /// Deletes the specified <paramref name="tenant"/> from the tenant store. /// </summary> /// <param name="tenant">The tenant to delete.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="TenancyResult"/> of the update operation.</returns> public override Task<TenancyResult> DeleteAsync(TTenant tenant, CancellationToken cancellationToken = default) { ArgCheck.NotNull(nameof(tenant), tenant); cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); _tenants.Remove(tenant); Logger.LogDebug($"Tenant ID '{{{nameof(TenancyTenant.Id)}}}' deleted.", tenant.Id); return Task.FromResult(TenancyResult.Success); } /// <summary> /// Finds and returns a tenant, if any, who has the specified <paramref name="tenantId"/>. /// </summary> /// <param name="tenantId">The tenant ID to search for.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the tenant matching the specified <paramref name="tenantId"/> if it exists. /// </returns> public override async ValueTask<TTenant> FindByIdAsync(string tenantId, CancellationToken cancellationToken = default) { ArgCheck.NotNull(nameof(tenantId), tenantId); cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); var tenant = await FindTenantAsync(ConvertIdFromString(tenantId), cancellationToken); if (tenant == null) { Logger.LogDebug($"Tenant ID '{{{nameof(TenancyTenant.Id)}}}' not found.", tenantId); } else { Logger.LogDebug($"Tenant ID '{{{nameof(TenancyTenant.Id)}}}' found.", tenantId); } return tenant; } /// <summary> /// Finds and returns a tenant, if any, who has the specified normalized canonical name. /// </summary> /// <param name="normalizedCanonicalName">The normalized canonical name to search for.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the tenant matching the specified <paramref name="normalizedCanonicalName"/> if it exists. /// </returns> public override ValueTask<TTenant> FindByCanonicalNameAsync(string normalizedCanonicalName, CancellationToken cancellationToken = default) { ArgCheck.NotNull(nameof(normalizedCanonicalName), normalizedCanonicalName); cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); var tenant = _tenants.SingleOrDefault(t => t.NormalizedCanonicalName == normalizedCanonicalName); if (tenant == null) { Logger.LogDebug($"Tenant canonical name '{{{nameof(TenancyTenant.CanonicalName)}}}' not found.", normalizedCanonicalName); } else { Logger.LogDebug($"Tenant canonical name '{{{nameof(TenancyTenant.CanonicalName)}}}' found.", normalizedCanonicalName); } return new ValueTask<TTenant>(tenant); } /// <summary> /// Return a tenant with the matching tenantId if it exists. /// </summary> /// <param name="tenantId">The tenant's id.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The tenant if it exists.</returns> protected override ValueTask<TTenant> FindTenantAsync(TKey tenantId, CancellationToken cancellationToken) { if (tenantId == null) { return default; } return new ValueTask<TTenant>(_tenants.SingleOrDefault(t => t.Id.Equals(tenantId))); } } }
47.674419
180
0.643659
[ "Apache-2.0" ]
MultiTenancyServer/MultiTenancyServer
src/Stores/InMemoryTenantStore.cs
8,202
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("InterfaceUsuario.Mvc5.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("InterfaceUsuario.Mvc5.Tests")] [assembly: AssemblyCopyright("Copyright © Microsoft 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("dabc7243-d8bb-4517-955d-a969c4bff475")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.888889
84
0.757143
[ "MIT" ]
gabrielsimas/SistemasExemplo
DDD/ControleLivros/InterfaceUsuario.Mvc5.Tests/Properties/AssemblyInfo.cs
1,403
C#
namespace Octokit.GraphQL.Model { using System; using System.Linq; using System.Linq.Expressions; using Octokit.GraphQL.Core; using Octokit.GraphQL.Core.Builders; /// <summary> /// The results of a search. /// </summary> public class SearchResultItem : QueryableValue<SearchResultItem>, IUnion { internal SearchResultItem(Expression expression) : base(expression) { } public TResult Switch<TResult>(Expression<Func<Selector<TResult>, Selector<TResult>>> select) => default; public class Selector<T> { /// <summary> /// An Issue is a place to discuss ideas, enhancements, tasks, and bugs for a project. /// </summary> public Selector<T> Issue(Func<Issue, T> selector) => default; /// <summary> /// A repository pull request. /// </summary> public Selector<T> PullRequest(Func<PullRequest, T> selector) => default; /// <summary> /// A repository contains the content for a project. /// </summary> public Selector<T> Repository(Func<Repository, T> selector) => default; /// <summary> /// A user is an individual's account on GitHub that owns repositories and can make new content. /// </summary> public Selector<T> User(Func<User, T> selector) => default; /// <summary> /// An account on GitHub, with one or more owners, that has repositories, members and teams. /// </summary> public Selector<T> Organization(Func<Organization, T> selector) => default; /// <summary> /// A listing in the GitHub integration marketplace. /// </summary> public Selector<T> MarketplaceListing(Func<MarketplaceListing, T> selector) => default; } internal static SearchResultItem Create(Expression expression) { return new SearchResultItem(expression); } } }
35.637931
113
0.584422
[ "MIT" ]
ChilliCream/octokit.graphql.net
Octokit.GraphQL/Model/SearchResultItem.cs
2,067
C#
using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using AutoMapper; using MediatR; using Microsoft.Extensions.Logging; using ServiceBusDriver.Core.Components.Search; using ServiceBusDriver.Core.Models.Features.Search; using ServiceBusDriver.Server.Services.Validations; using ServiceBusDriver.Shared.Features.Message; namespace ServiceBusDriver.Server.Features.Message.Search { public class SearchHandler : IRequestHandler<SearchRequest, List<MessageResponseDto>> { private readonly ISearchService _searchService; private readonly IMapper _mapper; private readonly IDbFetchHelper _dbFetchHelper; private readonly ILogger<SearchHandler> _logger; public SearchHandler(ISearchService searchService, ILogger<SearchHandler> logger, IMapper mapper, IDbFetchHelper dbFetchHelper) { _searchService = searchService; _logger = logger; _mapper = mapper; _dbFetchHelper = dbFetchHelper; } public async Task<List<MessageResponseDto>> Handle(SearchRequest request, CancellationToken cancellationToken) { _logger.LogTrace("Start {0}", nameof(Handle)); await _dbFetchHelper.BelongToCurrentUser(request.InstanceId, cancellationToken); var searchCommand = MapToSearchCommand(request); var result = await _searchService.Search(searchCommand, cancellationToken); var response = _mapper.Map<List<MessageResponseDto>>(result); _logger.LogTrace("Finish {0}", nameof(Handle)); return response; } private SearchCommand MapToSearchCommand(SearchRequest request) { var searchCommand = new SearchCommand { InstanceId = request.InstanceId, TopicName = request.TopicName, SubscriptionName = request.SubscriptionName, SearchDeadLetter = request.SearchDeadLetter, KeyPath = request.KeyPath, Value = request.Value, MatchType = request.MatchType, ContentType = request.ContentType, PrefetchCount = request.PrefetchCount, MaxMessages = 0 }; return searchCommand; } } }
36.53125
135
0.667665
[ "MIT" ]
beaudeanadams/ServiceBusDriver
Server/Features/Message/Search/SearchHandler.cs
2,340
C#
/* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.IO; using System.Linq; using System.Reflection; using ASC.Common.Logging; using ASC.Core; using ASC.Data.Backup.Tasks; using CommandLine; namespace ASC.Data.Backup.Console { class Program { class Options { [OptionArray('t', "tenants", HelpText = "Identifiers of portals to backup")] public int[] TenantIds { get; set; } [Option('c', "config", HelpText = "Path to Teamlab configuration file")] public string WebConfigPath { get; set; } [Option('d', "dir", HelpText = "Folder in which backup files are stored")] public string BackupDirectory { get; set; } [Option('r', "restore", HelpText = "File to restore backup.")] public string Restore { get; set; } } static void Main(string[] args) { System.Diagnostics.Debugger.Launch(); var options = new Options(); Parser.Default.ParseArgumentsStrict(args, options); if (!string.IsNullOrWhiteSpace(options.Restore)) { var webconfig = ToAbsolute(options.WebConfigPath ?? Path.Combine("..", "..", "WebStudio", "Web.config")); var backupfile = ToAbsolute(options.Restore); var backuper = new BackupManager(backupfile, webconfig); backuper.ProgressChanged += (s, e) => { var pos = System.Console.CursorTop; System.Console.SetCursorPosition(0, System.Console.CursorTop); System.Console.Write(new string(' ', System.Console.WindowWidth)); System.Console.SetCursorPosition(0, pos); System.Console.Write("{0}... {1}%", e.Status, e.Progress); }; System.Console.WriteLine(); backuper.Load(); System.Console.WriteLine(); } else { options.WebConfigPath = ToAbsolute(options.WebConfigPath); options.BackupDirectory = ToAbsolute(options.BackupDirectory); var log = LogManager.GetLogger("ASC"); if (!Path.HasExtension(options.WebConfigPath)) { options.WebConfigPath = Path.Combine(options.WebConfigPath, "Web.config"); } if (!File.Exists(options.WebConfigPath)) { log.Error("Configuration file not found."); return; } if (!Directory.Exists(options.BackupDirectory)) { Directory.CreateDirectory(options.BackupDirectory); } foreach (var tenant in options.TenantIds.Select(tenantId => CoreContext.TenantManager.GetTenant(tenantId)).Where(tenant => tenant != null)) { var backupFileName = string.Format("{0}-{1:yyyyMMddHHmmss}.zip", tenant.TenantAlias, DateTime.UtcNow); var backupFilePath = Path.Combine(options.BackupDirectory, backupFileName); var task = new BackupPortalTask(log, tenant.TenantId, options.WebConfigPath, backupFilePath, 100); task.RunJob(); } } } private static string ToAbsolute(string basePath) { if (!Path.IsPathRooted(basePath)) { basePath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), basePath); } return basePath; } } }
38.0625
155
0.572836
[ "Apache-2.0" ]
Ektai-Solution-Pty-Ltd/CommunityServer
common/ASC.Data.Backup.Console/Program.cs
4,263
C#
using System.Net; using System.Web.Mvc; namespace WebForLink.Web.Areas.ConfiguracaoInicial.Controllers { [AllowAnonymous] public class VendorListController : Controller { // GET: ConfiguracaoInicial/VendorList public ActionResult Index() { return View(); } // GET: ConfiguracaoInicial/VendorList public ActionResult ConvidarFornecedor(string cnpj) { return View(); } // GET: ConfiguracaoInicial/VendorList /// <summary> /// 02.03 Enviar e-mail informando o motivo do convite e link para ele acessar o Webforlink, conhecer o produto e realizar o cadastro de sua Ficha Cadastral e o upload dos documentos solicitados. /// </summary> /// <param name="cnpj"></param> /// <returns></returns> public ActionResult EnviarEmailConvite(string cnpj) { return View(); } [HttpGet] public JsonResult RetornarFichaCadastral(string cnpj, string codCliente) { var resultado = ""; if (string.IsNullOrEmpty(cnpj)) resultado = "problema na string"; Response.StatusCode = (int)HttpStatusCode.BadRequest; return Json(new { mensagem = resultado }, JsonRequestBehavior.AllowGet); //Response.StatusCode = (int)HttpStatusCode.OK; } } }
32.790698
203
0.608511
[ "MIT" ]
nelson1987/ProjetoPadraoTDD
Code/1_Presentation/WebForLink.Web/Areas/Administracao/Controllers/VendorListController.cs
1,412
C#
namespace BeUtl; [Flags] public enum PropertyObservability { None = 0b0000, Changed = 0b0001, DoNotNotifyLogicalTree = 0b0011, }
14.3
36
0.706294
[ "MIT" ]
YiB-PC/BeUtl
src/BeUtl.Core/PropertyObservability.cs
145
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; namespace VBSourceEmitter { public interface ISourceEmitterOutput { void WriteLine(string str, bool fIndent); void WriteLine(string str); void Write(string str, bool fIndent); void Write(string str); void IncreaseIndent(); void DecreaseIndent(); /// <summary> /// Indicates whether anything has been written to the current line yet /// </summary> bool CurrentLineEmpty { get; } /// <summary> /// Invoked at the start of a new non-empty line, just before writing the indent /// </summary> event Action<ISourceEmitterOutput> LineStart; } }
28.310345
101
0.704019
[ "MIT" ]
Bhaskers-Blu-Org2/cci
SourceEmitters/VB/VBSourceEmitter/ISourceEmitterOutput.cs
821
C#
namespace Coevery.ContentManagement.Drivers { public class ContentLocation { public string Zone { get; set; } public string Position { get; set; } } }
29.166667
46
0.651429
[ "BSD-3-Clause" ]
Coevery/Coevery-Framework
src/Coevery/ContentManagement/Drivers/ContentLocation.cs
177
C#
using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using LoggerLibrary; using Xunit.Abstractions; using MonotonicContext = HpTimeStamps.MonotonicStampContext; using Duration = HpTimeStamps.Duration; [assembly: InternalsVisibleTo("Cjm.Templates.Test")] namespace SourceGeneratorUnitTests { using MonotonicStamp = HpTimeStamps.MonotonicTimeStamp<MonotonicContext>; using MonotonicSource = HpTimeStamps.MonotonicTimeStampUtil<MonotonicContext>; public static class AlternateLoggerSource { public static ICodeGenLogger CreateAlternateLogger(ITestOutputHelper helper) => AlternateLogger.CreateLogger(helper ?? throw new ArgumentNullException(nameof(helper))); public static void InjectAlternateLogger(ITestOutputHelper helper) { ICodeGenLogger? logger = null; try { if (_setOnce.TrySet()) { logger = AlternateLogger.CreateLogger(helper); CodeGenLogger.SupplyAlternateLoggerOrThrow(logger); } } catch (Exception ex) { Debug.WriteLine(ex); logger?.Dispose(); } } sealed class AlternateLogger : ICodeGenLogger, IWrap<ITestOutputHelper> { internal static ICodeGenLogger CreateLogger(ITestOutputHelper helper) { if (helper == null) throw new ArgumentNullException(nameof(helper)); AlternateLogger? ret = null; try { ret = new AlternateLogger(helper); ret._t.Start(ret._cts.Token); MonotonicStamp quitAfter = MonotonicSource.StampNow + Duration.FromSeconds(2); while (MonotonicSource.StampNow <= quitAfter && !ret._threadStart.IsSet) { Thread.Sleep(TimeSpan.FromMilliseconds(25)); } return ret; } catch (Exception) { ret?.Dispose(); throw; } } public bool IsGood => _threadStart.IsSet && !_threadEnd.IsSet && !_disposed.IsSet && !_faulted.IsSet; /// <inheritdoc /> public event EventHandler<MonotonicStampedEventArgs>? Faulted; /// <inheritdoc /> public event EventHandler<MonotonicStampedEventArgs>? ThreadStopped; public bool IsDisposed => _disposed.IsSet; /// <inheritdoc /> public ITestOutputHelper CurrentSetting => _helper; /// <inheritdoc /> [SuppressMessage("ReSharper", "ConstantNullCoalescingCondition")] public EntryExitLog CreateEel(string type, string method, string extraInfo) { return new EntryExitLog(type ?? "UNKNOWN TYPE", method ?? "UNKNOWN METHOD", extraInfo ?? "NO MESSAGE", this); } /// <inheritdoc /> public void Log(in LogMessage lm) { if (IsGood && !IsDisposed) { try { _logCollection.Add(lm); } catch { //eat it } } } /// <inheritdoc /> public void LogMessage(string message) { LogMessage lm = LoggerLibrary.LogMessage.CreateMessageLog(message); Log(in lm); } /// <inheritdoc /> public void LogError(string error) { LogMessage lm = LoggerLibrary.LogMessage.CreateErrorLog(error); Log(in lm); } /// <inheritdoc /> public void LogException(Exception error) { LogMessage lm = LoggerLibrary.LogMessage.CreateExceptionLog(error); Log(in lm); } public void Dispose() => Dispose(true); /// <inheritdoc /> public ITestOutputHelper Update(ITestOutputHelper value) { if (value == null) throw new ArgumentNullException(nameof(value)); if (IsDisposed) { throw new ObjectDisposedException(nameof(AlternateLogger), $"Illegal call to {nameof(Update)} method: object is disposed."); } return Interlocked.Exchange(ref _helper, value); } private void Dispose(bool disposing) { if (_disposed.TrySet() && disposing) { if (_threadStart.IsSet && !_threadEnd.IsSet) { _cts.Cancel(); } _t.Join(); _cts.Dispose(); _logCollection.Dispose(); _eventPump.Dispose(); } } private void ThreadLoop(object? ctObj) { try { if (ctObj is CancellationToken token) { _threadStart.TrySet(); while (true) { LogMessage dequeued = _logCollection.Take(token); Log(in dequeued, token); token.ThrowIfCancellationRequested(); } } } catch (OperationCanceledException) { } catch (Exception ex) { if (_faulted.TrySet()) { OnFaulted($"The logger has entered a faulted state and cannot be used. Exception: [{ex}]"); } } finally { if (_threadEnd.TrySet()) { OnThreadStopped("The logger just shut down."); } } } private void OnFaulted(string s) { MonotonicStampedEventArgs args = new MonotonicStampedEventArgs(s); bool doOnEventPump = _eventPump.IsGood; bool doOnThreadPool = !doOnEventPump; if (doOnEventPump) { try { _eventPump.RaiseEvent(DoIt); } catch { doOnThreadPool = true; } } if (doOnThreadPool) { Task.Run(DoIt); } void DoIt() => Faulted?.Invoke(this, args); } private void OnThreadStopped(string s) { MonotonicStampedEventArgs args = new MonotonicStampedEventArgs(s); bool doOnEventPump = _eventPump.IsGood; bool doOnThreadPool = !doOnEventPump; if (doOnEventPump) { try { _eventPump.RaiseEvent(DoIt); } catch { doOnThreadPool = true; } } if (doOnThreadPool) { Task.Run(DoIt); } void DoIt() => ThreadStopped?.Invoke(this, args); } private void Log(in LogMessage lm, CancellationToken token) { bool loggedIt = false; int currentLogAttempt = 1; string? text = Stringify(in lm); token.ThrowIfCancellationRequested(); while (!loggedIt && currentLogAttempt++ <= _maxLogAttempts && text != null) { try { WriteLine(text); loggedIt = true; } catch (OperationCanceledException) { throw; } catch (Exception) { Thread.Sleep(TimeSpan.FromMilliseconds(50)); token.ThrowIfCancellationRequested(); } } } private string? Stringify(in LogMessage lm) { try { return (lm.TypeOfLog) switch { LogType.EntryExit => lm.Message, LogType.Error => $"At {lm.EntryTime.ToString()}, the following error occurred: [{lm.Message}].", LogType.Exception => $"At {lm.EntryTime.ToString()}, an exception of type " + $"{lm.ReportedException?.GetType().Name ?? "UNKNOWN"} with " + $"message \"{lm.ReportedException?.Message ?? "NONE"}\" was thrown. " + $"Contents: [{lm.ReportedException?.ToString() ?? "NONE"}].", _ => $"At {lm.EntryTime.ToString()}, the following message was posted: [{lm.Message}]." }; } catch (OperationCanceledException) { throw; } catch { return null; } } private AlternateLogger(ITestOutputHelper helper) { _cts = new CancellationTokenSource(); _logCollection = new BlockingCollection<LogMessage>(new ConcurrentQueue<LogMessage>()); _t = new Thread(ThreadLoop) { Name = "LogThread", IsBackground = true, Priority = ThreadPriority.BelowNormal }; _eventPump = EventPumpFactorySource.FactoryInstance("LoggerEventPump"); _helper = helper ?? throw new ArgumentNullException(nameof(helper)); } private void WriteLine(string writeMe) { ITestOutputHelper toh = _helper; toh.WriteLine(writeMe); } private volatile ITestOutputHelper _helper; private readonly IEventPump _eventPump; private readonly int _maxLogAttempts = 3; private LocklessSetOnlyRefStr _disposed; private readonly CancellationTokenSource _cts; private readonly Thread _t; private LocklessSetOnlyRefStr _threadStart; private LocklessSetOnlyRefStr _threadEnd; private LocklessSetOnlyRefStr _faulted; private readonly BlockingCollection<LogMessage> _logCollection; } private static LocklessSetOnlyFlag _setOnce; } }
35.475155
120
0.464239
[ "MIT" ]
cpsusie/codegen-experiment
src/SourceGeneratorUnitTests/AlternateLogger.cs
11,425
C#
using System; using System.Threading.Tasks; using Discord.Commands; using WizBot.Modules.Administration.Services; using WizBot.Core.Common.TypeReaders; using Discord.WebSocket; using Microsoft.Extensions.DependencyInjection; namespace WizBot.Common.TypeReaders { public class GuildDateTimeTypeReader : WizBotTypeReader<GuildDateTime> { public GuildDateTimeTypeReader(DiscordSocketClient client, CommandService cmds) : base(client, cmds) { } public override Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services) { var gdt = Parse(services, context.Guild.Id, input); if(gdt == null) return Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "Input string is in an incorrect format.")); return Task.FromResult(TypeReaderResult.FromSuccess(gdt)); } public static GuildDateTime Parse(IServiceProvider services, ulong guildId, string input) { var _gts = services.GetService<GuildTimezoneService>(); if (!DateTime.TryParse(input, out var dt)) return null; var tz = _gts.GetTimeZoneOrUtc(guildId); return new GuildDateTime(tz, dt); } } public class GuildDateTime { public TimeZoneInfo Timezone { get; } public DateTime CurrentGuildTime { get; } public DateTime InputTime { get; } public DateTime InputTimeUtc { get; } private GuildDateTime() { } public GuildDateTime(TimeZoneInfo guildTimezone, DateTime inputTime) { var now = DateTime.UtcNow; Timezone = guildTimezone; CurrentGuildTime = TimeZoneInfo.ConvertTime(now, TimeZoneInfo.Utc, Timezone); InputTime = inputTime; InputTimeUtc = TimeZoneInfo.ConvertTime(inputTime, Timezone, TimeZoneInfo.Utc); } } }
34.350877
136
0.665986
[ "MIT" ]
fossabot/WizBot
WizBot.Core/Common/TypeReaders/GuildDateTimeTypeReader.cs
1,960
C#
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using StaticAssets; using System; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; namespace Authorization.Services { public class JWTDecryptor { public JWTSettings jwtOptions; private ILogger<JWTDecryptor> logger; public JWTDecryptor(JWTSettings options, ILogger<JWTDecryptor> logger) => (jwtOptions, this.logger) = (options, logger); public string? GetUsername(string token) { try { var signingKey = Encoding.UTF8.GetBytes(jwtOptions.SigningKey); var encKey = Encoding.UTF8.GetBytes(jwtOptions.EncryptionKey); var byteArray = new byte[32]; Array.Copy(encKey, byteArray, 32); var encSigningKey = new SymmetricSecurityKey(signingKey); var encEncKey = new SymmetricSecurityKey(byteArray); var handler = new JwtSecurityTokenHandler(); var claim = handler.ValidateToken(token, new TokenValidationParameters() { TokenDecryptionKey = encEncKey, IssuerSigningKey = encSigningKey, ValidAudience = jwtOptions.Issuer, ValidIssuer = jwtOptions.Issuer }, out SecurityToken securityToken); var username = claim.FindFirst(ClaimTypes.Email); return username?.Value; } catch (Exception e) { logger.LogError($"Invalid Jwt with error {e.Message}"); return null; } } } }
38.27907
187
0.636087
[ "MIT" ]
cryoelite/ChoicesRemake-Backend
ChoicesRemake/Authorization/Services/JWTDecryptor.cs
1,648
C#
// ************************************************************************************* // SCICHART® Copyright SciChart Ltd. 2011-2021. All rights reserved. // // Web: http://www.scichart.com // Support: support@scichart.com // Sales: sales@scichart.com // // SciTraderView.xaml.cs is part of the SCICHART® Examples. Permission is hereby granted // to modify, create derivative works, distribute and publish any part of this source // code whether for commercial, private or personal use. // // The SCICHART® examples are distributed in the hope that they will be useful, but // without any warranty. It is provided "AS IS" without warranty of any kind, either // expressed or implied. // ************************************************************************************* using System.Windows.Controls; namespace SciChart.Examples.Examples.SeeFeaturedApplication.SciTrader { public partial class SciTraderView : UserControl { public SciTraderView() { InitializeComponent(); } } }
38.703704
89
0.593301
[ "MIT" ]
SHAREVIEW/SciChart.Wpf.Examples
Examples/SciChart.Examples/Examples/SeeFeaturedApplication/SciTrader/SciTraderView.xaml.cs
1,050
C#
using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using NServiceBus; using Shared; namespace ApiApplication.Controllers { [Route("api/[controller]")] [ApiController] public class TestController : ControllerBase { private readonly IMessageSession _messageSession; public TestController(IMessageSession messageSession) { _messageSession = messageSession; } [HttpGet("{id}")] public async Task<IActionResult> Get(int id) { //Alternative is to use wrapper abstraction or custom IMessageSession decorator with hidden: // var sendOptions = new SendOptions(); // sendOptions.SetHeader("ContextId", _sharedContext.ContextId); await _messageSession.Send("Host", new MyFirstMessage { MessageId = id }).ConfigureAwait(false); return Ok(); } } }
27.142857
104
0.623158
[ "MIT" ]
oddbear/NServiceBusContext
ApiApplication/Controllers/TestController.cs
952
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore.Tools.Properties; namespace Microsoft.DotNet.Cli.CommandLine { internal class CommandLineApplication { private enum ParseOptionResult { Succeeded, ShowHelp, ShowVersion, UnexpectedArgs } // Indicates whether the parser should throw an exception when it runs into an unexpected argument. // If this field is set to false, the parser will stop parsing when it sees an unexpected argument, and all // remaining arguments, including the first unexpected argument, will be stored in RemainingArguments property. private readonly bool _throwOnUnexpectedArg; public CommandLineApplication(bool throwOnUnexpectedArg = true) { _throwOnUnexpectedArg = throwOnUnexpectedArg; Options = new List<CommandOption>(); Arguments = new List<CommandArgument>(); Commands = new List<CommandLineApplication>(); RemainingArguments = new List<string>(); ApplicationArguments = new List<string>(); Invoke = (args) => 0; } public CommandLineApplication Parent { get; set; } public string Name { get; set; } public string FullName { get; set; } public string Syntax { get; set; } public string Description { get; set; } public List<CommandOption> Options { get; } public CommandOption OptionHelp { get; private set; } public CommandOption OptionVersion { get; private set; } public List<CommandArgument> Arguments { get; } public List<string> RemainingArguments { get; } public List<string> ApplicationArguments { get; } public bool IsShowingInformation { get; protected set; } // Is showing help or version? public Func<string[], int> Invoke { get; set; } public Func<string> LongVersionGetter { get; set; } public Func<string> ShortVersionGetter { get; set; } public List<CommandLineApplication> Commands { get; } public bool HandleResponseFiles { get; set; } public bool AllowArgumentSeparator { get; set; } public bool HandleRemainingArguments { get; set; } public string ArgumentSeparatorHelpText { get; set; } public CommandLineApplication Command(string name, bool throwOnUnexpectedArg = true) => Command(name, _ => { }, throwOnUnexpectedArg); public CommandLineApplication Command( string name, Action<CommandLineApplication> configuration, bool throwOnUnexpectedArg = true) { var command = new CommandLineApplication(throwOnUnexpectedArg) { Name = name, Parent = this }; Commands.Add(command); configuration(command); return command; } public CommandOption Option(string template, string description, CommandOptionType optionType) => Option(template, description, optionType, _ => { }); public CommandOption Option(string template, string description, CommandOptionType optionType, Action<CommandOption> configuration) { var option = new CommandOption(template, optionType) { Description = description }; Options.Add(option); configuration(option); return option; } public CommandArgument Argument(string name, string description, bool multipleValues = false) => Argument(name, description, _ => { }, multipleValues); public CommandArgument Argument(string name, string description, Action<CommandArgument> configuration, bool multipleValues = false) { var lastArg = Arguments.LastOrDefault(); if (lastArg?.MultipleValues == true) { throw new InvalidOperationException(Resources.LastArgumentHasMultipleValues(lastArg.Name)); } var argument = new CommandArgument { Name = name, Description = description, MultipleValues = multipleValues }; Arguments.Add(argument); configuration(argument); return argument; } public void OnExecute(Func<string[], int> invoke) => Invoke = invoke; public void OnExecute(Func<string[], Task<int>> invoke) => Invoke = (args) => invoke(args).Result; public int Execute(params string[] args) { var command = this; IEnumerator<CommandArgument> arguments = null; if (HandleResponseFiles) { args = ExpandResponseFiles(args).ToArray(); } for (var index = 0; index < args.Length; index++) { var arg = args[index]; var isLongOption = arg.StartsWith("--"); if (isLongOption || arg.StartsWith("-")) { var result = ParseOption(isLongOption, command, args, ref index, out var option); if (result == ParseOptionResult.ShowHelp) { command.ShowHelp(); return 0; } if (result == ParseOptionResult.ShowVersion) { command.ShowVersion(); return 0; } } else { var subcommand = ParseSubCommand(arg, command); if (subcommand != null) { command = subcommand; } else { if (arguments == null) { arguments = new CommandArgumentEnumerator(command.Arguments.GetEnumerator()); } if (arguments.MoveNext()) { arguments.Current.Values.Add(arg); } else { HandleUnexpectedArg(command, args, index, argTypeName: "command or argument"); } } } } return command.Invoke(command.ApplicationArguments.ToArray()); } private ParseOptionResult ParseOption( bool isLongOption, CommandLineApplication command, string[] args, ref int index, out CommandOption option) { option = null; var result = ParseOptionResult.Succeeded; var arg = args[index]; var optionPrefixLength = isLongOption ? 2 : 1; var optionComponents = arg.Substring(optionPrefixLength).Split(new[] { ':', '=' }, 2); var optionName = optionComponents[0]; if (isLongOption) { option = command.Options.SingleOrDefault( opt => string.Equals(opt.LongName, optionName, StringComparison.Ordinal)); } else { option = command.Options.SingleOrDefault( opt => string.Equals(opt.ShortName, optionName, StringComparison.Ordinal)); if (option == null) { option = command.Options.SingleOrDefault( opt => string.Equals(opt.SymbolName, optionName, StringComparison.Ordinal)); } } if (option == null) { if (isLongOption && string.IsNullOrEmpty(optionName) && command.AllowArgumentSeparator) { // a stand-alone "--" is the argument separator, so skip it and // handle the rest of the args as application args for (index++; index < args.Length; index++) { command.ApplicationArguments.Add(args[index]); } } else { HandleUnexpectedArg(command, args, index, argTypeName: "option"); } result = ParseOptionResult.UnexpectedArgs; } else if (command.OptionHelp == option) { result = ParseOptionResult.ShowHelp; } else if (command.OptionVersion == option) { result = ParseOptionResult.ShowVersion; } else { if (optionComponents.Length == 2) { if (!option.TryParse(optionComponents[1])) { command.ShowHint(); throw new CommandParsingException(command, Resources.UnexpectedOptionValue(optionComponents[1], optionName)); } } else { if (option.OptionType == CommandOptionType.NoValue || option.OptionType == CommandOptionType.BoolValue) { // No value is needed for this option option.TryParse(null); } else { index++; arg = args[index]; if (!option.TryParse(arg)) { command.ShowHint(); throw new CommandParsingException(command, Resources.UnexpectedOptionValue(arg, optionName)); } } } } return result; } private static CommandLineApplication ParseSubCommand(string arg, CommandLineApplication command) { foreach (var subcommand in command.Commands) { if (string.Equals(subcommand.Name, arg, StringComparison.OrdinalIgnoreCase)) { return subcommand; } } return null; } // Helper method that adds a help option public CommandOption HelpOption(string template) { // Help option is special because we stop parsing once we see it // So we store it separately for further use OptionHelp = Option(template, "Show help information", CommandOptionType.NoValue); return OptionHelp; } public CommandOption VersionOption( string template, string shortFormVersion, string longFormVersion = null) { if (longFormVersion == null) { return VersionOption(template, () => shortFormVersion); } return VersionOption(template, () => shortFormVersion, () => longFormVersion); } // Helper method that adds a version option public CommandOption VersionOption( string template, Func<string> shortFormVersionGetter, Func<string> longFormVersionGetter = null) { // Version option is special because we stop parsing once we see it // So we store it separately for further use OptionVersion = Option(template, "Show version information", CommandOptionType.NoValue); ShortVersionGetter = shortFormVersionGetter; LongVersionGetter = longFormVersionGetter ?? shortFormVersionGetter; return OptionVersion; } // Show short hint that reminds users to use help option public void ShowHint() { if (OptionHelp != null) { Console.WriteLine("Specify --{0} for a list of available options and commands.", OptionHelp.LongName); } } // Show full help public void ShowHelp(string commandName = null) { var headerBuilder = new StringBuilder("Usage:"); var usagePrefixLength = headerBuilder.Length; for (var cmd = this; cmd != null; cmd = cmd.Parent) { cmd.IsShowingInformation = true; if (cmd != this && cmd.Arguments.Count > 0) { var args = string.Join(" ", cmd.Arguments.Select(arg => arg.Name)); headerBuilder.Insert(usagePrefixLength, string.Format(" {0} {1}", cmd.Name, args)); } else { headerBuilder.Insert(usagePrefixLength, string.Format(" {0}", cmd.Name)); } } CommandLineApplication target; if (commandName == null || string.Equals(Name, commandName, StringComparison.OrdinalIgnoreCase)) { target = this; } else { target = Commands.SingleOrDefault(cmd => string.Equals(cmd.Name, commandName, StringComparison.OrdinalIgnoreCase)); if (target != null) { headerBuilder.AppendFormat(" {0}", commandName); } else { // The command name is invalid so don't try to show help for something that doesn't exist target = this; } } var optionsBuilder = new StringBuilder(); var commandsBuilder = new StringBuilder(); var argumentsBuilder = new StringBuilder(); var argumentSeparatorBuilder = new StringBuilder(); var maxArgLen = 0; for (var cmd = target; cmd != null; cmd = cmd.Parent) { if (cmd.Arguments.Count > 0) { if (cmd == target) { headerBuilder.Append(" [arguments]"); } if (argumentsBuilder.Length == 0) { argumentsBuilder.AppendLine(); argumentsBuilder.AppendLine("Arguments:"); } maxArgLen = Math.Max(maxArgLen, MaxArgumentLength(cmd.Arguments)); } } for (var cmd = target; cmd != null; cmd = cmd.Parent) { if (cmd.Arguments.Count > 0) { var outputFormat = " {0}{1}"; foreach (var arg in cmd.Arguments) { argumentsBuilder.AppendFormat( outputFormat, arg.Name.PadRight(maxArgLen + 2), arg.Description); argumentsBuilder.AppendLine(); } } } if (target.Options.Count > 0) { headerBuilder.Append(" [options]"); optionsBuilder.AppendLine(); optionsBuilder.AppendLine("Options:"); var maxOptLen = MaxOptionTemplateLength(target.Options); var outputFormat = string.Format(" {{0, -{0}}}{{1}}", maxOptLen + 2); foreach (var opt in target.Options) { optionsBuilder.AppendFormat(outputFormat, opt.Template, opt.Description); optionsBuilder.AppendLine(); } } if (target.Commands.Count > 0) { headerBuilder.Append(" [command]"); commandsBuilder.AppendLine(); commandsBuilder.AppendLine("Commands:"); var maxCmdLen = MaxCommandLength(target.Commands); var outputFormat = string.Format(" {{0, -{0}}}{{1}}", maxCmdLen + 2); foreach (var cmd in target.Commands.OrderBy(c => c.Name)) { commandsBuilder.AppendFormat(outputFormat, cmd.Name, cmd.Description); commandsBuilder.AppendLine(); } if (OptionHelp != null) { commandsBuilder.AppendLine(); commandsBuilder.AppendFormat("Use \"{0} [command] --help\" for more information about a command.", Name); commandsBuilder.AppendLine(); } } if (target.AllowArgumentSeparator || target.HandleRemainingArguments) { if (target.AllowArgumentSeparator) { headerBuilder.Append(" [[--] <arg>...]]"); } else { headerBuilder.Append(" [args]"); } if (!string.IsNullOrEmpty(target.ArgumentSeparatorHelpText)) { argumentSeparatorBuilder.AppendLine(); argumentSeparatorBuilder.AppendLine("Args:"); argumentSeparatorBuilder.Append(" ").AppendLine(target.ArgumentSeparatorHelpText); argumentSeparatorBuilder.AppendLine(); } } headerBuilder.AppendLine(); var nameAndVersion = new StringBuilder(); nameAndVersion.AppendLine(GetFullNameAndVersion()); nameAndVersion.AppendLine(); Console.Write( "{0}{1}{2}{3}{4}{5}", nameAndVersion, headerBuilder, argumentsBuilder, optionsBuilder, commandsBuilder, argumentSeparatorBuilder); } public void ShowVersion() { for (var cmd = this; cmd != null; cmd = cmd.Parent) { cmd.IsShowingInformation = true; } Console.WriteLine(FullName); Console.WriteLine(LongVersionGetter()); } public string GetFullNameAndVersion() => ShortVersionGetter == null ? FullName : string.Format("{0} {1}", FullName, ShortVersionGetter()); public void ShowRootCommandFullNameAndVersion() { var rootCmd = this; while (rootCmd.Parent != null) { rootCmd = rootCmd.Parent; } Console.WriteLine(rootCmd.GetFullNameAndVersion()); Console.WriteLine(); } private static int MaxOptionTemplateLength(IEnumerable<CommandOption> options) { var maxLen = 0; foreach (var opt in options) { maxLen = opt.Template.Length > maxLen ? opt.Template.Length : maxLen; } return maxLen; } private static int MaxCommandLength(IEnumerable<CommandLineApplication> commands) { var maxLen = 0; foreach (var cmd in commands) { maxLen = cmd.Name.Length > maxLen ? cmd.Name.Length : maxLen; } return maxLen; } private static int MaxArgumentLength(IEnumerable<CommandArgument> arguments) { var maxLen = 0; foreach (var arg in arguments) { maxLen = arg.Name.Length > maxLen ? arg.Name.Length : maxLen; } return maxLen; } private static void HandleUnexpectedArg(CommandLineApplication command, string[] args, int index, string argTypeName) { if (command._throwOnUnexpectedArg) { command.ShowHint(); throw new CommandParsingException(command, Resources.UnexpectedArgument(argTypeName, args[index])); } command.RemainingArguments.Add(args[index]); } private IEnumerable<string> ExpandResponseFiles(IEnumerable<string> args) { foreach (var arg in args) { if (!arg.StartsWith("@", StringComparison.Ordinal)) { yield return arg; } else { var fileName = arg.Substring(1); var responseFileArguments = ParseResponseFile(fileName); // ParseResponseFile can suppress expanding this response file by // returning null. In that case, we'll treat the response // file token as a regular argument. if (responseFileArguments == null) { yield return arg; } else { foreach (var responseFileArgument in responseFileArguments) { yield return responseFileArgument.Trim(); } } } } } private IEnumerable<string> ParseResponseFile(string fileName) { if (!HandleResponseFiles) { return null; } if (!File.Exists(fileName)) { throw new InvalidOperationException(Resources.ResponseFileMissing(fileName)); } return File.ReadLines(fileName); } private sealed class CommandArgumentEnumerator : IEnumerator<CommandArgument> { private readonly IEnumerator<CommandArgument> _enumerator; public CommandArgumentEnumerator(IEnumerator<CommandArgument> enumerator) => _enumerator = enumerator; public CommandArgument Current => _enumerator.Current; object IEnumerator.Current => Current; public void Dispose() => _enumerator.Dispose(); public bool MoveNext() { if (Current?.MultipleValues != true) { return _enumerator.MoveNext(); } // If current argument allows multiple values, we don't move forward and // all later values will be added to current CommandArgument.Values return true; } public void Reset() => _enumerator.Reset(); } } }
36.812298
140
0.512967
[ "Apache-2.0" ]
0b01/efcore
src/ef/CommandLineUtils/CommandLineApplication.cs
22,750
C#
#define Graph_And_Chart_PRO using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using UnityEngine.Serialization; using UnityEngine.UI; namespace ChartAndGraph { /// <summary> /// base class for all axis monobehaviours. This class contains paramets for defining chart axis /// </summary> public abstract class AxisBase : ChartSettingItemBase, ISerializationCallbackReceiver { #pragma warning disable 0414 /// <summary> /// used internally by the axis inspector /// </summary> [SerializeField] private bool SimpleView = true; #pragma warning restore 0414 /// <summary> /// the format of the axis labels. This can be either a number, time or date time. If the selected value is either DateTime or Time , user ChartDateUtillity to convert dates to double values that can be set to the chart. /// </summary> [SerializeField] [Tooltip("the format of the axis labels. This can be either a number, time or date time. If the selected value is either DateTime or Time , user ChartDateUtillity to convert dates to double values that can be set to the graph")] private AxisFormat format; /// <summary> /// the format of the axis labels. This can be either a number, time or date time. If the selected value is either DateTime or Time , user ChartDateUtillity to convert dates to double values that can be set to the chart. /// </summary> public AxisFormat Format { get { return format; } set { format = value; RaiseOnChanged(); } } /// <summary> /// the depth of the axis reltive to the chart position /// </summary> [SerializeField] [Tooltip("the depth of the axis reltive to the chart position")] private AutoFloat depth; public AutoFloat Depth { get { return depth; } set { depth = value; RaiseOnChanged(); } } [SerializeField] [Tooltip("The main divisions of the chart axis")] [FormerlySerializedAs("MainDivisions")] private ChartMainDivisionInfo mainDivisions = new ChartMainDivisionInfo(); [SerializeField] [Tooltip("The sub divisions of each main division")] [FormerlySerializedAs("SubDivisions")] private ChartSubDivisionInfo subDivisions = new ChartSubDivisionInfo(); private Dictionary<double, string> mFormats = new Dictionary<double, string>(); private List<double> mTmpToRemove = new List<double>(); /// <summary> /// the main division properies for this axis /// </summary> public ChartMainDivisionInfo MainDivisions { get { return mainDivisions; } } /// <summary> /// the sub division properies for this axis /// </summary> public ChartDivisionInfo SubDivisions { get { return subDivisions; } } public void ClearFormats() { mFormats.Clear(); } public AxisBase() { AddInnerItems(); } private void AddInnerItems() { AddInnerItem(MainDivisions); AddInnerItem(SubDivisions); } /// <summary> /// used internally to hold data required for updating the axis lables /// </summary> internal class TextData { public ChartDivisionInfo info; public float interp; public int fractionDigits; } /// <summary> /// checks that all properies of this instance have valid values. This method is used internally and should not be called /// </summary> public void ValidateProperties() { mainDivisions.ValidateProperites(); subDivisions.ValidateProperites(); } /// <summary> /// retrieves the begining and end division of the chart /// </summary> /// <param name="parent"></param> /// <param name="orientation"></param> /// <param name="total"></param> /// <param name="start"></param> /// <param name="end"></param> private void GetStartEnd(AnyChart parent, ChartOrientation orientation, float total, out float start, out float end) { start = 0; end = total; // if ((orientation == ChartOrientation.Horizontal) ? parent.Frame.Left.Visible : parent.Frame.Bottom.Visible) // ++start; // if ((orientation == ChartOrientation.Horizontal) ? parent.Frame.Right.Visible : parent.Frame.Top.Visible) // --end; } /// <summary> /// sets the uv of a chart mesh based on the current length and offset /// </summary> /// <param name="mesh"></param> /// <param name="length"></param> /// <param name="offset"></param> private void SetMeshUv(IChartMesh mesh, float length,float offset) { if (length < 0) offset -= length; mesh.Length = length; mesh.Offset = offset; } private void DrawDivisions(double scrollOffset, AnyChart parent, Transform parentTransform, ChartDivisionInfo info, IChartMesh mesh, int group, ChartOrientation orientation, double gap, bool oppositeSide, double mainGap) { //scrollOffset = -scrollOffset; double parentSize = (orientation == ChartOrientation.Vertical) ? ((IInternalUse)parent).InternalTotalHeight : ((IInternalUse)parent).InternalTotalWidth; DoubleVector3 startPosition, lengthDirection, advanceDirection; GetDirectionVectors(parent, info, orientation, 0f, oppositeSide, out startPosition, out lengthDirection, out advanceDirection); double markDepth = ChartCommon.GetAutoDepth(parent, orientation, info); double length = ChartCommon.GetAutoLength(parent, orientation, info); double backLength = (orientation == ChartOrientation.Vertical) ? ((IInternalUse)parent).InternalTotalWidth : ((IInternalUse)parent).InternalTotalHeight; if (info.MarkBackLength.Automatic == false) backLength = info.MarkBackLength.Value; double totaluv = Math.Abs(length); if (backLength != 0 && markDepth > 0) totaluv += Math.Abs(backLength) + Math.Abs(markDepth); DoubleVector3 halfThickness = advanceDirection * (info.MarkThickness * 0.5f); // if (scrollOffset != 0f) // last--; bool hasValues = ((IInternalUse)parent).InternalHasValues(this); double maxValue = ((IInternalUse)parent).InternalMaxValue(this); double minValue = ((IInternalUse)parent).InternalMinValue(this); double range = maxValue - minValue; float AutoAxisDepth = Depth.Value; // float scrollFactor = (scrollOffset / (float)(maxValue - minValue)); //scrollOffset = scrollFactor * parentSize; if (Depth.Automatic) { AutoAxisDepth = (float)((((IInternalUse)parent).InternalTotalDepth) - markDepth); } double startValue = (scrollOffset + minValue); double endValue = (scrollOffset + maxValue) + double.Epsilon; double direction = 1.0; Func<double, double> ValueToPosition = x => ((x - startValue) / range) * parentSize; if (startValue > endValue) { direction = -1.0; //ValueToPosition = x => (1.0- ((x - startValue) / range)) * parentSize; } gap = Math.Abs(gap); double fraction = gap - (scrollOffset - Math.Floor((scrollOffset / gap) - double.Epsilon) * gap); double mainfraction = -1f; double currentMain = 0f; if (mainGap > 0f) { mainfraction = mainGap - (scrollOffset - Math.Floor((scrollOffset / mainGap) - double.Epsilon) * mainGap); currentMain = (scrollOffset + minValue + mainfraction); } int i = 0; mTmpToRemove.Clear(); double startRange = startValue + fraction; foreach (double key in mFormats.Keys) { if (key* direction > endValue* direction || key* direction < startRange* direction) mTmpToRemove.Add(key); } for(int k=0; k<mTmpToRemove.Count; k++) mFormats.Remove(mTmpToRemove[k]); for (double current = startRange; direction*current <= direction*endValue; current += gap*direction) { ++i; if (i > 3000) { break; } if (mainGap > 0.0) { if(Math.Abs(current - currentMain) < 0.00001) { currentMain += mainGap; continue; } if(current > currentMain) { currentMain += mainGap; } } double offset = ValueToPosition(current); if (offset < 0 || offset > parentSize) continue; DoubleVector3 start = startPosition + advanceDirection * offset; DoubleVector3 size = halfThickness + length * lengthDirection; start -= halfThickness; //size += halfThickness; float uvoffset = 0f; Rect r = ChartCommon.FixRect(new Rect((float)start.x, (float)start.y, (float)size.x, (float)size.y)); SetMeshUv(mesh, (float)(-length / totaluv), uvoffset); uvoffset += Math.Abs(mesh.Length); mesh.AddXYRect(r, group, AutoAxisDepth); if (hasValues) { double val = Math.Round(current*1000.0)/1000.0; string toSet = ""; double keyVal = val;// (int)Math.Round(val); var dic = (orientation == ChartOrientation.Horizontal) ? parent.HorizontalValueToStringMap : parent.VerticalValueToStringMap; if (!(Math.Abs(val - keyVal) < 0.001 && dic.TryGetValue(keyVal, out toSet))) { if (mFormats.TryGetValue(val, out toSet) == false) { if (format == AxisFormat.Number) toSet = ChartAdancedSettings.Instance.FormatFractionDigits(info.FractionDigits, val, parent.CustomNumberFormat); else { DateTime date = ChartDateUtility.ValueToDate(val); if (format == AxisFormat.DateTime) toSet = ChartDateUtility.DateToDateTimeString(date, parent.CustomDateTimeFormat); else { if (format == AxisFormat.Date) toSet = ChartDateUtility.DateToDateString(date); else toSet = ChartDateUtility.DateToTimeString(date); } } toSet = info.TextPrefix + toSet + info.TextSuffix; mFormats[val] = toSet; } } else { toSet = info.TextPrefix + toSet + info.TextSuffix; } DoubleVector3 textPos = new DoubleVector3(start.x, start.y); textPos += lengthDirection * info.TextSeperation; TextData userData = new TextData(); userData.interp = (float)(offset/parentSize); userData.info = info; userData.fractionDigits = info.FractionDigits; mesh.AddText(parent, info.TextPrefab, parentTransform, info.FontSize, info.FontSharpness, toSet, (float)textPos.x, (float)textPos.y, AutoAxisDepth + info.TextDepth, 0f, userData); } if (markDepth > 0) { if (orientation == ChartOrientation.Horizontal) { SetMeshUv(mesh,(float)( markDepth / totaluv), uvoffset); r = ChartCommon.FixRect(new Rect((float)start.x, AutoAxisDepth, (float)size.x, (float)markDepth)); mesh.AddXZRect(r, group, (float)start.y); } else { SetMeshUv(mesh,(float) (-markDepth / totaluv), uvoffset); r = ChartCommon.FixRect(new Rect((float)start.y, AutoAxisDepth, (float)size.y, (float)markDepth)); mesh.AddYZRect(r, group, (float)start.x); } uvoffset += Math.Abs(mesh.Length); if (backLength != 0) { SetMeshUv(mesh, (float)(backLength / totaluv), uvoffset); uvoffset += Math.Abs(mesh.Length); DoubleVector3 backSize = halfThickness + backLength * lengthDirection; Rect backR = ChartCommon.FixRect(new Rect((float)start.x, (float)start.y, (float)backSize.x, (float)backSize.y)); mesh.AddXYRect(backR, group, (float)(AutoAxisDepth + markDepth)); } } } // Debug.Log("start"); // Debug.Log(mFormats.Count); // Debug.Log(cached); } // /// <summary> // /// used internally to draw the division of the axis into a chart mesh // /// </summary> // /// <param name="parent"></param> // /// <param name="parentTransform"></param> // /// <param name="info"></param> // /// <param name="mesh"></param> // /// <param name="group"></param> // /// <param name="orientation"></param> // /// <param name="totalDivisions"></param> // /// <param name="oppositeSide"></param> // /// <param name="skip"></param> // private void DrawDivisions(float scrollOffset,AnyChart parent, Transform parentTransform, ChartDivisionInfo info, IChartMesh mesh, int group, ChartOrientation orientation, float totalDivisions, bool oppositeSide, int skip) // { // //scrollOffset = -scrollOffset; // float parentSize = (orientation == ChartOrientation.Vertical) ? ((IInternalUse)parent).InternalTotalHeight : ((IInternalUse)parent).InternalTotalWidth; // Vector2 startPosition, lengthDirection, advanceDirection; // GetDirectionVectors(parent, info, orientation, 0f, oppositeSide, out startPosition, out lengthDirection, out advanceDirection); // float markDepth = ChartCommon.GetAutoDepth(parent, orientation, info); // float length = ChartCommon.GetAutoLength(parent, orientation, info); // float backLength = (orientation == ChartOrientation.Vertical) ? ((IInternalUse)parent).InternalTotalWidth : ((IInternalUse)parent).InternalTotalHeight; // if (info.MarkBackLength.Automatic == false) // backLength = info.MarkBackLength.Value; // float totaluv = Math.Abs(length); // if (backLength != 0 && markDepth > 0) // totaluv += Math.Abs(backLength) + Math.Abs(markDepth); // Vector2 halfThickness = advanceDirection * (info.MarkThickness * 0.5f); // // if (scrollOffset != 0f) // // last--; // bool hasValues = ((IInternalUse)parent).InternalHasValues(this); // double maxValue = ((IInternalUse)parent).InternalMaxValue(this); // double minValue = ((IInternalUse)parent).InternalMinValue(this); // ChartMainDivisionInfo main = info as ChartMainDivisionInfo; // float divisionComplement = 0f; // float divisionOffsetComplement = 0f; // if (main != null) // { // if(main.Messure == ChartDivisionInfo.DivisionMessure.DataUnits) // { // if (main.UnitsPerDivision <= 0.0001f) // return; // float range = (float)(maxValue - minValue); // totalDivisions = (range / main.UnitsPerDivision) + 1; // divisionComplement = (float)(1f - (main.UnitsPerDivision - Math.Truncate(main.UnitsPerDivision))) / range; // divisionOffsetComplement = (divisionComplement) * parentSize; // } // } // float first, last; // GetStartEnd(parent, orientation, totalDivisions, out first, out last); // float AutoAxisDepth = Depth.Value; // float scrollFactor = (scrollOffset / (float)(maxValue - minValue)); // scrollOffset = scrollFactor * parentSize; // if (Depth.Automatic) // { // AutoAxisDepth = (((IInternalUse)parent).InternalTotalDepth) - markDepth; // } // float floorLast = Mathf.Floor(last); // for (float i = first; i < floorLast; i++) // { // if (skip != -1 && ((int)i) % skip == 0) // continue; // float factor = ((float)i) / (float)(totalDivisions - 1); // float offset = -scrollOffset + factor * parentSize; // if (scrollOffset != 0f) // { // float prevOffs = offset; // offset = offset - Mathf.Floor((offset / parentSize)) * parentSize; //// Debug.Log("prev " + prevOffs); //// Debug.Log("offs " + offset); // if (offset < prevOffs) // { // offset -= divisionOffsetComplement; // } // } // if (offset < 0f) // continue; // Vector2 start = startPosition + advanceDirection * offset; // Vector2 size = halfThickness + length * lengthDirection; // start -= halfThickness; // //size += halfThickness; // float uvoffset = 0f; // Rect r = ChartCommon.FixRect(new Rect(start.x, start.y, size.x, size.y)); // SetMeshUv(mesh, -length / totaluv, uvoffset); // uvoffset += Math.Abs(mesh.Length); // mesh.AddXYRect(r, group, AutoAxisDepth); // if (hasValues) // { // float valFactor = -scrollFactor + factor; // if (scrollOffset != 0f) // { // float prevFact = valFactor; // valFactor -= Mathf.Floor(valFactor); // if(valFactor < prevFact) // { // valFactor -= divisionComplement; // } // } // //valFactor += scrollFactor; // double offsetPos = (maxValue - minValue) * valFactor; // double scroll = minValue + ((maxValue - minValue) * scrollFactor); // double val = scroll + offsetPos; // string toSet = ""; // if (format == AxisFormat.Number) // toSet = ChartAdancedSettings.Instance.FormatFractionDigits(info.FractionDigits, (float)val); // else // { // DateTime date = ChartDateUtility.ValueToDate(val); // if (format == AxisFormat.DateTime) // toSet = ChartDateUtility.DateToDateTimeString(date); // else // { // if (format == AxisFormat.Date) // toSet = ChartDateUtility.DateToDateString(date); // else // toSet = ChartDateUtility.DateToTimeString(date); // } // } // toSet = info.TextPrefix + toSet + info.TextSuffix; // Vector2 textPos = new Vector2(start.x, start.y); // textPos += lengthDirection * info.TextSeperation; // TextData userData = new TextData(); // userData.interp = factor; // userData.info = info; // userData.fractionDigits = info.FractionDigits; // mesh.AddText(parent, info.TextPrefab, parentTransform, info.FontSize, info.FontSharpness, toSet, textPos.x, textPos.y, AutoAxisDepth + info.TextDepth,0f, userData); // } // if (markDepth > 0) // { // if (orientation == ChartOrientation.Horizontal) // { // SetMeshUv(mesh, markDepth / totaluv, uvoffset); // r = ChartCommon.FixRect(new Rect(start.x, AutoAxisDepth, size.x, markDepth)); // mesh.AddXZRect(r, group, start.y); // } // else // { // SetMeshUv(mesh, -markDepth / totaluv, uvoffset); // r = ChartCommon.FixRect(new Rect(start.y, AutoAxisDepth, size.y, markDepth)); // mesh.AddYZRect(r, group, start.x); // } // uvoffset += Math.Abs(mesh.Length); // if (backLength != 0) // { // SetMeshUv(mesh, backLength / totaluv, uvoffset); // uvoffset += Math.Abs(mesh.Length); // Vector2 backSize = halfThickness + backLength * lengthDirection; // Rect backR = ChartCommon.FixRect(new Rect(start.x, start.y, backSize.x, backSize.y)); // mesh.AddXYRect(backR, group, AutoAxisDepth + markDepth); // } // } // } // } /// <summary> /// used internally to determine drawing direction of the each chart division /// </summary> /// <param name="parent"></param> /// <param name="info"></param> /// <param name="orientation"></param> /// <param name="oppositeSide"></param> /// <param name="startPosition"></param> /// <param name="lengthDirection"></param> /// <param name="advanceDirection"></param> private void GetDirectionVectors(AnyChart parent, ChartDivisionInfo info, ChartOrientation orientation,float scrollOffset, bool oppositeSide, out DoubleVector3 startPosition, out DoubleVector3 lengthDirection, out DoubleVector3 advanceDirection) { if (orientation == ChartOrientation.Horizontal) { advanceDirection = new DoubleVector3(1f, 0f); if (oppositeSide) { startPosition = new DoubleVector3(scrollOffset, ((IInternalUse)parent).InternalTotalHeight); lengthDirection = new DoubleVector3(0f, -1f); return; } startPosition = new DoubleVector3(0f, 0f); lengthDirection = new DoubleVector3(0f, 1f); return; } advanceDirection = new DoubleVector3(0f, 1f); if (oppositeSide) { startPosition = new DoubleVector3(0f, 0f); lengthDirection = new DoubleVector3(1f, 0f); return; } startPosition = new DoubleVector3(((IInternalUse)parent).InternalTotalWidth, scrollOffset); lengthDirection = new DoubleVector3(-1f, 0f); } /// <summary> /// used internally , adds the axis sub divisions to the chart mesh /// </summary> /// <param name="parent"></param> /// <param name="parentTransform"></param> /// <param name="mesh"></param> /// <param name="orientation"></param> internal void AddSubdivisionToChartMesh(double scrollOffset,AnyChart parent, Transform parentTransform, IChartMesh mesh, ChartOrientation orientation) { int total = SubDivisions.Total; if (total <= 1) // no need for more return; double maxValue = ((IInternalUse)parent).InternalMaxValue(this); double minValue = ((IInternalUse)parent).InternalMinValue(this); double range = maxValue - minValue; double? gap = GetMainGap(parent, range); if (gap.HasValue == false) return; double subGap = gap.Value / (total); mesh.Tile = ChartCommon.GetTiling(SubDivisions.MaterialTiling); if ((SubDivisions.Alignment & ChartDivisionAligment.Opposite) == ChartDivisionAligment.Opposite) DrawDivisions(scrollOffset,parent, parentTransform, SubDivisions, mesh, 0, orientation, subGap, false, gap.Value); if ((SubDivisions.Alignment & ChartDivisionAligment.Standard) == ChartDivisionAligment.Standard) DrawDivisions(scrollOffset,parent, parentTransform, SubDivisions, mesh, 0, orientation, subGap, true, gap.Value); } double? GetMainGap(AnyChart parent, double range) { double gap = ((ChartMainDivisionInfo)MainDivisions).UnitsPerDivision; if (((ChartMainDivisionInfo)MainDivisions).Messure == ChartDivisionInfo.DivisionMessure.TotalDivisions) { int total = ((ChartMainDivisionInfo)MainDivisions).Total; if (total <= 0) return null; gap = (range / (double)(total)); } return gap; } /// <summary> /// used internally , adds the axis main divisions to the chart mesh /// </summary> /// <param name="parent"></param> /// <param name="parentTransform"></param> /// <param name="mesh"></param> /// <param name="orientation"></param> internal void AddMainDivisionToChartMesh(double scrollOffset,AnyChart parent, Transform parentTransform, IChartMesh mesh, ChartOrientation orientation) { double maxValue = ((IInternalUse)parent).InternalMaxValue(this); double minValue = ((IInternalUse)parent).InternalMinValue(this); double range = maxValue - minValue; double? gap = GetMainGap(parent, range); if (gap.HasValue == false) return; mesh.Tile = ChartCommon.GetTiling(MainDivisions.MaterialTiling); if ((MainDivisions.Alignment & ChartDivisionAligment.Opposite) == ChartDivisionAligment.Opposite) DrawDivisions(scrollOffset,parent, parentTransform, MainDivisions, mesh, 0, orientation,gap.Value, false, -1); if ((MainDivisions.Alignment & ChartDivisionAligment.Standard) == ChartDivisionAligment.Standard) DrawDivisions(scrollOffset,parent, parentTransform, MainDivisions, mesh, 0, orientation, gap.Value, true, -1); } void ISerializationCallbackReceiver.OnBeforeSerialize() { } void ISerializationCallbackReceiver.OnAfterDeserialize() { AddInnerItems(); } } }
46.623549
253
0.533364
[ "MIT" ]
FrozenSonar/Fencing3DNEAT
Assets/Chart And Graph/Script/Axis/AxisBase.cs
28,114
C#
//----------------------------------------------------------------------- // <copyright file="OwnershipAnalysisPass.cs"> // Copyright (c) Microsoft Corporation. All rights reserved. // // 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. // </copyright> //----------------------------------------------------------------------- using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.DataFlowAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.PSharp.IO; namespace Microsoft.PSharp.StaticAnalysis { /// <summary> /// Implementation of an abstract ownership analysis pass. /// </summary> internal abstract class OwnershipAnalysisPass : StateMachineAnalysisPass { #region internal API /// <summary> /// Runs the analysis on the specified machines. /// </summary> /// <param name="machines">StateMachines</param> internal override void Run(ISet<StateMachine> machines) { // Starts profiling the ownership analysis. if (base.Configuration.EnableProfiling) { base.Profiler.StartMeasuringExecutionTime(); } foreach (var machine in machines) { this.AnalyzeMethodSummariesInMachine(machine); } // Stops profiling the ownership analysis. if (base.Configuration.EnableProfiling) { base.Profiler.StopMeasuringExecutionTime(); this.PrintProfilingResults(); } } #endregion #region protected methods /// <summary> /// Constructor. /// </summary> /// <param name="context">AnalysisContext</param> /// <param name="configuration">Configuration</param> /// <param name="logger">ILogger</param> /// <param name="errorReporter">ErrorReporter</param> protected OwnershipAnalysisPass(AnalysisContext context, Configuration configuration, ILogger logger, ErrorReporter errorReporter) : base(context, configuration, logger, errorReporter) { } /// <summary> /// Analyzes the ownership of the given-up symbol /// in the control-flow graph. /// </summary> /// <param name="givenUpSymbol">GivenUpOwnershipSymbol</param> /// <param name="machine">StateMachine</param> /// <param name="model">SemanticModel</param> /// <param name="trace">TraceInfo</param> protected abstract void AnalyzeOwnershipInControlFlowGraph(GivenUpOwnershipSymbol givenUpSymbol, StateMachine machine, SemanticModel model, TraceInfo trace); /// <summary> /// Analyzes the ownership of the given-up symbol /// in the control-flow graph node. /// </summary> /// <param name="givenUpSymbol">GivenUpOwnershipSymbol</param> /// <param name="statement">Statement</param> /// <param name="machine">StateMachine</param> /// <param name="model">SemanticModel</param> /// <param name="trace">TraceInfo</param> protected void AnalyzeOwnershipInStatement(GivenUpOwnershipSymbol givenUpSymbol, Statement statement, StateMachine machine, SemanticModel model, TraceInfo trace) { var localDecl = statement.SyntaxNode.DescendantNodesAndSelf(). OfType<LocalDeclarationStatementSyntax>().FirstOrDefault(); var expr = statement.SyntaxNode.DescendantNodesAndSelf(). OfType<ExpressionStatementSyntax>().FirstOrDefault(); if (localDecl != null) { var varDecl = localDecl.Declaration; this.AnalyzeOwnershipInLocalDeclaration(givenUpSymbol, varDecl, statement, machine, model, trace); } else if (expr != null) { if (expr.Expression is AssignmentExpressionSyntax) { var assignment = expr.Expression as AssignmentExpressionSyntax; this.AnalyzeOwnershipInAssignment(givenUpSymbol, assignment, statement, machine, model, trace); } else if (expr.Expression is InvocationExpressionSyntax || expr.Expression is ObjectCreationExpressionSyntax) { trace.InsertCall(statement.Summary.Method, expr.Expression); this.AnalyzeOwnershipInCall(givenUpSymbol, expr.Expression, statement, machine, model, trace); } } } /// <summary> /// Analyzes the ownership of the given-up symbol /// in the variable declaration. /// </summary> /// <param name="givenUpSymbol">GivenUpOwnershipSymbol</param> /// <param name="varDecl">VariableDeclarationSyntax</param> /// <param name="statement">Statement</param> /// <param name="machine">StateMachine</param> /// <param name="model">SemanticModel</param> /// <param name="trace">TraceInfo</param> protected abstract void AnalyzeOwnershipInLocalDeclaration(GivenUpOwnershipSymbol givenUpSymbol, VariableDeclarationSyntax varDecl, Statement statement, StateMachine machine, SemanticModel model, TraceInfo trace); /// <summary> /// Analyzes the ownership of the given-up symbol /// in the assignment expression. /// </summary> /// <param name="givenUpSymbol">GivenUpOwnershipSymbol</param> /// <param name="assignment">AssignmentExpressionSyntax</param> /// <param name="statement">Statement</param> /// <param name="machine">StateMachine</param> /// <param name="model">SemanticModel</param> /// <param name="trace">TraceInfo</param> protected abstract void AnalyzeOwnershipInAssignment(GivenUpOwnershipSymbol givenUpSymbol, AssignmentExpressionSyntax assignment, Statement statement, StateMachine machine, SemanticModel model, TraceInfo trace); /// <summary> /// Analyzes the ownership of the given-up symbol /// in the call. /// </summary> /// <param name="givenUpSymbol">GivenUpOwnershipSymbol</param> /// <param name="call">ExpressionSyntax</param> /// <param name="statement">Statement</param> /// <param name="machine">StateMachine</param> /// <param name="model">SemanticModel</param> /// <param name="trace">TraceInfo</param> /// <returns>Set of return symbols</returns> protected HashSet<ISymbol> AnalyzeOwnershipInCall(GivenUpOwnershipSymbol givenUpSymbol, ExpressionSyntax call, Statement statement, StateMachine machine, SemanticModel model, TraceInfo trace) { var potentialReturnSymbols = new HashSet<ISymbol>(); var invocation = call as InvocationExpressionSyntax; var objCreation = call as ObjectCreationExpressionSyntax; if ((invocation == null && objCreation == null)) { return potentialReturnSymbols; } TraceInfo callTrace = new TraceInfo(); callTrace.Merge(trace); callTrace.AddErrorTrace(call); var callSymbol = model.GetSymbolInfo(call).Symbol; if (callSymbol == null) { base.ErrorReporter.ReportExternalInvocation(callTrace); return potentialReturnSymbols; } if (callSymbol.ContainingType.ToString().Equals("Microsoft.PSharp.Machine")) { this.AnalyzeOwnershipInGivesUpCall(givenUpSymbol, invocation, statement, machine, model, callTrace); return potentialReturnSymbols; } if (SymbolFinder.FindSourceDefinitionAsync(callSymbol, this.AnalysisContext.Solution).Result == null) { base.ErrorReporter.ReportExternalInvocation(callTrace); return potentialReturnSymbols; } var candidateSummaries = MethodSummary.GetCachedSummaries(callSymbol, statement); foreach (var candidateSummary in candidateSummaries) { this.AnalyzeOwnershipInCandidateCallee(givenUpSymbol, candidateSummary, call, statement, machine, model, callTrace); if (invocation != null) { var resolvedReturnSymbols = candidateSummary.GetResolvedReturnSymbols(invocation, model); foreach (var resolvedReturnSymbol in resolvedReturnSymbols) { potentialReturnSymbols.Add(resolvedReturnSymbol); } } } return potentialReturnSymbols; } /// <summary> /// Analyzes the ownership of the given-up symbol /// in the candidate callee. /// </summary> /// <param name="givenUpSymbol">GivenUpOwnershipSymbol</param> /// <param name="calleeSummary">MethodSummary</param> /// <param name="call">ExpressionSyntax</param> /// <param name="statement">Statement</param> /// <param name="machine">StateMachine</param> /// <param name="model">SemanticModel</param> /// <param name="trace">TraceInfo</param> protected abstract void AnalyzeOwnershipInCandidateCallee(GivenUpOwnershipSymbol givenUpSymbol, MethodSummary calleeSummary, ExpressionSyntax call, Statement statement, StateMachine machine, SemanticModel model, TraceInfo trace); /// <summary> /// Analyzes the ownership of the given-up symbol /// in the gives-up operation. /// </summary> /// <param name="givenUpSymbol">GivenUpOwnershipSymbol</param> /// <param name="call">Gives-up call</param> /// <param name="statement">Statement</param> /// <param name="machine">StateMachine</param> /// <param name="model">SemanticModel</param> /// <param name="trace">TraceInfo</param> protected abstract void AnalyzeOwnershipInGivesUpCall(GivenUpOwnershipSymbol givenUpSymbol, InvocationExpressionSyntax call, Statement statement, StateMachine machine, SemanticModel model, TraceInfo trace); #endregion #region private methods /// <summary> /// Analyzes the method summaries of the machine to check if /// each summary respects given-up ownerships. /// </summary> /// <param name="machine">StateMachine</param> private void AnalyzeMethodSummariesInMachine(StateMachine machine) { foreach (var summary in machine.MethodSummaries.Values) { foreach (var givenUpSymbol in summary.GetSymbolsWithGivenUpOwnership()) { TraceInfo trace = new TraceInfo(summary.Method, machine, null, givenUpSymbol.ContainingSymbol); trace.AddErrorTrace(givenUpSymbol.Statement.SyntaxNode); var model = this.AnalysisContext.Compilation.GetSemanticModel( givenUpSymbol.Statement.SyntaxNode.SyntaxTree); this.AnalyzeOwnershipInControlFlowGraph(givenUpSymbol, machine, model, trace); } } } #endregion #region helper methods /// <summary> /// Returns true if the field symbol is being accessed /// in a successor summary. /// </summary> /// <param name="fieldSymbol">IFieldSymbol</param> /// <param name="summary">MethodSummary</param> /// <param name="machine">StateMachine</param> /// <returns>Boolean</returns> protected bool IsFieldAccessedInSuccessor(IFieldSymbol fieldSymbol, MethodSummary summary, StateMachine machine) { if (!base.Configuration.DoStateTransitionAnalysis) { return true; } var successors = machine.GetSuccessorSummaries(summary); foreach (var successor in successors) { if (successor.SideEffectsInfo.FieldAccesses.ContainsKey(fieldSymbol)) { return true; } } return false; } /// <summary> /// Extracts arguments from the list of arguments. /// </summary> /// <param name="arguments">List of arguments</param> /// <returns>List of arguments</returns> protected List<ExpressionSyntax> ExtractArguments(List<ExpressionSyntax> arguments) { var args = new List<ExpressionSyntax>(); foreach (var arg in arguments) { if (arg is ObjectCreationExpressionSyntax) { var objCreation = arg as ObjectCreationExpressionSyntax; List<ExpressionSyntax> argExprs = new List<ExpressionSyntax>(); foreach (var objCreationArg in objCreation.ArgumentList.Arguments) { argExprs.Add(objCreationArg.Expression); } var objCreationArgs = this.ExtractArguments(argExprs); foreach (var objCreationArg in objCreationArgs) { args.Add(objCreationArg); } } else if (arg is InvocationExpressionSyntax) { var invocation = arg as InvocationExpressionSyntax; List<ExpressionSyntax> argExprs = new List<ExpressionSyntax>(); foreach (var invocationArg in invocation.ArgumentList.Arguments) { argExprs.Add(invocationArg.Expression); } var invocationArgs = this.ExtractArguments(argExprs); foreach (var invocationArg in invocationArgs) { args.Add(invocationArg); } } else if (!(arg is LiteralExpressionSyntax)) { args.Add(arg); } } return args; } #endregion } }
41.546448
115
0.588189
[ "MIT" ]
chandramouleswaran/PSharp
Source/StaticAnalysis/Analyses/Ownership/OwnershipAnalysisPass.cs
15,208
C#
using System; namespace GrandPrix.CustomExceptions { public class BlownTyreException : Exception { public BlownTyreException(string message) : base(message) { } } }
16.916667
65
0.64532
[ "MIT" ]
kovachevmartin/SoftUni
CSharp-OOP/Exams/Basics_05-Sept-2017_GrandPrix/GrandPrix/CustomExceptions/BlownTyreException.cs
205
C#
using System.Text.Json.Serialization; namespace Pandorax.UKVehicleData.Models { public class FirstYear { /// <summary> /// Six month VED rate for first year after a new vehicle is registered. /// </summary> [JsonPropertyName("SixMonth")] public double? SixMonth { get; set; } /// <summary> /// Twelve month VED rate for first year after a new vehicle is registered. /// </summary> [JsonPropertyName("TwelveMonth")] public double? TwelveMonth { get; set; } } }
27.7
83
0.604693
[ "MIT" ]
Pandorax100/UKVehicleData
src/Pandorax.UKVehicleData/Models/FirstYear.cs
554
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.MachineLearningServices.V20181119.Outputs { [OutputType] public sealed class DataFactoryResponse { /// <summary> /// Location for the underlying compute /// </summary> public readonly string? ComputeLocation; /// <summary> /// The type of compute /// Expected value is 'DataFactory'. /// </summary> public readonly string ComputeType; /// <summary> /// The date and time when the compute was created. /// </summary> public readonly string CreatedOn; /// <summary> /// The description of the Machine Learning compute. /// </summary> public readonly string? Description; /// <summary> /// Indicating whether the compute was provisioned by user and brought from outside if true, or machine learning service provisioned it if false. /// </summary> public readonly bool IsAttachedCompute; /// <summary> /// The date and time when the compute was last modified. /// </summary> public readonly string ModifiedOn; /// <summary> /// Errors during provisioning /// </summary> public readonly ImmutableArray<Outputs.MachineLearningServiceErrorResponse> ProvisioningErrors; /// <summary> /// The provision state of the cluster. Valid values are Unknown, Updating, Provisioning, Succeeded, and Failed. /// </summary> public readonly string ProvisioningState; /// <summary> /// ARM resource id of the underlying compute /// </summary> public readonly string? ResourceId; [OutputConstructor] private DataFactoryResponse( string? computeLocation, string computeType, string createdOn, string? description, bool isAttachedCompute, string modifiedOn, ImmutableArray<Outputs.MachineLearningServiceErrorResponse> provisioningErrors, string provisioningState, string? resourceId) { ComputeLocation = computeLocation; ComputeType = computeType; CreatedOn = createdOn; Description = description; IsAttachedCompute = isAttachedCompute; ModifiedOn = modifiedOn; ProvisioningErrors = provisioningErrors; ProvisioningState = provisioningState; ResourceId = resourceId; } } }
33.104651
153
0.621005
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/MachineLearningServices/V20181119/Outputs/DataFactoryResponse.cs
2,847
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.dg.Transform; using Aliyun.Acs.dg.Transform.V20190327; namespace Aliyun.Acs.dg.Model.V20190327 { public class CreateGatewayRequest : RpcAcsRequest<CreateGatewayResponse> { public CreateGatewayRequest() : base("dg", "2019-03-27", "CreateGateway", "dg", "openAPI") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Aliyun.Acs.dg.Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Aliyun.Acs.dg.Endpoint.endpointRegionalType, null); } Protocol = ProtocolType.HTTPS; Method = MethodType.POST; } private string gatewayDesc; private string gatewayName; public string GatewayDesc { get { return gatewayDesc; } set { gatewayDesc = value; DictionaryUtil.Add(BodyParameters, "GatewayDesc", value); } } public string GatewayName { get { return gatewayName; } set { gatewayName = value; DictionaryUtil.Add(BodyParameters, "GatewayName", value); } } public override CreateGatewayResponse GetResponse(UnmarshallerContext unmarshallerContext) { return CreateGatewayResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
30.5375
134
0.688498
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-dg/Dg/Model/V20190327/CreateGatewayRequest.cs
2,443
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 neptune-2014-10-31.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.Neptune.Model { /// <summary> /// Container for the parameters to the CopyDBParameterGroup operation. /// Copies the specified DB parameter group. /// </summary> public partial class CopyDBParameterGroupRequest : AmazonNeptuneRequest { private string _sourceDBParameterGroupIdentifier; private List<Tag> _tags = new List<Tag>(); private string _targetDBParameterGroupDescription; private string _targetDBParameterGroupIdentifier; /// <summary> /// Gets and sets the property SourceDBParameterGroupIdentifier. /// <para> /// The identifier or ARN for the source DB parameter group. For information about creating /// an ARN, see <a href="https://docs.aws.amazon.com/neptune/latest/UserGuide/tagging.ARN.html#tagging.ARN.Constructing"> /// Constructing an Amazon Resource Name (ARN)</a>. /// </para> /// /// <para> /// Constraints: /// </para> /// <ul> <li> /// <para> /// Must specify a valid DB parameter group. /// </para> /// </li> <li> /// <para> /// Must specify a valid DB parameter group identifier, for example <code>my-db-param-group</code>, /// or a valid ARN. /// </para> /// </li> </ul> /// </summary> [AWSProperty(Required=true)] public string SourceDBParameterGroupIdentifier { get { return this._sourceDBParameterGroupIdentifier; } set { this._sourceDBParameterGroupIdentifier = value; } } // Check to see if SourceDBParameterGroupIdentifier property is set internal bool IsSetSourceDBParameterGroupIdentifier() { return this._sourceDBParameterGroupIdentifier != null; } /// <summary> /// Gets and sets the property Tags. /// <para> /// The tags to be assigned to the copied DB parameter group. /// </para> /// </summary> public List<Tag> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } /// <summary> /// Gets and sets the property TargetDBParameterGroupDescription. /// <para> /// A description for the copied DB parameter group. /// </para> /// </summary> [AWSProperty(Required=true)] public string TargetDBParameterGroupDescription { get { return this._targetDBParameterGroupDescription; } set { this._targetDBParameterGroupDescription = value; } } // Check to see if TargetDBParameterGroupDescription property is set internal bool IsSetTargetDBParameterGroupDescription() { return this._targetDBParameterGroupDescription != null; } /// <summary> /// Gets and sets the property TargetDBParameterGroupIdentifier. /// <para> /// The identifier for the copied DB parameter group. /// </para> /// /// <para> /// Constraints: /// </para> /// <ul> <li> /// <para> /// Cannot be null, empty, or blank. /// </para> /// </li> <li> /// <para> /// Must contain from 1 to 255 letters, numbers, or hyphens. /// </para> /// </li> <li> /// <para> /// First character must be a letter. /// </para> /// </li> <li> /// <para> /// Cannot end with a hyphen or contain two consecutive hyphens. /// </para> /// </li> </ul> /// <para> /// Example: <code>my-db-parameter-group</code> /// </para> /// </summary> [AWSProperty(Required=true)] public string TargetDBParameterGroupIdentifier { get { return this._targetDBParameterGroupIdentifier; } set { this._targetDBParameterGroupIdentifier = value; } } // Check to see if TargetDBParameterGroupIdentifier property is set internal bool IsSetTargetDBParameterGroupIdentifier() { return this._targetDBParameterGroupIdentifier != null; } } }
34.613924
130
0.571585
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/Neptune/Generated/Model/CopyDBParameterGroupRequest.cs
5,469
C#
using System; using Abp; using Abp.Authorization; using Abp.Dependency; using Abp.UI; namespace MellowoodMedical.MyTest.Authorization { public class AbpLoginResultTypeHelper : AbpServiceBase, ITransientDependency { public AbpLoginResultTypeHelper() { LocalizationSourceName = MyTestConsts.LocalizationSourceName; } public Exception CreateExceptionForFailedLoginAttempt(AbpLoginResultType result, string usernameOrEmailAddress, string tenancyName) { switch (result) { case AbpLoginResultType.Success: return new Exception("Don't call this method with a success result!"); case AbpLoginResultType.InvalidUserNameOrEmailAddress: case AbpLoginResultType.InvalidPassword: return new UserFriendlyException(L("LoginFailed"), L("InvalidUserNameOrPassword")); case AbpLoginResultType.InvalidTenancyName: return new UserFriendlyException(L("LoginFailed"), L("ThereIsNoTenantDefinedWithName{0}", tenancyName)); case AbpLoginResultType.TenantIsNotActive: return new UserFriendlyException(L("LoginFailed"), L("TenantIsNotActive", tenancyName)); case AbpLoginResultType.UserIsNotActive: return new UserFriendlyException(L("LoginFailed"), L("UserIsNotActiveAndCanNotLogin", usernameOrEmailAddress)); case AbpLoginResultType.UserEmailIsNotConfirmed: return new UserFriendlyException(L("LoginFailed"), L("UserEmailIsNotConfirmedAndCanNotLogin")); case AbpLoginResultType.LockedOut: return new UserFriendlyException(L("LoginFailed"), L("UserLockedOutMessage")); default: // Can not fall to default actually. But other result types can be added in the future and we may forget to handle it Logger.Warn("Unhandled login fail reason: " + result); return new UserFriendlyException(L("LoginFailed")); } } public string CreateLocalizedMessageForFailedLoginAttempt(AbpLoginResultType result, string usernameOrEmailAddress, string tenancyName) { switch (result) { case AbpLoginResultType.Success: throw new Exception("Don't call this method with a success result!"); case AbpLoginResultType.InvalidUserNameOrEmailAddress: case AbpLoginResultType.InvalidPassword: return L("InvalidUserNameOrPassword"); case AbpLoginResultType.InvalidTenancyName: return L("ThereIsNoTenantDefinedWithName{0}", tenancyName); case AbpLoginResultType.TenantIsNotActive: return L("TenantIsNotActive", tenancyName); case AbpLoginResultType.UserIsNotActive: return L("UserIsNotActiveAndCanNotLogin", usernameOrEmailAddress); case AbpLoginResultType.UserEmailIsNotConfirmed: return L("UserEmailIsNotConfirmedAndCanNotLogin"); default: // Can not fall to default actually. But other result types can be added in the future and we may forget to handle it Logger.Warn("Unhandled login fail reason: " + result); return L("LoginFailed"); } } } }
53.446154
143
0.645941
[ "MIT" ]
ravvikt/MellowoodMedical.MyTest
src/MellowoodMedical.MyTest.Application/Authorization/AbpLoginResultTypeHelper.cs
3,476
C#
using System; using Common.Log; using Lykke.Common.Log; namespace Lykke.Service.PaySign.Client { public class PaySignClient : IPaySignClient, IDisposable { private readonly ILog _log; public PaySignClient(string serviceUrl, ILogFactory logFactory) { _log = logFactory.CreateLog(this); } public void Dispose() { //if (_service == null) // return; //_service.Dispose(); //_service = null; } } }
21.12
71
0.5625
[ "MIT" ]
LykkeCity/Lykke.Service.PaySign
client/Lykke.Service.PaySign.Client/PaySignClient.cs
530
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ResponsiveGridSample2.Wpf.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
34.83871
151
0.586111
[ "MIT" ]
sourcechord/ResponsiveGrid
Sample/ResponsiveGridSample2.Wpf/Properties/Settings.Designer.cs
1,082
C#
using System.Text.Json.Serialization; namespace Essensoft.AspNetCore.Payment.Alipay.Response { /// <summary> /// MybankCreditUserRoleCreateResponse. /// </summary> public class MybankCreditUserRoleCreateResponse : AlipayResponse { /// <summary> /// 参与者 /// </summary> [JsonPropertyName("ip_id")] public string IpId { get; set; } /// <summary> /// 参与者会员角色号 /// </summary> [JsonPropertyName("ip_role_id")] public string IpRoleId { get; set; } } }
24
68
0.583333
[ "MIT" ]
LuohuaRain/payment
src/Essensoft.AspNetCore.Payment.Alipay/Response/MybankCreditUserRoleCreateResponse.cs
576
C#
using System; using System.Windows; using static System.Math; namespace VSimulator { public sealed class VPlotterModel { public Size DrawingArea { get; } public Point GondolaPosition { get; private set; } public event EventHandler GondolaPositionChanged; public double StepLength { get; set; } = 10; public Point LeftHookLocation => new Point(x: 0, y: 0); public Point RightHookLocation => new Point(x: DrawingArea.Width, y: 0); public VPlotterModel(Size area) { if (area.Height <= 0) throw new ArgumentException(nameof(area)); if (area.Width <= 0) throw new ArgumentException(nameof(area)); DrawingArea = area; GondolaPosition = new Point(x: area.Width / 2, y: area.Height / 2); } private static double Square(double value) => value * value; public double LeftHypo { get => Sqrt(Square(GondolaPosition.X) + Square(GondolaPosition.Y)); private set => UpdateGondolaPosition(value, RightHypo); } public double RightHypo { get => Sqrt(Square(DrawingArea.Width - GondolaPosition.X) + Square(GondolaPosition.Y)); private set => UpdateGondolaPosition(LeftHypo, value); } private void UpdateGondolaPosition(double leftHypo, double rightHypo) { if (leftHypo <= 0) throw new ArgumentOutOfRangeException(nameof(leftHypo)); if (rightHypo <= 0) throw new ArgumentOutOfRangeException(nameof(rightHypo)); var widthSquared = Square(DrawingArea.Width); var leftHypoSquared = Square(leftHypo); var rightHypoSquared = Square(rightHypo); var ySquared = 0.5 * (leftHypoSquared + rightHypoSquared - 0.5 * (widthSquared + Square(leftHypoSquared - rightHypoSquared) / widthSquared)); var xSquared = leftHypoSquared - ySquared; var newPosition = new Point(x: Sqrt(xSquared), y: Sqrt(ySquared)); GondolaPosition = newPosition; GondolaPositionChanged?.Invoke(this, EventArgs.Empty); } public void DoStep(Stepper stepper, Direction direction) { var delta = direction == Direction.Forward ? +StepLength : -StepLength; switch (stepper) { case Stepper.Left: LeftHypo += delta; break; case Stepper.Right: RightHypo += delta; break; default: throw new ArgumentOutOfRangeException(nameof(stepper)); } } } public enum Stepper { Left, Right } public enum Direction { Forward, Backward } }
29.493976
147
0.674837
[ "MIT" ]
controlflow/vplotter
vsimulator/VPlotterModel.cs
2,448
C#
using Abp.Application.Services.Dto; using Abp.AutoMapper; using Abp.Authorization; namespace Don2018.PhonebookSpa.Roles.Dto { [AutoMapFrom(typeof(Permission))] public class PermissionDto : EntityDto<long> { public string Name { get; set; } public string DisplayName { get; set; } public string Description { get; set; } } }
21.588235
48
0.678474
[ "MIT" ]
antgerasim/DonPhonebookSpaCore2018
aspnet-core/src/Don2018.PhonebookSpa.Application/Roles/Dto/PermissionDto.cs
367
C#
using System.Collections.Generic; namespace ET { /// <summary> /// When the server is in this state, the server make preparation that the game needs. /// The playerIndex is arranged in this state, so is the settings. Messages will be sent to clients to inform the information. /// Transfers to RoundStartState. The state transfer will be done regardless whether enough client responds received. /// </summary> public class GamePrepareState : ServerState { private HashSet<long> responds; private long timerId; public void Init() { responds = new HashSet<long>(); } public void Destroy() { TimerComponent.Instance.Remove(timerId); timerId = 0; responds = null; } public override void OnServerStateEnter() { timerId = TimerComponent.Instance.NewOnceTimer(TimeHelper.ServerNow() + 5000, TimeOutRoundStart); CurrentRoundStatus.ShufflePlayers(); AssignInitialPoints(); for (int index = 0; index < players.Count; index++) { //var tiles = CurrentRoundStatus.HandTiles(index); //Log.Debug($"[Server] Hand tiles of player {index}: {string.Join("", tiles)}"); var info = new M2C_GamePrepare { PlayerIndex = index, Points = CurrentRoundStatus.Points, PlayerNames = CurrentRoundStatus.PlayerNames, Settings=CurrentRoundStatus.GameSettings }; Game.EventSystem.Publish(new EventType.ActorMessage() { actorId=players[index],actorMessage=info }).Coroutine(); } } public override void OnServerStateExit() { responds.Clear(); TimerComponent.Instance.Remove(timerId); timerId = 0; } private void AssignInitialPoints() { for (int i = 0; i < players.Count; i++) { CurrentRoundStatus.SetPoints(CurrentRoundStatus.GameSettings.InitialPoints); } } public void TimeOutRoundStart() { Log.Debug("[Server] Prepare state time out"); if (GetParent<MahjoneBehaviourComponent>().IsBattleMod) { GetParent<MahjoneBehaviourComponent>().SelectTiles(); } else { GetParent<MahjoneBehaviourComponent>().RoundStart(true, false, false); } } public void OnEvent(long playerid) { responds.Add(playerid); if (responds.Count == totalPlayers) { Log.Debug("[Server] Prepare state MaxPlayer"); TimeOutRoundStart(); } } } }
34.141176
130
0.548587
[ "MIT" ]
wryl/MahjoneET
Server/Model/Mahjone/Controller/GameState/GamePrepareState.cs
2,902
C#
using System; namespace Xms.Plugin { public interface IEntityPluginDeleter { bool DeleteById(params Guid[] id); bool DeleteByEntityId(Guid entityId); } }
16.727273
45
0.663043
[ "MIT" ]
861191244/xms
Libraries/Plugin/Xms.Plugin/IEntityPluginDeleter.cs
186
C#
//------------------ //-- Create By lookchem 3.0 //-- File: Dal/Base/DalW_Intention.cs //-- 2020/5/8 16:32:13 //------------------ using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.SqlClient; using Model; using DBUtility; namespace Dal.Base.HardwareMall { public abstract class DalW_Intention:HardwareMallBase { public DalW_Intention():base() { } public DalW_Intention(ESqlConnType eSqlConnType) : base(eSqlConnType) { } /// <summary> /// 实例化一个当前数据操作对象 /// </summary> /// <returns></returns> public static Dal.HardwareMall.DalW_Intention Instance() { return new Dal.HardwareMall.DalW_Intention(); } /// <summary> /// 增加记录并且返回当前信息ID /// </summary> /// <param name="w_Intention">Model.HardwareMall.ModW_Intention</param> /// <returns>成功返回当前插入ID,失败返回0</returns> public virtual int Add(Model.HardwareMall.ModW_Intention model) { string sql = "insert into dbo.W_Intention ([Name],[ContactDetails],[Remark],[CreateTime],[ProcessStatus],[ProcessRemark],[ProcessTime])values(@Name,@ContactDetails,@Remark,@CreateTime,@ProcessStatus,@ProcessRemark,@ProcessTime);select SCOPE_IDENTITY() as InsertId"; SqlParameter[] parameters = { new SqlParameter("@Name",SqlDbType.VarChar,255), new SqlParameter("@ContactDetails",SqlDbType.VarChar,-1), new SqlParameter("@Remark",SqlDbType.VarChar,-1), new SqlParameter("@CreateTime",SqlDbType.DateTime), new SqlParameter("@ProcessStatus",SqlDbType.TinyInt,1), new SqlParameter("@ProcessRemark",SqlDbType.VarChar,-1), new SqlParameter("@ProcessTime",SqlDbType.DateTime) }; parameters[0].Value = model.Name ; parameters[1].Value = model.ContactDetails ; parameters[2].Value = model.Remark ; parameters[3].Value = model.CreateTime ; parameters[4].Value = model.ProcessStatus ; parameters[5].Value = model.ProcessRemark ; parameters[6].Value = model.ProcessTime ; object insertId = this.ExecuteScalar(sql, DB.ReadAndWrite, parameters); if(insertId==null){ return 0; } else{ return int.Parse(insertId.ToString()); } } /// <summary> /// 增加记录,返回成功或失败 /// </summary> /// <param name="w_Intention">Model.HardwareMall.ModW_Intention</param> /// <returns>成功返回True,错误返回False</returns> public virtual bool AddNoReturn(Model.HardwareMall.ModW_Intention model) { string sql = "insert into dbo.W_Intention ([Name],[ContactDetails],[Remark],[CreateTime],[ProcessStatus],[ProcessRemark],[ProcessTime])values(@Name,@ContactDetails,@Remark,@CreateTime,@ProcessStatus,@ProcessRemark,@ProcessTime)"; SqlParameter[] parameters = { new SqlParameter("@Name",SqlDbType.VarChar,255), new SqlParameter("@ContactDetails",SqlDbType.VarChar,-1), new SqlParameter("@Remark",SqlDbType.VarChar,-1), new SqlParameter("@CreateTime",SqlDbType.DateTime), new SqlParameter("@ProcessStatus",SqlDbType.TinyInt,1), new SqlParameter("@ProcessRemark",SqlDbType.VarChar,-1), new SqlParameter("@ProcessTime",SqlDbType.DateTime) }; parameters[0].Value = model.Name ; parameters[1].Value = model.ContactDetails ; parameters[2].Value = model.Remark ; parameters[3].Value = model.CreateTime ; parameters[4].Value = model.ProcessStatus ; parameters[5].Value = model.ProcessRemark ; parameters[6].Value = model.ProcessTime ; if(this.ExecuteNonQuery(sql, DB.ReadAndWrite, parameters)>0){ return true; } else{ return false; } } /// <summary> /// 更新记录 /// </summary> /// <param name="w_Intention">Model.HardwareMall.ModW_Intention</param> /// <returns>成功True ,失败False</returns> public virtual bool Update(Model.HardwareMall.ModW_Intention model) { string sql = @"update dbo.W_Intention set [Name] = @Name ,[ContactDetails] = @ContactDetails ,[Remark] = @Remark ,[CreateTime] = @CreateTime ,[ProcessStatus] = @ProcessStatus ,[ProcessRemark] = @ProcessRemark ,[ProcessTime] = @ProcessTime where [Id]=@Id"; SqlParameter[] parameters = { new SqlParameter("@Id",SqlDbType.Int,4), new SqlParameter("@Name",SqlDbType.VarChar,255), new SqlParameter("@ContactDetails",SqlDbType.VarChar,-1), new SqlParameter("@Remark",SqlDbType.VarChar,-1), new SqlParameter("@CreateTime",SqlDbType.DateTime), new SqlParameter("@ProcessStatus",SqlDbType.TinyInt,1), new SqlParameter("@ProcessRemark",SqlDbType.VarChar,-1), new SqlParameter("@ProcessTime",SqlDbType.DateTime) }; parameters[0].Value = model.Id ; parameters[1].Value = model.Name ; parameters[2].Value = model.ContactDetails ; parameters[3].Value = model.Remark ; parameters[4].Value = model.CreateTime ; parameters[5].Value = model.ProcessStatus ; parameters[6].Value = model.ProcessRemark ; parameters[7].Value = model.ProcessTime ; if(this.ExecuteNonQuery(sql, DB.ReadAndWrite, parameters)>0){ return true; } else{ return false; } } /// <summary> /// 更新记录 /// </summary> /// <param name="keyValue">Dictionary<string, object> keyValue</param> /// <param name="id">更新记录ID</param> /// <returns>成功True ,失败False</returns> public virtual bool Update(Dictionary<string, object> keyValue, int id) { string sql = "update dbo.W_Intention set "; SqlParameter[] param = new SqlParameter[keyValue.Count]; int i = 0; foreach (KeyValuePair<string, object> item in keyValue) { sql += string.Format("{0}=@{0},", item.Key); param[i] = new SqlParameter("@" + item.Key, item.Value); i++; } sql = sql.TrimEnd(',') + " where Id=" + id.ToString(); if (this.ExecuteNonQuery(sql, DB.ReadAndWrite, param) > 0) { return true; } else { return false; } } /// <summary> /// 设置Bit类型字段的值 /// </summary> /// <param name="fieldName">字段名</param> /// <param name="setValue">要设的值</param> /// <param name="id">信息ID</param> /// <returns>true or false</returns> public bool UpdateBitField(string fieldName, bool setValue, int id) { string sql = string.Format("update dbo.W_Intention set {0} = @SetValue where [Id]=@Id", fieldName); SqlParameter[] parameters = { new SqlParameter("@SetValue", SqlDbType.Bit,1), new SqlParameter("@Id", SqlDbType.Int,4) }; parameters[0].Value = setValue; parameters[1].Value = id; if (this.ExecuteNonQuery(sql, DB.ReadAndWrite, parameters) > 0) { return true; } else { return false; } } /// <summary> /// 删除记录 /// </summary> /// <param name="id">id</param> /// <returns>True or False</returns> public virtual bool Delete(int id) { string sql = @"delete from dbo.W_Intention where [Id]=@Id"; SqlParameter[] parameters = { new SqlParameter("@Id", SqlDbType.Int) }; parameters[0].Value = id; if(this.ExecuteNonQuery(sql, DB.ReadAndWrite, parameters)>0){ return true; } else{ return false; } } /// <summary> /// 根据Id取得一条记录 /// </summary> /// <param name="id">id</param> /// <returns>无记录或出错返回 null,有记录返回一个Model</returns> public virtual Model.HardwareMall.ModW_Intention GetModel(int id) { string sql = @"select * from dbo.W_Intention where [Id]=@Id"; SqlParameter[] parameters = { new SqlParameter("@Id", SqlDbType.Int) }; parameters[0].Value = id; using (SqlDataReader reader = this.ExecuteReader(sql, parameters)) { Model.HardwareMall.ModW_Intention model = null; if (reader.Read()) { model = new Model.HardwareMall.ModW_Intention(); if(reader["Id"]!= System.DBNull.Value) {model.Id = System.Int32.Parse(reader["Id"].ToString());} model.Name = reader["Name"].ToString(); model.ContactDetails = reader["ContactDetails"].ToString(); model.Remark = reader["Remark"].ToString(); if(reader["CreateTime"]!= System.DBNull.Value) {model.CreateTime = System.DateTime.Parse(reader["CreateTime"].ToString());} if(reader["ProcessStatus"]!= System.DBNull.Value) {model.ProcessStatus = System.Byte.Parse(reader["ProcessStatus"].ToString());} model.ProcessRemark = reader["ProcessRemark"].ToString(); if(reader["ProcessTime"]!= System.DBNull.Value) {model.ProcessTime = System.DateTime.Parse(reader["ProcessTime"].ToString());} } reader.Close(); return model; } } /// <summary> /// 根据Id和字段名取得一条记录 /// </summary> /// <param name="id">id</param> /// <param name="cols">需要获取的字段,例:"id,name,classid"</param> /// <returns>无记录或出错返回 null,有记录返回一个Model</returns> public virtual Model.HardwareMall.ModW_Intention GetModel(int id,string cols) { cols = cols.ToLower(); string sql = @"select "+cols+" from dbo.W_Intention where [Id]=@Id"; cols = "," + cols + ","; SqlParameter[] parameters = { new SqlParameter("@Id", SqlDbType.Int) }; parameters[0].Value = id; using (SqlDataReader reader = this.ExecuteReader(sql, parameters)) { Model.HardwareMall.ModW_Intention model = null; if (reader.Read()) { model = new Model.HardwareMall.ModW_Intention(); if(cols.IndexOf(",Id,".ToLower())>=0){if(reader["Id"]!= System.DBNull.Value) {model.Id = System.Int32.Parse(reader["Id"].ToString());}} if(cols.IndexOf(",Name,".ToLower())>=0){model.Name = reader["Name"].ToString();} if(cols.IndexOf(",ContactDetails,".ToLower())>=0){model.ContactDetails = reader["ContactDetails"].ToString();} if(cols.IndexOf(",Remark,".ToLower())>=0){model.Remark = reader["Remark"].ToString();} if(cols.IndexOf(",CreateTime,".ToLower())>=0){if(reader["CreateTime"]!= System.DBNull.Value) {model.CreateTime = System.DateTime.Parse(reader["CreateTime"].ToString());}} if(cols.IndexOf(",ProcessStatus,".ToLower())>=0){if(reader["ProcessStatus"]!= System.DBNull.Value) {model.ProcessStatus = System.Byte.Parse(reader["ProcessStatus"].ToString());}} if(cols.IndexOf(",ProcessRemark,".ToLower())>=0){model.ProcessRemark = reader["ProcessRemark"].ToString();} if(cols.IndexOf(",ProcessTime,".ToLower())>=0){if(reader["ProcessTime"]!= System.DBNull.Value) {model.ProcessTime = System.DateTime.Parse(reader["ProcessTime"].ToString());}} } reader.Close(); return model; } } /// <summary> /// 获取列表记录 /// </summary> /// <param name="top">获取记录条数(不限则为0)</param> /// <param name="col">需要获取的字段</param> /// <param name="where">where条件,不带where关键字.例: classid = 1</param> /// <param name="orderby">order by 条件,不带order by</param> /// <returns></returns> public DataTable GetSelectList(int top,string col, string where, string orderby) { string selectTop = ""; if(top<0) {top=0;} if (top > 0) {selectTop = " top " + top.ToString();} if (string.IsNullOrEmpty(col)) { col = "*"; } if (!string.IsNullOrEmpty(where)) { where = " where " + where; } if (!string.IsNullOrEmpty(orderby)) { orderby = " order by " + orderby; } string sql = string.Format("select {3} {0} from dbo.W_Intention {1} {2}", col, where, orderby,selectTop); DataTable dt = this.ExecuteDataset(sql).Tables[0]; return dt; } } }
35.757493
277
0.559704
[ "Apache-2.0" ]
THAyou/HardWareMall
HardwareMall.DAL/Base/HardwareMall/W/DalW_Intention.cs
13,515
C#
using Abp.Authorization.Users; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.Linq; using Abp.Organizations; using Senior.Boilerplate.Authorization.Roles; namespace Senior.Boilerplate.Authorization.Users { public class UserStore : AbpUserStore<Role, User> { public UserStore( IUnitOfWorkManager unitOfWorkManager, IRepository<User, long> userRepository, IRepository<Role> roleRepository, IRepository<UserRole, long> userRoleRepository, IRepository<UserLogin, long> userLoginRepository, IRepository<UserClaim, long> userClaimRepository, IRepository<UserPermissionSetting, long> userPermissionSettingRepository, IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository, IRepository<OrganizationUnitRole, long> organizationUnitRoleRepository) : base(unitOfWorkManager, userRepository, roleRepository, userRoleRepository, userLoginRepository, userClaimRepository, userPermissionSettingRepository, userOrganizationUnitRepository, organizationUnitRoleRepository ) { } } }
36.555556
85
0.651976
[ "MIT" ]
seniorpe/dotnet-angular-react-vue
aspnet-core/src/Senior.Boilerplate.Core/Authorization/Users/UserStore.cs
1,316
C#
using System; using System.Buffers; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using HedgeModManager.Annotations; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Newtonsoft.Json; namespace HedgeModManager.Misc { public static class Extensions { public static int GetDeterministicHashCode(this string str) { unchecked { int hash1 = (5381 << 16) + 5381; int hash2 = hash1; for (int i = 0; i < str.Length; i += 2) { hash1 = ((hash1 << 5) + hash1) ^ str[i]; if (i == str.Length - 1) break; hash2 = ((hash2 << 5) + hash2) ^ str[i + 1]; } return hash1 + (hash2 * 1566083941); } } #region https://stackoverflow.com/a/31941159 /// <summary> /// Returns true if <paramref name="path"/> starts with the path <paramref name="baseDirPath"/>. /// The comparison is case-insensitive, handles / and \ slashes as folder separators and /// only matches if the base dir folder name is matched exactly ("c:\foobar\file.txt" is not a sub path of "c:\foo"). /// </summary> public static bool IsSubPathOf(this string path, string baseDirPath) { string normalizedPath = Path.GetFullPath(path.Replace('/', '\\') .WithEnding("\\")); string normalizedBaseDirPath = Path.GetFullPath(baseDirPath.Replace('/', '\\') .WithEnding("\\")); return normalizedPath.StartsWith(normalizedBaseDirPath, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Returns <paramref name="str"/> with the minimal concatenation of <paramref name="ending"/> (starting from end) that /// results in satisfying .EndsWith(ending). /// </summary> /// <example>"hel".WithEnding("llo") returns "hello", which is the result of "hel" + "lo".</example> public static string WithEnding([CanBeNull] this string str, string ending) { if (str == null) return ending; string result = str; // Right() is 1-indexed, so include these cases // * Append no characters // * Append up to N characters, where N is ending length for (int i = 0; i <= ending.Length; i++) { string tmp = result + ending.Right(i); if (tmp.EndsWith(ending)) return tmp; } return result; } /// <summary>Gets the rightmost <paramref name="length" /> characters from a string.</summary> /// <param name="value">The string to retrieve the substring from.</param> /// <param name="length">The number of characters to retrieve.</param> /// <returns>The substring.</returns> public static string Right([NotNull] this string value, int length) { if (value == null) { throw new ArgumentNullException("value"); } if (length < 0) { throw new ArgumentOutOfRangeException("length", length, "Length is less than zero"); } return (length < value.Length) ? value.Substring(value.Length - length) : value; } #endregion public static IEnumerable<TSource> DistinctBy<TSource, TKey> (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { HashSet<TKey> seenKeys = new HashSet<TKey>(); foreach (TSource element in source) { if (seenKeys.Add(keySelector(element))) { yield return element; } } } public static async Task<T> GetAsJsonAsync<T>(this HttpClient client, string uri) { try { string result = await client.GetStringAsync(uri); return JsonConvert.DeserializeObject<T>(result); } catch { return default; } } public static async Task CopyToAsync(this HttpContent content, Stream destination, IProgress<double?> progress, CancellationToken cancellationToken = default) { progress?.Report(null); using (var source = await content.ReadAsStreamAsync().ConfigureAwait(false)) { // adapted from CoreFX // https://source.dot.net/#System.Private.CoreLib/Stream.cs,8048a9680abdd13b if (source is null) throw new ArgumentNullException(nameof(source)); if (destination is null) throw new ArgumentNullException(nameof(destination)); var contentLength = content.Headers.ContentLength; var bufferLength = 65536; // 64K seams reasonable? var buffer = ArrayPool<byte>.Shared.Rent(bufferLength); // prevents allocation of garbage arrays try { int bytesRead; int totalBytes = 0; while ((bytesRead = await source.ReadAsync(buffer, 0, bufferLength, cancellationToken).ConfigureAwait(false)) != 0) { totalBytes += bytesRead; await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false); if (contentLength.HasValue) { progress?.Report((double)totalBytes / contentLength.Value); } else { progress?.Report(null); } } } finally { ArrayPool<byte>.Shared.Return(buffer); } } } public static async Task DownloadFileAsync(this HttpClient client, string url, string filePath, IProgress<double?> progress = null, CancellationToken cancellationToken = default) { using var httpResponse = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); httpResponse.EnsureSuccessStatusCode(); using var outputFile = File.Create(filePath, 8192, FileOptions.Asynchronous); await httpResponse.Content.CopyToAsync(outputFile, progress, cancellationToken).ConfigureAwait(false); } public static int Clamp(this int value, int min, int max) { if (value > max) return max; if (value < min) return min; else return value; } public static float Clamp(this float value, float min, float max) { if (value > max) return max; if (value < min) return min; else return value; } public static double Clamp(this double value, double min, double max) { if (value > max) return max; if (value < min) return min; else return value; } } public static class SyntaxFactoryEx { private static Dictionary<string, TypeSyntax> mTypeSyntaxes = new Dictionary<string, TypeSyntax>(); private static Dictionary<string, SyntaxToken> mTokens = new Dictionary<string, SyntaxToken>(); public static TypeSyntax GetTypeSyntax(string name) { if (mTypeSyntaxes.TryGetValue(name, out var value)) { return value; } var type = SyntaxFactory.ParseTypeName(name); mTypeSyntaxes.Add(name, type); return type; } public static SyntaxToken GetToken(string name) { if (mTokens.TryGetValue(name, out var value)) { return value; } var type = SyntaxFactory.ParseToken(name); mTokens.Add(name, type); return type; } public static MethodDeclarationSyntax MethodDeclaration(string identifier, string returnType, BlockSyntax body, params string[] modifiers) { var mods = new SyntaxToken[modifiers.Length]; for (int i = 0; i < mods.Length; i++) mods[i] = GetToken(modifiers[i]); return SyntaxFactory.MethodDeclaration(new SyntaxList<AttributeListSyntax>(), SyntaxFactory.TokenList(mods), SyntaxFactory.PredefinedType(GetToken("void")), null, GetToken(identifier), null, SyntaxFactory.ParameterList(), new SyntaxList<TypeParameterConstraintClauseSyntax>(), body, null, SyntaxFactory.Token(SyntaxKind.None)); } } }
37.680328
186
0.55471
[ "MIT" ]
Ahremic/HedgeModManager
HedgeModManager/Misc/Extensions.cs
9,196
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("CustomEventManager")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CustomEventManager")] [assembly: AssemblyCopyright("Copyright © 2008")] [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("b5333842-b6fb-4ddd-b121-3bd01e362b27")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.027778
84
0.750913
[ "MIT" ]
Kentico/Samples
Events/EventsAsProductsKentico/CustomEventManager/Properties/AssemblyInfo.cs
1,372
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DragonFly.Core.WebHooks.Types { public class WebHookResult { public string? Message { get; set; } } }
17.857143
44
0.716
[ "MIT" ]
usercode/DragonFly
src/DragonFly.Core/WebHooks/Types/WebHookResult.cs
252
C#
using System.Threading; using Microsoft.SPOT; using Netduino.Foundation.Sensors.Motion; using SecretLabs.NETMF.Hardware.NetduinoPlus; namespace ADXL335PollingSample { public class Program { public static void Main() { var adxl335 = new ADXL335(AnalogChannels.ANALOG_PIN_A0, AnalogChannels.ANALOG_PIN_A1, AnalogChannels.ANALOG_PIN_A2, updateInterval: 0); adxl335.SupplyVoltage = 3.3; adxl335.XVoltsPerG = 0.343; adxl335.YVoltsPerG = 0.287; adxl335.ZVoltsPerG = 0.541; while (true) { adxl335.Update(); var rawData = adxl335.GetRawSensorData(); Debug.Print("\n"); Debug.Print("X: " + adxl335.X.ToString("F2") + ", " + rawData.X.ToString("F2")); Debug.Print("Y: " + adxl335.Y.ToString("F2") + ", " + rawData.Y.ToString("F2")); Debug.Print("Z: " + adxl335.Z.ToString("F2") + ", " + rawData.Z.ToString("F2")); Thread.Sleep(250); } } } }
35.967742
97
0.540807
[ "Apache-2.0" ]
WildernessLabs/Netduino.Foundation
Source/Peripheral_Libs/Sensors.Motion.ADXL335/Samples/ADXL335PollingSample/Program.cs
1,117
C#
using System; using System.Web; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using SuperheroesUniverse.Authentication; namespace SuperheroesUniverse.Account { public partial class Manage : System.Web.UI.Page { protected string SuccessMessage { get; private set; } private bool HasPassword(ApplicationUserManager manager) { return manager.HasPassword(User.Identity.GetUserId()); } public bool HasPhoneNumber { get; private set; } public bool TwoFactorEnabled { get; private set; } public bool TwoFactorBrowserRemembered { get; private set; } public int LoginsCount { get; set; } protected void Page_Load() { var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); HasPhoneNumber = String.IsNullOrEmpty(manager.GetPhoneNumber(User.Identity.GetUserId())); // Enable this after setting up two-factor authentientication //PhoneNumber.Text = manager.GetPhoneNumber(User.Identity.GetUserId()) ?? String.Empty; TwoFactorEnabled = manager.GetTwoFactorEnabled(User.Identity.GetUserId()); LoginsCount = manager.GetLogins(User.Identity.GetUserId()).Count; var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; if (!IsPostBack) { // Determine the sections to render if (HasPassword(manager)) { ChangePassword.Visible = true; } else { CreatePassword.Visible = true; ChangePassword.Visible = false; } // Render success message var message = Request.QueryString["m"]; if (message != null) { // Strip the query string from action Form.Action = ResolveUrl("~/Account/Manage"); SuccessMessage = message == "ChangePwdSuccess" ? "Your password has been changed." : message == "SetPwdSuccess" ? "Your password has been set." : message == "RemoveLoginSuccess" ? "The account was removed." : message == "AddPhoneNumberSuccess" ? "Phone number has been added" : message == "RemovePhoneNumberSuccess" ? "Phone number was removed" : String.Empty; successMessage.Visible = !String.IsNullOrEmpty(SuccessMessage); } } } private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError("", error); } } // Remove phonenumber from user protected void RemovePhone_Click(object sender, EventArgs e) { var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>(); var result = manager.SetPhoneNumber(User.Identity.GetUserId(), null); if (!result.Succeeded) { return; } var user = manager.FindById(User.Identity.GetUserId()); if (user != null) { signInManager.SignIn(user, isPersistent: false, rememberBrowser: false); Response.Redirect("/Account/Manage?m=RemovePhoneNumberSuccess"); } } // DisableTwoFactorAuthentication protected void TwoFactorDisable_Click(object sender, EventArgs e) { var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); manager.SetTwoFactorEnabled(User.Identity.GetUserId(), false); Response.Redirect("/Account/Manage"); } //EnableTwoFactorAuthentication protected void TwoFactorEnable_Click(object sender, EventArgs e) { var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); manager.SetTwoFactorEnabled(User.Identity.GetUserId(), true); Response.Redirect("/Account/Manage"); } } }
36.295082
101
0.576784
[ "MIT" ]
pavelhristov/ASP.NETWebForms
SuperheroesUniverse/SuperheroesUniverse/Account/Manage.aspx.cs
4,430
C#
// MIT License (MIT) - Copyright (c) 2014 jakevn - Please see included LICENSE file using MassiveNet; using UnityEngine; namespace Massive.Examples.NetAdvanced { [RequireComponent(typeof(NetSocket), typeof(NetViewManager))] public class ClientModel : MonoBehaviour { private NetConnection server; private NetSocket socket; private NetViewManager viewManager; private NetZoneClient zoneClient; private void Start() { socket = GetComponent<NetSocket>(); viewManager = GetComponent<NetViewManager>(); zoneClient = GetComponent<NetZoneClient>(); ExampleItems.PopulateItemDatabase(); zoneClient.OnZoneSetupSuccess += ZoneSetupSuccessful; socket.Events.OnDisconnectedFromServer += DisconnectedFromServer; socket.StartSocket(); socket.RegisterRpcListener(this); } private void ZoneSetupSuccessful(NetConnection zoneServer) { } private void DisconnectedFromServer(NetConnection serv) { viewManager.DestroyViewsServing(serv); } } }
27.119048
84
0.665496
[ "MIT" ]
RainsSoft/MassiveNet
Unity3d.Examples/Assets/MassiveNet/Examples/NetAdvanced/Client/Scripts/ClientModel.cs
1,141
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using System.Xml.Linq; using HtmlAgilityPack; namespace pRoom.Models { public class vPlayerModel { public dynamic m=null; public int isActive = 0; public userMD admin = null; } public static class vPlayer { public static async Task<string> parse(message m, meeting meet) { //Console.WriteLine(m.messStr); meet.vPlayerModel.m = m.d; meet.vPlayerModel.isActive = 1; var action = m.d.action; if(action== "setAdmin") { await setAdmin(m, meet); } else { if(meet.vPlayerModel.admin!=null && m.user.name==meet.vPlayerModel.admin.name) if(meet.activePanel== "vPlayer") await mqtt.send(meet.id, m.messStr); //await meet.userManager.sendToAllAsync(m.messStr); } //switch (action) //{ // case "setAdmin": // await setAdmin(m, meet); // break; // default: // await defaultCase(m, meet); // break; //} return ""; } public static async Task<string> setAdmin(message m, meeting meet) { // Console.WriteLine("player set admin"); string url = m.d.url; string newUrl =await aparatCheck(url); m.d.url = newUrl; meet.vPlayerModel.admin = m.user; await mqtt.send(meet.id, m.d); return ""; } public static async Task<string> aparatCheck(string url) { if (url.StartsWith("https://aparat.com/") || url.StartsWith("https://www.aparat.com/")) { Console.WriteLine("url is aparat"); try { string newUrl = await getAparatFileUrl(url); return newUrl; } catch { return "error"; } } else return url; } public static async Task<string> getAparatFileUrl(string url) { //return "gwwwwwwwwwwwwwwwwwww"; using WebClient client = new WebClient(); var html = await client.DownloadStringTaskAsync(url); //Console.WriteLine("html length : " + html.Length); //XDocument doc = XDocument.Parse(html); //var root = doc.Elements("mxfile").FirstOrDefault(); // HtmlWeb web = new HtmlWeb(); var doc = new HtmlAgilityPack.HtmlDocument(); doc.LoadHtml(html); // var doc = web.Load(url); // var dropdown = doc.DocumentNode.Descendants("div").Where(d => d.Attributes["class"].Value.Contains("download-dropdown")).FirstOrDefault(); var dropdown = doc.DocumentNode.Descendants("div").Where(a => a.GetAttributeValue("class", "").Contains("download-dropdown")).FirstOrDefault(); if (dropdown == null) { Console.WriteLine("dropdown not found"); return "error"; } var links = dropdown.Descendants("a").ToList(); Console.WriteLine("link count : "+links.Count); if (links.Count < 1 || links == null) return "error"; var num = Math.Min(4, links.Count); var href = links[num-1].GetAttributeValue("href", "").Trim(); Console.WriteLine(href); return href; } } }
33.982456
155
0.487093
[ "Apache-2.0" ]
torkashvand630/room
Models/vPlayer.cs
3,876
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Authentication.Facebook; using Microsoft.AspNet.Authentication.Google; using Microsoft.AspNet.Authentication.MicrosoftAccount; using Microsoft.AspNet.Authentication.Twitter; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Diagnostics; using Microsoft.AspNet.Diagnostics.Entity; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNet.Routing; using Microsoft.Data.Entity; using Microsoft.Framework.Configuration; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.Logging; using Microsoft.Framework.Logging.Console; using Microsoft.Framework.Runtime; using WebApplication1.Models; using WebApplication1.Services; namespace WebApplication1 { public class Startup { public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) { // Setup configuration sources. var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath) .AddJsonFile("config.json") .AddJsonFile($"config.{env.EnvironmentName}.json", optional: true); if (env.IsDevelopment()) { // This reads the configuration keys from the secret store. // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709 builder.AddUserSecrets(); } builder.AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfiguration Configuration { get; set; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add Entity Framework services to the services container. services.AddEntityFramework() .AddSqlServer() .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])); // Add Identity services to the services container. services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); // Configure the options for the authentication middleware. // You can add options for Google, Twitter and other middleware as shown below. // For more information see http://go.microsoft.com/fwlink/?LinkID=532715 services.Configure<FacebookAuthenticationOptions>(options => { options.AppId = Configuration["Authentication:Facebook:AppId"]; options.AppSecret = Configuration["Authentication:Facebook:AppSecret"]; }); services.Configure<MicrosoftAccountAuthenticationOptions>(options => { options.ClientId = Configuration["Authentication:MicrosoftAccount:ClientId"]; options.ClientSecret = Configuration["Authentication:MicrosoftAccount:ClientSecret"]; }); // Add MVC services to the services container. services.AddMvc(); // Uncomment the following line to add Web API services which makes it easier to port Web API 2 controllers. // You will also need to add the Microsoft.AspNet.Mvc.WebApiCompatShim package to the 'dependencies' section of project.json. // services.AddWebApiConventions(); // Register application services. services.AddTransient<IEmailSender, AuthMessageSender>(); services.AddTransient<ISmsSender, AuthMessageSender>(); } // Configure is called after ConfigureServices is called. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.MinimumLevel = LogLevel.Information; loggerFactory.AddConsole(); // Configure the HTTP request pipeline. // Add the following to the request pipeline only in development environment. if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseErrorPage(ErrorPageOptions.ShowAll); app.UseDatabaseErrorPage(DatabaseErrorPageOptions.ShowAll); } else { // Add Error handling middleware which catches all application specific errors and // sends the request to the following path or controller action. app.UseErrorHandler("/Home/Error"); } // Add static files to the request pipeline. app.UseStaticFiles(); // Add cookie-based authentication to the request pipeline. app.UseIdentity(); // Add authentication middleware to the request pipeline. You can configure options such as Id and Secret in the ConfigureServices method. // For more information see http://go.microsoft.com/fwlink/?LinkID=532715 // app.UseFacebookAuthentication(); // app.UseGoogleAuthentication(); // app.UseMicrosoftAccountAuthentication(); // app.UseTwitterAuthentication(); // Add MVC to the request pipeline. app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); // Uncomment the following line to add a route for porting Web API 2 controllers. // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}"); }); } } }
42.640288
150
0.649907
[ "Apache-2.0" ]
Acidburn0zzz/Docs-6
aspnet/tutorials/your-first-aspnet-application/sample/src/WebApplication1/Startup.cs
5,929
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ILatestPackageVersionCommand.cs" company="Hukano"> // Copyright (c) Hukano. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Sundew.Packaging.Versioning.Commands; using System.Collections.Generic; using System.Threading.Tasks; using global::NuGet.Versioning; /// <summary> /// Interface for implementing a command that gets the latest version of a package. /// </summary> public interface ILatestPackageVersionCommand { /// <summary> /// Gets the latest major minor version. /// </summary> /// <param name="packageId">The package identifier.</param> /// <param name="sources">The sources.</param> /// <param name="nuGetVersion">The nu get version.</param> /// <param name="includePatchInMatch">if set to <c>true</c> [include patch in match].</param> /// <param name="allowPrerelease">if set to <c>true</c> [allow prerelease].</param> /// <returns>An async task with the latest version.</returns> Task<NuGetVersion?> GetLatestMajorMinorVersion( string packageId, IReadOnlyList<string> sources, NuGetVersion nuGetVersion, bool includePatchInMatch, bool allowPrerelease); }
44.529412
120
0.593791
[ "MIT" ]
hugener/Sundew.Packaging.Publish
Source/Sundew.Packaging/Versioning/Commands/ILatestPackageVersionCommand.cs
1,516
C#
namespace System.Threading.Tasks { public static partial class TaskFactoryExtensions { public static Task StartNewDelayed( this TaskFactory factory, int millisecondsDelay) { return StartNewDelayed(factory, millisecondsDelay, CancellationToken.None); } public static Task StartNewDelayed(this TaskFactory factory, int millisecondsDelay, CancellationToken cancellationToken) { // Validate arguments if (factory == null) throw new ArgumentNullException("factory"); if (millisecondsDelay < 0) throw new ArgumentOutOfRangeException("millisecondsDelay"); // Create the timed task var tcs = new TaskCompletionSource<object>(factory.CreationOptions); var ctr = default(CancellationTokenRegistration); // Create the timer but don't start it yet. If we start it now, // it might fire before ctr has been set to the right registration. var timer = new Timer(self => { // Clean up both the cancellation token and the timer, and try to transition to completed ctr.Dispose(); ((Timer)self).Dispose(); tcs.TrySetResult(null); }); // Register with the cancellation token. if (cancellationToken.CanBeCanceled) { // When cancellation occurs, cancel the timer and try to transition to canceled. // There could be a race, but it's benign. ctr = cancellationToken.Register(() => { timer.Dispose(); tcs.TrySetCanceled(); }); } // Start the timer and hand back the task... timer.Change(millisecondsDelay, Timeout.Infinite); return tcs.Task; } public static Task StartNewDelayed( this TaskFactory factory, int millisecondsDelay, Action action) { if (factory == null) throw new ArgumentNullException("factory"); return StartNewDelayed(factory, millisecondsDelay, action, factory.CancellationToken, factory.CreationOptions, factory.GetTargetScheduler()); } public static Task StartNewDelayed( this TaskFactory factory, int millisecondsDelay, Action action, TaskCreationOptions creationOptions) { if (factory == null) throw new ArgumentNullException("factory"); return StartNewDelayed(factory, millisecondsDelay, action, factory.CancellationToken, creationOptions, factory.GetTargetScheduler()); } public static Task StartNewDelayed( this TaskFactory factory, int millisecondsDelay, Action action, CancellationToken cancellationToken) { if (factory == null) throw new ArgumentNullException("factory"); return StartNewDelayed(factory, millisecondsDelay, action, cancellationToken, factory.CreationOptions, factory.GetTargetScheduler()); } public static Task StartNewDelayed( this TaskFactory factory, int millisecondsDelay, Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler) { if (factory == null) throw new ArgumentNullException("factory"); if (millisecondsDelay < 0) throw new ArgumentOutOfRangeException("millisecondsDelay"); if (action == null) throw new ArgumentNullException("action"); if (scheduler == null) throw new ArgumentNullException("scheduler"); return factory .StartNewDelayed(millisecondsDelay, cancellationToken) .ContinueWith(_ => action(), cancellationToken, TaskContinuationOptions.OnlyOnRanToCompletion, scheduler); } public static Task StartNewDelayed( this TaskFactory factory, int millisecondsDelay, Action<object> action, object state) { if (factory == null) throw new ArgumentNullException("factory"); return StartNewDelayed(factory, millisecondsDelay, action, state, factory.CancellationToken, factory.CreationOptions, factory.GetTargetScheduler()); } public static Task StartNewDelayed( this TaskFactory factory, int millisecondsDelay, Action<object> action, object state, TaskCreationOptions creationOptions) { if (factory == null) throw new ArgumentNullException("factory"); return StartNewDelayed(factory, millisecondsDelay, action, state, factory.CancellationToken, creationOptions, factory.GetTargetScheduler()); } public static Task StartNewDelayed( this TaskFactory factory, int millisecondsDelay, Action<object> action, object state, CancellationToken cancellationToken) { if (factory == null) throw new ArgumentNullException("factory"); return StartNewDelayed(factory, millisecondsDelay, action, state, cancellationToken, factory.CreationOptions, factory.GetTargetScheduler()); } public static Task StartNewDelayed( this TaskFactory factory, int millisecondsDelay, Action<object> action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler) { if (factory == null) throw new ArgumentNullException("factory"); if (millisecondsDelay < 0) throw new ArgumentOutOfRangeException("millisecondsDelay"); if (action == null) throw new ArgumentNullException("action"); if (scheduler == null) throw new ArgumentNullException("scheduler"); // Create the task that will be returned; workaround for no ContinueWith(..., state) overload. var result = new TaskCompletionSource<object>(state); // Delay a continuation to run the action factory .StartNewDelayed(millisecondsDelay, cancellationToken) .ContinueWith(t => { if (t.IsCanceled) result.TrySetCanceled(); else { try { action(state); result.TrySetResult(null); } catch (Exception exc) { result.TrySetException(exc); } } }, scheduler); // Return the task return result.Task; } public static Task<TResult> StartNewDelayed<TResult>( this TaskFactory<TResult> factory, int millisecondsDelay, Func<TResult> function) { if (factory == null) throw new ArgumentNullException("factory"); return StartNewDelayed(factory, millisecondsDelay, function, factory.CancellationToken, factory.CreationOptions, factory.GetTargetScheduler()); } public static Task<TResult> StartNewDelayed<TResult>( this TaskFactory<TResult> factory, int millisecondsDelay, Func<TResult> function, TaskCreationOptions creationOptions) { if (factory == null) throw new ArgumentNullException("factory"); return StartNewDelayed(factory, millisecondsDelay, function, factory.CancellationToken, creationOptions, factory.GetTargetScheduler()); } public static Task<TResult> StartNewDelayed<TResult>( this TaskFactory<TResult> factory, int millisecondsDelay, Func<TResult> function, CancellationToken cancellationToken) { if (factory == null) throw new ArgumentNullException("factory"); return StartNewDelayed(factory, millisecondsDelay, function, cancellationToken, factory.CreationOptions, factory.GetTargetScheduler()); } public static Task<TResult> StartNewDelayed<TResult>( this TaskFactory<TResult> factory, int millisecondsDelay, Func<TResult> function, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler) { if (factory == null) throw new ArgumentNullException("factory"); if (millisecondsDelay < 0) throw new ArgumentOutOfRangeException("millisecondsDelay"); if (function == null) throw new ArgumentNullException("function"); if (scheduler == null) throw new ArgumentNullException("scheduler"); // Create the trigger and the timer to start it var tcs = new TaskCompletionSource<object>(); var timer = new Timer(obj => ((TaskCompletionSource<object>)obj).SetResult(null), tcs, millisecondsDelay, Timeout.Infinite); // Return a task that executes the function when the trigger fires return tcs.Task.ContinueWith(_ => { timer.Dispose(); return function(); }, cancellationToken, ContinuationOptionsFromCreationOptions(creationOptions), scheduler); } public static Task<TResult> StartNewDelayed<TResult>( this TaskFactory<TResult> factory, int millisecondsDelay, Func<object, TResult> function, object state) { if (factory == null) throw new ArgumentNullException("factory"); return StartNewDelayed(factory, millisecondsDelay, function, state, factory.CancellationToken, factory.CreationOptions, factory.GetTargetScheduler()); } public static Task<TResult> StartNewDelayed<TResult>( this TaskFactory<TResult> factory, int millisecondsDelay, Func<object, TResult> function, object state, CancellationToken cancellationToken) { if (factory == null) throw new ArgumentNullException("factory"); return StartNewDelayed(factory, millisecondsDelay, function, state, cancellationToken, factory.CreationOptions, factory.GetTargetScheduler()); } /// <summary>Creates and schedules a task for execution after the specified time delay.</summary> /// <param name="factory">The factory to use to create the task.</param> /// <param name="millisecondsDelay">The delay after which the task will be scheduled.</param> /// <param name="function">The delegate executed by the task.</param> /// <param name="state">An object provided to the delegate.</param> /// <param name="creationOptions">Options that control the task's behavior.</param> /// <returns>The created Task.</returns> public static Task<TResult> StartNewDelayed<TResult>( this TaskFactory<TResult> factory, int millisecondsDelay, Func<object, TResult> function, object state, TaskCreationOptions creationOptions) { if (factory == null) throw new ArgumentNullException("factory"); return StartNewDelayed(factory, millisecondsDelay, function, state, factory.CancellationToken, creationOptions, factory.GetTargetScheduler()); } /// <summary>Creates and schedules a task for execution after the specified time delay.</summary> /// <param name="factory">The factory to use to create the task.</param> /// <param name="millisecondsDelay">The delay after which the task will be scheduled.</param> /// <param name="function">The delegate executed by the task.</param> /// <param name="state">An object provided to the delegate.</param> /// <param name="cancellationToken">The CancellationToken to assign to the Task.</param> /// <param name="creationOptions">Options that control the task's behavior.</param> /// <param name="scheduler">The scheduler to which the Task will be scheduled.</param> /// <returns>The created Task.</returns> public static Task<TResult> StartNewDelayed<TResult>( this TaskFactory<TResult> factory, int millisecondsDelay, Func<object, TResult> function, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler) { if (factory == null) throw new ArgumentNullException("factory"); if (millisecondsDelay < 0) throw new ArgumentOutOfRangeException("millisecondsDelay"); if (function == null) throw new ArgumentNullException("action"); if (scheduler == null) throw new ArgumentNullException("scheduler"); // Create the task that will be returned var result = new TaskCompletionSource<TResult>(state); Timer timer = null; // Create the task that will run the user's function var functionTask = new Task<TResult>(function, state, creationOptions); // When the function task completes, transfer the results to the returned task functionTask.ContinueWith(t => { result.SetFromTask(t); timer.Dispose(); }, cancellationToken, ContinuationOptionsFromCreationOptions(creationOptions) | TaskContinuationOptions.ExecuteSynchronously, scheduler); // Start the timer for the trigger timer = new Timer(obj => ((Task)obj).Start(scheduler), functionTask, millisecondsDelay, Timeout.Infinite); return result.Task; } /// <summary>Gets the TaskScheduler instance that should be used to schedule tasks.</summary> public static TaskScheduler GetTargetScheduler(this TaskFactory factory) { if (factory == null) throw new ArgumentNullException("factory"); return factory.Scheduler ?? TaskScheduler.Current; } /// <summary>Gets the TaskScheduler instance that should be used to schedule tasks.</summary> public static TaskScheduler GetTargetScheduler<TResult>(this TaskFactory<TResult> factory) { if (factory == null) throw new ArgumentNullException("factory"); return factory.Scheduler != null ? factory.Scheduler : TaskScheduler.Current; } /// <summary>Converts TaskCreationOptions into TaskContinuationOptions.</summary> /// <param name="creationOptions"></param> /// <returns></returns> private static TaskContinuationOptions ContinuationOptionsFromCreationOptions(TaskCreationOptions creationOptions) { return (TaskContinuationOptions) ((creationOptions & TaskCreationOptions.AttachedToParent) | (creationOptions & TaskCreationOptions.PreferFairness) | (creationOptions & TaskCreationOptions.LongRunning)); } } }
54.817164
162
0.653189
[ "Apache-2.0" ]
FoundatioFx/Foundatio.Skeleton
api/src/Core/Extensions/TaskFactoryExtensions.cs
14,693
C#
using System.CodeDom.Compiler; using System.Runtime.Serialization; namespace SolidRpc.Test.Vitec.Types.BusinessIntelligense.Models { /// <summary> /// /// </summary> [GeneratedCode("OpenApiCodeGeneratorV2","1.0.0.0")] public class EconomicAddress { /// <summary> /// Gatuadress /// </summary> [DataMember(Name="streetAddress",EmitDefaultValue=false)] public string StreetAddress { get; set; } /// <summary> /// Postnummer /// </summary> [DataMember(Name="zipCode",EmitDefaultValue=false)] public string ZipCode { get; set; } /// <summary> /// Landskod /// </summary> [DataMember(Name="countryCode",EmitDefaultValue=false)] public string CountryCode { get; set; } } }
29.5
65
0.585956
[ "MIT" ]
aarrgard/solidrpc
SolidRpc.Test.Vitec/Types/BusinessIntelligense/Models/EconomicAddress.cs
826
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading; using Multimus.Plugin; namespace Multimus.Models { static class CurrentPlayer { private static IMediaPlayer currendMediaPlayer = new NullPlayer(); public static ReaderWriterLockSlim readerWriterLock = new ReaderWriterLockSlim(); public static IMediaPlayer CurrendMediaPlayer { get { readerWriterLock.EnterReadLock(); try { return currendMediaPlayer; } finally { readerWriterLock.ExitReadLock(); } } set { readerWriterLock.EnterWriteLock(); try { var oldplayer = currendMediaPlayer; currendMediaPlayer = value; oldplayer.IsPaused = true; oldplayer.Dispose(); } finally { readerWriterLock.ExitWriteLock(); } } } } }
25.1875
89
0.468156
[ "MIT" ]
chris-pie/Multimus
Multimus/Multimus/Models/CurrentPlayer.cs
1,211
C#
#region PDFsharp - A .NET library for processing PDF // // Authors: // David Stephensen (mailto:David.Stephensen@pdfsharp.com) // // Copyright (c) 2005-2009 empira Software GmbH, Cologne (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System; using System.IO; namespace PdfSharp.Pdf.Filters { /// <summary> /// Implements the LzwDecode filter. /// </summary> public class LzwDecode : Filter { /// <summary> /// Throws a NotImplementedException because the obsolete LZW encoding is not supported by PDFsharp. /// </summary> public override byte[] Encode(byte[] data) { throw new NotImplementedException("PDFsharp does not support LZW encoding."); } /// <summary> /// Decodes the specified data. /// </summary> public override byte[] Decode(byte[] data, FilterParms parms) { if (data[0] == 0x00 && data[1] == 0x01) throw new Exception("LZW flavour not supported."); MemoryStream outputStream = new MemoryStream(); InitializeDictionary(); this.data = data; bytePointer = 0; nextData = 0; nextBits = 0; int code, oldCode = 0; byte[] str; while ((code = NextCode) != 257) { if (code == 256) { InitializeDictionary(); code = NextCode; if (code == 257) { break; } outputStream.Write(stringTable[code], 0, stringTable[code].Length); oldCode = code; } else { if (code < tableIndex) { str = stringTable[code]; outputStream.Write(str, 0, str.Length); AddEntry(stringTable[oldCode], str[0]); oldCode = code; } else { str = stringTable[oldCode]; outputStream.Write(str, 0, str.Length); AddEntry(str, str[0]); oldCode = code; } } } if (outputStream.Length >= 0) { outputStream.Capacity = (int)outputStream.Length; return outputStream.GetBuffer(); } return null; } /// <summary> /// Initialize the dictionary. /// </summary> void InitializeDictionary() { stringTable = new byte[8192][]; for (int i = 0; i < 256; i++) { stringTable[i] = new byte[1]; stringTable[i][0] = (byte)i; } tableIndex = 258; bitsToGet = 9; } /// <summary> /// Add a new entry to the Dictionary. /// </summary> void AddEntry(byte[] oldstring, byte newstring) { int length = oldstring.Length; byte[] str = new byte[length + 1]; Array.Copy(oldstring, 0, str, 0, length); str[length] = newstring; stringTable[tableIndex++] = str; if (tableIndex == 511) bitsToGet = 10; else if (tableIndex == 1023) bitsToGet = 11; else if (tableIndex == 2047) bitsToGet = 12; } /// <summary> /// Returns the next set of bits. /// </summary> int NextCode { get { try { nextData = (nextData << 8) | (data[bytePointer++] & 0xff); nextBits += 8; if (nextBits < bitsToGet) { nextData = (nextData << 8) | (data[bytePointer++] & 0xff); nextBits += 8; } int code = (nextData >> (nextBits - bitsToGet)) & andTable[bitsToGet - 9]; nextBits -= bitsToGet; return code; } catch { return 257; } } } readonly int[] andTable = { 511, 1023, 2047, 4095 }; byte[][] stringTable; byte[] data; int tableIndex, bitsToGet = 9; int bytePointer; int nextData = 0; int nextBits = 0; } }
26.766304
104
0.579086
[ "MIT" ]
XpsToPdf/XpsToPdf
XpsToPdf/PdfSharp.Pdf.Filters/LzwDecode.cs
4,925
C#
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // This file is part of the Griffin+ common library suite (https://github.com/griffinplus/dotnet-libs-codegen) // The source code is licensed under the MIT license. /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Reflection.Emit; namespace GriffinPlus.Lib.CodeGeneration { /// <summary> /// Definition of a type to create dynamically. /// </summary> public abstract class TypeDefinition { private readonly Stack<TypeBuilder> mTypeBuilders; /// <summary> /// Initializes a new <see cref="TypeDefinition"/> for a struct or a class not deriving from a base type. /// </summary> /// <param name="module">Module definition to associate the type definition with (<c>null</c> to create a new module definition).</param> /// <param name="isValueType"> /// <c>true</c> if the type to define is a value type (struct); /// <c>false</c> if it is a reference type (class). /// </param> /// <param name="name">Name of the type to create (<c>null</c> to create a random name).</param> internal TypeDefinition(ModuleDefinition module, bool isValueType, string name = null) { // no base class means that the type effectively derives from System.ValueType for value types and System.Object for classes BaseClassType = isValueType ? typeof(ValueType) : typeof(object); // determine the name of the generated type TypeName = string.IsNullOrWhiteSpace(name) ? "DynamicType_" + Guid.NewGuid().ToString("N") : name; CodeGenHelpers.EnsureNameIsValidLanguageIndependentIdentifier(TypeName); // create a builder for type to create ModuleDefinition = module ?? new ModuleDefinition(); TypeBuilder = CreateTypeBuilder(out mTypeBuilders); } /// <summary> /// Initializes a new <see cref="TypeDefinition"/> for a class deriving from the specified base class. /// </summary> /// <param name="module">Module definition to associate the type definition with (<c>null</c> to create a new module definition).</param> /// <param name="baseClass">Base class to derive the created class from.</param> /// <param name="name">Name of the class to create (<c>null</c> to keep the name of the base class).</param> /// <exception cref="ArgumentNullException"><paramref name="baseClass"/> is <c>null</c>.</exception> /// <exception cref="ArgumentException"> /// <paramref name="baseClass"/> is not a class /// -or- /// <paramref name="name"/> is not a valid type name. /// </exception> internal TypeDefinition(ModuleDefinition module, Type baseClass, string name = null) { if (baseClass == null) throw new ArgumentNullException(nameof(baseClass)); // ensure that the base class is really a class that is totally public // (otherwise the generated assembly will not be able to access it) if (!baseClass.IsClass) throw new ArgumentException($"The specified type ({baseClass.FullName}) is not a class.", nameof(baseClass)); CodeGenHelpers.EnsureTypeIsTotallyPublic(baseClass); BaseClassType = baseClass; // determine the name of the generated type // (take the name of the base type if no name is specified) TypeName = string.IsNullOrWhiteSpace(name) ? BaseClassType.FullName : name; CodeGenHelpers.EnsureNameIsValidTypeName(TypeName); // create a builder for type to create ModuleDefinition = module ?? new ModuleDefinition(); TypeBuilder = CreateTypeBuilder(out mTypeBuilders); } /// <summary> /// Creates a builder for the type to generate. /// </summary> /// <param name="typeBuilders"> /// Receives the type builders that are needed to generate the requested type as well /// (nested types need to be generated bottom up, so each nesting level has its own type builder). /// </param> /// <returns>The created type builder.</returns> private TypeBuilder CreateTypeBuilder(out Stack<TypeBuilder> typeBuilders) { // create a type builder typeBuilders = new Stack<TypeBuilder>(); string[] splitTypeNameTokens = TypeName.Split('+'); if (splitTypeNameTokens.Length > 1) { TypeBuilder parent = ModuleDefinition.ModuleBuilder.DefineType(splitTypeNameTokens[0], TypeAttributes.Public | TypeAttributes.Class, null); typeBuilders.Push(parent); for (int i = 1; i < splitTypeNameTokens.Length; i++) { if (i + 1 < splitTypeNameTokens.Length) { parent = parent.DefineNestedType(splitTypeNameTokens[i], TypeAttributes.NestedPublic | TypeAttributes.Class); typeBuilders.Push(parent); } else { parent = parent.DefineNestedType(splitTypeNameTokens[i], TypeAttributes.NestedPublic | TypeAttributes.Class, BaseClassType); typeBuilders.Push(parent); } } } else { TypeBuilder builder = ModuleDefinition.ModuleBuilder.DefineType(splitTypeNameTokens[0], TypeAttributes.Public | TypeAttributes.Class, BaseClassType); typeBuilders.Push(builder); } return typeBuilders.Peek(); } /// <summary> /// Gets the name of the type to create. /// </summary> public string TypeName { get; } /// <summary> /// Gets the base type of the type to create. /// </summary> public Type BaseClassType { get; } /// <summary> /// Gets the definition of the module the type in creation is defined in. /// </summary> public ModuleDefinition ModuleDefinition { get; } /// <summary> /// Gets the <see cref="System.Reflection.Emit.TypeBuilder"/> that is used to create the type. /// </summary> public TypeBuilder TypeBuilder { get; } /// <summary> /// Gets the collection of external objects that is added to the created type. /// </summary> internal List<object> ExternalObjects { get; } = new List<object>(); #region Information about Base Class Constructors private List<IConstructor> mBaseClassConstructors; /// <summary> /// Gets constructors of the base type that are accessible to the type in creation. /// </summary> public IEnumerable<IConstructor> BaseClassConstructors { get { // return the cached set of base class constructors, if available if (mBaseClassConstructors != null) return mBaseClassConstructors; // determine base class constructors and cache them mBaseClassConstructors = new List<IConstructor>(); BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly; foreach (ConstructorInfo constructorInfo in BaseClassType.GetConstructors(flags)) { // skip constructor if it is private or internal // (cannot be accessed by a derived type defined in another assembly) if (constructorInfo.IsPrivate || constructorInfo.IsAssembly) continue; // keep constructor mBaseClassConstructors.Add(new Constructor(constructorInfo)); } return mBaseClassConstructors; } } #endregion #region Information about Inherited Fields, Events, Properties and Methods /// <summary> /// Gets the fields the type to create inherits from its base type. /// </summary> public IEnumerable<IInheritedField> InheritedFields => GetInheritedFields(false); /// <summary> /// Gets the events the type to create inherits from its base type. /// </summary> public IEnumerable<IInheritedEvent> InheritedEvents => GetInheritedEvents(false); /// <summary> /// Gets the properties the type to create inherits from its base type. /// </summary> public IEnumerable<IInheritedProperty> InheritedProperties => GetInheritedProperties(false); /// <summary> /// Gets the methods the type to create inherits from its base type. /// Does not contain inherited add/remove accessor methods of events and get/set accessor methods of properties. /// You can use <see cref="IInheritedEvent.AddAccessor"/> and <see cref="IInheritedEvent.RemoveAccessor"/> to get /// event accessor methods. Property accessor methods are available via <see cref="IInheritedProperty.GetAccessor"/> /// and <see cref="IInheritedProperty.SetAccessor"/>. /// </summary> public IEnumerable<IInheritedMethod> InheritedMethods => GetInheritedMethods(false); /// <summary> /// Gets fields inherited from the base class. /// </summary> /// <param name="includeHidden"> /// <c>true</c> to include fields that have been hidden by more specific types if the base type derives from some other type on its own; /// <c>false</c> to return only the most specific fields (default, same as <see cref="InheritedFields"/>). /// </param> /// <returns>The inherited fields.</returns> public IEnumerable<IInheritedField> GetInheritedFields(bool includeHidden) { BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; HashSet<IInheritedField> inheritedFields = new HashSet<IInheritedField>(); Type typeToInspect = BaseClassType; while (typeToInspect != null) { foreach (FieldInfo fieldInfo in typeToInspect.GetFields(flags)) { // skip field if it is 'private' or 'internal' // (cannot be accessed by a derived type defined in another assembly) if (fieldInfo.IsPrivate || fieldInfo.IsAssembly) continue; // skip field if a field with the same signature is already in the set of fields // and hidden fields should not be returned if (!includeHidden && inheritedFields.Any(x => HasSameSignature(x.FieldInfo, fieldInfo))) continue; // the field is accessible from a derived class in some other assembly Type inheritedFieldType = typeof(InheritedField<>).MakeGenericType(fieldInfo.FieldType); IInheritedField inheritedField = (IInheritedField)Activator.CreateInstance( inheritedFieldType, BindingFlags.Instance | BindingFlags.NonPublic, Type.DefaultBinder, new object[] { this, fieldInfo }, CultureInfo.InvariantCulture); inheritedFields.Add(inheritedField); } typeToInspect = typeToInspect.BaseType; } return inheritedFields; } /// <summary> /// Gets events inherited from the base class. /// </summary> /// <param name="includeHidden"> /// <c>true</c> to include events that have been hidden by more specific types if the base type derives from some other type on its own; /// <c>false</c> to return only the most specific events (default, same as <see cref="InheritedEvents"/>). /// </param> /// <returns>The inherited events.</returns> public IEnumerable<IInheritedEvent> GetInheritedEvents(bool includeHidden) { BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; HashSet<IInheritedEvent> inheritedEvents = new HashSet<IInheritedEvent>(); Type typeToInspect = BaseClassType; while (typeToInspect != null) { foreach (EventInfo eventInfo in typeToInspect.GetEvents(flags)) { // skip event if it is 'private' or 'internal' // (cannot be accessed by a derived type defined in another assembly) MethodInfo addMethod = eventInfo.GetAddMethod(true); MethodInfo removeMethod = eventInfo.GetRemoveMethod(true); if (addMethod.IsPrivate || addMethod.IsAssembly) continue; if (removeMethod.IsPrivate || removeMethod.IsAssembly) continue; // skip event if it is virtual and already in the set of events (also covers abstract, virtual and overridden events) // => only the most specific implementation gets into the returned set of events if ((addMethod.IsVirtual || removeMethod.IsVirtual) && inheritedEvents.Any(x => HasSameSignature(x.EventInfo, eventInfo))) continue; // skip event if an event with the same signature is already in the set of events // and hidden events should not be returned if (!includeHidden && inheritedEvents.Any(x => HasSameSignature(x.EventInfo, eventInfo))) continue; // the event is accessible from a derived class in some other assembly Type inheritedEventType = typeof(InheritedEvent<>).MakeGenericType(eventInfo.EventHandlerType); IInheritedEvent inheritedEvent = (IInheritedEvent)Activator.CreateInstance( inheritedEventType, BindingFlags.Instance | BindingFlags.NonPublic, Type.DefaultBinder, new object[] { this, eventInfo }, CultureInfo.InvariantCulture); inheritedEvents.Add(inheritedEvent); } typeToInspect = typeToInspect.BaseType; } return inheritedEvents; } /// <summary> /// Gets properties inherited from the base class. /// </summary> /// <param name="includeHidden"> /// <c>true</c> to include properties that have been hidden by more specific types if the base type derives from some other type on its own; /// <c>false</c> to return only the most specific properties (default, same as <see cref="InheritedProperties"/>). /// </param> /// <returns>The inherited properties.</returns> public IEnumerable<IInheritedProperty> GetInheritedProperties(bool includeHidden) { BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; HashSet<IInheritedProperty> inheritedProperties = new HashSet<IInheritedProperty>(); Type typeToInspect = BaseClassType; while (typeToInspect != null) { foreach (PropertyInfo propertyInfo in typeToInspect.GetProperties(flags)) { // skip accessors that are 'private' or 'internal' // (cannot be accessed by a derived type defined in another assembly) int callableAccessorCount = 0; // check visibility of the 'get' accessor MethodInfo getAccessor = propertyInfo.GetGetMethod(true); if (getAccessor != null && !getAccessor.IsPrivate && !getAccessor.IsAssembly) callableAccessorCount++; // check visibility of the 'set' accessor MethodInfo setAccessor = propertyInfo.GetSetMethod(true); if (setAccessor != null && !setAccessor.IsPrivate && !setAccessor.IsAssembly) callableAccessorCount++; // skip property if neither a get accessor method nor a set accessor method are accessible if (callableAccessorCount == 0) continue; // skip property if it is already in the set of properties and its accessor methods are virtual // (the check for virtual also covers abstract, virtual and override methods) // => only the most specific implementation gets into the returned set of properties if (inheritedProperties.Any(x => HasSameSignature(x.PropertyInfo, propertyInfo))) { if (getAccessor != null && getAccessor.IsVirtual) continue; if (setAccessor != null && setAccessor.IsVirtual) continue; } // skip property if a property with the same signature is already in the set of properties // and hidden properties should not be returned if (!includeHidden && inheritedProperties.Any(x => HasSameSignature(x.PropertyInfo, propertyInfo))) continue; // the property is accessible from a derived class in some other assembly Type inheritedPropertyType = typeof(InheritedProperty<>).MakeGenericType(propertyInfo.PropertyType); IInheritedProperty property = (IInheritedProperty)Activator.CreateInstance( inheritedPropertyType, BindingFlags.Instance | BindingFlags.NonPublic, Type.DefaultBinder, new object[] { this, propertyInfo }, CultureInfo.InvariantCulture); inheritedProperties.Add(property); } typeToInspect = typeToInspect.BaseType; } return inheritedProperties; } /// <summary> /// Gets methods inherited from the base class. /// </summary> /// <param name="includeHidden"> /// <c>true</c> to include methods that have been hidden by more specific types if the base type derives from some other type on its own; /// <c>false</c> to return only the most specific methods (default, same as <see cref="InheritedMethods"/>). /// </param> /// <returns>The inherited methods.</returns> public IEnumerable<IInheritedMethod> GetInheritedMethods(bool includeHidden) { BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; HashSet<IInheritedMethod> inheritedMethods = new HashSet<IInheritedMethod>(); Type typeToInspect = BaseClassType; while (typeToInspect != null) { foreach (MethodInfo methodInfo in typeToInspect.GetMethods(flags)) { // skip method if it is 'private' or 'internal' // (cannot be accessed by a derived type defined in another assembly) if (methodInfo.IsPrivate || methodInfo.IsAssembly) continue; // skip methods with a special name as these methods usually cannot be called by the user directly // (add/remove accessor methods of events and get/set accessor methods of properties) if (methodInfo.IsSpecialName) continue; // skip method if it is virtual and already in the set of methods (also covers abstract, virtual and overridden events) // => only the most specific implementation gets into the returned set of methods if (methodInfo.IsVirtual && inheritedMethods.Any(x => HasSameSignature(x.MethodInfo, methodInfo))) continue; // skip property if a method with the same signature is already in the set of methods // and hidden methods should not be returned if (!includeHidden && inheritedMethods.Any(x => HasSameSignature(x.MethodInfo, methodInfo))) continue; // the method is accessible from a derived class in some other assembly InheritedMethod inheritedMethod = new InheritedMethod(this, methodInfo); inheritedMethods.Add(inheritedMethod); } typeToInspect = typeToInspect.BaseType; } return inheritedMethods; } #endregion #region Information about Generated Fields, Events, Properties and Methods private readonly List<IGeneratedFieldInternal> mGeneratedFields = new List<IGeneratedFieldInternal>(); private readonly List<IGeneratedEvent> mGeneratedEvents = new List<IGeneratedEvent>(); private readonly List<IGeneratedProperty> mGeneratedProperties = new List<IGeneratedProperty>(); private readonly List<IGeneratedMethodInternal> mGeneratedMethods = new List<IGeneratedMethodInternal>(); #if NET461 || NET5_0 && WINDOWS private readonly List<IGeneratedDependencyProperty> mGeneratedDependencyProperties = new List<IGeneratedDependencyProperty>(); #elif NETSTANDARD2_0 || NETSTANDARD2_1 // Dependency properties are not supported on .NET Standard... #else #error Unhandled Target Framework. #endif /// <summary> /// Gets the fields that have already been generated on the type. /// </summary> public IEnumerable<IGeneratedField> GeneratedFields => mGeneratedFields; /// <summary> /// Gets the events that have already been generated on the type. /// </summary> public IEnumerable<IGeneratedEvent> GeneratedEvents => mGeneratedEvents; /// <summary> /// Gets the properties that have already been generated on the type. /// </summary> public IEnumerable<IGeneratedProperty> GeneratedProperties => mGeneratedProperties; /// <summary> /// Gets the methods that have already been generated on the type. /// Does not contain generated add/remove accessor methods of events and get/set accessor methods of properties. /// You can use <see cref="IGeneratedEvent.AddAccessor"/> and <see cref="IGeneratedEvent.RemoveAccessor"/> to get /// event accessor methods. Property accessor methods are available via <see cref="IGeneratedProperty.GetAccessor"/> /// and <see cref="IGeneratedProperty.SetAccessor"/>. /// </summary> public IEnumerable<IGeneratedMethod> GeneratedMethods => mGeneratedMethods.Where(x => !x.MethodInfo.IsSpecialName); #if NET461 || NET5_0 && WINDOWS /// <summary> /// Gets the dependency properties that have already been generated on the type. /// </summary> public IEnumerable<IGeneratedDependencyProperty> GeneratedDependencyProperties => mGeneratedDependencyProperties; #elif NETSTANDARD2_0 || NETSTANDARD2_1 // Dependency properties are not supported on .NET Standard... #else #error Unhandled Target Framework. #endif #endregion #region Adding Implemented Interfaces /// <summary> /// Gets the interfaces implemented by the created type. /// </summary> public IEnumerable<Type> ImplementedInterfaces => TypeBuilder.GetTypeInfo().ImplementedInterfaces; /// <summary> /// Adds the specified interface to the type in creation. /// </summary> /// <typeparam name="T">Interface to add to the type in creation.</typeparam> public void AddImplementedInterface<T>() { TypeBuilder.AddInterfaceImplementation(typeof(T)); } #endregion #region Adding Constructors private readonly List<IGeneratedConstructorInternal> mConstructors = new List<IGeneratedConstructorInternal>(); /// <summary> /// Gets constructor definitions determining what constructors need to be created. /// </summary> public IEnumerable<IGeneratedConstructor> Constructors => mConstructors; /// <summary> /// Adds a new constructor to the type definition. /// </summary> /// <param name="visibility">Visibility of the constructor.</param> /// <param name="parameterTypes">Constructor parameter types.</param> /// <param name="baseClassConstructorCallImplementation"> /// Callback that implements the call to a base class constructor if the type in creation derives from another type; /// <c>null</c> to call the parameterless constructor of the base class. /// </param> /// <param name="implementConstructorCallback"> /// Callback that emits additional code to execute after the constructor of the base class has run; /// <c>null</c> to skip emitting additional code. /// </param> public IGeneratedConstructor AddConstructor( Visibility visibility, Type[] parameterTypes, ConstructorBaseClassCallImplementationCallback baseClassConstructorCallImplementation = null, ConstructorImplementationCallback implementConstructorCallback = null) { // check parameter types if (parameterTypes == null) throw new ArgumentNullException(nameof(parameterTypes)); if (mConstructors.FirstOrDefault(x => x.ParameterTypes.SequenceEqual(parameterTypes)) != null) throw new CodeGenException("A constructor with the same signature is already part of the definition."); // create constructor GeneratedConstructor constructor = new GeneratedConstructor( this, visibility, parameterTypes, baseClassConstructorCallImplementation, implementConstructorCallback); mConstructors.Add(constructor); return constructor; } #endregion #region Adding Fields /// <summary> /// Adds a new instance field to the type definition (without an initial value). /// </summary> /// <typeparam name="T">Type of the field to add.</typeparam> /// <param name="name">Name of the field to add (<c>null</c> to create a random name).</param> /// <param name="visibility">Visibility of the field.</param> /// <returns>The added field.</returns> public IGeneratedField<T> AddField<T>(string name, Visibility visibility) { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedField<T> field = new GeneratedField<T>(this, false, name, visibility); mGeneratedFields.Add(field); return field; } /// <summary> /// Adds a new instance field to the type definition (without an initial value). /// </summary> /// <param name="type">Type of the field to add.</param> /// <param name="name">Name of the field to add (<c>null</c> to create a random name).</param> /// <param name="visibility">Visibility of the field.</param> /// <returns>The added field.</returns> /// <exception cref="ArgumentNullException">The specified <paramref name="type"/> is <c>null</c>.</exception> public IGeneratedField AddField(Type type, string name, Visibility visibility) { EnsureThatIdentifierHasNotBeenUsedYet(name); if (type == null) throw new ArgumentNullException(nameof(type)); var constructor = typeof(GeneratedField<>) .MakeGenericType(type) .GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, Type.DefaultBinder, new[] { typeof(TypeDefinition), typeof(bool), typeof(string), typeof(Visibility) }, null); Debug.Assert(constructor != null, nameof(constructor) + " != null"); IGeneratedFieldInternal field = (IGeneratedFieldInternal)constructor.Invoke(new object[] { this, false, name, visibility }); mGeneratedFields.Add(field); return field; } /// <summary> /// Adds a new instance field to the type definition (with initial value). /// </summary> /// <typeparam name="T">Type of the field to add.</typeparam> /// <param name="name">Name of the field to add (<c>null</c> to create a random name).</param> /// <param name="visibility">Visibility of the field.</param> /// <param name="initialValue">Initial value of the field.</param> /// <returns>The added field.</returns> public IGeneratedField<T> AddField<T>(string name, Visibility visibility, T initialValue) { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedField<T> field = new GeneratedField<T>(this, false, name, visibility, initialValue); mGeneratedFields.Add(field); return field; } /// <summary> /// Adds a new instance field to the type definition (with initial value). /// </summary> /// <param name="type">Type of the field to add.</param> /// <param name="name">Name of the field to add (<c>null</c> to create a random name).</param> /// <param name="visibility">Visibility of the field.</param> /// <param name="initialValue">Initial value of the field (must be of the specified <paramref name="type"/>).</param> /// <returns>The added field.</returns> /// <exception cref="ArgumentNullException">The specified <paramref name="type"/> is <c>null</c>.</exception> /// <exception cref="ArgumentException"> /// The initial value is not assignable to a field of the specified type /// -or- /// The field to add is a value type, initial value <c>null</c> is not allowed. /// </exception> public IGeneratedField AddField( Type type, string name, Visibility visibility, object initialValue) { EnsureThatIdentifierHasNotBeenUsedYet(name); if (type == null) throw new ArgumentNullException(nameof(type)); if (initialValue != null && !type.IsInstanceOfType(initialValue)) throw new ArgumentException("The initial value is not assignable to a field of the specified type.", nameof(initialValue)); if (initialValue == null && type.IsValueType) throw new ArgumentException("The field to add is a value type, initial value <null> is not allowed.", nameof(initialValue)); var constructor = typeof(GeneratedField<>) .MakeGenericType(type) .GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, Type.DefaultBinder, new[] { typeof(TypeDefinition), typeof(bool), typeof(string), typeof(Visibility), type }, null); Debug.Assert(constructor != null, nameof(constructor) + " != null"); IGeneratedFieldInternal field = (IGeneratedFieldInternal)constructor.Invoke(new[] { this, false, name, visibility, initialValue }); mGeneratedFields.Add(field); return field; } /// <summary> /// Adds a new instance field to the type definition (with custom initializer). /// </summary> /// <typeparam name="T">Type of the field to add.</typeparam> /// <param name="name">Name of the field to add (<c>null</c> to create a random name).</param> /// <param name="visibility">Visibility of the field.</param> /// <param name="initializer"> /// A callback that provides an implementation pushing an object onto the evaluation stack to use as the initial /// value for the generated field. /// </param> /// <returns>The added field.</returns> /// <exception cref="ArgumentNullException"><paramref name="initializer"/> is <c>null</c>.</exception> public IGeneratedField<T> AddField<T>(string name, Visibility visibility, FieldInitializer initializer) { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedField<T> field = new GeneratedField<T>(this, false, name, visibility, initializer); mGeneratedFields.Add(field); return field; } /// <summary> /// Adds a new instance field to the type definition (with custom initializer). /// </summary> /// <param name="type">Type of the field to add.</param> /// <param name="name">Name of the field to add (<c>null</c> to create a random name).</param> /// <param name="visibility">Visibility of the field.</param> /// <param name="initializer"> /// A callback that provides an implementation pushing an object onto the evaluation stack to use as the initial /// value for the generated field. /// </param> /// <returns>The added field.</returns> /// <exception cref="ArgumentNullException"> /// The specified <paramref name="type"/> or <paramref name="initializer"/> is <c>null</c>. /// </exception> public IGeneratedField AddField( Type type, string name, Visibility visibility, FieldInitializer initializer) { EnsureThatIdentifierHasNotBeenUsedYet(name); if (type == null) throw new ArgumentNullException(nameof(type)); var constructor = typeof(GeneratedField<>) .MakeGenericType(type) .GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, Type.DefaultBinder, new[] { typeof(TypeDefinition), typeof(bool), typeof(string), typeof(Visibility), typeof(FieldInitializer) }, null); Debug.Assert(constructor != null, nameof(constructor) + " != null"); IGeneratedFieldInternal field = (IGeneratedFieldInternal)constructor.Invoke(new object[] { this, false, name, visibility, initializer }); mGeneratedFields.Add(field); return field; } /// <summary> /// Adds a new instance field to the type definition (with factory callback for an initial value). /// </summary> /// <typeparam name="T">Type of the field to add.</typeparam> /// <param name="name">Name of the field to add (<c>null</c> to create a random name).</param> /// <param name="visibility">Visibility of the field.</param> /// <param name="provideInitialValueCallback">Factory callback providing the initial value of the field.</param> /// <returns>The added field.</returns> /// <exception cref="ArgumentNullException"><paramref name="provideInitialValueCallback"/> is <c>null</c>.</exception> public IGeneratedField<T> AddField<T>(string name, Visibility visibility, ProvideValueCallback<T> provideInitialValueCallback) { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedField<T> field = new GeneratedField<T>(this, false, name, visibility, provideInitialValueCallback); mGeneratedFields.Add(field); return field; } /// <summary> /// Adds a new instance field to the type definition (with factory callback for an initial value). /// </summary> /// <param name="type">Type of the field to add.</param> /// <param name="name">Name of the field to add (<c>null</c> to create a random name).</param> /// <param name="visibility">Visibility of the field.</param> /// <param name="provideInitialValueCallback">Factory callback providing the initial value of the field.</param> /// <returns>The added field.</returns> /// <exception cref="ArgumentNullException"> /// The specified <paramref name="type"/> or <paramref name="provideInitialValueCallback"/> is <c>null</c>. /// </exception> public IGeneratedField AddField( Type type, string name, Visibility visibility, ProvideValueCallback provideInitialValueCallback) { EnsureThatIdentifierHasNotBeenUsedYet(name); if (type == null) throw new ArgumentNullException(nameof(type)); var constructor = typeof(GeneratedField<>) .MakeGenericType(type) .GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, Type.DefaultBinder, new[] { typeof(TypeDefinition), typeof(bool), typeof(string), typeof(Visibility), typeof(ProvideValueCallback) }, null); Debug.Assert(constructor != null, nameof(constructor) + " != null"); IGeneratedFieldInternal field = (IGeneratedFieldInternal)constructor.Invoke(new object[] { this, false, name, visibility, provideInitialValueCallback }); mGeneratedFields.Add(field); return field; } /// <summary> /// Adds a new static field to the type definition (without an initial value). /// </summary> /// <typeparam name="T">Type of the field to add.</typeparam> /// <param name="name">Name of the field to add (<c>null</c> to create a random name).</param> /// <param name="visibility">Visibility of the field.</param> /// <returns>The added field.</returns> public IGeneratedField<T> AddStaticField<T>(string name, Visibility visibility) { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedField<T> field = new GeneratedField<T>(this, true, name, visibility); mGeneratedFields.Add(field); return field; } /// <summary> /// Adds a new static field to the type definition (without an initial value). /// </summary> /// <param name="type">Type of the field to add.</param> /// <param name="name">Name of the field to add (<c>null</c> to create a random name).</param> /// <param name="visibility">Visibility of the field.</param> /// <returns>The added field.</returns> public IGeneratedField AddStaticField(Type type, string name, Visibility visibility) { EnsureThatIdentifierHasNotBeenUsedYet(name); if (type == null) throw new ArgumentNullException(nameof(type)); var constructor = typeof(GeneratedField<>) .MakeGenericType(type) .GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, Type.DefaultBinder, new[] { typeof(TypeDefinition), typeof(bool), typeof(string), typeof(Visibility) }, null); Debug.Assert(constructor != null, nameof(constructor) + " != null"); IGeneratedFieldInternal field = (IGeneratedFieldInternal)constructor.Invoke(new object[] { this, true, name, visibility }); mGeneratedFields.Add(field); return field; } /// <summary> /// Adds a new static field to the type definition (with initial value). /// </summary> /// <typeparam name="T">Type of the field to add.</typeparam> /// <param name="name">Name of the field to add (<c>null</c> to create a random name).</param> /// <param name="visibility">Visibility of the field.</param> /// <param name="initialValue">Initial value of the field.</param> /// <returns>The added field.</returns> public IGeneratedField<T> AddStaticField<T>(string name, Visibility visibility, T initialValue) { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedField<T> field = new GeneratedField<T>(this, true, name, visibility, initialValue); mGeneratedFields.Add(field); return field; } /// <summary> /// Adds a new static field to the type definition (with initial value). /// </summary> /// <param name="type">Type of the field to add.</param> /// <param name="name">Name of the field to add (<c>null</c> to create a random name).</param> /// <param name="visibility">Visibility of the field.</param> /// <param name="initialValue">Initial value of the field.</param> /// <returns>The added field.</returns> /// <exception cref="ArgumentNullException">The specified <paramref name="type"/> is <c>null</c>.</exception> /// <exception cref="ArgumentException"> /// The initial value is not assignable to a field of the specified type /// -or- /// The field to add is a value type, initial value <c>null</c> is not allowed. /// </exception> public IGeneratedField AddStaticField( Type type, string name, Visibility visibility, object initialValue) { EnsureThatIdentifierHasNotBeenUsedYet(name); if (type == null) throw new ArgumentNullException(nameof(type)); if (initialValue != null && !type.IsInstanceOfType(initialValue)) throw new ArgumentException("The initial value is not assignable to a field of the specified type.", nameof(initialValue)); if (initialValue == null && type.IsValueType) throw new ArgumentException("The field to add is a value type, initial value <null> is not allowed.", nameof(initialValue)); var constructor = typeof(GeneratedField<>) .MakeGenericType(type) .GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, Type.DefaultBinder, new[] { typeof(TypeDefinition), typeof(bool), typeof(string), typeof(Visibility), type }, null); Debug.Assert(constructor != null, nameof(constructor) + " != null"); IGeneratedFieldInternal field = (IGeneratedFieldInternal)constructor.Invoke(new[] { this, true, name, visibility, initialValue }); mGeneratedFields.Add(field); return field; } /// <summary> /// Adds a new static field to the type definition (with custom initializer). /// </summary> /// <typeparam name="T">Type of the field to add.</typeparam> /// <param name="name">Name of the field to add (<c>null</c> to create a random name).</param> /// <param name="visibility">Visibility of the field.</param> /// <param name="initializer"> /// A callback that provides an implementation pushing an object onto the evaluation stack to use as the initial /// value for the generated field. /// </param> /// <returns>The added field.</returns> /// <exception cref="ArgumentNullException"><paramref name="initializer"/> is <c>null</c>.</exception> public IGeneratedField<T> AddStaticField<T>(string name, Visibility visibility, FieldInitializer initializer) { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedField<T> field = new GeneratedField<T>(this, true, name, visibility, initializer); mGeneratedFields.Add(field); return field; } /// <summary> /// Adds a new static field to the type definition (with custom initializer). /// </summary> /// <param name="type">Type of the field to add.</param> /// <param name="name">Name of the field to add (<c>null</c> to create a random name).</param> /// <param name="visibility">Visibility of the field.</param> /// <param name="initializer"> /// A callback that provides an implementation pushing an object onto the evaluation stack to use as the initial /// value for the generated field. /// </param> /// <returns>The added field.</returns> /// <exception cref="ArgumentNullException"> /// The specified <paramref name="type"/> or <paramref name="initializer"/> is <c>null</c>. /// </exception> public IGeneratedField AddStaticField( Type type, string name, Visibility visibility, FieldInitializer initializer) { EnsureThatIdentifierHasNotBeenUsedYet(name); if (type == null) throw new ArgumentNullException(nameof(type)); var constructor = typeof(GeneratedField<>) .MakeGenericType(type) .GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, Type.DefaultBinder, new[] { typeof(TypeDefinition), typeof(bool), typeof(string), typeof(Visibility), typeof(FieldInitializer) }, null); Debug.Assert(constructor != null, nameof(constructor) + " != null"); IGeneratedFieldInternal field = (IGeneratedFieldInternal)constructor.Invoke(new object[] { this, true, name, visibility, initializer }); mGeneratedFields.Add(field); return field; } /// <summary> /// Adds a new static field to the type definition (with factory callback for an initial value). /// </summary> /// <typeparam name="T">Type of the field to add.</typeparam> /// <param name="name">Name of the field to add (<c>null</c> to create a random name).</param> /// <param name="visibility">Visibility of the field.</param> /// <param name="provideInitialValueCallback">Factory callback providing the initial value of the field.</param> /// <returns>The added field.</returns> /// <exception cref="ArgumentNullException"><paramref name="provideInitialValueCallback"/> is <c>null</c>.</exception> public IGeneratedField<T> AddStaticField<T>(string name, Visibility visibility, ProvideValueCallback<T> provideInitialValueCallback) { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedField<T> field = new GeneratedField<T>(this, true, name, visibility, provideInitialValueCallback); mGeneratedFields.Add(field); return field; } /// <summary> /// Adds a new static field to the type definition (with factory callback for an initial value). /// </summary> /// <param name="type">Type of the field to add.</param> /// <param name="name">Name of the field to add (<c>null</c> to create a random name).</param> /// <param name="visibility">Visibility of the field.</param> /// <param name="provideInitialValueCallback">Factory callback providing the initial value of the field.</param> /// <returns>The added field.</returns> /// <exception cref="ArgumentNullException"> /// The specified <paramref name="type"/> or <paramref name="provideInitialValueCallback"/> is <c>null</c>. /// </exception> public IGeneratedField AddStaticField( Type type, string name, Visibility visibility, ProvideValueCallback provideInitialValueCallback) { EnsureThatIdentifierHasNotBeenUsedYet(name); var constructor = typeof(GeneratedField<>) .MakeGenericType(type) .GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, Type.DefaultBinder, new[] { typeof(TypeDefinition), typeof(bool), typeof(string), typeof(Visibility), typeof(ProvideValueCallback) }, null); Debug.Assert(constructor != null, nameof(constructor) + " != null"); IGeneratedFieldInternal field = (IGeneratedFieldInternal)constructor.Invoke(new object[] { this, true, name, visibility, provideInitialValueCallback }); mGeneratedFields.Add(field); return field; } #endregion #region Adding Events /// <summary> /// Adds a new instance event to the type definition. /// </summary> /// <typeparam name="T">Type of the event to add.</typeparam> /// <param name="name">Name of the event to add (<c>null</c> to create a random name).</param> /// <param name="visibility">Visibility of the event.</param> /// <param name="implementation"> /// Implementation strategy that implements the add/remove accessor methods and the event raiser method, if added. /// </param> /// <returns>The added event.</returns> /// <exception cref="ArgumentNullException"><paramref name="implementation"/> is <c>null</c>.</exception> public IGeneratedEvent<T> AddEvent<T>(string name, Visibility visibility, IEventImplementation implementation) where T : Delegate { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedEvent<T> generatedEvent = new GeneratedEvent<T>( this, EventKind.Normal, name, visibility, implementation); mGeneratedEvents.Add(generatedEvent); return generatedEvent; } /// <summary> /// Adds a new instance event to the type definition. /// </summary> /// <typeparam name="T">Type of the event to add.</typeparam> /// <param name="name">Name of the event to add (<c>null</c> to create a random name).</param> /// <param name="visibility">Visibility of the event.</param> /// <param name="addAccessorImplementationCallback">A callback that implements the add accessor method of the event.</param> /// <param name="removeAccessorImplementationCallback">A callback that implements the remove accessor method of the event.</param> /// <returns>The added event.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="addAccessorImplementationCallback"/> or <paramref name="removeAccessorImplementationCallback"/> is <c>null</c>. /// </exception> public IGeneratedEvent<T> AddEvent<T>( string name, Visibility visibility, EventAccessorImplementationCallback addAccessorImplementationCallback, EventAccessorImplementationCallback removeAccessorImplementationCallback) where T : Delegate { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedEvent<T> generatedEvent = new GeneratedEvent<T>( this, EventKind.Normal, name, visibility, addAccessorImplementationCallback, removeAccessorImplementationCallback); mGeneratedEvents.Add(generatedEvent); return generatedEvent; } /// <summary> /// Adds a new abstract instance event to the type definition (add/remove methods only). /// </summary> /// <typeparam name="T">Type of the event to add.</typeparam> /// <param name="eventName">Name of the event to add (<c>null</c> to create a random name).</param> /// <param name="visibility">Visibility of the event.</param> /// <returns>The added event.</returns> public IGeneratedEvent<T> AddAbstractEvent<T>(string eventName, Visibility visibility) where T : Delegate { EnsureThatIdentifierHasNotBeenUsedYet(eventName); GeneratedEvent<T> generatedEvent = new GeneratedEvent<T>( this, EventKind.Abstract, eventName, visibility, null); mGeneratedEvents.Add(generatedEvent); return generatedEvent; } /// <summary> /// Adds a new virtual instance event to the type definition. /// </summary> /// <typeparam name="T">Type of the event to add.</typeparam> /// <param name="eventName">Name of the event to add (<c>null</c> to create a random name).</param> /// <param name="visibility">Visibility of the event.</param> /// <param name="implementation"> /// Implementation strategy that implements the add/remove accessor methods and the event raiser method, if added. /// </param> /// <returns>The added event.</returns> /// <exception cref="ArgumentNullException"><paramref name="implementation"/> is <c>null</c>.</exception> public IGeneratedEvent<T> AddVirtualEvent<T>( string eventName, Visibility visibility, IEventImplementation implementation) where T : Delegate { EnsureThatIdentifierHasNotBeenUsedYet(eventName); GeneratedEvent<T> generatedEvent = new GeneratedEvent<T>( this, EventKind.Virtual, eventName, visibility, implementation); mGeneratedEvents.Add(generatedEvent); return generatedEvent; } /// <summary> /// Adds a new virtual instance event to the type definition. /// </summary> /// <typeparam name="T">Type of the event to add.</typeparam> /// <param name="name">Name of the event to add (<c>null</c> to create a random name).</param> /// <param name="visibility">Visibility of the event.</param> /// <param name="addAccessorImplementationCallback">A callback that implements the add accessor method of the event.</param> /// <param name="removeAccessorImplementationCallback">A callback that implements the remove accessor method of the event.</param> /// <returns>The added event.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="addAccessorImplementationCallback"/> or <paramref name="removeAccessorImplementationCallback"/> is <c>null</c>. /// </exception> public IGeneratedEvent<T> AddVirtualEvent<T>( string name, Visibility visibility, EventAccessorImplementationCallback addAccessorImplementationCallback, EventAccessorImplementationCallback removeAccessorImplementationCallback) where T : Delegate { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedEvent<T> generatedEvent = new GeneratedEvent<T>( this, EventKind.Virtual, name, visibility, addAccessorImplementationCallback, removeAccessorImplementationCallback); mGeneratedEvents.Add(generatedEvent); return generatedEvent; } /// <summary> /// Adds a new static event to the type definition. /// </summary> /// <typeparam name="T">Type of the event to add.</typeparam> /// <param name="eventName">Name of the event to add (<c>null</c> to create a random name).</param> /// <param name="visibility">Visibility of the event.</param> /// <param name="implementation"> /// Implementation strategy that implements the add/remove accessor methods and the event raiser method, if added. /// </param> /// <returns>The added event.</returns> /// <exception cref="ArgumentNullException"><paramref name="implementation"/> is <c>null</c>.</exception> public IGeneratedEvent<T> AddStaticEvent<T>( string eventName, Visibility visibility, IEventImplementation implementation) where T : Delegate { EnsureThatIdentifierHasNotBeenUsedYet(eventName); GeneratedEvent<T> generatedEvent = new GeneratedEvent<T>( this, EventKind.Static, eventName, visibility, implementation); mGeneratedEvents.Add(generatedEvent); return generatedEvent; } /// <summary> /// Adds a new static event to the type definition. /// </summary> /// <typeparam name="T">Type of the event to add.</typeparam> /// <param name="name">Name of the event to add (<c>null</c> to create a random name).</param> /// <param name="visibility">Visibility of the event.</param> /// <param name="addAccessorImplementationCallback">A callback that implements the add accessor method of the event.</param> /// <param name="removeAccessorImplementationCallback">A callback that implements the remove accessor method of the event.</param> /// <returns>The added event.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="addAccessorImplementationCallback"/> or <paramref name="removeAccessorImplementationCallback"/> is <c>null</c>. /// </exception> public IGeneratedEvent<T> AddStaticEvent<T>( string name, Visibility visibility, EventAccessorImplementationCallback addAccessorImplementationCallback, EventAccessorImplementationCallback removeAccessorImplementationCallback) where T : Delegate { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedEvent<T> generatedEvent = new GeneratedEvent<T>( this, EventKind.Static, name, visibility, addAccessorImplementationCallback, removeAccessorImplementationCallback); mGeneratedEvents.Add(generatedEvent); return generatedEvent; } /// <summary> /// Overrides the specified inherited event in the type definition. /// </summary> /// <param name="eventToOverride">Event to override.</param> /// <param name="implementation"> /// Implementation strategy that implements the add/remove accessor methods and the event raiser method, if added. /// </param> /// <returns>The added event overriding the specified inherited event.</returns> /// <exception cref="ArgumentNullException"><paramref name="implementation"/> is <c>null</c>.</exception> public IGeneratedEvent<T> AddEventOverride<T>(IInheritedEvent<T> eventToOverride, IEventImplementation implementation) where T : Delegate { EnsureThatIdentifierHasNotBeenUsedYet(eventToOverride.Name); // ensure that the property is abstract, virtual or an overrider switch (eventToOverride.Kind) { case EventKind.Abstract: case EventKind.Virtual: case EventKind.Override: break; default: throw new CodeGenException($"The specified event ({eventToOverride.Name}) is neither abstract, virtual nor an override of a virtual/abstract event."); } // create event override GeneratedEvent<T> overrider = new GeneratedEvent<T>(this, eventToOverride, implementation); mGeneratedEvents.Add(overrider); return overrider; } /// <summary> /// Overrides the specified inherited event in the type definition. /// </summary> /// <param name="eventToOverride">Event to override.</param> /// <param name="addAccessorImplementationCallback">A callback that implements the add accessor method of the event.</param> /// <param name="removeAccessorImplementationCallback">A callback that implements the remove accessor method of the event.</param> /// <returns>The added event overriding the specified inherited event.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="addAccessorImplementationCallback"/> or <paramref name="removeAccessorImplementationCallback"/> is <c>null</c>. /// </exception> public IGeneratedEvent<T> AddEventOverride<T>( IInheritedEvent<T> eventToOverride, EventAccessorImplementationCallback addAccessorImplementationCallback, EventAccessorImplementationCallback removeAccessorImplementationCallback) where T : Delegate { EnsureThatIdentifierHasNotBeenUsedYet(eventToOverride.Name); // ensure that the property is abstract, virtual or an overrider switch (eventToOverride.Kind) { case EventKind.Abstract: case EventKind.Virtual: case EventKind.Override: break; default: throw new CodeGenException($"The specified event ({eventToOverride.Name}) is neither abstract, virtual nor an override of a virtual/abstract event."); } // create event override GeneratedEvent<T> overrider = new GeneratedEvent<T>(this, eventToOverride, addAccessorImplementationCallback, removeAccessorImplementationCallback); mGeneratedEvents.Add(overrider); return overrider; } #endregion #region Adding Properties /// <summary> /// Adds a new instance property to the type definition. The property does not have accessor methods. /// The desired accessor methods can be added using <see cref="IGeneratedProperty.AddGetAccessor"/> and /// <see cref="IGeneratedProperty.AddSetAccessor"/>). /// </summary> /// <param name="name">Name of the property to add (<c>null</c> to create a random name).</param> /// <returns>The added property.</returns> public IGeneratedProperty<T> AddProperty<T>(string name) { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedProperty<T> property = new GeneratedProperty<T>(this, PropertyKind.Normal, name); mGeneratedProperties.Add(property); return property; } /// <summary> /// Adds a new instance property to the type definition. The property does not have accessor methods. /// The desired accessor methods can be added using <see cref="IGeneratedProperty.AddGetAccessor"/> and /// <see cref="IGeneratedProperty.AddSetAccessor"/>). /// </summary> /// <param name="type">Type of the property to add.</param> /// <param name="name">Name of the property to add (<c>null</c> to create a random name).</param> /// <returns>The added property.</returns> public IGeneratedProperty AddProperty(Type type, string name) { EnsureThatIdentifierHasNotBeenUsedYet(name); if (type == null) throw new ArgumentNullException(nameof(type)); var constructor = typeof(GeneratedProperty<>) .MakeGenericType(type) .GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, Type.DefaultBinder, new[] { typeof(TypeDefinition), typeof(PropertyKind), typeof(string) }, null); Debug.Assert(constructor != null, nameof(constructor) + " != null"); IGeneratedProperty property = (IGeneratedProperty)constructor.Invoke(new object[] { this, PropertyKind.Normal, name }); mGeneratedProperties.Add(property); return property; } /// <summary> /// Adds a new instance property to the type definition. The property does not have accessor methods. /// The desired accessor methods can be added using <see cref="IGeneratedProperty.AddGetAccessor"/> and /// <see cref="IGeneratedProperty.AddSetAccessor"/>). /// </summary> /// <param name="name">Name of the property to add (<c>null</c> to create a random name).</param> /// <param name="implementation">Implementation strategy that implements the get/set accessors of the property.</param> /// <returns>The added property.</returns> /// <exception cref="ArgumentNullException"><paramref name="implementation"/> is <c>null</c>.</exception> public IGeneratedProperty<T> AddProperty<T>(string name, IPropertyImplementation implementation) { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedProperty<T> property = new GeneratedProperty<T>(this, PropertyKind.Normal, name, implementation); mGeneratedProperties.Add(property); return property; } /// <summary> /// Adds a new instance property to the type definition. The property does not have accessor methods. /// The desired accessor methods can be added using <see cref="IGeneratedProperty.AddGetAccessor"/> and /// <see cref="IGeneratedProperty.AddSetAccessor"/>). /// </summary> /// <param name="type">Type of the property to add.</param> /// <param name="name">Name of the property to add (<c>null</c> to create a random name).</param> /// <param name="implementation">Implementation strategy that implements the get/set accessors of the property.</param> /// <returns>The added property.</returns> /// <exception cref="ArgumentNullException"><paramref name="implementation"/> is <c>null</c>.</exception> public IGeneratedProperty AddProperty(Type type, string name, IPropertyImplementation implementation) { EnsureThatIdentifierHasNotBeenUsedYet(name); if (type == null) throw new ArgumentNullException(nameof(type)); var constructor = typeof(GeneratedProperty<>) .MakeGenericType(type) .GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, Type.DefaultBinder, new[] { typeof(TypeDefinition), typeof(PropertyKind), typeof(string), typeof(IPropertyImplementation) }, null); Debug.Assert(constructor != null, nameof(constructor) + " != null"); IGeneratedProperty property = (IGeneratedProperty)constructor.Invoke(new object[] { this, PropertyKind.Normal, name, implementation }); mGeneratedProperties.Add(property); return property; } /// <summary> /// Adds a new abstract instance property to the type definition. /// </summary> /// <param name="name">Name of the property to add (<c>null</c> to create a random name).</param> /// <returns>The added property.</returns> public IGeneratedProperty<T> AddAbstractProperty<T>(string name) { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedProperty<T> property = new GeneratedProperty<T>(this, PropertyKind.Abstract, name, null); mGeneratedProperties.Add(property); return property; } /// <summary> /// Adds a new abstract instance property to the type definition. /// </summary> /// <param name="type">Type of the property to add.</param> /// <param name="name">Name of the property to add (<c>null</c> to create a random name).</param> /// <returns>The added property.</returns> public IGeneratedProperty AddAbstractProperty(Type type, string name) { EnsureThatIdentifierHasNotBeenUsedYet(name); if (type == null) throw new ArgumentNullException(nameof(type)); var constructor = typeof(GeneratedProperty<>) .MakeGenericType(type) .GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, Type.DefaultBinder, new[] { typeof(TypeDefinition), typeof(PropertyKind), typeof(string) }, null); Debug.Assert(constructor != null, nameof(constructor) + " != null"); IGeneratedProperty property = (IGeneratedProperty)constructor.Invoke(new object[] { this, PropertyKind.Abstract, name }); mGeneratedProperties.Add(property); return property; } /// <summary> /// Adds a new virtual instance property to the type definition. The property does not have accessor methods. /// The desired accessor methods can be added using <see cref="IGeneratedProperty.AddGetAccessor"/> and /// <see cref="IGeneratedProperty.AddSetAccessor"/>). /// </summary> /// <param name="name">Name of the property to add (<c>null</c> to create a random name).</param> /// <returns>The added property.</returns> public IGeneratedProperty<T> AddVirtualProperty<T>(string name) { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedProperty<T> property = new GeneratedProperty<T>(this, PropertyKind.Virtual, name); mGeneratedProperties.Add(property); return property; } /// <summary> /// Adds a new virtual instance property to the type definition. The property does not have accessor methods. /// The desired accessor methods can be added using <see cref="IGeneratedProperty.AddGetAccessor"/> and /// <see cref="IGeneratedProperty.AddSetAccessor"/>). /// </summary> /// <param name="type">Type of the property to add.</param> /// <param name="name">Name of the property to add (<c>null</c> to create a random name).</param> /// <returns>The added property.</returns> public IGeneratedProperty AddVirtualProperty(Type type, string name) { EnsureThatIdentifierHasNotBeenUsedYet(name); if (type == null) throw new ArgumentNullException(nameof(type)); var constructor = typeof(GeneratedProperty<>) .MakeGenericType(type) .GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, Type.DefaultBinder, new[] { typeof(TypeDefinition), typeof(PropertyKind), typeof(string) }, null); Debug.Assert(constructor != null, nameof(constructor) + " != null"); IGeneratedProperty property = (IGeneratedProperty)constructor.Invoke(new object[] { this, PropertyKind.Virtual, name }); mGeneratedProperties.Add(property); return property; } /// <summary> /// Adds a new virtual instance property to the type definition. The property does not have accessor methods. /// The desired accessor methods can be added using <see cref="IGeneratedProperty.AddGetAccessor"/> and /// <see cref="IGeneratedProperty.AddSetAccessor"/>). /// </summary> /// <param name="name">Name of the property to add (<c>null</c> to create a random name).</param> /// <param name="implementation">Implementation strategy that implements the get/set accessors of the property.</param> /// <returns>The added property.</returns> /// <exception cref="ArgumentNullException"><paramref name="implementation"/> is <c>null</c>.</exception> public IGeneratedProperty<T> AddVirtualProperty<T>(string name, IPropertyImplementation implementation) { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedProperty<T> property = new GeneratedProperty<T>(this, PropertyKind.Virtual, name, implementation); mGeneratedProperties.Add(property); return property; } /// <summary> /// Adds a new virtual instance property to the type definition. The property does not have accessor methods. /// The desired accessor methods can be added using <see cref="IGeneratedProperty.AddGetAccessor"/> and /// <see cref="IGeneratedProperty.AddSetAccessor"/>). /// </summary> /// <param name="type">Type of the property to add.</param> /// <param name="name">Name of the property to add (<c>null</c> to create a random name).</param> /// <param name="implementation">Implementation strategy that implements the get/set accessors of the property.</param> /// <returns>The added property.</returns> /// <exception cref="ArgumentNullException"><paramref name="implementation"/> is <c>null</c>.</exception> public IGeneratedProperty AddVirtualProperty(Type type, string name, IPropertyImplementation implementation) { EnsureThatIdentifierHasNotBeenUsedYet(name); if (type == null) throw new ArgumentNullException(nameof(type)); var constructor = typeof(GeneratedProperty<>) .MakeGenericType(type) .GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, Type.DefaultBinder, new[] { typeof(TypeDefinition), typeof(PropertyKind), typeof(string), typeof(IPropertyImplementation) }, null); Debug.Assert(constructor != null, nameof(constructor) + " != null"); IGeneratedProperty property = (IGeneratedProperty)constructor.Invoke(new object[] { this, PropertyKind.Virtual, name, implementation }); mGeneratedProperties.Add(property); return property; } /// <summary> /// Adds a new static property to the type definition. The property does not have accessor methods. /// The desired accessor methods can be added using <see cref="IGeneratedProperty.AddGetAccessor"/> and /// <see cref="IGeneratedProperty.AddSetAccessor"/>). /// </summary> /// <param name="name">Name of the property to add (<c>null</c> to create a random name).</param> /// <returns>The added property.</returns> public IGeneratedProperty<T> AddStaticProperty<T>(string name) { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedProperty<T> property = new GeneratedProperty<T>(this, PropertyKind.Static, name); mGeneratedProperties.Add(property); return property; } /// <summary> /// Adds a new static property to the type definition. The property does not have accessor methods. /// The desired accessor methods can be added using <see cref="IGeneratedProperty.AddGetAccessor"/> and /// <see cref="IGeneratedProperty.AddSetAccessor"/>). /// </summary> /// <param name="type">Type of the property to add.</param> /// <param name="name">Name of the property to add (<c>null</c> to create a random name).</param> /// <returns>The added property.</returns> public IGeneratedProperty AddStaticProperty(Type type, string name) { EnsureThatIdentifierHasNotBeenUsedYet(name); if (type == null) throw new ArgumentNullException(nameof(type)); var constructor = typeof(GeneratedProperty<>) .MakeGenericType(type) .GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, Type.DefaultBinder, new[] { typeof(TypeDefinition), typeof(PropertyKind), typeof(string) }, null); Debug.Assert(constructor != null, nameof(constructor) + " != null"); IGeneratedProperty property = (IGeneratedProperty)constructor.Invoke(new object[] { this, PropertyKind.Static, name }); mGeneratedProperties.Add(property); return property; } /// <summary> /// Adds a new static property to the type definition. /// </summary> /// <param name="name">Name of the property to add (<c>null</c> to create a random name).</param> /// <param name="implementation">Implementation strategy that implements the get/set accessors of the property.</param> /// <returns>The added property.</returns> /// <exception cref="ArgumentNullException"><paramref name="implementation"/> is <c>null</c>.</exception> public IGeneratedProperty<T> AddStaticProperty<T>(string name, IPropertyImplementation implementation) { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedProperty<T> property = new GeneratedProperty<T>(this, PropertyKind.Static, name, implementation); mGeneratedProperties.Add(property); return property; } /// <summary> /// Adds a new static property to the type definition. The property does not have accessor methods. /// The desired accessor methods can be added using <see cref="IGeneratedProperty.AddGetAccessor"/> and /// <see cref="IGeneratedProperty.AddSetAccessor"/>). /// </summary> /// <param name="type">Type of the property to add.</param> /// <param name="name">Name of the property to add (<c>null</c> to create a random name).</param> /// <param name="implementation">Implementation strategy that implements the get/set accessors of the property.</param> /// <returns>The added property.</returns> /// <exception cref="ArgumentNullException"><paramref name="implementation"/> is <c>null</c>.</exception> public IGeneratedProperty AddStaticProperty(Type type, string name, IPropertyImplementation implementation) { EnsureThatIdentifierHasNotBeenUsedYet(name); if (type == null) throw new ArgumentNullException(nameof(type)); var constructor = typeof(GeneratedProperty<>) .MakeGenericType(type) .GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, Type.DefaultBinder, new[] { typeof(TypeDefinition), typeof(PropertyKind), typeof(string), typeof(IPropertyImplementation) }, null); Debug.Assert(constructor != null, nameof(constructor) + " != null"); IGeneratedProperty property = (IGeneratedProperty)constructor.Invoke(new object[] { this, PropertyKind.Static, name, implementation }); mGeneratedProperties.Add(property); return property; } /// <summary> /// Adds an override for the specified inherited property. /// </summary> /// <param name="property">Property to add an override for.</param> /// <param name="implementation">Implementation strategy that implements the get/set accessors of the property.</param> /// <returns>The added property override.</returns> /// <exception cref="ArgumentNullException"><paramref name="implementation"/> is <c>null</c>.</exception> public IGeneratedProperty<T> AddPropertyOverride<T>( IInheritedProperty<T> property, IPropertyImplementation implementation) { EnsureThatIdentifierHasNotBeenUsedYet(property.Name); // ensure that the property is abstract, virtual or overriding an abstract/virtual property switch (property.Kind) { case PropertyKind.Abstract: case PropertyKind.Virtual: case PropertyKind.Override: break; default: throw new CodeGenException($"The specified property ({property.Name}) is neither abstract, nor virtual nor an overrider."); } // add the property GeneratedProperty<T> overrider = new GeneratedProperty<T>(this, property, implementation); mGeneratedProperties.Add(overrider); return overrider; } /// <summary> /// Adds an override for the specified inherited property. /// </summary> /// <param name="property">Property to add an override for.</param> /// <param name="implementation">Implementation strategy that implements the get/set accessors of the property.</param> /// <returns>The added property override.</returns> /// <exception cref="ArgumentNullException"><paramref name="implementation"/> is <c>null</c>.</exception> public IGeneratedProperty AddPropertyOverride( IInheritedProperty property, IPropertyImplementation implementation) { EnsureThatIdentifierHasNotBeenUsedYet(property.Name); // ensure that the property is abstract, virtual or overriding an abstract/virtual property switch (property.Kind) { case PropertyKind.Abstract: case PropertyKind.Virtual: case PropertyKind.Override: break; default: throw new CodeGenException($"The specified property ({property.Name}) is neither abstract, nor virtual nor an overrider."); } // add the property var constructor = typeof(GeneratedProperty<>) .MakeGenericType(property.PropertyType) .GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, Type.DefaultBinder, new[] { typeof(TypeDefinition), typeof(IInheritedProperty<>).MakeGenericType(property.PropertyType), typeof(PropertyImplementation) }, null); Debug.Assert(constructor != null, nameof(constructor) + " != null"); IGeneratedProperty overrider = (IGeneratedProperty)constructor.Invoke(new object[] { this, property, implementation }); mGeneratedProperties.Add(overrider); return overrider; } /// <summary> /// Adds an override for the specified inherited property. /// </summary> /// <param name="property">Property to add an override for.</param> /// <param name="getAccessorImplementationCallback"> /// A callback that implements the get accessor method of the property /// (may be <c>null</c> if the inherited property does not have a get accessor method). /// </param> /// <param name="setAccessorImplementationCallback"> /// A callback that implements the set accessor method of the property /// (may be <c>null</c> if the inherited property does not have a set accessor method). /// </param> /// <returns>The added property override.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="property"/> has a get accessor, but <paramref name="getAccessorImplementationCallback"/> is <c>null</c> /// -or- /// <paramref name="property"/> has a set accessor, but <paramref name="setAccessorImplementationCallback"/> is <c>null</c> /// </exception> public IGeneratedProperty<T> AddPropertyOverride<T>( IInheritedProperty<T> property, PropertyAccessorImplementationCallback getAccessorImplementationCallback, PropertyAccessorImplementationCallback setAccessorImplementationCallback) { EnsureThatIdentifierHasNotBeenUsedYet(property.Name); // ensure that the property is abstract, virtual or an overrider switch (property.Kind) { case PropertyKind.Abstract: case PropertyKind.Virtual: case PropertyKind.Override: break; default: throw new CodeGenException($"The specified property ({property.Name}) is neither abstract, nor virtual nor an overrider."); } // add the property GeneratedProperty<T> overrider = new GeneratedProperty<T>(this, property, getAccessorImplementationCallback, setAccessorImplementationCallback); mGeneratedProperties.Add(overrider); return overrider; } /// <summary> /// Adds an override for the specified inherited property. /// </summary> /// <param name="property">Property to add an override for.</param> /// <param name="getAccessorImplementationCallback"> /// A callback that implements the get accessor method of the property /// (may be <c>null</c> if the inherited property does not have a get accessor method). /// </param> /// <param name="setAccessorImplementationCallback"> /// A callback that implements the set accessor method of the property /// (may be <c>null</c> if the inherited property does not have a set accessor method). /// </param> /// <returns>The added property override.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="property"/> has a get accessor, but <paramref name="getAccessorImplementationCallback"/> is <c>null</c> /// -or- /// <paramref name="property"/> has a set accessor, but <paramref name="setAccessorImplementationCallback"/> is <c>null</c> /// </exception> public IGeneratedProperty AddPropertyOverride( IInheritedProperty property, PropertyAccessorImplementationCallback getAccessorImplementationCallback, PropertyAccessorImplementationCallback setAccessorImplementationCallback) { EnsureThatIdentifierHasNotBeenUsedYet(property.Name); // ensure that the property is abstract, virtual or an overrider switch (property.Kind) { case PropertyKind.Abstract: case PropertyKind.Virtual: case PropertyKind.Override: break; default: throw new CodeGenException($"The specified property ({property.Name}) is neither abstract, nor virtual nor an overrider."); } // add the property var constructor = typeof(GeneratedProperty<>) .MakeGenericType(property.PropertyType) .GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, Type.DefaultBinder, new[] { typeof(TypeDefinition), typeof(IInheritedProperty<>).MakeGenericType(property.PropertyType), typeof(PropertyAccessorImplementationCallback), typeof(PropertyAccessorImplementationCallback) }, null); Debug.Assert(constructor != null, nameof(constructor) + " != null"); IGeneratedProperty overrider = (IGeneratedProperty)constructor.Invoke(new object[] { this, property, getAccessorImplementationCallback, setAccessorImplementationCallback }); mGeneratedProperties.Add(overrider); return overrider; } #endregion #region Adding Dependency Properties #if NET461 || NET5_0 && WINDOWS /// <summary> /// Adds a new dependency property to the type definition (without initial value). /// </summary> /// <typeparam name="T">Type of the dependency property.</typeparam> /// <param name="name">Name of the dependency property (just the name, not with the 'Property' suffix).</param> /// <param name="isReadOnly"> /// <c>true</c> if the dependency property is read-only; /// <c>false</c> if it is read-write. /// </param> /// <returns>The added dependency property.</returns> public IGeneratedDependencyProperty<T> AddDependencyProperty<T>(string name, bool isReadOnly) { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedDependencyProperty<T> dependencyProperty = new GeneratedDependencyProperty<T>(this, name, isReadOnly); mGeneratedDependencyProperties.Add(dependencyProperty); return dependencyProperty; } /// <summary> /// Adds a new dependency property to the type definition (with initial value). /// </summary> /// <typeparam name="T">Type of the dependency property.</typeparam> /// <param name="name">Name of the dependency property (just the name, not with the 'Property' suffix).</param> /// <param name="isReadOnly"> /// <c>true</c> if the dependency property is read-only; /// <c>false</c> if it is read-write. /// </param> /// <param name="initialValue">Initial value of the dependency property.</param> /// <returns>The added dependency property.</returns> public IGeneratedDependencyProperty<T> AddDependencyProperty<T>(string name, bool isReadOnly, T initialValue) { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedDependencyProperty<T> dependencyProperty = new GeneratedDependencyProperty<T>(this, name, isReadOnly, initialValue); mGeneratedDependencyProperties.Add(dependencyProperty); return dependencyProperty; } /// <summary> /// Adds a new dependency property to the type definition (with custom initializer). /// </summary> /// <typeparam name="T">Type of the dependency property.</typeparam> /// <param name="name">Name of the dependency property (just the name, not with the 'Property' suffix).</param> /// <param name="isReadOnly"> /// <c>true</c> if the dependency property is read-only; /// <c>false</c> if it is read-write. /// </param> /// <param name="initializer"> /// A callback that provides an implementation pushing an object onto the evaluation stack to use as the initial /// value for the generated dependency property. /// </param> /// <returns>The added dependency property.</returns> /// <exception cref="ArgumentNullException"><paramref name="initializer"/> is <c>null</c>.</exception> public IGeneratedDependencyProperty<T> AddDependencyProperty<T>(string name, bool isReadOnly, DependencyPropertyInitializer initializer) { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedDependencyProperty<T> dependencyProperty = new GeneratedDependencyProperty<T>(this, name, isReadOnly, initializer); mGeneratedDependencyProperties.Add(dependencyProperty); return dependencyProperty; } /// <summary> /// Adds a new dependency property to the type definition (with factory callback for an initial value). /// </summary> /// <typeparam name="T">Type of the dependency property.</typeparam> /// <param name="name">Name of the dependency property (just the name, not with the 'Property' suffix).</param> /// <param name="isReadOnly"> /// <c>true</c> if the dependency property is read-only; /// <c>false</c> if it is read-write. /// </param> /// <param name="provideInitialValueCallback">Factory callback providing the initial value of the dependency property.</param> /// <returns>The added dependency property.</returns> /// <exception cref="ArgumentNullException"><paramref name="provideInitialValueCallback"/> is <c>null</c>.</exception> public IGeneratedDependencyProperty<T> AddDependencyProperty<T>(string name, bool isReadOnly, ProvideValueCallback<T> provideInitialValueCallback) { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedDependencyProperty<T> dependencyProperty = new GeneratedDependencyProperty<T>(this, name, isReadOnly, provideInitialValueCallback); mGeneratedDependencyProperties.Add(dependencyProperty); return dependencyProperty; } #elif NETSTANDARD2_0 || NETSTANDARD2_1 // Dependency properties are not supported on .NET Standard... #else #error Unhandled Target Framework. #endif #endregion #region Adding Methods /// <summary> /// Adds a new instance method to the type definition. /// </summary> /// <param name="name">Name of the method to add (<c>null</c> to create a random name).</param> /// <param name="returnType">Return type of the method.</param> /// <param name="parameterTypes">Types of the method's parameters.</param> /// <param name="visibility">Visibility of the method.</param> /// <param name="implementation">Implementation strategy that implements the method.</param> /// <param name="additionalMethodAttributes">Additional method attributes to 'or' with other attributes.</param> /// <returns>The added method.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="returnType"/>, <paramref name="parameterTypes"/> or <paramref name="implementation"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="name"/> is not a valid language independent identifier /// -or- /// <paramref name="parameterTypes"/> contains a null reference. /// </exception> public IGeneratedMethod AddMethod( string name, Type returnType, Type[] parameterTypes, Visibility visibility, IMethodImplementation implementation, MethodAttributes additionalMethodAttributes = 0) { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedMethod method = new GeneratedMethod(this, MethodKind.Normal, name, returnType, parameterTypes, visibility, additionalMethodAttributes, implementation); mGeneratedMethods.Add(method); return method; } /// <summary> /// Adds a new instance method to the type definition. /// </summary> /// <param name="name">Name of the method to add (<c>null</c> to create a random name).</param> /// <param name="returnType">Return type of the method.</param> /// <param name="parameterTypes">Types of the method's parameters.</param> /// <param name="visibility">Visibility of the method.</param> /// <param name="implementationCallback">Callback that implements the method.</param> /// <param name="additionalMethodAttributes">Additional method attributes to 'or' with other attributes.</param> /// <returns>The added method.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="returnType"/>, <paramref name="parameterTypes"/> or <paramref name="implementationCallback"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="name"/> is not a valid language independent identifier /// -or- /// <paramref name="parameterTypes"/> contains a null reference. /// </exception> public IGeneratedMethod AddMethod( string name, Type returnType, Type[] parameterTypes, Visibility visibility, MethodImplementationCallback implementationCallback, MethodAttributes additionalMethodAttributes = 0) { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedMethod method = new GeneratedMethod(this, MethodKind.Normal, name, returnType, parameterTypes, visibility, additionalMethodAttributes, implementationCallback); mGeneratedMethods.Add(method); return method; } /// <summary> /// Adds a new abstract instance method to the type definition. /// </summary> /// <param name="name">Name of the method to add (<c>null</c> to create a random name).</param> /// <param name="returnType">Return type of the method.</param> /// <param name="parameterTypes">Types of the method's parameters.</param> /// <param name="visibility">Visibility of the method.</param> /// <param name="additionalMethodAttributes">Additional method attributes to 'or' with other attributes.</param> /// <returns>The added method.</returns> /// <exception cref="ArgumentNullException"><paramref name="returnType"/> or <paramref name="parameterTypes"/> is <c>null</c>.</exception> /// <exception cref="ArgumentException"> /// <paramref name="name"/> is not a valid language independent identifier /// -or- /// <paramref name="parameterTypes"/> contains a null reference. /// </exception> public IGeneratedMethod AddAbstractMethod( string name, Type returnType, Type[] parameterTypes, Visibility visibility, MethodAttributes additionalMethodAttributes = 0) { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedMethod method = new GeneratedMethod(this, MethodKind.Abstract, name, returnType, parameterTypes, visibility, additionalMethodAttributes, (IMethodImplementation)null); mGeneratedMethods.Add(method); return method; } /// <summary> /// Adds a new virtual instance method to the type definition. /// </summary> /// <param name="name">Name of the method to add (<c>null</c> to create a random name).</param> /// <param name="returnType">Return type of the method.</param> /// <param name="parameterTypes">Types of the method's parameters.</param> /// <param name="visibility">Visibility of the method.</param> /// <param name="implementation">Implementation strategy that implements the method.</param> /// <param name="additionalMethodAttributes">Additional method attributes to 'or' with other attributes.</param> /// <returns>The added method.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="returnType"/>, <paramref name="parameterTypes"/> or <paramref name="implementation"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="name"/> is not a valid language independent identifier /// -or- /// <paramref name="parameterTypes"/> contains a null reference. /// </exception> public IGeneratedMethod AddVirtualMethod( string name, Type returnType, Type[] parameterTypes, Visibility visibility, IMethodImplementation implementation, MethodAttributes additionalMethodAttributes = 0) { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedMethod method = new GeneratedMethod(this, MethodKind.Virtual, name, returnType, parameterTypes, visibility, additionalMethodAttributes, implementation); mGeneratedMethods.Add(method); return method; } /// <summary> /// Adds a new virtual instance method to the type definition. /// </summary> /// <param name="name">Name of the method to add (<c>null</c> to create a random name).</param> /// <param name="returnType">Return type of the method.</param> /// <param name="parameterTypes">Types of the method's parameters.</param> /// <param name="visibility">Visibility of the method.</param> /// <param name="implementationCallback">Callback that implements the method.</param> /// <param name="additionalMethodAttributes">Additional method attributes to 'or' with other attributes.</param> /// <returns>The added method.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="returnType"/>, <paramref name="parameterTypes"/> or <paramref name="implementationCallback"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="name"/> is not a valid language independent identifier /// -or- /// <paramref name="parameterTypes"/> contains a null reference. /// </exception> public IGeneratedMethod AddVirtualMethod( string name, Type returnType, Type[] parameterTypes, Visibility visibility, MethodImplementationCallback implementationCallback, MethodAttributes additionalMethodAttributes = 0) { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedMethod method = new GeneratedMethod(this, MethodKind.Virtual, name, returnType, parameterTypes, visibility, additionalMethodAttributes, implementationCallback); mGeneratedMethods.Add(method); return method; } /// <summary> /// Adds a new static method to the type definition. /// </summary> /// <param name="name">Name of the method to add (<c>null</c> to create a random name).</param> /// <param name="returnType">Return type of the method.</param> /// <param name="parameterTypes">Types of the method's parameters.</param> /// <param name="visibility">Visibility of the method.</param> /// <param name="implementation">Implementation strategy that implements the method.</param> /// <param name="additionalMethodAttributes">Additional method attributes to 'or' with other attributes.</param> /// <returns>The added method.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="returnType"/>, <paramref name="parameterTypes"/> or <paramref name="implementation"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="name"/> is not a valid language independent identifier /// -or- /// <paramref name="parameterTypes"/> contains a null reference. /// </exception> public IGeneratedMethod AddStaticMethod( string name, Type returnType, Type[] parameterTypes, Visibility visibility, IMethodImplementation implementation, MethodAttributes additionalMethodAttributes = 0) { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedMethod method = new GeneratedMethod(this, MethodKind.Static, name, returnType, parameterTypes, visibility, additionalMethodAttributes, implementation); mGeneratedMethods.Add(method); return method; } /// <summary> /// Adds a new static method to the type definition. /// </summary> /// <param name="name">Name of the method to add (<c>null</c> to create a random name).</param> /// <param name="returnType">Return type of the method.</param> /// <param name="parameterTypes">Types of the method's parameters.</param> /// <param name="visibility">Visibility of the method.</param> /// <param name="implementationCallback">Callback that implements the method.</param> /// <param name="additionalMethodAttributes">Additional method attributes to 'or' with other attributes.</param> /// <returns>The added method.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="returnType"/>, <paramref name="parameterTypes"/> or <paramref name="implementationCallback"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="name"/> is not a valid language independent identifier /// -or- /// <paramref name="parameterTypes"/> contains a null reference. /// </exception> public IGeneratedMethod AddStaticMethod( string name, Type returnType, Type[] parameterTypes, Visibility visibility, MethodImplementationCallback implementationCallback, MethodAttributes additionalMethodAttributes = 0) { EnsureThatIdentifierHasNotBeenUsedYet(name); GeneratedMethod method = new GeneratedMethod(this, MethodKind.Static, name, returnType, parameterTypes, visibility, additionalMethodAttributes, implementationCallback); mGeneratedMethods.Add(method); return method; } /// <summary> /// Adds an override for an inherited method. /// </summary> /// <param name="method">Method to add an override for.</param> /// <param name="implementation">Implementation strategy that implements the method.</param> /// <returns>The added method override.</returns> /// <exception cref="ArgumentNullException"><paramref name="method"/> or <paramref name="implementation"/> is <c>null</c>.</exception> public IGeneratedMethod AddMethodOverride(IInheritedMethod method, IMethodImplementation implementation) { EnsureThatIdentifierHasNotBeenUsedYet(method.Name); // ensure that the property is abstract, virtual or an overrider switch (method.Kind) { case MethodKind.Abstract: case MethodKind.Virtual: case MethodKind.Override: break; default: throw new CodeGenException($"The specified method ({method.Name}) is neither abstract, nor virtual nor an overrider."); } // create method GeneratedMethod overriddenMethod = new GeneratedMethod(this, method, implementation); mGeneratedMethods.Add(overriddenMethod); return overriddenMethod; } /// <summary> /// Adds an override for an inherited method. /// </summary> /// <param name="method">Method to add an override for.</param> /// <param name="implementationCallback">Callback that implements the method.</param> /// <returns>The added method override.</returns> /// <exception cref="ArgumentNullException"><paramref name="method"/> or <paramref name="implementationCallback"/> is <c>null</c>.</exception> public IGeneratedMethod AddMethodOverride(IInheritedMethod method, MethodImplementationCallback implementationCallback) { EnsureThatIdentifierHasNotBeenUsedYet(method.Name); // ensure that the property is abstract, virtual or an overrider switch (method.Kind) { case MethodKind.Abstract: case MethodKind.Virtual: case MethodKind.Override: break; default: throw new CodeGenException($"The specified method ({method.Name}) is neither abstract, nor virtual nor an overrider."); } // create method GeneratedMethod overriddenMethod = new GeneratedMethod(this, method, implementationCallback); mGeneratedMethods.Add(overriddenMethod); return overriddenMethod; } /// <summary> /// Adds a method to the type definition. /// </summary> /// <param name="kind"> /// Kind of the property to add. May be one of the following: /// - <see cref="MethodKind.Static"/> /// - <see cref="MethodKind.Normal"/> /// - <see cref="MethodKind.Virtual"/> /// - <see cref="MethodKind.Abstract"/> /// </param> /// <param name="name">Name of the method to add (<c>null</c> to create a random name).</param> /// <param name="returnType">Return type of the method.</param> /// <param name="parameterTypes">Types of the method's parameters.</param> /// <param name="visibility">Visibility of the method.</param> /// <param name="implementation">Implementation strategy that implements the method.</param> /// <param name="additionalMethodAttributes">Additional method attributes to 'or' with other attributes.</param> /// <returns>The added method.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="returnType"/>, <paramref name="parameterTypes"/> or <paramref name="implementation"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="kind"/> is an invalid method kind /// -or- /// <paramref name="name"/> is not a valid language independent identifier /// -or- /// <paramref name="parameterTypes"/> contains a null reference. /// </exception> public IGeneratedMethod AddMethod( MethodKind kind, string name, Type returnType, Type[] parameterTypes, Visibility visibility, IMethodImplementation implementation, MethodAttributes additionalMethodAttributes = 0) { EnsureThatIdentifierHasNotBeenUsedYet(name); // ensure that a valid property kind was specified switch (kind) { case MethodKind.Static: case MethodKind.Normal: case MethodKind.Virtual: case MethodKind.Abstract: break; case MethodKind.Override: throw new ArgumentException( $"Method kind must not be '{MethodKind.Override}'. " + $"Overrides should be done using the {nameof(IInheritedMethod)}.{nameof(IInheritedMethod.Override)}() methods."); default: throw new ArgumentException("Invalid method kind.", nameof(kind)); } // create method GeneratedMethod method = new GeneratedMethod(this, kind, name, returnType, parameterTypes, visibility, additionalMethodAttributes, implementation); mGeneratedMethods.Add(method); return method; } /// <summary> /// Adds a method to the type definition. /// </summary> /// <param name="kind"> /// Kind of the property to add. May be one of the following: /// - <see cref="MethodKind.Static"/> /// - <see cref="MethodKind.Normal"/> /// - <see cref="MethodKind.Virtual"/> /// - <see cref="MethodKind.Abstract"/> /// </param> /// <param name="name">Name of the method to add (<c>null</c> to create a random name).</param> /// <param name="returnType">Return type of the method.</param> /// <param name="parameterTypes">Types of the method's parameters.</param> /// <param name="visibility">Visibility of the method.</param> /// <param name="implementationCallback">Callback that implements the method.</param> /// <param name="additionalMethodAttributes">Additional method attributes to 'or' with other attributes.</param> /// <returns>The added method.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="returnType"/>, <paramref name="parameterTypes"/> or <paramref name="implementationCallback"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="kind"/> is an invalid method kind /// -or- /// <paramref name="name"/> is not a valid language independent identifier /// -or- /// <paramref name="parameterTypes"/> contains a null reference. /// </exception> public IGeneratedMethod AddMethod( MethodKind kind, string name, Type returnType, Type[] parameterTypes, Visibility visibility, MethodImplementationCallback implementationCallback, MethodAttributes additionalMethodAttributes = 0) { EnsureThatIdentifierHasNotBeenUsedYet(name); // ensure that a valid property kind was specified switch (kind) { case MethodKind.Static: case MethodKind.Normal: case MethodKind.Virtual: case MethodKind.Abstract: break; case MethodKind.Override: throw new ArgumentException( $"Method kind must not be '{MethodKind.Override}'. " + $"Overrides should be done using the {nameof(IInheritedMethod)}.{nameof(IInheritedMethod.Override)}() methods."); default: throw new ArgumentException("Invalid method kind.", nameof(kind)); } // create method GeneratedMethod method = new GeneratedMethod(this, kind, name, returnType, parameterTypes, visibility, additionalMethodAttributes, implementationCallback); mGeneratedMethods.Add(method); return method; } #endregion #region Creating the Defined Type /// <summary> /// Creates the defined type. /// </summary> /// <returns>The created type.</returns> public Type CreateType() { // add class constructor AddClassConstructor(TypeBuilder); // add constructors AddConstructors(); // implement methods (includes event accessor methods and property accessor methods) foreach (var generatedMethod in mGeneratedMethods) generatedMethod.Implement(); // create the defined type Type createdType = null; while (mTypeBuilders.Count > 0) { TypeBuilder builder = mTypeBuilders.Pop(); if (createdType == null) createdType = builder.CreateTypeInfo()?.AsType(); else builder.CreateTypeInfo()?.AsType(); } CodeGenExternalStorage.Add(createdType, ExternalObjects.ToArray()); return createdType; } /// <summary> /// Adds the class constructor to the specified type and calls the specified modules to add their code to it. /// </summary> private void AddClassConstructor(TypeBuilder typeBuilder) { // define the class constructor ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor( MethodAttributes.Private | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, CallingConventions.Standard, Type.EmptyTypes); // get a MSIL generator attached to the constructor ILGenerator msilGenerator = constructorBuilder.GetILGenerator(); // add field initialization code foreach (var field in mGeneratedFields.Where(x => x.IsStatic)) { field.ImplementFieldInitialization(typeBuilder, msilGenerator); } // add opcode to return from the class constructor msilGenerator.Emit(OpCodes.Ret); } /// <summary> /// Adds a parameterless constructor to the specified type and calls the specified modules to add their code to it. /// </summary> private void AddConstructors() { // add default constructor if no constructor is defined until now... if (mConstructors.Count == 0) { var defaultConstructor = new GeneratedConstructor(this, Visibility.Public, Type.EmptyTypes, null, null); mConstructors.Add(defaultConstructor); } // create constructors foreach (var constructor in mConstructors) { ILGenerator msilGenerator = constructor.ConstructorBuilder.GetILGenerator(); // call parameterless constructor of the base class if the created class has a base class if (TypeBuilder.BaseType != null) { if (constructor.BaseClassConstructorCallImplementationCallback != null) { // the constructor will use user-supplied code to call a base class constructor constructor.BaseClassConstructorCallImplementationCallback(constructor, msilGenerator); } else { // the constructor does not have any special handling of the base class constructor call // => call parameterless constructor BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; ConstructorInfo constructorInfo = TypeBuilder.BaseType.GetConstructor(bindingFlags, null, Type.EmptyTypes, null); if (constructorInfo == null) { string error = $"The base class ({TypeBuilder.BaseType.FullName}) does not have an accessible parameterless constructor."; throw new CodeGenException(error); } msilGenerator.Emit(OpCodes.Ldarg_0); msilGenerator.Emit(OpCodes.Call, constructorInfo); } } // emit field initialization code foreach (var field in mGeneratedFields.Where(x => !x.IsStatic)) { field.ImplementFieldInitialization(TypeBuilder, msilGenerator); } // emit additional constructor code constructor.ImplementConstructorCallback?.Invoke(constructor, msilGenerator); // emit 'ret' to return from the constructor msilGenerator.Emit(OpCodes.Ret); } } #endregion #region Helpers /// <summary> /// Gets inherited abstract properties that have not been implemented/overridden, yet. /// </summary> /// <returns>Inherited abstract properties that still need to be overridden to allow the type to be created.</returns> public IInheritedProperty[] GetAbstractPropertiesWithoutOverride() { List<IInheritedProperty> abstractProperties = new List<IInheritedProperty>(); foreach (var property in InheritedProperties.Where(x => x.Kind == PropertyKind.Abstract)) { var overrider = mGeneratedProperties.Find(x => x.Kind == PropertyKind.Override && x.Name == property.Name); if (overrider == null) abstractProperties.Add(property); } return abstractProperties.ToArray(); } /// <summary> /// Gets the method with the specified name and the specified parameters /// (works with inherited and generated methods). /// </summary> /// <param name="name">Name of the method to get.</param> /// <param name="parameterTypes">Types of the method's parameters.</param> /// <returns> /// The requested method; /// <c>null</c> if the method was not found. /// </returns> public IMethod GetMethod(string name, Type[] parameterTypes) { // check whether the requested method is a generated method foreach (IGeneratedMethodInternal method in mGeneratedMethods) { if (method.Name == name && method.ParameterTypes.SequenceEqual(parameterTypes)) { return method; } } // check inherited methods foreach (IInheritedMethod method in InheritedMethods) { if (method.Name == name && method.ParameterTypes.SequenceEqual(parameterTypes)) { return method; } } // method was not found return null; } /// <summary> /// Checks whether the signatures (name + field type) of the specified fields are the same. /// </summary> /// <param name="x">Field to compare.</param> /// <param name="y">Field to compare to.</param> /// <returns> /// <c>true</c> if the specified fields have the same signature; /// otherwise <c>false</c>. /// </returns> private static bool HasSameSignature(FieldInfo x, FieldInfo y) { if (x.Name != y.Name) return false; return x.FieldType == y.FieldType; } /// <summary> /// Checks whether the signatures (name + event handler type) of the specified events are the same. /// </summary> /// <param name="x">Event to compare.</param> /// <param name="y">Event to compare to.</param> /// <returns> /// <c>true</c> if the specified events have the same signature; /// otherwise <c>false</c>. /// </returns> private static bool HasSameSignature(EventInfo x, EventInfo y) { if (x.Name != y.Name) return false; return x.EventHandlerType == y.EventHandlerType; } /// <summary> /// Checks whether the signatures (name + property type) of the specified properties are the same. /// </summary> /// <param name="x">Property to compare.</param> /// <param name="y">Property to compare to.</param> /// <returns> /// <c>true</c> if the specified properties have the same signature; /// otherwise <c>false</c>. /// </returns> private static bool HasSameSignature(PropertyInfo x, PropertyInfo y) { if (x.Name != y.Name) return false; return x.PropertyType == y.PropertyType; } /// <summary> /// Checks whether the signatures (name + return type + parameter types) of the specified methods are the same. /// </summary> /// <param name="x">Method to compare.</param> /// <param name="y">Method to compare to.</param> /// <returns> /// <c>true</c> if the specified methods have the same signature; /// otherwise <c>false</c>. /// </returns> private static bool HasSameSignature(MethodInfo x, MethodInfo y) { if (x.Name != y.Name) return false; return x.GetParameters().Select(z => z.ParameterType).SequenceEqual(y.GetParameters().Select(z => z.ParameterType)); } /// <summary> /// Ensures that the specified identifier (field, property, method) has not been used, yet. /// </summary> /// <param name="identifier">Name of the identifier to check.</param> /// <exception cref="CodeGenException">The identifier with the specified name has already been declared.</exception> private void EnsureThatIdentifierHasNotBeenUsedYet(string identifier) { if (identifier == null) return; // null means that a unique name is chosen => no conflict... foreach (var field in mGeneratedFields) { if (field.Name == identifier) { throw new CodeGenException($"The specified identifier ({identifier}) has already been used to declare a field."); } } foreach (var generatedEvent in mGeneratedEvents) { if (generatedEvent.Name == identifier) { throw new CodeGenException($"The specified identifier ({identifier}) has already been used to declare an event."); } } foreach (var generatedProperty in mGeneratedProperties) { if (generatedProperty.Name == identifier) { throw new CodeGenException($"The specified identifier ({identifier}) has already been used to declare a property."); } } foreach (var generatedMethod in mGeneratedMethods) { if (generatedMethod.Name == identifier) { throw new CodeGenException($"The specified identifier ({identifier}) has already been used to declare a method."); } } } #endregion } }
43.900729
178
0.709378
[ "MIT" ]
GriffinPlus/dotnet-libs-codegen
src/GriffinPlus.Lib.CodeGeneration/TypeDefinition.cs
108,349
C#
using System.Text; using System.Web.Mvc; namespace ChilliSource.Cloud.Web.MVC.Misc { /// <summary> /// Contains extension methods for System.Web.Mvc.HtmlHelper. /// </summary> public static class BlueChilliMotifHtmlHelper { /// <summary> /// Returns HTML string for BlueChilli ASCII code. /// </summary> /// <param name="html">The System.Web.Mvc.HtmlHelper instance that this method extends.</param> /// <returns>An HTML-encoded string.</returns> public static MvcHtmlString BlueChilliAsciiMotif(this HtmlHelper html) { var sb = new StringBuilder(); sb.AppendLine("<!--"); sb.AppendLine(" +"); sb.AppendLine(" +"); sb.AppendLine(" @"); sb.AppendLine(" @"); sb.AppendLine(" @"); sb.AppendLine(" BBBBBBb LLl cCCCc hHH II LLl lLL II @"); sb.AppendLine(" BBBBBBBBb LLl cCCCCCCC hHH II LLl lLL II #@"); sb.AppendLine(" BBB bBB LLl CCC cCCc hHH LLl lLL @@@"); sb.AppendLine(" BBB BB LLl uUU UU eEEEe cCC cCC hHHhHHH II LLl lLL II ::::."); sb.AppendLine(" BBB bBB LLl uUU UU EEEEEEe CCC hHHHHHHH II LLl lLL II ::::"); sb.AppendLine(" BBBBBBBB LLl uUU UU eEE EE CCc hHH hHH II LLl lLL II ::::"); sb.AppendLine(" BBBbbbBBB LLl uUU UU EEeeeeEE CCc hHH HH II LLl lLL II :::,"); sb.AppendLine(" BBB BBb LLl uUU UU EEEEEEEE CCc ccc hHH HH II LLl lLL II :::"); sb.AppendLine(" BBB BBb LLl uUU uUU EEe cCC CCC hHH HH II LLl lLL II ::`"); sb.AppendLine(" BBBbbbBBB LLl uUU UUU eEE eEE CCCc cCCc hHH HH II LLl lLL II ::,"); sb.AppendLine(" BBBBBBBBb LLl UUUUUUU eEEEEEe cCCCCCCc hHH HH II LLl lLL II ::"); sb.AppendLine(" bbbbbbbb lll uuuuuu eEEee cCCC hhh hh ii lll lLL ii ::"); sb.AppendLine(" ::"); sb.AppendLine(" :"); sb.AppendLine(" -->"); return MvcHtmlString.Create(sb.ToString()); } } }
70.883721
114
0.384843
[ "MIT" ]
BlueChilli/ChilliSource.Cloud.Web.MVC
src/ChilliSource.Cloud.Web.MVC/Extensions/Helpers/Misc/BlueChilliMotif.cs
3,050
C#
using ITSWebMgmt.Caches; using Microsoft.AspNetCore.Mvc; using System; using System.Net; namespace ITSWebMgmt.Controllers { public class ManagedByController : Controller { public string ErrorMessage; [HttpPost] public ActionResult SaveEditManagedBy([FromBody]string email) { SaveManagedBy(email); if (ErrorMessage == "") { Response.StatusCode = (int)HttpStatusCode.OK; return Json(new { success = true }); } else { Response.StatusCode = (int)HttpStatusCode.BadRequest; return Json(new { success = false, errorMessage = ErrorMessage }); } } public void SaveManagedBy(string email) { try { UserController uc = new UserController(null);//TODO Test if it still works after update on usercontroller uc.UserModel.adpath = uc.globalSearch(email); if (uc.UserModel.DistinguishedName.Contains("CN=")) { new GroupADcache(uc.UserModel.adpath).saveProperty("managedBy", uc.UserModel.DistinguishedName); ErrorMessage = ""; } else { ErrorMessage = "Error in email"; } } catch (Exception e) { ErrorMessage = e.Message; } } } }
29.72549
121
0.511214
[ "BSD-2-Clause" ]
mathgaming/AAUWebMgmt
ITSWebMgmt/Controllers/ManagedByController.cs
1,518
C#
using MonkeyButler.Abstractions.Data.Api.Models.XivApi.Character; using MonkeyButler.Abstractions.Data.Api.Models.XivApi.Enumerations; using MonkeyButler.Business.Engines; using Xunit; namespace MonkeyButler.Business.Tests.Engines; public class CharacterResultEngineTests { [Theory] [InlineData(null, null)] [InlineData("", "")] [InlineData(" ", " ")] [InlineData("h", "H")] [InlineData("hElLo", "Hello")] [InlineData("gladiator / paladin", "Gladiator / Paladin")] [InlineData("double space", "Double Space")] [InlineData("so many spaces", "So Many Spaces")] public void ShouldCapitilizeClassJobName(string? input, string? expectedName) { var characterBrief = new CharacterBrief(); var details = new GetCharacterData() { Character = new CharacterFull() { ActiveClassJob = new ClassJob() { Name = input } } }; var result = CharacterResultEngine.Merge(characterBrief, details); Assert.Equal(expectedName, result.CurrentClassJob?.Name); } [Theory] [InlineData("Dark Knight", "Dark Knight")] [InlineData("Gladiator / Paladin", "Gladiator / Paladin")] [InlineData("Dark Knight / Dark Knight", "Dark Knight")] [InlineData("dark knight / dark knight", "Dark Knight")] [InlineData("dark knight / Dark Knight", "Dark Knight")] public void ShouldRemoveDuplicates(string? input, string? expectedName) { var characterBrief = new CharacterBrief(); var details = new GetCharacterData() { Character = new CharacterFull() { ActiveClassJob = new ClassJob() { Name = input } } }; var result = CharacterResultEngine.Merge(characterBrief, details); Assert.Equal(expectedName, result.CurrentClassJob?.Name); } [Theory] [InlineData(null, null)] [InlineData(Race.Unknown, "Unknown")] [InlineData(Race.Hyur, "Hyur")] [InlineData(Race.AuRa, "Au Ra")] public void ShouldConvertRace(Race? race, string? expectedRace) { var characterBrief = new CharacterBrief(); var details = new GetCharacterData() { Character = new CharacterFull() { Race = race } }; var result = CharacterResultEngine.Merge(characterBrief, details); Assert.Equal(expectedRace, result.Race); } [Theory] [InlineData(null, null)] [InlineData(Tribe.Unknown, "Unknown")] [InlineData(Tribe.Hellsguard, "Hellsguard")] [InlineData(Tribe.SeaWolf, "Sea Wolf")] [InlineData(Tribe.SeekerOfTheMoon, "Seeker of the Moon")] [InlineData(Tribe.SeekerOfTheSun, "Seeker of the Sun")] public void ShouldConvertTribe(Tribe? tribe, string? expectedTribe) { var characterBrief = new CharacterBrief(); var details = new GetCharacterData() { Character = new CharacterFull() { Tribe = tribe } }; var result = CharacterResultEngine.Merge(characterBrief, details); Assert.Equal(expectedTribe, result.Tribe); } [Theory] [InlineData(0, "https://na.finalfantasyxiv.com/lodestone/character/0")] [InlineData(123456, "https://na.finalfantasyxiv.com/lodestone/character/123456")] public void ShouldGenerateLodestoneUrl(long id, string expectedUrl) { var characterBrief = new CharacterBrief() { Id = id }; var details = new GetCharacterData(); var result = CharacterResultEngine.Merge(characterBrief, details); Assert.Equal(expectedUrl, result.LodestoneUrl); } }
31.398374
85
0.603832
[ "MIT" ]
Foshkey/MonkeyButler
tests/MonkeyButler.Business.Tests/Engines/CharacterResultEngineTests.cs
3,864
C#
using System.Runtime.Serialization; namespace Service.Liquidity.Portfolio.Grpc.Simulation.Models { [DataContract] public class DeleteSimulationRequest { [DataMember(Order = 1)] public long SimulationId { get; set; } } }
22.363636
70
0.711382
[ "MIT" ]
MyJetWallet/Service.Liquidity.Portfolio
src/Service.Liquidity.Portfolio.Grpc/Simulation/Models/DeleteSimulationRequest.cs
248
C#
using System; using System.IO; using System.Linq; namespace ScsSitecoreResourceManager.Pipelines.SitecoreResourceManager { public class InsertNewCsMethod { private readonly string _fileName; private readonly string _template; private readonly string _applicableTemplateZip; public InsertNewCsMethod(string fileName, string template, string applicableTemplateZip) { _fileName = fileName; _template = template; _applicableTemplateZip = applicableTemplateZip; } public void Process(SitecoreResourceManagerArgs args) { if (Path.GetFileName(args.Wrapper.TemplateZip.ToLower()) != _applicableTemplateZip.ToLower()) return; var fileName = ReplaceAllTokens.ReplaceTokens(_fileName, args); var template = ReplaceAllTokens.ReplaceTokens(_template, args); var path = Directory.EnumerateFiles(args.OverlayTarget, $"*{fileName}*", SearchOption.AllDirectories).FirstOrDefault(x => (Path.GetFileName(x)?.ToLower() ?? string.Empty) == fileName.ToLower()); if (path == null) return; var content = File.ReadAllText(path); int index = content.LastIndexOf('}'); if (index > -1) index--; index = content.LastIndexOf('}', index); content = content.Insert(index, template); File.WriteAllText(path, content); } } }
31.097561
197
0.740392
[ "MIT" ]
aevanommen/SitecoreSidekick
ScsSitecoreResourceManager/Pipelines/SitecoreResourceManager/InsertNewCsMethod.cs
1,277
C#
using System; using System.IO; using System.Reflection; using Unicorn.ControlPanel.Headings; namespace Helixbase.Feature.Fun.Unicorn.Pipelines { /// <summary> /// https://github.com/SitecoreUnicorn/Unicorn/blob/master/src/Unicorn/ControlPanel/Headings/HeadingService.cs /// </summary> public class HeadingServiceFun : HeadingService { private static readonly Random Random = new Random(); private static readonly string[] HtmlChoices = { "Helixbase.Feature.Fun.Unicorn.Images.Helixbase.html", "Helixbase.Feature.Fun.Unicorn.Images.Unicorn.html", "Helixbase.Feature.Fun.Unicorn.Images.Unicorn.svg.html", "Helixbase.Feature.Fun.Unicorn.Images.Unicorn2.svg.html", "Helixbase.Feature.Fun.Unicorn.Images.Unicorn3.svg.html" }; public new string GetHeadingHtml() { // heh heh :) //if (DateTime.Today.Month == 4 && DateTime.Today.Day == 1) return ReadResource("Unicorn.ControlPanel.Headings.April.svg.html"); var headerIndex = Random.Next(0, HtmlChoices.Length); return ReadResource(HtmlChoices[headerIndex]); } protected override string ReadResource(string name) { var assembly = Assembly.GetExecutingAssembly(); using (var stream = assembly.GetManifestResourceStream(name)) using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } } }
34.355556
140
0.633894
[ "MIT" ]
muso31/Helixbase-modules
src/Feature/Fun/website/Unicorn/Pipelines/HeadingServiceFun.cs
1,548
C#
using System; using ClearHl7.Extensions; using ClearHl7.Helpers; using ClearHl7.Serialization; namespace ClearHl7.V281.Types { /// <summary> /// HL7 Version 2 DDI - Daily Deductible Information. /// </summary> public class DailyDeductibleInformation : IType { /// <inheritdoc/> public bool IsSubcomponent { get; set; } /// <summary> /// DDI.1 - Delay Days. /// </summary> public decimal? DelayDays { get; set; } /// <summary> /// DDI.2 - Monetary Amount. /// </summary> public Money MonetaryAmount { get; set; } /// <summary> /// DDI.3 - Number of Days. /// </summary> public decimal? NumberOfDays { get; set; } /// <inheritdoc/> public void FromDelimitedString(string delimitedString) { FromDelimitedString(delimitedString, null); } /// <inheritdoc/> public void FromDelimitedString(string delimitedString, Separators separators) { Separators seps = separators ?? new Separators().UsingConfigurationValues(); string[] separator = IsSubcomponent ? seps.SubcomponentSeparator : seps.ComponentSeparator; string[] segments = delimitedString == null ? Array.Empty<string>() : delimitedString.Split(separator, StringSplitOptions.None); DelayDays = segments.Length > 0 && segments[0].Length > 0 ? segments[0].ToNullableDecimal() : null; MonetaryAmount = segments.Length > 1 && segments[1].Length > 0 ? TypeSerializer.Deserialize<Money>(segments[1], true, seps) : null; NumberOfDays = segments.Length > 2 && segments[2].Length > 0 ? segments[2].ToNullableDecimal() : null; } /// <inheritdoc/> public string ToDelimitedString() { System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.CurrentCulture; string separator = IsSubcomponent ? Configuration.SubcomponentSeparator : Configuration.ComponentSeparator; return string.Format( culture, StringHelper.StringFormatSequence(0, 3, separator), DelayDays.HasValue ? DelayDays.Value.ToString(Consts.NumericFormat, culture) : null, MonetaryAmount?.ToDelimitedString(), NumberOfDays.HasValue ? NumberOfDays.Value.ToString(Consts.NumericFormat, culture) : null ).TrimEnd(separator.ToCharArray()); } } }
39.477612
143
0.589414
[ "MIT" ]
kamlesh-microsoft/clear-hl7-net
src/ClearHl7/V281/Types/DailyDeductibleInformation.cs
2,647
C#
// ----------------------------------------------------------------------- // <copyright file="InlineAutoMoqDataAttribute.cs" company="Piotr Xeinaemm Czech"> // Copyright (c) Piotr Xeinaemm Czech. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> // ----------------------------------------------------------------------- namespace Xeinaemm.Tests.Common.Attributes { using AutoFixture.Xunit2; using Xunit; public sealed class InlineAutoMoqDataAttribute : CompositeDataAttribute { public InlineAutoMoqDataAttribute(params object[] values) : base(new InlineDataAttribute(values), new AutoMoqDataAttribute()) { } } }
38.05
101
0.579501
[ "MIT" ]
Xeinaemm/Xeinaemm.Standard
src/Xeinaemm.Tests.Common/Attributes/InlineAutoMoqDataAttribute.cs
763
C#
using JsonValidatorTool; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; namespace Kooboo.Json.Test { [TestClass] public class IgnoreDefaultValue { [IgnoreDefaultValue] class User { public int? Num { get; set; } public int Age { get; set; } public string Name { get; set; } } [TestMethod] public void IgnoreDefaultValueFeature_use_classAttribute_should_be_work_correct() { var json = JsonSerializer.ToJson(new User()); Assert.IsTrue(JsonValidator.IsValid(json)); Assert.AreEqual("{}", json); } class User2 { [IgnoreDefaultValue] public int? Num { get; set; } public int Age { get; set; } public string Name { get; set; } } [TestMethod] public void IgnoreDefaultValueFeature_use_attribute_should_be_work_correct() { var json = JsonSerializer.ToJson(new User2()); Assert.IsTrue(JsonValidator.IsValid(json)); Assert.AreEqual("{\"Age\":0,\"Name\":null}", json); } } }
25.595745
89
0.571072
[ "MIT" ]
Kooboo/Json
Kooboo.Json.Test/Test/Feature/IgnoreDefaultValue.cs
1,205
C#
using UnityEngine; using System.Collections; namespace Babbel { public enum FilterMatching { Never = 0, Case = 1 << 0, Name = 1 << 1, Description = 1 << 2, Both = (1 << 1) | (1 << 2), Any = (1 << 1) | (1 << 2) | (1 << 3) }; public static class FilterMatchingTools { public static bool In(this FilterMatching me, FilterMatching other) { return (me & other) == me; } } public class Tag : ScriptableObject { public string description; public bool Matches(string filter, FilterMatching criteria = FilterMatching.Any) { if (criteria == FilterMatching.Never) { return false; } string desc = description; string name = this.name; if (!FilterMatching.Case.In(criteria)) { filter = filter.ToLower(); if (FilterMatching.Name.In(criteria)) { name = this.name.ToLower(); } if (FilterMatching.Description.In(criteria)) { desc = description.ToLower(); } } if (FilterMatching.Any.In(criteria)) { return name.Contains(filter) || desc.Contains(filter); } else if (FilterMatching.Both.In(criteria)) { return name.Contains(filter) && desc.Contains(filter); } else if (FilterMatching.Name.In(criteria)) { return name.Contains(filter); } else if (FilterMatching.Description.In(criteria)) { return desc.Contains(filter); } else { throw new System.MissingMemberException("Can't filter on requested criteria: " + criteria); } } } }
28.376812
107
0.47855
[ "MIT" ]
local-minimum/babbel
Assets/Addons/Babbel/Scripts/ScriptableObjects/Tag.cs
1,960
C#
// Copyright 2022 Google LLC // // 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 // // 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. // Generated code. DO NOT EDIT! namespace Google.Cloud.MediaTranslation.V1Beta1.Snippets { using Google.Api.Gax.Grpc; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedSpeechTranslationServiceClientSnippets { /// <summary>Snippet for StreamingTranslateSpeech</summary> public async Task StreamingTranslateSpeech() { // Snippet: StreamingTranslateSpeech(CallSettings, BidirectionalStreamingSettings) // Create client SpeechTranslationServiceClient speechTranslationServiceClient = SpeechTranslationServiceClient.Create(); // Initialize streaming call, retrieving the stream object SpeechTranslationServiceClient.StreamingTranslateSpeechStream response = speechTranslationServiceClient.StreamingTranslateSpeech(); // Sending requests and retrieving responses can be arbitrarily interleaved // Exact sequence will depend on client/server behavior // Create task to do something with responses from server Task responseHandlerTask = Task.Run(async () => { // Note that C# 8 code can use await foreach AsyncResponseStream<StreamingTranslateSpeechResponse> responseStream = response.GetResponseStream(); while (await responseStream.MoveNextAsync()) { StreamingTranslateSpeechResponse responseItem = responseStream.Current; // Do something with streamed response } // The response stream has completed }); // Send requests to the server bool done = false; while (!done) { // Initialize a request StreamingTranslateSpeechRequest request = new StreamingTranslateSpeechRequest { StreamingConfig = new StreamingTranslateSpeechConfig(), }; // Stream a request to the server await response.WriteAsync(request); // Set "done" to true when sending requests is complete } // Complete writing requests to the stream await response.WriteCompleteAsync(); // Await the response handler // This will complete once all server responses have been processed await responseHandlerTask; // End snippet } } }
42.739726
143
0.649038
[ "Apache-2.0" ]
AlexandrTrf/google-cloud-dotnet
apis/Google.Cloud.MediaTranslation.V1Beta1/Google.Cloud.MediaTranslation.V1Beta1.Snippets/SpeechTranslationServiceClientSnippets.g.cs
3,120
C#
using Circle.Game.Beatmaps; using Circle.Game.Screens.Select; using osu.Framework.Allocation; namespace Circle.Game.Tests.Visual.SongSelect { public class TestSceneBeatmapCarousel : CircleTestScene { [BackgroundDependencyLoader] private void load(BeatmapStorage beatmaps) { BeatmapCarousel carousel; Add(carousel = new BeatmapCarousel()); AddLabel("Add carousel item"); foreach (var bi in beatmaps.GetBeatmapInfos()) AddStep($"Add item({bi})", () => carousel.Add(bi, null)); AddLabel("Select beatmap(vertical direction)"); AddRepeatStep("Select beatmap(down)", carousel.SelectNext, 5); AddRepeatStep("Select beatmap(up)", carousel.SelectPrevious, 5); AddLabel("Select beatmap(beatmap)"); foreach (var bi in beatmaps.GetBeatmapInfos()) { AddAssert($"Select beatmap({bi})", () => { carousel.Select(bi); return carousel.SelectedItem.Value.BeatmapInfo.Equals(bi); }); } } } }
33.057143
78
0.57822
[ "MIT" ]
ojh050118/Circle
Circle.Game.Tests/Visual/SongSelect/TestSceneBeatmapCarousel.cs
1,159
C#
using System.Collections.Generic; using Cicee.Commands.Lib; namespace Cicee.Commands.Template.Lib { public record TemplateLibResult( string ProjectRoot, LibraryShellTemplate ShellTemplate, string LibPath, bool OverwriteFiles, DirectoryCopyResult CiLibraryCopyResult, IReadOnlyCollection<FileCopyResult> CiceeExecCopyResults, string CiLibraryEntrypointPath, string CiceeExecEntrypointPath ); }
25.294118
61
0.795349
[ "MIT" ]
JeremiahSanders/cicee
src/Commands/Template/Lib/TemplateLibResult.cs
430
C#
using LLBLGenPro.OrmCookbook.EntityClasses; using Microsoft.VisualStudio.TestTools.UnitTesting; using Recipes.ModelWithLookup; namespace Recipes.LLBLGenPro.ModelWithLookup { [TestClass] public class ModelWithLookupSimpleTests : ModelWithLookupSimpleTests<EmployeeEntity> { protected override IModelWithLookupSimpleScenario<EmployeeEntity> GetScenario() { return new ModelWithLookupSimpleScenario(); } } }
28.6875
88
0.760349
[ "Unlicense" ]
FransBouma/DotNet-ORM-Cookbook
ORM Cookbook/Recipes.LLBLGenPro/Recipes/ModelWithLookup/ModelWithLookupSimpleTests.cs
461
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using Bright.Serialization; using System.Collections.Generic; namespace cfg.ai { public sealed partial class UeTimeLimit : ai.Decorator { public UeTimeLimit(ByteBuf _buf) : base(_buf) { LimitTime = _buf.ReadFloat(); PostInit(); } public static UeTimeLimit DeserializeUeTimeLimit(ByteBuf _buf) { return new ai.UeTimeLimit(_buf); } public float LimitTime { get; private set; } public const int __ID__ = 338469720; public override int GetTypeId() => __ID__; public override void Resolve(Dictionary<string, object> _tables) { base.Resolve(_tables); PostResolve(); } public override void TranslateText(System.Func<string, string, string> translator) { base.TranslateText(translator); } public override string ToString() { return "{ " + "Id:" + Id + "," + "NodeName:" + NodeName + "," + "FlowAbortMode:" + FlowAbortMode + "," + "LimitTime:" + LimitTime + "," + "}"; } partial void PostInit(); partial void PostResolve(); } }
24.483333
86
0.54663
[ "MIT" ]
HFX-93/luban_examples
Projects/Csharp_DotNet5_bin/Gen/ai/UeTimeLimit.cs
1,469
C#
using DCSoft.Drawing; using System; using System.Drawing; using System.Runtime.InteropServices; namespace DCSoftDotfuscate { [ComVisible(false)] public class GClass443 { private float float_0; private float float_1; private float float_2; private FontWidthStyle fontWidthStyle_0; private Font font_0; private Graphics graphics_0; private StringFormat stringFormat_0; public GClass443(StringFormat stringFormat_1, Graphics graphics_1, Font font_1) { int num = 17; float_0 = 0f; float_1 = 0f; float_2 = 0f; fontWidthStyle_0 = FontWidthStyle.Monospaced; font_0 = null; graphics_0 = null; stringFormat_0 = null; if (font_1 == null) { throw new ArgumentNullException("f"); } if (graphics_1 == null) { throw new ArgumentNullException("g"); } graphics_0 = graphics_1; font_0 = font_1; if (stringFormat_1 == null) { stringFormat_0 = new StringFormat(StringFormat.GenericTypographic); stringFormat_0.FormatFlags = (StringFormatFlags.FitBlackBox | StringFormatFlags.MeasureTrailingSpaces | StringFormatFlags.NoClip); } else { stringFormat_0 = stringFormat_1; } SizeF sizeF = graphics_1.MeasureString("W", font_0, 10000, stringFormat_0); SizeF sizeF2 = graphics_1.MeasureString("i", font_0, 10000, stringFormat_0); if (sizeF.Width == sizeF2.Width) { fontWidthStyle_0 = FontWidthStyle.Monospaced; } else { fontWidthStyle_0 = FontWidthStyle.Proportional; } if (fontWidthStyle_0 == FontWidthStyle.Monospaced) { float_2 = sizeF.Width; } float_1 = graphics_1.MeasureString("袁", font_0, 10000, stringFormat_0).Width; float_0 = graphics_1.MeasureString(" ", font_0, 1000, stringFormat_0).Width; if ((double)float_0 < 0.1) { float_0 = graphics_1.MeasureString("i", font_0, 1000, stringFormat_0).Width; } } public float method_0(string string_0) { if (string.IsNullOrEmpty(string_0)) { return 0f; } bool flag = false; if (fontWidthStyle_0 == FontWidthStyle.Monospaced) { float num = 0f; flag = true; foreach (char c in string_0) { if (smethod_0(c)) { num += float_1; continue; } if (c == ' ') { num += float_0; continue; } if (c <= '\u007f') { num += float_2; continue; } flag = false; break; } if (flag) { return num; } } return graphics_0.MeasureString(string_0, font_0, 10000, stringFormat_0).Width; } private static bool smethod_0(char char_0) { int num = 17; if ('一' <= char_0 && char_0 < '龥') { return true; } if ("‘’“”‘、,。?☆★○●◎◇◆□℃‰■△▲※→←↑↓".IndexOf(char_0) >= 0) { return true; } return false; } } }
21.198473
134
0.637018
[ "MIT" ]
h1213159982/HDF
Example/WinForm/Editor/DCWriter/DCSoft.Writer.Cleaned/DCSoftDotfuscate/GClass443.cs
2,837
C#
#region using Bimface.SDK.Attributes.Http; using Bimface.SDK.Entities.Parameters.Base; #endregion namespace Bimface.SDK.Entities.Parameters.Data.File { [BimfaceDataApiHttpRequest("/files/{fileId}/areas/{areaId}")] public class LookupFileAreaParameter : FileParameter { #region Constructors public LookupFileAreaParameter(long fileId, string areaId) : base(fileId) { AreaId = areaId; } #endregion #region Properties [HttpPathComponent] public string AreaId { get; } #endregion } }
20.275862
81
0.651361
[ "MIT" ]
KennanChan/Bimface.SDK
Bimface.SDK.Standard/Bimface.SDK/Entities/Parameters/Data/File/LookupFileAreaParameter.cs
590
C#
using NLog; using System; using System.Diagnostics; using static NLazyToString.LazyToString; namespace NLazyToStringNLogConsole { internal static class Program { private const int LoopCounter = 1_000_000; private static readonly string LongString = new('9', 20); private static readonly ILogger Logger= LogManager.GetCurrentClassLogger(); static Program() { var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); var config = new NLog.Config.LoggingConfiguration(); config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); LogManager.Configuration = config; } static void Main(string[] args) { TestWhenInterpolationIsNotNeeded(); TestWhenInterpolationIsNeeded(); } private static void TestWhenInterpolationIsNotNeeded() { Console.WriteLine("Testing savings when interpolation is not needed..."); Console.WriteLine(); long ticksInterpolate, ticksFormat, ticksLazyString; var logger = Logger; using (var chronometer = new Chronometer("Interpolate loop")) { for (int i = 0; i < LoopCounter; i++) logger.Debug($"Gaidys dbg {i} {LongString}"); ticksInterpolate = chronometer.ElapsedTicks; } using (var chronometer = new Chronometer("string.Format loop")) { for (int i = 0; i < LoopCounter; i++) logger.Debug(string.Format("Gaidys dbg {0} {1}", i, LongString)); ticksFormat = chronometer.ElapsedTicks; } using (var chronometer = new Chronometer("LazyToString loop")) { for (int i = 0; i < LoopCounter; i++) logger.Debug(LazyString(() => $"Gaidys dbg {i} {LongString}")); ticksLazyString = chronometer.ElapsedTicks; } Console.WriteLine(); Console.WriteLine($"Ticks: interpolate={ticksInterpolate}, format={ticksFormat}, {nameof(LazyString)}={ticksLazyString}"); Console.WriteLine(); Console.WriteLine($"{nameof(LazyString)} was faster than interpolate {(double)ticksInterpolate / ticksLazyString} times."); Console.WriteLine(); Console.WriteLine($"{nameof(LazyString)} was faster than format {(double)ticksFormat / ticksLazyString} times."); Console.WriteLine(); } private static void TestWhenInterpolationIsNeeded() { Console.WriteLine("Testing overhead when interpolation is needed..."); Console.WriteLine(); long ticksInterpolate, ticksFormat, ticksLazyString; var logger = new FakeLogger(); using (var chronometer = new Chronometer("Interpolate loop")) { for (int i = 0; i < LoopCounter; i++) logger.Debug($"Gaidys dbg {i} {LongString}"); ticksInterpolate = chronometer.ElapsedTicks; } using (var chronometer = new Chronometer("string.Format loop")) { for (int i = 0; i < LoopCounter; i++) logger.Debug(string.Format("Gaidys dbg {0} {1}", i, LongString)); ticksFormat = chronometer.ElapsedTicks; } using (var chronometer = new Chronometer("LazyToString loop")) { for (int i = 0; i < LoopCounter; i++) logger.Debug(LazyString(() => $"Gaidys dbg {i} {LongString}")); ticksLazyString = chronometer.ElapsedTicks; } Console.WriteLine(); Console.WriteLine($"Ticks: interpolate={ticksInterpolate}, format={ticksFormat}, {nameof(LazyString)}={ticksLazyString}"); Console.WriteLine(); Console.WriteLine($"{nameof(LazyString)} was slower than interpolate {(double)ticksLazyString / ticksInterpolate} times."); Console.WriteLine(); Console.WriteLine($"{nameof(LazyString)} was slower than format {(double)ticksLazyString / ticksFormat } times."); Console.WriteLine(); } private sealed class Chronometer : IDisposable { private readonly string _episode; private readonly Stopwatch _stopWatch; public Chronometer(string episode) { _episode = episode; _stopWatch = Stopwatch.StartNew(); Logger.Info($"{_episode} start"); } public long ElapsedTicks => _stopWatch.ElapsedTicks; public void Dispose() { _stopWatch.Stop(); Logger.Info($"{_episode} end, took {_stopWatch.Elapsed}"); } } private sealed class FakeLogger { internal void Debug(string str) { SimulateLog(str); } internal void Debug(object obj) { SimulateLog(obj?.ToString()); } private void SimulateLog(string str) { } } } }
38.092857
136
0.552222
[ "MIT" ]
r-pankevicius/NLazyToString
src/NLazyToStringNLogConsole/Program.cs
5,335
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Rebar.Core.Query; namespace sample.Queries { public class SampleQueryHandler : IQueryHandler<SampleQuery, SampleResponse> { public Task<SampleResponse> ExecuteAsync(SampleQuery query, CancellationToken cancellationToken) { var musicans = new List<string>() { "Bob Dylan", "Miles Davis", "Frank Sinatra" }; var musican = musicans.FirstOrDefault(m => m.Contains(query.Name)); return Task.FromResult(new SampleResponse(musican)); } } }
28.909091
104
0.696541
[ "MIT" ]
Hoodster/rebar.core
sample/sample/Queries/SampleQueryHandler.cs
638
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.AspNetCore.Mvc.ApplicationModels; using Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure; namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Filters; internal class TempDataApplicationModelProvider : IApplicationModelProvider { private readonly TempDataSerializer _tempDataSerializer; public TempDataApplicationModelProvider(TempDataSerializer tempDataSerializer) { _tempDataSerializer = tempDataSerializer; } /// <inheritdoc /> /// <remarks>This order ensures that <see cref="TempDataApplicationModelProvider"/> runs after the <see cref="DefaultApplicationModelProvider"/>.</remarks> public int Order => -1000 + 10; /// <inheritdoc /> public void OnProvidersExecuted(ApplicationModelProviderContext context) { } /// <inheritdoc /> public void OnProvidersExecuting(ApplicationModelProviderContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } foreach (var controllerModel in context.Result.Controllers) { var modelType = controllerModel.ControllerType.AsType(); var tempDataProperties = SaveTempDataPropertyFilterBase.GetTempDataProperties(_tempDataSerializer, modelType); if (tempDataProperties == null) { continue; } var filter = new ControllerSaveTempDataPropertyFilterFactory(tempDataProperties); controllerModel.Filters.Add(filter); } } }
33.54
159
0.70483
[ "MIT" ]
3ejki/aspnetcore
src/Mvc/Mvc.ViewFeatures/src/Filters/TempDataApplicationModelProvider.cs
1,679
C#
using System; using System.Collections; using System.Collections.Generic; namespace OmiyaGames { ///----------------------------------------------------------------------- /// <remarks> /// <copyright file="ListSet.cs" company="Omiya Games"> /// The MIT License (MIT) /// /// Copyright (c) 2014-2020 Omiya Games /// /// 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. /// </copyright> /// <list type="table"> /// <listheader> /// <term>Revision</term> /// <description>Description</description> /// </listheader> /// <item> /// <term> /// <strong>Date:</strong> 1/23/2019<br/> /// <strong>Author:</strong> Taro Omiya /// </term> /// <description> /// Initial version. /// </description> /// </item> /// <item> /// <term> /// <strong>Version:</strong> 0.1.0-preview.1<br/> /// <strong>Date:</strong> 3/25/2020<br/> /// <strong>Author:</strong> Taro Omiya /// </term> /// <description> /// Converted the class to a package. /// </description> /// </item> /// <item> /// <term> /// <strong>Version:</strong> 0.1.4-preview.1<br/> /// <strong>Date:</strong> 5/27/2020<br/> /// <strong>Author:</strong> Taro Omiya /// </term> /// <description> /// Updating documentation to be compatible with DocFX. /// </description> /// </item> /// </list> /// </remarks> ///----------------------------------------------------------------------- /// <summary> /// A list where all the elements are unique (i.e. a set). /// Note that due to its nature, null cannot be added into this collection. /// <seealso cref="HashSet{T}"/> /// <seealso cref="List{T}"/> /// <seealso cref="Dictionary{TKey, TValue}"/> /// </summary> public class ListSet<T> : ISet<T>, IList<T> { /// <summary> /// The list itself. /// </summary> private readonly List<T> list; /// <summary> /// The dictionary mapping from an item to an index. /// Used to verify whether an item already exists in the list. /// </summary> private readonly Dictionary<T, int> itemToIndexMap; #region Constructors /// <summary> /// Default constructor that sets up an empty list. /// </summary> public ListSet() { itemToIndexMap = new Dictionary<T, int>(); list = new List<T>(); } /// <summary> /// Constructor an empty list with initial capacity defined. /// </summary> /// <param name="capacity">Initial capacity of this list.</param> public ListSet(int capacity) { itemToIndexMap = new Dictionary<T, int>(capacity); list = new List<T>(capacity); } /// <summary> /// Constructor to set the <see cref="IEqualityComparer{T}"/>, /// used to check if two elements matches. /// </summary> /// <param name="comparer"> /// Comparer to check if two elements matches. /// </param> public ListSet(IEqualityComparer<T> comparer) { itemToIndexMap = new Dictionary<T, int>(comparer); list = new List<T>(); } /// <summary> /// Constructor to set the <see cref="IEqualityComparer{T}"/>, /// used to check if two elements matches. /// </summary> /// <param name="capacity">Initial capacity of this list.</param> /// <param name="comparer"> /// Comparer to check if two elements matches. /// </param> public ListSet(int capacity, IEqualityComparer<T> comparer) { itemToIndexMap = new Dictionary<T, int>(capacity, comparer); list = new List<T>(capacity); } #endregion #region Properties /// <summary> /// Gets or sets an element in the list. For the setter, /// if an element already in the list is inserted, /// an exception will be thrown. /// </summary> /// <param name="index"></param> /// <returns></returns> public T this[int index] { get => list[index]; set { // First confirm the value and index is valid if (index < 0) { throw new IndexOutOfRangeException("Index cannot be negative."); } else if (index >= Count) { throw new IndexOutOfRangeException("Index cannot be greater than or equal to list size."); } else if (value == null) { throw new ArgumentNullException("value"); } else if (Contains(value) == true) { throw new ArgumentException("Cannot insert an item already in the list.", "value"); } else { // Update the map with the new item itemToIndexMap.Remove(list[index]); itemToIndexMap.Add(value, index); // Update the list with the new item list[index] = value; } } } /// <inheritdoc/> public int Count => list.Count; /// <inheritdoc/> public bool IsReadOnly => ((IList<T>)list).IsReadOnly; #endregion /// <inheritdoc/> public System.Collections.ObjectModel.ReadOnlyCollection<T> AsReadOnly() { return list.AsReadOnly(); } /// <inheritdoc/> public void Clear() { // Clear both lists itemToIndexMap.Clear(); list.Clear(); } /// <inheritdoc/> public bool Contains(T item) { // Check contains on the dictionary return itemToIndexMap.ContainsKey(item); } /// <inheritdoc/> public void CopyTo(T[] array, int arrayIndex) { // Copy from the list list.CopyTo(array, arrayIndex); } /// <inheritdoc/> public IEnumerator<T> GetEnumerator() { // Grab the enumerator from the list (thus preserving insertion order) return list.GetEnumerator(); } /// <inheritdoc/> IEnumerator IEnumerable.GetEnumerator() { // Grab the enumerator from the list (thus preserving insertion order) return list.GetEnumerator(); } /// <summary> /// Gets the index of an item, or -1 if it isn't in the list. /// </summary> /// <param name="item">The element to search through the list.</param> /// <returns>Index of an item, or -1 if it isn't in the list.</returns> public int IndexOf(T item) { // Check if the dictionary contains the index int returnIndex; if (itemToIndexMap.TryGetValue(item, out returnIndex) == false) { // If not, return -1 returnIndex = -1; } return returnIndex; } /// <inheritdoc/> public bool Add(T item) { // Make sure the item isn't null, // and already in the list. bool returnFlag = ((item != null) && (Contains(item) == false)); if (returnFlag == true) { AddHelper(item); } return returnFlag; } /// <inheritdoc/> void ICollection<T>.Add(T item) { if (item == null) { throw new ArgumentNullException("item"); } else if (Contains(item) == true) { throw new ArgumentException("Cannot add elements already in the list.", "item"); } else { AddHelper(item); } } /// <inheritdoc/> public bool Insert(int index, T item) { bool returnFlag = ((index >= 0) && (index <= Count) && (item != null) && (Contains(item) == false)); if (returnFlag == true) { InsertHelper(index, item); } return returnFlag; } /// <inheritdoc/> void IList<T>.Insert(int index, T item) { if (index < 0) { throw new IndexOutOfRangeException("Index cannot be negative."); } else if (index > Count) { throw new IndexOutOfRangeException("Index cannot be greater than list size."); } else if (item == null) { throw new ArgumentNullException("item"); } else if (Contains(item) == true) { throw new ArgumentException("Cannot insert elements already in a list.", "item"); } else { InsertHelper(index, item); } } /// <inheritdoc/> public bool Remove(T item) { // Check the index to remove from. // We'll need it to figure out which index to update the list. int index = IndexOf(item); if (index >= 0) { // Just let RemoveAt handle it at this point RemoveAt(index); } return (index >= 0); } /// <inheritdoc/> public void RemoveAt(int index) { // Check if index is valid if (index < 0) { throw new IndexOutOfRangeException("Index cannot be negative."); } else if (index >= Count) { throw new IndexOutOfRangeException("Index cannot be greater than or equal to list size."); } // Remove the item from the dictionary // before it's removed from the list. itemToIndexMap.Remove(list[index]); // Remove the item from the list list.RemoveAt(index); // Udpate the list UpdateMapFromIndex(index); } #region Unimplemented Interface Methods /// <summary> /// Not implemented! /// </summary> /// <exception cref="NotImplementedException">Always.</exception> [Obsolete("Not implemented!", true)] public void ExceptWith(IEnumerable<T> other) { throw new NotImplementedException(); } /// <summary> /// Not implemented! /// </summary> /// <exception cref="NotImplementedException">Always.</exception> [Obsolete("Not implemented!", true)] public void IntersectWith(IEnumerable<T> other) { throw new NotImplementedException(); } /// <summary> /// Not implemented! /// </summary> /// <exception cref="NotImplementedException">Always.</exception> [Obsolete("Not implemented!", true)] public bool IsProperSubsetOf(IEnumerable<T> other) { throw new NotImplementedException(); } /// <summary> /// Not implemented! /// </summary> /// <exception cref="NotImplementedException">Always.</exception> [Obsolete("Not implemented!", true)] public bool IsProperSupersetOf(IEnumerable<T> other) { throw new NotImplementedException(); } /// <summary> /// Not implemented! /// </summary> /// <exception cref="NotImplementedException">Always.</exception> [Obsolete("Not implemented!", true)] public bool IsSubsetOf(IEnumerable<T> other) { throw new NotImplementedException(); } /// <summary> /// Not implemented! /// </summary> /// <exception cref="NotImplementedException">Always.</exception> [Obsolete("Not implemented!", true)] public bool IsSupersetOf(IEnumerable<T> other) { throw new NotImplementedException(); } /// <summary> /// Not implemented! /// </summary> /// <exception cref="NotImplementedException">Always.</exception> [Obsolete("Not implemented!", true)] public bool Overlaps(IEnumerable<T> other) { throw new NotImplementedException(); } /// <summary> /// Not implemented! /// </summary> /// <exception cref="NotImplementedException">Always.</exception> [Obsolete("Not implemented!", true)] public bool SetEquals(IEnumerable<T> other) { throw new NotImplementedException(); } /// <summary> /// Not implemented! /// </summary> /// <exception cref="NotImplementedException">Always.</exception> [Obsolete("Not implemented!", true)] public void SymmetricExceptWith(IEnumerable<T> other) { throw new NotImplementedException(); } /// <summary> /// Not implemented! /// </summary> /// <exception cref="NotImplementedException">Always.</exception> [Obsolete("Not implemented!", true)] public void UnionWith(IEnumerable<T> other) { throw new NotImplementedException(); } #endregion #region Helper Methods /// <summary> /// Adds an item into the list and dictionary. /// Using a helper to avoid ambiguity between /// interface methods. /// </summary> private void AddHelper(T item) { // Add the item into the dictionary first. // We need to preserve the old list size, as // that will be the index the item will be added to. itemToIndexMap.Add(item, list.Count); // Add the item into the list last list.Add(item); } /// <summary> /// Inserts an item into the list and dictionary. /// Using a helper to avoid ambiguity between /// interface methods. /// </summary> private void InsertHelper(int index, T item) { // Add the item into the dictionary first. itemToIndexMap.Add(item, index); // Add the item into the list last list.Insert(index, item); // Update the list from index + 1 up UpdateMapFromIndex(index + 1); } /// <summary> /// Synchronizes the mapping from item-to-index, /// starting at the provided index. /// </summary> /// <param name="startIndex"></param> private void UpdateMapFromIndex(int startIndex) { // Go through the list for (int index = startIndex; index < list.Count; ++index) { // Update the map itemToIndexMap[list[index]] = index; } } #endregion } }
33.564612
113
0.500207
[ "MIT" ]
OmiyaGames/omiya-games-common
Runtime/ListSet.cs
16,885
C#
using QFramework; public class UpdataAvatarUICommand : AbstractCommand { private readonly int mAid; public UpdataAvatarUICommand(int aid) { mAid = aid; } protected override void OnExecute() { this.SendEvent(new UpdataAvatarUIEvent(mAid)); } }
20.214286
54
0.681979
[ "MIT" ]
TastSong/CrazyCar
CrazyCar/Assets/Scripts/Command/UpdataAvatarUICommand.cs
285
C#
// ----------------------------------------------------------------------- // <copyright file="IRealTimeDataSource.cs" company=""> // Copyright 2013 Alexander Soffronow Pagonidis // </copyright> // ----------------------------------------------------------------------- using System; using System.ComponentModel; namespace QDMS { /// <summary> /// Provides real time OHLC bars /// </summary> public interface IRealTimeDataSource : INotifyPropertyChanged { /// <summary> /// Connect to the data source. /// </summary> void Connect(); /// <summary> /// Disconnect from the data source. /// </summary> void Disconnect(); /// <summary> /// Whether the connection to the data source is up or not. /// </summary> bool Connected { get; } /// <summary> /// Request real time data. /// </summary> /// <param name="request"></param> void RequestRealTimeData(RealTimeDataRequest request); /// <summary> /// Cancel a real time data stream. /// </summary> /// <param name="requestID">The ID of the real time data stream.</param> void CancelRealTimeData(int requestID); /// <summary> /// The name of the data source. /// </summary> string Name { get; } /// <summary> /// Fires when new real bar time data is received. /// </summary> event EventHandler<RealTimeDataEventArgs> DataReceived; /// <summary> /// Fires when new real tick time data is received. /// </summary> event EventHandler<TickEventArgs> TickReceived; /// <summary> /// Fires on any error. /// </summary> event EventHandler<ErrorArgs> Error; /// <summary> /// Fires on disconnection from the data source. /// </summary> event EventHandler<DataSourceDisconnectEventArgs> Disconnected; } }
28.857143
80
0.519307
[ "BSD-3-Clause" ]
santoch/qdms
QDMS/Interfaces/IRealTimeDataSource.cs
2,022
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace TennApp.Models.AccountViewModels { public class RegisterViewModel { [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } }
30.678571
125
0.650757
[ "MIT" ]
leinadpb/TENNAPP
TennApp/Models/AccountViewModels/RegisterViewModel.cs
861
C#
using Speckle.Newtonsoft.Json; using Speckle.Core.Kits; using Speckle.Core.Models; using System.Collections.Generic; using Objects.Structural.Analysis; using Objects.Structural.Loading; namespace Objects.Structural.Results { public class ResultGlobal : Result { [DetachProperty] public Model model { get; set; } // this should be a model identifier instead public float? loadX { get; set; } public float? loadY { get; set; } public float? loadZ { get; set; } public float? loadXX { get; set; } public float? loadYY { get; set; } public float? loadZZ { get; set; } public float? reactionX { get; set; } public float? reactionY { get; set; } public float? reactionZ { get; set; } public float? reactionXX { get; set; } public float? reactionYY { get; set; } public float? reactionZZ { get; set; } public float? mode { get; set; } public float? frequency { get; set; } public float? loadFactor { get; set; } public float? modalStiffness { get; set; } public float? modalGeoStiffness { get; set; } public float? effMassX { get; set; } public float? effMassY { get; set; } public float? effMassZ { get; set; } public float? effMassXX { get; set; } public float? effMassYY { get; set; } public float? effMassZZ { get; set; } public ResultGlobal() { } [SchemaInfo("ResultGlobal (load case)", "Creates a Speckle global result object (for load case)", "Structural", "Results")] public ResultGlobal(LoadCase resultCase, float loadX, float loadY, float loadZ, float loadXX, float loadYY, float loadZZ, float reactionX, float reactionY, float reactionZ, float reactionXX, float reactionYY, float reactionZZ, float mode, float frequency, float loadFactor, float modalStiffness, float modalGeoStiffness, float effMassX, float effMassY, float effMassZ, float effMassXX, float effMassYY, float effMassZZ) { this.resultCase = resultCase; this.loadX = loadX; this.loadY = loadY; this.loadZ = loadZ; this.loadXX = loadXX; this.loadYY = loadYY; this.loadZZ = loadZZ; this.reactionX = reactionX; this.reactionY = reactionY; this.reactionZ = reactionZ; this.reactionXX = reactionXX; this.reactionYY = reactionYY; this.reactionZZ = reactionZZ; this.mode = mode; this.frequency = frequency; this.loadFactor = loadFactor; this.modalStiffness = modalStiffness; this.modalGeoStiffness = modalGeoStiffness; this.effMassX = effMassX; this.effMassY = effMassY; this.effMassZ = effMassZ; this.effMassXX = effMassXX; this.effMassYY = effMassYY; this.effMassZZ = effMassZZ; } [SchemaInfo("ResultGlobal (load combination)", "Creates a Speckle global result object (for load combination)", "Structural", "Results")] public ResultGlobal(LoadCombination resultCase, float loadX, float loadY, float loadZ, float loadXX, float loadYY, float loadZZ, float reactionX, float reactionY, float reactionZ, float reactionXX, float reactionYY, float reactionZZ, float mode, float frequency, float loadFactor, float modalStiffness, float modalGeoStiffness, float effMassX, float effMassY, float effMassZ, float effMassXX, float effMassYY, float effMassZZ) { this.resultCase = resultCase; this.loadX = loadX; this.loadY = loadY; this.loadZ = loadZ; this.loadXX = loadXX; this.loadYY = loadYY; this.loadZZ = loadZZ; this.reactionX = reactionX; this.reactionY = reactionY; this.reactionZ = reactionZ; this.reactionXX = reactionXX; this.reactionYY = reactionYY; this.reactionZZ = reactionZZ; this.mode = mode; this.frequency = frequency; this.loadFactor = loadFactor; this.modalStiffness = modalStiffness; this.modalGeoStiffness = modalGeoStiffness; this.effMassX = effMassX; this.effMassY = effMassY; this.effMassZ = effMassZ; this.effMassXX = effMassXX; this.effMassYY = effMassYY; this.effMassZZ = effMassZZ; } } }
46.346939
434
0.616469
[ "Apache-2.0" ]
OswaldoHernandezB/speckle-sharp
Objects/Objects/Structural/Results/ResultGlobal.cs
4,544
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections.Generic; using System.Globalization; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager; using Azure.ResourceManager.Core; using Azure.ResourceManager.KeyVault.Models; namespace Azure.ResourceManager.KeyVault { /// <summary> A Class representing a MhsmPrivateEndpointConnection along with the instance operations that can be performed on it. </summary> public partial class MhsmPrivateEndpointConnection : ArmResource { /// <summary> Generate the resource identifier of a <see cref="MhsmPrivateEndpointConnection"/> instance. </summary> public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string name, string privateEndpointConnectionName) { var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/managedHSMs/{name}/privateEndpointConnections/{privateEndpointConnectionName}"; return new ResourceIdentifier(resourceId); } private readonly ClientDiagnostics _clientDiagnostics; private readonly MhsmPrivateEndpointConnectionsRestOperations _mHSMPrivateEndpointConnectionsRestClient; private readonly MhsmPrivateEndpointConnectionData _data; /// <summary> Initializes a new instance of the <see cref="MhsmPrivateEndpointConnection"/> class for mocking. </summary> protected MhsmPrivateEndpointConnection() { } /// <summary> Initializes a new instance of the <see cref = "MhsmPrivateEndpointConnection"/> class. </summary> /// <param name="options"> The client parameters to use in these operations. </param> /// <param name="data"> The resource that is the target of operations. </param> internal MhsmPrivateEndpointConnection(ArmResource options, MhsmPrivateEndpointConnectionData data) : base(options, data.Id) { HasData = true; _data = data; _clientDiagnostics = new ClientDiagnostics(ClientOptions); _mHSMPrivateEndpointConnectionsRestClient = new MhsmPrivateEndpointConnectionsRestOperations(_clientDiagnostics, Pipeline, ClientOptions, BaseUri); #if DEBUG ValidateResourceId(Id); #endif } /// <summary> Initializes a new instance of the <see cref="MhsmPrivateEndpointConnection"/> class. </summary> /// <param name="options"> The client parameters to use in these operations. </param> /// <param name="id"> The identifier of the resource that is the target of operations. </param> internal MhsmPrivateEndpointConnection(ArmResource options, ResourceIdentifier id) : base(options, id) { _clientDiagnostics = new ClientDiagnostics(ClientOptions); _mHSMPrivateEndpointConnectionsRestClient = new MhsmPrivateEndpointConnectionsRestOperations(_clientDiagnostics, Pipeline, ClientOptions, BaseUri); #if DEBUG ValidateResourceId(Id); #endif } /// <summary> Initializes a new instance of the <see cref="MhsmPrivateEndpointConnection"/> class. </summary> /// <param name="clientOptions"> The client options to build client context. </param> /// <param name="credential"> The credential to build client context. </param> /// <param name="uri"> The uri to build client context. </param> /// <param name="pipeline"> The pipeline to build client context. </param> /// <param name="id"> The identifier of the resource that is the target of operations. </param> internal MhsmPrivateEndpointConnection(ArmClientOptions clientOptions, TokenCredential credential, Uri uri, HttpPipeline pipeline, ResourceIdentifier id) : base(clientOptions, credential, uri, pipeline, id) { _clientDiagnostics = new ClientDiagnostics(ClientOptions); _mHSMPrivateEndpointConnectionsRestClient = new MhsmPrivateEndpointConnectionsRestOperations(_clientDiagnostics, Pipeline, ClientOptions, BaseUri); #if DEBUG ValidateResourceId(Id); #endif } /// <summary> Gets the resource type for the operations. </summary> public static readonly ResourceType ResourceType = "Microsoft.KeyVault/managedHSMs/privateEndpointConnections"; /// <summary> Gets whether or not the current instance has data. </summary> public virtual bool HasData { get; } /// <summary> Gets the data representing this Feature. </summary> /// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception> public virtual MhsmPrivateEndpointConnectionData Data { get { if (!HasData) throw new InvalidOperationException("The current instance does not have data, you must call Get first."); return _data; } } internal static void ValidateResourceId(ResourceIdentifier id) { if (id.ResourceType != ResourceType) throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); } /// <summary> Gets the specified private endpoint connection associated with the managed HSM Pool. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public async virtual Task<Response<MhsmPrivateEndpointConnection>> GetAsync(CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("MhsmPrivateEndpointConnection.Get"); scope.Start(); try { var response = await _mHSMPrivateEndpointConnectionsRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false); if (response.Value == null) throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(response.GetRawResponse()).ConfigureAwait(false); return Response.FromValue(new MhsmPrivateEndpointConnection(this, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets the specified private endpoint connection associated with the managed HSM Pool. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response<MhsmPrivateEndpointConnection> Get(CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("MhsmPrivateEndpointConnection.Get"); scope.Start(); try { var response = _mHSMPrivateEndpointConnectionsRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken); if (response.Value == null) throw _clientDiagnostics.CreateRequestFailedException(response.GetRawResponse()); return Response.FromValue(new MhsmPrivateEndpointConnection(this, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Lists all available geo-locations. </summary> /// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param> /// <returns> A collection of locations that may take multiple service requests to iterate over. </returns> public async virtual Task<IEnumerable<AzureLocation>> GetAvailableLocationsAsync(CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("MhsmPrivateEndpointConnection.GetAvailableLocations"); scope.Start(); try { return await ListAvailableLocationsAsync(ResourceType, cancellationToken).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Lists all available geo-locations. </summary> /// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param> /// <returns> A collection of locations that may take multiple service requests to iterate over. </returns> public virtual IEnumerable<AzureLocation> GetAvailableLocations(CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("MhsmPrivateEndpointConnection.GetAvailableLocations"); scope.Start(); try { return ListAvailableLocations(ResourceType, cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Deletes the specified private endpoint connection associated with the managed hsm pool. </summary> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public async virtual Task<MhsmPrivateEndpointConnectionDeleteOperation> DeleteAsync(bool waitForCompletion, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("MhsmPrivateEndpointConnection.Delete"); scope.Start(); try { var response = await _mHSMPrivateEndpointConnectionsRestClient.DeleteAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false); var operation = new MhsmPrivateEndpointConnectionDeleteOperation(_clientDiagnostics, Pipeline, _mHSMPrivateEndpointConnectionsRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name).Request, response); if (waitForCompletion) await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Deletes the specified private endpoint connection associated with the managed hsm pool. </summary> /// <param name="waitForCompletion"> Waits for the completion of the long running operations. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual MhsmPrivateEndpointConnectionDeleteOperation Delete(bool waitForCompletion, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("MhsmPrivateEndpointConnection.Delete"); scope.Start(); try { var response = _mHSMPrivateEndpointConnectionsRestClient.Delete(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name, cancellationToken); var operation = new MhsmPrivateEndpointConnectionDeleteOperation(_clientDiagnostics, Pipeline, _mHSMPrivateEndpointConnectionsRestClient.CreateDeleteRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Name, Id.Name).Request, response); if (waitForCompletion) operation.WaitForCompletion(cancellationToken); return operation; } catch (Exception e) { scope.Failed(e); throw; } } } }
54.168142
258
0.676115
[ "MIT" ]
AhmedLeithy/azure-sdk-for-net
sdk/keyvault/Azure.ResourceManager.KeyVault/src/Generated/MhsmPrivateEndpointConnection.cs
12,242
C#
using System; using System.Collections.Generic; using System.Text; namespace Line.Messaging { public enum ButtonHeight { Sm, Md, } }
12.538462
33
0.631902
[ "MIT" ]
EvanceKao/LineMessagingApi
src/Line.Messaging/Messages/Flex/ParameterTypes/ButtonHeight.cs
165
C#
using System; using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Parameters { public class KdfCounterParameters : IDerivationParameters { private byte[] ki; private byte[] fixedInputDataCounterPrefix; private byte[] fixedInputDataCounterSuffix; private int r; /// <summary> /// Base constructor - suffix fixed input data only. /// </summary> /// <param name="ki">the KDF seed</param> /// <param name="fixedInputDataCounterSuffix">fixed input data to follow counter.</param> /// <param name="r">length of the counter in bits</param> public KdfCounterParameters(byte[] ki, byte[] fixedInputDataCounterSuffix, int r) : this(ki, null, fixedInputDataCounterSuffix, r) { } /// <summary> /// Base constructor - prefix and suffix fixed input data. /// </summary> /// <param name="ki">the KDF seed</param> /// <param name="fixedInputDataCounterPrefix">fixed input data to precede counter</param> /// <param name="fixedInputDataCounterSuffix">fixed input data to follow counter.</param> /// <param name="r">length of the counter in bits.</param> public KdfCounterParameters(byte[] ki, byte[] fixedInputDataCounterPrefix, byte[] fixedInputDataCounterSuffix, int r) { if (ki == null) { throw new ArgumentException("A KDF requires Ki (a seed) as input"); } this.ki = Arrays.Clone(ki); if (fixedInputDataCounterPrefix == null) { this.fixedInputDataCounterPrefix = new byte[0]; } else { this.fixedInputDataCounterPrefix = Arrays.Clone(fixedInputDataCounterPrefix); } if (fixedInputDataCounterSuffix == null) { this.fixedInputDataCounterSuffix = new byte[0]; } else { this.fixedInputDataCounterSuffix = Arrays.Clone(fixedInputDataCounterSuffix); } if (r != 8 && r != 16 && r != 24 && r != 32) { throw new ArgumentException("Length of counter should be 8, 16, 24 or 32"); } this.r = r; } public byte[] Ki { get { return ki; } } public byte[] FixedInputData { get { return Arrays.Clone(fixedInputDataCounterSuffix); } } public byte[] FixedInputDataCounterPrefix { get { return Arrays.Clone(fixedInputDataCounterPrefix); } } public byte[] FixedInputDataCounterSuffix { get { return Arrays.Clone(fixedInputDataCounterSuffix); } } public int R { get { return r; } } } }
31.445652
138
0.557553
[ "MIT" ]
0x070696E65/Symnity
Assets/Plugins/Symnity/Pulgins/crypto/src/crypto/parameters/KDFCounterParameters.cs
2,895
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using FastSQL.Core; using FastSQL.Sync.Core; using FastSQL.Sync.Core.Indexer; using FastSQL.Sync.Core.Puller; using FastSQL.Sync.Core.Repositories; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace FastSQL.API.Controllers { [Route("api/[controller]")] public class PullersController : Controller { private readonly IEnumerable<IEntityPuller> _entityPullers; private readonly IEnumerable<IAttributePuller> _attributePullers; private readonly IEnumerable<IIndexer> _indexers; public ResolverFactory ResolverFactory { get; set; } public PullersController(IEnumerable<IEntityPuller> entityPullers, IEnumerable<IAttributePuller> attributePullers, IEnumerable<IIndexer> indexers) { _entityPullers = entityPullers; _attributePullers = attributePullers; _indexers = indexers; } [HttpPost("entity/{id}")] public IActionResult PullEntityData(string id, [FromBody] object nextToken = null) { using (var connectionRepository = ResolverFactory.Resolve<ConnectionRepository>()) using (var entityRepository = ResolverFactory.Resolve<EntityRepository>()) using (var attributeRepository = ResolverFactory.Resolve<AttributeRepository>()) { var entity = entityRepository.GetById(id); var sourceConnection = connectionRepository.GetById(entity.SourceConnectionId.ToString()); var puller = _entityPullers.FirstOrDefault(p => p.IsImplemented(entity.SourceProcessorId, sourceConnection.ProviderId)); puller.SetIndex(entity); var data = puller.PullNext(nextToken); return Ok(data); } } [HttpPost("attribute/{id}")] public IActionResult PullAttributeData(string id, [FromBody] object nextToken = null) { using (var connectionRepository = ResolverFactory.Resolve<ConnectionRepository>()) using (var entityRepository = ResolverFactory.Resolve<EntityRepository>()) using (var attributeRepository = ResolverFactory.Resolve<AttributeRepository>()) { var attribute = attributeRepository.GetById(id); var entity = entityRepository.GetById(attribute.EntityId.ToString()); var sourceConnection = connectionRepository.GetById(attribute.SourceConnectionId.ToString()); var puller = _attributePullers.FirstOrDefault(p => p.IsImplemented(attribute.SourceProcessorId, entity.SourceProcessorId, sourceConnection.ProviderId)); puller.SetIndex(attribute); var data = puller.PullNext(nextToken); return Ok(data); } } } }
46.153846
169
0.656
[ "MIT" ]
st2forget/fastSQL
src/api/FastSQL.API/Controllers/PullersController.cs
3,002
C#
using GraphQL.Types; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace {{cookiecutter.library_name}}.Types { public class Base64DataType : ObjectGraphType<Models.Base64Data> { public Base64DataType() { Name = "Base64Data"; Field(data => data.Name).Description("The name of the binary data"); Field(data => data.Base64).Description("The base64 encoded binary data"); } } }
23.4
76
0.739316
[ "MIT" ]
lou-parslow/graphql-framework-library
{{cookiecutter.library_name}}/{{cookiecutter.library_name}}/Types/Base64DataType.cs
470
C#
using MongoDB.Bson; using MongoDB.Driver; using MongoDB.Driver.Linq; using SkdRefSiteAPI.DAO.Models; using SkdRefSiteAPI.DAO.Models.Animals; using SkdRefSiteAPI.DAO.Models.People; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; namespace SkdRefSiteAPI.DAO.Queryables { public class AnimalsQueryable : IQueryable<AnimalReference, AnimalClassifications> { public IMongoQueryable<AnimalReference> GetQueryable(IMongoCollection<AnimalReference> collection, AnimalClassifications classifications, bool? recentImagesOnly) { var query = collection.AsQueryable(); if (classifications.Category.HasValue) query = query.Where(x => x.Classifications.Category == classifications.Category); if (classifications.Species.HasValue) query = query.Where(x => x.Classifications.Species == classifications.Species); if (classifications.ViewAngle.HasValue) query = query.Where(x => x.Classifications.ViewAngle == classifications.ViewAngle); if (recentImagesOnly == true) { var mostRecentUpload = GetMostRecentImageUploadDate(collection); query = query.Where(x => x.UploadDate >= mostRecentUpload.AddDays(-30)); } if (classifications.Status.HasValue) query = query.Where(x => x.Status == classifications.Status); return query; } private DateTime GetMostRecentImageUploadDate(IMongoCollection<AnimalReference> collection) { var query = collection.AsQueryable().OrderByDescending(x => x.UploadDate).Take(1); var item = query.First(); return item.UploadDate; } } }
40.2
169
0.671089
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
faintpixel/skdRefSite
API/SkdRefSiteAPI.DAO/Queryables/AnimalsQueryable.cs
1,811
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading.Tasks; using VkNet.Model; namespace VkNet.Abstractions.Category { /// <summary> /// Secure В этой секции представлены административные методы, /// предназначенные для вызова от имени приложения с использованием стороннего /// сервера. /// Для использования этих методов необходимо применять специальную схему /// авторизации. /// Помимо стандартных параметров, указанных в описании методов, /// к запросу необходимо добавлять параметр client_secret, содержащий значение из /// поля «Защищенный ключ» в настройках приложения. /// Обратите внимание, тестовый режим при работе с secure-методами не /// поддерживается! /// </summary> public interface ISecureCategoryAsync { /// <summary> /// Добавляет информацию о достижениях пользователя в приложении. /// </summary> /// <param name="userId"> /// Идентификатор пользователя, для которого нужно записать данные. /// положительное число, по умолчанию идентификатор текущего пользователя, /// обязательный параметр /// </param> /// <param name="activityId"> /// Идентификатор достижения. Доступные значения: /// 1 — достигнут новый уровень, работает аналогично secure.setUserLevel; /// 2 — заработано новое число очков; /// положительное число, отличное от 1 и 2 — выполнена миссия с идентификатором /// activity_id. /// положительное число, обязательный параметр /// </param> /// <param name="value"> /// Номер уровня или заработанное количество очков (соответственно, для /// activity_id=1 и activity_id=2). /// Параметр игнорируется при значении activity_id, отличном от 1 и 2. /// положительное число, максимальное значение 10000 /// </param> /// <returns> /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/secure.addAppEvent /// </remarks> Task<bool> AddAppEventAsync(ulong userId, ulong activityId, ulong? value = null); /// <summary> /// Позволяет проверять валидность пользователя в IFrame, Flash и /// Standalone-приложениях с помощью передаваемого в приложения параметра /// access_token. /// </summary> /// <param name="token"> /// Клиентский access_token строка /// </param> /// <param name="ip"> /// Ip адрес пользователя. Обратите внимание, что пользователь может обращаться /// через ipv6, в этом случае обязательно передавать ipv6 адрес пользователя. /// Если параметр не передан – ip адрес проверен не будет. строка /// </param> /// <returns> /// В случае успеха будет возвращен объект, содержащий следующие поля: /// success = 1 /// user_id = идентификатор пользователя /// date = unixtime дата, когда access_token был сгенерирован /// expire = unixtime дата, когда access_token станет не валиден /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/secure.checkToken /// </remarks> Task<CheckTokenResult> CheckTokenAsync(string token, string ip = null); /// <summary> /// Возвращает платежный баланс (счет) приложения в сотых долях голоса. /// </summary> /// <returns> /// Возвращает количество голосов (в сотых долях), которые есть на счете /// приложения. /// Например, если метод возвращает 5000, это означает, что на балансе приложения /// 50 голосов. /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/secure.getAppBalance /// </remarks> Task<ulong> GetAppBalanceAsync(); /// <summary> /// Выводит список SMS-уведомлений, отосланных приложением с помощью метода /// secure.sendSMSNotification. /// </summary> /// <param name="userId"> /// Фильтр по id пользователя, которому высылалось уведомление. положительное число /// </param> /// <param name="dateFrom"> /// Фильтр по дате начала. Задается в виде UNIX-time. положительное число /// </param> /// <param name="dateTo"> /// Фильтр по дате окончания. Задается в виде UNIX-time. положительное число /// </param> /// <param name="limit"> /// Количество возвращаемых записей. По умолчанию 1000. положительное число, по /// умолчанию 1000, максимальное значение 1000 /// </param> /// <returns> /// Возвращает список SMS-уведомлений, отосланных приложением, отсортированных по /// убыванию даты и отфильтрованных с помощью параметров uid, date_from, date_to, /// limit. /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/secure.getSMSHistory /// </remarks> Task<ReadOnlyCollection<SmsHistoryItem>> GetSmsHistoryAsync(ulong? userId = null, DateTime? dateFrom = null, DateTime? dateTo = null, ulong? limit = null); /// <summary> /// Выводит историю транзакций по переводу голосов между пользователями и /// приложением. /// </summary> /// <returns> /// Возвращает список транзакций, отсортированных по убыванию даты, и /// отфильтрованных с помощью параметров type, uid_from, uid_to, date_from, /// date_to, limit. /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/secure.getTransactionsHistory /// </remarks> Task<ReadOnlyCollection<Transaction>> GetTransactionsHistoryAsync(); /// <summary> /// Возвращает ранее выставленный игровой уровень одного или нескольких /// пользователей в приложении. /// </summary> /// <param name="userIds"> /// Идентификаторы пользователей, информацию об уровнях которых требуется получить. /// список целых чисел, разделенных запятыми, обязательный параметр /// </param> /// <returns> /// Возвращает значения игровых уровней пользователей в приложении. /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/secure.getUserLevel /// </remarks> Task<ReadOnlyCollection<SecureLevel>> GetUserLevelAsync(IEnumerable<long> userIds); /// <summary> /// Выдает пользователю стикер и открывает игровое достижение. /// </summary> /// <param name="userIds"> /// Список id пользователей которым нужно открыть достижение список положительных /// чисел, разделенных запятыми, обязательный параметр /// </param> /// <param name="achievementId"> /// Id игрового достижения на платформе игр положительное число, обязательный /// параметр /// </param> /// <returns> /// Возвращает список результатов выполнения в виде списка объектов: /// { /// "user_id": int, /// "status": string /// } /// status может принимать значения: /// OK - операция успешна /// ERROR_ACHIEVEMENT_ALREADY_OPENED - стикер уже выдан пользователю /// ERROR_UNKNOWN_ERROR - непредвиденная ошибка /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/secure.giveEventSticker /// </remarks> Task<ReadOnlyCollection<EventSticker>> GiveEventStickerAsync(IEnumerable<ulong> userIds, ulong achievementId); /// <summary> /// Отправляет уведомление пользователю. /// </summary> /// <param name="message"> /// Текст уведомления, который следует передавать в кодировке UTF-8 (максимум 254 /// символа). строка, обязательный параметр /// </param> /// <param name="userIds"> /// Перечисленные через запятую идентификаторы пользователей, которым отправляется /// уведомление (максимум 100 штук). список положительных чисел, разделенных /// запятыми /// </param> /// <returns> /// Возвращает перечисленные через запятую ID пользователей, которым было успешно /// отправлено уведомление. /// Обратите внимание, нельзя отправлять пользователю более 1 уведомления в час (3 /// в сутки). Кроме того, нельзя отправить одному пользователю два уведомления с /// одинаковым текстом подряд. /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/secure.sendNotification /// </remarks> Task<ReadOnlyCollection<ulong>> SendNotificationAsync(string message, IEnumerable<ulong> userIds = null); /// <summary> /// Отправляет SMS-уведомление на мобильный телефон пользователя. /// </summary> /// <param name="userId"> /// Id пользователя, которому отправляется SMS-уведомление. Пользователь должен /// разрешить приложению отсылать ему уведомления (getUserSettings, +1). /// положительное число, обязательный параметр /// </param> /// <param name="message"> /// Текст SMS, который следует передавать в кодировке UTF-8. Допускаются только /// латинские буквы и цифры. Максимальный размер - 160 символов. строка, /// обязательный параметр /// </param> /// <returns> /// Возвращает 1 в случае успешной отсылки SMS. /// Если номер пользователя еще не известен системе, то метод вернет ошибку 146 /// (The mobile number of the user is unknown). Для решения этой проблемы метод /// users.get возвращает поле has_mobile, которое позволяет определить, известен ли /// номер пользователя. /// Если номер пользователя неизвестен, но Вы хотели бы иметь возможность высылать /// ему SMS-уведомления, необходимо предложить ему ввести номер мобильного /// телефона, не отвлекая от приложения. /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/secure.sendSMSNotification /// </remarks> Task<bool> SendSmsNotificationAsync(ulong userId, string message); /// <summary> /// Устанавливает счетчик, который выводится пользователю жирным шрифтом в левом /// меню. /// </summary> /// <param name="counters"> /// Позволяет устанавливать счетчики нескольким пользователям за один запрос. /// Значение следует указывать в следующем формате: /// user_id1:counter1[:increment],user_id2:counter2[:increment], пример: /// 66748:6:1,6492:2. В случае, если указан этот параметр, параметры counter, /// user_id и increment не учитываются. Можно передать не более 200 значений за /// один запрос. список слов, разделенных через запятую /// </param> /// <param name="userId"> /// Идентификатор пользователя. положительное число /// </param> /// <param name="counter"> /// Значение счетчика. целое число /// </param> /// <param name="increment"> /// Определяет, нужно ли заменить значение счетчика или прибавить новое значение к /// уже имеющемуся. 1 — прибавить counter к старому значению, 0 — заменить счетчик /// (по умолчанию). флаг, может принимать значения 1 или 0 /// </param> /// <returns> /// Возвращает 1 в случае успешной установки счетчика. /// Если пользователь не установил приложение в левое меню, метод вернет ошибку 148 /// (Access to the menu of the user denied). Избежать этой ошибки можно с помощью /// метода account.getAppPermissions. /// Вы также можете обращаться к этому методу при стандартном взаимодействии с /// клиентской стороны, указывая setCounter вместо secure.setCounter в названии /// метода. В этом случае параметр uid передавать не нужно, счетчик установится для /// текущего пользователя. /// Метод setCounter при стандартном, а не защищенном взаимодействии можно /// использовать для того, чтобы, например, сбрасывать счетчик при заходе /// пользователя в приложение. /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/secure.setCounter /// </remarks> Task<bool> SetCounterAsync(IEnumerable<string> counters, ulong? userId = null, long? counter = null, bool? increment = null); } }
41.87037
127
0.710217
[ "MIT" ]
Azrael141/vk
VkNet/Abstractions/Category/Async/ISecureCategoryAsync.cs
16,514
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/Shlwapi.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. namespace TerraFX.Interop.Windows; public static partial class URL { [NativeTypeName("#define URL_UNESCAPE 0x10000000")] public const int URL_UNESCAPE = 0x10000000; [NativeTypeName("#define URL_ESCAPE_UNSAFE 0x20000000")] public const int URL_ESCAPE_UNSAFE = 0x20000000; [NativeTypeName("#define URL_PLUGGABLE_PROTOCOL 0x40000000")] public const int URL_PLUGGABLE_PROTOCOL = 0x40000000; [NativeTypeName("#define URL_WININET_COMPATIBILITY 0x80000000")] public const uint URL_WININET_COMPATIBILITY = 0x80000000; [NativeTypeName("#define URL_DONT_ESCAPE_EXTRA_INFO 0x02000000")] public const int URL_DONT_ESCAPE_EXTRA_INFO = 0x02000000; [NativeTypeName("#define URL_DONT_UNESCAPE_EXTRA_INFO URL_DONT_ESCAPE_EXTRA_INFO")] public const int URL_DONT_UNESCAPE_EXTRA_INFO = 0x02000000; [NativeTypeName("#define URL_BROWSER_MODE URL_DONT_ESCAPE_EXTRA_INFO")] public const int URL_BROWSER_MODE = 0x02000000; [NativeTypeName("#define URL_ESCAPE_SPACES_ONLY 0x04000000")] public const int URL_ESCAPE_SPACES_ONLY = 0x04000000; [NativeTypeName("#define URL_DONT_SIMPLIFY 0x08000000")] public const int URL_DONT_SIMPLIFY = 0x08000000; [NativeTypeName("#define URL_NO_META URL_DONT_SIMPLIFY")] public const int URL_NO_META = 0x08000000; [NativeTypeName("#define URL_UNESCAPE_INPLACE 0x00100000")] public const int URL_UNESCAPE_INPLACE = 0x00100000; [NativeTypeName("#define URL_CONVERT_IF_DOSPATH 0x00200000")] public const int URL_CONVERT_IF_DOSPATH = 0x00200000; [NativeTypeName("#define URL_UNESCAPE_HIGH_ANSI_ONLY 0x00400000")] public const int URL_UNESCAPE_HIGH_ANSI_ONLY = 0x00400000; [NativeTypeName("#define URL_INTERNAL_PATH 0x00800000")] public const int URL_INTERNAL_PATH = 0x00800000; [NativeTypeName("#define URL_FILE_USE_PATHURL 0x00010000")] public const int URL_FILE_USE_PATHURL = 0x00010000; [NativeTypeName("#define URL_DONT_UNESCAPE 0x00020000")] public const int URL_DONT_UNESCAPE = 0x00020000; [NativeTypeName("#define URL_ESCAPE_AS_UTF8 0x00040000")] public const int URL_ESCAPE_AS_UTF8 = 0x00040000; [NativeTypeName("#define URL_UNESCAPE_AS_UTF8 URL_ESCAPE_AS_UTF8")] public const int URL_UNESCAPE_AS_UTF8 = 0x00040000; [NativeTypeName("#define URL_ESCAPE_ASCII_URI_COMPONENT 0x00080000")] public const int URL_ESCAPE_ASCII_URI_COMPONENT = 0x00080000; [NativeTypeName("#define URL_ESCAPE_URI_COMPONENT (URL_ESCAPE_ASCII_URI_COMPONENT | URL_ESCAPE_AS_UTF8)")] public const int URL_ESCAPE_URI_COMPONENT = (0x00080000 | 0x00040000); [NativeTypeName("#define URL_UNESCAPE_URI_COMPONENT URL_UNESCAPE_AS_UTF8")] public const int URL_UNESCAPE_URI_COMPONENT = 0x00040000; [NativeTypeName("#define URL_ESCAPE_PERCENT 0x00001000")] public const int URL_ESCAPE_PERCENT = 0x00001000; [NativeTypeName("#define URL_ESCAPE_SEGMENT_ONLY 0x00002000")] public const int URL_ESCAPE_SEGMENT_ONLY = 0x00002000; [NativeTypeName("#define URL_PARTFLAG_KEEPSCHEME 0x00000001")] public const int URL_PARTFLAG_KEEPSCHEME = 0x00000001; [NativeTypeName("#define URL_APPLY_DEFAULT 0x00000001")] public const int URL_APPLY_DEFAULT = 0x00000001; [NativeTypeName("#define URL_APPLY_GUESSSCHEME 0x00000002")] public const int URL_APPLY_GUESSSCHEME = 0x00000002; [NativeTypeName("#define URL_APPLY_GUESSFILE 0x00000004")] public const int URL_APPLY_GUESSFILE = 0x00000004; [NativeTypeName("#define URL_APPLY_FORCEAPPLY 0x00000008")] public const int URL_APPLY_FORCEAPPLY = 0x00000008; }
41.457447
145
0.78291
[ "MIT" ]
IngmarBitter/terrafx.interop.windows
sources/Interop/Windows/Windows/um/Shlwapi/URL.cs
3,899
C#
namespace NOBuildTools.SourceUpdater { 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.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.textBoxSource = new System.Windows.Forms.TextBox(); this.textBoxDest = new System.Windows.Forms.TextBox(); this.buttonChooseSource = new System.Windows.Forms.Button(); this.buttonChooseDest = new System.Windows.Forms.Button(); this.buttonStart = new System.Windows.Forms.Button(); this.textBoxLog = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(29, 62); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(41, 13); this.label1.TabIndex = 0; this.label1.Text = "Source"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(29, 88); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(29, 13); this.label2.TabIndex = 1; this.label2.Text = "Dest"; // // textBoxSource // this.textBoxSource.Location = new System.Drawing.Point(76, 59); this.textBoxSource.Name = "textBoxSource"; this.textBoxSource.Size = new System.Drawing.Size(606, 20); this.textBoxSource.TabIndex = 2; this.textBoxSource.Text = "C:\\LateBindingApi\\LateBindingApi.CodeGenerator.WFApplication\\bin\\Debug\\NetOffice"; // // textBoxDest // this.textBoxDest.Location = new System.Drawing.Point(76, 85); this.textBoxDest.Name = "textBoxDest"; this.textBoxDest.Size = new System.Drawing.Size(606, 20); this.textBoxDest.TabIndex = 3; this.textBoxDest.Text = "C:\\NetOffice\\Source"; // // buttonChooseSource // this.buttonChooseSource.Location = new System.Drawing.Point(688, 57); this.buttonChooseSource.Name = "buttonChooseSource"; this.buttonChooseSource.Size = new System.Drawing.Size(44, 23); this.buttonChooseSource.TabIndex = 4; this.buttonChooseSource.Text = "..."; this.buttonChooseSource.UseVisualStyleBackColor = true; this.buttonChooseSource.Click += new System.EventHandler(this.buttonChooseSource_Click); // // buttonChooseDest // this.buttonChooseDest.Location = new System.Drawing.Point(688, 88); this.buttonChooseDest.Name = "buttonChooseDest"; this.buttonChooseDest.Size = new System.Drawing.Size(44, 23); this.buttonChooseDest.TabIndex = 5; this.buttonChooseDest.Text = "..."; this.buttonChooseDest.UseVisualStyleBackColor = true; this.buttonChooseDest.Click += new System.EventHandler(this.buttonChooseDest_Click); // // buttonStart // this.buttonStart.Location = new System.Drawing.Point(596, 126); this.buttonStart.Name = "buttonStart"; this.buttonStart.Size = new System.Drawing.Size(77, 23); this.buttonStart.TabIndex = 6; this.buttonStart.Text = "Start"; this.buttonStart.UseVisualStyleBackColor = true; this.buttonStart.Click += new System.EventHandler(this.buttonStart_Click); // // textBoxLog // this.textBoxLog.Location = new System.Drawing.Point(76, 129); this.textBoxLog.Name = "textBoxLog"; this.textBoxLog.ReadOnly = true; this.textBoxLog.Size = new System.Drawing.Size(485, 20); this.textBoxLog.TabIndex = 7; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(73, 9); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(624, 13); this.label3.TabIndex = 8; this.label3.Text = "This tool update the existing NetOffice source folder with a newer version. (repl" + "ace by windows explorer kills .svn meta information)"; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(761, 180); this.Controls.Add(this.label3); this.Controls.Add(this.textBoxLog); this.Controls.Add(this.buttonStart); this.Controls.Add(this.buttonChooseDest); this.Controls.Add(this.buttonChooseSource); this.Controls.Add(this.textBoxDest); this.Controls.Add(this.textBoxSource); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Name = "Form1"; this.Text = "SVN friendly CodeIntegrator"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox textBoxSource; private System.Windows.Forms.TextBox textBoxDest; private System.Windows.Forms.Button buttonChooseSource; private System.Windows.Forms.Button buttonChooseDest; private System.Windows.Forms.Button buttonStart; private System.Windows.Forms.TextBox textBoxLog; private System.Windows.Forms.Label label3; } }
43.301887
126
0.581699
[ "MIT" ]
igoreksiz/NetOffice
BuildTools/SourceUpdater/Form1.Designer.cs
6,887
C#
#region License /* The MIT License Copyright (c) 2008 Sky Morey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using NAnt.Core; using NAnt.Core.Attributes; using System; using System.IO; using System.Linq; using System.Patterns.ReleaseManagement; namespace Digital.Nant.Hosting.Tasks { [TaskName("manageIis"), Serializable] public partial class ManageIisTask : Task { [TaskAttribute("deploymentEnvironment", Required = true), StringValidator(AllowEmpty = false)] public DeploymentEnvironment DeploymentEnvironment { get; set; } [TaskAttribute("applicationId", Required = true), StringValidator(AllowEmpty = false)] public string ApplicationId { get; set; } [TaskAttribute("remove")] public bool Remove { get; set; } [BuildElementArray("binding")] public Binding[] Bindings { get; set; } private string ApplicationPath { get; set; } private decimal IisVersion { get; set; } private decimal LayoutVersion { get; set; } protected override void ExecuteTask() { LayoutVersion = 2M; IisVersion = 7M; var iis = (IisVersion != 6M ? (IIis)new Iis7 { Project = Project } : (IIis)new Iis6 { Project = Project }); ApplicationPath = (!Project.Properties.Contains("applicationPath") ? @"C:\_APPLICATION2" : Project.Properties["applicationPath"]); // site var bindings = (Bindings != null ? Bindings.Select(c => new IisContext.Binding { Information = c.Information, Protocol = c.Protocol }).ToArray() : null); var iisContext = new IisContext { LayoutVersion = LayoutVersion, ApplicationPoolId = ApplicationId, ApplicationPoolUserId = DeploymentEnvironment.CreateAccountUserId(ApplicationId, "IUSR"), ApplicationPoolPassword = DeploymentEnvironment.CreateAccountPassword(ApplicationId, "IUSR"), Bindings = bindings, SiteId = ApplicationId, Domain = ApplicationId + "." + DeploymentEnvironment.ToShortName() + (DeploymentEnvironment.GetExternalDeployment() ? ".x.com" : ".x.com"), RootPath = ApplicationPath + @"\" + ApplicationId, }; if (!Remove) iis.CreateSite(iisContext); else iis.RemoveSite(iisContext); } } }
39.444444
157
0.726448
[ "Apache-2.0", "MIT" ]
Grimace1975/bclcontrib
Extents/Digital.Nant.Hosting.Tasks/Nant/Hosting/Tasks+Web/ManageIisTask.cs
3,197
C#
using System.Reflection; using System.Runtime.CompilerServices; namespace NeinLinq; /// <summary> /// Expression visitor for making member access null-safe. /// </summary> public class NullsafeQueryRewriter : ExpressionVisitor { private static readonly ObjectCache<Type, Expression?> Cache = new(); /// <inheritdoc /> protected override Expression VisitMember(MemberExpression node) { if (node is null) throw new ArgumentNullException(nameof(node)); var target = Visit(node.Expression); if (!IsSafe(target)) { // insert null-check before accessing property or field return BeSafe(target!, node, node.Update); } return node.Update(target!); } /// <inheritdoc /> protected override Expression VisitMethodCall(MethodCallExpression node) { if (node is null) throw new ArgumentNullException(nameof(node)); var target = Visit(node.Object); if (!IsSafe(target)) { // insert null-check before invoking instance method return BeSafe(target!, node, fallback => node.Update(fallback, node.Arguments)); } var arguments = Visit(node.Arguments); if (IsExtensionMethod(node.Method) && !IsSafe(arguments[0])) { // insert null-check before invoking extension method return BeSafe(arguments[0], node.Update(target!, arguments), fallback => { var args = new Expression[arguments.Count]; arguments.CopyTo(args, 0); args[0] = fallback; return node.Update(target!, args); }); } return node.Update(target!, arguments); } private static Expression BeSafe(Expression target, Expression expression, Func<Expression, Expression> update) { var fallback = Cache.GetOrAdd(target.Type, Fallback); if (fallback is not null) { // coalesce instead, a bit intrusive but fast... return update(Expression.Coalesce(target, fallback)); } // target can be null, which is why we are actually here... var targetFallback = Expression.Constant(null, target.Type); // expression can be default or null, which is basically the same... var expressionFallback = !IsNullableOrReferenceType(expression.Type) ? (Expression)Expression.Default(expression.Type) : Expression.Constant(null, expression.Type); return Expression.Condition(Expression.Equal(target, targetFallback), expressionFallback, expression); } private static bool IsSafe(Expression? expression) => expression is null // in method call results and constant values we trust to avoid too much conditions... || expression.NodeType == ExpressionType.Call || expression.NodeType == ExpressionType.Constant || !IsNullableOrReferenceType(expression.Type); private static Expression? Fallback(Type type) { // default values for generic collections if (type.IsGenericType && type.GetGenericArguments().Length == 1) { return CollectionFallback(typeof(List<>), type) ?? CollectionFallback(typeof(HashSet<>), type); } // default value for arrays return type.IsArray ? Expression.NewArrayInit(type.GetElementType()!) : null; } private static Expression? CollectionFallback(Type definition, Type type) { var collection = definition.MakeGenericType(type.GetGenericArguments()); // try if an instance of this collection would suffice return type.IsAssignableFrom(collection) ? Expression.Convert(Expression.New(collection), type) : null; } private static bool IsExtensionMethod(MethodInfo element) => element.IsDefined(typeof(ExtensionAttribute), false); private static bool IsNullableOrReferenceType(Type type) => !type.IsValueType || Nullable.GetUnderlyingType(type) is not null; }
34.4
116
0.637597
[ "MIT" ]
rostunic/nein-linq
src/NeinLinq/NullsafeQueryRewriter.cs
4,130
C#
using FaasNet.Runtime.Domains.Definitions; using FaasNet.Runtime.Extensions; using System.Collections.Concurrent; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace FaasNet.Runtime.Persistence.InMemory { public class InMemoryWorkflowDefinitionRepository : IWorkflowDefinitionRepository { private readonly ConcurrentBag<WorkflowDefinitionAggregate> _defs; public InMemoryWorkflowDefinitionRepository(ConcurrentBag<WorkflowDefinitionAggregate> defs) { _defs = defs; } public Task Add(WorkflowDefinitionAggregate workflowDef, CancellationToken cancellationToken) { _defs.Add(workflowDef); return Task.CompletedTask; } public Task Update(WorkflowDefinitionAggregate workflowDef, CancellationToken cancellationToken) { _defs.Remove(_defs.First(_ => _.Id == workflowDef.Id)); _defs.Add(workflowDef); return Task.CompletedTask; } public IQueryable<WorkflowDefinitionAggregate> Query() { return _defs.AsQueryable(); } public Task<int> SaveChanges(CancellationToken cancellationToken) { return Task.FromResult(1); } } }
29.25
104
0.679876
[ "Apache-2.0" ]
simpleidserver/FaasNet
src/FaasNet.Runtime/Persistence/InMemory/InMemoryWorkflowDefinitionRepository.cs
1,289
C#
using System.IO; using System.Runtime.Serialization; using WolvenKit.CR2W.Reflection; using FastMember; using static WolvenKit.CR2W.Types.Enums; namespace WolvenKit.CR2W.Types { [DataContract(Namespace = "")] [REDMeta] public class CGlabalTicketSourceProvider : CObject { public CGlabalTicketSourceProvider(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CGlabalTicketSourceProvider(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
31
139
0.748948
[ "MIT" ]
DerinHalil/CP77Tools
CP77.CR2W/Types/W3/RTTIConvert/CGlabalTicketSourceProvider.cs
691
C#
using System; using SaaSOvation.Common.Domain.Model; using SaaSOvation.Collaboration.Domain.Model.Tenants; namespace SaaSOvation.Collaboration.Domain.Model.Forums { public class DiscussionClosed : IDomainEvent { public DiscussionClosed(Tenant tenantId, ForumId forumId, DiscussionId discussionId, string exclusiveOwner) { TenantId = tenantId; ForumId = forumId; DiscussionId = discussionId; ExclusiveOwner = exclusiveOwner; } public Tenant TenantId { get; } public ForumId ForumId { get; } public DiscussionId DiscussionId { get; } public string ExclusiveOwner { get; } public int EventVersion { get; set; } public DateTime OccurredOn { get; set; } } }
30.346154
115
0.66033
[ "Apache-2.0" ]
GermanKuber-zz/IDDD_Samples_NET
iddd_collaboration/Domain.Model/Forums/DiscussionClosed.cs
791
C#
// ---------------------------------------------------------------------------- // <auto-generated> // This is autogenerated code by CppSharp. // Do not edit this file or all your changes will be lost after re-generation. // </auto-generated> // ---------------------------------------------------------------------------- using System; using System.Runtime.InteropServices; using System.Security; using System.Runtime.CompilerServices; [assembly:InternalsVisibleTo("CppSharp.Parser.CSharp")] [assembly:InternalsVisibleTo("CppSharp.CppParser")] namespace Std { public unsafe partial class Lockit { [StructLayout(LayoutKind.Explicit, Size = 4)] public partial struct __Internal { [FieldOffset(0)] internal int _Locktype; } } } namespace Std { } namespace Std { public unsafe partial class ExceptionPtr { [StructLayout(LayoutKind.Explicit, Size = 8)] public partial struct __Internal { [FieldOffset(0)] internal global::System.IntPtr _Data1; [FieldOffset(4)] internal global::System.IntPtr _Data2; } } } public unsafe partial class StdExceptionData { [StructLayout(LayoutKind.Explicit, Size = 8)] public partial struct __Internal { [FieldOffset(0)] internal global::System.IntPtr _What; [FieldOffset(4)] internal byte _DoFree; } } namespace Std { namespace CharTraits { [StructLayout(LayoutKind.Explicit, Size = 0)] public unsafe partial struct __Internal { } } public unsafe partial class CharTraits<_Elem> : IDisposable { public global::System.IntPtr __Instance { get; protected set; } protected int __PointerAdjustment; internal static readonly global::System.Collections.Concurrent.ConcurrentDictionary<IntPtr, global::Std.CharTraits<_Elem>> NativeToManagedMap = new global::System.Collections.Concurrent.ConcurrentDictionary<IntPtr, global::Std.CharTraits<_Elem>>(); protected void*[] __OriginalVTables; protected bool __ownsNativeInstance; internal static global::Std.CharTraits<_Elem> __CreateInstance(global::System.IntPtr native, bool skipVTables = false) { return new global::Std.CharTraits<_Elem>(native.ToPointer(), skipVTables); } internal static global::Std.CharTraits<_Elem> __CreateInstance(global::Std.CharTraits.__Internal native, bool skipVTables = false) { return new global::Std.CharTraits<_Elem>(native, skipVTables); } private static void* __CopyValue(global::Std.CharTraits.__Internal native) { var ret = Marshal.AllocHGlobal(sizeof(global::Std.CharTraits.__Internal)); *(global::Std.CharTraits.__Internal*) ret = native; return ret.ToPointer(); } private CharTraits(global::Std.CharTraits.__Internal native, bool skipVTables = false) : this(__CopyValue(native), skipVTables) { __ownsNativeInstance = true; NativeToManagedMap[__Instance] = this; } protected CharTraits(void* native, bool skipVTables = false) { if (native == null) return; __Instance = new global::System.IntPtr(native); } public void Dispose() { Dispose(disposing: true); } public virtual void Dispose(bool disposing) { if (__Instance == IntPtr.Zero) return; global::Std.CharTraits<_Elem> __dummy; NativeToManagedMap.TryRemove(__Instance, out __dummy); if (__ownsNativeInstance) Marshal.FreeHGlobal(__Instance); __Instance = IntPtr.Zero; } } } namespace Std { } namespace Std { namespace Yarn { [StructLayout(LayoutKind.Explicit, Size = 8)] public unsafe partial struct __Internalc__N_std_S__Yarn__C { [FieldOffset(0)] internal global::System.IntPtr _Myptr; [FieldOffset(4)] internal sbyte _Nul; } [StructLayout(LayoutKind.Explicit, Size = 8)] public unsafe partial struct __Internalc__N_std_S__Yarn__W { [FieldOffset(0)] internal global::System.IntPtr _Myptr; [FieldOffset(4)] internal char _Nul; } } namespace CompressedPair { [StructLayout(LayoutKind.Explicit, Size = 24)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator__C___N_std_S__String_val____N_std_S__Simple_types__C_Vb1 { [FieldOffset(0)] internal global::Std.StringVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator_____N_CppSharp_N_CppParser_N_AST_S_PreprocessedEntity___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator_____N_CppSharp_N_CppParser_N_AST_S_Declaration___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator_____N_CppSharp_N_CppParser_N_AST_S_BlockContentComment___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator_____N_CppSharp_N_CppParser_N_AST_S_Template___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator_____N_CppSharp_N_CppParser_N_AST_S_TypedefDecl___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator_____N_CppSharp_N_CppParser_N_AST_S_TypeAlias___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator_____N_CppSharp_N_CppParser_N_AST_S_Variable___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator_____N_CppSharp_N_CppParser_N_AST_S_Friend___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 8)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_less____N_std_S_basic_string__C___N_std_S_char_traits__C___N_std_S_allocator__C___N_std_S__Compressed_pair____N_std_S_allocator____N_std_S__Tree_node____N_std_S_pair__1S1_____N_CppSharp_N_CppParser_N_AST_S_Declaration__v___N_std_S__Tree_val____N_std_S__Tree_simple_types__S7__Vb1_Vb1 { [FieldOffset(0)] internal global::Std.CompressedPair.__Internalc__N_std_S__Compressed_pair____N_std_S_allocator____N_std_S__Tree_node____N_std_S_pair__1__N_std_S_basic_string__C___N_std_S_char_traits__C___N_std_S_allocator__C____N_CppSharp_N_CppParser_N_AST_S_Declaration__v___N_std_S__Tree_val____N_std_S__Tree_simple_types__S2__Vb1 _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 8)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator____N_std_S__Tree_node____N_std_S_pair__1__N_std_S_basic_string__C___N_std_S_char_traits__C___N_std_S_allocator__C____N_CppSharp_N_CppParser_N_AST_S_Declaration__v___N_std_S__Tree_val____N_std_S__Tree_simple_types__S2__Vb1 { [FieldOffset(0)] internal global::Std.TreeVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator_____N_CppSharp_N_CppParser_N_AST_S_BaseClassSpecifier___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator_____N_CppSharp_N_CppParser_N_AST_S_Field___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator_____N_CppSharp_N_CppParser_N_AST_S_Parameter___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator_____N_CppSharp_N_CppParser_N_AST_S_FunctionTemplateSpecialization___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator____N_CppSharp_N_CppParser_N_AST_S_TemplateArgument___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator_____N_CppSharp_N_CppParser_N_AST_S_Method___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator_____N_CppSharp_N_CppParser_N_AST_S_AccessSpecifierDecl___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator____N_CppSharp_N_CppParser_N_AST_S_VTableComponent___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator____N_CppSharp_N_CppParser_N_AST_S_VFTableInfo___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator____N_CppSharp_N_CppParser_N_AST_S_LayoutField___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator____N_CppSharp_N_CppParser_N_AST_S_LayoutBase___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator_____N_CppSharp_N_CppParser_N_AST_S_Class___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator_____N_CppSharp_N_CppParser_N_AST_S_Function___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator_____N_CppSharp_N_CppParser_N_AST_S_Enumeration_S_Item___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator_____N_CppSharp_N_CppParser_N_AST_S_Enumeration___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator_____N_CppSharp_N_CppParser_N_AST_S_Namespace___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator____N_std_S_basic_string__C___N_std_S_char_traits__C___N_std_S_allocator__C___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator_____N_CppSharp_N_CppParser_N_AST_S_ClassTemplateSpecialization___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator_____N_CppSharp_N_CppParser_N_AST_S_Expression___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator_____N_CppSharp_N_CppParser_N_AST_S_VarTemplateSpecialization___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator_____N_CppSharp_N_CppParser_N_AST_S_MacroDefinition___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator_____N_CppSharp_N_CppParser_N_AST_S_TranslationUnit___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator_____N_CppSharp_N_CppParser_N_AST_S_InlineContentComment___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator____N_CppSharp_N_CppParser_N_AST_S_BlockCommandComment_S_Argument___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator__i___N_std_S__Vector_val____N_std_S__Simple_types__i_Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator_____N_CppSharp_N_CppParser_N_AST_S_VerbatimBlockLineComment___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator____N_CppSharp_N_CppParser_N_AST_S_InlineCommandComment_S_Argument___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator____N_CppSharp_N_CppParser_N_AST_S_HTMLStartTagComment_S_Attribute___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internalc__N_std_S__Compressed_pair____N_std_S_allocator____N_CppSharp_N_CppParser_S_ParserDiagnostic___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 { [FieldOffset(0)] internal global::Std.VectorVal.__Internal _Myval2; } } } namespace Std { namespace Allocator { [StructLayout(LayoutKind.Explicit, Size = 0)] public unsafe partial struct __Internal { [SuppressUnmanagedCodeSecurity] [DllImport("Std-symbols", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="??0?$allocator@D@std@@QAE@XZ")] internal static extern global::System.IntPtr ctorc__N_std_S_allocator__C(global::System.IntPtr instance); } } public unsafe partial class Allocator<_Ty> : IDisposable { public global::System.IntPtr __Instance { get; protected set; } protected int __PointerAdjustment; internal static readonly global::System.Collections.Concurrent.ConcurrentDictionary<IntPtr, global::Std.Allocator<_Ty>> NativeToManagedMap = new global::System.Collections.Concurrent.ConcurrentDictionary<IntPtr, global::Std.Allocator<_Ty>>(); protected void*[] __OriginalVTables; protected bool __ownsNativeInstance; internal static global::Std.Allocator<_Ty> __CreateInstance(global::System.IntPtr native, bool skipVTables = false) { return new global::Std.Allocator<_Ty>(native.ToPointer(), skipVTables); } internal static global::Std.Allocator<_Ty> __CreateInstance(global::Std.Allocator.__Internal native, bool skipVTables = false) { return new global::Std.Allocator<_Ty>(native, skipVTables); } private static void* __CopyValue(global::Std.Allocator.__Internal native) { var ret = Marshal.AllocHGlobal(sizeof(global::Std.Allocator.__Internal)); *(global::Std.Allocator.__Internal*) ret = native; return ret.ToPointer(); } private Allocator(global::Std.Allocator.__Internal native, bool skipVTables = false) : this(__CopyValue(native), skipVTables) { __ownsNativeInstance = true; NativeToManagedMap[__Instance] = this; } protected Allocator(void* native, bool skipVTables = false) { if (native == null) return; __Instance = new global::System.IntPtr(native); } public Allocator() { var ___Ty = typeof(_Ty); if (___Ty.IsAssignableFrom(typeof(sbyte))) { __Instance = Marshal.AllocHGlobal(sizeof(global::Std.Allocator.__Internal)); __ownsNativeInstance = true; NativeToManagedMap[__Instance] = this; global::Std.Allocator.__Internal.ctorc__N_std_S_allocator__C((__Instance + __PointerAdjustment)); return; } throw new ArgumentOutOfRangeException("_Ty", string.Join(", ", new[] { typeof(_Ty).FullName }), "global::Std.Allocator<_Ty> maps a C++ template class and therefore it only supports a limited set of types and their subclasses: <sbyte>."); } public void Dispose() { Dispose(disposing: true); } public virtual void Dispose(bool disposing) { if (__Instance == IntPtr.Zero) return; global::Std.Allocator<_Ty> __dummy; NativeToManagedMap.TryRemove(__Instance, out __dummy); if (__ownsNativeInstance) Marshal.FreeHGlobal(__Instance); __Instance = IntPtr.Zero; } } } namespace Std { public unsafe static partial class BasicStringExtensions { [StructLayout(LayoutKind.Explicit, Size = 0)] public partial struct __Internal { [SuppressUnmanagedCodeSecurity] [DllImport("Std-symbols", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@QBDABV?$allocator@D@1@@Z")] internal static extern global::System.IntPtr BasicString(global::System.IntPtr instance, [MarshalAs(UnmanagedType.LPStr)] string _Ptr, global::System.IntPtr _Al); [SuppressUnmanagedCodeSecurity] [DllImport("Std-symbols", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?c_str@?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QBEPBDXZ")] internal static extern global::System.IntPtr CStr(global::System.IntPtr instance); } public static global::Std.BasicString<sbyte, global::Std.CharTraits<sbyte>, global::Std.Allocator<sbyte>> BasicString(string _Ptr, global::Std.Allocator<sbyte> _Al) { if (ReferenceEquals(_Al, null)) throw new global::System.ArgumentNullException("_Al", "Cannot be null because it is a C++ reference (&)."); var __arg1 = _Al.__Instance; var __ret = Marshal.AllocHGlobal(24); __Internal.BasicString(__ret, _Ptr, __arg1); global::Std.BasicString<sbyte, global::Std.CharTraits<sbyte>, global::Std.Allocator<sbyte>> __result0; if (__ret == IntPtr.Zero) __result0 = null; else if (global::Std.BasicString<sbyte, global::Std.CharTraits<sbyte>, global::Std.Allocator<sbyte>>.NativeToManagedMap.ContainsKey(__ret)) __result0 = (global::Std.BasicString<sbyte, global::Std.CharTraits<sbyte>, global::Std.Allocator<sbyte>>) global::Std.BasicString<sbyte, global::Std.CharTraits<sbyte>, global::Std.Allocator<sbyte>>.NativeToManagedMap[__ret]; else __result0 = global::Std.BasicString<sbyte, global::Std.CharTraits<sbyte>, global::Std.Allocator<sbyte>>.__CreateInstance(__ret); return __result0; } public static string CStr(this global::Std.BasicString<sbyte, global::Std.CharTraits<sbyte>, global::Std.Allocator<sbyte>> @this) { var __arg0 = ReferenceEquals(@this, null) ? global::System.IntPtr.Zero : @this.__Instance; var __ret = __Internal.CStr(__arg0); return Marshal.PtrToStringAnsi(__ret); } } namespace BasicString { [StructLayout(LayoutKind.Explicit, Size = 24)] public unsafe partial struct __Internal { [FieldOffset(0)] internal global::Std.CompressedPair.__Internalc__N_std_S__Compressed_pair____N_std_S_allocator__C___N_std_S__String_val____N_std_S__Simple_types__C_Vb1 _Mypair; [SuppressUnmanagedCodeSecurity] [DllImport("Std-symbols", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="??1?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@XZ")] internal static extern void dtorc__N_std_S_basic_string__C___N_std_S_char_traits__C___N_std_S_allocator__C(global::System.IntPtr instance, int delete); [SuppressUnmanagedCodeSecurity] [DllImport("Std-symbols", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.ThisCall, EntryPoint="?c_str@?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QBEPBDXZ")] internal static extern global::System.IntPtr CStrc__N_std_S_basic_string__C___N_std_S_char_traits__C___N_std_S_allocator__C(global::System.IntPtr instance); } } public unsafe partial class BasicString<_Elem, _Traits, _Alloc> : IDisposable { public global::System.IntPtr __Instance { get; protected set; } protected int __PointerAdjustment; internal static readonly global::System.Collections.Concurrent.ConcurrentDictionary<IntPtr, global::Std.BasicString<_Elem, _Traits, _Alloc>> NativeToManagedMap = new global::System.Collections.Concurrent.ConcurrentDictionary<IntPtr, global::Std.BasicString<_Elem, _Traits, _Alloc>>(); protected void*[] __OriginalVTables; protected bool __ownsNativeInstance; internal static global::Std.BasicString<_Elem, _Traits, _Alloc> __CreateInstance(global::System.IntPtr native, bool skipVTables = false) { return new global::Std.BasicString<_Elem, _Traits, _Alloc>(native.ToPointer(), skipVTables); } internal static global::Std.BasicString<_Elem, _Traits, _Alloc> __CreateInstance(global::Std.BasicString.__Internal native, bool skipVTables = false) { return new global::Std.BasicString<_Elem, _Traits, _Alloc>(native, skipVTables); } private static void* __CopyValue(global::Std.BasicString.__Internal native) { var ret = Marshal.AllocHGlobal(sizeof(global::Std.BasicString.__Internal)); *(global::Std.BasicString.__Internal*) ret = native; return ret.ToPointer(); } private BasicString(global::Std.BasicString.__Internal native, bool skipVTables = false) : this(__CopyValue(native), skipVTables) { __ownsNativeInstance = true; NativeToManagedMap[__Instance] = this; } protected BasicString(void* native, bool skipVTables = false) { if (native == null) return; __Instance = new global::System.IntPtr(native); } public void Dispose() { Dispose(disposing: true); } public virtual void Dispose(bool disposing) { if (__Instance == IntPtr.Zero) return; global::Std.BasicString<_Elem, _Traits, _Alloc> __dummy; NativeToManagedMap.TryRemove(__Instance, out __dummy); if (disposing) { var ___Elem = typeof(_Elem); var ___Traits = typeof(_Traits); var ___Alloc = typeof(_Alloc); if (___Elem.IsAssignableFrom(typeof(sbyte)) && ___Traits.IsAssignableFrom(typeof(global::Std.CharTraits<sbyte>)) && ___Alloc.IsAssignableFrom(typeof(global::Std.Allocator<sbyte>))) { global::Std.BasicString.__Internal.dtorc__N_std_S_basic_string__C___N_std_S_char_traits__C___N_std_S_allocator__C((__Instance + __PointerAdjustment), 0); return; } throw new ArgumentOutOfRangeException("_Elem, _Traits, _Alloc", string.Join(", ", new[] { typeof(_Elem).FullName, typeof(_Traits).FullName, typeof(_Alloc).FullName }), "global::Std.BasicString<_Elem, _Traits, _Alloc> maps a C++ template class and therefore it only supports a limited set of types and their subclasses: <sbyte, global::Std.CharTraits<sbyte>, global::Std.Allocator<sbyte>>."); } if (__ownsNativeInstance) Marshal.FreeHGlobal(__Instance); __Instance = IntPtr.Zero; } } namespace StringVal { [StructLayout(LayoutKind.Explicit, Size = 24)] public unsafe partial struct __Internal { [FieldOffset(0)] internal global::Std.StringVal.Bxty.__Internal _Bx; [FieldOffset(16)] internal uint _Mysize; [FieldOffset(20)] internal uint _Myres; } public unsafe partial struct Bxty { [StructLayout(LayoutKind.Explicit, Size = 16)] public partial struct __Internal { [FieldOffset(0)] internal fixed sbyte _Buf[16]; [FieldOffset(0)] internal global::System.IntPtr _Ptr; [FieldOffset(0)] internal fixed sbyte _Alias[16]; } } } } namespace Std { namespace VectorVal { [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internal { [FieldOffset(0)] internal global::System.IntPtr _Myfirst; [FieldOffset(4)] internal global::System.IntPtr _Mylast; [FieldOffset(8)] internal global::System.IntPtr _Myend; } } namespace Vector { [StructLayout(LayoutKind.Explicit, Size = 12)] public unsafe partial struct __Internal { [FieldOffset(0)] internal global::Std.CompressedPair.__Internalc__N_std_S__Compressed_pair____N_std_S_allocator_____N_CppSharp_N_CppParser_N_AST_S_PreprocessedEntity___N_std_S__Vector_val____N_std_S__Simple_types__S1__Vb1 _Mypair; } } } namespace Std { } namespace Std { namespace TreeVal { [StructLayout(LayoutKind.Explicit, Size = 8)] public unsafe partial struct __Internal { [FieldOffset(0)] internal global::System.IntPtr _Myhead; [FieldOffset(4)] internal uint _Mysize; } } } namespace Std { namespace Map { [StructLayout(LayoutKind.Explicit, Size = 8)] public unsafe partial struct __Internal { [FieldOffset(0)] internal global::Std.CompressedPair.__Internalc__N_std_S__Compressed_pair____N_std_S_less____N_std_S_basic_string__C___N_std_S_char_traits__C___N_std_S_allocator__C___N_std_S__Compressed_pair____N_std_S_allocator____N_std_S__Tree_node____N_std_S_pair__1S1_____N_CppSharp_N_CppParser_N_AST_S_Declaration__v___N_std_S__Tree_val____N_std_S__Tree_simple_types__S7__Vb1_Vb1 _Mypair; } } } public unsafe partial class StdTypeInfoData { [StructLayout(LayoutKind.Explicit, Size = 8)] public partial struct __Internal { [FieldOffset(0)] internal global::System.IntPtr _UndecoratedName; [FieldOffset(4)] internal fixed sbyte _DecoratedName[1]; } } public unsafe partial class Ctypevec { [StructLayout(LayoutKind.Explicit, Size = 16)] public partial struct __Internal { [FieldOffset(0)] internal uint _Page; [FieldOffset(4)] internal global::System.IntPtr _Table; [FieldOffset(8)] internal int _Delfl; [FieldOffset(12)] internal global::System.IntPtr _LocaleName; } } public unsafe partial class Cvtvec { [StructLayout(LayoutKind.Explicit, Size = 44)] public partial struct __Internal { [FieldOffset(0)] internal uint _Page; [FieldOffset(4)] internal uint _Mbcurmax; [FieldOffset(8)] internal int _Isclocale; [FieldOffset(12)] internal fixed byte _Isleadbyte[32]; } } namespace Std { [Flags] public enum CodecvtMode { ConsumeHeader = 4, GenerateHeader = 2 } } namespace Std { public unsafe partial class ErrorCode { [StructLayout(LayoutKind.Explicit, Size = 8)] public partial struct __Internal { [FieldOffset(0)] internal int _Myval; [FieldOffset(4)] internal global::System.IntPtr _Mycat; } } } namespace Std { namespace Literals { } }
41.463734
407
0.690832
[ "MIT" ]
roscopecoltran/SniperKit-Core
Toolkits/Interop/CppSharp/src/CppParser/Bindings/CSharp/i686-pc-win32-msvc/Std.cs
34,871
C#
using System; namespace AvScan.EsetScanner { using System.Diagnostics; using System.IO; using Core; public class EsetScanner: IScanner { private readonly string esetClsLocation; /// <summary> /// Creates a new scanner /// </summary> /// <param name="esetClsLocation">The location of the ecls.exe file e.g. C:\Program Files\ESET\ESET Endpoint Antivirus\ecls.exe</param> public EsetScanner(string esetClsLocation) { if (!File.Exists(esetClsLocation)) { throw new FileNotFoundException(); } this.esetClsLocation = new FileInfo(esetClsLocation).FullName; } /// <summary> /// Scan a single file /// </summary> /// <param name="file">The file to scan</param> /// <param name="timeoutInMs">The maximum time in milliseconds to take for this scan</param> /// <returns>The scan result</returns> public ScanResult Scan(string file, int timeoutInMs = 30000) { if (!File.Exists(file)) { return ScanResult.FileNotFound; } var fileInfo = new FileInfo(file); var process = new Process(); var startInfo = new ProcessStartInfo(this.esetClsLocation) { Arguments = $"\"{fileInfo.FullName}\" /no-log-console /preserve-time", CreateNoWindow = true, ErrorDialog = false, WindowStyle = ProcessWindowStyle.Hidden, UseShellExecute = false }; process.StartInfo = startInfo; process.Start(); process.WaitForExit(timeoutInMs); if (!process.HasExited) { process.Kill(); return ScanResult.Timeout; } switch (process.ExitCode) { case 0: return ScanResult.NoThreatFound; case 1: case 50: return ScanResult.ThreatFound; case 10: case 100: return ScanResult.Error; default: return ScanResult.Error; } } } }
29.316456
143
0.51209
[ "MIT" ]
Cliov/AvScan
src/AvScan.EsetScanner/EsetScanner.cs
2,318
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ShiftRightLogicalAdd_Vector128_Int16_1() { var test = new ImmBinaryOpTest__ShiftRightLogicalAdd_Vector128_Int16_1(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmBinaryOpTest__ShiftRightLogicalAdd_Vector128_Int16_1 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Int16> _fld1; public Vector128<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__ShiftRightLogicalAdd_Vector128_Int16_1 testClass) { var result = AdvSimd.ShiftRightLogicalAdd(_fld1, _fld2, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmBinaryOpTest__ShiftRightLogicalAdd_Vector128_Int16_1 testClass) { fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<Int16>* pFld2 = &_fld2) { var result = AdvSimd.ShiftRightLogicalAdd( AdvSimd.LoadVector128((Int16*)(pFld1)), AdvSimd.LoadVector128((Int16*)(pFld2)), 1 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly byte Imm = 1; private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector128<Int16> _clsVar1; private static Vector128<Int16> _clsVar2; private Vector128<Int16> _fld1; private Vector128<Int16> _fld2; private DataTable _dataTable; static ImmBinaryOpTest__ShiftRightLogicalAdd_Vector128_Int16_1() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); } public ImmBinaryOpTest__ShiftRightLogicalAdd_Vector128_Int16_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.ShiftRightLogicalAdd( Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.ShiftRightLogicalAdd( AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int16*)(_dataTable.inArray2Ptr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightLogicalAdd), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightLogicalAdd), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int16*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftRightLogicalAdd( _clsVar1, _clsVar2, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int16>* pClsVar1 = &_clsVar1) fixed (Vector128<Int16>* pClsVar2 = &_clsVar2) { var result = AdvSimd.ShiftRightLogicalAdd( AdvSimd.LoadVector128((Int16*)(pClsVar1)), AdvSimd.LoadVector128((Int16*)(pClsVar2)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr); var result = AdvSimd.ShiftRightLogicalAdd(op1, op2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int16*)(_dataTable.inArray2Ptr)); var result = AdvSimd.ShiftRightLogicalAdd(op1, op2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__ShiftRightLogicalAdd_Vector128_Int16_1(); var result = AdvSimd.ShiftRightLogicalAdd(test._fld1, test._fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmBinaryOpTest__ShiftRightLogicalAdd_Vector128_Int16_1(); fixed (Vector128<Int16>* pFld1 = &test._fld1) fixed (Vector128<Int16>* pFld2 = &test._fld2) { var result = AdvSimd.ShiftRightLogicalAdd( AdvSimd.LoadVector128((Int16*)(pFld1)), AdvSimd.LoadVector128((Int16*)(pFld2)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftRightLogicalAdd(_fld1, _fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<Int16>* pFld2 = &_fld2) { var result = AdvSimd.ShiftRightLogicalAdd( AdvSimd.LoadVector128((Int16*)(pFld1)), AdvSimd.LoadVector128((Int16*)(pFld2)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.ShiftRightLogicalAdd(test._fld1, test._fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.ShiftRightLogicalAdd( AdvSimd.LoadVector128((Int16*)(&test._fld1)), AdvSimd.LoadVector128((Int16*)(&test._fld2)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int16> firstOp, Vector128<Int16> secondOp, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), firstOp); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), secondOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* firstOp, void* secondOp, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] firstOp, Int16[] secondOp, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftRightLogicalAdd(firstOp[i], secondOp[i], Imm) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftRightLogicalAdd)}<Int16>(Vector128<Int16>, Vector128<Int16>, 1): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
42.573013
187
0.584621
[ "MIT" ]
06needhamt/runtime
src/coreclr/tests/src/JIT/HardwareIntrinsics/Arm/AdvSimd/ShiftRightLogicalAdd.Vector128.Int16.1.cs
23,032
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("VVD-GH-To-CG")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("VVD-GH-To-CG")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("daeca2c2-2711-4113-b728-c80f57437e8a")] // 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.756757
84
0.740873
[ "MIT" ]
StudioLE/VVD
VVD-GH-To-CG/VVD-GH-To-CG/Properties/AssemblyInfo.cs
1,400
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using NUnit.Framework; using Rebus.Activation; using Rebus.Config; using Rebus.Logging; using Rebus.Messages; using Rebus.Routing.TypeBased; using Rebus.Tests.Contracts; using Rebus.Tests.Contracts.Utilities; using Rebus.Tests.Extensions; using Rebus.Transport.InMem; #pragma warning disable 1998 namespace Rebus.Tests.Integration; [TestFixture] public class TestMessageDeferralAndRequestReply : FixtureBase { BuiltinHandlerActivator _service; BuiltinHandlerActivator _client; Stopwatch _stopwatch; protected override void SetUp() { var inMemNetwork = new InMemNetwork(); _stopwatch = Stopwatch.StartNew(); _service = CreateEndpoint(inMemNetwork, "service"); _client = CreateEndpoint(inMemNetwork, "client"); } BuiltinHandlerActivator CreateEndpoint(InMemNetwork inMemNetwork, string inputQueueName) { var service = Using(new BuiltinHandlerActivator()); Configure.With(service) .Logging(l => l.Console(minLevel: LogLevel.Warn)) .Transport(t => t.UseInMemoryTransport(inMemNetwork, inputQueueName)) .Routing(r => r.TypeBased().Map<string>("service")) .Start(); return service; } [Test] [Description("Defers the message with bus.Defer, which sends the message as a new message (and therefore needs to transfer the ReturnAddress in order to be able to bus.Reply later)")] public async Task DeferringRequestDoesNotBreakAbilityToReply_DeferWithMessageApi() { _service.AddHandlerWithBusTemporarilyStopped<string>(async (bus, context, str) => { const string deferredMessageHeader = "this message was already deferred"; if (!context.TransportMessage.Headers.ContainsKey(deferredMessageHeader)) { var extraHeaders = new Dictionary<string, string> { {deferredMessageHeader, ""}, {Headers.ReturnAddress, context.Headers[Headers.ReturnAddress]} }; Console.WriteLine($"SERVICE deferring '{str}' 1 second (elapsed: {_stopwatch.Elapsed.TotalSeconds:0.# s})"); await bus.Defer(TimeSpan.FromSeconds(1), str, extraHeaders); return; } const string reply = "yeehaa!"; Console.WriteLine($"SERVICE replying '{reply}' (elapsed: {_stopwatch.Elapsed.TotalSeconds:0.# s})"); await bus.Reply(reply); }); await RunDeferTest(); } [Test] [Description("Defers the message with bus.Advanced.TransportMessage.Defer, which defers the original transport message (and thus only needs to include a known header to spot when to bus.Reply)")] public async Task DeferringRequestDoesNotBreakAbilityToReply_DeferWithTransportMessageApi() { _service.AddHandlerWithBusTemporarilyStopped<string>(async (bus, context, str) => { const string deferredMessageHeader = "this message was already deferred"; if (!context.TransportMessage.Headers.ContainsKey(deferredMessageHeader)) { var extraHeaders = new Dictionary<string, string> { {deferredMessageHeader, ""}, }; Console.WriteLine($"SERVICE deferring '{str}' 1 second (elapsed: {_stopwatch.Elapsed.TotalSeconds:0.# s})"); await bus.Advanced.TransportMessage.Defer(TimeSpan.FromSeconds(1), extraHeaders); return; } const string reply = "yeehaa!"; Console.WriteLine($"SERVICE replying '{reply}' (elapsed: {_stopwatch.Elapsed.TotalSeconds:0.# s})"); await bus.Reply(reply); }); await RunDeferTest(); } async Task RunDeferTest() { var replyCounter = new SharedCounter(1); _client.AddHandlerWithBusTemporarilyStopped<string>(async reply => { Console.WriteLine($"CLIENT got reply '{reply}' (elapsed: {_stopwatch.Elapsed.TotalSeconds:0.# s})"); replyCounter.Decrement(); }); await _client.Bus.Send("request"); replyCounter.WaitForResetEvent(); } }
36.016667
199
0.649005
[ "MIT" ]
bog1978/Rebus
Rebus.Tests/Integration/TestMessageDeferralAndRequestReply.cs
4,324
C#