content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.IO; using System.Xml.Serialization; using AElf.CLI.JS; using AElf.CLI.Utils; using ChakraCore.NET; using CommandLine; namespace AElf.CLI.Commands { [Verb("create", HelpText = "Create a new account.")] public class CreateOption : BaseOption { } public class CreateCommand : Command { private readonly CreateOption _option; public CreateCommand(BaseOption option) : base(option) { _option = (CreateOption) option; } private string PromptPassword() { const string prompt0 = "Enter a password: "; const string prompt1 = "Confirm password: "; var p0 = ReadLine.ReadPassword(prompt0); var p1 = ReadLine.ReadPassword(prompt1); while (p1 != p0) { Console.WriteLine("Passwords don't match!"); p1 = ReadLine.ReadPassword(prompt1); } return p0; } public override void Execute() { var obj = _engine.Evaluate("Aelf.wallet.createNewWallet()"); string mnemonic = obj.ReadProperty<string>("mnemonic"); string privKey = obj.ReadProperty<string>("privateKey"); string address = obj.ReadProperty<string>("address"); JSValue keyPair = obj.ReadProperty<JSValue>("keyPair"); string pubKey = keyPair.CallFunction<string, string>("getPublic", "hex"); PrintAccount(address, mnemonic, privKey, pubKey); if (!ReadLine.Read("Saving account info to file? (Y/N): ").Equals("y", StringComparison.OrdinalIgnoreCase)) { return; } var password = PromptPassword(); var accountFile = _option.GetPathForAccount(address); Pem.WriteKeyPair(accountFile, privKey, pubKey, password); } private void PrintAccount(string address, string mnemonic, string privKey, string pubKey) { Console.WriteLine( string.Join( Environment.NewLine, @"Your wallet info is :", $@"Mnemonic : {mnemonic}", $@"Private Key : {privKey}", $@"Public Key : {pubKey}", $@"Address : {address}" ) ); } } }
31.142857
119
0.548374
[ "MIT" ]
Git-zyn-Hub/AElf
AElf.CLI/Commands/CreateCommand.cs
2,398
C#
// // class.cs: Class and Struct handlers // // Authors: Miguel de Icaza (miguel@gnu.org) // Martin Baulig (martin@ximian.com) // Marek Safar (marek.safar@gmail.com) // // Dual licensed under the terms of the MIT X11 or GNU GPL // // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com) // Copyright 2004-2011 Novell, Inc // Copyright 2011 Xamarin, Inc (http://www.xamarin.com) // using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Linq; using System.Text; using System.Diagnostics; using Mono.CompilerServices.SymbolWriter; #if NET_2_1 using XmlElement = System.Object; #endif #if STATIC using SecurityType = System.Collections.Generic.List<IKVM.Reflection.Emit.CustomAttributeBuilder>; using IKVM.Reflection; using IKVM.Reflection.Emit; #else using SecurityType = System.Collections.Generic.Dictionary<System.Security.Permissions.SecurityAction, System.Security.PermissionSet>; using System.Reflection; using System.Reflection.Emit; #endif namespace Mono.CSharp { // // General types container, used as a base class for all constructs which can hold types // public abstract class TypeContainer : MemberCore { public readonly MemberKind Kind; public readonly string Basename; protected List<TypeContainer> containers; TypeDefinition main_container; protected Dictionary<string, MemberCore> defined_names; protected bool is_defined; public TypeContainer (TypeContainer parent, MemberName name, Attributes attrs, MemberKind kind) : base (parent, name, attrs) { this.Kind = kind; if (name != null) this.Basename = name.Basename; defined_names = new Dictionary<string, MemberCore> (); } public override TypeSpec CurrentType { get { return null; } } public TypeDefinition PartialContainer { get { return main_container; } protected set { main_container = value; } } public IList<TypeContainer> Containers { get { return containers; } } #if FULL_AST // // Any unattached attributes during parsing get added here. // public Attributes UnattachedAttributes { get; set; } #endif public virtual void AddCompilerGeneratedClass (CompilerGeneratedContainer c) { containers.Add (c); } public virtual void AddPartial (TypeDefinition next_part) { MemberCore mc; (PartialContainer ?? this).defined_names.TryGetValue (next_part.Basename, out mc); AddPartial (next_part, mc as TypeDefinition); } protected void AddPartial (TypeDefinition next_part, TypeDefinition existing) { next_part.ModFlags |= Modifiers.PARTIAL; if (existing == null) { AddTypeContainer (next_part); return; } if ((existing.ModFlags & Modifiers.PARTIAL) == 0) { if (existing.Kind != next_part.Kind) { AddTypeContainer (next_part); } else { Report.SymbolRelatedToPreviousError (next_part); Error_MissingPartialModifier (existing); } return; } if (existing.Kind != next_part.Kind) { Report.SymbolRelatedToPreviousError (existing); Report.Error (261, next_part.Location, "Partial declarations of `{0}' must be all classes, all structs or all interfaces", next_part.GetSignatureForError ()); } if ((existing.ModFlags & Modifiers.AccessibilityMask) != (next_part.ModFlags & Modifiers.AccessibilityMask) && ((existing.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0 && (next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0)) { Report.SymbolRelatedToPreviousError (existing); Report.Error (262, next_part.Location, "Partial declarations of `{0}' have conflicting accessibility modifiers", next_part.GetSignatureForError ()); } var tc_names = existing.CurrentTypeParameters; if (tc_names != null) { for (int i = 0; i < tc_names.Count; ++i) { var tp = next_part.MemberName.TypeParameters[i]; if (tc_names[i].MemberName.Name != tp.MemberName.Name) { Report.SymbolRelatedToPreviousError (existing.Location, ""); Report.Error (264, next_part.Location, "Partial declarations of `{0}' must have the same type parameter names in the same order", next_part.GetSignatureForError ()); break; } if (tc_names[i].Variance != tp.Variance) { Report.SymbolRelatedToPreviousError (existing.Location, ""); Report.Error (1067, next_part.Location, "Partial declarations of `{0}' must have the same type parameter variance modifiers", next_part.GetSignatureForError ()); break; } } } if ((next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) { existing.ModFlags |= next_part.ModFlags & ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.AccessibilityMask); } else if ((existing.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) { existing.ModFlags &= ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.AccessibilityMask); existing.ModFlags |= next_part.ModFlags; } else { existing.ModFlags |= next_part.ModFlags; } existing.Definition.Modifiers = existing.ModFlags; if (next_part.attributes != null) { if (existing.attributes == null) existing.attributes = next_part.attributes; else existing.attributes.AddAttributes (next_part.attributes.Attrs); } next_part.PartialContainer = existing; if (containers == null) containers = new List<TypeContainer> (); containers.Add (next_part); } public virtual void AddTypeContainer (TypeContainer tc) { containers.Add (tc); var tparams = tc.MemberName.TypeParameters; if (tparams != null && tc.PartialContainer != null) { var td = (TypeDefinition) tc; for (int i = 0; i < tparams.Count; ++i) { var tp = tparams[i]; if (tp.MemberName == null) continue; td.AddNameToContainer (tp, tp.Name); } } } public virtual void CloseContainer () { if (containers != null) { foreach (TypeContainer tc in containers) { tc.CloseContainer (); } } } public virtual void CreateMetadataName (StringBuilder sb) { if (Parent != null && Parent.MemberName != null) Parent.CreateMetadataName (sb); MemberName.CreateMetadataName (sb); } public virtual bool CreateContainer () { if (containers != null) { foreach (TypeContainer tc in containers) { tc.CreateContainer (); } } return true; } public override bool Define () { if (containers != null) { foreach (TypeContainer tc in containers) { tc.Define (); } } // Release cache used by parser only if (Module.Evaluator == null) { defined_names = null; } else { defined_names.Clear (); } return true; } public virtual void PrepareEmit () { if (containers != null) { foreach (var t in containers) { try { t.PrepareEmit (); } catch (Exception e) { if (MemberName == MemberName.Null) throw; throw new InternalErrorException (t, e); } } } } public virtual bool DefineContainer () { if (is_defined) return true; is_defined = true; DoDefineContainer (); if (containers != null) { foreach (TypeContainer tc in containers) { try { tc.DefineContainer (); } catch (Exception e) { if (MemberName == MemberName.Null) throw; throw new InternalErrorException (tc, e); } } } return true; } protected virtual void DefineNamespace () { if (containers != null) { foreach (var tc in containers) { try { tc.DefineNamespace (); } catch (Exception e) { throw new InternalErrorException (tc, e); } } } } protected virtual void DoDefineContainer () { } public virtual void EmitContainer () { if (containers != null) { for (int i = 0; i < containers.Count; ++i) containers[i].EmitContainer (); } } protected void Error_MissingPartialModifier (MemberCore type) { Report.Error (260, type.Location, "Missing partial modifier on declaration of type `{0}'. Another partial declaration of this type exists", type.GetSignatureForError ()); } public override string GetSignatureForDocumentation () { if (Parent != null && Parent.MemberName != null) return Parent.GetSignatureForDocumentation () + "." + MemberName.GetSignatureForDocumentation (); return MemberName.GetSignatureForDocumentation (); } public override string GetSignatureForError () { if (Parent != null && Parent.MemberName != null) return Parent.GetSignatureForError () + "." + MemberName.GetSignatureForError (); return MemberName.GetSignatureForError (); } public virtual void RemoveContainer (TypeContainer cont) { if (containers != null) containers.Remove (cont); defined_names.Remove (cont.Basename); } public virtual void VerifyMembers () { if (containers != null) { foreach (TypeContainer tc in containers) tc.VerifyMembers (); } } public override void WriteDebugSymbol (MonoSymbolFile file) { if (containers != null) { foreach (TypeContainer tc in containers) { tc.WriteDebugSymbol (file); } } } } public abstract class TypeDefinition : TypeContainer, ITypeDefinition { // // Different context is needed when resolving type container base // types. Type names come from the parent scope but type parameter // names from the container scope. // public struct BaseContext : IMemberContext { TypeContainer tc; public BaseContext (TypeContainer tc) { this.tc = tc; } #region IMemberContext Members public CompilerContext Compiler { get { return tc.Compiler; } } public TypeSpec CurrentType { get { return tc.Parent.CurrentType; } } public TypeParameters CurrentTypeParameters { get { return tc.PartialContainer.CurrentTypeParameters; } } public MemberCore CurrentMemberDefinition { get { return tc; } } public bool IsObsolete { get { return tc.IsObsolete; } } public bool IsUnsafe { get { return tc.IsUnsafe; } } public bool IsStatic { get { return tc.IsStatic; } } public ModuleContainer Module { get { return tc.Module; } } public string GetSignatureForError () { return tc.GetSignatureForError (); } public ExtensionMethodCandidates LookupExtensionMethod (TypeSpec extensionType, string name, int arity) { return null; } public FullNamedExpression LookupNamespaceAlias (string name) { return tc.Parent.LookupNamespaceAlias (name); } public FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc) { if (arity == 0) { var tp = CurrentTypeParameters; if (tp != null) { TypeParameter t = tp.Find (name); if (t != null) return new TypeParameterExpr (t, loc); } } return tc.Parent.LookupNamespaceOrType (name, arity, mode, loc); } #endregion } [Flags] enum CachedMethods { Equals = 1, GetHashCode = 1 << 1, HasStaticFieldInitializer = 1 << 2 } readonly List<MemberCore> members; // Holds a list of fields that have initializers protected List<FieldInitializer> initialized_fields; // Holds a list of static fields that have initializers protected List<FieldInitializer> initialized_static_fields; Dictionary<MethodSpec, Method> hoisted_base_call_proxies; Dictionary<string, FullNamedExpression> Cache = new Dictionary<string, FullNamedExpression> (); // // Points to the first non-static field added to the container. // // This is an arbitrary choice. We are interested in looking at _some_ non-static field, // and the first one's as good as any. // protected FieldBase first_nonstatic_field; // // This one is computed after we can distinguish interfaces // from classes from the arraylist `type_bases' // protected TypeSpec base_type; FullNamedExpression base_type_expr; // TODO: It's temporary variable protected TypeSpec[] iface_exprs; protected List<FullNamedExpression> type_bases; TypeDefinition InTransit; public TypeBuilder TypeBuilder; GenericTypeParameterBuilder[] all_tp_builders; // // All recursive type parameters put together sharing same // TypeParameter instances // TypeParameters all_type_parameters; public const string DefaultIndexerName = "Item"; bool has_normal_indexers; string indexer_name; protected bool requires_delayed_unmanagedtype_check; bool error; bool members_defined; bool members_defined_ok; protected bool has_static_constructor; private CachedMethods cached_method; protected TypeSpec spec; TypeSpec current_type; public int DynamicSitesCounter; public int AnonymousMethodsCounter; static readonly string[] attribute_targets = new string[] { "type" }; /// <remarks> /// The pending methods that need to be implemented // (interfaces or abstract methods) /// </remarks> PendingImplementation pending; public TypeDefinition (TypeContainer parent, MemberName name, Attributes attrs, MemberKind kind) : base (parent, name, attrs, kind) { PartialContainer = this; members = new List<MemberCore> (); } #region Properties public List<FullNamedExpression> BaseTypeExpressions { get { return type_bases; } } public override TypeSpec CurrentType { get { if (current_type == null) { if (IsGenericOrParentIsGeneric) { // // Switch to inflated version as it's used by all expressions // var targs = CurrentTypeParameters == null ? TypeSpec.EmptyTypes : CurrentTypeParameters.Types; current_type = spec.MakeGenericType (this, targs); } else { current_type = spec; } } return current_type; } } public override TypeParameters CurrentTypeParameters { get { return PartialContainer.MemberName.TypeParameters; } } int CurrentTypeParametersStartIndex { get { int total = all_tp_builders.Length; if (CurrentTypeParameters != null) { return total - CurrentTypeParameters.Count; } return total; } } public virtual AssemblyDefinition DeclaringAssembly { get { return Module.DeclaringAssembly; } } IAssemblyDefinition ITypeDefinition.DeclaringAssembly { get { return Module.DeclaringAssembly; } } public TypeSpec Definition { get { return spec; } } public bool HasMembersDefined { get { return members_defined; } } public bool HasInstanceConstructor { get { return (caching_flags & Flags.HasInstanceConstructor) != 0; } set { caching_flags |= Flags.HasInstanceConstructor; } } // Indicated whether container has StructLayout attribute set Explicit public bool HasExplicitLayout { get { return (caching_flags & Flags.HasExplicitLayout) != 0; } set { caching_flags |= Flags.HasExplicitLayout; } } public bool HasOperators { get { return (caching_flags & Flags.HasUserOperators) != 0; } set { caching_flags |= Flags.HasUserOperators; } } public bool HasStructLayout { get { return (caching_flags & Flags.HasStructLayout) != 0; } set { caching_flags |= Flags.HasStructLayout; } } public TypeSpec[] Interfaces { get { return iface_exprs; } } public bool IsGenericOrParentIsGeneric { get { return all_type_parameters != null; } } public bool IsTopLevel { get { return !(Parent is TypeDefinition); } } public bool IsPartial { get { return (ModFlags & Modifiers.PARTIAL) != 0; } } // // Returns true for secondary partial containers // bool IsPartialPart { get { return PartialContainer != this; } } public MemberCache MemberCache { get { return spec.MemberCache; } } public List<MemberCore> Members { get { return members; } } string ITypeDefinition.Namespace { get { var p = Parent; while (p.Kind != MemberKind.Namespace) p = p.Parent; return p.MemberName == null ? null : p.GetSignatureForError (); } } public TypeParameters TypeParametersAll { get { return all_type_parameters; } } public override string[] ValidAttributeTargets { get { return attribute_targets; } } #endregion public override void Accept (StructuralVisitor visitor) { visitor.Visit (this); } public void AddMember (MemberCore symbol) { if (symbol.MemberName.ExplicitInterface != null) { if (!(Kind == MemberKind.Class || Kind == MemberKind.Struct)) { Report.Error (541, symbol.Location, "`{0}': explicit interface declaration can only be declared in a class or struct", symbol.GetSignatureForError ()); } } AddNameToContainer (symbol, symbol.MemberName.Basename); members.Add (symbol); } public override void AddTypeContainer (TypeContainer tc) { AddNameToContainer (tc, tc.Basename); if (containers == null) containers = new List<TypeContainer> (); members.Add (tc); base.AddTypeContainer (tc); } public override void AddCompilerGeneratedClass (CompilerGeneratedContainer c) { members.Add (c); if (containers == null) containers = new List<TypeContainer> (); base.AddCompilerGeneratedClass (c); } // // Adds the member to defined_names table. It tests for duplications and enclosing name conflicts // public virtual void AddNameToContainer (MemberCore symbol, string name) { if (((ModFlags | symbol.ModFlags) & Modifiers.COMPILER_GENERATED) != 0) return; MemberCore mc; if (!PartialContainer.defined_names.TryGetValue (name, out mc)) { PartialContainer.defined_names.Add (name, symbol); return; } if (symbol.EnableOverloadChecks (mc)) return; InterfaceMemberBase im = mc as InterfaceMemberBase; if (im != null && im.IsExplicitImpl) return; Report.SymbolRelatedToPreviousError (mc); if ((mc.ModFlags & Modifiers.PARTIAL) != 0 && (symbol is ClassOrStruct || symbol is Interface)) { Error_MissingPartialModifier (symbol); return; } if (symbol is TypeParameter) { Report.Error (692, symbol.Location, "Duplicate type parameter `{0}'", symbol.GetSignatureForError ()); } else { Report.Error (102, symbol.Location, "The type `{0}' already contains a definition for `{1}'", GetSignatureForError (), name); } return; } public void AddConstructor (Constructor c) { AddConstructor (c, false); } public void AddConstructor (Constructor c, bool isDefault) { bool is_static = (c.ModFlags & Modifiers.STATIC) != 0; if (!isDefault) AddNameToContainer (c, is_static ? Constructor.TypeConstructorName : Constructor.ConstructorName); if (is_static && c.ParameterInfo.IsEmpty) { PartialContainer.has_static_constructor = true; } else { PartialContainer.HasInstanceConstructor = true; } members.Add (c); } public bool AddField (FieldBase field) { AddMember (field); if ((field.ModFlags & Modifiers.STATIC) != 0) return true; var first_field = PartialContainer.first_nonstatic_field; if (first_field == null) { PartialContainer.first_nonstatic_field = field; return true; } if (Kind == MemberKind.Struct && first_field.Parent != field.Parent) { Report.SymbolRelatedToPreviousError (first_field.Parent); Report.Warning (282, 3, field.Location, "struct instance field `{0}' found in different declaration from instance field `{1}'", field.GetSignatureForError (), first_field.GetSignatureForError ()); } return true; } /// <summary> /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute /// </summary> public void AddIndexer (Indexer i) { members.Add (i); } public void AddOperator (Operator op) { PartialContainer.HasOperators = true; AddMember (op); } public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa) { if (has_normal_indexers && a.Type == pa.DefaultMember) { Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer"); return; } if (a.Type == pa.Required) { Report.Error (1608, a.Location, "The RequiredAttribute attribute is not permitted on C# types"); return; } TypeBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata); } public override AttributeTargets AttributeTargets { get { throw new NotSupportedException (); } } public TypeSpec BaseType { get { return spec.BaseType; } } protected virtual TypeAttributes TypeAttr { get { return ModifiersExtensions.TypeAttr (ModFlags, IsTopLevel); } } public int TypeParametersCount { get { return MemberName.Arity; } } TypeParameterSpec[] ITypeDefinition.TypeParameters { get { return PartialContainer.CurrentTypeParameters.Types; } } public string GetAttributeDefaultMember () { return indexer_name ?? DefaultIndexerName; } public bool IsComImport { get { if (OptAttributes == null) return false; return OptAttributes.Contains (Module.PredefinedAttributes.ComImport); } } public virtual void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression) { if (IsPartialPart) PartialContainer.RegisterFieldForInitialization (field, expression); if ((field.ModFlags & Modifiers.STATIC) != 0){ if (initialized_static_fields == null) { HasStaticFieldInitializer = true; initialized_static_fields = new List<FieldInitializer> (4); } initialized_static_fields.Add (expression); } else { if (initialized_fields == null) initialized_fields = new List<FieldInitializer> (4); initialized_fields.Add (expression); } } public void ResolveFieldInitializers (BlockContext ec) { Debug.Assert (!IsPartialPart); if (ec.IsStatic) { if (initialized_static_fields == null) return; bool has_complex_initializer = !ec.Module.Compiler.Settings.Optimize; int i; ExpressionStatement [] init = new ExpressionStatement [initialized_static_fields.Count]; for (i = 0; i < initialized_static_fields.Count; ++i) { FieldInitializer fi = initialized_static_fields [i]; ExpressionStatement s = fi.ResolveStatement (ec); if (s == null) { s = EmptyExpressionStatement.Instance; } else if (!fi.IsSideEffectFree) { has_complex_initializer |= true; } init [i] = s; } for (i = 0; i < initialized_static_fields.Count; ++i) { FieldInitializer fi = initialized_static_fields [i]; // // Need special check to not optimize code like this // static int a = b = 5; // static int b = 0; // if (!has_complex_initializer && fi.IsDefaultInitializer) continue; ec.CurrentBlock.AddScopeStatement (new StatementExpression (init [i])); } return; } if (initialized_fields == null) return; for (int i = 0; i < initialized_fields.Count; ++i) { FieldInitializer fi = initialized_fields [i]; ExpressionStatement s = fi.ResolveStatement (ec); if (s == null) continue; // // Field is re-initialized to its default value => removed // if (fi.IsDefaultInitializer && ec.Module.Compiler.Settings.Optimize) continue; ec.CurrentBlock.AddScopeStatement (new StatementExpression (s)); } } public override string DocComment { get { return comment; } set { if (value == null) return; comment += value; } } public PendingImplementation PendingImplementations { get { return pending; } } internal override void GenerateDocComment (DocumentationBuilder builder) { base.GenerateDocComment (builder); foreach (var member in members) member.GenerateDocComment (builder); } public TypeSpec GetAttributeCoClass () { if (OptAttributes == null) return null; Attribute a = OptAttributes.Search (Module.PredefinedAttributes.CoClass); if (a == null) return null; return a.GetCoClassAttributeValue (); } public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa) { Attribute a = null; if (OptAttributes != null) { a = OptAttributes.Search (pa); } if (a == null) return null; return a.GetAttributeUsageAttribute (); } public virtual CompilationSourceFile GetCompilationSourceFile () { TypeContainer ns = Parent; while (true) { var sf = ns as CompilationSourceFile; if (sf != null) return sf; ns = ns.Parent; } } public virtual void AddBasesForPart (List<FullNamedExpression> bases) { type_bases = bases; } /// <summary> /// This function computes the Base class and also the /// list of interfaces that the class or struct @c implements. /// /// The return value is an array (might be null) of /// interfaces implemented (as Types). /// /// The @base_class argument is set to the base object or null /// if this is `System.Object'. /// </summary> protected virtual TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class) { base_class = null; if (type_bases == null) return null; int count = type_bases.Count; TypeSpec[] ifaces = null; var base_context = new BaseContext (this); for (int i = 0, j = 0; i < count; i++){ FullNamedExpression fne = type_bases [i]; var fne_resolved = fne.ResolveAsType (base_context); if (fne_resolved == null) continue; if (i == 0 && Kind == MemberKind.Class && !fne_resolved.IsInterface) { if (fne_resolved.BuiltinType == BuiltinTypeSpec.Type.Dynamic) { Report.Error (1965, Location, "Class `{0}' cannot derive from the dynamic type", GetSignatureForError ()); continue; } base_type = fne_resolved; base_class = fne; continue; } if (ifaces == null) ifaces = new TypeSpec [count - i]; if (fne_resolved.IsInterface) { for (int ii = 0; ii < j; ++ii) { if (fne_resolved == ifaces [ii]) { Report.Error (528, Location, "`{0}' is already listed in interface list", fne_resolved.GetSignatureForError ()); break; } } if (Kind == MemberKind.Interface && !IsAccessibleAs (fne_resolved)) { Report.Error (61, fne.Location, "Inconsistent accessibility: base interface `{0}' is less accessible than interface `{1}'", fne_resolved.GetSignatureForError (), GetSignatureForError ()); } } else { Report.SymbolRelatedToPreviousError (fne_resolved); if (Kind != MemberKind.Class) { Report.Error (527, fne.Location, "Type `{0}' in interface list is not an interface", fne_resolved.GetSignatureForError ()); } else if (base_class != null) Report.Error (1721, fne.Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')", GetSignatureForError (), base_class.GetSignatureForError (), fne_resolved.GetSignatureForError ()); else { Report.Error (1722, fne.Location, "`{0}': Base class `{1}' must be specified as first", GetSignatureForError (), fne_resolved.GetSignatureForError ()); } } ifaces [j++] = fne_resolved; } return ifaces; } // // Checks that some operators come in pairs: // == and != // > and < // >= and <= // true and false // // They are matched based on the return type and the argument types // void CheckPairedOperators () { bool has_equality_or_inequality = false; List<Operator.OpType> found_matched = new List<Operator.OpType> (); for (int i = 0; i < members.Count; ++i) { var o_a = members[i] as Operator; if (o_a == null) continue; var o_type = o_a.OperatorType; if (o_type == Operator.OpType.Equality || o_type == Operator.OpType.Inequality) has_equality_or_inequality = true; if (found_matched.Contains (o_type)) continue; var matching_type = o_a.GetMatchingOperator (); if (matching_type == Operator.OpType.TOP) { continue; } bool pair_found = false; for (int ii = i + 1; ii < members.Count; ++ii) { var o_b = members[ii] as Operator; if (o_b == null || o_b.OperatorType != matching_type) continue; if (!TypeSpecComparer.IsEqual (o_a.ReturnType, o_b.ReturnType)) continue; if (!TypeSpecComparer.Equals (o_a.ParameterTypes, o_b.ParameterTypes)) continue; found_matched.Add (matching_type); pair_found = true; break; } if (!pair_found) { Report.Error (216, o_a.Location, "The operator `{0}' requires a matching operator `{1}' to also be defined", o_a.GetSignatureForError (), Operator.GetName (matching_type)); } } if (has_equality_or_inequality) { if (!HasEquals) Report.Warning (660, 2, Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)", GetSignatureForError ()); if (!HasGetHashCode) Report.Warning (661, 2, Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()", GetSignatureForError ()); } } public override void CreateMetadataName (StringBuilder sb) { if (Parent.MemberName != null) { Parent.CreateMetadataName (sb); if (sb.Length != 0) { sb.Append ("."); } } sb.Append (MemberName.Basename); } bool CreateTypeBuilder () { // // Sets .size to 1 for structs with no instance fields // int type_size = Kind == MemberKind.Struct && first_nonstatic_field == null ? 1 : 0; var parent_def = Parent as TypeDefinition; if (parent_def == null) { var sb = new StringBuilder (); CreateMetadataName (sb); TypeBuilder = Module.CreateBuilder (sb.ToString (), TypeAttr, type_size); } else { TypeBuilder = parent_def.TypeBuilder.DefineNestedType (Basename, TypeAttr, null, type_size); } if (DeclaringAssembly.Importer != null) DeclaringAssembly.Importer.AddCompiledType (TypeBuilder, spec); spec.SetMetaInfo (TypeBuilder); spec.MemberCache = new MemberCache (this); TypeParameters parentAllTypeParameters = null; if (parent_def != null) { spec.DeclaringType = Parent.CurrentType; parent_def.MemberCache.AddMember (spec); parentAllTypeParameters = parent_def.all_type_parameters; } if (MemberName.TypeParameters != null || parentAllTypeParameters != null) { var tparam_names = CreateTypeParameters (parentAllTypeParameters); all_tp_builders = TypeBuilder.DefineGenericParameters (tparam_names); if (CurrentTypeParameters != null) CurrentTypeParameters.Define (all_tp_builders, spec, CurrentTypeParametersStartIndex, this); } return true; } string[] CreateTypeParameters (TypeParameters parentAllTypeParameters) { string[] names; int parent_offset = 0; if (parentAllTypeParameters != null) { if (CurrentTypeParameters == null) { all_type_parameters = parentAllTypeParameters; return parentAllTypeParameters.GetAllNames (); } names = new string[parentAllTypeParameters.Count + CurrentTypeParameters.Count]; all_type_parameters = new TypeParameters (names.Length); all_type_parameters.Add (parentAllTypeParameters); parent_offset = all_type_parameters.Count; for (int i = 0; i < parent_offset; ++i) names[i] = all_type_parameters[i].MemberName.Name; } else { names = new string[CurrentTypeParameters.Count]; } for (int i = 0; i < CurrentTypeParameters.Count; ++i) { if (all_type_parameters != null) all_type_parameters.Add (MemberName.TypeParameters[i]); var name = CurrentTypeParameters[i].MemberName.Name; names[parent_offset + i] = name; for (int ii = 0; ii < parent_offset + i; ++ii) { if (names[ii] != name) continue; var tp = CurrentTypeParameters[i]; var conflict = all_type_parameters[ii]; tp.WarningParentNameConflict (conflict); } } if (all_type_parameters == null) all_type_parameters = CurrentTypeParameters; return names; } public SourceMethodBuilder CreateMethodSymbolEntry () { if (Module.DeclaringAssembly.SymbolWriter == null) return null; var source_file = GetCompilationSourceFile (); if (source_file == null) return null; return new SourceMethodBuilder (source_file.SymbolUnitEntry); } // // Creates a proxy base method call inside this container for hoisted base member calls // public MethodSpec CreateHoistedBaseCallProxy (ResolveContext rc, MethodSpec method) { Method proxy_method; // // One proxy per base method is enough // if (hoisted_base_call_proxies == null) { hoisted_base_call_proxies = new Dictionary<MethodSpec, Method> (); proxy_method = null; } else { hoisted_base_call_proxies.TryGetValue (method, out proxy_method); } if (proxy_method == null) { string name = CompilerGeneratedContainer.MakeName (method.Name, null, "BaseCallProxy", hoisted_base_call_proxies.Count); var base_parameters = new Parameter[method.Parameters.Count]; for (int i = 0; i < base_parameters.Length; ++i) { var base_param = method.Parameters.FixedParameters[i]; base_parameters[i] = new Parameter (new TypeExpression (method.Parameters.Types[i], Location), base_param.Name, base_param.ModFlags, null, Location); base_parameters[i].Resolve (this, i); } var cloned_params = ParametersCompiled.CreateFullyResolved (base_parameters, method.Parameters.Types); if (method.Parameters.HasArglist) { cloned_params.FixedParameters[0] = new Parameter (null, "__arglist", Parameter.Modifier.NONE, null, Location); cloned_params.Types[0] = Module.PredefinedTypes.RuntimeArgumentHandle.Resolve (); } MemberName member_name; TypeArguments targs = null; if (method.IsGeneric) { // // Copy all base generic method type parameters info // var hoisted_tparams = method.GenericDefinition.TypeParameters; var tparams = new TypeParameters (); targs = new TypeArguments (); targs.Arguments = new TypeSpec[hoisted_tparams.Length]; for (int i = 0; i < hoisted_tparams.Length; ++i) { var tp = hoisted_tparams[i]; tparams.Add (new TypeParameter (tp, null, new MemberName (tp.Name, Location), null)); targs.Add (new SimpleName (tp.Name, Location)); targs.Arguments[i] = tp; } member_name = new MemberName (name, tparams, Location); } else { member_name = new MemberName (name); } // Compiler generated proxy proxy_method = new Method (this, new TypeExpression (method.ReturnType, Location), Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED | Modifiers.DEBUGGER_HIDDEN, member_name, cloned_params, null); var block = new ToplevelBlock (Compiler, proxy_method.ParameterInfo, Location) { IsCompilerGenerated = true }; var mg = MethodGroupExpr.CreatePredefined (method, method.DeclaringType, Location); mg.InstanceExpression = new BaseThis (method.DeclaringType, Location); if (targs != null) mg.SetTypeArguments (rc, targs); // Get all the method parameters and pass them as arguments var real_base_call = new Invocation (mg, block.GetAllParametersArguments ()); Statement statement; if (method.ReturnType.Kind == MemberKind.Void) statement = new StatementExpression (real_base_call); else statement = new Return (real_base_call, Location); block.AddStatement (statement); proxy_method.Block = block; members.Add (proxy_method); proxy_method.Define (); hoisted_base_call_proxies.Add (method, proxy_method); } return proxy_method.Spec; } protected bool DefineBaseTypes () { iface_exprs = ResolveBaseTypes (out base_type_expr); bool set_base_type; if (IsPartialPart) { set_base_type = false; if (base_type_expr != null) { if (PartialContainer.base_type_expr != null && PartialContainer.base_type != base_type) { Report.SymbolRelatedToPreviousError (base_type_expr.Location, ""); Report.Error (263, Location, "Partial declarations of `{0}' must not specify different base classes", GetSignatureForError ()); } else { PartialContainer.base_type_expr = base_type_expr; PartialContainer.base_type = base_type; set_base_type = true; } } if (iface_exprs != null) { if (PartialContainer.iface_exprs == null) PartialContainer.iface_exprs = iface_exprs; else { var ifaces = new List<TypeSpec> (PartialContainer.iface_exprs); foreach (var iface_partial in iface_exprs) { if (ifaces.Contains (iface_partial)) continue; ifaces.Add (iface_partial); } PartialContainer.iface_exprs = ifaces.ToArray (); } } PartialContainer.members.AddRange (members); if (containers != null) { if (PartialContainer.containers == null) PartialContainer.containers = new List<TypeContainer> (); PartialContainer.containers.AddRange (containers); } members_defined = members_defined_ok = true; caching_flags |= Flags.CloseTypeCreated; } else { set_base_type = true; } var cycle = CheckRecursiveDefinition (this); if (cycle != null) { Report.SymbolRelatedToPreviousError (cycle); if (this is Interface) { Report.Error (529, Location, "Inherited interface `{0}' causes a cycle in the interface hierarchy of `{1}'", GetSignatureForError (), cycle.GetSignatureForError ()); iface_exprs = null; } else { Report.Error (146, Location, "Circular base class dependency involving `{0}' and `{1}'", GetSignatureForError (), cycle.GetSignatureForError ()); base_type = null; } } if (iface_exprs != null) { foreach (var iface_type in iface_exprs) { // Prevents a crash, the interface might not have been resolved: 442144 if (iface_type == null) continue; if (!spec.AddInterfaceDefined (iface_type)) continue; TypeBuilder.AddInterfaceImplementation (iface_type.GetMetaInfo ()); // Ensure the base is always setup var compiled_iface = iface_type.MemberDefinition as Interface; if (compiled_iface != null) { // TODO: Need DefineBaseType only compiled_iface.DefineContainer (); } if (iface_type.Interfaces != null) { var base_ifaces = new List<TypeSpec> (iface_type.Interfaces); for (int i = 0; i < base_ifaces.Count; ++i) { var ii_iface_type = base_ifaces[i]; if (spec.AddInterfaceDefined (ii_iface_type)) { TypeBuilder.AddInterfaceImplementation (ii_iface_type.GetMetaInfo ()); if (ii_iface_type.Interfaces != null) base_ifaces.AddRange (ii_iface_type.Interfaces); } } } } } if (Kind == MemberKind.Interface) { spec.BaseType = Compiler.BuiltinTypes.Object; return true; } if (set_base_type) { if (base_type != null) { spec.BaseType = base_type; // Set base type after type creation TypeBuilder.SetParent (base_type.GetMetaInfo ()); } else { TypeBuilder.SetParent (null); } } return true; } public override void PrepareEmit () { if ((caching_flags & Flags.CloseTypeCreated) != 0) return; foreach (var member in members) { var pm = member as IParametersMember; if (pm != null) { var p = pm.Parameters; if (p.IsEmpty) continue; ((ParametersCompiled) p).ResolveDefaultValues (member); } var c = member as Const; if (c != null) c.DefineValue (); } base.PrepareEmit (); } // // Defines the type in the appropriate ModuleBuilder or TypeBuilder. // public override bool CreateContainer () { if (TypeBuilder != null) return !error; if (error) return false; if (IsPartialPart) { spec = PartialContainer.spec; TypeBuilder = PartialContainer.TypeBuilder; all_tp_builders = PartialContainer.all_tp_builders; all_type_parameters = PartialContainer.all_type_parameters; } else { if (!CreateTypeBuilder ()) { error = true; return false; } } return base.CreateContainer (); } protected override void DoDefineContainer () { DefineBaseTypes (); DoResolveTypeParameters (); } // // Replaces normal spec with predefined one when compiling corlib // and this type container defines predefined type // public void SetPredefinedSpec (BuiltinTypeSpec spec) { // When compiling build-in types we start with two // version of same type. One is of BuiltinTypeSpec and // second one is ordinary TypeSpec. The unification // happens at later stage when we know which type // really matches the builtin type signature. However // that means TypeSpec create during CreateType of this // type has to be replaced with builtin one // spec.SetMetaInfo (TypeBuilder); spec.MemberCache = this.spec.MemberCache; spec.DeclaringType = this.spec.DeclaringType; this.spec = spec; current_type = null; } void UpdateTypeParameterConstraints (TypeDefinition part) { for (int i = 0; i < CurrentTypeParameters.Count; i++) { if (CurrentTypeParameters[i].AddPartialConstraints (part, part.MemberName.TypeParameters[i])) continue; Report.SymbolRelatedToPreviousError (Location, ""); Report.Error (265, part.Location, "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'", GetSignatureForError (), CurrentTypeParameters[i].GetSignatureForError ()); } } public override void RemoveContainer (TypeContainer cont) { base.RemoveContainer (cont); Members.Remove (cont); Cache.Remove (cont.Basename); } protected virtual bool DoResolveTypeParameters () { var tparams = CurrentTypeParameters; if (tparams == null) return true; var base_context = new BaseContext (this); for (int i = 0; i < tparams.Count; ++i) { var tp = tparams[i]; if (!tp.ResolveConstraints (base_context)) { error = true; return false; } } if (IsPartialPart) { PartialContainer.UpdateTypeParameterConstraints (this); } return true; } TypeSpec CheckRecursiveDefinition (TypeDefinition tc) { if (InTransit != null) return spec; InTransit = tc; if (base_type != null) { var ptc = base_type.MemberDefinition as TypeDefinition; if (ptc != null && ptc.CheckRecursiveDefinition (this) != null) return base_type; } if (iface_exprs != null) { foreach (var iface in iface_exprs) { // the interface might not have been resolved, prevents a crash, see #442144 if (iface == null) continue; var ptc = iface.MemberDefinition as Interface; if (ptc != null && ptc.CheckRecursiveDefinition (this) != null) return iface; } } if (!IsTopLevel && Parent.PartialContainer.CheckRecursiveDefinition (this) != null) return spec; InTransit = null; return null; } /// <summary> /// Populates our TypeBuilder with fields and methods /// </summary> public sealed override bool Define () { if (members_defined) return members_defined_ok; members_defined_ok = DoDefineMembers (); members_defined = true; base.Define (); return members_defined_ok; } protected virtual bool DoDefineMembers () { Debug.Assert (!IsPartialPart); if (iface_exprs != null) { foreach (var iface_type in iface_exprs) { if (iface_type == null) continue; // Ensure the base is always setup var compiled_iface = iface_type.MemberDefinition as Interface; if (compiled_iface != null) compiled_iface.Define (); if (Kind == MemberKind.Interface) MemberCache.AddInterface (iface_type); ObsoleteAttribute oa = iface_type.GetAttributeObsolete (); if (oa != null && !IsObsolete) AttributeTester.Report_ObsoleteMessage (oa, iface_type.GetSignatureForError (), Location, Report); if (iface_type.Arity > 0) { // TODO: passing `this' is wrong, should be base type iface instead TypeManager.CheckTypeVariance (iface_type, Variance.Covariant, this); if (((InflatedTypeSpec) iface_type).HasDynamicArgument () && !IsCompilerGenerated) { Report.Error (1966, Location, "`{0}': cannot implement a dynamic interface `{1}'", GetSignatureForError (), iface_type.GetSignatureForError ()); return false; } } if (iface_type.IsGenericOrParentIsGeneric) { if (spec.Interfaces != null) { foreach (var prev_iface in iface_exprs) { if (prev_iface == iface_type) break; if (!TypeSpecComparer.Unify.IsEqual (iface_type, prev_iface)) continue; Report.Error (695, Location, "`{0}' cannot implement both `{1}' and `{2}' because they may unify for some type parameter substitutions", GetSignatureForError (), prev_iface.GetSignatureForError (), iface_type.GetSignatureForError ()); } } } } } if (base_type != null) { // // Run checks skipped during DefineType (e.g FullNamedExpression::ResolveAsType) // if (base_type_expr != null) { ObsoleteAttribute obsolete_attr = base_type.GetAttributeObsolete (); if (obsolete_attr != null && !IsObsolete) AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), base_type_expr.Location, Report); if (IsGenericOrParentIsGeneric && base_type.IsAttribute) { Report.Error (698, base_type_expr.Location, "A generic type cannot derive from `{0}' because it is an attribute class", base_type.GetSignatureForError ()); } } if (base_type.Interfaces != null) { foreach (var iface in base_type.Interfaces) spec.AddInterface (iface); } var baseContainer = base_type.MemberDefinition as ClassOrStruct; if (baseContainer != null) { baseContainer.Define (); // // It can trigger define of this type (for generic types only) // if (HasMembersDefined) return true; } } if (Kind == MemberKind.Struct || Kind == MemberKind.Class) { pending = PendingImplementation.GetPendingImplementations (this); } var count = members.Count; for (int i = 0; i < count; ++i) { var mc = members[i] as InterfaceMemberBase; if (mc == null || !mc.IsExplicitImpl) continue; try { mc.Define (); } catch (Exception e) { throw new InternalErrorException (mc, e); } } for (int i = 0; i < count; ++i) { var mc = members[i] as InterfaceMemberBase; if (mc != null && mc.IsExplicitImpl) continue; if (members[i] is TypeContainer) continue; try { members[i].Define (); } catch (Exception e) { throw new InternalErrorException (members[i], e); } } if (HasOperators) { CheckPairedOperators (); } if (requires_delayed_unmanagedtype_check) { requires_delayed_unmanagedtype_check = false; foreach (var member in members) { var f = member as Field; if (f != null && f.MemberType != null && f.MemberType.IsPointer) TypeManager.VerifyUnmanaged (Module, f.MemberType, f.Location); } } ComputeIndexerName(); if (HasEquals && !HasGetHashCode) { Report.Warning (659, 3, Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", GetSignatureForError ()); } if (Kind == MemberKind.Interface && iface_exprs != null) { MemberCache.RemoveHiddenMembers (spec); } return true; } void ComputeIndexerName () { var indexers = MemberCache.FindMembers (spec, MemberCache.IndexerNameAlias, true); if (indexers == null) return; string class_indexer_name = null; has_normal_indexers = true; // // Check normal indexers for consistent name, explicit interface implementation // indexers are ignored // foreach (var indexer in indexers) { if (class_indexer_name == null) { indexer_name = class_indexer_name = indexer.Name; continue; } if (indexer.Name != class_indexer_name) Report.Error (668, ((Indexer)indexer.MemberDefinition).Location, "Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type"); } } void EmitIndexerName () { if (!has_normal_indexers) return; var ctor = Module.PredefinedMembers.DefaultMemberAttributeCtor.Get (); if (ctor == null) return; var encoder = new AttributeEncoder (); encoder.Encode (GetAttributeDefaultMember ()); encoder.EncodeEmptyNamedArguments (); TypeBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ()); } public override void VerifyMembers () { // // Check for internal or private fields that were never assigned // if (!IsCompilerGenerated && Compiler.Settings.WarningLevel >= 3 && this == PartialContainer) { bool is_type_exposed = Kind == MemberKind.Struct || IsExposedFromAssembly (); foreach (var member in members) { if (member is Event) { // // An event can be assigned from same class only, so we can report // this warning for all accessibility modes // if (!member.IsUsed) Report.Warning (67, 3, member.Location, "The event `{0}' is never used", member.GetSignatureForError ()); continue; } if ((member.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE) { if (is_type_exposed) continue; member.SetIsUsed (); } var f = member as Field; if (f == null) continue; if (!member.IsUsed) { if ((member.caching_flags & Flags.IsAssigned) == 0) { Report.Warning (169, 3, member.Location, "The private field `{0}' is never used", member.GetSignatureForError ()); } else { Report.Warning (414, 3, member.Location, "The private field `{0}' is assigned but its value is never used", member.GetSignatureForError ()); } continue; } if ((f.caching_flags & Flags.IsAssigned) != 0) continue; // // Only report 649 on level 4 // if (Compiler.Settings.WarningLevel < 4) continue; // // Don't be pendatic over serializable attributes // if (f.OptAttributes != null || PartialContainer.HasStructLayout) continue; Constant c = New.Constantify (f.MemberType, f.Location); string value; if (c != null) { value = c.GetValueAsLiteral (); } else if (TypeSpec.IsReferenceType (f.MemberType)) { value = "null"; } else { // Ignore this warning for struct value fields (they are always initialized) if (f.MemberType.IsStruct) continue; value = null; } if (value != null) value = " `" + value + "'"; Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value{1}", f.GetSignatureForError (), value); } } base.VerifyMembers (); } public override void Emit () { if (OptAttributes != null) OptAttributes.Emit (); if (!IsCompilerGenerated) { if (!IsTopLevel) { MemberSpec candidate; bool overrides = false; var conflict_symbol = MemberCache.FindBaseMember (this, out candidate, ref overrides); if (conflict_symbol == null && candidate == null) { if ((ModFlags & Modifiers.NEW) != 0) Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ()); } else { if ((ModFlags & Modifiers.NEW) == 0) { if (candidate == null) candidate = conflict_symbol; Report.SymbolRelatedToPreviousError (candidate); Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended", GetSignatureForError (), candidate.GetSignatureForError ()); } } } // Run constraints check on all possible generic types if (base_type != null && base_type_expr != null) { ConstraintChecker.Check (this, base_type, base_type_expr.Location); } if (iface_exprs != null) { foreach (var iface_type in iface_exprs) { if (iface_type == null) continue; ConstraintChecker.Check (this, iface_type, Location); // TODO: Location is wrong } } } if (all_tp_builders != null) { int current_starts_index = CurrentTypeParametersStartIndex; for (int i = 0; i < all_tp_builders.Length; i++) { if (i < current_starts_index) { all_type_parameters[i].EmitConstraints (all_tp_builders [i]); } else { var tp = CurrentTypeParameters [i - current_starts_index]; tp.CheckGenericConstraints (!IsObsolete); tp.Emit (); } } } if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated) Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (TypeBuilder); #if STATIC if ((TypeBuilder.Attributes & TypeAttributes.StringFormatMask) == 0 && Module.HasDefaultCharSet) TypeBuilder.__SetAttributes (TypeBuilder.Attributes | Module.DefaultCharSetType); #endif base.Emit (); for (int i = 0; i < members.Count; i++) members[i].Emit (); EmitIndexerName (); CheckAttributeClsCompliance (); if (pending != null) pending.VerifyPendingMethods (); } void CheckAttributeClsCompliance () { if (!spec.IsAttribute || !IsExposedFromAssembly () || !Compiler.Settings.VerifyClsCompliance || !IsClsComplianceRequired ()) return; foreach (var m in members) { var c = m as Constructor; if (c == null) continue; if (c.HasCompliantArgs) return; } Report.Warning (3015, 1, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ()); } public sealed override void EmitContainer () { if ((caching_flags & Flags.CloseTypeCreated) != 0) return; Emit (); } public override void CloseContainer () { if ((caching_flags & Flags.CloseTypeCreated) != 0) return; // Close base type container first to avoid TypeLoadException if (spec.BaseType != null) { var btype = spec.BaseType.MemberDefinition as TypeContainer; if (btype != null) { btype.CloseContainer (); if ((caching_flags & Flags.CloseTypeCreated) != 0) return; } } try { caching_flags |= Flags.CloseTypeCreated; TypeBuilder.CreateType (); } catch (TypeLoadException) { // // This is fine, the code still created the type // } catch (Exception e) { throw new InternalErrorException (this, e); } base.CloseContainer (); containers = null; initialized_fields = null; initialized_static_fields = null; type_bases = null; OptAttributes = null; } // // Performs the validation on a Method's modifiers (properties have // the same properties). // // TODO: Why is it not done at parse stage, move to Modifiers::Check // public bool MethodModifiersValid (MemberCore mc) { const Modifiers vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE); const Modifiers nv = (Modifiers.NEW | Modifiers.VIRTUAL); bool ok = true; var flags = mc.ModFlags; // // At most one of static, virtual or override // if ((flags & Modifiers.STATIC) != 0){ if ((flags & vao) != 0){ Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract", mc.GetSignatureForError ()); ok = false; } } if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){ Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual", mc.GetSignatureForError ()); ok = false; } // // If the declaration includes the abstract modifier, then the // declaration does not include static, virtual or extern // if ((flags & Modifiers.ABSTRACT) != 0){ if ((flags & Modifiers.EXTERN) != 0){ Report.Error ( 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ()); ok = false; } if ((flags & Modifiers.SEALED) != 0) { Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ()); ok = false; } if ((flags & Modifiers.VIRTUAL) != 0){ Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ()); ok = false; } if ((ModFlags & Modifiers.ABSTRACT) == 0){ Report.SymbolRelatedToPreviousError (this); Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'", mc.GetSignatureForError (), GetSignatureForError ()); ok = false; } } if ((flags & Modifiers.PRIVATE) != 0){ if ((flags & vao) != 0){ Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ()); ok = false; } } if ((flags & Modifiers.SEALED) != 0){ if ((flags & Modifiers.OVERRIDE) == 0){ Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ()); ok = false; } } return ok; } protected override bool VerifyClsCompliance () { if (!base.VerifyClsCompliance ()) return false; // Check all container names for user classes if (Kind != MemberKind.Delegate) MemberCache.VerifyClsCompliance (Definition, Report); if (BaseType != null && !BaseType.IsCLSCompliant ()) { Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), BaseType.GetSignatureForError ()); } return true; } /// <summary> /// Performs checks for an explicit interface implementation. First it /// checks whether the `interface_type' is a base inteface implementation. /// Then it checks whether `name' exists in the interface type. /// </summary> public bool VerifyImplements (InterfaceMemberBase mb) { var ifaces = spec.Interfaces; if (ifaces != null) { foreach (TypeSpec t in ifaces){ if (t == mb.InterfaceType) return true; } } Report.SymbolRelatedToPreviousError (mb.InterfaceType); Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'", mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType)); return false; } // // Used for visiblity checks to tests whether this definition shares // base type baseType, it does member-definition search // public bool IsBaseTypeDefinition (TypeSpec baseType) { // RootContext check if (TypeBuilder == null) return false; var type = spec; do { if (type.MemberDefinition == baseType.MemberDefinition) return true; type = type.BaseType; } while (type != null); return false; } public override bool IsClsComplianceRequired () { if (IsPartialPart) return PartialContainer.IsClsComplianceRequired (); return base.IsClsComplianceRequired (); } bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly) { return Module.DeclaringAssembly == assembly; } public virtual bool IsUnmanagedType () { return false; } public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache) { throw new NotSupportedException ("Not supported for compiled definition " + GetSignatureForError ()); } // // Public function used to locate types. // // Set 'ignore_cs0104' to true if you want to ignore cs0104 errors. // // Returns: Type or null if they type can not be found. // public override FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc) { FullNamedExpression e; if (arity == 0 && Cache.TryGetValue (name, out e) && mode != LookupMode.IgnoreAccessibility) return e; e = null; if (arity == 0) { var tp = CurrentTypeParameters; if (tp != null) { TypeParameter tparam = tp.Find (name); if (tparam != null) e = new TypeParameterExpr (tparam, Location.Null); } } if (e == null) { TypeSpec t = LookupNestedTypeInHierarchy (name, arity); if (t != null && (t.IsAccessible (this) || mode == LookupMode.IgnoreAccessibility)) e = new TypeExpression (t, Location.Null); else { e = Parent.LookupNamespaceOrType (name, arity, mode, loc); } } // TODO MemberCache: How to cache arity stuff ? if (arity == 0 && mode == LookupMode.Normal) Cache[name] = e; return e; } TypeSpec LookupNestedTypeInHierarchy (string name, int arity) { // Has any nested type // Does not work, because base type can have //if (PartialContainer.Types == null) // return null; var container = PartialContainer.CurrentType; return MemberCache.FindNestedType (container, name, arity); } public void Mark_HasEquals () { cached_method |= CachedMethods.Equals; } public void Mark_HasGetHashCode () { cached_method |= CachedMethods.GetHashCode; } public override void WriteDebugSymbol (MonoSymbolFile file) { if (IsPartialPart) return; foreach (var m in members) { m.WriteDebugSymbol (file); } } /// <summary> /// Method container contains Equals method /// </summary> public bool HasEquals { get { return (cached_method & CachedMethods.Equals) != 0; } } /// <summary> /// Method container contains GetHashCode method /// </summary> public bool HasGetHashCode { get { return (cached_method & CachedMethods.GetHashCode) != 0; } } public bool HasStaticFieldInitializer { get { return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0; } set { if (value) cached_method |= CachedMethods.HasStaticFieldInitializer; else cached_method &= ~CachedMethods.HasStaticFieldInitializer; } } public override string DocCommentHeader { get { return "T:"; } } } public abstract class ClassOrStruct : TypeDefinition { public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed; SecurityType declarative_security; public ClassOrStruct (TypeContainer parent, MemberName name, Attributes attrs, MemberKind kind) : base (parent, name, attrs, kind) { } protected override TypeAttributes TypeAttr { get { TypeAttributes ta = base.TypeAttr; if (!has_static_constructor) ta |= TypeAttributes.BeforeFieldInit; if (Kind == MemberKind.Class) { ta |= TypeAttributes.AutoLayout | TypeAttributes.Class; if (IsStatic) ta |= StaticClassAttribute; } else { ta |= TypeAttributes.SequentialLayout; } return ta; } } public override void AddNameToContainer (MemberCore symbol, string name) { if (!(symbol is Constructor) && symbol.MemberName.Name == MemberName.Name) { if (symbol is TypeParameter) { Report.Error (694, symbol.Location, "Type parameter `{0}' has same name as containing type, or method", symbol.GetSignatureForError ()); return; } InterfaceMemberBase imb = symbol as InterfaceMemberBase; if (imb == null || !imb.IsExplicitImpl) { Report.SymbolRelatedToPreviousError (this); Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type", symbol.GetSignatureForError ()); return; } } base.AddNameToContainer (symbol, name); } public override void VerifyMembers () { base.VerifyMembers (); if (containers != null) { foreach (var t in containers) t.VerifyMembers (); } } public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa) { if (a.IsValidSecurityAttribute ()) { a.ExtractSecurityPermissionSet (ctor, ref declarative_security); return; } if (a.Type == pa.StructLayout) { PartialContainer.HasStructLayout = true; if (a.IsExplicitLayoutKind ()) PartialContainer.HasExplicitLayout = true; } if (a.Type == pa.Dynamic) { a.Error_MisusedDynamicAttribute (); return; } base.ApplyAttributeBuilder (a, ctor, cdata, pa); } /// <summary> /// Defines the default constructors /// </summary> protected Constructor DefineDefaultConstructor (bool is_static) { // The default instance constructor is public // If the class is abstract, the default constructor is protected // The default static constructor is private Modifiers mods; if (is_static) { mods = Modifiers.STATIC | Modifiers.PRIVATE; } else { mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC; } var c = new Constructor (this, MemberName.Name, mods, null, ParametersCompiled.EmptyReadOnlyParameters, Location); c.Initializer = new GeneratedBaseInitializer (Location); AddConstructor (c, true); c.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location) { IsCompilerGenerated = true }; return c; } protected override bool DoDefineMembers () { CheckProtectedModifier (); base.DoDefineMembers (); return true; } public override void Emit () { if (!has_static_constructor && HasStaticFieldInitializer) { var c = DefineDefaultConstructor (true); c.Define (); } base.Emit (); if (declarative_security != null) { foreach (var de in declarative_security) { #if STATIC TypeBuilder.__AddDeclarativeSecurity (de); #else TypeBuilder.AddDeclarativeSecurity (de.Key, de.Value); #endif } } } } public sealed class Class : ClassOrStruct { const Modifiers AllowedModifiers = Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE | Modifiers.ABSTRACT | Modifiers.SEALED | Modifiers.STATIC | Modifiers.UNSAFE; public Class (TypeContainer parent, MemberName name, Modifiers mod, Attributes attrs) : base (parent, name, attrs, MemberKind.Class) { var accmods = IsTopLevel ? Modifiers.INTERNAL : Modifiers.PRIVATE; this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report); spec = new TypeSpec (Kind, null, this, null, ModFlags); } public override void Accept (StructuralVisitor visitor) { visitor.Visit (this); } public override void AddBasesForPart (List<FullNamedExpression> bases) { var pmn = MemberName; if (pmn.Name == "Object" && !pmn.IsGeneric && Parent.MemberName.Name == "System" && Parent.MemberName.Left == null) Report.Error (537, Location, "The class System.Object cannot have a base class or implement an interface."); base.AddBasesForPart (bases); } public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa) { if (a.Type == pa.AttributeUsage) { if (!BaseType.IsAttribute && spec.BuiltinType != BuiltinTypeSpec.Type.Attribute) { Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ()); } } if (a.Type == pa.Conditional && !BaseType.IsAttribute) { Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes"); return; } if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) { a.Error_MissingGuidAttribute (); return; } if (a.Type == pa.Extension) { a.Error_MisusedExtensionAttribute (); return; } if (a.Type.IsConditionallyExcluded (this, Location)) return; base.ApplyAttributeBuilder (a, ctor, cdata, pa); } public override AttributeTargets AttributeTargets { get { return AttributeTargets.Class; } } protected override bool DoDefineMembers () { if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) { Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ()); } if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) { Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ()); } if (IsStatic) { foreach (var m in Members) { if (m is Operator) { Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ()); continue; } if (m is Destructor) { Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ()); continue; } if (m is Indexer) { Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ()); continue; } if ((m.ModFlags & Modifiers.STATIC) != 0 || m is TypeContainer) continue; if (m is Constructor) { Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ()); continue; } Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ()); } } else { if (!PartialContainer.HasInstanceConstructor) DefineDefaultConstructor (false); } return base.DoDefineMembers (); } public override void Emit () { base.Emit (); if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0) Module.PredefinedAttributes.Extension.EmitAttribute (TypeBuilder); if (base_type != null && base_type.HasDynamicElement) { Module.PredefinedAttributes.Dynamic.EmitAttribute (TypeBuilder, base_type, Location); } } protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class) { var ifaces = base.ResolveBaseTypes (out base_class); if (base_class == null) { if (spec.BuiltinType != BuiltinTypeSpec.Type.Object) base_type = Compiler.BuiltinTypes.Object; } else { if (base_type.IsGenericParameter){ Report.Error (689, base_class.Location, "`{0}': Cannot derive from type parameter `{1}'", GetSignatureForError (), base_type.GetSignatureForError ()); } else if (base_type.IsStatic) { Report.SymbolRelatedToPreviousError (base_type); Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'", GetSignatureForError (), base_type.GetSignatureForError ()); } else if (base_type.IsSealed) { Report.SymbolRelatedToPreviousError (base_type); Report.Error (509, Location, "`{0}': cannot derive from sealed type `{1}'", GetSignatureForError (), base_type.GetSignatureForError ()); } else if (PartialContainer.IsStatic && base_type.BuiltinType != BuiltinTypeSpec.Type.Object) { Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object", GetSignatureForError (), base_type.GetSignatureForError ()); } switch (base_type.BuiltinType) { case BuiltinTypeSpec.Type.Enum: case BuiltinTypeSpec.Type.ValueType: case BuiltinTypeSpec.Type.MulticastDelegate: case BuiltinTypeSpec.Type.Delegate: case BuiltinTypeSpec.Type.Array: if (!(spec is BuiltinTypeSpec)) { Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'", GetSignatureForError (), base_type.GetSignatureForError ()); base_type = Compiler.BuiltinTypes.Object; } break; } if (!IsAccessibleAs (base_type)) { Report.SymbolRelatedToPreviousError (base_type); Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'", base_type.GetSignatureForError (), GetSignatureForError ()); } } if (PartialContainer.IsStatic && ifaces != null) { foreach (var t in ifaces) Report.SymbolRelatedToPreviousError (t); Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ()); } return ifaces; } /// Search for at least one defined condition in ConditionalAttribute of attribute class /// Valid only for attribute classes. public override string[] ConditionalConditions () { if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0) return null; caching_flags &= ~Flags.Excluded_Undetected; if (OptAttributes == null) return null; Attribute[] attrs = OptAttributes.SearchMulti (Module.PredefinedAttributes.Conditional); if (attrs == null) return null; string[] conditions = new string[attrs.Length]; for (int i = 0; i < conditions.Length; ++i) conditions[i] = attrs[i].GetConditionalAttributeValue (); caching_flags |= Flags.Excluded; return conditions; } } public sealed class Struct : ClassOrStruct { bool is_unmanaged, has_unmanaged_check_done; bool InTransit; // <summary> // Modifiers allowed in a struct declaration // </summary> const Modifiers AllowedModifiers = Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.UNSAFE | Modifiers.PRIVATE; public Struct (TypeContainer parent, MemberName name, Modifiers mod, Attributes attrs) : base (parent, name, attrs, MemberKind.Struct) { var accmods = IsTopLevel ? Modifiers.INTERNAL : Modifiers.PRIVATE; this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report) | Modifiers.SEALED ; spec = new TypeSpec (Kind, null, this, null, ModFlags); } public override AttributeTargets AttributeTargets { get { return AttributeTargets.Struct; } } public override void Accept (StructuralVisitor visitor) { visitor.Visit (this); } public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa) { base.ApplyAttributeBuilder (a, ctor, cdata, pa); // // When struct constains fixed fixed and struct layout has explicitly // set CharSet, its value has to be propagated to compiler generated // fixed types // if (a.Type == pa.StructLayout) { var value = a.GetNamedValue ("CharSet"); if (value == null) return; for (int i = 0; i < Members.Count; ++i) { FixedField ff = Members [i] as FixedField; if (ff == null) continue; ff.CharSet = (CharSet) System.Enum.Parse (typeof (CharSet), value.GetValue ().ToString ()); } } } bool CheckStructCycles () { if (InTransit) return false; InTransit = true; foreach (var member in Members) { var field = member as Field; if (field == null) continue; TypeSpec ftype = field.Spec.MemberType; if (!ftype.IsStruct) continue; if (ftype is BuiltinTypeSpec) continue; foreach (var targ in ftype.TypeArguments) { if (!CheckFieldTypeCycle (targ)) { Report.Error (523, field.Location, "Struct member `{0}' of type `{1}' causes a cycle in the struct layout", field.GetSignatureForError (), ftype.GetSignatureForError ()); break; } } // // Static fields of exactly same type are allowed // if (field.IsStatic && ftype == CurrentType) continue; if (!CheckFieldTypeCycle (ftype)) { Report.Error (523, field.Location, "Struct member `{0}' of type `{1}' causes a cycle in the struct layout", field.GetSignatureForError (), ftype.GetSignatureForError ()); break; } } InTransit = false; return true; } static bool CheckFieldTypeCycle (TypeSpec ts) { var fts = ts.MemberDefinition as Struct; if (fts == null) return true; return fts.CheckStructCycles (); } public override void Emit () { CheckStructCycles (); base.Emit (); } public override bool IsUnmanagedType () { if (has_unmanaged_check_done) return is_unmanaged; if (requires_delayed_unmanagedtype_check) return true; var parent_def = Parent.PartialContainer; if (parent_def != null && parent_def.IsGenericOrParentIsGeneric) { has_unmanaged_check_done = true; return false; } if (first_nonstatic_field != null) { requires_delayed_unmanagedtype_check = true; foreach (var member in Members) { var f = member as Field; if (f == null) continue; if (f.IsStatic) continue; // It can happen when recursive unmanaged types are defined // struct S { S* s; } TypeSpec mt = f.MemberType; if (mt == null) { return true; } if (mt.IsUnmanaged) continue; has_unmanaged_check_done = true; return false; } has_unmanaged_check_done = true; } is_unmanaged = true; return true; } protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class) { var ifaces = base.ResolveBaseTypes (out base_class); base_type = Compiler.BuiltinTypes.ValueType; return ifaces; } public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression) { if ((field.ModFlags & Modifiers.STATIC) == 0) { Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers", field.GetSignatureForError ()); return; } base.RegisterFieldForInitialization (field, expression); } } /// <summary> /// Interfaces /// </summary> public sealed class Interface : TypeDefinition { /// <summary> /// Modifiers allowed in a class declaration /// </summary> const Modifiers AllowedModifiers = Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.UNSAFE | Modifiers.PRIVATE; public Interface (TypeContainer parent, MemberName name, Modifiers mod, Attributes attrs) : base (parent, name, attrs, MemberKind.Interface) { var accmods = IsTopLevel ? Modifiers.INTERNAL : Modifiers.PRIVATE; this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, name.Location, Report); spec = new TypeSpec (Kind, null, this, null, ModFlags); } #region Properties public override AttributeTargets AttributeTargets { get { return AttributeTargets.Interface; } } protected override TypeAttributes TypeAttr { get { const TypeAttributes DefaultTypeAttributes = TypeAttributes.AutoLayout | TypeAttributes.Abstract | TypeAttributes.Interface; return base.TypeAttr | DefaultTypeAttributes; } } #endregion public override void Accept (StructuralVisitor visitor) { visitor.Visit (this); } public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa) { if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) { a.Error_MissingGuidAttribute (); return; } base.ApplyAttributeBuilder (a, ctor, cdata, pa); } protected override bool VerifyClsCompliance () { if (!base.VerifyClsCompliance ()) return false; if (iface_exprs != null) { foreach (var iface in iface_exprs) { if (iface.IsCLSCompliant ()) continue; Report.SymbolRelatedToPreviousError (iface); Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (iface)); } } return true; } } public abstract class InterfaceMemberBase : MemberBase { // // Common modifiers allowed in a class declaration // protected const Modifiers AllowedModifiersClass = Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE | Modifiers.STATIC | Modifiers.VIRTUAL | Modifiers.SEALED | Modifiers.OVERRIDE | Modifiers.ABSTRACT | Modifiers.UNSAFE | Modifiers.EXTERN; // // Common modifiers allowed in a struct declaration // protected const Modifiers AllowedModifiersStruct = Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE | Modifiers.STATIC | Modifiers.OVERRIDE | Modifiers.UNSAFE | Modifiers.EXTERN; // // Common modifiers allowed in a interface declaration // protected const Modifiers AllowedModifiersInterface = Modifiers.NEW | Modifiers.UNSAFE; // // Whether this is an interface member. // public bool IsInterface; // // If true, this is an explicit interface implementation // public readonly bool IsExplicitImpl; protected bool is_external_implementation; // // The interface type we are explicitly implementing // public TypeSpec InterfaceType; // // The method we're overriding if this is an override method. // protected MethodSpec base_method; readonly Modifiers explicit_mod_flags; public MethodAttributes flags; public InterfaceMemberBase (TypeDefinition parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, MemberName name, Attributes attrs) : base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name, attrs) { IsInterface = parent.Kind == MemberKind.Interface; IsExplicitImpl = (MemberName.ExplicitInterface != null); explicit_mod_flags = mod; } public abstract Variance ExpectedMemberTypeVariance { get; } protected override bool CheckBase () { if (!base.CheckBase ()) return false; if ((caching_flags & Flags.MethodOverloadsExist) != 0) CheckForDuplications (); if (IsExplicitImpl) return true; // For System.Object only if (Parent.BaseType == null) return true; MemberSpec candidate; bool overrides = false; var base_member = FindBaseMember (out candidate, ref overrides); if ((ModFlags & Modifiers.OVERRIDE) != 0) { if (base_member == null) { if (candidate == null) { if (this is Method && ((Method)this).ParameterInfo.IsEmpty && MemberName.Name == Destructor.MetadataName && MemberName.Arity == 0) { Report.Error (249, Location, "Do not override `{0}'. Use destructor syntax instead", "object.Finalize()"); } else { Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override", GetSignatureForError (), SimpleName.GetMemberType (this)); } } else { Report.SymbolRelatedToPreviousError (candidate); if (this is Event) Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event", GetSignatureForError (), TypeManager.GetFullNameSignature (candidate)); else if (this is PropertyBase) Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (candidate)); else Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (candidate)); } return false; } // // Handles ambiguous overrides // if (candidate != null) { Report.SymbolRelatedToPreviousError (candidate); Report.SymbolRelatedToPreviousError (base_member); // Get member definition for error reporting var m1 = MemberCache.GetMember (base_member.DeclaringType.GetDefinition (), base_member); var m2 = MemberCache.GetMember (candidate.DeclaringType.GetDefinition (), candidate); Report.Error (462, Location, "`{0}' cannot override inherited members `{1}' and `{2}' because they have the same signature when used in type `{3}'", GetSignatureForError (), m1.GetSignatureForError (), m2.GetSignatureForError (), Parent.GetSignatureForError ()); } if (!CheckOverrideAgainstBase (base_member)) return false; ObsoleteAttribute oa = base_member.GetAttributeObsolete (); if (oa != null) { if (OptAttributes == null || !OptAttributes.Contains (Module.PredefinedAttributes.Obsolete)) { Report.SymbolRelatedToPreviousError (base_member); Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'", GetSignatureForError (), base_member.GetSignatureForError ()); } } else { if (OptAttributes != null && OptAttributes.Contains (Module.PredefinedAttributes.Obsolete)) { Report.SymbolRelatedToPreviousError (base_member); Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'", GetSignatureForError (), base_member.GetSignatureForError ()); } } base_method = base_member as MethodSpec; return true; } if (base_member == null && candidate != null && (!(candidate is IParametersMember) || !(this is IParametersMember))) base_member = candidate; if (base_member == null) { if ((ModFlags & Modifiers.NEW) != 0) { if (base_member == null) { Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ()); } } } else { if ((ModFlags & Modifiers.NEW) == 0) { ModFlags |= Modifiers.NEW; if (!IsCompilerGenerated) { Report.SymbolRelatedToPreviousError (base_member); if (!IsInterface && (base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) != 0) { Report.Warning (114, 2, Location, "`{0}' hides inherited member `{1}'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword", GetSignatureForError (), base_member.GetSignatureForError ()); } else { Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended", GetSignatureForError (), base_member.GetSignatureForError ()); } } } if (!IsInterface && base_member.IsAbstract && !overrides) { Report.SymbolRelatedToPreviousError (base_member); Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'", GetSignatureForError (), base_member.GetSignatureForError ()); } } return true; } protected virtual bool CheckForDuplications () { return Parent.MemberCache.CheckExistingMembersOverloads (this, ParametersCompiled.EmptyReadOnlyParameters); } // // Performs various checks on the MethodInfo `mb' regarding the modifier flags // that have been defined. // protected virtual bool CheckOverrideAgainstBase (MemberSpec base_member) { bool ok = true; if ((base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) == 0) { Report.SymbolRelatedToPreviousError (base_member); Report.Error (506, Location, "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override", GetSignatureForError (), TypeManager.CSharpSignature (base_member)); ok = false; } // Now we check that the overriden method is not final if ((base_member.Modifiers & Modifiers.SEALED) != 0) { Report.SymbolRelatedToPreviousError (base_member); Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed", GetSignatureForError (), TypeManager.CSharpSignature (base_member)); ok = false; } var base_member_type = ((IInterfaceMemberSpec) base_member).MemberType; if (!TypeSpecComparer.Override.IsEqual (MemberType, base_member_type)) { Report.SymbolRelatedToPreviousError (base_member); if (this is PropertyBasedMember) { Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'", GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member)); } else { Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'", GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member)); } ok = false; } return ok; } protected static bool CheckAccessModifiers (MemberCore this_member, MemberSpec base_member) { var thisp = this_member.ModFlags & Modifiers.AccessibilityMask; var base_classp = base_member.Modifiers & Modifiers.AccessibilityMask; if ((base_classp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) { // // It must be at least "protected" // if ((thisp & Modifiers.PROTECTED) == 0) { return false; } // // when overriding protected internal, the method can be declared // protected internal only within the same assembly or assembly // which has InternalsVisibleTo // if ((thisp & Modifiers.INTERNAL) != 0) { return base_member.DeclaringType.MemberDefinition.IsInternalAsPublic (this_member.Module.DeclaringAssembly); } // // protected overriding protected internal inside same assembly // requires internal modifier as well // if (base_member.DeclaringType.MemberDefinition.IsInternalAsPublic (this_member.Module.DeclaringAssembly)) { return false; } return true; } return thisp == base_classp; } public override bool Define () { if (IsInterface) { ModFlags = Modifiers.PUBLIC | Modifiers.ABSTRACT | Modifiers.VIRTUAL | (ModFlags & (Modifiers.UNSAFE | Modifiers.NEW)); flags = MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual; } else { Parent.PartialContainer.MethodModifiersValid (this); flags = ModifiersExtensions.MethodAttr (ModFlags); } if (IsExplicitImpl) { InterfaceType = MemberName.ExplicitInterface.ResolveAsType (Parent); if (InterfaceType == null) return false; if ((ModFlags & Modifiers.PARTIAL) != 0) { Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface", GetSignatureForError ()); } if (!InterfaceType.IsInterface) { Report.SymbolRelatedToPreviousError (InterfaceType); Report.Error (538, Location, "The type `{0}' in explicit interface declaration is not an interface", TypeManager.CSharpName (InterfaceType)); } else { Parent.PartialContainer.VerifyImplements (this); } ModifiersExtensions.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location, Report); } return base.Define (); } protected bool DefineParameters (ParametersCompiled parameters) { if (!parameters.Resolve (this)) return false; bool error = false; for (int i = 0; i < parameters.Count; ++i) { Parameter p = parameters [i]; if (p.HasDefaultValue && (IsExplicitImpl || this is Operator || (this is Indexer && parameters.Count == 1))) p.Warning_UselessOptionalParameter (Report); if (p.CheckAccessibility (this)) continue; TypeSpec t = parameters.Types [i]; Report.SymbolRelatedToPreviousError (t); if (this is Indexer) Report.Error (55, Location, "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'", TypeManager.CSharpName (t), GetSignatureForError ()); else if (this is Operator) Report.Error (57, Location, "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'", TypeManager.CSharpName (t), GetSignatureForError ()); else Report.Error (51, Location, "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'", TypeManager.CSharpName (t), GetSignatureForError ()); error = true; } return !error; } protected override void DoMemberTypeDependentChecks () { base.DoMemberTypeDependentChecks (); TypeManager.CheckTypeVariance (MemberType, ExpectedMemberTypeVariance, this); } public override void Emit() { // for extern static method must be specified either DllImport attribute or MethodImplAttribute. // We are more strict than csc and report this as an error because SRE does not allow emit that if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) { if (this is Constructor) { Report.Warning (824, 1, Location, "Constructor `{0}' is marked `external' but has no external implementation specified", GetSignatureForError ()); } else { Report.Warning (626, 1, Location, "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation", GetSignatureForError ()); } } base.Emit (); } public override bool EnableOverloadChecks (MemberCore overload) { // // Two members can differ in their explicit interface // type parameter only // InterfaceMemberBase imb = overload as InterfaceMemberBase; if (imb != null && imb.IsExplicitImpl) { if (IsExplicitImpl) { caching_flags |= Flags.MethodOverloadsExist; } return true; } return IsExplicitImpl; } protected void Error_CannotChangeAccessModifiers (MemberCore member, MemberSpec base_member) { var base_modifiers = base_member.Modifiers; // Remove internal modifier from types which are not internally accessible if ((base_modifiers & Modifiers.AccessibilityMask) == (Modifiers.PROTECTED | Modifiers.INTERNAL) && !base_member.DeclaringType.MemberDefinition.IsInternalAsPublic (member.Module.DeclaringAssembly)) base_modifiers = Modifiers.PROTECTED; Report.SymbolRelatedToPreviousError (base_member); Report.Error (507, member.Location, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'", member.GetSignatureForError (), ModifiersExtensions.AccessibilityName (base_modifiers), base_member.GetSignatureForError ()); } protected void Error_StaticReturnType () { Report.Error (722, Location, "`{0}': static types cannot be used as return types", MemberType.GetSignatureForError ()); } /// <summary> /// Gets base method and its return type /// </summary> protected virtual MemberSpec FindBaseMember (out MemberSpec bestCandidate, ref bool overrides) { return MemberCache.FindBaseMember (this, out bestCandidate, ref overrides); } // // The "short" name of this property / indexer / event. This is the // name without the explicit interface. // public string ShortName { get { return MemberName.Name; } } // // Returns full metadata method name // public string GetFullName (MemberName name) { return GetFullName (name.Name); } public string GetFullName (string name) { if (!IsExplicitImpl) return name; // // When dealing with explicit members a full interface type // name is added to member name to avoid possible name conflicts // // We use CSharpName which gets us full name with benefit of // replacing predefined names which saves some space and name // is still unique // return TypeManager.CSharpName (InterfaceType) + "." + name; } public override string GetSignatureForDocumentation () { if (IsExplicitImpl) return Parent.GetSignatureForDocumentation () + "." + InterfaceType.GetExplicitNameSignatureForDocumentation () + "#" + ShortName; return Parent.GetSignatureForDocumentation () + "." + ShortName; } public override bool IsUsed { get { return IsExplicitImpl || base.IsUsed; } } } public abstract class MemberBase : MemberCore { protected FullNamedExpression type_expr; protected TypeSpec member_type; public new TypeDefinition Parent; protected MemberBase (TypeDefinition parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, Modifiers def_mod, MemberName name, Attributes attrs) : base (parent, name, attrs) { this.Parent = parent; this.type_expr = type; ModFlags = ModifiersExtensions.Check (allowed_mod, mod, def_mod, Location, Report); } #region Properties public TypeSpec MemberType { get { return member_type; } } public FullNamedExpression TypeExpression { get { return type_expr; } } #endregion // // Main member define entry // public override bool Define () { DoMemberTypeIndependentChecks (); // // Returns false only when type resolution failed // if (!ResolveMemberType ()) return false; DoMemberTypeDependentChecks (); return true; } // // Any type_name independent checks // protected virtual void DoMemberTypeIndependentChecks () { if ((Parent.ModFlags & Modifiers.SEALED) != 0 && (ModFlags & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) { Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'", GetSignatureForError (), Parent.GetSignatureForError ()); } } // // Any type_name dependent checks // protected virtual void DoMemberTypeDependentChecks () { // verify accessibility if (!IsAccessibleAs (MemberType)) { Report.SymbolRelatedToPreviousError (MemberType); if (this is Property) Report.Error (53, Location, "Inconsistent accessibility: property type `" + TypeManager.CSharpName (MemberType) + "' is less " + "accessible than property `" + GetSignatureForError () + "'"); else if (this is Indexer) Report.Error (54, Location, "Inconsistent accessibility: indexer return type `" + TypeManager.CSharpName (MemberType) + "' is less " + "accessible than indexer `" + GetSignatureForError () + "'"); else if (this is MethodCore) { if (this is Operator) Report.Error (56, Location, "Inconsistent accessibility: return type `" + TypeManager.CSharpName (MemberType) + "' is less " + "accessible than operator `" + GetSignatureForError () + "'"); else Report.Error (50, Location, "Inconsistent accessibility: return type `" + TypeManager.CSharpName (MemberType) + "' is less " + "accessible than method `" + GetSignatureForError () + "'"); } else { Report.Error (52, Location, "Inconsistent accessibility: field type `" + TypeManager.CSharpName (MemberType) + "' is less " + "accessible than field `" + GetSignatureForError () + "'"); } } } protected void IsTypePermitted () { if (MemberType.IsSpecialRuntimeType) { if (Parent is StateMachine) { Report.Error (4012, Location, "Parameters or local variables of type `{0}' cannot be declared in async methods or iterators", MemberType.GetSignatureForError ()); } else if (Parent is HoistedStoreyClass) { Report.Error (4013, Location, "Local variables of type `{0}' cannot be used inside anonymous methods, lambda expressions or query expressions", MemberType.GetSignatureForError ()); } else { Report.Error (610, Location, "Field or property cannot be of type `{0}'", MemberType.GetSignatureForError ()); } } } protected virtual bool CheckBase () { CheckProtectedModifier (); return true; } public override string GetSignatureForDocumentation () { return Parent.GetSignatureForDocumentation () + "." + MemberName.Basename; } protected virtual bool ResolveMemberType () { if (member_type != null) throw new InternalErrorException ("Multi-resolve"); member_type = type_expr.ResolveAsType (this); return member_type != null; } } }
28.177778
192
0.673472
[ "Apache-2.0" ]
pcc/mono
mcs/mcs/class.cs
100,172
C#
using System.IO; using BattleTech; using ModTek.Features.CustomResources; using ModTek.Features.Manifest; using ModTek.Features.Manifest.BTRL; using ModTek.Features.Manifest.MDD; namespace ModTek.Features.CustomGameTips { // custom streaming assets add existing resources to BTRL internal static class GameTipsFeature { internal static string GetGameTip(string path) { var id = Path.GetFileNameWithoutExtension(path); var entry = BetterBTRL.Instance.EntryByIDAndType(id, InternalCustomResourceType.GameTip.ToString()); return ModsManifest.GetText(entry); } internal static readonly VersionManifestEntry[] DefaulManifestEntries = { new VersionManifestEntry( "general", Path.Combine("GameTips", "general.txt"), InternalCustomResourceType.GameTip.ToString(), VersionManifestEntryExtensions.UpdatedOnLazyTracking, "1" ), new VersionManifestEntry( "combat", Path.Combine("GameTips", "combat.txt"), InternalCustomResourceType.GameTip.ToString(), VersionManifestEntryExtensions.UpdatedOnLazyTracking, "1" ), new VersionManifestEntry( "lore", Path.Combine("GameTips", "lore.txt"), InternalCustomResourceType.GameTip.ToString(), VersionManifestEntryExtensions.UpdatedOnLazyTracking, "1" ), new VersionManifestEntry( "sim", Path.Combine("GameTips", "sim.txt"), InternalCustomResourceType.GameTip.ToString(), VersionManifestEntryExtensions.UpdatedOnLazyTracking, "1" ) }; internal static bool FindAndSetMatchingType(ModEntry entry) { switch (entry.Id) { case "settings": entry.Type = InternalCustomResourceType.DebugSettings.ToString(); return true; case "general": case "combat": case "lore": case "sim": entry.Type = InternalCustomResourceType.GameTip.ToString(); return true; } return false; } } }
34.408451
112
0.560377
[ "Unlicense" ]
Mpstark/ModTek
ModTek/Features/CustomGameTips/GameTipsFeature.cs
2,445
C#
// ****************************************************************** // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THE CODE 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 CODE OR THE USE OR OTHER DEALINGS IN THE CODE. // ****************************************************************** using System; using System.IO; using System.Linq; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.Storage; using Windows.Storage.Search; using Windows.Storage.Streams; namespace Microsoft.Toolkit.Uwp.Helpers { /// <summary> /// This class provides static helper methods for <see cref="StorageFile" />. /// </summary> public static class StorageFileHelper { /// <summary> /// Saves a string value to a <see cref="StorageFile"/> in application local folder/>. /// </summary> /// <param name="text"> /// The <see cref="string"/> value to save to the file. /// </param> /// <param name="fileName"> /// The <see cref="string"/> name for the file. /// </param> /// <param name="options"> /// The creation collision options. Default is ReplaceExisting. /// </param> /// <returns> /// Returns the saved <see cref="StorageFile"/> containing the text. /// </returns> /// <exception cref="ArgumentNullException"> /// Exception thrown if the file location or file name are null or empty. /// </exception> public static Task<StorageFile> WriteTextToLocalFileAsync( string text, string fileName, CreationCollisionOption options = CreationCollisionOption.ReplaceExisting) { if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentNullException(nameof(fileName)); } var folder = ApplicationData.Current.LocalFolder; return folder.WriteTextToFileAsync(text, fileName, options); } /// <summary> /// Saves a string value to a <see cref="StorageFile"/> in application local cache folder/>. /// </summary> /// <param name="text"> /// The <see cref="string"/> value to save to the file. /// </param> /// <param name="fileName"> /// The <see cref="string"/> name for the file. /// </param> /// <param name="options"> /// The creation collision options. Default is ReplaceExisting. /// </param> /// <returns> /// Returns the saved <see cref="StorageFile"/> containing the text. /// </returns> /// <exception cref="ArgumentNullException"> /// Exception thrown if the file location or file name are null or empty. /// </exception> public static Task<StorageFile> WriteTextToLocalCacheFileAsync( string text, string fileName, CreationCollisionOption options = CreationCollisionOption.ReplaceExisting) { if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentNullException(nameof(fileName)); } var folder = ApplicationData.Current.LocalCacheFolder; return folder.WriteTextToFileAsync(text, fileName, options); } /// <summary> /// Saves a string value to a <see cref="StorageFile"/> in well known folder/>. /// </summary> /// <param name="knownFolderId"> /// The well known folder ID to use. /// </param> /// <param name="text"> /// The <see cref="string"/> value to save to the file. /// </param> /// <param name="fileName"> /// The <see cref="string"/> name for the file. /// </param> /// <param name="options"> /// The creation collision options. Default is ReplaceExisting. /// </param> /// <returns> /// Returns the saved <see cref="StorageFile"/> containing the text. /// </returns> /// <exception cref="ArgumentNullException"> /// Exception thrown if the file location or file name are null or empty. /// </exception> public static Task<StorageFile> WriteTextToKnownFolderFileAsync( KnownFolderId knownFolderId, string text, string fileName, CreationCollisionOption options = CreationCollisionOption.ReplaceExisting) { if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentNullException(nameof(fileName)); } var folder = GetFolderFromKnownFolderId(knownFolderId); return folder.WriteTextToFileAsync(text, fileName, options); } /// <summary> /// Saves a string value to a <see cref="StorageFile"/> in the given <see cref="StorageFolder"/>. /// </summary> /// <param name="fileLocation"> /// The <see cref="StorageFolder"/> to save the file in. /// </param> /// <param name="text"> /// The <see cref="string"/> value to save to the file. /// </param> /// <param name="fileName"> /// The <see cref="string"/> name for the file. /// </param> /// <param name="options"> /// The creation collision options. Default is ReplaceExisting. /// </param> /// <returns> /// Returns the saved <see cref="StorageFile"/> containing the text. /// </returns> /// <exception cref="ArgumentNullException"> /// Exception thrown if the file location or file name are null or empty. /// </exception> public static async Task<StorageFile> WriteTextToFileAsync( this StorageFolder fileLocation, string text, string fileName, CreationCollisionOption options = CreationCollisionOption.ReplaceExisting) { if (fileLocation == null) { throw new ArgumentNullException(nameof(fileLocation)); } if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentNullException(nameof(fileName)); } var storageFile = await fileLocation.CreateFileAsync(fileName, options); await FileIO.WriteTextAsync(storageFile, text); return storageFile; } /// <summary> /// Saves an array of bytes to a <see cref="StorageFile"/> to application local folder/>. /// </summary> /// <param name="bytes"> /// The <see cref="byte"/> array to save to the file. /// </param> /// <param name="fileName"> /// The <see cref="string"/> name for the file. /// </param> /// <param name="options"> /// The creation collision options. Default is ReplaceExisting. /// </param> /// <returns> /// Returns the saved <see cref="StorageFile"/> containing the bytes. /// </returns> /// <exception cref="ArgumentNullException"> /// Exception thrown if the file location or file name are null or empty. /// </exception> public static Task<StorageFile> WriteBytesToLocalFileAsync( byte[] bytes, string fileName, CreationCollisionOption options = CreationCollisionOption.ReplaceExisting) { if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentNullException(nameof(fileName)); } var folder = ApplicationData.Current.LocalFolder; return folder.WriteBytesToFileAsync(bytes, fileName, options); } /// <summary> /// Saves an array of bytes to a <see cref="StorageFile"/> to application local cache folder/>. /// </summary> /// <param name="bytes"> /// The <see cref="byte"/> array to save to the file. /// </param> /// <param name="fileName"> /// The <see cref="string"/> name for the file. /// </param> /// <param name="options"> /// The creation collision options. Default is ReplaceExisting. /// </param> /// <returns> /// Returns the saved <see cref="StorageFile"/> containing the bytes. /// </returns> /// <exception cref="ArgumentNullException"> /// Exception thrown if the file location or file name are null or empty. /// </exception> public static Task<StorageFile> WriteBytesToLocalCacheFileAsync( byte[] bytes, string fileName, CreationCollisionOption options = CreationCollisionOption.ReplaceExisting) { if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentNullException(nameof(fileName)); } var folder = ApplicationData.Current.LocalCacheFolder; return folder.WriteBytesToFileAsync(bytes, fileName, options); } /// <summary> /// Saves an array of bytes to a <see cref="StorageFile"/> to well known folder/>. /// </summary> /// <param name="knownFolderId"> /// The well known folder ID to use. /// </param> /// <param name="bytes"> /// The <see cref="byte"/> array to save to the file. /// </param> /// <param name="fileName"> /// The <see cref="string"/> name for the file. /// </param> /// <param name="options"> /// The creation collision options. Default is ReplaceExisting. /// </param> /// <returns> /// Returns the saved <see cref="StorageFile"/> containing the bytes. /// </returns> /// <exception cref="ArgumentNullException"> /// Exception thrown if the file location or file name are null or empty. /// </exception> public static Task<StorageFile> WriteBytesToKnownFolderFileAsync( KnownFolderId knownFolderId, byte[] bytes, string fileName, CreationCollisionOption options = CreationCollisionOption.ReplaceExisting) { if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentNullException(nameof(fileName)); } var folder = GetFolderFromKnownFolderId(knownFolderId); return folder.WriteBytesToFileAsync(bytes, fileName, options); } /// <summary> /// Saves an array of bytes to a <see cref="StorageFile"/> in the given <see cref="StorageFolder"/>. /// </summary> /// <param name="fileLocation"> /// The <see cref="StorageFolder"/> to save the file in. /// </param> /// <param name="bytes"> /// The <see cref="byte"/> array to save to the file. /// </param> /// <param name="fileName"> /// The <see cref="string"/> name for the file. /// </param> /// <param name="options"> /// The creation collision options. Default is ReplaceExisting. /// </param> /// <returns> /// Returns the saved <see cref="StorageFile"/> containing the bytes. /// </returns> /// <exception cref="ArgumentNullException"> /// Exception thrown if the file location or file name are null or empty. /// </exception> public static async Task<StorageFile> WriteBytesToFileAsync( this StorageFolder fileLocation, byte[] bytes, string fileName, CreationCollisionOption options = CreationCollisionOption.ReplaceExisting) { if (fileLocation == null) { throw new ArgumentNullException(nameof(fileLocation)); } if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentNullException(nameof(fileName)); } var storageFile = await fileLocation.CreateFileAsync(fileName, options); await FileIO.WriteBytesAsync(storageFile, bytes); return storageFile; } /// <summary> /// Gets a string value from a <see cref="StorageFile"/> located in the application installation folder. /// </summary> /// <param name="fileName"> /// The relative <see cref="string"/> file path. /// </param> /// <returns> /// Returns the stored <see cref="string"/> value. /// </returns> /// <exception cref="ArgumentNullException"> /// Exception thrown if the <paramref name="fileName"/> is null or empty. /// </exception> public static Task<string> ReadTextFromPackagedFileAsync(string fileName) { if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentNullException(nameof(fileName)); } var folder = Package.Current.InstalledLocation; return folder.ReadTextFromFileAsync(fileName); } /// <summary> /// Gets a string value from a <see cref="StorageFile"/> located in the application local cache folder. /// </summary> /// <param name="fileName"> /// The relative <see cref="string"/> file path. /// </param> /// <returns> /// Returns the stored <see cref="string"/> value. /// </returns> /// <exception cref="ArgumentNullException"> /// Exception thrown if the <paramref name="fileName"/> is null or empty. /// </exception> public static Task<string> ReadTextFromLocalCacheFileAsync(string fileName) { if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentNullException(nameof(fileName)); } var folder = ApplicationData.Current.LocalCacheFolder; return folder.ReadTextFromFileAsync(fileName); } /// <summary> /// Gets a string value from a <see cref="StorageFile"/> located in the application local folder. /// </summary> /// <param name="fileName"> /// The relative <see cref="string"/> file path. /// </param> /// <returns> /// Returns the stored <see cref="string"/> value. /// </returns> /// <exception cref="ArgumentNullException"> /// Exception thrown if the <paramref name="fileName"/> is null or empty. /// </exception> public static Task<string> ReadTextFromLocalFileAsync(string fileName) { if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentNullException(nameof(fileName)); } var folder = ApplicationData.Current.LocalFolder; return folder.ReadTextFromFileAsync(fileName); } /// <summary> /// Gets a string value from a <see cref="StorageFile"/> located in a well known folder. /// </summary> /// <param name="knownFolderId"> /// The well known folder ID to use. /// </param> /// <param name="fileName"> /// The relative <see cref="string"/> file path. /// </param> /// <returns> /// Returns the stored <see cref="string"/> value. /// </returns> /// <exception cref="ArgumentNullException"> /// Exception thrown if the <paramref name="fileName"/> is null or empty. /// </exception> public static Task<string> ReadTextFromKnownFoldersFileAsync( KnownFolderId knownFolderId, string fileName) { if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentNullException(nameof(fileName)); } var folder = GetFolderFromKnownFolderId(knownFolderId); return folder.ReadTextFromFileAsync(fileName); } /// <summary> /// Gets a string value from a <see cref="StorageFile"/> located in the given <see cref="StorageFolder"/>. /// </summary> /// <param name="fileLocation"> /// The <see cref="StorageFolder"/> to save the file in. /// </param> /// <param name="fileName"> /// The relative <see cref="string"/> file path. /// </param> /// <returns> /// Returns the stored <see cref="string"/> value. /// </returns> /// <exception cref="ArgumentNullException"> /// Exception thrown if the <paramref name="fileName"/> is null or empty. /// </exception> public static async Task<string> ReadTextFromFileAsync( this StorageFolder fileLocation, string fileName) { if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentNullException(nameof(fileName)); } var file = await fileLocation.GetFileAsync(fileName); return await FileIO.ReadTextAsync(file); } /// <summary> /// Gets an array of bytes from a <see cref="StorageFile"/> located in the application installation folder. /// </summary> /// <param name="fileName"> /// The relative <see cref="string"/> file path. /// </param> /// <returns> /// Returns the stored <see cref="byte"/> array. /// </returns> /// <exception cref="ArgumentNullException"> /// Exception thrown if the <paramref name="fileName"/> is null or empty. /// </exception> public static Task<byte[]> ReadBytesFromPackagedFileAsync(string fileName) { if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentNullException(nameof(fileName)); } var folder = Package.Current.InstalledLocation; return folder.ReadBytesFromFileAsync(fileName); } /// <summary> /// Gets an array of bytes from a <see cref="StorageFile"/> located in the application local cache folder. /// </summary> /// <param name="fileName"> /// The relative <see cref="string"/> file path. /// </param> /// <returns> /// Returns the stored <see cref="byte"/> array. /// </returns> /// <exception cref="ArgumentNullException"> /// Exception thrown if the <paramref name="fileName"/> is null or empty. /// </exception> public static Task<byte[]> ReadBytesFromLocalCacheFileAsync(string fileName) { if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentNullException(nameof(fileName)); } var folder = ApplicationData.Current.LocalCacheFolder; return folder.ReadBytesFromFileAsync(fileName); } /// <summary> /// Gets an array of bytes from a <see cref="StorageFile"/> located in the application local folder. /// </summary> /// <param name="fileName"> /// The relative <see cref="string"/> file path. /// </param> /// <returns> /// Returns the stored <see cref="byte"/> array. /// </returns> /// <exception cref="ArgumentNullException"> /// Exception thrown if the <paramref name="fileName"/> is null or empty. /// </exception> public static Task<byte[]> ReadBytesFromLocalFileAsync(string fileName) { if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentNullException(nameof(fileName)); } var folder = ApplicationData.Current.LocalFolder; return folder.ReadBytesFromFileAsync(fileName); } /// <summary> /// Gets an array of bytes from a <see cref="StorageFile"/> located in a well known folder. /// </summary> /// <param name="knownFolderId"> /// The well known folder ID to use. /// </param> /// <param name="fileName"> /// The relative <see cref="string"/> file path. /// </param> /// <returns> /// Returns the stored <see cref="byte"/> array. /// </returns> /// <exception cref="ArgumentNullException"> /// Exception thrown if the <paramref name="fileName"/> is null or empty. /// </exception> public static Task<byte[]> ReadBytesFromKnownFoldersFileAsync( KnownFolderId knownFolderId, string fileName) { if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentNullException(nameof(fileName)); } var folder = GetFolderFromKnownFolderId(knownFolderId); return folder.ReadBytesFromFileAsync(fileName); } /// <summary> /// Gets an array of bytes from a <see cref="StorageFile"/> located in the given <see cref="StorageFolder"/>. /// </summary> /// <param name="fileLocation"> /// The <see cref="StorageFolder"/> to save the file in. /// </param> /// <param name="fileName"> /// The relative <see cref="string"/> file path. /// </param> /// <returns> /// Returns the stored <see cref="byte"/> array. /// </returns> /// <exception cref="ArgumentNullException"> /// Exception thrown if the <paramref name="fileName"/> is null or empty. /// </exception> public static async Task<byte[]> ReadBytesFromFileAsync( this StorageFolder fileLocation, string fileName) { if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentNullException(nameof(fileName)); } var file = await fileLocation.GetFileAsync(fileName).AsTask().ConfigureAwait(false); return await file.ReadBytesAsync(); } /// <summary> /// Gets an array of bytes from a <see cref="StorageFile"/>. /// </summary> /// <param name="file"> /// The <see cref="StorageFile"/>. /// </param> /// <returns> /// Returns the stored <see cref="byte"/> array. /// </returns> public static async Task<byte[]> ReadBytesAsync(this StorageFile file) { if (file == null) { return null; } using (IRandomAccessStream stream = await file.OpenReadAsync()) { using (var reader = new DataReader(stream.GetInputStreamAt(0))) { await reader.LoadAsync((uint)stream.Size); var bytes = new byte[stream.Size]; reader.ReadBytes(bytes); return bytes; } } } /// <summary> /// Gets a value indicating whether a file exists in the current folder. /// </summary> /// <param name="folder"> /// The <see cref="StorageFolder"/> to look for the file in. /// </param> /// <param name="fileName"> /// The <see cref="string"/> filename of the file to search for. Must include the file extension and is not case-sensitive. /// </param> /// <param name="isRecursive"> /// The <see cref="bool"/>, indicating if the subfolders should also be searched through. /// </param> /// <returns> /// Returns true, if the file exists. /// </returns> public static Task<bool> FileExistsAsync(this StorageFolder folder, string fileName, bool isRecursive = false) => isRecursive ? FileExistsInSubtreeAsync(folder, fileName) : FileExistsInFolderAsync(folder, fileName); /// <summary> /// Gets a value indicating whether a filename is correct or not using the Storage feature. /// </summary> /// <param name="fileName">The filename to test. Must include the file extension and is not case-sensitive.</param> /// <returns>Returns true if the filename is valid.</returns> public static bool IsFileNameValid(string fileName) { var illegalChars = Path.GetInvalidFileNameChars(); return fileName.All(c => !illegalChars.Contains(c)); } /// <summary> /// Gets a value indicating whether a file path is correct or not using the Storage feature. /// </summary> /// <param name="filePath">The file path to test. Must include the file extension and is not case-sensitive.</param> /// <returns>Returns true if the file path is valid.</returns> public static bool IsFilePathValid(string filePath) { var illegalChars = Path.GetInvalidPathChars(); return filePath.All(c => !illegalChars.Contains(c)); } /// <summary> /// Gets a value indicating whether a file exists in the current folder. /// </summary> /// <param name="folder"> /// The <see cref="StorageFolder"/> to look for the file in. /// </param> /// <param name="fileName"> /// The <see cref="string"/> filename of the file to search for. Must include the file extension and is not case-sensitive. /// </param> /// <returns> /// Returns true, if the file exists. /// </returns> internal static async Task<bool> FileExistsInFolderAsync(StorageFolder folder, string fileName) { var item = await folder.TryGetItemAsync(fileName).AsTask().ConfigureAwait(false); return (item != null) && item.IsOfType(StorageItemTypes.File); } /// <summary> /// Gets a value indicating whether a file exists in the current folder or in one of its subfolders. /// </summary> /// <param name="rootFolder"> /// The <see cref="StorageFolder"/> to look for the file in. /// </param> /// <param name="fileName"> /// The <see cref="string"/> filename of the file to search for. Must include the file extension and is not case-sensitive. /// </param> /// <returns> /// Returns true, if the file exists. /// </returns> /// <exception cref="ArgumentException"> /// Exception thrown if the <paramref name="fileName"/> contains a quotation mark. /// </exception> internal static async Task<bool> FileExistsInSubtreeAsync(StorageFolder rootFolder, string fileName) { if (fileName.IndexOf('"') >= 0) { throw new ArgumentException(nameof(fileName)); } var options = new QueryOptions { FolderDepth = FolderDepth.Deep, UserSearchFilter = $"filename:=\"{fileName}\"" // “:=” is the exact-match operator }; var files = await rootFolder.CreateFileQueryWithOptions(options).GetFilesAsync().AsTask().ConfigureAwait(false); return files.Count > 0; } /// <summary> /// Returns a <see cref="StorageFolder"/> from a <see cref="KnownFolderId"/> /// </summary> /// <param name="knownFolderId">Folder Id</param> /// <returns><see cref="StorageFolder"/></returns> internal static StorageFolder GetFolderFromKnownFolderId(KnownFolderId knownFolderId) { StorageFolder workingFolder; switch (knownFolderId) { case KnownFolderId.AppCaptures: workingFolder = KnownFolders.AppCaptures; break; case KnownFolderId.CameraRoll: workingFolder = KnownFolders.CameraRoll; break; case KnownFolderId.DocumentsLibrary: workingFolder = KnownFolders.DocumentsLibrary; break; case KnownFolderId.HomeGroup: workingFolder = KnownFolders.HomeGroup; break; case KnownFolderId.MediaServerDevices: workingFolder = KnownFolders.MediaServerDevices; break; case KnownFolderId.MusicLibrary: workingFolder = KnownFolders.MusicLibrary; break; case KnownFolderId.Objects3D: workingFolder = KnownFolders.Objects3D; break; case KnownFolderId.PicturesLibrary: workingFolder = KnownFolders.PicturesLibrary; break; case KnownFolderId.Playlists: workingFolder = KnownFolders.Playlists; break; case KnownFolderId.RecordedCalls: workingFolder = KnownFolders.RecordedCalls; break; case KnownFolderId.RemovableDevices: workingFolder = KnownFolders.RemovableDevices; break; case KnownFolderId.SavedPictures: workingFolder = KnownFolders.SavedPictures; break; case KnownFolderId.VideosLibrary: workingFolder = KnownFolders.VideosLibrary; break; default: throw new ArgumentOutOfRangeException(nameof(knownFolderId), knownFolderId, null); } return workingFolder; } } }
40.40027
131
0.562231
[ "MIT" ]
dipidoo/UWPCommunityToolkit
Microsoft.Toolkit.Uwp/Helpers/StorageFileHelper.cs
29,987
C#
using System; namespace YubicoLib.YubikeyNeo { internal class YubikeyNeoDeviceHandle : IDisposable { public IntPtr Device { get; private set; } public YubikeyNeoDeviceHandle() { IntPtr intPtr = IntPtr.Zero; YubikeyNeoNative.YkNeoManagerInit(ref intPtr); Device = intPtr; } public void Dispose() { if (Device != IntPtr.Zero) YubikeyNeoNative.YkNeoManagerDone(Device); Device = IntPtr.Zero; } } }
22.583333
58
0.568266
[ "MIT" ]
CSIS/EnrollmentStation
YubicoLib/YubikeyNeo/YubikeyNeoDeviceHandle.cs
542
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using System.Buffers.Text; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text.Encodings.Web; using System.Text.Unicode; namespace System.Text.Json { // TODO: Replace the escaping logic with publicly shipping APIs from https://github.com/dotnet/corefx/issues/33509 internal static partial class JsonWriterHelper { // Only allow ASCII characters between ' ' (0x20) and '~' (0x7E), inclusively, // but exclude characters that need to be escaped as hex: '"', '\'', '&', '+', '<', '>', '`' // and exclude characters that need to be escaped by adding a backslash: '\n', '\r', '\t', '\\', '\b', '\f' // // non-zero = allowed, 0 = disallowed public const int LastAsciiCharacter = 0x7F; private static ReadOnlySpan<byte> AllowList => new byte[LastAsciiCharacter + 1] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // U+0000..U+000F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // U+0010..U+001F 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, // U+0020..U+002F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, // U+0030..U+003F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // U+0040..U+004F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, // U+0050..U+005F 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // U+0060..U+006F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, // U+0070..U+007F }; private const string HexFormatString = "X4"; private static readonly StandardFormat s_hexStandardFormat = new StandardFormat('X', 4); [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool NeedsEscapingNoBoundsCheck(byte value) { Debug.Assert(value <= LastAsciiCharacter); return AllowList[value] == 0; } private static bool NeedsEscapingNoBoundsCheck(char value) { Debug.Assert(value <= LastAsciiCharacter); return AllowList[value] == 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool NeedsEscaping(byte value) => value > LastAsciiCharacter || AllowList[value] == 0; [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool NeedsEscaping(char value) => value > LastAsciiCharacter || AllowList[value] == 0; public static int NeedsEscaping(ReadOnlySpan<byte> value, JavaScriptEncoder encoder) { if (encoder != null) { return encoder.FindFirstCharacterToEncodeUtf8(value); } int idx; for (idx = 0; idx < value.Length; idx++) { if (NeedsEscaping(value[idx])) { goto Return; } } idx = -1; // all characters allowed Return: return idx; } public static int NeedsEscaping(ReadOnlySpan<char> value, JavaScriptEncoder encoder) { if (encoder != null) { return encoder.FindFirstCharacterToEncodeUtf8(MemoryMarshal.Cast<char, byte>(value)); } int idx; for (idx = 0; idx < value.Length; idx++) { if (NeedsEscaping(value[idx])) { goto Return; } } idx = -1; // all characters allowed Return: return idx; } public static int GetMaxEscapedLength(int textLength, int firstIndexToEscape) { Debug.Assert(textLength > 0); Debug.Assert(firstIndexToEscape >= 0 && firstIndexToEscape < textLength); return firstIndexToEscape + JsonConstants.MaxExpansionFactorWhileEscaping * (textLength - firstIndexToEscape); } private static void EscapeString(ReadOnlySpan<byte> value, Span<byte> destination, JavaScriptEncoder encoder, ref int written) { Debug.Assert(encoder != null); OperationStatus result = encoder.EncodeUtf8(value, destination, out int encoderBytesConsumed, out int encoderBytesWritten); Debug.Assert(result != OperationStatus.DestinationTooSmall); Debug.Assert(result != OperationStatus.NeedMoreData); Debug.Assert(encoderBytesConsumed == value.Length); if (result != OperationStatus.Done) { ThrowHelper.ThrowArgumentException_InvalidUTF8(value.Slice(encoderBytesWritten)); } written += encoderBytesWritten; } public static void EscapeString(ReadOnlySpan<byte> value, Span<byte> destination, int indexOfFirstByteToEscape, JavaScriptEncoder encoder, out int written) { Debug.Assert(indexOfFirstByteToEscape >= 0 && indexOfFirstByteToEscape < value.Length); value.Slice(0, indexOfFirstByteToEscape).CopyTo(destination); written = indexOfFirstByteToEscape; int consumed = indexOfFirstByteToEscape; if (encoder != null) { destination = destination.Slice(indexOfFirstByteToEscape); value = value.Slice(indexOfFirstByteToEscape); EscapeString(value, destination, encoder, ref written); } else { // For performance when no encoder is specified, perform escaping here for Ascii and on the // first occurrence of a non-Ascii character, then call into the default encoder. while (consumed < value.Length) { byte val = value[consumed]; if (IsAsciiValue(val)) { if (NeedsEscapingNoBoundsCheck(val)) { EscapeNextBytes(val, destination, ref written); consumed++; } else { destination[written] = val; written++; consumed++; } } else { // Fall back to default encoder. destination = destination.Slice(written); value = value.Slice(consumed); EscapeString(value, destination, JavaScriptEncoder.Default, ref written); break; } } } } private static void EscapeNextBytes(byte value, Span<byte> destination, ref int written) { destination[written++] = (byte)'\\'; switch (value) { case JsonConstants.Quote: // Optimize for the common quote case. destination[written++] = (byte)'u'; destination[written++] = (byte)'0'; destination[written++] = (byte)'0'; destination[written++] = (byte)'2'; destination[written++] = (byte)'2'; break; case JsonConstants.LineFeed: destination[written++] = (byte)'n'; break; case JsonConstants.CarriageReturn: destination[written++] = (byte)'r'; break; case JsonConstants.Tab: destination[written++] = (byte)'t'; break; case JsonConstants.BackSlash: destination[written++] = (byte)'\\'; break; case JsonConstants.BackSpace: destination[written++] = (byte)'b'; break; case JsonConstants.FormFeed: destination[written++] = (byte)'f'; break; default: destination[written++] = (byte)'u'; bool result = Utf8Formatter.TryFormat(value, destination.Slice(written), out int bytesWritten, format: s_hexStandardFormat); Debug.Assert(result); Debug.Assert(bytesWritten == 4); written += bytesWritten; break; } } private static bool IsAsciiValue(byte value) => value <= LastAsciiCharacter; private static bool IsAsciiValue(char value) => value <= LastAsciiCharacter; /// <summary> /// Returns <see langword="true"/> if <paramref name="value"/> is a UTF-8 continuation byte. /// A UTF-8 continuation byte is a byte whose value is in the range 0x80-0xBF, inclusive. /// </summary> private static bool IsUtf8ContinuationByte(byte value) => (value & 0xC0) == 0x80; /// <summary> /// Returns <see langword="true"/> if the low word of <paramref name="char"/> is a UTF-16 surrogate. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsLowWordSurrogate(uint @char) => (@char & 0xF800U) == 0xD800U; // We can't use the type Rune since it is not available on netstandard2.0 // To avoid extensive ifdefs and for simplicity, just using an int to reprepsent the scalar value, instead. public static SequenceValidity PeekFirstSequence(ReadOnlySpan<byte> data, out int numBytesConsumed, out int rune) { // This method is implemented to match the behavior of System.Text.Encoding.UTF8 in terms of // how many bytes it consumes when reporting invalid sequences. The behavior is as follows: // // - Some bytes are *always* invalid (ranges [ C0..C1 ] and [ F5..FF ]), and when these // are encountered it's an invalid sequence of length 1. // // - Multi-byte sequences which are overlong are reported as an invalid sequence of length 2, // since per the Unicode Standard Table 3-7 it's always possible to tell these by the second byte. // Exception: Sequences which begin with [ C0..C1 ] are covered by the above case, thus length 1. // // - Multi-byte sequences which are improperly terminated (no continuation byte when one is // expected) are reported as invalid sequences up to and including the last seen continuation byte. Debug.Assert(JsonHelpers.IsValidUnicodeScalar(ReplacementChar)); rune = ReplacementChar; if (data.IsEmpty) { // No data to peek at numBytesConsumed = 0; return SequenceValidity.Empty; } byte firstByte = data[0]; if (IsAsciiValue(firstByte)) { // ASCII byte = well-formed one-byte sequence. Debug.Assert(JsonHelpers.IsValidUnicodeScalar(firstByte)); rune = firstByte; numBytesConsumed = 1; return SequenceValidity.WellFormed; } if (!JsonHelpers.IsInRangeInclusive(firstByte, (byte)0xC2U, (byte)0xF4U)) { // Standalone continuation byte or "always invalid" byte = ill-formed one-byte sequence. goto InvalidOneByteSequence; } // At this point, we know we're working with a multi-byte sequence, // and we know that at least the first byte is potentially valid. if (data.Length < 2) { // One byte of an incomplete multi-byte sequence. goto OneByteOfIncompleteMultiByteSequence; } byte secondByte = data[1]; if (!IsUtf8ContinuationByte(secondByte)) { // One byte of an improperly terminated multi-byte sequence. goto InvalidOneByteSequence; } if (firstByte < (byte)0xE0U) { // Well-formed two-byte sequence. uint scalar = (((uint)firstByte & 0x1FU) << 6) | ((uint)secondByte & 0x3FU); Debug.Assert(JsonHelpers.IsValidUnicodeScalar(scalar)); rune = (int)scalar; numBytesConsumed = 2; return SequenceValidity.WellFormed; } if (firstByte < (byte)0xF0U) { // Start of a three-byte sequence. // Need to check for overlong or surrogate sequences. uint scalar = (((uint)firstByte & 0x0FU) << 12) | (((uint)secondByte & 0x3FU) << 6); if (scalar < 0x800U || IsLowWordSurrogate(scalar)) { goto OverlongOutOfRangeOrSurrogateSequence; } // At this point, we have a valid two-byte start of a three-byte sequence. if (data.Length < 3) { // Two bytes of an incomplete three-byte sequence. goto TwoBytesOfIncompleteMultiByteSequence; } else { byte thirdByte = data[2]; if (IsUtf8ContinuationByte(thirdByte)) { // Well-formed three-byte sequence. scalar |= (uint)thirdByte & 0x3FU; Debug.Assert(JsonHelpers.IsValidUnicodeScalar(scalar)); rune = (int)scalar; numBytesConsumed = 3; return SequenceValidity.WellFormed; } else { // Two bytes of improperly terminated multi-byte sequence. goto InvalidTwoByteSequence; } } } { // Start of four-byte sequence. // Need to check for overlong or out-of-range sequences. uint scalar = (((uint)firstByte & 0x07U) << 18) | (((uint)secondByte & 0x3FU) << 12); Debug.Assert(JsonHelpers.IsValidUnicodeScalar(scalar)); if (!JsonHelpers.IsInRangeInclusive(scalar, 0x10000U, 0x10FFFFU)) { goto OverlongOutOfRangeOrSurrogateSequence; } // At this point, we have a valid two-byte start of a four-byte sequence. if (data.Length < 3) { // Two bytes of an incomplete four-byte sequence. goto TwoBytesOfIncompleteMultiByteSequence; } else { byte thirdByte = data[2]; if (IsUtf8ContinuationByte(thirdByte)) { // Valid three-byte start of a four-byte sequence. if (data.Length < 4) { // Three bytes of an incomplete four-byte sequence. goto ThreeBytesOfIncompleteMultiByteSequence; } else { byte fourthByte = data[3]; if (IsUtf8ContinuationByte(fourthByte)) { // Well-formed four-byte sequence. scalar |= (((uint)thirdByte & 0x3FU) << 6) | ((uint)fourthByte & 0x3FU); Debug.Assert(JsonHelpers.IsValidUnicodeScalar(scalar)); rune = (int)scalar; numBytesConsumed = 4; return SequenceValidity.WellFormed; } else { // Three bytes of an improperly terminated multi-byte sequence. goto InvalidThreeByteSequence; } } } else { // Two bytes of improperly terminated multi-byte sequence. goto InvalidTwoByteSequence; } } } // Everything below here is error handling. InvalidOneByteSequence: numBytesConsumed = 1; return SequenceValidity.Invalid; InvalidTwoByteSequence: OverlongOutOfRangeOrSurrogateSequence: numBytesConsumed = 2; return SequenceValidity.Invalid; InvalidThreeByteSequence: numBytesConsumed = 3; return SequenceValidity.Invalid; OneByteOfIncompleteMultiByteSequence: numBytesConsumed = 1; return SequenceValidity.Incomplete; TwoBytesOfIncompleteMultiByteSequence: numBytesConsumed = 2; return SequenceValidity.Incomplete; ThreeBytesOfIncompleteMultiByteSequence: numBytesConsumed = 3; return SequenceValidity.Incomplete; } private static void EscapeString(ReadOnlySpan<char> value, Span<char> destination, JavaScriptEncoder encoder, ref int written) { // todo: issue #39523: add an Encode(ReadOnlySpan<char>) decode API to System.Text.Encodings.Web.TextEncoding to avoid utf16->utf8->utf16 conversion. Debug.Assert(encoder != null); // Convert char to byte. byte[] utf8DestinationArray = null; Span<byte> utf8Destination; int length = checked((value.Length) * JsonConstants.MaxExpansionFactorWhileTranscoding); if (length > JsonConstants.StackallocThreshold) { utf8DestinationArray = ArrayPool<byte>.Shared.Rent(length); utf8Destination = utf8DestinationArray; } else { unsafe { byte* ptr = stackalloc byte[JsonConstants.StackallocThreshold]; utf8Destination = new Span<byte>(ptr, JsonConstants.StackallocThreshold); } } ReadOnlySpan<byte> utf16Value = MemoryMarshal.AsBytes(value); OperationStatus toUtf8Status = ToUtf8(utf16Value, utf8Destination, out int bytesConsumed, out int bytesWritten); Debug.Assert(toUtf8Status != OperationStatus.DestinationTooSmall); Debug.Assert(toUtf8Status != OperationStatus.NeedMoreData); if (toUtf8Status != OperationStatus.Done) { if (utf8DestinationArray != null) { utf8Destination.Slice(0, bytesWritten).Clear(); ArrayPool<byte>.Shared.Return(utf8DestinationArray); } ThrowHelper.ThrowArgumentException_InvalidUTF8(utf16Value.Slice(bytesWritten)); } Debug.Assert(toUtf8Status == OperationStatus.Done); Debug.Assert(bytesConsumed == utf16Value.Length); // Escape the bytes. byte[] utf8ConvertedDestinationArray = null; Span<byte> utf8ConvertedDestination; length = checked(bytesWritten * JsonConstants.MaxExpansionFactorWhileEscaping); if (length > JsonConstants.StackallocThreshold) { utf8ConvertedDestinationArray = ArrayPool<byte>.Shared.Rent(length); utf8ConvertedDestination = utf8ConvertedDestinationArray; } else { unsafe { byte* ptr = stackalloc byte[JsonConstants.StackallocThreshold]; utf8ConvertedDestination = new Span<byte>(ptr, JsonConstants.StackallocThreshold); } } EscapeString(utf8Destination.Slice(0, bytesWritten), utf8ConvertedDestination, indexOfFirstByteToEscape: 0, encoder, out int convertedBytesWritten); if (utf8DestinationArray != null) { utf8Destination.Slice(0, bytesWritten).Clear(); ArrayPool<byte>.Shared.Return(utf8DestinationArray); } // Convert byte to char. #if BUILDING_INBOX_LIBRARY OperationStatus toUtf16Status = Utf8.ToUtf16(utf8ConvertedDestination.Slice(0, convertedBytesWritten), destination, out int bytesRead, out int charsWritten); Debug.Assert(toUtf16Status == OperationStatus.Done); Debug.Assert(bytesRead == convertedBytesWritten); #else string utf16 = JsonReaderHelper.GetTextFromUtf8(utf8ConvertedDestination.Slice(0, convertedBytesWritten)); utf16.AsSpan().CopyTo(destination); int charsWritten = utf16.Length; #endif written += charsWritten; if (utf8ConvertedDestinationArray != null) { utf8ConvertedDestination.Slice(0, written).Clear(); ArrayPool<byte>.Shared.Return(utf8ConvertedDestinationArray); } } public static void EscapeString(ReadOnlySpan<char> value, Span<char> destination, int indexOfFirstByteToEscape, JavaScriptEncoder encoder, out int written) { Debug.Assert(indexOfFirstByteToEscape >= 0 && indexOfFirstByteToEscape < value.Length); value.Slice(0, indexOfFirstByteToEscape).CopyTo(destination); written = indexOfFirstByteToEscape; int consumed = indexOfFirstByteToEscape; if (encoder != null) { destination = destination.Slice(indexOfFirstByteToEscape); value = value.Slice(indexOfFirstByteToEscape); EscapeString(value, destination, encoder, ref written); } else { // For performance when no encoder is specified, perform escaping here for Ascii and on the // first occurrence of a non-Ascii character, then call into the default encoder. while (consumed < value.Length) { char val = value[consumed]; if (IsAsciiValue(val)) { if (NeedsEscapingNoBoundsCheck(val)) { EscapeNextChars(val, destination, ref written); consumed++; } else { destination[written] = val; written++; consumed++; } } else { // Fall back to default encoder. destination = destination.Slice(written); value = value.Slice(consumed); EscapeString(value, destination, JavaScriptEncoder.Default, ref written); break; } } } } private static void EscapeNextChars(char value, Span<char> destination, ref int written) { Debug.Assert(IsAsciiValue(value)); destination[written++] = '\\'; switch ((byte)value) { case JsonConstants.Quote: // Optimize for the common quote case. destination[written++] = 'u'; destination[written++] = '0'; destination[written++] = '0'; destination[written++] = '2'; destination[written++] = '2'; break; case JsonConstants.LineFeed: destination[written++] = 'n'; break; case JsonConstants.CarriageReturn: destination[written++] = 'r'; break; case JsonConstants.Tab: destination[written++] = 't'; break; case JsonConstants.BackSlash: destination[written++] = '\\'; break; case JsonConstants.BackSpace: destination[written++] = 'b'; break; case JsonConstants.FormFeed: destination[written++] = 'f'; break; default: destination[written++] = 'u'; #if BUILDING_INBOX_LIBRARY int intChar = value; intChar.TryFormat(destination.Slice(written), out int charsWritten, HexFormatString); Debug.Assert(charsWritten == 4); written += charsWritten; #else written = WriteHex(value, destination, written); #endif break; } } /// <summary> /// A scalar that represents the Unicode replacement character U+FFFD. /// </summary> private const int ReplacementChar = 0xFFFD; #if !BUILDING_INBOX_LIBRARY private static int WriteHex(int value, Span<char> destination, int written) { destination[written++] = (char)Int32LsbToHexDigit(value >> 12); destination[written++] = (char)Int32LsbToHexDigit((int)((value >> 8) & 0xFU)); destination[written++] = (char)Int32LsbToHexDigit((int)((value >> 4) & 0xFU)); destination[written++] = (char)Int32LsbToHexDigit((int)(value & 0xFU)); return written; } /// <summary> /// Converts a number 0 - 15 to its associated hex character '0' - 'f' as byte. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static byte Int32LsbToHexDigit(int value) { Debug.Assert(value < 16); return (byte)((value < 10) ? ('0' + value) : ('a' + (value - 10))); } #endif } }
41.816038
169
0.523707
[ "MIT" ]
PRIMETSS/corefx
src/System.Text.Json/src/System/Text/Json/Writer/JsonWriterHelper.Escaping.cs
26,597
C#
//--------------------------------------------------------------------- // <copyright file="IDSPEnumerateTypesRule.cs" company=".NET Foundation"> // Copyright (c) .NET Foundation and Contributors. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- namespace DataWebRules { using System; using Microsoft.FxCop.Sdk; using System.Collections.Generic; /// <summary> /// This rule checks that only DataServiceWrapper.Types can call IsComplexTypeVisible() and IsEntityTypeVisible(). /// </summary> public class IDSPEnumerateTypesRule : BaseDataWebRule { private Method methodUnderCheck; /// <summary>Initializes a new <see cref="IDSPEnumerateTypesRule"/> instance.</summary> public IDSPEnumerateTypesRule() : base("IDSPEnumerateTypesRule") { } /// <summary>Visibility of targets to which this rule commonly applies.</summary> public override TargetVisibilities TargetVisibility { get { return TargetVisibilities.All; } } /// <summary>Checks type members.</summary> /// <param name="member">Member being checked.</param> /// <returns>A collection of problems found in <paramref name="member"/> or null.</returns> public override ProblemCollection Check(Member member) { Method method = member as Method; if (method == null) { return null; } methodUnderCheck = method; MethodCallFinder finder = new MethodCallFinder(MethodsNotAllowedOutsideMetadataPath.ToArray()); finder.Visit(method); if (!IsMethodSafeToEnumerateTypes(method.FullName)) { foreach (string metadataOnlyMethod in MethodsNotAllowedOutsideMetadataPath) { if (finder.Found(metadataOnlyMethod)) { this.Problems.Add(new Problem(GetResolution(method.FullName, metadataOnlyMethod))); } } } return Problems.Count > 0 ? Problems : null; } /// <summary> /// /// </summary> private static List<string> MethodsNotAllowedOutsideMetadataPath = new List<string>() { "Microsoft.OData.Service.Providers.DataServiceProviderWrapper.get_VisibleTypes", "Microsoft.OData.Service.Providers.DataServiceProviderWrapper.get_Types", "Microsoft.OData.Service.Providers.DataServiceProviderWrapper.get_ResourceSets", "Microsoft.OData.Service.Providers.DataServiceProviderWrapper.get_ServiceOperations", "Microsoft.OData.Service.Providers.IDataServiceProvider.get_Types", "Microsoft.OData.Service.Providers.IDataServiceProvider.get_ResourceSets", "Microsoft.OData.Service.Providers.IDataServiceProvider.get_ServiceOperations", }; /// <summary> /// /// </summary> private static List<string> MethodsSafeToEnumerateTypes = new List<string>() { "Microsoft.OData.Service.RequestDescription.UpdateMetadataVersion(Microsoft.OData.Service.Caching.DataServiceCacheItem,Microsoft.OData.Service.Providers.DataServiceProviderWrapper,Microsoft.OData.Service.Providers.BaseServiceProvider)", "Microsoft.OData.Service.Providers.ObjectContextServiceProvider.CheckConfigurationConsistency(Microsoft.OData.Service.DataServiceConfiguration)", "Microsoft.OData.Service.Providers.ObjectContextServiceProvider.GetMetadata(System.Xml.XmlWriter,Microsoft.OData.Service.Providers.DataServiceProviderWrapper,Microsoft.OData.Service.IDataService)", "Microsoft.OData.Service.Providers.ObjectContextServiceProvider+MetadataManager.#ctor(System.Data.Metadata.Edm.MetadataWorkspace,System.Data.Metadata.Edm.EntityContainer,Microsoft.OData.Service.Providers.DataServiceProviderWrapper,Microsoft.OData.Service.IDataService)", "Microsoft.OData.Service.Serializers.ServiceDocumentSerializer.WriteServiceDocument(Microsoft.OData.Service.Providers.DataServiceProviderWrapper)", "Microsoft.OData.Service.Providers.MetadataProviderEdmModel.GroupResourceTypesByNamespace(System.Boolean@,System.Boolean@)", "Microsoft.OData.Service.Providers.MetadataProviderEdmModel.EnsureStructuredTypes", "Microsoft.OData.Service.Providers.MetadataProviderEdmModel.PairUpNavigationProperties", "Microsoft.OData.Service.Providers.MetadataProviderEdmModel.EnsureEntityContainers", "Microsoft.OData.Service.Providers.DataServiceProviderWrapper.PopulateMetadataCacheItemForBuiltInProvider", "Microsoft.OData.Service.RequestDescription.UpdateMetadataVersion(Microsoft.OData.Service.Caching.DataServiceCacheItem,Microsoft.OData.Service.Providers.DataServiceProviderWrapper)" }; /// <summary> /// /// </summary> /// <param name="methodName"></param> /// <returns></returns> private bool IsMethodSafeToEnumerateTypes(string methodName) { return MethodsSafeToEnumerateTypes.Exists(s => s == methodName); } } }
50.943396
282
0.666667
[ "MIT" ]
OData/Extensions
tools/FxCopRules/IDSPEnumerateTypesRule.cs
5,402
C#
using Microsoft.AspNetCore.Mvc.RazorPages; namespace App.Pages { public class ContactModel : PageModel { public void OnGet() { } } }
15.454545
43
0.594118
[ "MIT" ]
andremachida/Microservices
src/WebApps/App/Pages/Contact.cshtml.cs
172
C#
using System; using System.ComponentModel; using System.Collections.Generic; using System.Linq; using System.Text; namespace $rootnamespace$ { public class $safeitemrootname$ { } }
14.307692
33
0.774194
[ "MIT" ]
IObsequious/Missing-Templates
src/ItemTemplates/Common/VsWPFInfrastructure/Class.cs
188
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a read-only list of <see cref="SyntaxTrivia"/>. /// </summary> [StructLayout(LayoutKind.Auto)] public readonly partial struct SyntaxTriviaList : IEquatable<SyntaxTriviaList>, IReadOnlyList<SyntaxTrivia> { public static SyntaxTriviaList Empty => default(SyntaxTriviaList); internal SyntaxTriviaList( in SyntaxToken token, GreenNode? node, int position, int index = 0 ) { Token = token; Node = node; Position = position; Index = index; } internal SyntaxTriviaList(in SyntaxToken token, GreenNode? node) { Token = token; Node = node; Position = token.Position; Index = 0; } public SyntaxTriviaList(SyntaxTrivia trivia) { Token = default(SyntaxToken); Node = trivia.UnderlyingNode; Position = 0; Index = 0; } /// <summary> /// Creates a list of trivia. /// </summary> /// <param name="trivias">An array of trivia.</param> public SyntaxTriviaList(params SyntaxTrivia[] trivias) : this(default, CreateNode(trivias), 0, 0) { } /// <summary> /// Creates a list of trivia. /// </summary> /// <param name="trivias">A sequence of trivia.</param> public SyntaxTriviaList(IEnumerable<SyntaxTrivia>? trivias) : this(default, SyntaxTriviaListBuilder.Create(trivias).Node, 0, 0) { } private static GreenNode? CreateNode(SyntaxTrivia[]? trivias) { if (trivias == null) { return null; } var builder = new SyntaxTriviaListBuilder(trivias.Length); builder.Add(trivias); return builder.ToList().Node; } internal SyntaxToken Token { get; } internal GreenNode? Node { get; } internal int Position { get; } internal int Index { get; } public int Count { get { return Node == null ? 0 : (Node.IsList ? Node.SlotCount : 1); } } public SyntaxTrivia ElementAt(int index) { return this[index]; } /// <summary> /// Gets the trivia at the specified index. /// </summary> /// <param name="index">The zero-based index of the trivia to get.</param> /// <returns>The token at the specified index.</returns> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="index" /> is less than 0.-or-<paramref name="index" /> is equal to or greater than <see cref="Count" />. </exception> public SyntaxTrivia this[int index] { get { if (Node != null) { if (Node.IsList) { if (unchecked((uint)index < (uint)Node.SlotCount)) { return new SyntaxTrivia( Token, Node.GetSlot(index), Position + Node.GetSlotOffset(index), Index + index ); } } else if (index == 0) { return new SyntaxTrivia(Token, Node, Position, Index); } } throw new ArgumentOutOfRangeException(nameof(index)); } } /// <summary> /// The absolute span of the list elements in characters, including the leading and trailing trivia of the first and last elements. /// </summary> public TextSpan FullSpan { get { if (Node == null) { return default(TextSpan); } return new TextSpan(this.Position, Node.FullWidth); } } /// <summary> /// The absolute span of the list elements in characters, not including the leading and trailing trivia of the first and last elements. /// </summary> public TextSpan Span { get { if (Node == null) { return default(TextSpan); } return TextSpan.FromBounds( Position + Node.GetLeadingTriviaWidth(), Position + Node.FullWidth - Node.GetTrailingTriviaWidth() ); } } /// <summary> /// Returns the first trivia in the list. /// </summary> /// <returns>The first trivia in the list.</returns> /// <exception cref="InvalidOperationException">The list is empty.</exception> public SyntaxTrivia First() { if (Any()) { return this[0]; } throw new InvalidOperationException(); } /// <summary> /// Returns the last trivia in the list. /// </summary> /// <returns>The last trivia in the list.</returns> /// <exception cref="InvalidOperationException">The list is empty.</exception> public SyntaxTrivia Last() { if (Any()) { return this[this.Count - 1]; } throw new InvalidOperationException(); } /// <summary> /// Does this list have any items. /// </summary> public bool Any() { return Node != null; } /// <summary> /// Returns a list which contains all elements of <see cref="SyntaxTriviaList"/> in reversed order. /// </summary> /// <returns><see cref="Reversed"/> which contains all elements of <see cref="SyntaxTriviaList"/> in reversed order</returns> public Reversed Reverse() { return new Reversed(this); } public Enumerator GetEnumerator() { return new Enumerator(in this); } public int IndexOf(SyntaxTrivia triviaInList) { for (int i = 0, n = this.Count; i < n; i++) { var trivia = this[i]; if (trivia == triviaInList) { return i; } } return -1; } internal int IndexOf(int rawKind) { for (int i = 0, n = this.Count; i < n; i++) { if (this[i].RawKind == rawKind) { return i; } } return -1; } /// <summary> /// Creates a new <see cref="SyntaxTriviaList"/> with the specified trivia added to the end. /// </summary> /// <param name="trivia">The trivia to add.</param> public SyntaxTriviaList Add(SyntaxTrivia trivia) { return Insert(this.Count, trivia); } /// <summary> /// Creates a new <see cref="SyntaxTriviaList"/> with the specified trivia added to the end. /// </summary> /// <param name="trivia">The trivia to add.</param> public SyntaxTriviaList AddRange(IEnumerable<SyntaxTrivia> trivia) { return InsertRange(this.Count, trivia); } /// <summary> /// Creates a new <see cref="SyntaxTriviaList"/> with the specified trivia inserted at the index. /// </summary> /// <param name="index">The index in the list to insert the trivia at.</param> /// <param name="trivia">The trivia to insert.</param> public SyntaxTriviaList Insert(int index, SyntaxTrivia trivia) { if (trivia == default(SyntaxTrivia)) { throw new ArgumentOutOfRangeException(nameof(trivia)); } return InsertRange(index, new[] { trivia }); } private static readonly ObjectPool<SyntaxTriviaListBuilder> s_builderPool = new ObjectPool<SyntaxTriviaListBuilder>(() => SyntaxTriviaListBuilder.Create()); private static SyntaxTriviaListBuilder GetBuilder() => s_builderPool.Allocate(); private static void ClearAndFreeBuilder(SyntaxTriviaListBuilder builder) { // It's possible someone might create a list with a huge amount of trivia // in it. We don't want to hold onto such items forever. So only cache // reasonably sized lists. In IDE testing, around 99% of all trivia lists // were 16 or less elements. const int MaxBuilderCount = 16; if (builder.Count <= MaxBuilderCount) { builder.Clear(); s_builderPool.Free(builder); } } /// <summary> /// Creates a new <see cref="SyntaxTriviaList"/> with the specified trivia inserted at the index. /// </summary> /// <param name="index">The index in the list to insert the trivia at.</param> /// <param name="trivia">The trivia to insert.</param> public SyntaxTriviaList InsertRange(int index, IEnumerable<SyntaxTrivia> trivia) { var thisCount = this.Count; if (index < 0 || index > thisCount) { throw new ArgumentOutOfRangeException(nameof(index)); } if (trivia == null) { throw new ArgumentNullException(nameof(trivia)); } // Just return ourselves if we're not being asked to add anything. var triviaCollection = trivia as ICollection<SyntaxTrivia>; if (triviaCollection != null && triviaCollection.Count == 0) { return this; } var builder = GetBuilder(); try { for (int i = 0; i < index; i++) { builder.Add(this[i]); } builder.AddRange(trivia); for (int i = index; i < thisCount; i++) { builder.Add(this[i]); } return builder.Count == thisCount ? this : builder.ToList(); } finally { ClearAndFreeBuilder(builder); } } /// <summary> /// Creates a new <see cref="SyntaxTriviaList"/> with the element at the specified index removed. /// </summary> /// <param name="index">The index identifying the element to remove.</param> public SyntaxTriviaList RemoveAt(int index) { if (index < 0 || index >= this.Count) { throw new ArgumentOutOfRangeException(nameof(index)); } var list = this.ToList(); list.RemoveAt(index); return new SyntaxTriviaList( default(SyntaxToken), GreenNode.CreateList(list, static n => n.RequiredUnderlyingNode), 0, 0 ); } /// <summary> /// Creates a new <see cref="SyntaxTriviaList"/> with the specified element removed. /// </summary> /// <param name="triviaInList">The trivia element to remove.</param> public SyntaxTriviaList Remove(SyntaxTrivia triviaInList) { var index = this.IndexOf(triviaInList); if (index >= 0 && index < this.Count) { return this.RemoveAt(index); } return this; } /// <summary> /// Creates a new <see cref="SyntaxTriviaList"/> with the specified element replaced with new trivia. /// </summary> /// <param name="triviaInList">The trivia element to replace.</param> /// <param name="newTrivia">The trivia to replace the element with.</param> public SyntaxTriviaList Replace(SyntaxTrivia triviaInList, SyntaxTrivia newTrivia) { if (newTrivia == default(SyntaxTrivia)) { throw new ArgumentOutOfRangeException(nameof(newTrivia)); } return ReplaceRange(triviaInList, new[] { newTrivia }); } /// <summary> /// Creates a new <see cref="SyntaxTriviaList"/> with the specified element replaced with new trivia. /// </summary> /// <param name="triviaInList">The trivia element to replace.</param> /// <param name="newTrivia">The trivia to replace the element with.</param> public SyntaxTriviaList ReplaceRange( SyntaxTrivia triviaInList, IEnumerable<SyntaxTrivia> newTrivia ) { var index = this.IndexOf(triviaInList); if (index >= 0 && index < this.Count) { var list = this.ToList(); list.RemoveAt(index); list.InsertRange(index, newTrivia); return new SyntaxTriviaList( default(SyntaxToken), GreenNode.CreateList(list, static n => n.RequiredUnderlyingNode), 0, 0 ); } throw new ArgumentOutOfRangeException(nameof(triviaInList)); } // for debugging private SyntaxTrivia[] Nodes => this.ToArray(); IEnumerator<SyntaxTrivia> IEnumerable<SyntaxTrivia>.GetEnumerator() { if (Node == null) { return SpecializedCollections.EmptyEnumerator<SyntaxTrivia>(); } return new EnumeratorImpl(in this); } IEnumerator IEnumerable.GetEnumerator() { if (Node == null) { return SpecializedCollections.EmptyEnumerator<SyntaxTrivia>(); } return new EnumeratorImpl(in this); } /// <summary> /// get the green node at the specific slot /// </summary> private GreenNode? GetGreenNodeAt(int i) { Debug.Assert(Node is object); return GetGreenNodeAt(Node, i); } private static GreenNode? GetGreenNodeAt(GreenNode node, int i) { Debug.Assert(node.IsList || (i == 0 && !node.IsList)); return node.IsList ? node.GetSlot(i) : node; } public bool Equals(SyntaxTriviaList other) { return Node == other.Node && Index == other.Index && Token.Equals(other.Token); } public static bool operator ==(SyntaxTriviaList left, SyntaxTriviaList right) { return left.Equals(right); } public static bool operator !=(SyntaxTriviaList left, SyntaxTriviaList right) { return !left.Equals(right); } public override bool Equals(object? obj) { return (obj is SyntaxTriviaList list) && Equals(list); } public override int GetHashCode() { return Hash.Combine(Token.GetHashCode(), Hash.Combine(Node, Index)); } /// <summary> /// Copy <paramref name="count"/> number of items starting at <paramref name="offset"/> from this list into <paramref name="array"/> starting at <paramref name="arrayOffset"/>. /// </summary> internal void CopyTo(int offset, SyntaxTrivia[] array, int arrayOffset, int count) { if (offset < 0 || count < 0 || this.Count < offset + count) { throw new IndexOutOfRangeException(); } if (count == 0) { return; } // get first one without creating any red node var first = this[offset]; array[arrayOffset] = first; // calculate trivia position from the first ourselves from now on var position = first.Position; var current = first; for (int i = 1; i < count; i++) { position += current.FullWidth; current = new SyntaxTrivia(Token, GetGreenNodeAt(offset + i), position, Index + i); array[arrayOffset + i] = current; } } public override string ToString() { return Node != null ? Node.ToString() : string.Empty; } public string ToFullString() { return Node != null ? Node.ToFullString() : string.Empty; } public static SyntaxTriviaList Create(SyntaxTrivia trivia) { return new SyntaxTriviaList(trivia); } } }
32.499072
184
0.518525
[ "MIT" ]
belav/roslyn
src/Compilers/Core/Portable/Syntax/SyntaxTriviaList.cs
17,519
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HolyHigh.Geometry { /// <summary> /// Plane equation definition. /// </summary> public struct PlaneEquation { public double X { get; set; } public double Y { get; set; } public double Z { get; set; } public double D { get; set; } /// <summary> /// Plane's coefficients constructor. Equation form: ax + by + cz + d = 0. /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="z"></param> /// <param name="d"></param> public PlaneEquation(double x, double y, double z, double d) { X = x; Y = y; Z = z; D = d; var v = new Vector3D(X, Y, Z); var length = v.Length; if (Math.Abs(1 - length) > Utility.EPSILON) { if (v.Normalize()) { X = v.X; Y = v.Y; Z = v.Z; D = D / length; } else throw new ArgumentException(); } } public PlaneEquation(double[] para) { X = para[0]; Y = para[1]; Z = para[2]; D = para[3]; var v = new Vector3D(X, Y, Z); var length = v.Length; if (Math.Abs(1 - length) > Utility.EPSILON) { if (v.Normalize()) { X = v.X; Y = v.Y; Z = v.Z; D = D / length; } else throw new ArgumentException(); } } public PlaneEquation(Point3D point, Vector3D normal) : this() { if (!Create(point, normal)) throw new ArgumentException(); } public bool Create(Point3D point, Vector3D normal) { bool rc = false; if (point.IsValid && normal.IsValid) { X = normal.X; Y = normal.Y; Z = normal.Z; Vector3D v = new Vector3D(X, Y, Z); rc = (Math.Abs(1.0 - v.Length) > Utility.EPSILON) ? v.Normalize() : true; D = -(X * point.X + Y * point.Y + Z * point.Z); } return rc; } public double ValueAt(Point3D p) { return (X * p.X + Y * p.Y + Z * p.Z + D); } public bool IsValid { get { return Utility.IsValidDouble(X) && Utility.IsValidDouble(Y) && Utility.IsValidDouble(Z) && Utility.IsValidDouble(D) && (X != 0.0 || Y != 0.0 || Z != 0.0); } } public Vector3D UnitNormal() { Vector3D normal = new Vector3D(X, Y, Z); if (false == normal.IsUnitVector && false == normal.Normalize()) normal = Vector3D.Zero; return normal; } } }
28.963303
170
0.417485
[ "MIT" ]
xk6338062/HolyHigh.Geometry
HolyHigh.Geometry/PlaneEquation.cs
3,159
C#
using Newtonsoft.Json; using DiscordBot.Interfaces; using DiscordBot.Models; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Discord.WebSocket; namespace DiscordBot.Handlers { public class GuildHandler { public static Dictionary<ulong, GuildModel> GuildConfigs { get; set; } = new Dictionary<ulong, GuildModel>(); public const string configPath = "files/GuildConfig.json"; public static async Task SaveAsync<T>(Dictionary<ulong, T> configs) where T : IServer => File.WriteAllText(configPath, await Task.Run(() => JsonConvert.SerializeObject(configs, Formatting.Indented)).ConfigureAwait(false)); public static async Task<Dictionary<ulong, T>> LoadServerConfigsAsync<T>() where T : IServer, new() { if (File.Exists(configPath)) { return JsonConvert.DeserializeObject<Dictionary<ulong, T>>(File.ReadAllText(configPath)); } var newConfig = new Dictionary<ulong, T>(); await SaveAsync(newConfig); return newConfig; } internal static async Task DeleteGuildConfig(SocketGuild Guild) { if (GuildHandler.GuildConfigs.ContainsKey(Guild.Id)) { GuildHandler.GuildConfigs.Remove(Guild.Id); } await GuildHandler.SaveAsync(GuildHandler.GuildConfigs); } internal static async Task HandleGuildConfigAsync(SocketGuild Guild) { var CreateConfig = new GuildModel(); if (!GuildHandler.GuildConfigs.ContainsKey(Guild.Id)) { GuildHandler.GuildConfigs.Add(Guild.Id, CreateConfig); } await GuildHandler.SaveAsync(GuildHandler.GuildConfigs); } } }
36.32
148
0.64207
[ "MIT" ]
skybro6789/DiscordBotTemplate
src/DiscordBot/Core/Services/Handlers/GuildHandler.cs
1,818
C#
using Api.Data.Context; using Api.Data.Repositories; using Api.Domain.Entities; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; using Api.Domain.Interfaces.Repositories; using Microsoft.Extensions.Logging; namespace Api.Data.Implementations { [ExcludeFromCodeCoverage] public class PhoneImplementations : BaseRepository<PhoneEntity>, IPhoneRepository { private readonly DbSet<PhoneEntity> _dataSet; public PhoneImplementations(ILogger logger, DataContext context) : base(logger, context) { _dataSet = context.Set<PhoneEntity>(); } public async Task<IEnumerable<PhoneEntity>> SelectByUserAsync(Guid id) { return await _dataSet.AsNoTracking().Where(u => u.UserId.Equals(id)).ToListAsync(); } } }
29.645161
96
0.729053
[ "MIT" ]
fabioborges-ti/api-netcore5
src/Api.Data/Implementations/PhoneImplementations.cs
921
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("LFS_Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("LFS_Test")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0c61eef1-2ae3-4084-bfa2-ae558281691e")] // 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.405405
84
0.746387
[ "MIT" ]
karmoka/LfsHelper
DirectoryWatcherTest/LFS_Test/Properties/AssemblyInfo.cs
1,387
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; #if UNITY_EDITOR using UnityEditor; #endif using UnityEngine.UI; [System.Serializable] public class UnityEvent_OnProgress : UnityEvent <float> {} public class PopTaskProgressBar : MonoBehaviour { public UnityEvent_OnProgress OnProgress; public UnityEvent OnComplete; [Header("UI progress bar")] public Slider ProgressSlider; public Button CancelButton; public Text DescriptionText; string ProgressName; int CurrentStep; bool Cancelled; uint StepCount; public void InitProgress(string ProgressName,uint StepCount) { this.ProgressName = ProgressName; CurrentStep = -1; Cancelled = false; this.StepCount = StepCount; if (ProgressSlider != null) { ProgressSlider.maxValue = StepCount; ProgressSlider.minValue = 0; ProgressSlider.value = 0; ProgressSlider.wholeNumbers = true; } if ( DescriptionText != null ) { DescriptionText.text = ProgressName; } if ( CancelButton != null ) { UnityAction Cancel = () => { Cancelled = true; }; CancelButton.onClick.AddListener( Cancel ); } } public void UpdateProgress(string Description) { CurrentStep++; float Progress = CurrentStep / (float)StepCount; try { OnProgress.Invoke(Progress); } catch (System.Exception e) { Debug.LogException( e ); } // update editorui #if UNITY_EDITOR if ( EditorUtility.DisplayCancelableProgressBar( ProgressName, Description, Progress ) ) { Cancelled = true; } #endif // update ui if ( ProgressSlider != null ) { ProgressSlider.value = CurrentStep; } if ( DescriptionText != null ) { DescriptionText.text = Description; } if (Cancelled) { FinishProgress(false); throw new System.Exception( ProgressName + " cancelled"); } } public void FinishProgress(bool Success=true) { #if UNITY_EDITOR EditorUtility.ClearProgressBar(); #endif if ( DescriptionText != null ) { if ( Success ) DescriptionText.text = ProgressName + " complete"; else DescriptionText.text = ProgressName + " failed"; } if ( ProgressSlider != null ) { if ( Success ) ProgressSlider.value = ProgressSlider.maxValue; } try { if ( Success ) OnComplete.Invoke(); } catch (System.Exception e) { Debug.LogException( e ); } } }
17.352518
90
0.682421
[ "MIT" ]
SoylentGraham/PopUnityCommon
PopTaskProgressBar.cs
2,412
C#
using System.Text; using Loon.Core.Geom; using Loon.Core.Graphics.Opengl; using Loon.Utils; namespace Loon.Core.Graphics.Component { public class Print : LRelease { private int index, offset, font, tmp_font; private int fontSizeDouble; private char text; private char[] showMessages; private int iconWidth; private LColor fontColor = LColor.white; private int interceptMaxString; private int interceptCount; private int messageLength = 10; private string messages; private bool onComplete, newLine, visible; private StringBuilder messageBuffer; private int width, height, leftOffset, topOffset, next, messageCount; private float alpha; private int size, wait, tmp_left, left, fontSize, fontHeight; private Vector2f vector; private LTexture creeseIcon; private LSTRFont strings; private bool isEnglish, isLeft, isWait; private float iconX, iconY; private int lazyHashCade = 1; public Print(Vector2f vector, LFont font, int width, int height):this("", font, vector, width, height) { } public Print(string context, LFont font, Vector2f vector, int width, int height) { this.messageBuffer = new StringBuilder(messageLength); this.SetMessage(context, font); this.vector = vector; this.width = width; this.height = height; this.wait = 0; this.isWait = false; } public void SetMessage(string context, LFont font) { SetMessage(context, font, false); } public void SetMessage(string context, LFont font, bool isComplete) { if (strings != null) { strings.Dispose(); } this.strings = new LSTRFont(font, context); this.lazyHashCade = 1; this.wait = 0; this.visible = false; this.showMessages = new char[] { '\0' }; this.interceptMaxString = 0; this.next = 0; this.messageCount = 0; this.interceptCount = 0; this.size = 0; this.tmp_left = 0; this.left = 0; this.fontSize = 0; this.fontHeight = 0; this.messages = context; this.next = context.Length; this.onComplete = false; this.newLine = false; this.messageCount = 0; this.messageBuffer.Clear(); if (isComplete) { this.Complete(); } this.visible = true; } public string GetMessage() { return messages; } private LColor GetColor(char flagName) { if ('r' == flagName || 'R' == flagName) { return LColor.red; } if ('b' == flagName || 'B' == flagName) { return LColor.black; } if ('l' == flagName || 'L' == flagName) { return LColor.blue; } if ('g' == flagName || 'G' == flagName) { return LColor.green; } if ('o' == flagName || 'O' == flagName) { return LColor.orange; } if ('y' == flagName || 'Y' == flagName) { return LColor.yellow; } if ('m' == flagName || 'M' == flagName) { return LColor.magenta; } return null; } public void Draw(GLEx g) { Draw(g, LColor.white); } private void DrawMessage(GLEx gl, LColor old) { if (!visible) { return; } if (strings == null) { return; } lock (showMessages) { this.size = showMessages.Length; this.fontSize = (isEnglish) ? strings.GetSize() / 2 : gl.GetFont() .GetSize(); this.fontHeight = strings.GetHeight(); this.tmp_left = isLeft ? 0 : (width - (fontSize * messageLength)) / 2 - (int)(fontSize * 1.5); this.left = tmp_left; this.index = offset = font = tmp_font = 0; this.fontSizeDouble = fontSize * 2; int hashCode = 1; hashCode = LSystem.Unite(hashCode, size); hashCode = LSystem.Unite(hashCode, left); hashCode = LSystem.Unite(hashCode, fontSize); hashCode = LSystem.Unite(hashCode, fontHeight); if (strings == null) { return; } if (hashCode == lazyHashCade) { strings.PostCharCache(); if (iconX != 0 && iconY != 0) { gl.DrawTexture(creeseIcon, iconX, iconY); } return; } strings.StartChar(); fontColor = old; for (int i = 0; i < size; i++) { text = showMessages[i]; if (text == '\0') { continue; } if (interceptCount < interceptMaxString) { interceptCount++; continue; } else { interceptMaxString = 0; interceptCount = 0; } if (showMessages[i] == 'n' && showMessages[(i > 0) ? i - 1 : 0] == '\\') { index = 0; left = tmp_left; offset++; continue; } else if (text == '\n') { index = 0; left = tmp_left; offset++; continue; } else if (text == '<') { LColor color = GetColor(showMessages[(i < size - 1) ? i + 1 : i]); if (color != null) { interceptMaxString = 1; fontColor = color; } continue; } else if (showMessages[(i > 0) ? i - 1 : i] == '<' && GetColor(text) != null) { continue; } else if (text == '/') { if (showMessages[(i < size - 1) ? i + 1 : i] == '>') { interceptMaxString = 1; fontColor = old; } continue; } else if (index > messageLength) { index = 0; left = tmp_left; offset++; newLine = false; } else if (text == '\\') { continue; } tmp_font = strings.CharWidth(text); if (System.Char.IsLetter(text)) { if (tmp_font < fontSize) { font = fontSize; } else { font = tmp_font; } } else { font = fontSize; } left += font; if (i != size - 1) { strings.AddChar(text, vector.x + left + leftOffset, (offset * fontHeight) + vector.y + fontSizeDouble + topOffset - font - 2, fontColor); } else if (!newLine && !onComplete) { iconX = vector.x + left + leftOffset + iconWidth ; iconY = (offset * fontHeight) + vector.y + fontSize + topOffset + strings.GetAscent(); if (iconX != 0 && iconY != 0) { gl.DrawTexture(creeseIcon, iconX, iconY); } } index++; } strings.StopChar(); strings.SaveCharCache(); lazyHashCade = hashCode; if (messageCount == next) { onComplete = true; } } } public void Draw(GLEx g, LColor old) { if (!visible) { return; } alpha = g.GetAlpha(); if (alpha > 0 && alpha < 1) { g.SetAlpha(1.0f); } DrawMessage(g, old); if (alpha > 0 && alpha < 1) { g.SetAlpha(alpha); } } public void SetX(int x) { vector.SetX(x); } public void SetY(int y) { vector.SetY(y); } public int GetX() { return vector.X(); } public int GetY() { return vector.Y(); } public void Complete() { lock (showMessages) { this.onComplete = true; this.messageCount = messages.Length; this.next = messageCount; this.showMessages = (messages + '_').ToCharArray(); this.size = showMessages.Length; } } public bool IsComplete() { if (isWait) { if (onComplete) { wait++; } return onComplete && wait > 100; } return onComplete; } public bool Next() { lock (messageBuffer) { if (!onComplete) { if (messageCount == next) { onComplete = true; return false; } if (messageBuffer.Length > 0) { messageBuffer.Remove(messageBuffer.Length - 1, messageBuffer.Length - (messageBuffer.Length - 1)); } this.messageBuffer.Append(messages[messageCount]); this.messageBuffer.Append('_'); this.showMessages = messageBuffer.ToString().ToCharArray(); this.size = showMessages.Length; this.messageCount++; } else { return false; } return true; } } public LTexture GetCreeseIcon() { return creeseIcon; } public void SetCreeseIcon(LTexture icon) { if (this.creeseIcon != null) { creeseIcon.Destroy(); creeseIcon = null; } this.creeseIcon = icon; if (icon == null) { return; } this.iconWidth = icon.GetWidth(); } public int GetMessageLength() { return messageLength; } public void SetMessageLength(int messageLength) { this.messageLength = (messageLength - 4); } public int GetHeight() { return height; } public void SetHeight(int height) { this.height = height; } public int GetWidth() { return width; } public void SetWidth(int width) { this.width = width; } public int GetLeftOffset() { return leftOffset; } public void SetLeftOffset(int leftOffset) { this.leftOffset = leftOffset; } public int GetTopOffset() { return topOffset; } public void SetTopOffset(int topOffset) { this.topOffset = topOffset; } public bool IsEnglish() { return isEnglish; } public void SetEnglish(bool isEnglish) { this.isEnglish = isEnglish; } public bool IsVisible() { return visible; } public void SetVisible(bool visible) { this.visible = visible; } public bool IsLeft() { return isLeft; } public void SetLeft(bool isLeft) { this.isLeft = isLeft; } public bool IsWait() { return isWait; } public void SetWait(bool isWait) { this.isWait = isWait; } public void Dispose() { if (strings != null) { strings.Dispose(); strings = null; } } } }
25.57173
122
0.44559
[ "Apache-2.0" ]
TheMadTitanSkid/LGame
C#/WindowsPhone/LGame-XNA-lib/Loon.Core.Graphics.Component/Print.cs
12,121
C#
using System.Collections; using System.Collections.Generic; using Assets.Scripts.Constants; using UnityEngine; using static Assets.Scripts.Constants.enums; //Fireball Games * * * PetrZavodny.com [CreateAssetMenu(fileName = "CourseBlock", menuName = "Hlas/CourseBlock")] public class CourseBlock : ScriptableObject { #pragma warning disable 649, 414 [SerializeField] string nameOfBlock; [SerializeField] CourseId courseId; [SerializeField] AudioClip clip; public string NameOfBlock { get => nameOfBlock; } public CourseId CourseId { get => courseId; } #pragma warning restore 649, 414 public float GetClipLength() { return clip.length; } public AudioClip GetClip() { return clip; } }
24.16129
74
0.715621
[ "Unlicense" ]
Ankhtepot/Hlas
Assets/Scripts/CourseBlock.cs
751
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace Movegen_dotNET.Sliders { public static class Switch { public static ulong GetSliderHCond(int SliderSquare, ulong occupy) { ulong result = 0; switch (SliderSquare) { case 0: result = 2ul; if ((occupy & 2ul) == 0) result |= 4ul; if ((occupy & 6ul) == 0) result |= 8ul; if ((occupy & 14ul) == 0) result |= 16ul; if ((occupy & 30ul) == 0) result |= 32ul; if ((occupy & 62ul) == 0) result |= 64ul; if ((occupy & 126ul) == 0) result |= 128ul; return result; case 1: result = 5ul; if ((occupy & 4ul) == 0) result |= 8ul; if ((occupy & 12ul) == 0) result |= 16ul; if ((occupy & 28ul) == 0) result |= 32ul; if ((occupy & 60ul) == 0) result |= 64ul; if ((occupy & 124ul) == 0) result |= 128ul; return result; case 2: result = 10ul; if ((occupy & 2ul) == 0) result |= 1ul; if ((occupy & 8ul) == 0) result |= 16ul; if ((occupy & 24ul) == 0) result |= 32ul; if ((occupy & 56ul) == 0) result |= 64ul; if ((occupy & 120ul) == 0) result |= 128ul; return result; case 3: result = 20ul; if ((occupy & 4ul) == 0) result |= 2ul; if ((occupy & 6ul) == 0) result |= 1ul; if ((occupy & 16ul) == 0) result |= 32ul; if ((occupy & 48ul) == 0) result |= 64ul; if ((occupy & 112ul) == 0) result |= 128ul; return result; case 4: result = 40ul; if ((occupy & 8ul) == 0) result |= 4ul; if ((occupy & 12ul) == 0) result |= 2ul; if ((occupy & 14ul) == 0) result |= 1ul; if ((occupy & 32ul) == 0) result |= 64ul; if ((occupy & 96ul) == 0) result |= 128ul; return result; case 5: result = 80ul; if ((occupy & 16ul) == 0) result |= 8ul; if ((occupy & 24ul) == 0) result |= 4ul; if ((occupy & 28ul) == 0) result |= 2ul; if ((occupy & 30ul) == 0) result |= 1ul; if ((occupy & 64ul) == 0) result |= 128ul; return result; case 6: result = 160ul; if ((occupy & 32ul) == 0) result |= 16ul; if ((occupy & 48ul) == 0) result |= 8ul; if ((occupy & 56ul) == 0) result |= 4ul; if ((occupy & 60ul) == 0) result |= 2ul; if ((occupy & 62ul) == 0) result |= 1ul; return result; case 7: result = 64ul; if ((occupy & 64ul) == 0) result |= 32ul; if ((occupy & 96ul) == 0) result |= 16ul; if ((occupy & 112ul) == 0) result |= 8ul; if ((occupy & 120ul) == 0) result |= 4ul; if ((occupy & 124ul) == 0) result |= 2ul; if ((occupy & 126ul) == 0) result |= 1ul; return result; case 8: result = 512ul; if ((occupy & 512ul) == 0) result |= 1024ul; if ((occupy & 1536ul) == 0) result |= 2048ul; if ((occupy & 3584ul) == 0) result |= 4096ul; if ((occupy & 7680ul) == 0) result |= 8192ul; if ((occupy & 15872ul) == 0) result |= 16384ul; if ((occupy & 32256ul) == 0) result |= 32768ul; return result; case 9: result = 1280ul; if ((occupy & 1024ul) == 0) result |= 2048ul; if ((occupy & 3072ul) == 0) result |= 4096ul; if ((occupy & 7168ul) == 0) result |= 8192ul; if ((occupy & 15360ul) == 0) result |= 16384ul; if ((occupy & 31744ul) == 0) result |= 32768ul; return result; case 10: result = 2560ul; if ((occupy & 512ul) == 0) result |= 256ul; if ((occupy & 2048ul) == 0) result |= 4096ul; if ((occupy & 6144ul) == 0) result |= 8192ul; if ((occupy & 14336ul) == 0) result |= 16384ul; if ((occupy & 30720ul) == 0) result |= 32768ul; return result; case 11: result = 5120ul; if ((occupy & 1024ul) == 0) result |= 512ul; if ((occupy & 1536ul) == 0) result |= 256ul; if ((occupy & 4096ul) == 0) result |= 8192ul; if ((occupy & 12288ul) == 0) result |= 16384ul; if ((occupy & 28672ul) == 0) result |= 32768ul; return result; case 12: result = 10240ul; if ((occupy & 2048ul) == 0) result |= 1024ul; if ((occupy & 3072ul) == 0) result |= 512ul; if ((occupy & 3584ul) == 0) result |= 256ul; if ((occupy & 8192ul) == 0) result |= 16384ul; if ((occupy & 24576ul) == 0) result |= 32768ul; return result; case 13: result = 20480ul; if ((occupy & 4096ul) == 0) result |= 2048ul; if ((occupy & 6144ul) == 0) result |= 1024ul; if ((occupy & 7168ul) == 0) result |= 512ul; if ((occupy & 7680ul) == 0) result |= 256ul; if ((occupy & 16384ul) == 0) result |= 32768ul; return result; case 14: result = 40960ul; if ((occupy & 8192ul) == 0) result |= 4096ul; if ((occupy & 12288ul) == 0) result |= 2048ul; if ((occupy & 14336ul) == 0) result |= 1024ul; if ((occupy & 15360ul) == 0) result |= 512ul; if ((occupy & 15872ul) == 0) result |= 256ul; return result; case 15: result = 16384ul; if ((occupy & 16384ul) == 0) result |= 8192ul; if ((occupy & 24576ul) == 0) result |= 4096ul; if ((occupy & 28672ul) == 0) result |= 2048ul; if ((occupy & 30720ul) == 0) result |= 1024ul; if ((occupy & 31744ul) == 0) result |= 512ul; if ((occupy & 32256ul) == 0) result |= 256ul; return result; case 16: result = 131072ul; if ((occupy & 131072ul) == 0) result |= 262144ul; if ((occupy & 393216ul) == 0) result |= 524288ul; if ((occupy & 917504ul) == 0) result |= 1048576ul; if ((occupy & 1966080ul) == 0) result |= 2097152ul; if ((occupy & 4063232ul) == 0) result |= 4194304ul; if ((occupy & 8257536ul) == 0) result |= 8388608ul; return result; case 17: result = 327680ul; if ((occupy & 262144ul) == 0) result |= 524288ul; if ((occupy & 786432ul) == 0) result |= 1048576ul; if ((occupy & 1835008ul) == 0) result |= 2097152ul; if ((occupy & 3932160ul) == 0) result |= 4194304ul; if ((occupy & 8126464ul) == 0) result |= 8388608ul; return result; case 18: result = 655360ul; if ((occupy & 131072ul) == 0) result |= 65536ul; if ((occupy & 524288ul) == 0) result |= 1048576ul; if ((occupy & 1572864ul) == 0) result |= 2097152ul; if ((occupy & 3670016ul) == 0) result |= 4194304ul; if ((occupy & 7864320ul) == 0) result |= 8388608ul; return result; case 19: result = 1310720ul; if ((occupy & 262144ul) == 0) result |= 131072ul; if ((occupy & 393216ul) == 0) result |= 65536ul; if ((occupy & 1048576ul) == 0) result |= 2097152ul; if ((occupy & 3145728ul) == 0) result |= 4194304ul; if ((occupy & 7340032ul) == 0) result |= 8388608ul; return result; case 20: result = 2621440ul; if ((occupy & 524288ul) == 0) result |= 262144ul; if ((occupy & 786432ul) == 0) result |= 131072ul; if ((occupy & 917504ul) == 0) result |= 65536ul; if ((occupy & 2097152ul) == 0) result |= 4194304ul; if ((occupy & 6291456ul) == 0) result |= 8388608ul; return result; case 21: result = 5242880ul; if ((occupy & 1048576ul) == 0) result |= 524288ul; if ((occupy & 1572864ul) == 0) result |= 262144ul; if ((occupy & 1835008ul) == 0) result |= 131072ul; if ((occupy & 1966080ul) == 0) result |= 65536ul; if ((occupy & 4194304ul) == 0) result |= 8388608ul; return result; case 22: result = 10485760ul; if ((occupy & 2097152ul) == 0) result |= 1048576ul; if ((occupy & 3145728ul) == 0) result |= 524288ul; if ((occupy & 3670016ul) == 0) result |= 262144ul; if ((occupy & 3932160ul) == 0) result |= 131072ul; if ((occupy & 4063232ul) == 0) result |= 65536ul; return result; case 23: result = 4194304ul; if ((occupy & 4194304ul) == 0) result |= 2097152ul; if ((occupy & 6291456ul) == 0) result |= 1048576ul; if ((occupy & 7340032ul) == 0) result |= 524288ul; if ((occupy & 7864320ul) == 0) result |= 262144ul; if ((occupy & 8126464ul) == 0) result |= 131072ul; if ((occupy & 8257536ul) == 0) result |= 65536ul; return result; case 24: result = 33554432ul; if ((occupy & 33554432ul) == 0) result |= 67108864ul; if ((occupy & 100663296ul) == 0) result |= 134217728ul; if ((occupy & 234881024ul) == 0) result |= 268435456ul; if ((occupy & 503316480ul) == 0) result |= 536870912ul; if ((occupy & 1040187392ul) == 0) result |= 1073741824ul; if ((occupy & 2113929216ul) == 0) result |= 2147483648ul; return result; case 25: result = 83886080ul; if ((occupy & 67108864ul) == 0) result |= 134217728ul; if ((occupy & 201326592ul) == 0) result |= 268435456ul; if ((occupy & 469762048ul) == 0) result |= 536870912ul; if ((occupy & 1006632960ul) == 0) result |= 1073741824ul; if ((occupy & 2080374784ul) == 0) result |= 2147483648ul; return result; case 26: result = 167772160ul; if ((occupy & 33554432ul) == 0) result |= 16777216ul; if ((occupy & 134217728ul) == 0) result |= 268435456ul; if ((occupy & 402653184ul) == 0) result |= 536870912ul; if ((occupy & 939524096ul) == 0) result |= 1073741824ul; if ((occupy & 2013265920ul) == 0) result |= 2147483648ul; return result; case 27: result = 335544320ul; if ((occupy & 67108864ul) == 0) result |= 33554432ul; if ((occupy & 100663296ul) == 0) result |= 16777216ul; if ((occupy & 268435456ul) == 0) result |= 536870912ul; if ((occupy & 805306368ul) == 0) result |= 1073741824ul; if ((occupy & 1879048192ul) == 0) result |= 2147483648ul; return result; case 28: result = 671088640ul; if ((occupy & 134217728ul) == 0) result |= 67108864ul; if ((occupy & 201326592ul) == 0) result |= 33554432ul; if ((occupy & 234881024ul) == 0) result |= 16777216ul; if ((occupy & 536870912ul) == 0) result |= 1073741824ul; if ((occupy & 1610612736ul) == 0) result |= 2147483648ul; return result; case 29: result = 1342177280ul; if ((occupy & 268435456ul) == 0) result |= 134217728ul; if ((occupy & 402653184ul) == 0) result |= 67108864ul; if ((occupy & 469762048ul) == 0) result |= 33554432ul; if ((occupy & 503316480ul) == 0) result |= 16777216ul; if ((occupy & 1073741824ul) == 0) result |= 2147483648ul; return result; case 30: result = 2684354560ul; if ((occupy & 536870912ul) == 0) result |= 268435456ul; if ((occupy & 805306368ul) == 0) result |= 134217728ul; if ((occupy & 939524096ul) == 0) result |= 67108864ul; if ((occupy & 1006632960ul) == 0) result |= 33554432ul; if ((occupy & 1040187392ul) == 0) result |= 16777216ul; return result; case 31: result = 1073741824ul; if ((occupy & 1073741824ul) == 0) result |= 536870912ul; if ((occupy & 1610612736ul) == 0) result |= 268435456ul; if ((occupy & 1879048192ul) == 0) result |= 134217728ul; if ((occupy & 2013265920ul) == 0) result |= 67108864ul; if ((occupy & 2080374784ul) == 0) result |= 33554432ul; if ((occupy & 2113929216ul) == 0) result |= 16777216ul; return result; case 32: result = 8589934592ul; if ((occupy & 8589934592ul) == 0) result |= 17179869184ul; if ((occupy & 25769803776ul) == 0) result |= 34359738368ul; if ((occupy & 60129542144ul) == 0) result |= 68719476736ul; if ((occupy & 128849018880ul) == 0) result |= 137438953472ul; if ((occupy & 266287972352ul) == 0) result |= 274877906944ul; if ((occupy & 541165879296ul) == 0) result |= 549755813888ul; return result; case 33: result = 21474836480ul; if ((occupy & 17179869184ul) == 0) result |= 34359738368ul; if ((occupy & 51539607552ul) == 0) result |= 68719476736ul; if ((occupy & 120259084288ul) == 0) result |= 137438953472ul; if ((occupy & 257698037760ul) == 0) result |= 274877906944ul; if ((occupy & 532575944704ul) == 0) result |= 549755813888ul; return result; case 34: result = 42949672960ul; if ((occupy & 8589934592ul) == 0) result |= 4294967296ul; if ((occupy & 34359738368ul) == 0) result |= 68719476736ul; if ((occupy & 103079215104ul) == 0) result |= 137438953472ul; if ((occupy & 240518168576ul) == 0) result |= 274877906944ul; if ((occupy & 515396075520ul) == 0) result |= 549755813888ul; return result; case 35: result = 85899345920ul; if ((occupy & 17179869184ul) == 0) result |= 8589934592ul; if ((occupy & 25769803776ul) == 0) result |= 4294967296ul; if ((occupy & 68719476736ul) == 0) result |= 137438953472ul; if ((occupy & 206158430208ul) == 0) result |= 274877906944ul; if ((occupy & 481036337152ul) == 0) result |= 549755813888ul; return result; case 36: result = 171798691840ul; if ((occupy & 34359738368ul) == 0) result |= 17179869184ul; if ((occupy & 51539607552ul) == 0) result |= 8589934592ul; if ((occupy & 60129542144ul) == 0) result |= 4294967296ul; if ((occupy & 137438953472ul) == 0) result |= 274877906944ul; if ((occupy & 412316860416ul) == 0) result |= 549755813888ul; return result; case 37: result = 343597383680ul; if ((occupy & 68719476736ul) == 0) result |= 34359738368ul; if ((occupy & 103079215104ul) == 0) result |= 17179869184ul; if ((occupy & 120259084288ul) == 0) result |= 8589934592ul; if ((occupy & 128849018880ul) == 0) result |= 4294967296ul; if ((occupy & 274877906944ul) == 0) result |= 549755813888ul; return result; case 38: result = 687194767360ul; if ((occupy & 137438953472ul) == 0) result |= 68719476736ul; if ((occupy & 206158430208ul) == 0) result |= 34359738368ul; if ((occupy & 240518168576ul) == 0) result |= 17179869184ul; if ((occupy & 257698037760ul) == 0) result |= 8589934592ul; if ((occupy & 266287972352ul) == 0) result |= 4294967296ul; return result; case 39: result = 274877906944ul; if ((occupy & 274877906944ul) == 0) result |= 137438953472ul; if ((occupy & 412316860416ul) == 0) result |= 68719476736ul; if ((occupy & 481036337152ul) == 0) result |= 34359738368ul; if ((occupy & 515396075520ul) == 0) result |= 17179869184ul; if ((occupy & 532575944704ul) == 0) result |= 8589934592ul; if ((occupy & 541165879296ul) == 0) result |= 4294967296ul; return result; case 40: result = 2199023255552ul; if ((occupy & 2199023255552ul) == 0) result |= 4398046511104ul; if ((occupy & 6597069766656ul) == 0) result |= 8796093022208ul; if ((occupy & 15393162788864ul) == 0) result |= 17592186044416ul; if ((occupy & 32985348833280ul) == 0) result |= 35184372088832ul; if ((occupy & 68169720922112ul) == 0) result |= 70368744177664ul; if ((occupy & 138538465099776ul) == 0) result |= 140737488355328ul; return result; case 41: result = 5497558138880ul; if ((occupy & 4398046511104ul) == 0) result |= 8796093022208ul; if ((occupy & 13194139533312ul) == 0) result |= 17592186044416ul; if ((occupy & 30786325577728ul) == 0) result |= 35184372088832ul; if ((occupy & 65970697666560ul) == 0) result |= 70368744177664ul; if ((occupy & 136339441844224ul) == 0) result |= 140737488355328ul; return result; case 42: result = 10995116277760ul; if ((occupy & 2199023255552ul) == 0) result |= 1099511627776ul; if ((occupy & 8796093022208ul) == 0) result |= 17592186044416ul; if ((occupy & 26388279066624ul) == 0) result |= 35184372088832ul; if ((occupy & 61572651155456ul) == 0) result |= 70368744177664ul; if ((occupy & 131941395333120ul) == 0) result |= 140737488355328ul; return result; case 43: result = 21990232555520ul; if ((occupy & 4398046511104ul) == 0) result |= 2199023255552ul; if ((occupy & 6597069766656ul) == 0) result |= 1099511627776ul; if ((occupy & 17592186044416ul) == 0) result |= 35184372088832ul; if ((occupy & 52776558133248ul) == 0) result |= 70368744177664ul; if ((occupy & 123145302310912ul) == 0) result |= 140737488355328ul; return result; case 44: result = 43980465111040ul; if ((occupy & 8796093022208ul) == 0) result |= 4398046511104ul; if ((occupy & 13194139533312ul) == 0) result |= 2199023255552ul; if ((occupy & 15393162788864ul) == 0) result |= 1099511627776ul; if ((occupy & 35184372088832ul) == 0) result |= 70368744177664ul; if ((occupy & 105553116266496ul) == 0) result |= 140737488355328ul; return result; case 45: result = 87960930222080ul; if ((occupy & 17592186044416ul) == 0) result |= 8796093022208ul; if ((occupy & 26388279066624ul) == 0) result |= 4398046511104ul; if ((occupy & 30786325577728ul) == 0) result |= 2199023255552ul; if ((occupy & 32985348833280ul) == 0) result |= 1099511627776ul; if ((occupy & 70368744177664ul) == 0) result |= 140737488355328ul; return result; case 46: result = 175921860444160ul; if ((occupy & 35184372088832ul) == 0) result |= 17592186044416ul; if ((occupy & 52776558133248ul) == 0) result |= 8796093022208ul; if ((occupy & 61572651155456ul) == 0) result |= 4398046511104ul; if ((occupy & 65970697666560ul) == 0) result |= 2199023255552ul; if ((occupy & 68169720922112ul) == 0) result |= 1099511627776ul; return result; case 47: result = 70368744177664ul; if ((occupy & 70368744177664ul) == 0) result |= 35184372088832ul; if ((occupy & 105553116266496ul) == 0) result |= 17592186044416ul; if ((occupy & 123145302310912ul) == 0) result |= 8796093022208ul; if ((occupy & 131941395333120ul) == 0) result |= 4398046511104ul; if ((occupy & 136339441844224ul) == 0) result |= 2199023255552ul; if ((occupy & 138538465099776ul) == 0) result |= 1099511627776ul; return result; case 48: result = 562949953421312ul; if ((occupy & 562949953421312ul) == 0) result |= 1125899906842624ul; if ((occupy & 1688849860263936ul) == 0) result |= 2251799813685248ul; if ((occupy & 3940649673949184ul) == 0) result |= 4503599627370496ul; if ((occupy & 8444249301319680ul) == 0) result |= 9007199254740992ul; if ((occupy & 17451448556060672ul) == 0) result |= 18014398509481984ul; if ((occupy & 35465847065542656ul) == 0) result |= 36028797018963968ul; return result; case 49: result = 1407374883553280ul; if ((occupy & 1125899906842624ul) == 0) result |= 2251799813685248ul; if ((occupy & 3377699720527872ul) == 0) result |= 4503599627370496ul; if ((occupy & 7881299347898368ul) == 0) result |= 9007199254740992ul; if ((occupy & 16888498602639360ul) == 0) result |= 18014398509481984ul; if ((occupy & 34902897112121344ul) == 0) result |= 36028797018963968ul; return result; case 50: result = 2814749767106560ul; if ((occupy & 562949953421312ul) == 0) result |= 281474976710656ul; if ((occupy & 2251799813685248ul) == 0) result |= 4503599627370496ul; if ((occupy & 6755399441055744ul) == 0) result |= 9007199254740992ul; if ((occupy & 15762598695796736ul) == 0) result |= 18014398509481984ul; if ((occupy & 33776997205278720ul) == 0) result |= 36028797018963968ul; return result; case 51: result = 5629499534213120ul; if ((occupy & 1125899906842624ul) == 0) result |= 562949953421312ul; if ((occupy & 1688849860263936ul) == 0) result |= 281474976710656ul; if ((occupy & 4503599627370496ul) == 0) result |= 9007199254740992ul; if ((occupy & 13510798882111488ul) == 0) result |= 18014398509481984ul; if ((occupy & 31525197391593472ul) == 0) result |= 36028797018963968ul; return result; case 52: result = 11258999068426240ul; if ((occupy & 2251799813685248ul) == 0) result |= 1125899906842624ul; if ((occupy & 3377699720527872ul) == 0) result |= 562949953421312ul; if ((occupy & 3940649673949184ul) == 0) result |= 281474976710656ul; if ((occupy & 9007199254740992ul) == 0) result |= 18014398509481984ul; if ((occupy & 27021597764222976ul) == 0) result |= 36028797018963968ul; return result; case 53: result = 22517998136852480ul; if ((occupy & 4503599627370496ul) == 0) result |= 2251799813685248ul; if ((occupy & 6755399441055744ul) == 0) result |= 1125899906842624ul; if ((occupy & 7881299347898368ul) == 0) result |= 562949953421312ul; if ((occupy & 8444249301319680ul) == 0) result |= 281474976710656ul; if ((occupy & 18014398509481984ul) == 0) result |= 36028797018963968ul; return result; case 54: result = 45035996273704960ul; if ((occupy & 9007199254740992ul) == 0) result |= 4503599627370496ul; if ((occupy & 13510798882111488ul) == 0) result |= 2251799813685248ul; if ((occupy & 15762598695796736ul) == 0) result |= 1125899906842624ul; if ((occupy & 16888498602639360ul) == 0) result |= 562949953421312ul; if ((occupy & 17451448556060672ul) == 0) result |= 281474976710656ul; return result; case 55: result = 18014398509481984ul; if ((occupy & 18014398509481984ul) == 0) result |= 9007199254740992ul; if ((occupy & 27021597764222976ul) == 0) result |= 4503599627370496ul; if ((occupy & 31525197391593472ul) == 0) result |= 2251799813685248ul; if ((occupy & 33776997205278720ul) == 0) result |= 1125899906842624ul; if ((occupy & 34902897112121344ul) == 0) result |= 562949953421312ul; if ((occupy & 35465847065542656ul) == 0) result |= 281474976710656ul; return result; case 56: result = 144115188075855872ul; if ((occupy & 144115188075855872ul) == 0) result |= 288230376151711744ul; if ((occupy & 432345564227567616ul) == 0) result |= 576460752303423488ul; if ((occupy & 1008806316530991104ul) == 0) result |= 1152921504606846976ul; if ((occupy & 2161727821137838080ul) == 0) result |= 2305843009213693952ul; if ((occupy & 4467570830351532032ul) == 0) result |= 4611686018427387904ul; if ((occupy & 9079256848778919936ul) == 0) result |= 9223372036854775808ul; return result; case 57: result = 360287970189639680ul; if ((occupy & 288230376151711744ul) == 0) result |= 576460752303423488ul; if ((occupy & 864691128455135232ul) == 0) result |= 1152921504606846976ul; if ((occupy & 2017612633061982208ul) == 0) result |= 2305843009213693952ul; if ((occupy & 4323455642275676160ul) == 0) result |= 4611686018427387904ul; if ((occupy & 8935141660703064064ul) == 0) result |= 9223372036854775808ul; return result; case 58: result = 720575940379279360ul; if ((occupy & 144115188075855872ul) == 0) result |= 72057594037927936ul; if ((occupy & 576460752303423488ul) == 0) result |= 1152921504606846976ul; if ((occupy & 1729382256910270464ul) == 0) result |= 2305843009213693952ul; if ((occupy & 4035225266123964416ul) == 0) result |= 4611686018427387904ul; if ((occupy & 8646911284551352320ul) == 0) result |= 9223372036854775808ul; return result; case 59: result = 1441151880758558720ul; if ((occupy & 288230376151711744ul) == 0) result |= 144115188075855872ul; if ((occupy & 432345564227567616ul) == 0) result |= 72057594037927936ul; if ((occupy & 1152921504606846976ul) == 0) result |= 2305843009213693952ul; if ((occupy & 3458764513820540928ul) == 0) result |= 4611686018427387904ul; if ((occupy & 8070450532247928832ul) == 0) result |= 9223372036854775808ul; return result; case 60: result = 2882303761517117440ul; if ((occupy & 576460752303423488ul) == 0) result |= 288230376151711744ul; if ((occupy & 864691128455135232ul) == 0) result |= 144115188075855872ul; if ((occupy & 1008806316530991104ul) == 0) result |= 72057594037927936ul; if ((occupy & 2305843009213693952ul) == 0) result |= 4611686018427387904ul; if ((occupy & 6917529027641081856ul) == 0) result |= 9223372036854775808ul; return result; case 61: result = 5764607523034234880ul; if ((occupy & 1152921504606846976ul) == 0) result |= 576460752303423488ul; if ((occupy & 1729382256910270464ul) == 0) result |= 288230376151711744ul; if ((occupy & 2017612633061982208ul) == 0) result |= 144115188075855872ul; if ((occupy & 2161727821137838080ul) == 0) result |= 72057594037927936ul; if ((occupy & 4611686018427387904ul) == 0) result |= 9223372036854775808ul; return result; case 62: result = 11529215046068469760ul; if ((occupy & 2305843009213693952ul) == 0) result |= 1152921504606846976ul; if ((occupy & 3458764513820540928ul) == 0) result |= 576460752303423488ul; if ((occupy & 4035225266123964416ul) == 0) result |= 288230376151711744ul; if ((occupy & 4323455642275676160ul) == 0) result |= 144115188075855872ul; if ((occupy & 4467570830351532032ul) == 0) result |= 72057594037927936ul; return result; case 63: result = 4611686018427387904ul; if ((occupy & 4611686018427387904ul) == 0) result |= 2305843009213693952ul; if ((occupy & 6917529027641081856ul) == 0) result |= 1152921504606846976ul; if ((occupy & 8070450532247928832ul) == 0) result |= 576460752303423488ul; if ((occupy & 8646911284551352320ul) == 0) result |= 288230376151711744ul; if ((occupy & 8935141660703064064ul) == 0) result |= 144115188075855872ul; if ((occupy & 9079256848778919936ul) == 0) result |= 72057594037927936ul; return result; } return 0; } public static ulong GetSliderVCond(int SliderSquare, ulong occupy) { ulong result = 0; switch (SliderSquare) { case 0: result = 256ul; if ((occupy & 256ul) == 0) result |= 65536ul; if ((occupy & 65792ul) == 0) result |= 16777216ul; if ((occupy & 16843008ul) == 0) result |= 4294967296ul; if ((occupy & 4311810304ul) == 0) result |= 1099511627776ul; if ((occupy & 1103823438080ul) == 0) result |= 281474976710656ul; if ((occupy & 282578800148736ul) == 0) result |= 72057594037927936ul; return result; case 1: result = 512ul; if ((occupy & 512ul) == 0) result |= 131072ul; if ((occupy & 131584ul) == 0) result |= 33554432ul; if ((occupy & 33686016ul) == 0) result |= 8589934592ul; if ((occupy & 8623620608ul) == 0) result |= 2199023255552ul; if ((occupy & 2207646876160ul) == 0) result |= 562949953421312ul; if ((occupy & 565157600297472ul) == 0) result |= 144115188075855872ul; return result; case 2: result = 1024ul; if ((occupy & 1024ul) == 0) result |= 262144ul; if ((occupy & 263168ul) == 0) result |= 67108864ul; if ((occupy & 67372032ul) == 0) result |= 17179869184ul; if ((occupy & 17247241216ul) == 0) result |= 4398046511104ul; if ((occupy & 4415293752320ul) == 0) result |= 1125899906842624ul; if ((occupy & 1130315200594944ul) == 0) result |= 288230376151711744ul; return result; case 3: result = 2048ul; if ((occupy & 2048ul) == 0) result |= 524288ul; if ((occupy & 526336ul) == 0) result |= 134217728ul; if ((occupy & 134744064ul) == 0) result |= 34359738368ul; if ((occupy & 34494482432ul) == 0) result |= 8796093022208ul; if ((occupy & 8830587504640ul) == 0) result |= 2251799813685248ul; if ((occupy & 2260630401189888ul) == 0) result |= 576460752303423488ul; return result; case 4: result = 4096ul; if ((occupy & 4096ul) == 0) result |= 1048576ul; if ((occupy & 1052672ul) == 0) result |= 268435456ul; if ((occupy & 269488128ul) == 0) result |= 68719476736ul; if ((occupy & 68988964864ul) == 0) result |= 17592186044416ul; if ((occupy & 17661175009280ul) == 0) result |= 4503599627370496ul; if ((occupy & 4521260802379776ul) == 0) result |= 1152921504606846976ul; return result; case 5: result = 8192ul; if ((occupy & 8192ul) == 0) result |= 2097152ul; if ((occupy & 2105344ul) == 0) result |= 536870912ul; if ((occupy & 538976256ul) == 0) result |= 137438953472ul; if ((occupy & 137977929728ul) == 0) result |= 35184372088832ul; if ((occupy & 35322350018560ul) == 0) result |= 9007199254740992ul; if ((occupy & 9042521604759552ul) == 0) result |= 2305843009213693952ul; return result; case 6: result = 16384ul; if ((occupy & 16384ul) == 0) result |= 4194304ul; if ((occupy & 4210688ul) == 0) result |= 1073741824ul; if ((occupy & 1077952512ul) == 0) result |= 274877906944ul; if ((occupy & 275955859456ul) == 0) result |= 70368744177664ul; if ((occupy & 70644700037120ul) == 0) result |= 18014398509481984ul; if ((occupy & 18085043209519104ul) == 0) result |= 4611686018427387904ul; return result; case 7: result = 32768ul; if ((occupy & 32768ul) == 0) result |= 8388608ul; if ((occupy & 8421376ul) == 0) result |= 2147483648ul; if ((occupy & 2155905024ul) == 0) result |= 549755813888ul; if ((occupy & 551911718912ul) == 0) result |= 140737488355328ul; if ((occupy & 141289400074240ul) == 0) result |= 36028797018963968ul; if ((occupy & 36170086419038208ul) == 0) result |= 9223372036854775808ul; return result; case 8: result = 65537ul; if ((occupy & 65536ul) == 0) result |= 16777216ul; if ((occupy & 16842752ul) == 0) result |= 4294967296ul; if ((occupy & 4311810048ul) == 0) result |= 1099511627776ul; if ((occupy & 1103823437824ul) == 0) result |= 281474976710656ul; if ((occupy & 282578800148480ul) == 0) result |= 72057594037927936ul; return result; case 9: result = 131074ul; if ((occupy & 131072ul) == 0) result |= 33554432ul; if ((occupy & 33685504ul) == 0) result |= 8589934592ul; if ((occupy & 8623620096ul) == 0) result |= 2199023255552ul; if ((occupy & 2207646875648ul) == 0) result |= 562949953421312ul; if ((occupy & 565157600296960ul) == 0) result |= 144115188075855872ul; return result; case 10: result = 262148ul; if ((occupy & 262144ul) == 0) result |= 67108864ul; if ((occupy & 67371008ul) == 0) result |= 17179869184ul; if ((occupy & 17247240192ul) == 0) result |= 4398046511104ul; if ((occupy & 4415293751296ul) == 0) result |= 1125899906842624ul; if ((occupy & 1130315200593920ul) == 0) result |= 288230376151711744ul; return result; case 11: result = 524296ul; if ((occupy & 524288ul) == 0) result |= 134217728ul; if ((occupy & 134742016ul) == 0) result |= 34359738368ul; if ((occupy & 34494480384ul) == 0) result |= 8796093022208ul; if ((occupy & 8830587502592ul) == 0) result |= 2251799813685248ul; if ((occupy & 2260630401187840ul) == 0) result |= 576460752303423488ul; return result; case 12: result = 1048592ul; if ((occupy & 1048576ul) == 0) result |= 268435456ul; if ((occupy & 269484032ul) == 0) result |= 68719476736ul; if ((occupy & 68988960768ul) == 0) result |= 17592186044416ul; if ((occupy & 17661175005184ul) == 0) result |= 4503599627370496ul; if ((occupy & 4521260802375680ul) == 0) result |= 1152921504606846976ul; return result; case 13: result = 2097184ul; if ((occupy & 2097152ul) == 0) result |= 536870912ul; if ((occupy & 538968064ul) == 0) result |= 137438953472ul; if ((occupy & 137977921536ul) == 0) result |= 35184372088832ul; if ((occupy & 35322350010368ul) == 0) result |= 9007199254740992ul; if ((occupy & 9042521604751360ul) == 0) result |= 2305843009213693952ul; return result; case 14: result = 4194368ul; if ((occupy & 4194304ul) == 0) result |= 1073741824ul; if ((occupy & 1077936128ul) == 0) result |= 274877906944ul; if ((occupy & 275955843072ul) == 0) result |= 70368744177664ul; if ((occupy & 70644700020736ul) == 0) result |= 18014398509481984ul; if ((occupy & 18085043209502720ul) == 0) result |= 4611686018427387904ul; return result; case 15: result = 8388736ul; if ((occupy & 8388608ul) == 0) result |= 2147483648ul; if ((occupy & 2155872256ul) == 0) result |= 549755813888ul; if ((occupy & 551911686144ul) == 0) result |= 140737488355328ul; if ((occupy & 141289400041472ul) == 0) result |= 36028797018963968ul; if ((occupy & 36170086419005440ul) == 0) result |= 9223372036854775808ul; return result; case 16: result = 16777472ul; if ((occupy & 256ul) == 0) result |= 1ul; if ((occupy & 16777216ul) == 0) result |= 4294967296ul; if ((occupy & 4311744512ul) == 0) result |= 1099511627776ul; if ((occupy & 1103823372288ul) == 0) result |= 281474976710656ul; if ((occupy & 282578800082944ul) == 0) result |= 72057594037927936ul; return result; case 17: result = 33554944ul; if ((occupy & 512ul) == 0) result |= 2ul; if ((occupy & 33554432ul) == 0) result |= 8589934592ul; if ((occupy & 8623489024ul) == 0) result |= 2199023255552ul; if ((occupy & 2207646744576ul) == 0) result |= 562949953421312ul; if ((occupy & 565157600165888ul) == 0) result |= 144115188075855872ul; return result; case 18: result = 67109888ul; if ((occupy & 1024ul) == 0) result |= 4ul; if ((occupy & 67108864ul) == 0) result |= 17179869184ul; if ((occupy & 17246978048ul) == 0) result |= 4398046511104ul; if ((occupy & 4415293489152ul) == 0) result |= 1125899906842624ul; if ((occupy & 1130315200331776ul) == 0) result |= 288230376151711744ul; return result; case 19: result = 134219776ul; if ((occupy & 2048ul) == 0) result |= 8ul; if ((occupy & 134217728ul) == 0) result |= 34359738368ul; if ((occupy & 34493956096ul) == 0) result |= 8796093022208ul; if ((occupy & 8830586978304ul) == 0) result |= 2251799813685248ul; if ((occupy & 2260630400663552ul) == 0) result |= 576460752303423488ul; return result; case 20: result = 268439552ul; if ((occupy & 4096ul) == 0) result |= 16ul; if ((occupy & 268435456ul) == 0) result |= 68719476736ul; if ((occupy & 68987912192ul) == 0) result |= 17592186044416ul; if ((occupy & 17661173956608ul) == 0) result |= 4503599627370496ul; if ((occupy & 4521260801327104ul) == 0) result |= 1152921504606846976ul; return result; case 21: result = 536879104ul; if ((occupy & 8192ul) == 0) result |= 32ul; if ((occupy & 536870912ul) == 0) result |= 137438953472ul; if ((occupy & 137975824384ul) == 0) result |= 35184372088832ul; if ((occupy & 35322347913216ul) == 0) result |= 9007199254740992ul; if ((occupy & 9042521602654208ul) == 0) result |= 2305843009213693952ul; return result; case 22: result = 1073758208ul; if ((occupy & 16384ul) == 0) result |= 64ul; if ((occupy & 1073741824ul) == 0) result |= 274877906944ul; if ((occupy & 275951648768ul) == 0) result |= 70368744177664ul; if ((occupy & 70644695826432ul) == 0) result |= 18014398509481984ul; if ((occupy & 18085043205308416ul) == 0) result |= 4611686018427387904ul; return result; case 23: result = 2147516416ul; if ((occupy & 32768ul) == 0) result |= 128ul; if ((occupy & 2147483648ul) == 0) result |= 549755813888ul; if ((occupy & 551903297536ul) == 0) result |= 140737488355328ul; if ((occupy & 141289391652864ul) == 0) result |= 36028797018963968ul; if ((occupy & 36170086410616832ul) == 0) result |= 9223372036854775808ul; return result; case 24: result = 4295032832ul; if ((occupy & 65536ul) == 0) result |= 256ul; if ((occupy & 65792ul) == 0) result |= 1ul; if ((occupy & 4294967296ul) == 0) result |= 1099511627776ul; if ((occupy & 1103806595072ul) == 0) result |= 281474976710656ul; if ((occupy & 282578783305728ul) == 0) result |= 72057594037927936ul; return result; case 25: result = 8590065664ul; if ((occupy & 131072ul) == 0) result |= 512ul; if ((occupy & 131584ul) == 0) result |= 2ul; if ((occupy & 8589934592ul) == 0) result |= 2199023255552ul; if ((occupy & 2207613190144ul) == 0) result |= 562949953421312ul; if ((occupy & 565157566611456ul) == 0) result |= 144115188075855872ul; return result; case 26: result = 17180131328ul; if ((occupy & 262144ul) == 0) result |= 1024ul; if ((occupy & 263168ul) == 0) result |= 4ul; if ((occupy & 17179869184ul) == 0) result |= 4398046511104ul; if ((occupy & 4415226380288ul) == 0) result |= 1125899906842624ul; if ((occupy & 1130315133222912ul) == 0) result |= 288230376151711744ul; return result; case 27: result = 34360262656ul; if ((occupy & 524288ul) == 0) result |= 2048ul; if ((occupy & 526336ul) == 0) result |= 8ul; if ((occupy & 34359738368ul) == 0) result |= 8796093022208ul; if ((occupy & 8830452760576ul) == 0) result |= 2251799813685248ul; if ((occupy & 2260630266445824ul) == 0) result |= 576460752303423488ul; return result; case 28: result = 68720525312ul; if ((occupy & 1048576ul) == 0) result |= 4096ul; if ((occupy & 1052672ul) == 0) result |= 16ul; if ((occupy & 68719476736ul) == 0) result |= 17592186044416ul; if ((occupy & 17660905521152ul) == 0) result |= 4503599627370496ul; if ((occupy & 4521260532891648ul) == 0) result |= 1152921504606846976ul; return result; case 29: result = 137441050624ul; if ((occupy & 2097152ul) == 0) result |= 8192ul; if ((occupy & 2105344ul) == 0) result |= 32ul; if ((occupy & 137438953472ul) == 0) result |= 35184372088832ul; if ((occupy & 35321811042304ul) == 0) result |= 9007199254740992ul; if ((occupy & 9042521065783296ul) == 0) result |= 2305843009213693952ul; return result; case 30: result = 274882101248ul; if ((occupy & 4194304ul) == 0) result |= 16384ul; if ((occupy & 4210688ul) == 0) result |= 64ul; if ((occupy & 274877906944ul) == 0) result |= 70368744177664ul; if ((occupy & 70643622084608ul) == 0) result |= 18014398509481984ul; if ((occupy & 18085042131566592ul) == 0) result |= 4611686018427387904ul; return result; case 31: result = 549764202496ul; if ((occupy & 8388608ul) == 0) result |= 32768ul; if ((occupy & 8421376ul) == 0) result |= 128ul; if ((occupy & 549755813888ul) == 0) result |= 140737488355328ul; if ((occupy & 141287244169216ul) == 0) result |= 36028797018963968ul; if ((occupy & 36170084263133184ul) == 0) result |= 9223372036854775808ul; return result; case 32: result = 1099528404992ul; if ((occupy & 16777216ul) == 0) result |= 65536ul; if ((occupy & 16842752ul) == 0) result |= 256ul; if ((occupy & 16843008ul) == 0) result |= 1ul; if ((occupy & 1099511627776ul) == 0) result |= 281474976710656ul; if ((occupy & 282574488338432ul) == 0) result |= 72057594037927936ul; return result; case 33: result = 2199056809984ul; if ((occupy & 33554432ul) == 0) result |= 131072ul; if ((occupy & 33685504ul) == 0) result |= 512ul; if ((occupy & 33686016ul) == 0) result |= 2ul; if ((occupy & 2199023255552ul) == 0) result |= 562949953421312ul; if ((occupy & 565148976676864ul) == 0) result |= 144115188075855872ul; return result; case 34: result = 4398113619968ul; if ((occupy & 67108864ul) == 0) result |= 262144ul; if ((occupy & 67371008ul) == 0) result |= 1024ul; if ((occupy & 67372032ul) == 0) result |= 4ul; if ((occupy & 4398046511104ul) == 0) result |= 1125899906842624ul; if ((occupy & 1130297953353728ul) == 0) result |= 288230376151711744ul; return result; case 35: result = 8796227239936ul; if ((occupy & 134217728ul) == 0) result |= 524288ul; if ((occupy & 134742016ul) == 0) result |= 2048ul; if ((occupy & 134744064ul) == 0) result |= 8ul; if ((occupy & 8796093022208ul) == 0) result |= 2251799813685248ul; if ((occupy & 2260595906707456ul) == 0) result |= 576460752303423488ul; return result; case 36: result = 17592454479872ul; if ((occupy & 268435456ul) == 0) result |= 1048576ul; if ((occupy & 269484032ul) == 0) result |= 4096ul; if ((occupy & 269488128ul) == 0) result |= 16ul; if ((occupy & 17592186044416ul) == 0) result |= 4503599627370496ul; if ((occupy & 4521191813414912ul) == 0) result |= 1152921504606846976ul; return result; case 37: result = 35184908959744ul; if ((occupy & 536870912ul) == 0) result |= 2097152ul; if ((occupy & 538968064ul) == 0) result |= 8192ul; if ((occupy & 538976256ul) == 0) result |= 32ul; if ((occupy & 35184372088832ul) == 0) result |= 9007199254740992ul; if ((occupy & 9042383626829824ul) == 0) result |= 2305843009213693952ul; return result; case 38: result = 70369817919488ul; if ((occupy & 1073741824ul) == 0) result |= 4194304ul; if ((occupy & 1077936128ul) == 0) result |= 16384ul; if ((occupy & 1077952512ul) == 0) result |= 64ul; if ((occupy & 70368744177664ul) == 0) result |= 18014398509481984ul; if ((occupy & 18084767253659648ul) == 0) result |= 4611686018427387904ul; return result; case 39: result = 140739635838976ul; if ((occupy & 2147483648ul) == 0) result |= 8388608ul; if ((occupy & 2155872256ul) == 0) result |= 32768ul; if ((occupy & 2155905024ul) == 0) result |= 128ul; if ((occupy & 140737488355328ul) == 0) result |= 36028797018963968ul; if ((occupy & 36169534507319296ul) == 0) result |= 9223372036854775808ul; return result; case 40: result = 281479271677952ul; if ((occupy & 4294967296ul) == 0) result |= 16777216ul; if ((occupy & 4311744512ul) == 0) result |= 65536ul; if ((occupy & 4311810048ul) == 0) result |= 256ul; if ((occupy & 4311810304ul) == 0) result |= 1ul; if ((occupy & 281474976710656ul) == 0) result |= 72057594037927936ul; return result; case 41: result = 562958543355904ul; if ((occupy & 8589934592ul) == 0) result |= 33554432ul; if ((occupy & 8623489024ul) == 0) result |= 131072ul; if ((occupy & 8623620096ul) == 0) result |= 512ul; if ((occupy & 8623620608ul) == 0) result |= 2ul; if ((occupy & 562949953421312ul) == 0) result |= 144115188075855872ul; return result; case 42: result = 1125917086711808ul; if ((occupy & 17179869184ul) == 0) result |= 67108864ul; if ((occupy & 17246978048ul) == 0) result |= 262144ul; if ((occupy & 17247240192ul) == 0) result |= 1024ul; if ((occupy & 17247241216ul) == 0) result |= 4ul; if ((occupy & 1125899906842624ul) == 0) result |= 288230376151711744ul; return result; case 43: result = 2251834173423616ul; if ((occupy & 34359738368ul) == 0) result |= 134217728ul; if ((occupy & 34493956096ul) == 0) result |= 524288ul; if ((occupy & 34494480384ul) == 0) result |= 2048ul; if ((occupy & 34494482432ul) == 0) result |= 8ul; if ((occupy & 2251799813685248ul) == 0) result |= 576460752303423488ul; return result; case 44: result = 4503668346847232ul; if ((occupy & 68719476736ul) == 0) result |= 268435456ul; if ((occupy & 68987912192ul) == 0) result |= 1048576ul; if ((occupy & 68988960768ul) == 0) result |= 4096ul; if ((occupy & 68988964864ul) == 0) result |= 16ul; if ((occupy & 4503599627370496ul) == 0) result |= 1152921504606846976ul; return result; case 45: result = 9007336693694464ul; if ((occupy & 137438953472ul) == 0) result |= 536870912ul; if ((occupy & 137975824384ul) == 0) result |= 2097152ul; if ((occupy & 137977921536ul) == 0) result |= 8192ul; if ((occupy & 137977929728ul) == 0) result |= 32ul; if ((occupy & 9007199254740992ul) == 0) result |= 2305843009213693952ul; return result; case 46: result = 18014673387388928ul; if ((occupy & 274877906944ul) == 0) result |= 1073741824ul; if ((occupy & 275951648768ul) == 0) result |= 4194304ul; if ((occupy & 275955843072ul) == 0) result |= 16384ul; if ((occupy & 275955859456ul) == 0) result |= 64ul; if ((occupy & 18014398509481984ul) == 0) result |= 4611686018427387904ul; return result; case 47: result = 36029346774777856ul; if ((occupy & 549755813888ul) == 0) result |= 2147483648ul; if ((occupy & 551903297536ul) == 0) result |= 8388608ul; if ((occupy & 551911686144ul) == 0) result |= 32768ul; if ((occupy & 551911718912ul) == 0) result |= 128ul; if ((occupy & 36028797018963968ul) == 0) result |= 9223372036854775808ul; return result; case 48: result = 72058693549555712ul; if ((occupy & 1099511627776ul) == 0) result |= 4294967296ul; if ((occupy & 1103806595072ul) == 0) result |= 16777216ul; if ((occupy & 1103823372288ul) == 0) result |= 65536ul; if ((occupy & 1103823437824ul) == 0) result |= 256ul; if ((occupy & 1103823438080ul) == 0) result |= 1ul; return result; case 49: result = 144117387099111424ul; if ((occupy & 2199023255552ul) == 0) result |= 8589934592ul; if ((occupy & 2207613190144ul) == 0) result |= 33554432ul; if ((occupy & 2207646744576ul) == 0) result |= 131072ul; if ((occupy & 2207646875648ul) == 0) result |= 512ul; if ((occupy & 2207646876160ul) == 0) result |= 2ul; return result; case 50: result = 288234774198222848ul; if ((occupy & 4398046511104ul) == 0) result |= 17179869184ul; if ((occupy & 4415226380288ul) == 0) result |= 67108864ul; if ((occupy & 4415293489152ul) == 0) result |= 262144ul; if ((occupy & 4415293751296ul) == 0) result |= 1024ul; if ((occupy & 4415293752320ul) == 0) result |= 4ul; return result; case 51: result = 576469548396445696ul; if ((occupy & 8796093022208ul) == 0) result |= 34359738368ul; if ((occupy & 8830452760576ul) == 0) result |= 134217728ul; if ((occupy & 8830586978304ul) == 0) result |= 524288ul; if ((occupy & 8830587502592ul) == 0) result |= 2048ul; if ((occupy & 8830587504640ul) == 0) result |= 8ul; return result; case 52: result = 1152939096792891392ul; if ((occupy & 17592186044416ul) == 0) result |= 68719476736ul; if ((occupy & 17660905521152ul) == 0) result |= 268435456ul; if ((occupy & 17661173956608ul) == 0) result |= 1048576ul; if ((occupy & 17661175005184ul) == 0) result |= 4096ul; if ((occupy & 17661175009280ul) == 0) result |= 16ul; return result; case 53: result = 2305878193585782784ul; if ((occupy & 35184372088832ul) == 0) result |= 137438953472ul; if ((occupy & 35321811042304ul) == 0) result |= 536870912ul; if ((occupy & 35322347913216ul) == 0) result |= 2097152ul; if ((occupy & 35322350010368ul) == 0) result |= 8192ul; if ((occupy & 35322350018560ul) == 0) result |= 32ul; return result; case 54: result = 4611756387171565568ul; if ((occupy & 70368744177664ul) == 0) result |= 274877906944ul; if ((occupy & 70643622084608ul) == 0) result |= 1073741824ul; if ((occupy & 70644695826432ul) == 0) result |= 4194304ul; if ((occupy & 70644700020736ul) == 0) result |= 16384ul; if ((occupy & 70644700037120ul) == 0) result |= 64ul; return result; case 55: result = 9223512774343131136ul; if ((occupy & 140737488355328ul) == 0) result |= 549755813888ul; if ((occupy & 141287244169216ul) == 0) result |= 2147483648ul; if ((occupy & 141289391652864ul) == 0) result |= 8388608ul; if ((occupy & 141289400041472ul) == 0) result |= 32768ul; if ((occupy & 141289400074240ul) == 0) result |= 128ul; return result; case 56: result = 281474976710656ul; if ((occupy & 281474976710656ul) == 0) result |= 1099511627776ul; if ((occupy & 282574488338432ul) == 0) result |= 4294967296ul; if ((occupy & 282578783305728ul) == 0) result |= 16777216ul; if ((occupy & 282578800082944ul) == 0) result |= 65536ul; if ((occupy & 282578800148480ul) == 0) result |= 256ul; if ((occupy & 282578800148736ul) == 0) result |= 1ul; return result; case 57: result = 562949953421312ul; if ((occupy & 562949953421312ul) == 0) result |= 2199023255552ul; if ((occupy & 565148976676864ul) == 0) result |= 8589934592ul; if ((occupy & 565157566611456ul) == 0) result |= 33554432ul; if ((occupy & 565157600165888ul) == 0) result |= 131072ul; if ((occupy & 565157600296960ul) == 0) result |= 512ul; if ((occupy & 565157600297472ul) == 0) result |= 2ul; return result; case 58: result = 1125899906842624ul; if ((occupy & 1125899906842624ul) == 0) result |= 4398046511104ul; if ((occupy & 1130297953353728ul) == 0) result |= 17179869184ul; if ((occupy & 1130315133222912ul) == 0) result |= 67108864ul; if ((occupy & 1130315200331776ul) == 0) result |= 262144ul; if ((occupy & 1130315200593920ul) == 0) result |= 1024ul; if ((occupy & 1130315200594944ul) == 0) result |= 4ul; return result; case 59: result = 2251799813685248ul; if ((occupy & 2251799813685248ul) == 0) result |= 8796093022208ul; if ((occupy & 2260595906707456ul) == 0) result |= 34359738368ul; if ((occupy & 2260630266445824ul) == 0) result |= 134217728ul; if ((occupy & 2260630400663552ul) == 0) result |= 524288ul; if ((occupy & 2260630401187840ul) == 0) result |= 2048ul; if ((occupy & 2260630401189888ul) == 0) result |= 8ul; return result; case 60: result = 4503599627370496ul; if ((occupy & 4503599627370496ul) == 0) result |= 17592186044416ul; if ((occupy & 4521191813414912ul) == 0) result |= 68719476736ul; if ((occupy & 4521260532891648ul) == 0) result |= 268435456ul; if ((occupy & 4521260801327104ul) == 0) result |= 1048576ul; if ((occupy & 4521260802375680ul) == 0) result |= 4096ul; if ((occupy & 4521260802379776ul) == 0) result |= 16ul; return result; case 61: result = 9007199254740992ul; if ((occupy & 9007199254740992ul) == 0) result |= 35184372088832ul; if ((occupy & 9042383626829824ul) == 0) result |= 137438953472ul; if ((occupy & 9042521065783296ul) == 0) result |= 536870912ul; if ((occupy & 9042521602654208ul) == 0) result |= 2097152ul; if ((occupy & 9042521604751360ul) == 0) result |= 8192ul; if ((occupy & 9042521604759552ul) == 0) result |= 32ul; return result; case 62: result = 18014398509481984ul; if ((occupy & 18014398509481984ul) == 0) result |= 70368744177664ul; if ((occupy & 18084767253659648ul) == 0) result |= 274877906944ul; if ((occupy & 18085042131566592ul) == 0) result |= 1073741824ul; if ((occupy & 18085043205308416ul) == 0) result |= 4194304ul; if ((occupy & 18085043209502720ul) == 0) result |= 16384ul; if ((occupy & 18085043209519104ul) == 0) result |= 64ul; return result; case 63: result = 36028797018963968ul; if ((occupy & 36028797018963968ul) == 0) result |= 140737488355328ul; if ((occupy & 36169534507319296ul) == 0) result |= 549755813888ul; if ((occupy & 36170084263133184ul) == 0) result |= 2147483648ul; if ((occupy & 36170086410616832ul) == 0) result |= 8388608ul; if ((occupy & 36170086419005440ul) == 0) result |= 32768ul; if ((occupy & 36170086419038208ul) == 0) result |= 128ul; return result; } return 0; } public static ulong GetSliderD2Cond(int SliderSquare, ulong occupy) { ulong result = 0; switch (SliderSquare) { case 0: result = 0ul; return result; case 1: result = 256ul; return result; case 2: result = 512ul; if ((occupy & 512ul) == 0) result |= 65536ul; return result; case 3: result = 1024ul; if ((occupy & 1024ul) == 0) result |= 131072ul; if ((occupy & 132096ul) == 0) result |= 16777216ul; return result; case 4: result = 2048ul; if ((occupy & 2048ul) == 0) result |= 262144ul; if ((occupy & 264192ul) == 0) result |= 33554432ul; if ((occupy & 33818624ul) == 0) result |= 4294967296ul; return result; case 5: result = 4096ul; if ((occupy & 4096ul) == 0) result |= 524288ul; if ((occupy & 528384ul) == 0) result |= 67108864ul; if ((occupy & 67637248ul) == 0) result |= 8589934592ul; if ((occupy & 8657571840ul) == 0) result |= 1099511627776ul; return result; case 6: result = 8192ul; if ((occupy & 8192ul) == 0) result |= 1048576ul; if ((occupy & 1056768ul) == 0) result |= 134217728ul; if ((occupy & 135274496ul) == 0) result |= 17179869184ul; if ((occupy & 17315143680ul) == 0) result |= 2199023255552ul; if ((occupy & 2216338399232ul) == 0) result |= 281474976710656ul; return result; case 7: result = 16384ul; if ((occupy & 16384ul) == 0) result |= 2097152ul; if ((occupy & 2113536ul) == 0) result |= 268435456ul; if ((occupy & 270548992ul) == 0) result |= 34359738368ul; if ((occupy & 34630287360ul) == 0) result |= 4398046511104ul; if ((occupy & 4432676798464ul) == 0) result |= 562949953421312ul; if ((occupy & 567382630219776ul) == 0) result |= 72057594037927936ul; return result; case 8: result = 2ul; return result; case 9: result = 65540ul; return result; case 10: result = 131080ul; if ((occupy & 131072ul) == 0) result |= 16777216ul; return result; case 11: result = 262160ul; if ((occupy & 262144ul) == 0) result |= 33554432ul; if ((occupy & 33816576ul) == 0) result |= 4294967296ul; return result; case 12: result = 524320ul; if ((occupy & 524288ul) == 0) result |= 67108864ul; if ((occupy & 67633152ul) == 0) result |= 8589934592ul; if ((occupy & 8657567744ul) == 0) result |= 1099511627776ul; return result; case 13: result = 1048640ul; if ((occupy & 1048576ul) == 0) result |= 134217728ul; if ((occupy & 135266304ul) == 0) result |= 17179869184ul; if ((occupy & 17315135488ul) == 0) result |= 2199023255552ul; if ((occupy & 2216338391040ul) == 0) result |= 281474976710656ul; return result; case 14: result = 2097280ul; if ((occupy & 2097152ul) == 0) result |= 268435456ul; if ((occupy & 270532608ul) == 0) result |= 34359738368ul; if ((occupy & 34630270976ul) == 0) result |= 4398046511104ul; if ((occupy & 4432676782080ul) == 0) result |= 562949953421312ul; if ((occupy & 567382630203392ul) == 0) result |= 72057594037927936ul; return result; case 15: result = 4194304ul; if ((occupy & 4194304ul) == 0) result |= 536870912ul; if ((occupy & 541065216ul) == 0) result |= 68719476736ul; if ((occupy & 69260541952ul) == 0) result |= 8796093022208ul; if ((occupy & 8865353564160ul) == 0) result |= 1125899906842624ul; if ((occupy & 1134765260406784ul) == 0) result |= 144115188075855872ul; return result; case 16: result = 512ul; if ((occupy & 512ul) == 0) result |= 4ul; return result; case 17: result = 16778240ul; if ((occupy & 1024ul) == 0) result |= 8ul; return result; case 18: result = 33556480ul; if ((occupy & 2048ul) == 0) result |= 16ul; if ((occupy & 33554432ul) == 0) result |= 4294967296ul; return result; case 19: result = 67112960ul; if ((occupy & 4096ul) == 0) result |= 32ul; if ((occupy & 67108864ul) == 0) result |= 8589934592ul; if ((occupy & 8657043456ul) == 0) result |= 1099511627776ul; return result; case 20: result = 134225920ul; if ((occupy & 8192ul) == 0) result |= 64ul; if ((occupy & 134217728ul) == 0) result |= 17179869184ul; if ((occupy & 17314086912ul) == 0) result |= 2199023255552ul; if ((occupy & 2216337342464ul) == 0) result |= 281474976710656ul; return result; case 21: result = 268451840ul; if ((occupy & 16384ul) == 0) result |= 128ul; if ((occupy & 268435456ul) == 0) result |= 34359738368ul; if ((occupy & 34628173824ul) == 0) result |= 4398046511104ul; if ((occupy & 4432674684928ul) == 0) result |= 562949953421312ul; if ((occupy & 567382628106240ul) == 0) result |= 72057594037927936ul; return result; case 22: result = 536903680ul; if ((occupy & 536870912ul) == 0) result |= 68719476736ul; if ((occupy & 69256347648ul) == 0) result |= 8796093022208ul; if ((occupy & 8865349369856ul) == 0) result |= 1125899906842624ul; if ((occupy & 1134765256212480ul) == 0) result |= 144115188075855872ul; return result; case 23: result = 1073741824ul; if ((occupy & 1073741824ul) == 0) result |= 137438953472ul; if ((occupy & 138512695296ul) == 0) result |= 17592186044416ul; if ((occupy & 17730698739712ul) == 0) result |= 2251799813685248ul; if ((occupy & 2269530512424960ul) == 0) result |= 288230376151711744ul; return result; case 24: result = 131072ul; if ((occupy & 131072ul) == 0) result |= 1024ul; if ((occupy & 132096ul) == 0) result |= 8ul; return result; case 25: result = 4295229440ul; if ((occupy & 262144ul) == 0) result |= 2048ul; if ((occupy & 264192ul) == 0) result |= 16ul; return result; case 26: result = 8590458880ul; if ((occupy & 524288ul) == 0) result |= 4096ul; if ((occupy & 528384ul) == 0) result |= 32ul; if ((occupy & 8589934592ul) == 0) result |= 1099511627776ul; return result; case 27: result = 17180917760ul; if ((occupy & 1048576ul) == 0) result |= 8192ul; if ((occupy & 1056768ul) == 0) result |= 64ul; if ((occupy & 17179869184ul) == 0) result |= 2199023255552ul; if ((occupy & 2216203124736ul) == 0) result |= 281474976710656ul; return result; case 28: result = 34361835520ul; if ((occupy & 2097152ul) == 0) result |= 16384ul; if ((occupy & 2113536ul) == 0) result |= 128ul; if ((occupy & 34359738368ul) == 0) result |= 4398046511104ul; if ((occupy & 4432406249472ul) == 0) result |= 562949953421312ul; if ((occupy & 567382359670784ul) == 0) result |= 72057594037927936ul; return result; case 29: result = 68723671040ul; if ((occupy & 4194304ul) == 0) result |= 32768ul; if ((occupy & 68719476736ul) == 0) result |= 8796093022208ul; if ((occupy & 8864812498944ul) == 0) result |= 1125899906842624ul; if ((occupy & 1134764719341568ul) == 0) result |= 144115188075855872ul; return result; case 30: result = 137447342080ul; if ((occupy & 137438953472ul) == 0) result |= 17592186044416ul; if ((occupy & 17729624997888ul) == 0) result |= 2251799813685248ul; if ((occupy & 2269529438683136ul) == 0) result |= 288230376151711744ul; return result; case 31: result = 274877906944ul; if ((occupy & 274877906944ul) == 0) result |= 35184372088832ul; if ((occupy & 35459249995776ul) == 0) result |= 4503599627370496ul; if ((occupy & 4539058877366272ul) == 0) result |= 576460752303423488ul; return result; case 32: result = 33554432ul; if ((occupy & 33554432ul) == 0) result |= 262144ul; if ((occupy & 33816576ul) == 0) result |= 2048ul; if ((occupy & 33818624ul) == 0) result |= 16ul; return result; case 33: result = 1099578736640ul; if ((occupy & 67108864ul) == 0) result |= 524288ul; if ((occupy & 67633152ul) == 0) result |= 4096ul; if ((occupy & 67637248ul) == 0) result |= 32ul; return result; case 34: result = 2199157473280ul; if ((occupy & 134217728ul) == 0) result |= 1048576ul; if ((occupy & 135266304ul) == 0) result |= 8192ul; if ((occupy & 135274496ul) == 0) result |= 64ul; if ((occupy & 2199023255552ul) == 0) result |= 281474976710656ul; return result; case 35: result = 4398314946560ul; if ((occupy & 268435456ul) == 0) result |= 2097152ul; if ((occupy & 270532608ul) == 0) result |= 16384ul; if ((occupy & 270548992ul) == 0) result |= 128ul; if ((occupy & 4398046511104ul) == 0) result |= 562949953421312ul; if ((occupy & 567347999932416ul) == 0) result |= 72057594037927936ul; return result; case 36: result = 8796629893120ul; if ((occupy & 536870912ul) == 0) result |= 4194304ul; if ((occupy & 541065216ul) == 0) result |= 32768ul; if ((occupy & 8796093022208ul) == 0) result |= 1125899906842624ul; if ((occupy & 1134695999864832ul) == 0) result |= 144115188075855872ul; return result; case 37: result = 17593259786240ul; if ((occupy & 1073741824ul) == 0) result |= 8388608ul; if ((occupy & 17592186044416ul) == 0) result |= 2251799813685248ul; if ((occupy & 2269391999729664ul) == 0) result |= 288230376151711744ul; return result; case 38: result = 35186519572480ul; if ((occupy & 35184372088832ul) == 0) result |= 4503599627370496ul; if ((occupy & 4538783999459328ul) == 0) result |= 576460752303423488ul; return result; case 39: result = 70368744177664ul; if ((occupy & 70368744177664ul) == 0) result |= 9007199254740992ul; if ((occupy & 9077567998918656ul) == 0) result |= 1152921504606846976ul; return result; case 40: result = 8589934592ul; if ((occupy & 8589934592ul) == 0) result |= 67108864ul; if ((occupy & 8657043456ul) == 0) result |= 524288ul; if ((occupy & 8657567744ul) == 0) result |= 4096ul; if ((occupy & 8657571840ul) == 0) result |= 32ul; return result; case 41: result = 281492156579840ul; if ((occupy & 17179869184ul) == 0) result |= 134217728ul; if ((occupy & 17314086912ul) == 0) result |= 1048576ul; if ((occupy & 17315135488ul) == 0) result |= 8192ul; if ((occupy & 17315143680ul) == 0) result |= 64ul; return result; case 42: result = 562984313159680ul; if ((occupy & 34359738368ul) == 0) result |= 268435456ul; if ((occupy & 34628173824ul) == 0) result |= 2097152ul; if ((occupy & 34630270976ul) == 0) result |= 16384ul; if ((occupy & 34630287360ul) == 0) result |= 128ul; if ((occupy & 562949953421312ul) == 0) result |= 72057594037927936ul; return result; case 43: result = 1125968626319360ul; if ((occupy & 68719476736ul) == 0) result |= 536870912ul; if ((occupy & 69256347648ul) == 0) result |= 4194304ul; if ((occupy & 69260541952ul) == 0) result |= 32768ul; if ((occupy & 1125899906842624ul) == 0) result |= 144115188075855872ul; return result; case 44: result = 2251937252638720ul; if ((occupy & 137438953472ul) == 0) result |= 1073741824ul; if ((occupy & 138512695296ul) == 0) result |= 8388608ul; if ((occupy & 2251799813685248ul) == 0) result |= 288230376151711744ul; return result; case 45: result = 4503874505277440ul; if ((occupy & 274877906944ul) == 0) result |= 2147483648ul; if ((occupy & 4503599627370496ul) == 0) result |= 576460752303423488ul; return result; case 46: result = 9007749010554880ul; if ((occupy & 9007199254740992ul) == 0) result |= 1152921504606846976ul; return result; case 47: result = 18014398509481984ul; if ((occupy & 18014398509481984ul) == 0) result |= 2305843009213693952ul; return result; case 48: result = 2199023255552ul; if ((occupy & 2199023255552ul) == 0) result |= 17179869184ul; if ((occupy & 2216203124736ul) == 0) result |= 134217728ul; if ((occupy & 2216337342464ul) == 0) result |= 1048576ul; if ((occupy & 2216338391040ul) == 0) result |= 8192ul; if ((occupy & 2216338399232ul) == 0) result |= 64ul; return result; case 49: result = 72061992084439040ul; if ((occupy & 4398046511104ul) == 0) result |= 34359738368ul; if ((occupy & 4432406249472ul) == 0) result |= 268435456ul; if ((occupy & 4432674684928ul) == 0) result |= 2097152ul; if ((occupy & 4432676782080ul) == 0) result |= 16384ul; if ((occupy & 4432676798464ul) == 0) result |= 128ul; return result; case 50: result = 144123984168878080ul; if ((occupy & 8796093022208ul) == 0) result |= 68719476736ul; if ((occupy & 8864812498944ul) == 0) result |= 536870912ul; if ((occupy & 8865349369856ul) == 0) result |= 4194304ul; if ((occupy & 8865353564160ul) == 0) result |= 32768ul; return result; case 51: result = 288247968337756160ul; if ((occupy & 17592186044416ul) == 0) result |= 137438953472ul; if ((occupy & 17729624997888ul) == 0) result |= 1073741824ul; if ((occupy & 17730698739712ul) == 0) result |= 8388608ul; return result; case 52: result = 576495936675512320ul; if ((occupy & 35184372088832ul) == 0) result |= 274877906944ul; if ((occupy & 35459249995776ul) == 0) result |= 2147483648ul; return result; case 53: result = 1152991873351024640ul; if ((occupy & 70368744177664ul) == 0) result |= 549755813888ul; return result; case 54: result = 2305983746702049280ul; return result; case 55: result = 4611686018427387904ul; return result; case 56: result = 562949953421312ul; if ((occupy & 562949953421312ul) == 0) result |= 4398046511104ul; if ((occupy & 567347999932416ul) == 0) result |= 34359738368ul; if ((occupy & 567382359670784ul) == 0) result |= 268435456ul; if ((occupy & 567382628106240ul) == 0) result |= 2097152ul; if ((occupy & 567382630203392ul) == 0) result |= 16384ul; if ((occupy & 567382630219776ul) == 0) result |= 128ul; return result; case 57: result = 1125899906842624ul; if ((occupy & 1125899906842624ul) == 0) result |= 8796093022208ul; if ((occupy & 1134695999864832ul) == 0) result |= 68719476736ul; if ((occupy & 1134764719341568ul) == 0) result |= 536870912ul; if ((occupy & 1134765256212480ul) == 0) result |= 4194304ul; if ((occupy & 1134765260406784ul) == 0) result |= 32768ul; return result; case 58: result = 2251799813685248ul; if ((occupy & 2251799813685248ul) == 0) result |= 17592186044416ul; if ((occupy & 2269391999729664ul) == 0) result |= 137438953472ul; if ((occupy & 2269529438683136ul) == 0) result |= 1073741824ul; if ((occupy & 2269530512424960ul) == 0) result |= 8388608ul; return result; case 59: result = 4503599627370496ul; if ((occupy & 4503599627370496ul) == 0) result |= 35184372088832ul; if ((occupy & 4538783999459328ul) == 0) result |= 274877906944ul; if ((occupy & 4539058877366272ul) == 0) result |= 2147483648ul; return result; case 60: result = 9007199254740992ul; if ((occupy & 9007199254740992ul) == 0) result |= 70368744177664ul; if ((occupy & 9077567998918656ul) == 0) result |= 549755813888ul; return result; case 61: result = 18014398509481984ul; if ((occupy & 18014398509481984ul) == 0) result |= 140737488355328ul; return result; case 62: result = 36028797018963968ul; return result; case 63: result = 0ul; return result; } return 0; } public static ulong GetSliderD1Cond(int SliderSquare, ulong occupy) { ulong result = 0; switch (SliderSquare) { case 0: result = 512ul; if ((occupy & 512ul) == 0) result |= 262144ul; if ((occupy & 262656ul) == 0) result |= 134217728ul; if ((occupy & 134480384ul) == 0) result |= 68719476736ul; if ((occupy & 68853957120ul) == 0) result |= 35184372088832ul; if ((occupy & 35253226045952ul) == 0) result |= 18014398509481984ul; if ((occupy & 18049651735527936ul) == 0) result |= 9223372036854775808ul; return result; case 1: result = 1024ul; if ((occupy & 1024ul) == 0) result |= 524288ul; if ((occupy & 525312ul) == 0) result |= 268435456ul; if ((occupy & 268960768ul) == 0) result |= 137438953472ul; if ((occupy & 137707914240ul) == 0) result |= 70368744177664ul; if ((occupy & 70506452091904ul) == 0) result |= 36028797018963968ul; return result; case 2: result = 2048ul; if ((occupy & 2048ul) == 0) result |= 1048576ul; if ((occupy & 1050624ul) == 0) result |= 536870912ul; if ((occupy & 537921536ul) == 0) result |= 274877906944ul; if ((occupy & 275415828480ul) == 0) result |= 140737488355328ul; return result; case 3: result = 4096ul; if ((occupy & 4096ul) == 0) result |= 2097152ul; if ((occupy & 2101248ul) == 0) result |= 1073741824ul; if ((occupy & 1075843072ul) == 0) result |= 549755813888ul; return result; case 4: result = 8192ul; if ((occupy & 8192ul) == 0) result |= 4194304ul; if ((occupy & 4202496ul) == 0) result |= 2147483648ul; return result; case 5: result = 16384ul; if ((occupy & 16384ul) == 0) result |= 8388608ul; return result; case 6: result = 32768ul; return result; case 7: result = 0ul; return result; case 8: result = 131072ul; if ((occupy & 131072ul) == 0) result |= 67108864ul; if ((occupy & 67239936ul) == 0) result |= 34359738368ul; if ((occupy & 34426978304ul) == 0) result |= 17592186044416ul; if ((occupy & 17626613022720ul) == 0) result |= 9007199254740992ul; if ((occupy & 9024825867763712ul) == 0) result |= 4611686018427387904ul; return result; case 9: result = 262145ul; if ((occupy & 262144ul) == 0) result |= 134217728ul; if ((occupy & 134479872ul) == 0) result |= 68719476736ul; if ((occupy & 68853956608ul) == 0) result |= 35184372088832ul; if ((occupy & 35253226045440ul) == 0) result |= 18014398509481984ul; if ((occupy & 18049651735527424ul) == 0) result |= 9223372036854775808ul; return result; case 10: result = 524290ul; if ((occupy & 524288ul) == 0) result |= 268435456ul; if ((occupy & 268959744ul) == 0) result |= 137438953472ul; if ((occupy & 137707913216ul) == 0) result |= 70368744177664ul; if ((occupy & 70506452090880ul) == 0) result |= 36028797018963968ul; return result; case 11: result = 1048580ul; if ((occupy & 1048576ul) == 0) result |= 536870912ul; if ((occupy & 537919488ul) == 0) result |= 274877906944ul; if ((occupy & 275415826432ul) == 0) result |= 140737488355328ul; return result; case 12: result = 2097160ul; if ((occupy & 2097152ul) == 0) result |= 1073741824ul; if ((occupy & 1075838976ul) == 0) result |= 549755813888ul; return result; case 13: result = 4194320ul; if ((occupy & 4194304ul) == 0) result |= 2147483648ul; return result; case 14: result = 8388640ul; return result; case 15: result = 64ul; return result; case 16: result = 33554432ul; if ((occupy & 33554432ul) == 0) result |= 17179869184ul; if ((occupy & 17213423616ul) == 0) result |= 8796093022208ul; if ((occupy & 8813306445824ul) == 0) result |= 4503599627370496ul; if ((occupy & 4512412933816320ul) == 0) result |= 2305843009213693952ul; return result; case 17: result = 67109120ul; if ((occupy & 67108864ul) == 0) result |= 34359738368ul; if ((occupy & 34426847232ul) == 0) result |= 17592186044416ul; if ((occupy & 17626612891648ul) == 0) result |= 9007199254740992ul; if ((occupy & 9024825867632640ul) == 0) result |= 4611686018427387904ul; return result; case 18: result = 134218240ul; if ((occupy & 512ul) == 0) result |= 1ul; if ((occupy & 134217728ul) == 0) result |= 68719476736ul; if ((occupy & 68853694464ul) == 0) result |= 35184372088832ul; if ((occupy & 35253225783296ul) == 0) result |= 18014398509481984ul; if ((occupy & 18049651735265280ul) == 0) result |= 9223372036854775808ul; return result; case 19: result = 268436480ul; if ((occupy & 1024ul) == 0) result |= 2ul; if ((occupy & 268435456ul) == 0) result |= 137438953472ul; if ((occupy & 137707388928ul) == 0) result |= 70368744177664ul; if ((occupy & 70506451566592ul) == 0) result |= 36028797018963968ul; return result; case 20: result = 536872960ul; if ((occupy & 2048ul) == 0) result |= 4ul; if ((occupy & 536870912ul) == 0) result |= 274877906944ul; if ((occupy & 275414777856ul) == 0) result |= 140737488355328ul; return result; case 21: result = 1073745920ul; if ((occupy & 4096ul) == 0) result |= 8ul; if ((occupy & 1073741824ul) == 0) result |= 549755813888ul; return result; case 22: result = 2147491840ul; if ((occupy & 8192ul) == 0) result |= 16ul; return result; case 23: result = 16384ul; if ((occupy & 16384ul) == 0) result |= 32ul; return result; case 24: result = 8589934592ul; if ((occupy & 8589934592ul) == 0) result |= 4398046511104ul; if ((occupy & 4406636445696ul) == 0) result |= 2251799813685248ul; if ((occupy & 2256206450130944ul) == 0) result |= 1152921504606846976ul; return result; case 25: result = 17179934720ul; if ((occupy & 17179869184ul) == 0) result |= 8796093022208ul; if ((occupy & 8813272891392ul) == 0) result |= 4503599627370496ul; if ((occupy & 4512412900261888ul) == 0) result |= 2305843009213693952ul; return result; case 26: result = 34359869440ul; if ((occupy & 131072ul) == 0) result |= 256ul; if ((occupy & 34359738368ul) == 0) result |= 17592186044416ul; if ((occupy & 17626545782784ul) == 0) result |= 9007199254740992ul; if ((occupy & 9024825800523776ul) == 0) result |= 4611686018427387904ul; return result; case 27: result = 68719738880ul; if ((occupy & 262144ul) == 0) result |= 512ul; if ((occupy & 262656ul) == 0) result |= 1ul; if ((occupy & 68719476736ul) == 0) result |= 35184372088832ul; if ((occupy & 35253091565568ul) == 0) result |= 18014398509481984ul; if ((occupy & 18049651601047552ul) == 0) result |= 9223372036854775808ul; return result; case 28: result = 137439477760ul; if ((occupy & 524288ul) == 0) result |= 1024ul; if ((occupy & 525312ul) == 0) result |= 2ul; if ((occupy & 137438953472ul) == 0) result |= 70368744177664ul; if ((occupy & 70506183131136ul) == 0) result |= 36028797018963968ul; return result; case 29: result = 274878955520ul; if ((occupy & 1048576ul) == 0) result |= 2048ul; if ((occupy & 1050624ul) == 0) result |= 4ul; if ((occupy & 274877906944ul) == 0) result |= 140737488355328ul; return result; case 30: result = 549757911040ul; if ((occupy & 2097152ul) == 0) result |= 4096ul; if ((occupy & 2101248ul) == 0) result |= 8ul; return result; case 31: result = 4194304ul; if ((occupy & 4194304ul) == 0) result |= 8192ul; if ((occupy & 4202496ul) == 0) result |= 16ul; return result; case 32: result = 2199023255552ul; if ((occupy & 2199023255552ul) == 0) result |= 1125899906842624ul; if ((occupy & 1128098930098176ul) == 0) result |= 576460752303423488ul; return result; case 33: result = 4398063288320ul; if ((occupy & 4398046511104ul) == 0) result |= 2251799813685248ul; if ((occupy & 2256197860196352ul) == 0) result |= 1152921504606846976ul; return result; case 34: result = 8796126576640ul; if ((occupy & 33554432ul) == 0) result |= 65536ul; if ((occupy & 8796093022208ul) == 0) result |= 4503599627370496ul; if ((occupy & 4512395720392704ul) == 0) result |= 2305843009213693952ul; return result; case 35: result = 17592253153280ul; if ((occupy & 67108864ul) == 0) result |= 131072ul; if ((occupy & 67239936ul) == 0) result |= 256ul; if ((occupy & 17592186044416ul) == 0) result |= 9007199254740992ul; if ((occupy & 9024791440785408ul) == 0) result |= 4611686018427387904ul; return result; case 36: result = 35184506306560ul; if ((occupy & 134217728ul) == 0) result |= 262144ul; if ((occupy & 134479872ul) == 0) result |= 512ul; if ((occupy & 134480384ul) == 0) result |= 1ul; if ((occupy & 35184372088832ul) == 0) result |= 18014398509481984ul; if ((occupy & 18049582881570816ul) == 0) result |= 9223372036854775808ul; return result; case 37: result = 70369012613120ul; if ((occupy & 268435456ul) == 0) result |= 524288ul; if ((occupy & 268959744ul) == 0) result |= 1024ul; if ((occupy & 268960768ul) == 0) result |= 2ul; if ((occupy & 70368744177664ul) == 0) result |= 36028797018963968ul; return result; case 38: result = 140738025226240ul; if ((occupy & 536870912ul) == 0) result |= 1048576ul; if ((occupy & 537919488ul) == 0) result |= 2048ul; if ((occupy & 537921536ul) == 0) result |= 4ul; return result; case 39: result = 1073741824ul; if ((occupy & 1073741824ul) == 0) result |= 2097152ul; if ((occupy & 1075838976ul) == 0) result |= 4096ul; if ((occupy & 1075843072ul) == 0) result |= 8ul; return result; case 40: result = 562949953421312ul; if ((occupy & 562949953421312ul) == 0) result |= 288230376151711744ul; return result; case 41: result = 1125904201809920ul; if ((occupy & 1125899906842624ul) == 0) result |= 576460752303423488ul; return result; case 42: result = 2251808403619840ul; if ((occupy & 8589934592ul) == 0) result |= 16777216ul; if ((occupy & 2251799813685248ul) == 0) result |= 1152921504606846976ul; return result; case 43: result = 4503616807239680ul; if ((occupy & 17179869184ul) == 0) result |= 33554432ul; if ((occupy & 17213423616ul) == 0) result |= 65536ul; if ((occupy & 4503599627370496ul) == 0) result |= 2305843009213693952ul; return result; case 44: result = 9007233614479360ul; if ((occupy & 34359738368ul) == 0) result |= 67108864ul; if ((occupy & 34426847232ul) == 0) result |= 131072ul; if ((occupy & 34426978304ul) == 0) result |= 256ul; if ((occupy & 9007199254740992ul) == 0) result |= 4611686018427387904ul; return result; case 45: result = 18014467228958720ul; if ((occupy & 68719476736ul) == 0) result |= 134217728ul; if ((occupy & 68853694464ul) == 0) result |= 262144ul; if ((occupy & 68853956608ul) == 0) result |= 512ul; if ((occupy & 68853957120ul) == 0) result |= 1ul; if ((occupy & 18014398509481984ul) == 0) result |= 9223372036854775808ul; return result; case 46: result = 36028934457917440ul; if ((occupy & 137438953472ul) == 0) result |= 268435456ul; if ((occupy & 137707388928ul) == 0) result |= 524288ul; if ((occupy & 137707913216ul) == 0) result |= 1024ul; if ((occupy & 137707914240ul) == 0) result |= 2ul; return result; case 47: result = 274877906944ul; if ((occupy & 274877906944ul) == 0) result |= 536870912ul; if ((occupy & 275414777856ul) == 0) result |= 1048576ul; if ((occupy & 275415826432ul) == 0) result |= 2048ul; if ((occupy & 275415828480ul) == 0) result |= 4ul; return result; case 48: result = 144115188075855872ul; return result; case 49: result = 288231475663339520ul; return result; case 50: result = 576462951326679040ul; if ((occupy & 2199023255552ul) == 0) result |= 4294967296ul; return result; case 51: result = 1152925902653358080ul; if ((occupy & 4398046511104ul) == 0) result |= 8589934592ul; if ((occupy & 4406636445696ul) == 0) result |= 16777216ul; return result; case 52: result = 2305851805306716160ul; if ((occupy & 8796093022208ul) == 0) result |= 17179869184ul; if ((occupy & 8813272891392ul) == 0) result |= 33554432ul; if ((occupy & 8813306445824ul) == 0) result |= 65536ul; return result; case 53: result = 4611703610613432320ul; if ((occupy & 17592186044416ul) == 0) result |= 34359738368ul; if ((occupy & 17626545782784ul) == 0) result |= 67108864ul; if ((occupy & 17626612891648ul) == 0) result |= 131072ul; if ((occupy & 17626613022720ul) == 0) result |= 256ul; return result; case 54: result = 9223407221226864640ul; if ((occupy & 35184372088832ul) == 0) result |= 68719476736ul; if ((occupy & 35253091565568ul) == 0) result |= 134217728ul; if ((occupy & 35253225783296ul) == 0) result |= 262144ul; if ((occupy & 35253226045440ul) == 0) result |= 512ul; if ((occupy & 35253226045952ul) == 0) result |= 1ul; return result; case 55: result = 70368744177664ul; if ((occupy & 70368744177664ul) == 0) result |= 137438953472ul; if ((occupy & 70506183131136ul) == 0) result |= 268435456ul; if ((occupy & 70506451566592ul) == 0) result |= 524288ul; if ((occupy & 70506452090880ul) == 0) result |= 1024ul; if ((occupy & 70506452091904ul) == 0) result |= 2ul; return result; case 56: result = 0ul; return result; case 57: result = 281474976710656ul; return result; case 58: result = 562949953421312ul; if ((occupy & 562949953421312ul) == 0) result |= 1099511627776ul; return result; case 59: result = 1125899906842624ul; if ((occupy & 1125899906842624ul) == 0) result |= 2199023255552ul; if ((occupy & 1128098930098176ul) == 0) result |= 4294967296ul; return result; case 60: result = 2251799813685248ul; if ((occupy & 2251799813685248ul) == 0) result |= 4398046511104ul; if ((occupy & 2256197860196352ul) == 0) result |= 8589934592ul; if ((occupy & 2256206450130944ul) == 0) result |= 16777216ul; return result; case 61: result = 4503599627370496ul; if ((occupy & 4503599627370496ul) == 0) result |= 8796093022208ul; if ((occupy & 4512395720392704ul) == 0) result |= 17179869184ul; if ((occupy & 4512412900261888ul) == 0) result |= 33554432ul; if ((occupy & 4512412933816320ul) == 0) result |= 65536ul; return result; case 62: result = 9007199254740992ul; if ((occupy & 9007199254740992ul) == 0) result |= 17592186044416ul; if ((occupy & 9024791440785408ul) == 0) result |= 34359738368ul; if ((occupy & 9024825800523776ul) == 0) result |= 67108864ul; if ((occupy & 9024825867632640ul) == 0) result |= 131072ul; if ((occupy & 9024825867763712ul) == 0) result |= 256ul; return result; case 63: result = 18014398509481984ul; if ((occupy & 18014398509481984ul) == 0) result |= 35184372088832ul; if ((occupy & 18049582881570816ul) == 0) result |= 68719476736ul; if ((occupy & 18049651601047552ul) == 0) result |= 134217728ul; if ((occupy & 18049651735265280ul) == 0) result |= 262144ul; if ((occupy & 18049651735527424ul) == 0) result |= 512ul; if ((occupy & 18049651735527936ul) == 0) result |= 1ul; return result; } return 0; } public static ulong Rook(int square, ulong occupy) { return GetSliderHCond(square, occupy) | GetSliderVCond(square, occupy); } public static ulong Bishop(int square, ulong occupy) { return GetSliderD1Cond(square, occupy) | GetSliderD2Cond(square, occupy); } public static ulong Queen(int square, ulong occupy) { return Rook(square, occupy) | Bishop(square, occupy); } [DllImport("Runtime\\Movegen_Compare.exe")] public static extern ulong Switch_t_Queen(int sq, ulong occupy); } }
44.836724
80
0.621957
[ "MIT" ]
Gigantua/Chess_Movegen
Movegen_dotNET/Sliders/Switch.cs
83,757
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Linq.Expressions; using Microsoft.EntityFrameworkCore.Utilities; namespace Microsoft.EntityFrameworkCore.Query.SqlExpressions { /// <summary> /// <para> /// An expression that represents a SQL token. /// </para> /// <para> /// This type is typically used by database providers (and other extensions). It is generally /// not used in application code. /// </para> /// </summary> public class SqlFragmentExpression : SqlExpression { /// <summary> /// Creates a new instance of the <see cref="SqlFragmentExpression" /> class. /// </summary> /// <param name="sql">A string token to print in SQL tree.</param> public SqlFragmentExpression(string sql) : base(typeof(string), null) { Check.NotEmpty(sql, nameof(sql)); Sql = sql; } /// <summary> /// The string token to print in SQL tree. /// </summary> public virtual string Sql { get; } /// <inheritdoc /> protected override Expression VisitChildren(ExpressionVisitor visitor) { Check.NotNull(visitor, nameof(visitor)); return this; } /// <inheritdoc /> protected override void Print(ExpressionPrinter expressionPrinter) { Check.NotNull(expressionPrinter, nameof(expressionPrinter)); expressionPrinter.Append(Sql); } /// <inheritdoc /> public override bool Equals(object? obj) => obj != null && (ReferenceEquals(this, obj) || obj is SqlFragmentExpression sqlFragmentExpression && Equals(sqlFragmentExpression)); private bool Equals(SqlFragmentExpression sqlFragmentExpression) => base.Equals(sqlFragmentExpression) && Sql == sqlFragmentExpression.Sql && Sql != "*"; // We make star projection different because it could be coming from different table. /// <inheritdoc /> public override int GetHashCode() => HashCode.Combine(base.GetHashCode(), Sql); } }
33.380282
116
0.586076
[ "MIT" ]
KaloyanIT/efcore
src/EFCore.Relational/Query/SqlExpressions/SqlFragmentExpression.cs
2,370
C#
namespace segmentVolumeDevice { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.volLvl = new System.Windows.Forms.Label(); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.usbToolStripStatusLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.displayUpdate = new System.Windows.Forms.Timer(this.components); this.dBBar = new System.Windows.Forms.ProgressBar(); this.statusStrip1.SuspendLayout(); this.SuspendLayout(); // // volLvl // this.volLvl.AutoSize = true; this.volLvl.Font = new System.Drawing.Font("Graphie", 60F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.volLvl.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(1)))), ((int)(((byte)(51)))), ((int)(((byte)(51))))); this.volLvl.Location = new System.Drawing.Point(-4, 9); this.volLvl.Name = "volLvl"; this.volLvl.Size = new System.Drawing.Size(257, 96); this.volLvl.TabIndex = 1; this.volLvl.Text = "100%"; // // statusStrip1 // this.statusStrip1.AllowMerge = false; this.statusStrip1.GripStyle = System.Windows.Forms.ToolStripGripStyle.Visible; this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.usbToolStripStatusLabel}); this.statusStrip1.Location = new System.Drawing.Point(0, 128); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.Size = new System.Drawing.Size(249, 22); this.statusStrip1.SizingGrip = false; this.statusStrip1.TabIndex = 2; this.statusStrip1.Text = "Unknown"; // // usbToolStripStatusLabel // this.usbToolStripStatusLabel.BackColor = System.Drawing.SystemColors.ControlLight; this.usbToolStripStatusLabel.ImageTransparentColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224))))); this.usbToolStripStatusLabel.Name = "usbToolStripStatusLabel"; this.usbToolStripStatusLabel.Size = new System.Drawing.Size(58, 17); this.usbToolStripStatusLabel.Text = "usbStatus"; // // displayUpdate // this.displayUpdate.Enabled = true; this.displayUpdate.Tick += new System.EventHandler(this.displayUpdate_tick); // // dBBar // this.dBBar.Cursor = System.Windows.Forms.Cursors.Default; this.dBBar.ForeColor = System.Drawing.Color.Lime; this.dBBar.Location = new System.Drawing.Point(12, 101); this.dBBar.Name = "dBBar"; this.dBBar.Size = new System.Drawing.Size(225, 20); this.dBBar.TabIndex = 3; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoValidate = System.Windows.Forms.AutoValidate.EnablePreventFocusChange; this.BackColor = System.Drawing.SystemColors.ButtonHighlight; this.ClientSize = new System.Drawing.Size(249, 150); this.Controls.Add(this.dBBar); this.Controls.Add(this.statusStrip1); this.Controls.Add(this.volLvl); this.Font = new System.Drawing.Font("MS Reference Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.Name = "Form1"; this.Text = "Flutter v1.0"; this.Load += new System.EventHandler(this.Form1_Load); this.statusStrip1.ResumeLayout(false); this.statusStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label volLvl; private System.Windows.Forms.StatusStrip statusStrip1; private System.Windows.Forms.Timer displayUpdate; private System.Windows.Forms.ToolStripStatusLabel usbToolStripStatusLabel; private System.Windows.Forms.ProgressBar dBBar; } }
46.966667
167
0.603797
[ "MIT" ]
tristanluther28/flutter
Software/VisualStudio19/Tristan's Workshop/Form1.Designer.cs
5,638
C#
/* Copyright 2010-2012 Ivan Alles. Licensed under the MIT License (see file LICENSE). */ using ai.lib.utils.commandline; namespace ai.lib.utils.version { /// <summary> /// Command line. /// </summary> class CommandLine { #region File parameters [DefaultArgument(ArgumentType.Multiple | ArgumentType.Required, LongName = "file", HelpText = "File(s) to process.")] public string[] Files = null; #endregion #region Options [Argument(ArgumentType.AtMostOnce, LongName = "set-user-descr", ShortName = "u", DefaultValue = null, HelpText = "Sets user description.")] public string SetUserDescr = null; [Argument(ArgumentType.AtMostOnce, LongName = "show-names", ShortName = "n", DefaultValue = false, HelpText = "Print file names.")] public bool PrintFileNames = false; #endregion } }
27.264706
90
0.621359
[ "MIT" ]
ivan-alles/poker-acpc
lib/utils/trunk/src/main/net/ai.lib.utils.version/CommandLine.cs
927
C#
using System; namespace AngularDemo1.Areas.HelpPage { /// <summary> /// This represents an invalid sample on the help page. There's a display template named InvalidSample associated with this class. /// </summary> public class InvalidSample { public InvalidSample(string errorMessage) { if (errorMessage == null) { throw new ArgumentNullException("errorMessage"); } ErrorMessage = errorMessage; } public string ErrorMessage { get; private set; } public override bool Equals(object obj) { InvalidSample other = obj as InvalidSample; return other != null && ErrorMessage == other.ErrorMessage; } public override int GetHashCode() { return ErrorMessage.GetHashCode(); } public override string ToString() { return ErrorMessage; } } }
26.324324
134
0.575975
[ "MIT" ]
V4NC3/angulardemo
AngularDemo1/Areas/HelpPage/SampleGeneration/InvalidSample.cs
974
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Nether.Ingest { public interface ITypeVersionMessage { string Type { get; } string Version { get; } } }
24.583333
101
0.681356
[ "MIT" ]
navalev/nether
src/Nether.Ingest/IMessage.cs
297
C#
using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using Xceed.Wpf.Toolkit; namespace TubeStar { public static class DialogHelper { private static Grid RootElement { get { return LogicalTreeHelper.FindLogicalNode(Application.Current.MainWindow, "LayoutRoot") as Grid; } } public static void ShowDialog(this ChildWindow window, Action onClose = null) { RootElement.Children.Add(window); window.IsModal = true; window.WindowStartupLocation = Xceed.Wpf.Toolkit.WindowStartupLocation.Center; Grid.SetRowSpan(window, 10); Grid.SetColumnSpan(window, 10); window.Closed += (s, ea) => { RootElement.Children.Remove(window); if (onClose != null) onClose(); }; window.Show(); window.Focus(); } } }
28.189189
111
0.565676
[ "MIT" ]
mchall/TubeStar
TubeStarDesktop/Helpers/DialogHelper.cs
1,045
C#
/* * OpenBots Server API * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: v1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = OpenBots.Server.SDK.Client.SwaggerDateConverter; namespace OpenBots.Server.SDK.Model { /// <summary> /// Stores the current status of a job /// </summary> /// <value>Stores the current status of a job</value> [JsonConverter(typeof(StringEnumConverter))] public enum JobStatusType { /// <summary> /// Enum Unknown for value: Unknown /// </summary> [EnumMember(Value = "Unknown")] Unknown = 0, /// <summary> /// Enum New for value: New /// </summary> [EnumMember(Value = "New")] New = 1, /// <summary> /// Enum Assigned for value: Assigned /// </summary> [EnumMember(Value = "Assigned")] Assigned = 2, /// <summary> /// Enum InProgress for value: InProgress /// </summary> [EnumMember(Value = "InProgress")] InProgress = 3, /// <summary> /// Enum Failed for value: Failed /// </summary> [EnumMember(Value = "Failed")] Failed = 4, /// <summary> /// Enum Completed for value: Completed /// </summary> [EnumMember(Value = "Completed")] Completed = 5, /// <summary> /// Enum Stopping for value: Stopping /// </summary> [EnumMember(Value = "Stopping")] Stopping = 6, /// <summary> /// Enum Abandoned for value: Abandoned /// </summary> [EnumMember(Value = "Abandoned")] Abandoned = 9 } }
29.067568
104
0.594607
[ "MIT" ]
OpenBotsAI/OpenBots.Server.SDK
src/OpenBots.Server.SDK/Model/JobStatusType.cs
2,151
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using static Il2CppDumper.Il2CppConstants; namespace Il2CppDumper { public class Il2CppDecompiler { private Il2CppExecutor executor; private Metadata metadata; private Il2Cpp il2Cpp; private Dictionary<Il2CppMethodDefinition, string> methodModifiers = new Dictionary<Il2CppMethodDefinition, string>(); public Il2CppDecompiler(Il2CppExecutor il2CppExecutor) { executor = il2CppExecutor; metadata = il2CppExecutor.metadata; il2Cpp = il2CppExecutor.il2Cpp; } public void Decompile(Config config, string outputDir) { var writer = new StreamWriter(new FileStream(outputDir + "dump.cs", FileMode.Create), new UTF8Encoding(false)); //dump image for (var imageIndex = 0; imageIndex < metadata.imageDefs.Length; imageIndex++) { var imageDef = metadata.imageDefs[imageIndex]; writer.Write($"// Image {imageIndex}: {metadata.GetStringFromIndex(imageDef.nameIndex)} - {imageDef.typeStart}\n"); } //dump type for (var imageIndex = 0; imageIndex < metadata.imageDefs.Length; imageIndex++) { try { var imageDef = metadata.imageDefs[imageIndex]; var typeEnd = imageDef.typeStart + imageDef.typeCount; for (int typeDefIndex = imageDef.typeStart; typeDefIndex < typeEnd; typeDefIndex++) { var typeDef = metadata.typeDefs[typeDefIndex]; var extends = new List<string>(); if (typeDef.parentIndex >= 0) { var parent = il2Cpp.types[typeDef.parentIndex]; var parentName = executor.GetTypeName(parent, false, false); if (!typeDef.IsValueType && !typeDef.IsEnum && parentName != "object") { extends.Add(parentName); } } if (typeDef.interfaces_count > 0) { for (int i = 0; i < typeDef.interfaces_count; i++) { var @interface = il2Cpp.types[metadata.interfaceIndices[typeDef.interfacesStart + i]]; extends.Add(executor.GetTypeName(@interface, false, false)); } } writer.Write($"\n// Namespace: {metadata.GetStringFromIndex(typeDef.namespaceIndex)}\n"); if (config.DumpAttribute) { writer.Write(GetCustomAttribute(imageDef, typeDef.customAttributeIndex, typeDef.token)); } if (config.DumpAttribute && (typeDef.flags & TYPE_ATTRIBUTE_SERIALIZABLE) != 0) writer.Write("[Serializable]\n"); var visibility = typeDef.flags & TYPE_ATTRIBUTE_VISIBILITY_MASK; switch (visibility) { case TYPE_ATTRIBUTE_PUBLIC: case TYPE_ATTRIBUTE_NESTED_PUBLIC: writer.Write("public "); break; case TYPE_ATTRIBUTE_NOT_PUBLIC: case TYPE_ATTRIBUTE_NESTED_FAM_AND_ASSEM: case TYPE_ATTRIBUTE_NESTED_ASSEMBLY: writer.Write("internal "); break; case TYPE_ATTRIBUTE_NESTED_PRIVATE: writer.Write("private "); break; case TYPE_ATTRIBUTE_NESTED_FAMILY: writer.Write("protected "); break; case TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM: writer.Write("protected internal "); break; } if ((typeDef.flags & TYPE_ATTRIBUTE_ABSTRACT) != 0 && (typeDef.flags & TYPE_ATTRIBUTE_SEALED) != 0) writer.Write("static "); else if ((typeDef.flags & TYPE_ATTRIBUTE_INTERFACE) == 0 && (typeDef.flags & TYPE_ATTRIBUTE_ABSTRACT) != 0) writer.Write("abstract "); else if (!typeDef.IsValueType && !typeDef.IsEnum && (typeDef.flags & TYPE_ATTRIBUTE_SEALED) != 0) writer.Write("sealed "); if ((typeDef.flags & TYPE_ATTRIBUTE_INTERFACE) != 0) writer.Write("interface "); else if (typeDef.IsEnum) writer.Write("enum "); else if (typeDef.IsValueType) writer.Write("struct "); else writer.Write("class "); var typeName = executor.GetTypeDefName(typeDef, false, true); writer.Write($"{typeName}"); if (extends.Count > 0) writer.Write($" : {string.Join(", ", extends)}"); if (config.DumpTypeDefIndex) writer.Write($" // TypeDefIndex: {typeDefIndex}\n{{"); else writer.Write("\n{"); //dump field if (config.DumpField && typeDef.field_count > 0) { writer.Write("\n\t// Fields\n"); var fieldEnd = typeDef.fieldStart + typeDef.field_count; for (var i = typeDef.fieldStart; i < fieldEnd; ++i) { var fieldDef = metadata.fieldDefs[i]; var fieldType = il2Cpp.types[fieldDef.typeIndex]; var isStatic = false; if (config.DumpAttribute) { writer.Write(GetCustomAttribute(imageDef, fieldDef.customAttributeIndex, fieldDef.token, "\t")); } writer.Write("\t"); var access = fieldType.attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK; switch (access) { case FIELD_ATTRIBUTE_PRIVATE: writer.Write("private "); break; case FIELD_ATTRIBUTE_PUBLIC: writer.Write("public "); break; case FIELD_ATTRIBUTE_FAMILY: writer.Write("protected "); break; case FIELD_ATTRIBUTE_ASSEMBLY: case FIELD_ATTRIBUTE_FAM_AND_ASSEM: writer.Write("internal "); break; case FIELD_ATTRIBUTE_FAM_OR_ASSEM: writer.Write("protected internal "); break; } if ((fieldType.attrs & FIELD_ATTRIBUTE_LITERAL) != 0) { writer.Write("const "); } else { if ((fieldType.attrs & FIELD_ATTRIBUTE_STATIC) != 0) { isStatic = true; writer.Write("static "); } if ((fieldType.attrs & FIELD_ATTRIBUTE_INIT_ONLY) != 0) { writer.Write("readonly "); } } writer.Write($"{executor.GetTypeName(fieldType, false, false)} {metadata.GetStringFromIndex(fieldDef.nameIndex)}"); if (metadata.GetFieldDefaultValueFromIndex(i, out var fieldDefaultValue) && fieldDefaultValue.dataIndex != -1) { if (TryGetDefaultValue(fieldDefaultValue.typeIndex, fieldDefaultValue.dataIndex, out var value)) { writer.Write($" = "); if (value is string str) { writer.Write($"\"{str.ToEscapedString()}\""); } else if (value is char c) { var v = (int)c; writer.Write($"'\\x{v:x}'"); } else if (value != null) { writer.Write($"{value}"); } } else { writer.Write($" /*Metadata offset 0x{value:X}*/"); } } if (config.DumpFieldOffset) writer.Write("; // 0x{0:X}\n", il2Cpp.GetFieldOffsetFromIndex(typeDefIndex, i - typeDef.fieldStart, i, typeDef.IsValueType, isStatic)); else writer.Write(";\n"); } } //dump property if (config.DumpProperty && typeDef.property_count > 0) { writer.Write("\n\t// Properties\n"); var propertyEnd = typeDef.propertyStart + typeDef.property_count; for (var i = typeDef.propertyStart; i < propertyEnd; ++i) { var propertyDef = metadata.propertyDefs[i]; if (config.DumpAttribute) { writer.Write(GetCustomAttribute(imageDef, propertyDef.customAttributeIndex, propertyDef.token, "\t")); } writer.Write("\t"); if (propertyDef.get >= 0) { var methodDef = metadata.methodDefs[typeDef.methodStart + propertyDef.get]; writer.Write(GetModifiers(methodDef)); var propertyType = il2Cpp.types[methodDef.returnType]; writer.Write($"{executor.GetTypeName(propertyType, false, false)} {metadata.GetStringFromIndex(propertyDef.nameIndex)} {{ "); } else if (propertyDef.set >= 0) { var methodDef = metadata.methodDefs[typeDef.methodStart + propertyDef.set]; writer.Write(GetModifiers(methodDef)); var parameterDef = metadata.parameterDefs[methodDef.parameterStart]; var propertyType = il2Cpp.types[parameterDef.typeIndex]; writer.Write($"{executor.GetTypeName(propertyType, false, false)} {metadata.GetStringFromIndex(propertyDef.nameIndex)} {{ "); } if (propertyDef.get >= 0) writer.Write("get; "); if (propertyDef.set >= 0) writer.Write("set; "); writer.Write("}"); writer.Write("\n"); } } //dump method if (config.DumpMethod && typeDef.method_count > 0) { writer.Write("\n\t// Methods\n"); var methodEnd = typeDef.methodStart + typeDef.method_count; for (var i = typeDef.methodStart; i < methodEnd; ++i) { writer.Write("\n"); var methodDef = metadata.methodDefs[i]; if (config.DumpAttribute) { writer.Write(GetCustomAttribute(imageDef, methodDef.customAttributeIndex, methodDef.token, "\t")); } if (config.DumpMethodOffset) { var methodPointer = il2Cpp.GetMethodPointer(methodDef, imageIndex); if (methodPointer > 0) { var fixedMethodPointer = il2Cpp.GetRVA(methodPointer); writer.Write("\t// RVA: 0x{0:X} Offset: 0x{1:X} VA: 0x{2:X}", fixedMethodPointer, il2Cpp.MapVATR(methodPointer), methodPointer); } else { writer.Write("\t// RVA: -1 Offset: -1"); } if (methodDef.slot != ushort.MaxValue) { writer.Write(" Slot: {0}", methodDef.slot); } writer.Write("\n"); } writer.Write("\t"); writer.Write(GetModifiers(methodDef)); var methodReturnType = il2Cpp.types[methodDef.returnType]; var methodName = metadata.GetStringFromIndex(methodDef.nameIndex); if (methodDef.genericContainerIndex >= 0) { var genericContainer = metadata.genericContainers[methodDef.genericContainerIndex]; methodName += executor.GetGenericContainerParams(genericContainer); } if (methodReturnType.byref == 1) { writer.Write("ref "); } writer.Write($"{executor.GetTypeName(methodReturnType, false, false)} {methodName}("); var parameterStrs = new List<string>(); for (var j = 0; j < methodDef.parameterCount; ++j) { var parameterStr = ""; var parameterDef = metadata.parameterDefs[methodDef.parameterStart + j]; var parameterName = metadata.GetStringFromIndex(parameterDef.nameIndex); var parameterType = il2Cpp.types[parameterDef.typeIndex]; var parameterTypeName = executor.GetTypeName(parameterType, false, false); if (parameterType.byref == 1) { if ((parameterType.attrs & PARAM_ATTRIBUTE_OUT) != 0 && (parameterType.attrs & PARAM_ATTRIBUTE_IN) == 0) { parameterStr += "out "; } else if ((parameterType.attrs & PARAM_ATTRIBUTE_OUT) == 0 && (parameterType.attrs & PARAM_ATTRIBUTE_IN) != 0) { parameterStr += "in "; } else { parameterStr += "ref "; } } else { if ((parameterType.attrs & PARAM_ATTRIBUTE_IN) != 0) { parameterStr += "[In] "; } if ((parameterType.attrs & PARAM_ATTRIBUTE_OUT) != 0) { parameterStr += "[Out] "; } } parameterStr += $"{parameterTypeName} {parameterName}"; if (metadata.GetParameterDefaultValueFromIndex(methodDef.parameterStart + j, out var parameterDefault) && parameterDefault.dataIndex != -1) { if (TryGetDefaultValue(parameterDefault.typeIndex, parameterDefault.dataIndex, out var value)) { parameterStr += " = "; if (value is string str) { parameterStr += $"\"{str.ToEscapedString()}\""; } else if (value is char c) { var v = (int)c; parameterStr += $"'\\x{v:x}'"; } else if (value != null) { parameterStr += $"{value}"; } } else { parameterStr += $" /*Metadata offset 0x{value:X}*/"; } } parameterStrs.Add(parameterStr); } writer.Write(string.Join(", ", parameterStrs)); writer.Write(") { }\n"); if (il2Cpp.methodDefinitionMethodSpecs.TryGetValue(i, out var methodSpecs)) { writer.Write("\t/* GenericInstMethod :\n"); var groups = methodSpecs.GroupBy(x => il2Cpp.methodSpecGenericMethodPointers[x]); foreach (var group in groups) { writer.Write("\t|\n"); var genericMethodPointer = group.Key; if (genericMethodPointer > 0) { var fixedPointer = il2Cpp.GetRVA(genericMethodPointer); writer.Write($"\t|-RVA: 0x{fixedPointer:X} Offset: 0x{il2Cpp.MapVATR(genericMethodPointer):X} VA: 0x{genericMethodPointer:X}\n"); } else { writer.Write("\t|-RVA: -1 Offset: -1\n"); } foreach (var methodSpec in group) { (var methodSpecTypeName, var methodSpecMethodName) = executor.GetMethodSpecName(methodSpec); writer.Write($"\t|-{methodSpecTypeName}.{methodSpecMethodName}\n"); } } writer.Write("\t*/\n"); } } } writer.Write("}\n"); } } catch (Exception e) { Console.WriteLine("ERROR: Some errors in dumping"); writer.Write("/*"); writer.Write(e); writer.Write("*/\n}\n"); } } writer.Close(); } public string GetCustomAttribute(Il2CppImageDefinition image, int customAttributeIndex, uint token, string padding = "") { if (il2Cpp.Version < 21) return string.Empty; var attributeIndex = metadata.GetCustomAttributeIndex(image, customAttributeIndex, token); if (attributeIndex >= 0) { var attributeTypeRange = metadata.attributeTypeRanges[attributeIndex]; var sb = new StringBuilder(); for (var i = 0; i < attributeTypeRange.count; i++) { var typeIndex = metadata.attributeTypes[attributeTypeRange.start + i]; var methodPointer = il2Cpp.customAttributeGenerators[attributeIndex]; var fixedMethodPointer = il2Cpp.GetRVA(methodPointer); sb.AppendFormat("{0}[{1}] // RVA: 0x{2:X} Offset: 0x{3:X} VA: 0x{4:X}\n", padding, executor.GetTypeName(il2Cpp.types[typeIndex], false, false), fixedMethodPointer, il2Cpp.MapVATR(methodPointer), methodPointer); } return sb.ToString(); } else { return string.Empty; } } public string GetModifiers(Il2CppMethodDefinition methodDef) { if (methodModifiers.TryGetValue(methodDef, out string str)) return str; var access = methodDef.flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK; switch (access) { case METHOD_ATTRIBUTE_PRIVATE: str += "private "; break; case METHOD_ATTRIBUTE_PUBLIC: str += "public "; break; case METHOD_ATTRIBUTE_FAMILY: str += "protected "; break; case METHOD_ATTRIBUTE_ASSEM: case METHOD_ATTRIBUTE_FAM_AND_ASSEM: str += "internal "; break; case METHOD_ATTRIBUTE_FAM_OR_ASSEM: str += "protected internal "; break; } if ((methodDef.flags & METHOD_ATTRIBUTE_STATIC) != 0) str += "static "; if ((methodDef.flags & METHOD_ATTRIBUTE_ABSTRACT) != 0) { str += "abstract "; if ((methodDef.flags & METHOD_ATTRIBUTE_VTABLE_LAYOUT_MASK) == METHOD_ATTRIBUTE_REUSE_SLOT) str += "override "; } else if ((methodDef.flags & METHOD_ATTRIBUTE_FINAL) != 0) { if ((methodDef.flags & METHOD_ATTRIBUTE_VTABLE_LAYOUT_MASK) == METHOD_ATTRIBUTE_REUSE_SLOT) str += "sealed override "; } else if ((methodDef.flags & METHOD_ATTRIBUTE_VIRTUAL) != 0) { if ((methodDef.flags & METHOD_ATTRIBUTE_VTABLE_LAYOUT_MASK) == METHOD_ATTRIBUTE_NEW_SLOT) str += "virtual "; else str += "override "; } if ((methodDef.flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) != 0) str += "extern "; methodModifiers.Add(methodDef, str); return str; } private bool TryGetDefaultValue(int typeIndex, int dataIndex, out object value) { var pointer = metadata.GetDefaultValueFromIndex(dataIndex); var defaultValueType = il2Cpp.types[typeIndex]; metadata.Position = pointer; switch (defaultValueType.type) { case Il2CppTypeEnum.IL2CPP_TYPE_BOOLEAN: value = metadata.ReadBoolean(); return true; case Il2CppTypeEnum.IL2CPP_TYPE_U1: value = metadata.ReadByte(); return true; case Il2CppTypeEnum.IL2CPP_TYPE_I1: value = metadata.ReadSByte(); return true; case Il2CppTypeEnum.IL2CPP_TYPE_CHAR: value = BitConverter.ToChar(metadata.ReadBytes(2), 0); return true; case Il2CppTypeEnum.IL2CPP_TYPE_U2: value = metadata.ReadUInt16(); return true; case Il2CppTypeEnum.IL2CPP_TYPE_I2: value = metadata.ReadInt16(); return true; case Il2CppTypeEnum.IL2CPP_TYPE_U4: value = metadata.ReadUInt32(); return true; case Il2CppTypeEnum.IL2CPP_TYPE_I4: value = metadata.ReadInt32(); return true; case Il2CppTypeEnum.IL2CPP_TYPE_U8: value = metadata.ReadUInt64(); return true; case Il2CppTypeEnum.IL2CPP_TYPE_I8: value = metadata.ReadInt64(); return true; case Il2CppTypeEnum.IL2CPP_TYPE_R4: value = metadata.ReadSingle(); return true; case Il2CppTypeEnum.IL2CPP_TYPE_R8: value = metadata.ReadDouble(); return true; case Il2CppTypeEnum.IL2CPP_TYPE_STRING: var len = metadata.ReadInt32(); value = Encoding.UTF8.GetString(metadata.ReadBytes(len)); return true; default: value = pointer; return false; } } } }
54.97076
175
0.388865
[ "MIT" ]
CrootonGaming/Il2CppDumper
Il2CppDumper/Outputs/Il2CppDecompiler.cs
28,202
C#
// // StaticRegistrar.cs: The static registrar // // Authors: // Rolf Bjarne Kvinge <rolf@xamarin.com> // // Copyright 2013 Xamarin Inc. // using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Xamarin.Bundler; using Xamarin.Linker; #if MTOUCH using ProductException=Xamarin.Bundler.MonoTouchException; #else using ProductException=Xamarin.Bundler.MonoMacException; #endif using Registrar; using Foundation; using ObjCRuntime; using Mono.Cecil; using Mono.Tuner; namespace Registrar { /* * This class will automatically detect lines starting/ending with curly braces, * and indent/unindent accordingly. * * It doesn't cope with indentation due to other circumstances than * curly braces (such as one-line if statements for instance). In this case * call Indent/Unindent manually. * * Also don't try to print '\n' directly, it'll get confused. Use * the AppendLine/WriteLine family of methods instead. */ class AutoIndentStringBuilder : IDisposable { StringBuilder sb = new StringBuilder (); int indent; bool was_last_newline = true; public int Indentation { get { return indent; } set { indent = value; } } public AutoIndentStringBuilder () { } public AutoIndentStringBuilder (int indentation) { indent = indentation; } public StringBuilder StringBuilder { get { return sb; } } void OutputIndentation () { if (!was_last_newline) return; sb.Append ('\t', indent); was_last_newline = false; } void Output (string a) { if (a.StartsWith ("}", StringComparison.Ordinal)) Unindent (); OutputIndentation (); sb.Append (a); if (a.EndsWith ("{", StringComparison.Ordinal)) Indent (); } public AutoIndentStringBuilder AppendLine (AutoIndentStringBuilder isb) { if (isb.Length > 0) { sb.Append (isb.ToString ()); AppendLine (); } return this; } public AutoIndentStringBuilder Append (AutoIndentStringBuilder isb) { if (isb.Length > 0) sb.Append (isb.ToString ()); return this; } public AutoIndentStringBuilder Append (string value) { Output (value); return this; } public AutoIndentStringBuilder AppendFormat (string format, params object[] args) { Output (string.Format (format, args)); return this; } public AutoIndentStringBuilder AppendLine (string value) { Output (value); sb.AppendLine (); was_last_newline = true; return this; } public AutoIndentStringBuilder AppendLine () { sb.AppendLine (); was_last_newline = true; return this; } public AutoIndentStringBuilder AppendLine (string format, params object[] args) { Output (string.Format (format, args)); sb.AppendLine (); was_last_newline = true; return this; } public AutoIndentStringBuilder Write (string value) { return Append (value); } public AutoIndentStringBuilder Write (string format, params object[] args) { return AppendFormat (format, args); } public AutoIndentStringBuilder WriteLine (string format, params object[] args) { return AppendLine (format, args); } public AutoIndentStringBuilder WriteLine (string value) { return AppendLine (value); } public AutoIndentStringBuilder WriteLine () { return AppendLine (); } public AutoIndentStringBuilder WriteLine (AutoIndentStringBuilder isb) { return AppendLine (isb); } public void Replace (string find, string replace) { sb.Replace (find, replace); } public AutoIndentStringBuilder Indent () { indent++; if (indent > 100) throw new ArgumentOutOfRangeException ("indent"); return this; } public AutoIndentStringBuilder Unindent () { indent--; return this; } public int Length { get { return sb.Length; } } public void Clear () { sb.Clear (); was_last_newline = true; } public void Dispose () { Clear (); } public override string ToString () { return sb.ToString (0, sb.Length); } } interface IStaticRegistrar { bool HasAttribute (ICustomAttributeProvider provider, string @namespace, string name, bool inherits = false); bool HasProtocolAttribute (TypeReference type); RegisterAttribute GetRegisterAttribute (TypeReference type); ProtocolAttribute GetProtocolAttribute (TypeReference type); string GetExportedTypeName (TypeReference type, RegisterAttribute register_attribute); void GenerateSingleAssembly (IEnumerable<AssemblyDefinition> assemblies, string header_path, string source_path, string assembly); void Generate (IEnumerable<AssemblyDefinition> assemblies, string header_path, string source_path); string ComputeSignature (TypeReference DeclaringType, MethodDefinition Method, Registrar.ObjCMember member = null, bool isCategoryInstance = false, bool isBlockSignature = false); string ComputeSignature (TypeReference declaring_type, bool is_ctor, TypeReference return_type, TypeReference [] parameters, MethodDefinition mi = null, Registrar.ObjCMember member = null, bool isCategoryInstance = false, bool isBlockSignature = false); bool MapProtocolMember (MethodDefinition method, out MethodDefinition extensionMethod); string PlatformAssembly { get; } Dictionary<ICustomAttribute, MethodDefinition> ProtocolMemberMethodMap { get; } } class StaticRegistrar : Registrar, IStaticRegistrar { Dictionary<ICustomAttribute, MethodDefinition> protocol_member_method_map; public Dictionary<ICustomAttribute, MethodDefinition> ProtocolMemberMethodMap { get { if (protocol_member_method_map == null) { #if MTOUCH if ((App.IsExtension && !App.IsWatchExtension) && App.IsCodeShared) { protocol_member_method_map = Target.ContainerTarget.StaticRegistrar.ProtocolMemberMethodMap; } else { protocol_member_method_map = new Dictionary<ICustomAttribute, MethodDefinition> (); } #else protocol_member_method_map = new Dictionary<ICustomAttribute, MethodDefinition> (); #endif } return protocol_member_method_map; } } public static bool IsPlatformType (TypeReference type, string @namespace, string name) { if (Registrar.IsDualBuild) { return type.Is (@namespace, name); } else { return type.Is (Registrar.CompatNamespace + "." + @namespace, name); } } public static bool ParametersMatch (IList<ParameterDefinition> a, TypeReference [] b) { if (a == null && b == null) return true; if (a == null ^ b == null) return false; if (a.Count != b.Length) return false; for (var i = 0; i < b.Length; i++) if (!TypeMatch (a [i].ParameterType, b [i])) return false; return true; } public static bool TypeMatch (IModifierType a, IModifierType b) { if (!TypeMatch (a.ModifierType, b.ModifierType)) return false; return TypeMatch (a.ElementType, b.ElementType); } public static bool TypeMatch (TypeSpecification a, TypeSpecification b) { if (a is GenericInstanceType) return TypeMatch ((GenericInstanceType) a, (GenericInstanceType) b); if (a is IModifierType) return TypeMatch ((IModifierType) a, (IModifierType) b); return TypeMatch (a.ElementType, b.ElementType); } public static bool TypeMatch (GenericInstanceType a, GenericInstanceType b) { if (!TypeMatch (a.ElementType, b.ElementType)) return false; if (a.GenericArguments.Count != b.GenericArguments.Count) return false; if (a.GenericArguments.Count == 0) return true; for (int i = 0; i < a.GenericArguments.Count; i++) if (!TypeMatch (a.GenericArguments [i], b.GenericArguments [i])) return false; return true; } public static bool TypeMatch (TypeReference a, TypeReference b) { if (a is GenericParameter) return true; if (a is TypeSpecification || b is TypeSpecification) { if (a.GetType () != b.GetType ()) return false; return TypeMatch ((TypeSpecification) a, (TypeSpecification) b); } return a.FullName == b.FullName; } public static bool MethodMatch (MethodDefinition candidate, MethodDefinition method) { if (!candidate.IsVirtual) return false; if (candidate.Name != method.Name) return false; if (!TypeMatch (candidate.ReturnType, method.ReturnType)) return false; if (!candidate.HasParameters) return !method.HasParameters; if (candidate.Parameters.Count != method.Parameters.Count) return false; for (int i = 0; i < candidate.Parameters.Count; i++) if (!TypeMatch (candidate.Parameters [i].ParameterType, method.Parameters [i].ParameterType)) return false; return true; } void CollectInterfaces (ref List<TypeDefinition> ifaces, TypeDefinition type) { if (type == null) return; if (type.BaseType != null) CollectInterfaces (ref ifaces, type.BaseType.Resolve ()); if (!type.HasInterfaces) return; foreach (var iface in type.Interfaces) { var itd = iface.InterfaceType.Resolve (); CollectInterfaces (ref ifaces, itd); if (!HasAttribute (itd, Registrar.Foundation, Registrar.StringConstants.ProtocolAttribute)) continue; if (ifaces == null) { ifaces = new List<TypeDefinition> (); } else if (ifaces.Contains (itd)) { continue; } ifaces.Add (itd); } } public Dictionary<MethodDefinition, List<MethodDefinition>> PrepareInterfaceMethodMapping (TypeReference type) { TypeDefinition td = type.Resolve (); List<TypeDefinition> ifaces = null; List<MethodDefinition> iface_methods; Dictionary<MethodDefinition, List<MethodDefinition>> rv = null; CollectInterfaces (ref ifaces, td); if (ifaces == null) return null; iface_methods = new List<MethodDefinition> (); foreach (var iface in ifaces) { var storedMethods = LinkContext?.GetProtocolMethods (iface.Resolve ()); if (storedMethods?.Count > 0) { foreach (var imethod in storedMethods) if (!iface_methods.Contains (imethod)) iface_methods.Add (imethod); } if (!iface.HasMethods) continue; foreach (var imethod in iface.Methods) { if (!iface_methods.Contains (imethod)) iface_methods.Add (imethod); } } // We only care about implementators declared in 'type'. // First find all explicitly implemented methods. foreach (var impl in td.Methods) { if (!impl.HasOverrides) continue; foreach (var ifaceMethod in impl.Overrides) { var ifaceMethodDef = ifaceMethod.Resolve (); if (!iface_methods.Contains (ifaceMethodDef)) { // The type may implement interfaces which aren't protocol interfaces, so this is OK. } else { iface_methods.Remove (ifaceMethodDef); List<MethodDefinition> list; if (rv == null) { rv = new Dictionary<MethodDefinition, List<MethodDefinition>> (); rv [impl] = list = new List<MethodDefinition> (); } else if (!rv.TryGetValue (impl, out list)) { rv [impl] = list = new List<MethodDefinition> (); } list.Add (ifaceMethodDef); } } } // Next find all implicitly implemented methods. foreach (var ifaceMethod in iface_methods) { foreach (var impl in td.Methods) { if (impl.Name != ifaceMethod.Name) continue; if (!MethodMatch (impl, ifaceMethod)) continue; List<MethodDefinition> list; if (rv == null) { rv = new Dictionary<MethodDefinition, List<MethodDefinition>> (); rv [impl] = list = new List<MethodDefinition> (); } else if (!rv.TryGetValue (impl, out list)) { rv [impl] = list = new List<MethodDefinition> (); } list.Add (ifaceMethod); } } return rv; } public static TypeReference GetEnumUnderlyingType (TypeDefinition type) { foreach (FieldDefinition field in type.Fields) if (field.IsSpecialName && field.Name == "value__") return field.FieldType; return null; } public string ToObjCType (TypeReference type) { var definition = type as TypeDefinition; if (definition != null) return ToObjCType (definition); if (type is TypeSpecification) return ToObjCType (((TypeSpecification) type).ElementType) + " *"; definition = type.Resolve (); if (definition != null) return ToObjCType (definition); return "void *"; } public string ToObjCType (TypeDefinition type) { switch (type.FullName) { case "System.IntPtr": return "void *"; case "System.SByte": return "unsigned char"; case "System.Byte": return "signed char"; case "System.Char": return "signed short"; case "System.Int16": return "short"; case "System.UInt16": return "unsigned short"; case "System.Int32": return "int"; case "System.UInt32": return "unsigned int"; case "System.Int64": return "long long"; case "System.UInt64": return "unsigned long long"; case "System.Single": return "float"; case "System.Double": return "double"; case "System.Boolean": return "BOOL"; case "System.Void": return "void"; case "System.String": return "NSString"; case Registrar.CompatNamespace + ".ObjCRuntime.Selector": return "SEL"; case Registrar.CompatNamespace + ".ObjCRuntime.Class": return "Class"; } if (IsNativeObject (type)) return "id"; if (IsDelegate (type)) return "id"; if (type.IsEnum) return ToObjCType (GetEnumUnderlyingType (type)); if (type.IsValueType) { return "void *"; } throw ErrorHelper.CreateError (4108, "The registrar cannot get the ObjectiveC type for managed type `{0}`.", type.FullName); } public static bool IsDelegate (TypeDefinition type) { while (type != null) { if (type.FullName == "System.Delegate") return true; type = type.BaseType != null ? type.BaseType.Resolve () : null; } return false; } TypeDefinition ResolveType (TypeReference tr) { // The static registrar might sometimes deal with types that have been linked away // It's not always possible to call .Resolve () on types that have been linked away, // it might result in a NotSupportedException, or just a null value, so here we // manually replicate some resolution logic to try to avoid those NotSupportedExceptions. // The static registrar calls .Resolve () in a lot of places; we'll only call // this method if there's an actual need. if (tr is ArrayType arrayType) { return arrayType.ElementType.Resolve (); } else if (tr is GenericInstanceType git) { return ResolveType (git.ElementType); } else { var td = tr.Resolve (); if (td == null) td = LinkContext?.GetLinkedAwayType (tr, out _); return td; } } public bool IsNativeObject (TypeReference tr) { var gp = tr as GenericParameter; if (gp != null) { if (gp.HasConstraints) { foreach (var constraint in gp.Constraints) { if (IsNativeObject (constraint)) return true; } } return false; } var type = ResolveType (tr); while (type != null) { if (type.HasInterfaces) { foreach (var iface in type.Interfaces) if (iface.InterfaceType.Is (Registrar.ObjCRuntime, Registrar.StringConstants.INativeObject)) return true; } type = type.BaseType != null ? type.BaseType.Resolve () : null; } return tr.Is (Registrar.ObjCRuntime, Registrar.StringConstants.INativeObject); } public Target Target { get; private set; } public bool IsSingleAssembly { get { return !string.IsNullOrEmpty (single_assembly); } } string single_assembly; IEnumerable<AssemblyDefinition> input_assemblies; Dictionary<IMetadataTokenProvider, object> availability_annotations; #if MONOMAC readonly Version MacOSTenTwelveVersion = new Version (10,12); #endif public Xamarin.Tuner.DerivedLinkContext LinkContext { get { return Target?.GetLinkContext (); } } Dictionary<IMetadataTokenProvider, object> AvailabilityAnnotations { get { if (availability_annotations == null) availability_annotations = LinkContext?.GetAllCustomAttributes ("Availability"); return availability_annotations; } } // Look for linked away attributes as well as attributes on the attribute provider. IEnumerable<ICustomAttribute> GetCustomAttributes (ICustomAttributeProvider provider, string @namespace, string name, bool inherits = false) { var dict = LinkContext?.Annotations?.GetCustomAnnotations (name); object annotations = null; if (dict?.TryGetValue (provider, out annotations) == true) { var attributes = (IEnumerable<ICustomAttribute>) annotations; foreach (var attrib in attributes) { if (IsAttributeMatch (attrib, @namespace, name, inherits)) yield return attrib; } } if (provider.HasCustomAttributes) { foreach (var attrib in provider.CustomAttributes) { if (IsAttributeMatch (attrib, @namespace, name, inherits)) yield return attrib; } } } public bool TryGetAttribute (ICustomAttributeProvider provider, string @namespace, string attributeName, out ICustomAttribute attribute) { attribute = null; foreach (var custom_attribute in GetCustomAttributes (provider, @namespace, attributeName)) { attribute = custom_attribute; return true; } return false; } public bool HasAttribute (ICustomAttributeProvider provider, string @namespace, string name, bool inherits = false) { return GetCustomAttributes (provider, @namespace, name, inherits).Any (); } bool IsAttributeMatch (ICustomAttribute attribute, string @namespace, string name, bool inherits) { if (inherits) return attribute.AttributeType.Inherits (@namespace, name); return attribute.AttributeType.Is (@namespace, name); } void Init (Application app) { this.App = app; trace = !LaxMode && (app.RegistrarOptions & RegistrarOptions.Trace) == RegistrarOptions.Trace; } public StaticRegistrar (Application app) { Init (app); } public StaticRegistrar (Target target) { Init (target.App); this.Target = target; } protected override PropertyDefinition FindProperty (TypeReference type, string name) { var td = type.Resolve (); if (td?.HasProperties != true) return null; foreach (var prop in td.Properties) { if (prop.Name == name) return prop; } return null; } protected override IEnumerable<MethodDefinition> FindMethods (TypeReference type, string name) { var td = type.Resolve (); if (td?.HasMethods != true) return null; List<MethodDefinition> list = null; foreach (var method in td.Methods) { if (method.Name != name) continue; if (list == null) list = new List<MethodDefinition> (); list.Add (method); } return list; } public override TypeReference FindType (TypeReference relative, string @namespace, string name) { return relative.Resolve ().Module.GetType (@namespace, name); } protected override bool LaxMode { get { return IsSingleAssembly; } } protected override void ReportError (int code, string message, params object[] args) { throw ErrorHelper.CreateError (code, message, args); } protected override void ReportWarning (int code, string message, params object[] args) { ErrorHelper.Show (ErrorHelper.CreateWarning (code, message, args)); } protected override bool IsCorlibType (TypeReference type) { return type.Resolve ().Module.Assembly.Name.Name == "mscorlib"; } public static int GetValueTypeSize (TypeDefinition type, bool is_64_bits) { switch (type.FullName) { case "System.Char": return 2; case "System.Boolean": case "System.SByte": case "System.Byte": return 1; case "System.Int16": case "System.UInt16": return 2; case "System.Single": case "System.Int32": case "System.UInt32": return 4; case "System.Double": case "System.Int64": case "System.UInt64": return 8; case "System.IntPtr": case "System.nfloat": case "System.nuint": case "System.nint": return is_64_bits ? 8 : 4; default: int size = 0; foreach (FieldDefinition field in type.Fields) { if (field.IsStatic) continue; int s = GetValueTypeSize (field.FieldType.Resolve (), is_64_bits); if (s == -1) return -1; size += s; } return size; } } protected override int GetValueTypeSize (TypeReference type) { return GetValueTypeSize (type.Resolve (), Is64Bits); } protected override bool HasReleaseAttribute (MethodDefinition method) { method = GetBaseMethodInTypeHierarchy (method); return HasAttribute (method.MethodReturnType, ObjCRuntime, StringConstants.ReleaseAttribute); } protected override bool HasThisAttribute (MethodDefinition method) { return HasAttribute (method, "System.Runtime.CompilerServices", "ExtensionAttribute"); } #if MTOUCH public bool IsSimulator { get { return App.IsSimulatorBuild; } } #endif protected override bool IsSimulatorOrDesktop { get { #if MONOMAC return true; #else return App.IsSimulatorBuild; #endif } } protected override bool Is64Bits { get { if (IsSingleAssembly) return App.Is64Build; // Target can be null when mmp is run for multiple assemblies return Target != null ? Target.Is64Build : App.Is64Build; } } protected override bool IsDualBuildImpl { get { #if MMP return Xamarin.Bundler.Driver.IsUnified; #else return true; #endif } } protected override Exception CreateException (int code, Exception innerException, MethodDefinition method, string message, params object[] args) { return ErrorHelper.CreateError (App, code, innerException, method, message, args); } protected override Exception CreateException (int code, Exception innerException, TypeReference type, string message, params object [] args) { return ErrorHelper.CreateError (App, code, innerException, type, message, args); } protected override bool ContainsPlatformReference (AssemblyDefinition assembly) { if (assembly.Name.Name == PlatformAssembly) return true; if (!assembly.MainModule.HasAssemblyReferences) return false; foreach (var ar in assembly.MainModule.AssemblyReferences) { if (ar.Name == PlatformAssembly) return true; } return false; } protected override IEnumerable<TypeReference> CollectTypes (AssemblyDefinition assembly) { var queue = new Queue<TypeDefinition> (); foreach (TypeDefinition type in assembly.MainModule.Types) { if (type.HasNestedTypes) queue.Enqueue (type); else yield return type; } while (queue.Count > 0) { var nt = queue.Dequeue (); foreach (var tp in nt.NestedTypes) { if (tp.HasNestedTypes) queue.Enqueue (tp); else yield return tp; } yield return nt; } } protected override IEnumerable<MethodDefinition> CollectMethods (TypeReference tr) { var type = tr.Resolve (); if (!type.HasMethods) yield break; foreach (MethodDefinition method in type.Methods) { if (method.IsConstructor) continue; yield return method; } } protected override IEnumerable<MethodDefinition> CollectConstructors (TypeReference tr) { var type = tr.Resolve (); if (!type.HasMethods) yield break; foreach (MethodDefinition ctor in type.Methods) { if (ctor.IsConstructor) yield return ctor; } } protected override IEnumerable<PropertyDefinition> CollectProperties (TypeReference tr) { var type = tr.Resolve (); if (!type.HasProperties) yield break; foreach (PropertyDefinition property in type.Properties) yield return property; } protected override string GetAssemblyName (AssemblyDefinition assembly) { return assembly.Name.Name; } protected override string GetTypeFullName (TypeReference type) { return type.FullName; } protected override string GetMethodName (MethodDefinition method) { return method.Name; } protected override string GetPropertyName (PropertyDefinition property) { return property.Name; } protected override TypeReference GetPropertyType (PropertyDefinition property) { return property.PropertyType; } protected override string GetTypeName (TypeReference type) { return type.Name; } protected override string GetFieldName (FieldDefinition field) { return field.Name; } protected override IEnumerable<FieldDefinition> GetFields (TypeReference tr) { var type = tr.Resolve (); foreach (FieldDefinition field in type.Fields) yield return field; } protected override TypeReference GetFieldType (FieldDefinition field) { return field.FieldType; } protected override bool IsByRef (TypeReference type) { return type.IsByReference; } protected override TypeReference MakeByRef (TypeReference type) { return new ByReferenceType (type); } protected override bool IsStatic (FieldDefinition field) { return field.IsStatic; } protected override bool IsStatic (MethodDefinition method) { return method.IsStatic; } protected override bool IsStatic (PropertyDefinition property) { if (property.GetMethod != null) return property.GetMethod.IsStatic; if (property.SetMethod != null) return property.SetMethod.IsStatic; return false; } protected override TypeReference GetElementType (TypeReference type) { var ts = type as TypeSpecification; if (ts != null) { // TypeSpecification.GetElementType calls GetElementType on the element type, thus unwinding multiple element types (which we don't want). // By fetching the ElementType property we only unwind one level. // This matches what the dynamic registrar (System.Reflection) does. return ts.ElementType; } if (type is ByReferenceType brt) { // ByReferenceType.GetElementType also calls GetElementType recursively. return brt.ElementType; } return type.GetElementType (); } protected override TypeReference GetReturnType (MethodDefinition method) { return method.ReturnType; } TypeReference system_void; protected override TypeReference GetSystemVoidType () { if (system_void != null) return system_void; // find corlib AssemblyDefinition corlib = null; AssemblyDefinition first = null; foreach (var assembly in input_assemblies) { if (first == null) first = assembly; if (assembly.Name.Name == "mscorlib") { corlib = assembly; break; } } if (corlib == null) { corlib = first.MainModule.AssemblyResolver.Resolve (AssemblyNameReference.Parse ("mscorlib"), new ReaderParameters ()); } foreach (var type in corlib.MainModule.Types) { if (type.Namespace == "System" && type.Name == "Void") return system_void = type; } throw ErrorHelper.CreateError (4165, "The registrar couldn't find the type 'System.Void' in any of the referenced assemblies."); } protected override bool IsVirtual (MethodDefinition method) { return method.IsVirtual; } bool IsOverride (MethodDefinition method) { return method.IsVirtual && !method.IsNewSlot; } bool IsOverride (PropertyDefinition property) { if (property.GetMethod != null) return IsOverride (property.GetMethod); return IsOverride (property.SetMethod); } protected override bool IsConstructor (MethodDefinition method) { return method.IsConstructor; } protected override bool IsDelegate (TypeReference tr) { var type = tr.Resolve (); return IsDelegate (type); } protected override bool IsValueType (TypeReference type) { var td = type.Resolve (); return td != null && td.IsValueType; } bool IsNativeEnum (TypeDefinition td) { return IsDualBuild && HasAttribute (td, ObjCRuntime, StringConstants.NativeAttribute); } protected override bool IsNullable (TypeReference type) { return GetNullableType (type) != null; } protected override bool IsEnum (TypeReference tr, out bool isNativeEnum) { var type = tr.Resolve (); isNativeEnum = false; if (type == null) return false; if (type.IsEnum) isNativeEnum = IsNativeEnum (type); return type.IsEnum; } protected override bool IsArray (TypeReference type, out int rank) { var arrayType = type as ArrayType; if (arrayType == null) { rank = 0; return false; } rank = arrayType.Rank; return true; } protected override bool IsGenericType (TypeReference type) { return type is GenericInstanceType || type.HasGenericParameters || type is GenericParameter; } protected override bool IsGenericMethod (MethodDefinition method) { return method.HasGenericParameters; } protected override bool IsInterface (TypeReference type) { return type.Resolve ().IsInterface; } protected override TypeReference[] GetInterfaces (TypeReference type) { var td = type.Resolve (); if (!td.HasInterfaces || td.Interfaces.Count == 0) return null; var rv = new TypeReference [td.Interfaces.Count]; for (int i = 0; i < td.Interfaces.Count; i++) rv [i] = td.Interfaces [i].InterfaceType.Resolve (); return rv; } protected override TypeReference [] GetLinkedAwayInterfaces (TypeReference type) { if (LinkContext == null) return null; if (LinkContext.ProtocolImplementations.TryGetValue (type.Resolve (), out var linkedAwayInterfaces) != true) return null; if (linkedAwayInterfaces.Count == 0) return null; return linkedAwayInterfaces.ToArray (); } protected override TypeReference GetGenericTypeDefinition (TypeReference type) { var git = type as GenericInstanceType; if (git != null) return git.ElementType; return type; } protected override bool AreEqual (TypeReference a, TypeReference b) { if (a == b) return true; if (a == null ^ b == null) return false; return TypeMatch (a, b); } protected override bool VerifyIsConstrainedToNSObject (TypeReference type, out TypeReference constrained_type) { constrained_type = null; var gp = type as GenericParameter; if (gp != null) { if (!gp.HasConstraints) return false; foreach (var c in gp.Constraints) { if (IsNSObject (c)) { constrained_type = c; return true; } } return false; } var git = type as GenericInstanceType; if (git != null) { var rv = true; if (git.HasGenericArguments) { var newGit = new GenericInstanceType (git.ElementType); for (int i = 0; i < git.GenericArguments.Count; i++) { TypeReference constr; rv &= VerifyIsConstrainedToNSObject (git.GenericArguments [i], out constr); newGit.GenericArguments.Add (constr ?? git.GenericArguments [i]); } constrained_type = newGit; } return rv; } var el = type as ArrayType; if (el != null) { var rv = VerifyIsConstrainedToNSObject (el.ElementType, out constrained_type); if (constrained_type == null) return rv; constrained_type = new ArrayType (constrained_type, el.Rank); return rv; } var rt = type as ByReferenceType; if (rt != null) { var rv = VerifyIsConstrainedToNSObject (rt.ElementType, out constrained_type); if (constrained_type == null) return rv; constrained_type = new ByReferenceType (constrained_type); return rv; } var tr = type as PointerType; if (tr != null) { var rv = VerifyIsConstrainedToNSObject (tr.ElementType, out constrained_type); if (constrained_type == null) return rv; constrained_type = new PointerType (constrained_type); return rv; } return true; } protected override bool IsINativeObject (TypeReference tr) { return IsNativeObject (tr); } protected override TypeReference GetBaseType (TypeReference tr) { var gp = tr as GenericParameter; if (gp != null) { foreach (var constr in gp.Constraints) { if (constr.Resolve ().IsClass) { return constr; } } return null; } var type = ResolveType (tr); if (type.BaseType == null) return null; return type.BaseType.Resolve (); } protected override MethodDefinition GetBaseMethod (MethodDefinition method) { return GetBaseMethodInTypeHierarchy (method); } protected override TypeReference GetEnumUnderlyingType (TypeReference tr) { var type = tr.Resolve (); return GetEnumUnderlyingType (type); } protected override TypeReference[] GetParameters (MethodDefinition method) { if (!method.HasParameters || method.Parameters.Count == 0) return null; var types = new TypeReference [method.Parameters.Count]; for (int i = 0; i < types.Length; i++) types [i] = method.Parameters [i].ParameterType; return types; } protected override string GetParameterName (MethodDefinition method, int parameter_index) { if (method == null) return "?"; return method.Parameters [parameter_index].Name; } protected override MethodDefinition GetGetMethod (PropertyDefinition property) { return property.GetMethod; } protected override MethodDefinition GetSetMethod (PropertyDefinition property) { return property.SetMethod; } protected override void GetNamespaceAndName (TypeReference type, out string @namespace, out string name) { name = type.Name; @namespace = type.Namespace; } protected override bool TryGetAttribute (TypeReference type, string attributeNamespace, string attributeType, out object attribute) { bool res = TryGetAttribute (type.Resolve (), attributeNamespace, attributeType, out var attrib); attribute = attrib; return res; } public override RegisterAttribute GetRegisterAttribute (TypeReference type) { RegisterAttribute rv = null; if (!TryGetAttribute (type.Resolve (), Foundation, StringConstants.RegisterAttribute, out var attrib)) return null; if (!attrib.HasConstructorArguments) { rv = new RegisterAttribute (); } else { switch (attrib.ConstructorArguments.Count) { case 0: rv = new RegisterAttribute (); break; case 1: rv = new RegisterAttribute ((string) attrib.ConstructorArguments [0].Value); break; case 2: rv = new RegisterAttribute ((string) attrib.ConstructorArguments [0].Value, (bool) attrib.ConstructorArguments [1].Value); break; default: throw ErrorHelper.CreateError (4124, "Invalid RegisterAttribute found on '{0}'. Please file a bug report at https://github.com/xamarin/xamarin-macios/issues/new", type.FullName); } } if (attrib.HasProperties) { foreach (var prop in attrib.Properties) { switch (prop.Name) { case "IsWrapper": rv.IsWrapper = (bool) prop.Argument.Value; break; case "Name": rv.Name = (string) prop.Argument.Value; break; case "SkipRegistration": rv.SkipRegistration = (bool) prop.Argument.Value; break; default: throw ErrorHelper.CreateError (4124, "Invalid RegisterAttribute property {1} found on '{0}'. Please file a bug report at https://github.com/xamarin/xamarin-macios/issues/new", type.FullName, prop.Name); } } } return rv; } protected override CategoryAttribute GetCategoryAttribute (TypeReference type) { string name = null; if (!TryGetAttribute (type.Resolve (), ObjCRuntime, StringConstants.CategoryAttribute, out var attrib)) return null; if (!attrib.HasConstructorArguments) throw ErrorHelper.CreateError (4124, "Invalid CategoryAttribute found on '{0}'. Please file a bug report at https://github.com/xamarin/xamarin-macios/issues/new", type.FullName); if (attrib.HasProperties) { foreach (var prop in attrib.Properties) { if (prop.Name == "Name") { name = (string) prop.Argument.Value; break; } } } switch (attrib.ConstructorArguments.Count) { case 1: var t1 = (TypeReference) attrib.ConstructorArguments [0].Value; return new CategoryAttribute (t1 != null ? t1.Resolve () : null) { Name = name }; default: throw ErrorHelper.CreateError (4124, "Invalid CategoryAttribute found on '{0}'. Please file a bug report at https://github.com/xamarin/xamarin-macios/issues/new", type.FullName); } } protected override ExportAttribute GetExportAttribute (MethodDefinition method) { return CreateExportAttribute (GetBaseMethodInTypeHierarchy (method) ?? method); } protected override ExportAttribute GetExportAttribute (PropertyDefinition property) { return CreateExportAttribute (GetBasePropertyInTypeHierarchy (property) ?? property); } public override ProtocolAttribute GetProtocolAttribute (TypeReference type) { if (!TryGetAttribute (type.Resolve (), Foundation, StringConstants.ProtocolAttribute, out var attrib)) return null; if (!attrib.HasProperties) return new ProtocolAttribute (); var rv = new ProtocolAttribute (); foreach (var prop in attrib.Properties) { switch (prop.Name) { case "Name": rv.Name = (string) prop.Argument.Value; break; case "WrapperType": rv.WrapperType = ((TypeReference) prop.Argument.Value).Resolve (); break; case "IsInformal": rv.IsInformal = (bool) prop.Argument.Value; break; case "FormalSince": Version version; if (!Version.TryParse ((string)prop.Argument.Value, out version)) throw ErrorHelper.CreateError (4147, "Invalid {0} found on '{1}'. Please file a bug report at https://github.com/xamarin/xamarin-macios/issues/new", "ProtocolAttribute", type.FullName); rv.FormalSinceVersion = version; break; default: throw ErrorHelper.CreateError (4147, "Invalid {0} found on '{1}'. Please file a bug report at https://github.com/xamarin/xamarin-macios/issues/new", "ProtocolAttribute", type.FullName); } } return rv; } public BlockProxyAttribute GetBlockProxyAttribute (ParameterDefinition parameter) { if (!TryGetAttribute (parameter, ObjCRuntime, "BlockProxyAttribute", out var attrib)) return null; var rv = new BlockProxyAttribute (); switch (attrib.ConstructorArguments.Count) { case 1: rv.Type = ((TypeReference) attrib.ConstructorArguments [0].Value).Resolve (); break; default: throw ErrorHelper.CreateError (4124, "Invalid BlockProxyAttribute found on '{0}'. Please file a bug report at https://github.com/xamarin/xamarin-macios/issues/new", ((MethodReference) parameter.Method)?.FullName); } return rv; } public DelegateProxyAttribute GetDelegateProxyAttribute (MethodDefinition method) { if (!TryGetAttribute (method.MethodReturnType, ObjCRuntime, "DelegateProxyAttribute", out var attrib)) return null; var rv = new DelegateProxyAttribute (); switch (attrib.ConstructorArguments.Count) { case 1: rv.DelegateType = ((TypeReference) attrib.ConstructorArguments [0].Value).Resolve (); break; default: throw ErrorHelper.CreateError (4124, "Invalid DelegateProxyAttribute found on '{0}'. Please file a bug report at https://github.com/xamarin/xamarin-macios/issues/new", ((MethodReference) method)?.FullName); } return rv; } protected override string PlatformName { get { return App.PlatformName; } } ProtocolMemberAttribute GetProtocolMemberAttribute (TypeReference type, string selector, ObjCMethod obj_method, MethodDefinition method) { var memberAttributes = GetProtocolMemberAttributes (type); foreach (var attrib in memberAttributes) { if (attrib.IsStatic != method.IsStatic) continue; if (attrib.IsProperty) { if (method.IsSetter && attrib.SetterSelector != selector) continue; else if (method.IsGetter && attrib.GetterSelector != selector) continue; } else { if (attrib.Selector != selector) continue; } if (!obj_method.IsPropertyAccessor) { var attribParameters = new TypeReference [attrib.ParameterType?.Length ?? 0]; for (var i = 0; i < attribParameters.Length; i++) { attribParameters [i] = attrib.ParameterType [i]; if (attrib.ParameterByRef [i]) attribParameters [i] = new ByReferenceType (attribParameters [i]); } if (!ParametersMatch (method.Parameters, attribParameters)) continue; } return attrib; } return null; } protected override IEnumerable<ProtocolMemberAttribute> GetProtocolMemberAttributes (TypeReference type) { var td = type.Resolve (); foreach (var ca in GetCustomAttributes (td, Foundation, StringConstants.ProtocolMemberAttribute)) { var rv = new ProtocolMemberAttribute (); MethodDefinition implMethod = null; if (ProtocolMemberMethodMap.TryGetValue (ca, out implMethod) == true) rv.Method = implMethod; foreach (var prop in ca.Properties) { switch (prop.Name) { case "IsRequired": rv.IsRequired = (bool)prop.Argument.Value; break; case "IsProperty": rv.IsProperty = (bool)prop.Argument.Value; break; case "IsStatic": rv.IsStatic = (bool)prop.Argument.Value; break; case "Name": rv.Name = (string)prop.Argument.Value; break; case "Selector": rv.Selector = (string)prop.Argument.Value; break; case "ReturnType": rv.ReturnType = (TypeReference)prop.Argument.Value; break; case "ReturnTypeDelegateProxy": rv.ReturnTypeDelegateProxy = (TypeReference) prop.Argument.Value; break; case "ParameterType": if (prop.Argument.Value != null) { var arr = (CustomAttributeArgument[])prop.Argument.Value; rv.ParameterType = new TypeReference[arr.Length]; for (int i = 0; i < arr.Length; i++) { rv.ParameterType [i] = (TypeReference)arr [i].Value; } } break; case "ParameterByRef": if (prop.Argument.Value != null) { var arr = (CustomAttributeArgument[])prop.Argument.Value; rv.ParameterByRef = new bool[arr.Length]; for (int i = 0; i < arr.Length; i++) { rv.ParameterByRef [i] = (bool)arr [i].Value; } } break; case "ParameterBlockProxy": if (prop.Argument.Value != null) { var arr = (CustomAttributeArgument []) prop.Argument.Value; rv.ParameterBlockProxy = new TypeReference [arr.Length]; for (int i = 0; i < arr.Length; i++) { rv.ParameterBlockProxy [i] = (TypeReference) arr [i].Value; } } break; case "IsVariadic": rv.IsVariadic = (bool)prop.Argument.Value; break; case "PropertyType": rv.PropertyType = (TypeReference)prop.Argument.Value; break; case "GetterSelector": rv.GetterSelector = (string)prop.Argument.Value; break; case "SetterSelector": rv.SetterSelector = (string)prop.Argument.Value; break; case "ArgumentSemantic": rv.ArgumentSemantic = (ArgumentSemantic)prop.Argument.Value; break; } } yield return rv; } } void CollectAvailabilityAttributes (IEnumerable<ICustomAttribute> attributes, ref List<AvailabilityBaseAttribute> list) { PlatformName currentPlatform; #if MTOUCH switch (App.Platform) { case Xamarin.Utils.ApplePlatform.iOS: currentPlatform = global::ObjCRuntime.PlatformName.iOS; break; case Xamarin.Utils.ApplePlatform.TVOS: currentPlatform = global::ObjCRuntime.PlatformName.TvOS; break; case Xamarin.Utils.ApplePlatform.WatchOS: currentPlatform = global::ObjCRuntime.PlatformName.WatchOS; break; default: throw ErrorHelper.CreateError (71, "Unknown platform: {0}. This usually indicates a bug in Xamarin.iOS; please file a bug report at https://github.com/xamarin/xamarin-macios/issues/new with a test case.", App.Platform); } #else currentPlatform = global::ObjCRuntime.PlatformName.MacOSX; #endif foreach (var ca in attributes) { var caType = ca.AttributeType; if (caType.Namespace != ObjCRuntime && !string.IsNullOrEmpty (caType.Namespace)) continue; AvailabilityKind kind; PlatformName platformName = global::ObjCRuntime.PlatformName.None; PlatformArchitecture architecture = PlatformArchitecture.All; string message = null; int majorVersion = 0, minorVersion = 0, subminorVersion = 0; bool shorthand = false; switch (caType.Name) { case "MacAttribute": shorthand = true; platformName = global::ObjCRuntime.PlatformName.MacOSX; goto case "IntroducedAttribute"; case "iOSAttribute": shorthand = true; platformName = global::ObjCRuntime.PlatformName.iOS; goto case "IntroducedAttribute"; case "IntroducedAttribute": kind = AvailabilityKind.Introduced; break; case "DeprecatedAttribute": kind = AvailabilityKind.Deprecated; break; case "ObsoletedAttribute": kind = AvailabilityKind.Obsoleted; break; case "UnavailableAttribute": kind = AvailabilityKind.Unavailable; break; default: continue; } switch (ca.ConstructorArguments.Count) { case 2: if (!shorthand) throw ErrorHelper.CreateError (4163, "Internal error in the registrar ({0} ctor with {1} arguments). Please file a bug report at https://github.com/xamarin/xamarin-macios/issues/new", caType.Name, ca.ConstructorArguments.Count); majorVersion = (byte) ca.ConstructorArguments [0].Value; minorVersion = (byte) ca.ConstructorArguments [1].Value; break; case 3: if (!shorthand) { platformName = (PlatformName) ca.ConstructorArguments [0].Value; architecture = (PlatformArchitecture) ca.ConstructorArguments [1].Value; message = (string) ca.ConstructorArguments [2].Value; } else { majorVersion = (byte) ca.ConstructorArguments [0].Value; minorVersion = (byte) ca.ConstructorArguments [1].Value; if (ca.ConstructorArguments [2].Type.Name == "Boolean") { var onlyOn64 = (bool) ca.ConstructorArguments [2].Value; architecture = onlyOn64 ? PlatformArchitecture.Arch64 : PlatformArchitecture.All; } else if (ca.ConstructorArguments [2].Type.Name == "Byte") { minorVersion = (byte) ca.ConstructorArguments [2].Value; } else { throw ErrorHelper.CreateError (4163, "Internal error in the registrar ({0} ctor with {1} arguments). Please file a bug report at https://github.com/xamarin/xamarin-macios/issues/new", caType.Name, ca.ConstructorArguments.Count); } } break; case 4: if (!shorthand) throw ErrorHelper.CreateError (4163, "Internal error in the registrar ({0} ctor with {1} arguments). Please file a bug report at https://github.com/xamarin/xamarin-macios/issues/new", caType.Name, ca.ConstructorArguments.Count); majorVersion = (byte) ca.ConstructorArguments [0].Value; minorVersion = (byte) ca.ConstructorArguments [1].Value; minorVersion = (byte) ca.ConstructorArguments [2].Value; if (ca.ConstructorArguments [3].Type.Name == "Boolean") { var onlyOn64 = (bool) ca.ConstructorArguments [3].Value; architecture = onlyOn64 ? PlatformArchitecture.Arch64 : PlatformArchitecture.All; } else if (ca.ConstructorArguments [3].Type.Name == "PlatformArchitecture") { architecture = (PlatformArchitecture) (byte) ca.ConstructorArguments [3].Value; } else { throw ErrorHelper.CreateError (4163, "Internal error in the registrar ({0} ctor with {1} arguments). Please file a bug report at https://github.com/xamarin/xamarin-macios/issues/new", caType.Name, ca.ConstructorArguments.Count); } break; case 5: platformName = (PlatformName) ca.ConstructorArguments [0].Value; majorVersion = (int) ca.ConstructorArguments [1].Value; minorVersion = (int) ca.ConstructorArguments [2].Value; architecture = (PlatformArchitecture) ca.ConstructorArguments [3].Value; message = (string) ca.ConstructorArguments [4].Value; break; case 6: platformName = (PlatformName) ca.ConstructorArguments [0].Value; majorVersion = (int) ca.ConstructorArguments [1].Value; minorVersion = (int) ca.ConstructorArguments [2].Value; subminorVersion = (int) ca.ConstructorArguments [3].Value; architecture = (PlatformArchitecture) ca.ConstructorArguments [4].Value; message = (string) ca.ConstructorArguments [5].Value; break; default: throw ErrorHelper.CreateError (4163, "Internal error in the registrar ({0} ctor with {1} arguments). Please file a bug report at https://github.com/xamarin/xamarin-macios/issues/new", caType.Name, ca.ConstructorArguments.Count); } if (platformName != currentPlatform) continue; AvailabilityBaseAttribute rv; switch (kind) { case AvailabilityKind.Introduced: if (shorthand) { rv = new IntroducedAttribute (platformName, majorVersion, minorVersion, subminorVersion, architecture, message); } else { switch (ca.ConstructorArguments.Count) { case 3: rv = new IntroducedAttribute (platformName, architecture, message); break; case 5: rv = new IntroducedAttribute (platformName, majorVersion, minorVersion, architecture, message); break; case 6: rv = new IntroducedAttribute (platformName, majorVersion, minorVersion, subminorVersion, architecture, message); break; default: throw ErrorHelper.CreateError (4163, "Internal error in the registrar ({0} ctor with {1} arguments). Please file a bug report at https://github.com/xamarin/xamarin-macios/issues/new", caType.Name, ca.ConstructorArguments.Count); } } break; case AvailabilityKind.Deprecated: switch (ca.ConstructorArguments.Count) { case 3: rv = new DeprecatedAttribute (platformName, architecture, message); break; case 5: rv = new DeprecatedAttribute (platformName, majorVersion, minorVersion, architecture, message); break; case 6: rv = new DeprecatedAttribute (platformName, majorVersion, minorVersion, subminorVersion, architecture, message); break; default: throw ErrorHelper.CreateError (4163, "Internal error in the registrar ({0} ctor with {1} arguments). Please file a bug report at https://github.com/xamarin/xamarin-macios/issues/new", caType.Name, ca.ConstructorArguments.Count); } break; case AvailabilityKind.Obsoleted: switch (ca.ConstructorArguments.Count) { case 3: rv = new ObsoletedAttribute (platformName, architecture, message); break; case 5: rv = new ObsoletedAttribute (platformName, majorVersion, minorVersion, architecture, message); break; case 6: rv = new ObsoletedAttribute (platformName, majorVersion, minorVersion, subminorVersion, architecture, message); break; default: throw ErrorHelper.CreateError (4163, "Internal error in the registrar ({0} ctor with {1} arguments). Please file a bug report at https://github.com/xamarin/xamarin-macios/issues/new", caType.Name, ca.ConstructorArguments.Count); } break; case AvailabilityKind.Unavailable: rv = new UnavailableAttribute (platformName, architecture, message); break; default: throw ErrorHelper.CreateError (4163, "Internal error in the registrar (Unknown availability kind: {0}). Please file a bug report at https://github.com/xamarin/xamarin-macios/issues/new", kind); } if (list == null) list = new List<AvailabilityBaseAttribute> (); list.Add (rv); } } protected override List<AvailabilityBaseAttribute> GetAvailabilityAttributes (TypeReference obj) { TypeDefinition td = obj.Resolve (); List<AvailabilityBaseAttribute> rv = null; if (td == null) return null; if (td.HasCustomAttributes) CollectAvailabilityAttributes (td.CustomAttributes, ref rv); if (AvailabilityAnnotations != null) { object attribObjects; if (AvailabilityAnnotations.TryGetValue (td, out attribObjects)) CollectAvailabilityAttributes ((IEnumerable<ICustomAttribute>) attribObjects, ref rv); } return rv; } protected override Version GetSDKVersion () { return App.SdkVersion; } protected override Dictionary<MethodDefinition, List<MethodDefinition>> PrepareMethodMapping (TypeReference type) { return PrepareInterfaceMethodMapping (type); } protected override TypeReference GetProtocolAttributeWrapperType (TypeReference type) { if (!TryGetAttribute (type.Resolve (), Foundation, StringConstants.ProtocolAttribute, out var attrib)) return null; if (attrib.HasProperties) { foreach (var prop in attrib.Properties) { if (prop.Name == "WrapperType") return (TypeReference) prop.Argument.Value; } } return null; } protected override IList<AdoptsAttribute> GetAdoptsAttributes (TypeReference type) { var attributes = GetCustomAttributes (type.Resolve (), ObjCRuntime, "AdoptsAttribute"); if (attributes == null || !attributes.Any ()) return null; var rv = new List<AdoptsAttribute> (); foreach (var ca in attributes) { var attrib = new AdoptsAttribute (); switch (ca.ConstructorArguments.Count) { case 1: attrib.ProtocolType = (string) ca.ConstructorArguments [0].Value; break; default: throw ErrorHelper.CreateError (4124, "Invalid AdoptsAttribute found on '{0}': expected 1 constructor arguments, got {1}. Please file a bug report at https://github.com/xamarin/xamarin-macios/issues/new", type.FullName, 1, ca.ConstructorArguments.Count); } rv.Add (attrib); } return rv; } protected override BindAsAttribute GetBindAsAttribute (PropertyDefinition property) { if (property == null) return null; property = GetBasePropertyInTypeHierarchy (property); if (!TryGetAttribute (property, ObjCRuntime, "BindAsAttribute", out var attrib)) return null; return CreateBindAsAttribute (attrib, property); } protected override BindAsAttribute GetBindAsAttribute (MethodDefinition method, int parameter_index) { if (method == null) return null; method = GetBaseMethodInTypeHierarchy (method); if (!TryGetAttribute (parameter_index == -1 ? (ICustomAttributeProvider) method.MethodReturnType : method.Parameters [parameter_index], ObjCRuntime, "BindAsAttribute", out var attrib)) return null; return CreateBindAsAttribute (attrib, method); } static BindAsAttribute CreateBindAsAttribute (ICustomAttribute attrib, IMemberDefinition member) { TypeReference originalType = null; if (attrib.HasFields) { foreach (var field in attrib.Fields) { switch (field.Name) { case "OriginalType": originalType = ((TypeReference) field.Argument.Value); break; default: throw ErrorHelper.CreateError (4124, "Invalid BindAsAttribute found on '{0}.{1}': unknown field {2}. Please file a bug report at https://github.com/xamarin/xamarin-macios/issues/new", member.DeclaringType.FullName, member.Name, field.Name); } } } switch (attrib.ConstructorArguments.Count) { case 1: var t1 = (TypeReference) attrib.ConstructorArguments [0].Value; return new BindAsAttribute (t1) { OriginalType = originalType }; default: throw ErrorHelper.CreateError (4124, "Invalid BindAsAttribute found on '{0}.{1}'. Please file a bug report at https://github.com/xamarin/xamarin-macios/issues/new", member.DeclaringType.FullName, member.Name); } } public override TypeReference GetNullableType (TypeReference type) { var git = type as GenericInstanceType; if (git == null) return null; if (!git.GetElementType ().Is ("System", "Nullable`1")) return null; return git.GenericArguments [0]; } protected override ConnectAttribute GetConnectAttribute (PropertyDefinition property) { ICustomAttribute attrib; if (!TryGetAttribute (property, Foundation, StringConstants.ConnectAttribute, out attrib)) return null; if (!attrib.HasConstructorArguments) return new ConnectAttribute (); switch (attrib.ConstructorArguments.Count) { case 0: return new ConnectAttribute (); case 1: return new ConnectAttribute (((string) attrib.ConstructorArguments [0].Value)); default: throw ErrorHelper.CreateError (4124, "Invalid ConnectAttribute found on '{0}.{1}'. Please file a bug report at https://github.com/xamarin/xamarin-macios/issues/new", property.DeclaringType.FullName, property.Name); } } ExportAttribute CreateExportAttribute (IMemberDefinition candidate) { bool is_variadic = false; var attribute = GetExportAttribute (candidate); if (attribute == null) return null; if (attribute.HasProperties) { foreach (var prop in attribute.Properties) { if (prop.Name == "IsVariadic") { is_variadic = (bool) prop.Argument.Value; break; } } } if (!attribute.HasConstructorArguments) return new ExportAttribute (null) { IsVariadic = is_variadic }; switch (attribute.ConstructorArguments.Count) { case 0: return new ExportAttribute (null) { IsVariadic = is_variadic }; case 1: return new ExportAttribute ((string) attribute.ConstructorArguments [0].Value) { IsVariadic = is_variadic }; case 2: return new ExportAttribute ((string) attribute.ConstructorArguments [0].Value, (ArgumentSemantic) attribute.ConstructorArguments [1].Value) { IsVariadic = is_variadic }; default: throw ErrorHelper.CreateError (4124, "Invalid ExportAttribute found on '{0}.{1}'. Please file a bug report at https://github.com/xamarin/xamarin-macios/issues/new", candidate.DeclaringType.FullName, candidate.Name); } } // [Export] is not sealed anymore - so we cannot simply compare strings ICustomAttribute GetExportAttribute (ICustomAttributeProvider candidate) { if (!candidate.HasCustomAttributes) return null; foreach (CustomAttribute ca in candidate.CustomAttributes) { if (ca.Constructor.DeclaringType.Inherits (Foundation, StringConstants.ExportAttribute)) return ca; } return null; } PropertyDefinition GetBasePropertyInTypeHierarchy (PropertyDefinition property) { if (!IsOverride (property)) return property; var @base = GetBaseType (property.DeclaringType); while (@base != null) { PropertyDefinition base_property = TryMatchProperty (@base.Resolve (), property); if (base_property != null) return GetBasePropertyInTypeHierarchy (base_property) ?? base_property; @base = GetBaseType (@base); } return property; } static PropertyDefinition TryMatchProperty (TypeDefinition type, PropertyDefinition property) { if (!type.HasProperties) return null; foreach (PropertyDefinition candidate in type.Properties) if (PropertyMatch (candidate, property)) return candidate; return null; } static bool PropertyMatch (PropertyDefinition candidate, PropertyDefinition property) { if (candidate.Name != property.Name) return false; if (candidate.GetMethod != null) { if (property.GetMethod == null) return false; if (!MethodMatch (candidate.GetMethod, property.GetMethod)) return false; } else if (property.GetMethod != null) { return false; } if (candidate.SetMethod != null) { if (property.SetMethod == null) return false; if (!MethodMatch (candidate.SetMethod, property.SetMethod)) return false; } else if (property.SetMethod != null) { return false; } return true; } MethodDefinition GetBaseMethodInTypeHierarchy (MethodDefinition method) { if (!IsOverride (method)) return method; var @base = GetBaseType (method.DeclaringType); while (@base != null) { MethodDefinition base_method = TryMatchMethod (@base.Resolve (), method); if (base_method != null) return GetBaseMethodInTypeHierarchy (base_method) ?? base_method; @base = GetBaseType (@base); } return method; } static MethodDefinition TryMatchMethod (TypeDefinition type, MethodDefinition method) { if (!type.HasMethods) return null; foreach (MethodDefinition candidate in type.Methods) if (MethodMatch (candidate, method)) return candidate; return null; } // here we try to create a specialized trampoline for the specified method. static int counter = 0; static bool trace = false; AutoIndentStringBuilder header; AutoIndentStringBuilder declarations; // forward declarations, struct definitions AutoIndentStringBuilder methods; // c methods that contain the actual implementations AutoIndentStringBuilder interfaces; // public objective-c @interface declarations AutoIndentStringBuilder nslog_start = new AutoIndentStringBuilder (); AutoIndentStringBuilder nslog_end = new AutoIndentStringBuilder (); AutoIndentStringBuilder comment = new AutoIndentStringBuilder (); AutoIndentStringBuilder copyback = new AutoIndentStringBuilder (); AutoIndentStringBuilder invoke = new AutoIndentStringBuilder (); AutoIndentStringBuilder setup_call_stack = new AutoIndentStringBuilder (); AutoIndentStringBuilder setup_return = new AutoIndentStringBuilder (); AutoIndentStringBuilder body = new AutoIndentStringBuilder (); AutoIndentStringBuilder body_setup = new AutoIndentStringBuilder (); HashSet<string> trampoline_names = new HashSet<string> (); HashSet<string> namespaces = new HashSet<string> (); HashSet<string> structures = new HashSet<string> (); Dictionary<Body, Body> bodies = new Dictionary<Body, Body> (); AutoIndentStringBuilder full_token_references = new AutoIndentStringBuilder (); uint full_token_reference_count; List<string> registered_assemblies = new List<string> (); bool IsPlatformType (TypeReference type) { if (type.IsNested) return false; string aname; if (type.Module == null) { // This type was probably linked away if (LinkContext.GetLinkedAwayType (type, out var module) != null) { aname = module.Assembly.Name.Name; } else { aname = string.Empty; } } else { aname = type.Module.Assembly.Name.Name; } if (aname != PlatformAssembly) return false; if (IsDualBuild) { return Driver.GetFrameworks (App).ContainsKey (type.Namespace); } else { return type.Namespace.StartsWith (CompatNamespace + ".", StringComparison.Ordinal); } } static bool IsLinkedAway (TypeReference tr) { return tr.Module == null; } void CheckNamespace (ObjCType objctype, List<Exception> exceptions) { CheckNamespace (objctype.Type, exceptions); } HashSet<string> reported_frameworks; void CheckNamespace (TypeReference type, List<Exception> exceptions) { if (!IsPlatformType (type)) return; var ns = type.Namespace; Framework framework; if (Driver.GetFrameworks (App).TryGetValue (ns, out framework)) { if (framework.Version > App.SdkVersion) { if (reported_frameworks == null) reported_frameworks = new HashSet<string> (); if (!reported_frameworks.Contains (framework.Name)) { exceptions.Add (ErrorHelper.CreateError (4134, #if MMP "Your application is using the '{0}' framework, which isn't included in the {3} SDK you're using to build your app (this framework was introduced in {3} {2}, while you're building with the {3} {1} SDK.) " + "This configuration is not supported with the static registrar (pass --registrar:dynamic as an additional mmp argument in your project's Mac Build option to select). " + "Alternatively select a newer SDK in your app's Mac Build options.", #else "Your application is using the '{0}' framework, which isn't included in the {3} SDK you're using to build your app (this framework was introduced in {3} {2}, while you're building with the {3} {1} SDK.) " + "Please select a newer SDK in your app's {3} Build options.", #endif framework.Name, App.SdkVersion, framework.Version, App.PlatformName)); reported_frameworks.Add (framework.Name); } return; } } // Strip off the 'MonoTouch.' prefix if (!IsDualBuild) ns = type.Namespace.Substring (ns.IndexOf ('.') + 1); CheckNamespace (ns, exceptions); } void CheckNamespace (string ns, List<Exception> exceptions) { if (string.IsNullOrEmpty (ns)) return; if (namespaces.Contains (ns)) return; namespaces.Add (ns); #if !MMP if (App.IsSimulatorBuild && !Driver.IsFrameworkAvailableInSimulator (App, ns)) { Driver.Log (5, "Not importing the framework {0} in the generated registrar code because it's not available in the simulator.", ns); return; } #endif string h; switch (ns) { #if MMP case "GLKit": // This prevents this warning: // /Applications/Xcode83.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/System/Library/Frameworks/OpenGL.framework/Headers/gl.h:5:2: warning: gl.h and gl3.h are both // included. Compiler will not invoke errors if using removed OpenGL functionality. [-W#warnings] // This warning shows up when both GLKit/GLKit.h and Quartz/Quartz.h are included. header.WriteLine ("#define GL_DO_NOT_WARN_IF_MULTI_GL_VERSION_HEADERS_INCLUDED 1"); goto default; case "CoreBluetooth": header.WriteLine ("#import <IOBluetooth/IOBluetooth.h>"); header.WriteLine ("#import <CoreBluetooth/CoreBluetooth.h>"); return; case "CoreImage": h = "<QuartzCore/QuartzCore.h>"; break; case "PdfKit": case "ImageKit": case "QuartzComposer": case "QuickLookUI": h = "<Quartz/Quartz.h>"; break; #else case "PdfKit": h = "<PDFKit/PDFKit.h>"; break; #endif case "OpenGLES": return; case "CoreAnimation": header.WriteLine ("#import <QuartzCore/QuartzCore.h>"); #if MTOUCH switch (App.Platform) { case Xamarin.Utils.ApplePlatform.iOS: case Xamarin.Utils.ApplePlatform.TVOS: if (App.SdkVersion.Major > 7 && App.SdkVersion.Major < 11) header.WriteLine ("#import <QuartzCore/CAEmitterBehavior.h>"); break; } #endif return; case "CoreMidi": h = "<CoreMIDI/CoreMIDI.h>"; break; #if MTOUCH case "CoreTelephony": // Grr, why doesn't CoreTelephony have one header that includes the rest !? header.WriteLine ("#import <CoreTelephony/CoreTelephonyDefines.h>"); header.WriteLine ("#import <CoreTelephony/CTCall.h>"); header.WriteLine ("#import <CoreTelephony/CTCallCenter.h>"); header.WriteLine ("#import <CoreTelephony/CTCarrier.h>"); header.WriteLine ("#import <CoreTelephony/CTTelephonyNetworkInfo.h>"); if (App.SdkVersion.Major >= 7) { header.WriteLine ("#import <CoreTelephony/CTSubscriber.h>"); header.WriteLine ("#import <CoreTelephony/CTSubscriberInfo.h>"); } return; #endif #if MTOUCH case "Accounts": var compiler = Path.GetFileName (App.CompilerPath); if (compiler == "gcc" || compiler == "g++") { exceptions.Add (new MonoTouchException (4121, true, "Cannot use GCC/G++ to compile the generated code from the static registrar when using the Accounts framework (the header files provided by Apple used during the compilation require Clang). Either use Clang (--compiler:clang) or the dynamic registrar (--registrar:dynamic).")); return; } goto default; #endif case "WatchKit": // There's a bug in Xcode 7 beta 2 headers where the build fails with // ObjC++ files if WatchKit.h is included before UIKit.h (radar 21651022). // Workaround this by manually include UIKit.h before WatchKit.h. if (!namespaces.Contains ("UIKit")) header.WriteLine ("#import <UIKit/UIKit.h>"); header.WriteLine ("#import <WatchKit/WatchKit.h>"); namespaces.Add ("UIKit"); return; case "QTKit": #if MONOMAC if (App.SdkVersion >= MacOSTenTwelveVersion) return; // 10.12 removed the header files for QTKit #endif goto default; case "IOSurface": // There is no IOSurface.h h = "<IOSurface/IOSurfaceObjC.h>"; break; default: h = string.Format ("<{0}/{0}.h>", ns); break; } header.WriteLine ("#import {0}", h); } string CheckStructure (TypeDefinition structure, string descriptiveMethodName, MemberReference inMember) { string n; StringBuilder name = new StringBuilder (); var body = new AutoIndentStringBuilder (1); int size = 0; ProcessStructure (name, body, structure, ref size, descriptiveMethodName, structure, inMember); n = "struct trampoline_struct_" + name.ToString (); if (!structures.Contains (n)) { structures.Add (n); declarations.WriteLine ("{0} {{\n{1}}};", n, body.ToString ()); } return n; } void ProcessStructure (StringBuilder name, AutoIndentStringBuilder body, TypeDefinition structure, ref int size, string descriptiveMethodName, TypeDefinition root_structure, MemberReference inMember) { switch (structure.FullName) { case "System.Char": name.Append ('s'); body.AppendLine ("short v{0};", size); size += 1; break; case "System.Boolean": // map managed 'bool' to ObjC BOOL name.Append ('B'); body.AppendLine ("BOOL v{0};", size); size += 1; break; case "System.Byte": case "System.SByte": name.Append ('b'); body.AppendLine ("char v{0};", size); size += 1; break; case "System.UInt16": case "System.Int16": name.Append ('s'); body.AppendLine ("short v{0};", size); size += 2; break; case "System.UInt32": case "System.Int32": name.Append ('i'); body.AppendLine ("int v{0};", size); size += 4; break; case "System.Int64": case "System.UInt64": name.Append ('l'); body.AppendLine ("long long v{0};", size); size += 8; break; case "System.Single": name.Append ('f'); body.AppendLine ("float v{0};", size); size += 4; break; case "System.Double": name.Append ('d'); body.AppendLine ("double v{0};", size); size += 8; break; case "System.IntPtr": name.Append ('p'); body.AppendLine ("void *v{0};", size); size += 4; // for now at least... break; default: bool found = false; foreach (FieldDefinition field in structure.Fields) { if (field.IsStatic) continue; var fieldType = field.FieldType.Resolve (); if (fieldType == null) throw ErrorHelper.CreateError (App, 4111, inMember, "The registrar cannot build a signature for type `{0}' in method `{1}`.", structure.FullName, descriptiveMethodName); if (!fieldType.IsValueType) throw ErrorHelper.CreateError (App, 4161, inMember, "The registrar found an unsupported structure '{0}': All fields in a structure must also be structures (field '{1}' with type '{2}' is not a structure).", root_structure.FullName, field.Name, fieldType.FullName); found = true; ProcessStructure (name, body, fieldType, ref size, descriptiveMethodName, root_structure, inMember); } if (!found) throw ErrorHelper.CreateError (App, 4111, inMember, "The registrar cannot build a signature for type `{0}' in method `{1}`.", structure.FullName, descriptiveMethodName); break; } } string GetUniqueTrampolineName (string suggestion) { char []fixup = suggestion.ToCharArray (); for (int i = 0; i < fixup.Length; i++) { char c = fixup [i]; if (c >= 'a' && c <= 'z') continue; if (c >= 'A' && c <= 'Z') continue; if (c >= '0' && c <= '9') continue; fixup [i] = '_'; } suggestion = new string (fixup); if (trampoline_names.Contains (suggestion)) { string tmp; int counter = 0; do { tmp = suggestion + (++counter).ToString (); } while (trampoline_names.Contains (tmp)); suggestion = tmp; } trampoline_names.Add (suggestion); return suggestion; } string ToObjCParameterType (TypeReference type, string descriptiveMethodName, List<Exception> exceptions, MemberReference inMethod) { TypeDefinition td = ResolveType (type); var reftype = type as ByReferenceType; ArrayType arrtype = type as ArrayType; GenericParameter gp = type as GenericParameter; if (gp != null) return "id"; if (reftype != null) { string res = ToObjCParameterType (GetElementType (reftype), descriptiveMethodName, exceptions, inMethod); if (res == null) return null; return res + "*"; } if (arrtype != null) return "NSArray *"; var git = type as GenericInstanceType; if (git != null && IsNSObject (type)) { var sb = new StringBuilder (); var elementType = git.GetElementType (); sb.Append (ToObjCParameterType (elementType, descriptiveMethodName, exceptions, inMethod)); if (sb [sb.Length - 1] != '*') { // I'm not sure if this is possible to hit (I couldn't come up with a test case), but better safe than sorry. AddException (ref exceptions, CreateException (4166, inMethod.Resolve () as MethodDefinition, "Cannot register the method '{0}' because the signature contains a type ({1}) that isn't a reference type.", descriptiveMethodName, GetTypeFullName (elementType))); return "id"; } sb.Length--; // remove the trailing * of the element type sb.Append ('<'); for (int i = 0; i < git.GenericArguments.Count; i++) { if (i > 0) sb.Append (", "); var argumentType = git.GenericArguments [i]; if (!IsINativeObject (argumentType)) { // I believe the generic constraints we have should make this error impossible to hit, but better safe than sorry. AddException (ref exceptions, CreateException (4167, inMethod.Resolve () as MethodDefinition, "Cannot register the method '{0}' because the signature contains a generic type ({1}) with a generic argument type that doesn't implement INativeObject ({2}).", descriptiveMethodName, GetTypeFullName (type), GetTypeFullName (argumentType))); return "id"; } sb.Append (ToObjCParameterType (argumentType, descriptiveMethodName, exceptions, inMethod)); } sb.Append ('>'); sb.Append ('*'); // put back the * from the element type return sb.ToString (); } switch (td.FullName) { #if MMP case "System.Drawing.RectangleF": return "NSRect"; case "System.Drawing.PointF": return "NSPoint"; case "System.Drawing.SizeF": return "NSSize"; #else case "System.Drawing.RectangleF": return "CGRect"; case "System.Drawing.PointF": return "CGPoint"; case "System.Drawing.SizeF": return "CGSize"; #endif case "System.String": return "NSString *"; case "System.IntPtr": return "void *"; case "System.SByte": return "signed char"; case "System.Byte": return "unsigned char"; case "System.Char": return "signed short"; case "System.Int16": return "short"; case "System.UInt16": return "unsigned short"; case "System.Int32": return "int"; case "System.UInt32": return "unsigned int"; case "System.Int64": return "long long"; case "System.UInt64": return "unsigned long long"; case "System.Single": return "float"; case "System.Double": return "double"; case "System.Boolean": return "BOOL"; // map managed 'bool' to ObjC BOOL = unsigned char case "System.Void": return "void"; case "System.nint": CheckNamespace ("Foundation", exceptions); return "NSInteger"; case "System.nuint": CheckNamespace ("Foundation", exceptions); return "NSUInteger"; case "System.nfloat": CheckNamespace ("CoreGraphics", exceptions); return "CGFloat"; case "System.DateTime": throw ErrorHelper.CreateError (4102, "The registrar found an invalid type `{0}` in signature for method `{2}`. Use `{1}` instead.", "System.DateTime", IsDualBuild ? "Foundation.NSDate" : CompatNamespace + ".Foundation.NSDate", descriptiveMethodName); case "ObjCRuntime.Selector": case CompatNamespace + ".ObjCRuntime.Selector": return "SEL"; case "ObjCRuntime.Class": case CompatNamespace + ".ObjCRuntime.Class": return "Class"; default: if (IsNSObject (td)) { if (!IsPlatformType (td)) return "id"; if (HasProtocolAttribute (td)) { return "id<" + GetExportedTypeName (td) + ">"; } else { return GetExportedTypeName (td) + " *"; } } else if (td.IsEnum) { if (IsDualBuild && HasAttribute (td, ObjCRuntime, StringConstants.NativeAttribute)) { switch (GetEnumUnderlyingType (td).FullName) { case "System.Int64": return "NSInteger"; case "System.UInt64": return "NSUInteger"; default: exceptions.Add (ErrorHelper.CreateError (4145, "Invalid enum '{0}': enums with the [Native] attribute must have a underlying enum type of either 'long' or 'ulong'.", td.FullName)); return "NSInteger"; } } return ToObjCParameterType (GetEnumUnderlyingType (td), descriptiveMethodName, exceptions, inMethod); } else if (td.IsValueType) { if (IsPlatformType (td)) { CheckNamespace (td, exceptions); return td.Name; } return CheckStructure (td, descriptiveMethodName, inMethod); } else { return ToObjCType (td); } } } string GetPrintfFormatSpecifier (TypeDefinition type, out bool unknown) { unknown = false; if (type.IsValueType) { switch (type.FullName) { case "System.Char": return "c"; case "System.Boolean": case "System.SByte": case "System.Int16": case "System.Int32": return "i"; case "System.Byte": case "System.UInt16": case "System.UInt32": return "u"; case "System.Int64": return "lld"; case "System.UInt64": return "llu"; case "System.nint": return "zd"; case "System.nuint": return "tu"; case "System.nfloat": case "System.Single": case "System.Double": return "f"; default: unknown = true; return "p"; } } else if (IsNSObject (type)) { return "@"; } else { unknown = true; return "p"; } } string GetObjCSignature (ObjCMethod method, List<Exception> exceptions) { if (method.CurrentTrampoline == Trampoline.Retain) return "-(id) retain"; else if (method.CurrentTrampoline == Trampoline.Release) return "-(void) release"; else if (method.CurrentTrampoline == Trampoline.GetGCHandle) return "-(int) xamarinGetGCHandle"; else if (method.CurrentTrampoline == Trampoline.SetGCHandle) return "-(void) xamarinSetGCHandle: (int) gchandle"; #if MONOMAC else if (method.CurrentTrampoline == Trampoline.CopyWithZone1 || method.CurrentTrampoline == Trampoline.CopyWithZone2) return "-(id) copyWithZone: (NSZone *)zone"; #endif var sb = new StringBuilder (); var isCtor = method.CurrentTrampoline == Trampoline.Constructor; sb.Append ((method.IsStatic && !method.IsCategoryInstance) ? '+' : '-'); sb.Append ('('); sb.Append (isCtor ? "id" : this.ToObjCParameterType (method.NativeReturnType, GetDescriptiveMethodName (method.Method), exceptions, method.Method)); sb.Append (')'); var split = method.Selector.Split (':'); if (split.Length == 1) { sb.Append (' '); sb.Append (split [0]); } else { var indexOffset = method.IsCategoryInstance ? 1 : 0; for (int i = 0; i < split.Length - 1; i++) { sb.Append (' '); sb.Append (split [i]); sb.Append (':'); sb.Append ('('); sb.Append (ToObjCParameterType (method.NativeParameters [i + indexOffset], method.DescriptiveMethodName, exceptions, method.Method)); sb.Append (')'); sb.AppendFormat ("p{0}", i); } } if (method.IsVariadic) sb.Append (", ..."); return sb.ToString (); } void WriteFullName (StringBuilder sb, TypeReference type) { if (type.DeclaringType != null) { WriteFullName (sb, type.DeclaringType); sb.Append ('+'); } else if (!string.IsNullOrEmpty (type.Namespace)) { sb.Append (type.Namespace); sb.Append ('.'); } sb.Append (type.Name); } protected override string GetAssemblyQualifiedName (TypeReference type) { var gp = type as GenericParameter; if (gp != null) return gp.Name; var sb = new StringBuilder (); WriteFullName (sb, type); var git = type as GenericInstanceType; if (git != null) { sb.Append ('['); for (int i = 0; i < git.GenericArguments.Count; i++) { if (i > 0) sb.Append (','); sb.Append ('['); sb.Append (GetAssemblyQualifiedName (git.GenericArguments [i])); sb.Append (']'); } sb.Append (']'); } var td = type.Resolve (); if (td != null) sb.Append (", ").Append (td.Module.Assembly.Name.Name); return sb.ToString (); } static string EncodeNonAsciiCharacters (string value) { StringBuilder sb = null; for (int i = 0; i < value.Length; i++) { char c = value [i]; if (c > 127) { if (sb == null) { sb = new StringBuilder (value.Length); sb.Append (value, 0, i); } sb.Append ("\\u"); sb.Append (((int) c).ToString ("x4")); } else if (sb != null) { sb.Append (c); } } return sb != null ? sb.ToString () : value; } static bool IsTypeCore (ObjCType type, string nsToMatch) { var ns = type.Type.Namespace; var t = type.Type; while (string.IsNullOrEmpty (ns) && t.DeclaringType != null) { t = t.DeclaringType; ns = t.Namespace; } return ns == nsToMatch; } static bool IsQTKitType (ObjCType type) => IsTypeCore (type, "QTKit"); static bool IsMapKitType (ObjCType type) => IsTypeCore (type, "MapKit"); static bool IsIntentsType (ObjCType type) => IsTypeCore (type, "Intents"); static bool IsExternalAccessoryType (ObjCType type) => IsTypeCore (type, "ExternalAccessory"); #if !MONOMAC bool IsTypeAllowedInSimulator (ObjCType type) { var ns = type.Type.Namespace; if (!IsDualBuild) ns = ns.Substring (CompatNamespace.Length + 1); return Driver.IsFrameworkAvailableInSimulator (App, ns); } #endif class ProtocolInfo { public uint TokenReference; public ObjCType Protocol; } class SkippedType { public TypeReference Skipped; public ObjCType Actual; public uint SkippedTokenReference; public uint ActualTokenReference; } List<SkippedType> skipped_types = new List<SkippedType> (); protected override void OnSkipType (TypeReference type, ObjCType registered_type) { base.OnSkipType (type, registered_type); #if MONOMAC if (!Is64Bits && IsOnly64Bits (type)) return; #endif skipped_types.Add (new SkippedType { Skipped = type, Actual = registered_type } ); } #if MONOMAC bool IsOnly64Bits (TypeReference type) { var attributes = GetAvailabilityAttributes (type); // Can return null list if (attributes == null) return false; return attributes.Any (x => x.Architecture == PlatformArchitecture.Arch64); } #endif void Specialize (AutoIndentStringBuilder sb) { List<Exception> exceptions = new List<Exception> (); List<ObjCMember> skip = new List<ObjCMember> (); var map = new AutoIndentStringBuilder (1); var map_init = new AutoIndentStringBuilder (); var map_dict = new Dictionary<ObjCType, int> (); // maps ObjCType to its index in the map var map_entries = 0; var protocol_wrapper_map = new Dictionary<uint, Tuple<ObjCType, uint>> (); var protocols = new List<ProtocolInfo> (); var i = 0; bool needs_protocol_map = false; // Check if we need the protocol map. // We don't need it if the linker removed the method ObjCRuntime.Runtime.GetProtocolForType, // or if we're not registering protocols. if (App.Optimizations.RegisterProtocols == true) { var asm = input_assemblies.FirstOrDefault ((v) => v.Name.Name == PlatformAssembly); needs_protocol_map = asm?.MainModule.GetType (!IsDualBuild ? (CompatNamespace + ".ObjCRuntime") : "ObjCRuntime", "Runtime")?.Methods.Any ((v) => v.Name == "GetProtocolForType") == true; } map.AppendLine ("static MTClassMap __xamarin_class_map [] = {"); if (string.IsNullOrEmpty (single_assembly)) { map_init.AppendLine ("void xamarin_create_classes () {"); } else { map_init.AppendLine ("void xamarin_create_classes_{0} () {{", single_assembly.Replace ('.', '_').Replace ('-', '_')); } // Select the types that needs to be registered. var allTypes = new List<ObjCType> (); foreach (var @class in Types.Values) { if (!string.IsNullOrEmpty (single_assembly) && single_assembly != @class.Type.Module.Assembly.Name.Name) continue; #if !MONOMAC var isPlatformType = IsPlatformType (@class.Type); if (isPlatformType && IsSimulatorOrDesktop && !IsTypeAllowedInSimulator (@class)) { Driver.Log (5, "The static registrar won't generate code for {0} because its framework is not supported in the simulator.", @class.ExportedName); continue; // Some types are not supported in the simulator. } #else // Don't register 64-bit only API on 32-bit XM if (!Is64Bits && IsOnly64Bits (@class.Type)) continue; if (IsQTKitType (@class) && App.SdkVersion >= MacOSTenTwelveVersion) continue; // QTKit header was removed in 10.12 SDK // These are 64-bit frameworks that extend NSExtensionContext / NSUserActivity, which you can't do // if the header doesn't declare them. So hack it away, since they are useless in 64-bit anyway if (!Is64Bits && (IsMapKitType (@class) || IsIntentsType (@class) || IsExternalAccessoryType (@class))) continue; #endif if (@class.IsFakeProtocol) continue; allTypes.Add (@class); } if (string.IsNullOrEmpty (single_assembly)) { foreach (var assembly in GetAssemblies ()) registered_assemblies.Add (GetAssemblyName (assembly)); } else { registered_assemblies.Add (single_assembly); } foreach (var @class in allTypes) { var isPlatformType = IsPlatformType (@class.Type); var flags = MTTypeFlags.None; skip.Clear (); uint token_ref = uint.MaxValue; if (!@class.IsProtocol && !@class.IsCategory) { if (!isPlatformType) flags |= MTTypeFlags.CustomType; if (!@class.IsWrapper && !@class.IsModel) flags |= MTTypeFlags.UserType; CheckNamespace (@class, exceptions); token_ref = CreateTokenReference (@class.Type, TokenType.TypeDef); map.AppendLine ("{{ NULL, 0x{1:X} /* #{3} '{0}' => '{2}' */, (MTTypeFlags) ({4}) /* {5} */ }},", @class.ExportedName, CreateTokenReference (@class.Type, TokenType.TypeDef), GetAssemblyQualifiedName (@class.Type), map_entries, (int) flags, flags); map_dict [@class] = map_entries++; bool use_dynamic; if (@class.Type.Resolve ().Module.Assembly.Name.Name == PlatformAssembly) { // we don't need to use the static ref to prevent the linker from removing (otherwise unreferenced) code for monotouch.dll types. use_dynamic = true; // be smarter: we don't need to use dynamic refs for types available in the lowest version (target deployment) we building for. // We do need to use dynamic class lookup when the following conditions are all true: // * The class is not available in the target deployment version. // * The class is not in a weakly linked framework (for instance if an existing framework introduces a new class, we don't // weakly link the framework because it already exists in the target deployment version - but since the class doesn't, we // must use dynamic class lookup to determine if it's available or not. } else { use_dynamic = false; } switch (@class.ExportedName) { case "EKObject": // EKObject's class is a private symbol, so we can't link with it... use_dynamic = true; break; } string get_class; if (use_dynamic) { get_class = string.Format ("objc_getClass (\"{0}\")", @class.ExportedName); } else { get_class = string.Format ("[{0} class]", EncodeNonAsciiCharacters (@class.ExportedName)); } map_init.AppendLine ("__xamarin_class_map [{1}].handle = {0};", get_class, i++); } if (@class.IsProtocol && @class.ProtocolWrapperType != null) { if (token_ref == uint.MaxValue) token_ref = CreateTokenReference (@class.Type, TokenType.TypeDef); protocol_wrapper_map.Add (token_ref, new Tuple<ObjCType, uint> (@class, CreateTokenReference (@class.ProtocolWrapperType, TokenType.TypeDef))); if (needs_protocol_map) { protocols.Add (new ProtocolInfo { TokenReference = token_ref, Protocol = @class }); CheckNamespace (@class, exceptions); } } if (@class.IsWrapper && isPlatformType) continue; if (@class.Methods == null && isPlatformType && !@class.IsProtocol && !@class.IsCategory) continue; CheckNamespace (@class, exceptions); if (@class.BaseType != null) CheckNamespace (@class.BaseType, exceptions); var class_name = EncodeNonAsciiCharacters (@class.ExportedName); var is_protocol = @class.IsProtocol; // Publicly visible types should go into the header, private types go into the .m var td = @class.Type.Resolve (); AutoIndentStringBuilder iface; if (td.IsNotPublic || td.IsNestedPrivate || td.IsNestedAssembly || td.IsNestedFamilyAndAssembly) { iface = sb; } else { iface = interfaces; } if (@class.IsCategory) { var exportedName = EncodeNonAsciiCharacters (@class.BaseType.ExportedName); iface.Write ("@interface {0} ({1})", exportedName, @class.CategoryName); declarations.AppendFormat ("@class {0};\n", exportedName); } else if (is_protocol) { var exportedName = EncodeNonAsciiCharacters (@class.ProtocolName); iface.Write ("@protocol ").Write (exportedName); declarations.AppendFormat ("@protocol {0};\n", exportedName); } else { iface.Write ("@interface {0} : {1}", class_name, EncodeNonAsciiCharacters (@class.SuperType.ExportedName)); declarations.AppendFormat ("@class {0};\n", class_name); } bool any_protocols = false; ObjCType tp = @class; while (tp != null && tp != tp.BaseType) { if (tp.IsWrapper) break; // no need to declare protocols for wrapper types, they do it already in their headers. if (tp.Protocols != null) { for (int p = 0; p < tp.Protocols.Length; p++) { if (tp.Protocols [p].ProtocolName == "UIAppearance") continue; iface.Append (any_protocols ? ", " : "<"); any_protocols = true; iface.Append (tp.Protocols [p].ProtocolName); var proto = tp.Protocols [p].Type; CheckNamespace (proto, exceptions); } } if (App.Optimizations.RegisterProtocols == true && tp.AdoptedProtocols != null) { for (int p = 0; p < tp.AdoptedProtocols.Length; p++) { if (tp.AdoptedProtocols [p] == "UIAppearance") continue; // This is not a real protocol iface.Append (any_protocols ? ", " : "<"); any_protocols = true; iface.Append (tp.AdoptedProtocols [p]); } } tp = tp.BaseType; } if (any_protocols) iface.Append (">"); AutoIndentStringBuilder implementation_fields = null; if (is_protocol) { iface.WriteLine (); } else { iface.WriteLine (" {"); if (@class.Fields != null) { foreach (var field in @class.Fields.Values) { AutoIndentStringBuilder fields = null; if (field.IsPrivate) { // Private fields go in the @implementation section. if (implementation_fields == null) implementation_fields = new AutoIndentStringBuilder (1); fields = implementation_fields; } else { // Public fields go in the header. fields = iface; } try { switch (field.FieldType) { case "@": fields.Write ("id "); break; case "^v": fields.Write ("void *"); break; case "XamarinObject": fields.Write ("XamarinObject "); break; default: throw ErrorHelper.CreateError (4120, "The registrar found an unknown field type '{0}' in field '{1}.{2}'. Please file a bug report at https://github.com/xamarin/xamarin-macios/issues/new", field.FieldType, field.DeclaringType.Type.FullName, field.Name); } fields.Write (field.Name); fields.WriteLine (";"); } catch (Exception ex) { exceptions.Add (ex); } } } iface.WriteLine ("}"); } iface.Indent (); if (@class.Properties != null) { foreach (var property in @class.Properties) { try { if (is_protocol) iface.Write (property.IsOptional ? "@optional " : "@required "); iface.Write ("@property (nonatomic"); switch (property.ArgumentSemantic) { case ArgumentSemantic.Copy: iface.Write (", copy"); break; case ArgumentSemantic.Retain: iface.Write (", retain"); break; case ArgumentSemantic.Assign: case ArgumentSemantic.None: default: iface.Write (", assign"); break; } if (property.IsReadOnly) iface.Write (", readonly"); if (property.Selector != null) { if (property.GetterSelector != null && property.Selector != property.GetterSelector) iface.Write (", getter = ").Write (property.GetterSelector); if (property.SetterSelector != null) { var setterSel = string.Format ("set{0}{1}:", char.ToUpperInvariant (property.Selector [0]), property.Selector.Substring (1)); if (setterSel != property.SetterSelector) iface.Write (", setter = ").Write (property.SetterSelector); } } iface.Write (") "); try { iface.Write (ToObjCParameterType (property.PropertyType, property.DeclaringType.Type.FullName, exceptions, property.Property)); } catch (ProductException mte) { exceptions.Add (CreateException (4138, mte, property.Property, "The registrar cannot marshal the property type '{0}' of the property '{1}.{2}'.", GetTypeFullName (property.PropertyType), property.DeclaringType.Type.FullName, property.Name)); } iface.Write (" ").Write (property.Selector); iface.WriteLine (";"); } catch (Exception ex) { exceptions.Add (ex); } } } if (@class.Methods != null) { foreach (var method in @class.Methods) { try { if (is_protocol) iface.Write (method.IsOptional ? "@optional " : "@required "); iface.WriteLine ("{0};", GetObjCSignature (method, exceptions)); } catch (ProductException ex) { skip.Add (method); exceptions.Add (ex); } catch (Exception ex) { skip.Add (method); exceptions.Add (ErrorHelper.CreateError (4114, ex, "Unexpected error in the registrar for the method '{0}.{1}' - Please file a bug report at https://github.com/xamarin/xamarin-macios/issues/new", method.DeclaringType.Type.FullName, method.Method.Name)); } } } iface.Unindent (); iface.WriteLine ("@end"); iface.WriteLine (); if (!is_protocol && !@class.IsWrapper) { var hasClangDiagnostic = @class.IsModel; if (hasClangDiagnostic) sb.WriteLine ("#pragma clang diagnostic push"); if (@class.IsModel) { sb.WriteLine ("#pragma clang diagnostic ignored \"-Wprotocol\""); sb.WriteLine ("#pragma clang diagnostic ignored \"-Wobjc-protocol-property-synthesis\""); sb.WriteLine ("#pragma clang diagnostic ignored \"-Wobjc-property-implementation\""); } if (@class.IsCategory) { sb.WriteLine ("@implementation {0} ({1})", EncodeNonAsciiCharacters (@class.BaseType.ExportedName), @class.CategoryName); } else { sb.WriteLine ("@implementation {0} {{", class_name); if (implementation_fields != null) { sb.Indent (); sb.Append (implementation_fields); sb.Unindent (); } sb.WriteLine ("}"); } sb.Indent (); if (@class.Methods != null) { foreach (var method in @class.Methods) { if (skip.Contains (method)) continue; try { Specialize (sb, method, exceptions); } catch (Exception ex) { exceptions.Add (ex); } } } sb.Unindent (); sb.WriteLine ("@end"); if (hasClangDiagnostic) sb.AppendLine ("#pragma clang diagnostic pop"); } sb.WriteLine (); } map.AppendLine ("{ NULL, 0 },"); map.AppendLine ("};"); map.AppendLine (); if (skipped_types.Count > 0) { map.AppendLine ("static const MTManagedClassMap __xamarin_skipped_map [] = {"); foreach (var skipped in skipped_types) { skipped.SkippedTokenReference = CreateTokenReference (skipped.Skipped, TokenType.TypeDef); skipped.ActualTokenReference = CreateTokenReference (skipped.Actual.Type, TokenType.TypeDef); } foreach (var skipped in skipped_types.OrderBy ((v) => v.SkippedTokenReference)) map.AppendLine ("{{ 0x{0:X}, 0x{1:X} /* '{2}' => '{3}' */ }},", skipped.SkippedTokenReference, skipped.ActualTokenReference, skipped.Skipped.FullName, skipped.Actual.Type.FullName); map.AppendLine ("};"); map.AppendLine (); } map.AppendLine ("static const char *__xamarin_registration_assemblies []= {"); int count = 0; foreach (var assembly in registered_assemblies) { count++; if (count > 1) map.AppendLine (", "); map.Append ("\""); map.Append (assembly); map.Append ("\""); } map.AppendLine (); map.AppendLine ("};"); map.AppendLine (); if (full_token_reference_count > 0) { map.AppendLine ("static const struct MTFullTokenReference __xamarin_token_references [] = {"); map.AppendLine (full_token_references); map.AppendLine ("};"); map.AppendLine (); } if (protocol_wrapper_map.Count > 0) { var ordered = protocol_wrapper_map.OrderBy ((v) => v.Key); map.AppendLine ("static const MTProtocolWrapperMap __xamarin_protocol_wrapper_map [] = {"); foreach (var p in ordered) { map.AppendLine ("{{ 0x{0:X} /* {1} */, 0x{2:X} /* {3} */ }},", p.Key, p.Value.Item1.Name, p.Value.Item2, p.Value.Item1.ProtocolWrapperType.Name); } map.AppendLine ("};"); map.AppendLine (); } if (needs_protocol_map && protocols.Count > 0) { var ordered = protocols.OrderBy ((v) => v.TokenReference); map.AppendLine ("static const uint32_t __xamarin_protocol_tokens [] = {"); foreach (var p in ordered) map.AppendLine ("0x{0:X}, /* {1} */", p.TokenReference, p.Protocol.Type.FullName); map.AppendLine ("};"); map.AppendLine ("static const Protocol* __xamarin_protocols [] = {"); foreach (var p in ordered) { bool use_dynamic = false; #if MTOUCH switch (p.Protocol.ProtocolName) { case "CAMetalDrawable": // The header isn't available for the simulator. use_dynamic = IsSimulator; break; } #endif if (use_dynamic) { map.AppendLine ("objc_getProtocol (\"{0}\"), /* {1} */", p.Protocol.ProtocolName, p.Protocol.Type.FullName); } else { map.AppendLine ("@protocol ({0}), /* {1} */", p.Protocol.ProtocolName, p.Protocol.Type.FullName); } } map.AppendLine ("};"); } map.AppendLine ("static struct MTRegistrationMap __xamarin_registration_map = {"); map.AppendLine ("__xamarin_registration_assemblies,"); map.AppendLine ("__xamarin_class_map,"); map.AppendLine (full_token_reference_count == 0 ? "NULL," : "__xamarin_token_references,"); map.AppendLine (skipped_types.Count == 0 ? "NULL," : "__xamarin_skipped_map,"); map.AppendLine (protocol_wrapper_map.Count == 0 ? "NULL," : "__xamarin_protocol_wrapper_map,"); if (needs_protocol_map && protocols.Count > 0) { map.AppendLine ("{ __xamarin_protocol_tokens, __xamarin_protocols },"); } else { map.AppendLine ("{ NULL, NULL },"); } map.AppendLine ("{0},", count); map.AppendLine ("{0},", i); map.AppendLine ("{0},", full_token_reference_count); map.AppendLine ("{0},", skipped_types.Count); map.AppendLine ("{0},", protocol_wrapper_map.Count); map.AppendLine ("{0}", needs_protocol_map ? protocols.Count : 0); map.AppendLine ("};"); map_init.AppendLine ("xamarin_add_registration_map (&__xamarin_registration_map, {0});", string.IsNullOrEmpty (single_assembly) ? "false" : "true"); map_init.AppendLine ("}"); sb.WriteLine (map.ToString ()); sb.WriteLine (map_init.ToString ()); ErrorHelper.ThrowIfErrors (exceptions); } static bool HasIntPtrBoolCtor (TypeDefinition type) { if (!type.HasMethods) return false; foreach (var method in type.Methods) { if (!method.IsConstructor || !method.HasParameters) continue; if (method.Parameters.Count != 2) continue; if (!method.Parameters [0].ParameterType.Is ("System", "IntPtr")) continue; if (method.Parameters [1].ParameterType.Is ("System", "Boolean")) return true; } return false; } void Specialize (AutoIndentStringBuilder sb, ObjCMethod method, List<Exception> exceptions) { var isGeneric = method.DeclaringType.IsGeneric; switch (method.CurrentTrampoline) { case Trampoline.Retain: sb.WriteLine ("-(id) retain"); sb.WriteLine ("{"); sb.WriteLine ("return xamarin_retain_trampoline (self, _cmd);"); sb.WriteLine ("}"); sb.WriteLine (); return; case Trampoline.Release: sb.WriteLine ("-(void) release"); sb.WriteLine ("{"); sb.WriteLine ("xamarin_release_trampoline (self, _cmd);"); sb.WriteLine ("}"); sb.WriteLine (); return; case Trampoline.GetGCHandle: sb.WriteLine ("-(int) xamarinGetGCHandle"); sb.WriteLine ("{"); sb.WriteLine ("return __monoObjectGCHandle.gc_handle;"); sb.WriteLine ("}"); sb.WriteLine (); return; case Trampoline.SetGCHandle: sb.WriteLine ("-(void) xamarinSetGCHandle: (int) gc_handle"); sb.WriteLine ("{"); sb.WriteLine ("__monoObjectGCHandle.gc_handle = gc_handle;"); sb.WriteLine ("__monoObjectGCHandle.native_object = self;"); sb.WriteLine ("}"); sb.WriteLine (); return; case Trampoline.Constructor: if (isGeneric) { sb.WriteLine (GetObjCSignature (method, exceptions)); sb.WriteLine ("{"); sb.WriteLine ("xamarin_throw_product_exception (4126, \"Cannot construct an instance of the type '{0}' from Objective-C because the type is generic.\");\n", method.DeclaringType.Type.FullName.Replace ("/", "+")); sb.WriteLine ("return self;"); sb.WriteLine ("}"); return; } break; #if MONOMAC case Trampoline.CopyWithZone1: sb.AppendLine ("-(id) copyWithZone: (NSZone *) zone"); sb.AppendLine ("{"); sb.AppendLine ("id rv;"); sb.AppendLine ("int gchandle;"); sb.AppendLine (); sb.AppendLine ("gchandle = xamarin_get_gchandle_with_flags (self);"); sb.AppendLine ("if (gchandle != 0)"); sb.Indent ().AppendLine ("xamarin_set_gchandle (self, 0);").Unindent (); // Call the base class implementation sb.AppendLine ("rv = [super copyWithZone: zone];"); sb.AppendLine (); sb.AppendLine ("if (gchandle != 0)"); sb.Indent ().AppendLine ("xamarin_set_gchandle (self, gchandle);").Unindent (); sb.AppendLine (); sb.AppendLine ("return rv;"); sb.AppendLine ("}"); return; case Trampoline.CopyWithZone2: sb.AppendLine ("-(id) copyWithZone: (NSZone *) zone"); sb.AppendLine ("{"); sb.AppendLine ("return xamarin_copyWithZone_trampoline2 (self, _cmd, zone);"); sb.AppendLine ("}"); return; #endif } var rettype = string.Empty; var returntype = method.ReturnType; var isStatic = method.IsStatic; var isInstanceCategory = method.IsCategoryInstance; var isCtor = false; var num_arg = method.Method.HasParameters ? method.Method.Parameters.Count : 0; var descriptiveMethodName = method.DescriptiveMethodName; var name = GetUniqueTrampolineName ("native_to_managed_trampoline_" + descriptiveMethodName); var isVoid = returntype.FullName == "System.Void"; var merge_bodies = true; switch (method.CurrentTrampoline) { case Trampoline.None: case Trampoline.Normal: case Trampoline.Static: case Trampoline.Single: case Trampoline.Double: case Trampoline.Long: case Trampoline.StaticLong: case Trampoline.StaticDouble: case Trampoline.StaticSingle: case Trampoline.X86_DoubleABI_StaticStretTrampoline: case Trampoline.X86_DoubleABI_StretTrampoline: case Trampoline.StaticStret: case Trampoline.Stret: switch (method.NativeReturnType.FullName) { case "System.Int64": rettype = "long long"; break; case "System.UInt64": rettype = "unsigned long long"; break; case "System.Single": rettype = "float"; break; case "System.Double": rettype = "double"; break; default: rettype = ToObjCParameterType (method.NativeReturnType, descriptiveMethodName, exceptions, method.Method); break; } break; case Trampoline.Constructor: rettype = "id"; isCtor = true; break; default: return; } comment.Clear (); nslog_start.Clear (); nslog_end.Clear (); copyback.Clear (); invoke.Clear (); setup_call_stack.Clear (); body.Clear (); body_setup.Clear (); setup_return.Clear (); counter++; body.WriteLine ("{"); var indent = merge_bodies ? sb.Indentation : sb.Indentation + 1; body.Indentation = indent; body_setup.Indentation = indent; copyback.Indentation = indent; invoke.Indentation = indent; setup_call_stack.Indentation = indent; setup_return.Indentation = indent; var token_ref = CreateTokenReference (method.Method, TokenType.Method); // A comment describing the managed signature if (trace) { nslog_start.Indentation = sb.Indentation; comment.Indentation = sb.Indentation; nslog_end.Indentation = sb.Indentation; comment.AppendFormat ("// {2} {0}.{1} (", method.Method.DeclaringType.FullName, method.Method.Name, method.Method.ReturnType.FullName); for (int i = 0; i < num_arg; i++) { var param = method.Method.Parameters [i]; if (i > 0) comment.Append (", "); comment.AppendFormat ("{0} {1}", param.ParameterType.FullName, param.Name); } comment.AppendLine (")"); comment.AppendLine ("// ArgumentSemantic: {0} IsStatic: {1} Selector: '{2}' Signature: '{3}'", method.ArgumentSemantic, method.IsStatic, method.Selector, method.Signature); } // a couple of debug printfs if (trace) { StringBuilder args = new StringBuilder (); nslog_start.AppendFormat ("NSLog (@\"{0} (this: %@, sel: %@", name); for (int i = 0; i < num_arg; i++) { var type = method.Method.Parameters [i].ParameterType; bool isRef = type.IsByReference; if (isRef) type = type.GetElementType (); var td = type.Resolve (); nslog_start.AppendFormat (", {0}: ", method.Method.Parameters [i].Name); args.Append (", "); switch (type.FullName) { case "System.Drawing.RectangleF": if (isRef) { nslog_start.Append ("%p : %@"); #if MMP args.AppendFormat ("p{0}, p{0} ? NSStringFromRect (*p{0}) : @\"NULL\"", i); #else args.AppendFormat ("p{0}, p{0} ? NSStringFromCGRect (*p{0}) : @\"NULL\"", i); #endif } else { nslog_start.Append ("%@"); #if MMP args.AppendFormat ("NSStringFromRect (p{0})", i); #else args.AppendFormat ("NSStringFromCGRect (p{0})", i); #endif } break; case "System.Drawing.PointF": if (isRef) { nslog_start.Append ("%p: %@"); #if MMP args.AppendFormat ("p{0}, p{0} ? NSStringFromPoint (*p{0}) : @\"NULL\"", i); #else args.AppendFormat ("p{0}, p{0} ? NSStringFromCGPoint (*p{0}) : @\"NULL\"", i); #endif } else { nslog_start.Append ("%@"); #if MMP args.AppendFormat ("NSStringFromPoint (p{0})", i); #else args.AppendFormat ("NSStringFromCGPoint (p{0})", i); #endif } break; default: bool unknown; var spec = GetPrintfFormatSpecifier (td, out unknown); if (unknown) { nslog_start.AppendFormat ("%{0}", spec); args.AppendFormat ("&p{0}", i); } else if (isRef) { nslog_start.AppendFormat ("%p *= %{0}", spec); args.AppendFormat ("p{0}, *p{0}", i); } else { nslog_start.AppendFormat ("%{0}", spec); args.AppendFormat ("p{0}", i); } break; } } string ret_arg = string.Empty; nslog_end.Append (nslog_start.ToString ()); if (!isVoid) { bool unknown; var spec = GetPrintfFormatSpecifier (method.Method.ReturnType.Resolve (), out unknown); if (!unknown) { nslog_end.Append (" ret: %"); nslog_end.Append (spec); ret_arg = ", res"; } } nslog_end.Append (") END\", self, NSStringFromSelector (_cmd)"); nslog_end.Append (args.ToString ()); nslog_end.Append (ret_arg); nslog_end.AppendLine (");"); nslog_start.Append (") START\", self, NSStringFromSelector (_cmd)"); nslog_start.Append (args.ToString ()); nslog_start.AppendLine (");"); } // prepare the parameters var baseMethod = GetBaseMethodInTypeHierarchy (method.Method); for (int i = 0; i < num_arg; i++) { var param = method.Method.Parameters [i]; var paramBase = baseMethod.Parameters [i]; var type = method.Parameters [i]; var nativetype = method.NativeParameters [i]; var objctype = ToObjCParameterType (nativetype, descriptiveMethodName, exceptions, method.Method); var original_objctype = objctype; var isRef = type.IsByReference; var isOut = param.IsOut || paramBase.IsOut; var isArray = type is ArrayType; var isByRefArray = isRef && GetElementType (type) is ArrayType; var isNativeEnum = false; var td = type.Resolve (); var isVariadic = i + 1 == num_arg && method.IsVariadic; if (type != nativetype) { GenerateConversionToManaged (nativetype, type, setup_call_stack, descriptiveMethodName, ref exceptions, method, $"p{i}", $"arg_ptrs [{i}]", $"mono_class_from_mono_type (xamarin_get_parameter_type (managed_method, {i}))"); if (isRef || isOut) throw ErrorHelper.CreateError (4163, $"Internal error in the registrar (BindAs parameters can't be ref/out: {descriptiveMethodName}). Please file a bug report at https://github.com/xamarin/xamarin-macios/issues/new"); continue; } else if (isRef) { type = GetElementType (type); td = type.Resolve (); original_objctype = ToObjCParameterType (type, descriptiveMethodName, exceptions, method.Method); objctype = ToObjCParameterType (type, descriptiveMethodName, exceptions, method.Method) + "*"; } else if (td.IsEnum) { type = GetEnumUnderlyingType (td); isNativeEnum = IsDualBuild && HasAttribute (td, ObjCRuntime, StringConstants.NativeAttribute); td = type.Resolve (); } switch (type.FullName) { case "System.Int64": case "System.UInt64": // We already show MT4145 if the underlying enum type isn't a long or ulong if (isNativeEnum) { string tp; string ntp; if (type.FullName == "System.UInt64") { tp = "unsigned long long"; ntp = "NSUInteger"; } else { tp = "long long"; ntp = "NSInteger"; } if (isRef || isOut) { body_setup.AppendLine ("{1} nativeEnum{0} = 0;", i, tp); setup_call_stack.AppendLine ("arg_ptrs [{0}] = &nativeEnum{0};", i); copyback.AppendLine ("*p{0} = ({1}) nativeEnum{0};", ntp); } else { body_setup.AppendLine ("{1} nativeEnum{0} = p{0};", i, tp); setup_call_stack.AppendLine ("arg_ptrs [{0}] = &nativeEnum{0};", i); } break; } goto case "System.SByte"; case "System.SByte": case "System.Byte": case "System.Char": case "System.Int16": case "System.UInt16": case "System.Int32": case "System.UInt32": case "System.Single": case "System.Double": case "System.Boolean": if (isRef || isOut) { // The isOut semantics isn't quite correct here: we pass the actual input value to managed code. // In theory we should create a temp location and then use a writeback when done instead. // This should be safe though, since managed code (at least C#) can't actually observe the value. setup_call_stack.AppendLine ("arg_ptrs [{0}] = p{0};", i); } else { setup_call_stack.AppendLine ("arg_ptrs [{0}] = &p{0};", i); } break; case "System.IntPtr": if (isVariadic) { body_setup.AppendLine ("va_list a{0};", i); setup_call_stack.AppendLine ("va_start (a{0}, p{1});", i, i - 1); setup_call_stack.AppendLine ("arg_ptrs [{0}] = &a{0};", i); copyback.AppendLine ("va_end (a{0});", i); } else if (isOut) { body_setup.AppendLine ("{1} a{0} = 0;", i, objctype); setup_call_stack.AppendLine ("arg_ptrs [{0}] = &a{0};", i); copyback.AppendLine ("*p{0} = a{0};", i); } else if (isRef) { setup_call_stack.AppendLine ("arg_ptrs [{0}] = p{0};", i); } else { body_setup.AppendLine ("{1} a{0} = p{0};", i, original_objctype); setup_call_stack.AppendLine ("arg_ptrs [{0}] = &a{0};", i); } break; case "ObjCRuntime.Selector": case CompatNamespace + ".ObjCRuntime.Selector": if (isRef) { body_setup.AppendLine ("MonoObject *a{0} = NULL;", i); if (!isOut) { setup_call_stack.AppendLine ("a{0} = *p{0} ? xamarin_get_selector (*p{0}, &exception_gchandle) : NULL;", i); setup_call_stack.AppendLine ("if (exception_gchandle != 0) goto exception_handling;"); } setup_call_stack.AppendLine ("arg_ptrs [{0}] = &a{0};", i); copyback.AppendLine ("*p{0} = a{0} ? (SEL) xamarin_get_handle_for_inativeobject (a{0}, &exception_gchandle) : NULL;", i); copyback.AppendLine ("if (exception_gchandle != 0) goto exception_handling;"); } else { setup_call_stack.AppendLine ("arg_ptrs [{0}] = p{0} ? xamarin_get_selector (p{0}, &exception_gchandle) : NULL;", i); setup_call_stack.AppendLine ("if (exception_gchandle != 0) goto exception_handling;"); } break; case "ObjCRuntime.Class": case CompatNamespace + ".ObjCRuntime.Class": if (isRef) { body_setup.AppendLine ("MonoObject *a{0} = NULL;", i); if (!isOut) { setup_call_stack.AppendLine ("a{0} = *p{0} ? xamarin_get_class (*p{0}, &exception_gchandle) : NULL;", i); setup_call_stack.AppendLine ("if (exception_gchandle != 0) goto exception_handling;"); } setup_call_stack.AppendLine ("arg_ptrs [{0}] = &a{0};", i); copyback.AppendLine ("*p{0} = a{0} ? (Class) xamarin_get_handle_for_inativeobject (a{0}, &exception_gchandle) : NULL;", i); copyback.AppendLine ("if (exception_gchandle != 0) goto exception_handling;"); } else { setup_call_stack.AppendLine ("arg_ptrs [{0}] = p{0} ? xamarin_get_class (p{0}, &exception_gchandle) : NULL;", i); setup_call_stack.AppendLine ("if (exception_gchandle != 0) goto exception_handling;"); } break; case "System.String": // This should always be an NSString and never char* if (isRef) { body_setup.AppendLine ("MonoString *a{0} = NULL;", i); if (!isOut) setup_call_stack.AppendLine ("a{0} = xamarin_nsstring_to_string (NULL, *p{0});", i); setup_call_stack.AppendLine ("arg_ptrs [{0}] = &a{0};", i); body_setup.AppendLine ("char *str{0} = NULL;", i); copyback.AppendLine ("*p{0} = xamarin_string_to_nsstring (a{0}, false);", i); } else { setup_call_stack.AppendLine ("arg_ptrs [{0}] = xamarin_nsstring_to_string (NULL, p{0});", i); } break; default: if (isArray || isByRefArray) { var elementType = ((ArrayType)type).ElementType; body_setup.AppendLine ("MonoArray *marr{0} = NULL;", i); body_setup.AppendLine ("NSArray *arr{0} = NULL;", i); if (isByRefArray) { body_setup.AppendLine ("MonoArray *original_marr{0} = NULL;", i); setup_call_stack.AppendLine ("if (p{0} == NULL) {{", i); setup_call_stack.AppendLine ("arg_ptrs [{0}] = NULL;", i); setup_call_stack.AppendLine ("} else {"); setup_call_stack.AppendLine ("if (*p{0} != NULL) {{", i); setup_call_stack.AppendLine ("arr{0} = *(NSArray **) p{0};", i); } else { setup_call_stack.AppendLine ("arr{0} = p{0};", i); if (App.EnableDebug) setup_call_stack.AppendLine ("xamarin_check_objc_type (p{0}, [NSArray class], _cmd, self, {0}, managed_method);", i); } var isString = elementType.Is ("System", "String"); var isNSObject = !isString && IsNSObject (elementType); var isINativeObject = !isString && !isNSObject && IsNativeObject (elementType); if (isString) { setup_call_stack.AppendLine ("marr{0} = xamarin_nsarray_to_managed_string_array (arr{0}, &exception_gchandle);", i); setup_call_stack.AppendLine ("if (exception_gchandle != 0) goto exception_handling;"); } else if (isNSObject) { setup_call_stack.AppendLine ("marr{0} = xamarin_nsarray_to_managed_nsobject_array (arr{0}, xamarin_get_parameter_type (managed_method, {0}), NULL, &exception_gchandle);", i); setup_call_stack.AppendLine ("if (exception_gchandle != 0) goto exception_handling;"); } else if (isINativeObject) { TypeDefinition nativeObjType = elementType.Resolve (); var isNativeObjectInterface = nativeObjType.IsInterface; if (isNativeObjectInterface) { var wrapper_type = GetProtocolAttributeWrapperType (nativeObjType); if (wrapper_type == null) throw ErrorHelper.CreateError (4125, "The registrar found an invalid type '{0}' in signature for method '{1}': " + "The interface must have a Protocol attribute specifying its wrapper type.", td.FullName, descriptiveMethodName); nativeObjType = wrapper_type.Resolve (); } // verify that the type has a ctor with two parameters if (!HasIntPtrBoolCtor (nativeObjType)) throw ErrorHelper.CreateError (4103, "The registrar found an invalid type `{0}` in signature for method `{1}`: " + "The type implements INativeObject, but does not have a constructor that takes " + "two (IntPtr, bool) arguments.", nativeObjType.FullName, descriptiveMethodName); if (isNativeObjectInterface) { var resolvedElementType = ResolveType (elementType); var iface_token_ref = $"0x{CreateTokenReference (resolvedElementType, TokenType.TypeDef):X} /* {resolvedElementType} */ "; var implementation_token_ref = $"0x{CreateTokenReference (nativeObjType, TokenType.TypeDef):X} /* {nativeObjType} */ "; setup_call_stack.AppendLine ("marr{0} = xamarin_nsarray_to_managed_inativeobject_array_static (arr{0}, xamarin_get_parameter_type (managed_method, {0}), NULL, {1}, {2}, &exception_gchandle);", i, iface_token_ref, implementation_token_ref); } else { setup_call_stack.AppendLine ("marr{0} = xamarin_nsarray_to_managed_inativeobject_array (arr{0}, xamarin_get_parameter_type (managed_method, {0}), NULL, &exception_gchandle);", i); } setup_call_stack.AppendLine ("if (exception_gchandle != 0) goto exception_handling;"); } else { throw ErrorHelper.CreateError (App, 4111, method.Method, "The registrar cannot build a signature for type `{0}' in method `{1}`.", type.FullName, descriptiveMethodName); } if (isByRefArray) { setup_call_stack.AppendLine ("}"); setup_call_stack.AppendLine ("original_marr{0} = marr{0};", i); setup_call_stack.AppendLine ("arg_ptrs [{0}] = &marr{0};", i); setup_call_stack.AppendLine ("}"); } else { setup_call_stack.AppendLine ("arg_ptrs [{0}] = marr{0};", i); } if (isByRefArray) { copyback.AppendLine ("if (p{0} && original_marr{0} != marr{0}) {{", i); if (isString) { copyback.AppendLine ("*p{0} = xamarin_managed_string_array_to_nsarray (marr{0}, &exception_gchandle);", i); } else if (isNSObject) { copyback.AppendLine ("*p{0} = xamarin_managed_nsobject_array_to_nsarray (marr{0}, &exception_gchandle);", i); } else if (isINativeObject) { copyback.AppendLine ("*p{0} = xamarin_managed_inativeobject_array_to_nsarray (marr{0}, &exception_gchandle);", i); } else { throw ErrorHelper.CreateError (99, "Internal error: byref array is neither string, NSObject or INativeObject."); } copyback.AppendLine ("}"); } } else if (IsNSObject (type)) { if (isRef) { body_setup.AppendLine ("MonoObject *mobj{0} = NULL;", i); if (!isOut) { body_setup.AppendLine ("NSObject *nsobj{0} = NULL;", i); setup_call_stack.AppendLine ("nsobj{0} = *(NSObject **) p{0};", i); setup_call_stack.AppendLine ("if (nsobj{0}) {{", i); body_setup.AppendLine ("MonoType *paramtype{0} = NULL;", i); setup_call_stack.AppendLine ("paramtype{0} = xamarin_get_parameter_type (managed_method, {0});", i); setup_call_stack.AppendLine ("mobj{0} = xamarin_get_nsobject_with_type_for_ptr (nsobj{0}, false, paramtype{0}, &exception_gchandle);", i); setup_call_stack.AppendLine ("if (exception_gchandle != 0) {"); setup_call_stack.AppendLine ("exception_gchandle = xamarin_get_exception_for_parameter (8029, exception_gchandle, \"Unable to marshal the byref parameter\", _cmd, managed_method, paramtype{0}, {0}, true);", i); setup_call_stack.AppendLine ("goto exception_handling;"); setup_call_stack.AppendLine ("}"); if (App.EnableDebug) { setup_call_stack.AppendLine ("xamarin_verify_parameter (mobj{0}, _cmd, self, nsobj{0}, {0}, mono_class_from_mono_type (paramtype{0}), managed_method);", i); } setup_call_stack.AppendLine ("}"); } // argument semantics? setup_call_stack.AppendLine ("arg_ptrs [{0}] = (int *) &mobj{0};", i); body_setup.AppendLine ("void * handle{0} = NULL;", i); copyback.AppendLine ("if (mobj{0} != NULL)", i); copyback.AppendLine ("handle{0} = xamarin_get_nsobject_handle (mobj{0});", i); copyback.AppendLine ("if (p{0} != NULL)", i).Indent (); copyback.AppendLine ("*p{0} = (id) handle{0};", i).Unindent (); } else { body_setup.AppendLine ("NSObject *nsobj{0} = NULL;", i); setup_call_stack.AppendLine ("nsobj{0} = (NSObject *) p{0};", i); if (method.ArgumentSemantic == ArgumentSemantic.Copy) { setup_call_stack.AppendLine ("nsobj{0} = [nsobj{0} copy];", i); setup_call_stack.AppendLine ("[nsobj{0} autorelease];", i); } body_setup.AppendLine ("MonoObject *mobj{0} = NULL;", i); body_setup.AppendLine ("int32_t created{0} = false;", i); setup_call_stack.AppendLine ("if (nsobj{0}) {{", i); body_setup.AppendLine ("MonoType *paramtype{0} = NULL;", i); setup_call_stack.AppendLine ("paramtype{0} = xamarin_get_parameter_type (managed_method, {0});", i); setup_call_stack.AppendLine ("mobj{0} = xamarin_get_nsobject_with_type_for_ptr_created (nsobj{0}, false, paramtype{0}, &created{0}, &exception_gchandle);", i); setup_call_stack.AppendLine ("if (exception_gchandle != 0) {"); setup_call_stack.AppendLine ("exception_gchandle = xamarin_get_exception_for_parameter (8029, exception_gchandle, \"Unable to marshal the parameter\", _cmd, managed_method, paramtype{0}, {0}, true);", i); setup_call_stack.AppendLine ("goto exception_handling;"); setup_call_stack.AppendLine ("}"); if (App.EnableDebug) { setup_call_stack.AppendLine ("xamarin_verify_parameter (mobj{0}, _cmd, self, nsobj{0}, {0}, mono_class_from_mono_type (paramtype{0}), managed_method);", i); } setup_call_stack.AppendLine ("}"); setup_call_stack.AppendLine ("arg_ptrs [{0}] = mobj{0};", i); if (HasAttribute (paramBase, ObjCRuntime, StringConstants.TransientAttribute)) { copyback.AppendLine ("if (created{0}) {{", i); copyback.AppendLine ("xamarin_dispose (mobj{0}, &exception_gchandle);", i); copyback.AppendLine ("if (exception_gchandle != 0) goto exception_handling;"); copyback.AppendLine ("}"); } } } else if (IsNativeObject (td)) { TypeDefinition nativeObjType = td; if (td.IsInterface) { var wrapper_type = GetProtocolAttributeWrapperType (td); if (wrapper_type == null) throw ErrorHelper.CreateError (4125, "The registrar found an invalid type '{0}' in signature for method '{1}': " + "The interface must have a Protocol attribute specifying its wrapper type.", td.FullName, descriptiveMethodName); nativeObjType = wrapper_type.Resolve (); } // verify that the type has a ctor with two parameters if (!HasIntPtrBoolCtor (nativeObjType)) throw ErrorHelper.CreateError (4103, "The registrar found an invalid type `{0}` in signature for method `{1}`: " + "The type implements INativeObject, but does not have a constructor that takes " + "two (IntPtr, bool) arguments.", nativeObjType.FullName, descriptiveMethodName); if (!td.IsInterface) { // find the MonoClass for this parameter body_setup.AppendLine ("MonoType *type{0};", i); setup_call_stack.AppendLine ("type{0} = xamarin_get_parameter_type (managed_method, {0});", i); } if (isRef) { body_setup.AppendLine ("MonoObject *inobj{0} = NULL;", i); if (isOut) { setup_call_stack.AppendLine ("inobj{0} = NULL;", i); } else if (td.IsInterface) { setup_call_stack.AppendLine ("inobj{0} = xamarin_get_inative_object_static (*p{0}, false, 0x{1:X} /* {2} */, 0x{3:X} /* {4} */, &exception_gchandle);", i, CreateTokenReference (td, TokenType.TypeDef), td.FullName, CreateTokenReference (nativeObjType, TokenType.TypeDef), nativeObjType.FullName); setup_call_stack.AppendLine ("if (exception_gchandle != 0) goto exception_handling;"); } else { setup_call_stack.AppendLine ("inobj{0} = xamarin_get_inative_object_dynamic (*p{0}, false, mono_type_get_object (mono_domain_get (), type{0}), &exception_gchandle);", i); setup_call_stack.AppendLine ("if (exception_gchandle != 0) goto exception_handling;"); } setup_call_stack.AppendLine ("arg_ptrs [{0}] = &inobj{0};", i); body_setup.AppendLine ("id handle{0} = nil;", i); copyback.AppendLine ("if (inobj{0} != NULL)", i); copyback.AppendLine ("handle{0} = xamarin_get_handle_for_inativeobject (inobj{0}, &exception_gchandle);", i); copyback.AppendLine ("if (exception_gchandle != 0) goto exception_handling;"); copyback.AppendLine ("*p{0} = (id) handle{0};", i); } else { if (td.IsInterface) { setup_call_stack.AppendLine ("arg_ptrs [{0}] = xamarin_get_inative_object_static (p{0}, false, 0x{1:X} /* {2} */, 0x{3:X} /* {4} */, &exception_gchandle);", i, CreateTokenReference (td, TokenType.TypeDef), td.FullName, CreateTokenReference (nativeObjType, TokenType.TypeDef), nativeObjType.FullName); } else { setup_call_stack.AppendLine ("arg_ptrs [{0}] = xamarin_get_inative_object_dynamic (p{0}, false, mono_type_get_object (mono_domain_get (), type{0}), &exception_gchandle);", i); } setup_call_stack.AppendLine ("if (exception_gchandle != 0) goto exception_handling;"); } } else if (type.IsValueType) { if (isRef || isOut) { // The isOut semantics isn't quite correct here: we pass the actual input value to managed code. // In theory we should create a temp location and then use a writeback when done instead. // This should be safe though, since managed code (at least C#) can't actually observe the value. setup_call_stack.AppendLine ("arg_ptrs [{0}] = p{0};", i); } else { setup_call_stack.AppendLine ("arg_ptrs [{0}] = &p{0};", i); } } else if (td.BaseType.FullName == "System.MulticastDelegate") { if (isRef) { throw ErrorHelper.CreateError (4110, "The registrar cannot marshal the out parameter of type `{0}` in signature for method `{1}`.", type.FullName, descriptiveMethodName); } else { // Bug #4858 (also related: #4718) var token = "INVALID_TOKEN_REF"; if (App.Optimizations.StaticBlockToDelegateLookup == true) { var creatorMethod = GetBlockWrapperCreator (method, i); if (creatorMethod != null) { token = $"0x{CreateTokenReference (creatorMethod, TokenType.Method):X} /* {creatorMethod.FullName} */ "; } else { exceptions.Add (ErrorHelper.CreateWarning (App, 4174, method.Method, "Unable to locate the block to delegate conversion method for the method {0}'s parameter #{1}.", method.DescriptiveMethodName, i + 1)); } } setup_call_stack.AppendLine ("if (p{0}) {{", i); setup_call_stack.AppendLine ("arg_ptrs [{0}] = (void *) xamarin_get_delegate_for_block_parameter (managed_method, {1}, {0}, p{0}, &exception_gchandle);", i, token); setup_call_stack.AppendLine ("if (exception_gchandle != 0) goto exception_handling;"); setup_call_stack.AppendLine ("} else {"); setup_call_stack.AppendLine ("arg_ptrs [{0}] = NULL;", i); setup_call_stack.AppendLine ("}"); } } else { throw ErrorHelper.CreateError (App, 4105, method.Method, "The registrar cannot marshal the parameter of type `{0}` in signature for method `{1}`.", type.FullName, descriptiveMethodName); } break; } } // the actual invoke if (isCtor) { invoke.AppendLine ("mthis = mono_object_new (mono_domain_get (), mono_method_get_class (managed_method));"); body_setup.AppendLine ("uint8_t flags = NSObjectFlagsNativeRef;"); invoke.AppendLine ("xamarin_set_nsobject_handle (mthis, self);"); invoke.AppendLine ("xamarin_set_nsobject_flags (mthis, flags);"); } var marshal_exception = "NULL"; if (App.MarshalManagedExceptions != MarshalManagedExceptionMode.Disable) { body_setup.AppendLine ("MonoObject *exception = NULL;"); if (App.EnableDebug && App.IsDefaultMarshalManagedExceptionMode) { body_setup.AppendLine ("MonoObject **exception_ptr = xamarin_is_managed_exception_marshaling_disabled () ? NULL : &exception;"); marshal_exception = "exception_ptr"; } else { marshal_exception = "&exception"; } } if (!isVoid) { body_setup.AppendLine ("MonoObject *retval = NULL;"); invoke.Append ("retval = "); } invoke.AppendLine ("mono_runtime_invoke (managed_method, {0}, arg_ptrs, {1});", isStatic ? "NULL" : "mthis", marshal_exception); if (isCtor) invoke.AppendLine ("xamarin_create_managed_ref (self, mthis, true);"); body_setup.AppendLine ("guint32 exception_gchandle = 0;"); // prepare the return value if (!isVoid) { switch (rettype) { case "CGRect": body_setup.AppendLine ("{0} res = {{{{0}}}};", rettype); break; default: body_setup.AppendLine ("{0} res = {{0}};", rettype); break; } var isArray = returntype is ArrayType; var type = returntype.Resolve () ?? returntype; var retain = method.RetainReturnValue; if (returntype != method.NativeReturnType) { GenerateConversionToNative (returntype, method.NativeReturnType, setup_return, descriptiveMethodName, ref exceptions, method, "retval", "res", "mono_class_from_mono_type (xamarin_get_parameter_type (managed_method, -1))"); } else if (returntype.IsValueType) { setup_return.AppendLine ("res = *({0} *) mono_object_unbox ((MonoObject *) retval);", rettype); } else if (isArray) { var elementType = ((ArrayType) returntype).ElementType; var conversion_func = string.Empty; if (elementType.FullName == "System.String") { conversion_func = "xamarin_managed_string_array_to_nsarray"; } else if (IsNSObject (elementType)) { conversion_func = "xamarin_managed_nsobject_array_to_nsarray"; } else if (IsINativeObject (elementType)) { conversion_func = "xamarin_managed_inativeobject_array_to_nsarray"; } else { throw ErrorHelper.CreateError (App, 4111, method.Method, "The registrar cannot build a signature for type `{0}' in method `{1}`.", method.NativeReturnType.FullName, descriptiveMethodName); } setup_return.AppendLine ("res = {0} ((MonoArray *) retval, &exception_gchandle);", conversion_func); if (retain) setup_return.AppendLine ("[res retain];"); setup_return.AppendLine ("if (exception_gchandle != 0) goto exception_handling;"); setup_return.AppendLine ("xamarin_framework_peer_lock ();"); setup_return.AppendLine ("mt_dummy_use (retval);"); setup_return.AppendLine ("xamarin_framework_peer_unlock ();"); } else { setup_return.AppendLine ("if (!retval) {"); setup_return.AppendLine ("res = NULL;"); setup_return.AppendLine ("} else {"); if (IsNSObject (type)) { setup_return.AppendLine ("id retobj;"); setup_return.AppendLine ("retobj = xamarin_get_nsobject_handle (retval);"); setup_return.AppendLine ("xamarin_framework_peer_lock ();"); setup_return.AppendLine ("[retobj retain];"); setup_return.AppendLine ("xamarin_framework_peer_unlock ();"); if (!retain) setup_return.AppendLine ("[retobj autorelease];"); setup_return.AppendLine ("mt_dummy_use (retval);"); setup_return.AppendLine ("res = retobj;"); } else if (IsPlatformType (type, "ObjCRuntime", "Selector")) { setup_return.AppendLine ("res = (SEL) xamarin_get_handle_for_inativeobject (retval, &exception_gchandle);"); setup_return.AppendLine ("if (exception_gchandle != 0) goto exception_handling;"); } else if (IsPlatformType (type, "ObjCRuntime", "Class")) { setup_return.AppendLine ("res = (Class) xamarin_get_handle_for_inativeobject (retval, &exception_gchandle);"); setup_return.AppendLine ("if (exception_gchandle != 0) goto exception_handling;"); } else if (IsNativeObject (type)) { setup_return.AppendLine ("{0} retobj;", rettype); setup_return.AppendLine ("retobj = xamarin_get_handle_for_inativeobject ((MonoObject *) retval, &exception_gchandle);"); setup_return.AppendLine ("if (exception_gchandle != 0) goto exception_handling;"); setup_return.AppendLine ("xamarin_framework_peer_lock ();"); setup_return.AppendLine ("[retobj retain];"); setup_return.AppendLine ("xamarin_framework_peer_unlock ();"); if (!retain) setup_return.AppendLine ("[retobj autorelease];"); setup_return.AppendLine ("mt_dummy_use (retval);"); setup_return.AppendLine ("res = retobj;"); } else if (type.FullName == "System.String") { // This should always be an NSString and never char* setup_return.AppendLine ("res = xamarin_string_to_nsstring ((MonoString *) retval, {0});", retain ? "true" : "false"); } else if (IsDelegate (type.Resolve ())) { var signature = "NULL"; var token = "INVALID_TOKEN_REF"; if (App.Optimizations.OptimizeBlockLiteralSetupBlock == true) { if (type.Is ("System", "Delegate") || type.Is ("System", "MulticastDelegate")) { ErrorHelper.Show (ErrorHelper.CreateWarning (App, 4173, method.Method, $"The registrar can't compute the block signature for the delegate of type {type.FullName} in the method {descriptiveMethodName} because {type.FullName} doesn't have a specific signature.")); } else { var delegateMethod = type.Resolve ().GetMethods ().FirstOrDefault ((v) => v.Name == "Invoke"); if (delegateMethod == null) { ErrorHelper.Show (ErrorHelper.CreateWarning (App, 4173, method.Method, $"The registrar can't compute the block signature for the delegate of type {type.FullName} in the method {descriptiveMethodName} because it couldn't find the Invoke method of the delegate type.")); } else { signature = "\"" + ComputeSignature (method.DeclaringType.Type, null, method, isBlockSignature: true) + "\""; } } var delegateProxyType = GetDelegateProxyType (method); if (delegateProxyType != null) { token = $"0x{CreateTokenReference (delegateProxyType, TokenType.TypeDef):X} /* {delegateProxyType.FullName} */ "; } else { exceptions.Add (ErrorHelper.CreateWarning (App, 4176, method.Method, "Unable to locate the delegate to block conversion type for the return value of the method {0}.", method.DescriptiveMethodName)); } } setup_return.AppendLine ("res = xamarin_get_block_for_delegate (managed_method, retval, {0}, {1}, &exception_gchandle);", signature, token); setup_return.AppendLine ("if (exception_gchandle != 0) goto exception_handling;"); } else { throw ErrorHelper.CreateError (4104, "The registrar cannot marshal the return value for type `{0}` in signature for method `{1}`.", returntype.FullName, descriptiveMethodName); } setup_return.AppendLine ("}"); } } if (App.Embeddinator) body.WriteLine ("xamarin_embeddinator_initialize ();"); body.WriteLine ("MONO_ASSERT_GC_SAFE;"); body.WriteLine ("MONO_THREAD_ATTACH;"); // COOP: this will switch to GC_UNSAFE body.WriteLine (); // Write out everything if (merge_bodies) { body_setup.WriteLine ("MonoMethod *managed_method = *managed_method_ptr;"); } else { if (!isGeneric) body.Write ("static "); body.WriteLine ("MonoMethod *managed_method = NULL;"); } if (comment.Length > 0) body.WriteLine (comment.ToString ()); if (isInstanceCategory) body.WriteLine ("id p0 = self;"); body_setup.WriteLine ("void *arg_ptrs [{0}];", num_arg); if (!isStatic || isInstanceCategory) body.WriteLine ("MonoObject *mthis = NULL;"); if (isCtor) { body.WriteLine ("bool has_nsobject = xamarin_has_nsobject (self, &exception_gchandle);"); body.WriteLine ("if (exception_gchandle != 0) goto exception_handling;"); body.WriteLine ("if (has_nsobject) {"); body.WriteLine ("*call_super = true;"); body.WriteLine ("goto exception_handling;"); body.WriteLine ("}"); } if ((!isStatic || isInstanceCategory) && !isCtor) { body.WriteLine ("if (self) {"); body.WriteLine ("mthis = xamarin_get_managed_object_for_ptr_fast (self, &exception_gchandle);"); body.WriteLine ("if (exception_gchandle != 0) goto exception_handling;"); body.WriteLine ("}"); } // no locking should be required here, it doesn't matter if we overwrite the field (it'll be the same value). body.WriteLine ("if (!managed_method) {"); body.Write ("MonoReflectionMethod *reflection_method = "); if (isGeneric) body.Write ("xamarin_get_generic_method_from_token (mthis, "); else body.Write ("xamarin_get_method_from_token ("); if (merge_bodies) { body.WriteLine ("token_ref, &exception_gchandle);"); } else { body.WriteLine ("0x{0:X}, &exception_gchandle);", token_ref); } body.WriteLine ("if (exception_gchandle != 0) goto exception_handling;"); body.WriteLine ("managed_method = xamarin_get_reflection_method_method (reflection_method);"); if (merge_bodies) body.WriteLine ("*managed_method_ptr = managed_method;"); body.WriteLine ("}"); if (!isStatic && !isInstanceCategory && !isCtor) { body.WriteLine ("xamarin_check_for_gced_object (mthis, _cmd, self, managed_method, &exception_gchandle);"); body.WriteLine ("if (exception_gchandle != 0) goto exception_handling;"); } if (trace) body.AppendLine (nslog_start); body.AppendLine (setup_call_stack); body.AppendLine (invoke); body.AppendLine (copyback); body.AppendLine (setup_return); if (trace ) body.AppendLine (nslog_end); body.StringBuilder.AppendLine ("exception_handling:;"); body.WriteLine ("MONO_THREAD_DETACH;"); // COOP: this will switch to GC_SAFE body.AppendLine ("if (exception_gchandle != 0)"); body.Indent ().WriteLine ("xamarin_process_managed_exception_gchandle (exception_gchandle);").Unindent (); if (App.MarshalManagedExceptions != MarshalManagedExceptionMode.Disable) body.WriteLine ("xamarin_process_managed_exception (exception);"); if (isCtor) { body.WriteLine ("return self;"); } else if (isVoid) { body.WriteLine ("return;"); } else { body.WriteLine ("return res;"); } body.WriteLine ("}"); body.StringBuilder.Insert (2, body_setup); /* We merge duplicated bodies (based on the signature of the method and the entire body) */ var objc_signature = new StringBuilder ().Append (rettype).Append (":"); if (method.Method.HasParameters) { for (int i = 0; i < method.NativeParameters.Length; i++) objc_signature.Append (ToObjCParameterType (method.NativeParameters [i], descriptiveMethodName, exceptions, method.Method)).Append (":"); } Body existing; Body b = new Body () { Code = body.ToString (), Signature = objc_signature.ToString (), }; if (merge_bodies && bodies.TryGetValue (b, out existing)) { /* We already have an identical trampoline, use it instead */ b = existing; } else { /* Need to create a new trampoline */ if (merge_bodies) bodies [b] = b; b.Name = "native_to_managed_trampoline_" + bodies.Count.ToString (); if (merge_bodies) { methods.Append ("static "); methods.Append (rettype).Append (" ").Append (b.Name).Append (" (id self, SEL _cmd, MonoMethod **managed_method_ptr"); var pcount = method.Method.HasParameters ? method.NativeParameters.Length : 0; for (int i = (isInstanceCategory ? 1 : 0); i < pcount; i++) { methods.Append (", ").Append (ToObjCParameterType (method.NativeParameters [i], descriptiveMethodName, exceptions, method.Method)); methods.Append (" ").Append ("p").Append (i.ToString ()); } if (isCtor) methods.Append (", bool* call_super"); methods.Append (", uint32_t token_ref"); methods.AppendLine (")"); methods.AppendLine (body); methods.AppendLine (); } } b.Count++; sb.WriteLine (); sb.WriteLine (GetObjCSignature (method, exceptions)); if (merge_bodies) { sb.WriteLine ("{"); if (!isGeneric) sb.Write ("static "); sb.WriteLine ("MonoMethod *managed_method = NULL;"); if (isCtor) { sb.WriteLine ("bool call_super = false;"); sb.Write ("id rv = "); } else if (!isVoid) { sb.Write ("return "); } sb.Write (b.Name); sb.Write (" (self, _cmd, &managed_method"); var paramCount = method.Method.HasParameters ? method.Method.Parameters.Count : 0; if (isInstanceCategory) paramCount--; for (int i = 0; i < paramCount; i++) sb.Write (", p{0}", i); if (isCtor) sb.Write (", &call_super"); sb.Write (", 0x{0:X}", token_ref); sb.WriteLine (");"); if (isCtor) { sb.WriteLine ("if (call_super && rv) {"); sb.Write ("struct objc_super super = { rv, [").Write (method.DeclaringType.SuperType.ExportedName).WriteLine (" class] };"); sb.Write ("rv = ((id (*)(objc_super*, SEL"); if (method.Parameters != null) { for (int i = 0; i < method.Parameters.Length; i++) sb.Append (", ").Append (ToObjCParameterType (method.Parameters [i], method.DescriptiveMethodName, exceptions, method.Method)); } if (method.IsVariadic) sb.Append (", ..."); sb.Write (")) objc_msgSendSuper) (&super, @selector ("); sb.Write (method.Selector); sb.Write (")"); var split = method.Selector.Split (':'); for (int i = 0; i < split.Length - 1; i++) { sb.Append (", "); sb.AppendFormat ("p{0}", i); } sb.WriteLine (");"); sb.WriteLine ("}"); sb.WriteLine ("return rv;"); } sb.WriteLine ("}"); } else { sb.WriteLine (body); } } TypeDefinition GetDelegateProxyType (ObjCMethod obj_method) { // A mirror of this method is also implemented in BlockLiteral:GetDelegateProxyType // If this method is changed, that method will probably have to be updated too (tests!!!) MethodDefinition method = obj_method.Method; MethodDefinition first = method; MethodDefinition last = null; while (method != last) { last = method; var delegateProxyType = GetDelegateProxyAttribute (method); if (delegateProxyType?.DelegateType != null) return delegateProxyType.DelegateType; method = GetBaseMethodInTypeHierarchy (method); } // Might be the implementation of an interface method, so find the corresponding // MethodDefinition for the interface, and check for DelegateProxy attributes there as well. var map = PrepareMethodMapping (first.DeclaringType); if (map != null && map.TryGetValue (first, out var list)) { if (list.Count != 1) throw Shared.GetMT4127 (first, list); var delegateProxyType = GetDelegateProxyAttribute (list [0]); if (delegateProxyType?.DelegateType != null) return delegateProxyType.DelegateType; } // Might be an implementation of an optional protocol member. var allProtocols = obj_method.DeclaringType.AllProtocols; if (allProtocols != null) { string selector = null; foreach (var proto in allProtocols) { // We store the DelegateProxy type in the ProtocolMemberAttribute, so check those. if (selector == null) selector = obj_method.Selector ?? string.Empty; if (selector != null) { var attrib = GetProtocolMemberAttribute (proto.Type, selector, obj_method, method); if (attrib?.ReturnTypeDelegateProxy != null) return attrib.ReturnTypeDelegateProxy.Resolve (); } } } return null; } MethodDefinition GetBlockWrapperCreator (ObjCMethod obj_method, int parameter) { // A mirror of this method is also implemented in Runtime:GetBlockWrapperCreator // If this method is changed, that method will probably have to be updated too (tests!!!) MethodDefinition method = obj_method.Method; MethodDefinition first = method; MethodDefinition last = null; while (method != last) { last = method; var createMethod = GetBlockProxyAttributeMethod (method, parameter) ; if (createMethod != null) return createMethod; method = GetBaseMethodInTypeHierarchy (method); } // Might be the implementation of an interface method, so find the corresponding // MethodDefinition for the interface, and check for BlockProxy attributes there as well. var map = PrepareMethodMapping (first.DeclaringType); if (map != null && map.TryGetValue (first, out var list)) { if (list.Count != 1) throw Shared.GetMT4127 (first, list); var createMethod = GetBlockProxyAttributeMethod (list [0], parameter); if (createMethod != null) return createMethod; } // Might be an implementation of an optional protocol member. var allProtocols = obj_method.DeclaringType.AllProtocols; if (allProtocols != null) { string selector = null; foreach (var proto in allProtocols) { // We store the BlockProxy type in the ProtocolMemberAttribute, so check those. // We may run into binding assemblies built with earlier versions of the generator, // which means we can't rely on finding the BlockProxy attribute in the ProtocolMemberAttribute. if (selector == null) selector = obj_method.Selector ?? string.Empty; if (selector != null) { var attrib = GetProtocolMemberAttribute (proto.Type, selector, obj_method, method); if (attrib?.ParameterBlockProxy?.Length > parameter && attrib.ParameterBlockProxy [parameter] != null) return attrib.ParameterBlockProxy [parameter].Resolve ().Methods.First ((v) => v.Name == "Create"); } if (proto.Methods != null) { foreach (var pMethod in proto.Methods) { if (!pMethod.IsOptional) continue; if (pMethod.Name != method.Name) continue; if (!TypeMatch (pMethod.ReturnType, method.ReturnType)) continue; if (ParametersMatch (method.Parameters, pMethod.Parameters)) continue; MethodDefinition extensionMethod = pMethod.Method; if (extensionMethod == null) { MapProtocolMember (obj_method.Method, out extensionMethod); if (extensionMethod == null) return null; } var createMethod = GetBlockProxyAttributeMethod (extensionMethod, parameter + 1); if (createMethod != null) return createMethod; } } } } return null; } MethodDefinition GetBlockProxyAttributeMethod (MethodDefinition method, int parameter) { var param = method.Parameters [parameter]; var attrib = GetBlockProxyAttribute (param); if (attrib == null) return null; var createMethod = attrib.Type.Methods.FirstOrDefault ((v) => v.Name == "Create"); if (createMethod == null) { // This may happen if users add their own BlockProxy attributes and don't know which types to pass. // One common variation is that the IDE will add the BlockProxy attribute found in base methods when the user overrides those methods, // which unfortunately doesn't compile (because the type passed to the BlockProxy attribute is internal), and then // the user just modifies the attribute to something that compiles. ErrorHelper.Show (ErrorHelper.CreateWarning (App, 4175, method, $"{(string.IsNullOrEmpty (param.Name) ? $"Parameter #{param.Index + 1}" : $"The parameter '{param.Name}'")} in the method '{GetTypeFullName (method.DeclaringType)}.{GetDescriptiveMethodName (method)}' has an invalid BlockProxy attribute (the type passed to the attribute does not have a 'Create' method).")); // Returning null will make the caller look for the attribute in the base implementation. } return createMethod; } public bool MapProtocolMember (MethodDefinition method, out MethodDefinition extensionMethod) { // Given 'method', finds out if it's the implementation of an optional protocol method, // and if so, return the corresponding IProtocol_Extensions method. extensionMethod = null; if (!method.HasCustomAttributes) return false; var t = method.DeclaringType; if (!t.HasInterfaces) return false; // special processing to find [BlockProxy] attributes in _Extensions types // ref: https://bugzilla.xamarin.com/show_bug.cgi?id=23540 string selector = null; foreach (var r in t.Interfaces) { var i = r.InterfaceType.Resolve (); if (i == null || !HasAttribute (i, Namespaces.Foundation, "ProtocolAttribute")) continue; if (selector == null) { // delay and don't compute each time var ea = CreateExportAttribute (method); selector = ea?.Selector; } string name = null; bool match = false; ICustomAttribute protocolMemberAttribute = null; foreach (var ca in GetCustomAttributes (i, Foundation, StringConstants.ProtocolMemberAttribute)) { foreach (var p in ca.Properties) { switch (p.Name) { case "Selector": match = (p.Argument.Value as string == selector); break; case "Name": name = p.Argument.Value as string; break; } } if (match) { protocolMemberAttribute = ca; break; } } if (!match || name == null) continue; // _Extensions time... var td = i.Module.GetType (i.Namespace, i.Name.Substring (1) + "_Extensions"); if (td != null && td.HasMethods) { foreach (var m in td.Methods) { if (!m.HasParameters || (m.Name != name) || !m.IsOptimizableCode (LinkContext)) continue; bool proxy = false; match = method.Parameters.Count == m.Parameters.Count - 1; if (match) { for (int n = 1; n < m.Parameters.Count; n++) { var p = m.Parameters [n]; var pt = p.ParameterType; match &= method.Parameters [n - 1].ParameterType.Is (pt.Namespace, pt.Name); proxy |= p.HasCustomAttribute (Namespaces.ObjCRuntime, "BlockProxyAttribute"); } } if (match && proxy) { ProtocolMemberMethodMap [protocolMemberAttribute] = m; extensionMethod = m; return true; } } } } return false; } string GetManagedToNSNumberFunc (TypeReference managedType, TypeReference inputType, TypeReference outputType, string descriptiveMethodName) { var typeName = managedType.FullName; switch (typeName) { case "System.SByte": return "xamarin_sbyte_to_nsnumber"; case "System.Byte": return "xamarin_byte_to_nsnumber"; case "System.Int16": return "xamarin_short_to_nsnumber"; case "System.UInt16": return "xamarin_ushort_to_nsnumber"; case "System.Int32": return "xamarin_int_to_nsnumber"; case "System.UInt32": return "xamarin_uint_to_nsnumber"; case "System.Int64": return "xamarin_long_to_nsnumber"; case "System.UInt64": return "xamarin_ulong_to_nsnumber"; case "System.nint": return "xamarin_nint_to_nsnumber"; case "System.nuint": return "xamarin_nuint_to_nsnumber"; case "System.Single": return "xamarin_float_to_nsnumber"; case "System.Double": return "xamarin_double_to_nsnumber"; case "System.nfloat": return "xamarin_nfloat_to_nsnumber"; case "System.Boolean": return "xamarin_bool_to_nsnumber"; default: if (IsEnum (managedType)) return GetManagedToNSNumberFunc (GetEnumUnderlyingType (managedType), inputType, outputType, descriptiveMethodName); throw ErrorHelper.CreateError (99, $"Internal error: can't convert from '{inputType.FullName}' to '{outputType.FullName}' in {descriptiveMethodName}. Please file a bug report with a test case (https://github.com/xamarin/xamarin-macios/issues/new)."); } } string GetNSNumberToManagedFunc (TypeReference managedType, TypeReference inputType, TypeReference outputType, string descriptiveMethodName, out string nativeType) { var typeName = managedType.FullName; switch (typeName) { case "System.SByte": nativeType = "int8_t"; return "xamarin_nsnumber_to_sbyte"; case "System.Byte": nativeType = "uint8_t"; return "xamarin_nsnumber_to_byte"; case "System.Int16": nativeType = "int16_t"; return "xamarin_nsnumber_to_short"; case "System.UInt16": nativeType = "uint16_t"; return "xamarin_nsnumber_to_ushort"; case "System.Int32": nativeType = "int32_t"; return "xamarin_nsnumber_to_int"; case "System.UInt32": nativeType = "uint32_t"; return "xamarin_nsnumber_to_uint"; case "System.Int64": nativeType = "int64_t"; return "xamarin_nsnumber_to_long"; case "System.UInt64": nativeType = "uint64_t"; return "xamarin_nsnumber_to_ulong"; case "System.nint": nativeType = "NSInteger"; return "xamarin_nsnumber_to_nint"; case "System.nuint": nativeType = "NSUInteger"; return "xamarin_nsnumber_to_nuint"; case "System.Single": nativeType = "float"; return "xamarin_nsnumber_to_float"; case "System.Double": nativeType = "double"; return "xamarin_nsnumber_to_double"; case "System.nfloat": nativeType = "CGFloat"; return "xamarin_nsnumber_to_nfloat"; case "System.Boolean": nativeType = "BOOL"; return "xamarin_nsnumber_to_bool"; default: if (IsEnum (managedType)) return GetNSNumberToManagedFunc (GetEnumUnderlyingType (managedType), inputType, outputType, descriptiveMethodName, out nativeType); throw ErrorHelper.CreateError (99, $"Internal error: can't convert from '{inputType.FullName}' to '{outputType.FullName}' in {descriptiveMethodName}. Please file a bug report with a test case (https://github.com/xamarin/xamarin-macios/issues/new)."); } } string GetNSValueToManagedFunc (TypeReference managedType, TypeReference inputType, TypeReference outputType, string descriptiveMethodName, out string nativeType) { var underlyingTypeName = managedType.FullName; #if MMP // Remove 'MonoMac.' namespace prefix to make switch smaller if (!Registrar.IsDualBuild && underlyingTypeName.StartsWith ("MonoMac.", StringComparison.Ordinal)) underlyingTypeName = underlyingTypeName.Substring ("MonoMac.".Length); #endif switch (underlyingTypeName) { case "Foundation.NSRange": nativeType = "NSRange"; return "xamarin_nsvalue_to_nsrange"; case "CoreGraphics.CGAffineTransform": nativeType = "CGAffineTransform"; return "xamarin_nsvalue_to_cgaffinetransform"; case "CoreGraphics.CGPoint": nativeType = "CGPoint"; return "xamarin_nsvalue_to_cgpoint"; case "CoreGraphics.CGRect": nativeType = "CGRect"; return "xamarin_nsvalue_to_cgrect"; case "CoreGraphics.CGSize": nativeType = "CGSize"; return "xamarin_nsvalue_to_cgsize"; case "CoreGraphics.CGVector": nativeType = "CGVector"; return "xamarin_nsvalue_to_cgvector"; case "CoreAnimation.CATransform3D": nativeType = "CATransform3D"; return "xamarin_nsvalue_to_catransform3d"; case "CoreLocation.CLLocationCoordinate2D": nativeType = "CLLocationCoordinate2D"; return "xamarin_nsvalue_to_cllocationcoordinate2d"; case "CoreMedia.CMTime": nativeType = "CMTime"; return "xamarin_nsvalue_to_cmtime"; case "CoreMedia.CMTimeMapping": nativeType = "CMTimeMapping"; return "xamarin_nsvalue_to_cmtimemapping"; case "CoreMedia.CMTimeRange": nativeType = "CMTimeRange"; return "xamarin_nsvalue_to_cmtimerange"; case "MapKit.MKCoordinateSpan": nativeType = "MKCoordinateSpan"; return "xamarin_nsvalue_to_mkcoordinatespan"; case "SceneKit.SCNMatrix4": nativeType = "SCNMatrix4"; return "xamarin_nsvalue_to_scnmatrix4"; case "SceneKit.SCNVector3": nativeType = "SCNVector3"; return "xamarin_nsvalue_to_scnvector3"; case "SceneKit.SCNVector4": nativeType = "SCNVector4"; return "xamarin_nsvalue_to_scnvector4"; case "UIKit.UIEdgeInsets": nativeType = "UIEdgeInsets"; return "xamarin_nsvalue_to_uiedgeinsets"; case "UIKit.UIOffset": nativeType = "UIOffset"; return "xamarin_nsvalue_to_uioffset"; case "UIKit.NSDirectionalEdgeInsets": nativeType = "NSDirectionalEdgeInsets"; return "xamarin_nsvalue_to_nsdirectionaledgeinsets"; default: throw ErrorHelper.CreateError (99, $"Internal error: can't convert from '{inputType.FullName}' to '{outputType.FullName}' in {descriptiveMethodName}. Please file a bug report with a test case (https://github.com/xamarin/xamarin-macios/issues/new)."); } } string GetManagedToNSValueFunc (TypeReference managedType, TypeReference inputType, TypeReference outputType, string descriptiveMethodName) { var underlyingTypeName = managedType.FullName; #if MMP // Remove 'MonoMac.' namespace prefix to make switch smaller if (!Registrar.IsDualBuild && underlyingTypeName.StartsWith ("MonoMac.", StringComparison.Ordinal)) underlyingTypeName = underlyingTypeName.Substring ("MonoMac.".Length); #endif switch (underlyingTypeName) { case "Foundation.NSRange": return "xamarin_nsrange_to_nsvalue"; case "CoreGraphics.CGAffineTransform": return "xamarin_cgaffinetransform_to_nsvalue"; case "CoreGraphics.CGPoint": return "xamarin_cgpoint_to_nsvalue"; case "CoreGraphics.CGRect": return "xamarin_cgrect_to_nsvalue"; case "CoreGraphics.CGSize": return "xamarin_cgsize_to_nsvalue"; case "CoreGraphics.CGVector": return "xamarin_cgvector_to_nsvalue"; case "CoreAnimation.CATransform3D": return "xamarin_catransform3d_to_nsvalue"; case "CoreLocation.CLLocationCoordinate2D": return "xamarin_cllocationcoordinate2d_to_nsvalue"; case "CoreMedia.CMTime": return "xamarin_cmtime_to_nsvalue"; case "CoreMedia.CMTimeMapping": return "xamarin_cmtimemapping_to_nsvalue"; case "CoreMedia.CMTimeRange": return "xamarin_cmtimerange_to_nsvalue"; case "MapKit.MKCoordinateSpan": return "xamarin_mkcoordinatespan_to_nsvalue"; case "SceneKit.SCNMatrix4": return "xamarin_scnmatrix4_to_nsvalue"; case "SceneKit.SCNVector3": return "xamarin_scnvector3_to_nsvalue"; case "SceneKit.SCNVector4": return "xamarin_scnvector4_to_nsvalue"; case "UIKit.UIEdgeInsets": return "xamarin_uiedgeinsets_to_nsvalue"; case "UIKit.UIOffset": return "xamarin_uioffset_to_nsvalue"; case "UIKit.NSDirectionalEdgeInsets": return "xamarin_nsdirectionaledgeinsets_to_nsvalue"; default: throw ErrorHelper.CreateError (99, $"Internal error: can't convert from '{inputType.FullName}' to '{outputType.FullName}' in {descriptiveMethodName}. Please file a bug report with a test case (https://github.com/xamarin/xamarin-macios/issues/new)."); } } string GetNSStringToSmartEnumFunc (TypeReference managedType, TypeReference inputType, TypeReference outputType, string descriptiveMethodName, string parameterClass, out string nativeType) { nativeType = "NSString *"; return $"xamarin_get_nsstring_to_smart_enum_func ({parameterClass}, managed_method, &exception_gchandle)"; } string GetSmartEnumToNSStringFunc (TypeReference managedType, TypeReference inputType, TypeReference outputType, string descriptiveMethodName, string parameterClass) { return $"xamarin_get_smart_enum_to_nsstring_func ({parameterClass}, managed_method, &exception_gchandle)"; } void GenerateConversionToManaged (TypeReference inputType, TypeReference outputType, AutoIndentStringBuilder sb, string descriptiveMethodName, ref List<Exception> exceptions, ObjCMethod method, string inputName, string outputName, string managedClassExpression) { // This is a mirror of the native method xamarin_generate_conversion_to_managed (for the dynamic registrar). // These methods must be kept in sync. var managedType = outputType; var nativeType = inputType; var isManagedNullable = IsNullable (managedType); var underlyingManagedType = managedType; var underlyingNativeType = nativeType; var isManagedArray = IsArray (managedType); var isNativeArray = IsArray (nativeType); if (isManagedArray != isNativeArray) throw ErrorHelper.CreateError (99, $"Internal error: can't convert from '{inputType.FullName}' to '{outputType.FullName}' in {descriptiveMethodName}. Please file a bug report with a test case (https://github.com/xamarin/xamarin-macios/issues/new)."); var classVariableName = $"{inputName}_conv_class"; body_setup.AppendLine ($"MonoClass *{classVariableName} = NULL;"); if (isManagedArray) { if (isManagedNullable) throw ErrorHelper.CreateError (99, $"Internal error: can't convert from '{inputType.FullName}' to '{outputType.FullName}' in {descriptiveMethodName}. Please file a bug report with a test case (https://github.com/xamarin/xamarin-macios/issues/new)."); underlyingNativeType = GetElementType (nativeType); underlyingManagedType = GetElementType (managedType); sb.AppendLine ($"{classVariableName} = mono_class_get_element_class ({managedClassExpression});"); } else if (isManagedNullable) { underlyingManagedType = GetNullableType (managedType); sb.AppendLine ($"{classVariableName} = xamarin_get_nullable_type ({managedClassExpression}, &exception_gchandle);"); sb.AppendLine ($"if (exception_gchandle != 0) goto exception_handling;"); } else { sb.AppendLine ($"{classVariableName} = {managedClassExpression};"); } CheckNamespace (underlyingNativeType.Resolve (), exceptions); CheckNamespace (underlyingManagedType.Resolve (), exceptions); if (isManagedNullable || isManagedArray) sb.AppendLine ($"if ({inputName}) {{"); string func; string nativeTypeName; string token = "0"; if (underlyingNativeType.Is (Foundation, "NSNumber")) { func = GetNSNumberToManagedFunc (underlyingManagedType, inputType, outputType, descriptiveMethodName, out nativeTypeName); } else if (underlyingNativeType.Is (Foundation, "NSValue")) { func = GetNSValueToManagedFunc (underlyingManagedType, inputType, outputType, descriptiveMethodName, out nativeTypeName); } else if (underlyingNativeType.Is (Foundation, "NSString")) { func = GetNSStringToSmartEnumFunc (underlyingManagedType, inputType, outputType, descriptiveMethodName, managedClassExpression, out nativeTypeName); MethodDefinition getConstantMethod, getValueMethod; if (!IsSmartEnum (underlyingManagedType, out getConstantMethod, out getValueMethod)) { // method linked away!? this should already be verified ErrorHelper.Show (ErrorHelper.CreateWarning (99, $"Internal error: the smart enum {underlyingManagedType.FullName} doesn't seem to be a smart enum after all. Please file a bug report with a test case (https://github.com/xamarin/xamarin-macios/issues/new).")); token = "INVALID_TOKEN_REF"; } else { token = $"0x{CreateTokenReference (getValueMethod, TokenType.Method):X} /* {getValueMethod.FullName} */"; } } else { throw ErrorHelper.CreateError (99, $"Internal error: can't convert from '{inputType.FullName}' to '{outputType.FullName}' in {descriptiveMethodName}. Please file a bug report with a test case (https://github.com/xamarin/xamarin-macios/issues/new)."); } if (isManagedArray) { sb.AppendLine ($"xamarin_id_to_managed_func {inputName}_conv_func = (xamarin_id_to_managed_func) {func};"); sb.AppendLine ("if (exception_gchandle != 0) goto exception_handling;"); sb.AppendLine ($"{outputName} = xamarin_convert_nsarray_to_managed_with_func ({inputName}, {classVariableName}, {inputName}_conv_func, GINT_TO_POINTER ({token}), &exception_gchandle);"); sb.AppendLine ("if (exception_gchandle != 0) goto exception_handling;"); } else { var tmpName = $"{inputName}_conv_tmp"; body_setup.AppendLine ($"{nativeTypeName} {tmpName};"); if (isManagedNullable) { var tmpName2 = $"{inputName}_conv_ptr"; body_setup.AppendLine ($"void *{tmpName2} = NULL;"); sb.AppendLine ($"{tmpName2} = {func} ({inputName}, &{tmpName}, {classVariableName}, GINT_TO_POINTER ({token}), &exception_gchandle);"); sb.AppendLine ("if (exception_gchandle != 0) goto exception_handling;"); sb.AppendLine ($"{outputName} = mono_value_box (mono_domain_get (), {classVariableName}, {tmpName2});"); } else { sb.AppendLine ($"{outputName} = {func} ({inputName}, &{tmpName}, {classVariableName}, GINT_TO_POINTER ({token}), &exception_gchandle);"); sb.AppendLine ("if (exception_gchandle != 0) goto exception_handling;"); } } if (isManagedNullable || isManagedArray) { sb.AppendLine ($"}} else {{"); sb.AppendLine ($"{outputName} = NULL;"); sb.AppendLine ($"}}"); } } void GenerateConversionToNative (TypeReference inputType, TypeReference outputType, AutoIndentStringBuilder sb, string descriptiveMethodName, ref List<Exception> exceptions, ObjCMethod method, string inputName, string outputName, string managedClassExpression) { // This is a mirror of the native method xamarin_generate_conversion_to_native (for the dynamic registrar). // These methods must be kept in sync. var managedType = inputType; var nativeType = outputType; var isManagedNullable = IsNullable (managedType); var underlyingManagedType = managedType; var underlyingNativeType = nativeType; var isManagedArray = IsArray (managedType); var isNativeArray = IsArray (nativeType); if (isManagedArray != isNativeArray) throw ErrorHelper.CreateError (99, $"Internal error: can't convert from '{inputType.FullName}' to '{outputType.FullName}' in {descriptiveMethodName}. Please file a bug report with a test case (https://github.com/xamarin/xamarin-macios/issues/new)."); var classVariableName = $"{inputName}_conv_class"; body_setup.AppendLine ($"MonoClass *{classVariableName} = NULL;"); if (isManagedArray) { if (isManagedNullable) throw ErrorHelper.CreateError (99, $"Internal error: can't convert from '{inputType.FullName}' to '{outputType.FullName}' in {descriptiveMethodName}. Please file a bug report with a test case (https://github.com/xamarin/xamarin-macios/issues/new)."); underlyingNativeType = GetElementType (nativeType); underlyingManagedType = GetElementType (managedType); sb.AppendLine ($"{classVariableName} = mono_class_get_element_class ({managedClassExpression});"); } else if (isManagedNullable) { underlyingManagedType = GetNullableType (managedType); sb.AppendLine ($"{classVariableName} = xamarin_get_nullable_type ({managedClassExpression}, &exception_gchandle);"); sb.AppendLine ($"if (exception_gchandle != 0) goto exception_handling;"); } else { sb.AppendLine ($"{classVariableName} = {managedClassExpression};"); } CheckNamespace (underlyingNativeType.Resolve (), exceptions); CheckNamespace (underlyingManagedType.Resolve (), exceptions); if (isManagedNullable || isManagedArray) sb.AppendLine ($"if ({inputName}) {{"); string func; string token = "0"; if (underlyingNativeType.Is (Foundation, "NSNumber")) { func = GetManagedToNSNumberFunc (underlyingManagedType, inputType, outputType, descriptiveMethodName); } else if (underlyingNativeType.Is (Foundation, "NSValue")) { func = GetManagedToNSValueFunc (underlyingManagedType, inputType, outputType, descriptiveMethodName); } else if (underlyingNativeType.Is (Foundation, "NSString")) { func = GetSmartEnumToNSStringFunc (underlyingManagedType, inputType, outputType, descriptiveMethodName, classVariableName); MethodDefinition getConstantMethod, getValueMethod; if (!IsSmartEnum (underlyingManagedType, out getConstantMethod, out getValueMethod)) { // method linked away!? this should already be verified ErrorHelper.Show (ErrorHelper.CreateWarning (99, $"Internal error: the smart enum {underlyingManagedType.FullName} doesn't seem to be a smart enum after all. Please file a bug report with a test case (https://github.com/xamarin/xamarin-macios/issues/new).")); token = "INVALID_TOKEN_REF"; } else { token = $"0x{CreateTokenReference (getConstantMethod, TokenType.Method):X} /* {getConstantMethod.FullName} */"; } } else { throw ErrorHelper.CreateError (99, $"Internal error: can't convert from '{inputType.FullName}' to '{outputType.FullName}' in {descriptiveMethodName}. Please file a bug report with a test case (https://github.com/xamarin/xamarin-macios/issues/new)."); } if (isManagedArray) { sb.AppendLine ($"{outputName} = xamarin_convert_managed_to_nsarray_with_func ((MonoArray *) {inputName}, (xamarin_managed_to_id_func) {func}, GINT_TO_POINTER ({token}), &exception_gchandle);"); } else { sb.AppendLine ($"{outputName} = {func} ({inputName}, GINT_TO_POINTER ({token}), &exception_gchandle);"); } sb.AppendLine ($"if (exception_gchandle != 0) goto exception_handling;"); if (isManagedNullable || isManagedArray) { sb.AppendLine ($"}} else {{"); sb.AppendLine ($"{outputName} = NULL;"); sb.AppendLine ($"}}"); } } class Body { public string Code; public string Signature; public string Name; public int Count; public override int GetHashCode () { return Code.GetHashCode () ^ Signature.GetHashCode (); } public override bool Equals (object obj) { var other = obj as Body; if (other == null) return false; return Code == other.Code && Signature == other.Signature; } } uint CreateFullTokenReference (MemberReference member) { var rv = (full_token_reference_count++ << 1) + 1; switch (member.MetadataToken.TokenType) { case TokenType.TypeDef: case TokenType.Method: break; // OK default: throw ErrorHelper.CreateError (99, $"Internal error: unsupported tokentype ({member.MetadataToken.TokenType}) for {member.FullName}. Please file a bug report with a test case (https://github.com/xamarin/xamarin-macios/issues/new)."); } full_token_references.AppendFormat ("\t\t{{ /* #{3} = 0x{4:X} */ \"{0}\", 0x{1:X}, 0x{2:X} }},\n", GetAssemblyName (member.Module.Assembly), member.Module.MetadataToken.ToUInt32 (), member.MetadataToken.ToUInt32 (), full_token_reference_count, rv); return rv; } Dictionary<Tuple<MemberReference, TokenType>, uint> token_ref_cache = new Dictionary<Tuple<MemberReference, TokenType>, uint> (); uint CreateTokenReference (MemberReference member, TokenType implied_type) { var key = new Tuple<MemberReference, TokenType> (member, implied_type); uint rv; if (!token_ref_cache.TryGetValue (key, out rv)) token_ref_cache [key] = rv = CreateTokenReference2 (member, implied_type); return rv; } uint CreateTokenReference2 (MemberReference member, TokenType implied_type) { var token = member.MetadataToken; /* We can't create small token references if we're in partial mode, because we may have multiple arrays of registered assemblies, and no way of saying which one we refer to with the assembly index */ if (IsSingleAssembly) return CreateFullTokenReference (member); /* If the implied token type doesn't match, we need a full token */ if (implied_type != token.TokenType) return CreateFullTokenReference (member); /* For small token references the only valid module is the first one */ if (member.Module.MetadataToken.ToInt32 () != 1) return CreateFullTokenReference (member); /* The assembly must be a registered one, and only within the first 128 assemblies */ var assembly_name = GetAssemblyName (member.Module.Assembly); var index = registered_assemblies.IndexOf (assembly_name); if (index < 0 || index > 127) return CreateFullTokenReference (member); return (token.RID << 8) + ((uint) index << 1); } public void GeneratePInvokeWrappersStart (AutoIndentStringBuilder hdr, AutoIndentStringBuilder decls, AutoIndentStringBuilder mthds, AutoIndentStringBuilder ifaces) { header = hdr; declarations = decls; methods = mthds; interfaces = ifaces; } public void GeneratePInvokeWrappersEnd () { header = null; declarations = null; methods = null; interfaces = null; namespaces.Clear (); structures.Clear (); FlushTrace (); } static string GetParamName (MethodDefinition method, int i) { var p = method.Parameters [i]; if (p.Name != null) return p.Name; return "__p__" + i.ToString (); } string TryGeneratePInvokeWrapper (PInvokeWrapperGenerator state, MethodDefinition method) { var signatures = state.signatures; var exceptions = state.exceptions; var signature = state.signature; var names = state.names; var sb = state.sb; var pinfo = method.PInvokeInfo; var is_stret = pinfo.EntryPoint.EndsWith ("_stret", StringComparison.Ordinal); var isVoid = method.ReturnType.FullName == "System.Void"; var descriptiveMethodName = method.DeclaringType.FullName + "." + method.Name; signature.Clear (); string native_return_type; int first_parameter = 0; if (is_stret) { native_return_type = ToObjCParameterType (method.Parameters [0].ParameterType.GetElementType (), descriptiveMethodName, exceptions, method); first_parameter = 1; } else { native_return_type = ToObjCParameterType (method.ReturnType, descriptiveMethodName, exceptions, method); } signature.Append (native_return_type); signature.Append (" "); signature.Append (pinfo.EntryPoint); signature.Append (" ("); for (int i = 0; i < method.Parameters.Count; i++) { if (i > 0) signature.Append (", "); signature.Append (ToObjCParameterType (method.Parameters[i].ParameterType, descriptiveMethodName, exceptions, method)); } signature.Append (")"); string wrapperName; if (!signatures.TryGetValue (signature.ToString (), out wrapperName)) { var name = "xamarin_pinvoke_wrapper_" + method.Name; var counter = 0; while (names.Contains (name)) { name = "xamarin_pinvoke_wrapper_" + method.Name + (++counter).ToString (); } names.Add (name); signatures [signature.ToString ()] = wrapperName = name; sb.WriteLine ("// EntryPoint: {0}", pinfo.EntryPoint); sb.WriteLine ("// Managed method: {0}.{1}", method.DeclaringType.FullName, method.Name); sb.WriteLine ("// Signature: {0}", signature.ToString ()); sb.Write ("typedef "); sb.Write (native_return_type); sb.Write ("(*func_"); sb.Write (name); sb.Write (") ("); for (int i = first_parameter; i < method.Parameters.Count; i++) { if (i > first_parameter) sb.Write (", "); sb.Write (ToObjCParameterType (method.Parameters[i].ParameterType, descriptiveMethodName, exceptions, method)); sb.Write (" "); sb.Write (GetParamName (method, i)); } sb.WriteLine (");"); sb.WriteLine (native_return_type); sb.Write (name); sb.Write (" ("); for (int i = first_parameter; i < method.Parameters.Count; i++) { if (i > first_parameter) sb.Write (", "); sb.Write (ToObjCParameterType (method.Parameters[i].ParameterType, descriptiveMethodName, exceptions, method)); sb.Write (" "); sb.Write (GetParamName (method, i)); } sb.WriteLine (")"); sb.WriteLine ("{"); if (is_stret) { sb.StringBuilder.AppendLine ("#if defined (__arm64__)"); sb.WriteLine ("xamarin_process_managed_exception ((MonoObject *) mono_exception_from_name_msg (mono_get_corlib (), \"System\", \"EntryPointNotFoundException\", \"{0}\"));", pinfo.EntryPoint); sb.StringBuilder.AppendLine ("#else"); } sb.WriteLine ("@try {"); if (!isVoid || is_stret) sb.Write ("return "); sb.Write ("((func_{0}) {1}) (", name, pinfo.EntryPoint); for (int i = first_parameter; i < method.Parameters.Count; i++) { if (i > first_parameter) sb.Write (", "); sb.Write (GetParamName (method, i)); } sb.WriteLine (");"); sb.WriteLine ("} @catch (NSException *exc) {"); sb.WriteLine ("xamarin_process_nsexception (exc);"); sb.WriteLine ("}"); if (is_stret) sb.StringBuilder.AppendLine ("#endif /* defined (__arm64__) */"); sb.WriteLine ("}"); sb.WriteLine (); } else { // Console.WriteLine ("Signature already processed: {0} for {1}.{2}", signature.ToString (), method.DeclaringType.FullName, method.Name); } return wrapperName; } public void GeneratePInvokeWrapper (PInvokeWrapperGenerator state, MethodDefinition method) { string wrapperName; try { wrapperName = TryGeneratePInvokeWrapper (state, method); } catch (Exception e) { throw ErrorHelper.CreateError (App, 4169, e, method, $"Failed to generate a P/Invoke wrapper for {GetDescriptiveMethodName (method)}: {e.Message}"); } // find the module reference to __Internal ModuleReference mr = null; foreach (var mref in method.Module.ModuleReferences) { if (mref.Name == "__Internal") { mr = mref; break; } } if (mr == null) method.Module.ModuleReferences.Add (mr = new ModuleReference ("__Internal")); var pinfo = method.PInvokeInfo; pinfo.Module = mr; pinfo.EntryPoint = wrapperName; } public void GenerateSingleAssembly (IEnumerable<AssemblyDefinition> assemblies, string header_path, string source_path, string assembly) { single_assembly = assembly; Generate (assemblies, header_path, source_path); } public void Generate (IEnumerable<AssemblyDefinition> assemblies, string header_path, string source_path) { if (Target?.CachedLink == true) throw ErrorHelper.CreateError (99, "Internal error: the static registrar should not execute unless the linker also executed (or was disabled). A potential workaround is to pass '-f' as an additional " + Driver.NAME + " argument to force a full build. Please file a bug report with a test case (https://github.com/xamarin/xamarin-macios/issues/new)."); this.input_assemblies = assemblies; foreach (var assembly in assemblies) { Driver.Log (3, "Generating static registrar for {0}", assembly.Name); RegisterAssembly (assembly); } Generate (header_path, source_path); } void Generate (string header_path, string source_path) { var sb = new AutoIndentStringBuilder (); header = new AutoIndentStringBuilder (); declarations = new AutoIndentStringBuilder (); methods = new AutoIndentStringBuilder (); interfaces = new AutoIndentStringBuilder (); header.WriteLine ("#pragma clang diagnostic ignored \"-Wdeprecated-declarations\""); header.WriteLine ("#pragma clang diagnostic ignored \"-Wtypedef-redefinition\""); // temporary hack until we can stop including glib.h header.WriteLine ("#pragma clang diagnostic ignored \"-Wobjc-designated-initializers\""); header.WriteLine ("#pragma clang diagnostic ignored \"-Wunguarded-availability-new\""); if (App.EnableDebug) { header.WriteLine ("#define DEBUG 1"); methods.WriteLine ("#define DEBUG 1"); } header.WriteLine ("#include <stdarg.h>"); if (SupportsModernObjectiveC) { methods.WriteLine ("#include <xamarin/xamarin.h>"); } else { header.WriteLine ("#include <xamarin/xamarin.h>"); } header.WriteLine ("#include <objc/objc.h>"); header.WriteLine ("#include <objc/runtime.h>"); header.WriteLine ("#include <objc/message.h>"); methods.WriteLine ($"#include \"{Path.GetFileName (header_path)}\""); methods.StringBuilder.AppendLine ("extern \"C\" {"); if (App.Embeddinator) methods.WriteLine ("void xamarin_embeddinator_initialize ();"); Specialize (sb); methods.WriteLine (); methods.AppendLine (); methods.AppendLine (sb); methods.StringBuilder.AppendLine ("} /* extern \"C\" */"); FlushTrace (); Driver.WriteIfDifferent (source_path, methods.ToString (), true); header.AppendLine (); header.AppendLine (declarations); header.AppendLine (interfaces); Driver.WriteIfDifferent (header_path, header.ToString (), true); header.Dispose (); header = null; declarations.Dispose (); declarations = null; methods.Dispose (); methods = null; interfaces.Dispose (); interfaces = null; sb.Dispose (); } protected override bool SkipRegisterAssembly (AssemblyDefinition assembly) { if (assembly.HasCustomAttributes) { foreach (var ca in assembly.CustomAttributes) { var t = ca.AttributeType.Resolve (); while (t != null) { if (t.Is ("ObjCRuntime", "DelayedRegistrationAttribute")) return true; t = t.BaseType?.Resolve (); } } } return base.SkipRegisterAssembly (assembly); } } // Replicate a few attribute types here, with TypeDefinition instead of Type class ProtocolAttribute : Attribute { public TypeDefinition WrapperType { get; set; } public string Name { get; set; } public bool IsInformal { get; set; } public Version FormalSinceVersion { get; set; } } class BlockProxyAttribute : Attribute { public TypeDefinition Type { get; set; } } class DelegateProxyAttribute : Attribute { public TypeDefinition DelegateType { get; set; } } class BindAsAttribute : Attribute { public BindAsAttribute (TypeReference type) { this.Type = type; } public TypeReference Type { get; set; } public TypeReference OriginalType { get; set; } } public sealed class ProtocolMemberAttribute : Attribute { public ProtocolMemberAttribute () {} public bool IsRequired { get; set; } public bool IsProperty { get; set; } public bool IsStatic { get; set; } public string Name { get; set; } public string Selector { get; set; } public TypeReference ReturnType { get; set; } public TypeReference ReturnTypeDelegateProxy { get; set; } public TypeReference[] ParameterType { get; set; } public bool[] ParameterByRef { get; set; } public TypeReference [] ParameterBlockProxy { get; set; } public bool IsVariadic { get; set; } public TypeReference PropertyType { get; set; } public string GetterSelector { get; set; } public string SetterSelector { get; set; } public ArgumentSemantic ArgumentSemantic { get; set; } public MethodDefinition Method { get; set; } // not in the API, used to find the original method in the static registrar } class CategoryAttribute : Attribute { public CategoryAttribute (TypeDefinition type) { Type = type; } public TypeDefinition Type { get; set; } public string Name { get; set; } } class RegisterAttribute : Attribute { public RegisterAttribute () {} public RegisterAttribute (string name) { this.Name = name; } public RegisterAttribute (string name, bool isWrapper) { this.Name = name; this.IsWrapper = isWrapper; } public string Name { get; set; } public bool IsWrapper { get; set; } public bool SkipRegistration { get; set; } } class AdoptsAttribute : Attribute { public string ProtocolType { get; set; } } [Flags] internal enum MTTypeFlags : uint { None = 0, CustomType = 1, UserType = 2, } }
36.749105
376
0.679265
[ "BSD-3-Clause" ]
1975781737/xamarin-macios
tools/common/StaticRegistrar.cs
184,701
C#
using System; using System.Collections.Generic; using System.Linq; using JSIL; using JSIL.Meta; namespace SharpJS.Dom { /// <summary> /// The base Element class for a managed C# interface to DOM. /// </summary> public class Element { #region Private Fields #endregion Private Fields #region Public Constructors public Element(string type) : this(Verbatim.Expression("document.createElement(type)")) { } #endregion Public Constructors #region Internal Constructors public Element(object elementHandle) { if (elementHandle == null) throw new ArgumentNullException(nameof(elementHandle)); ElementHandle = elementHandle; _selfReference = this; StyleCollection = new StyleCollection(this); } #endregion Internal Constructors #region Protected Constructors protected Element() { } #endregion Protected Constructors #region Public Indexers public string this[string index] { get { return GetAttributeValue(index) ?? string.Empty; } set { SetAttributeValue(index, value); } } #endregion Public Indexers #region Events public event EventHandler Change { add { AddNativeHandler("change", e => { _change(this, new EventArgs()); }); _change += value; } remove { RemoveNativehandler("change"); _change -= value; } } public event EventHandler Click { add { AddNativeHandler("click", e => { _click(this, new EventArgs()); }); _click += value; } remove { RemoveNativehandler("click"); _click -= value; } } public event EventHandler KeyDown { add { AddNativeHandler("keydown", e => { _keyDown(this, new EventArgs()); }); _keyDown += value; } remove { RemoveNativehandler("keydown"); _keyDown -= value; } } public event EventHandler MouseOut { add { AddNativeHandler("mouseout", e => { _mouseOut(this, new EventArgs()); }); _mouseOut += value; } remove { RemoveNativehandler("mouseout"); _mouseOut -= value; } } public event EventHandler MouseOver { add { AddNativeHandler("mouseover", e => { _mouseOver(this, new EventArgs()); }); _mouseOver += value; } remove { RemoveNativehandler("mouseover"); _mouseOver -= value; } } private event EventHandler _change; private event EventHandler _click; private event EventHandler _keyDown; private event EventHandler _mouseOut; private event EventHandler _mouseOver; #endregion Events #region Generic event handling private readonly Dictionary<object, Proxy> _handlers = new Dictionary<object, Proxy>(); protected void AddNativeHandler(string eventName, Action<object> handler) { if (!_handlers.ContainsKey(eventName) || _handlers[eventName] == null) { var proxy = new Proxy { Handler = handler }; AddEventListener(eventName, proxy.Handler); _handlers[eventName] = proxy; } else { _handlers[eventName].Counter++; } } protected void RemoveNativehandler(string eventName) { var handler = _handlers[eventName]; handler.Counter--; if (handler.Counter <= 0) { RemoveEventListener(eventName, handler.Handler); _handlers[eventName] = null; } } [JSReplacement("$this.ElementHandle.addEventListener($name, $handler)")] private void AddEventListener(string name, Action<object> handler) { } [JSReplacement("$this.ElementHandle.removeEventListener($name, $handler)")] private void RemoveEventListener(string name, Action<object> handler) { } private class Proxy { #region Public Fields public int Counter; public Action<object> Handler; #endregion Public Fields } #endregion Generic event handling #region Properties public string Class { get { return this["className"]; } set { this["className"] = value; } } public bool Enabled { get { return (bool)Verbatim.Expression("!this.ElementHandle.disabled"); } set { Verbatim.Expression("this.ElementHandle.disabled = !value"); } } public double Height { get { return (double)Verbatim.Expression("this.ElementHandle.height"); } set { Verbatim.Expression("this.ElementHandle.height = value"); } } public string Id { get { return (string)Verbatim.Expression("this.ElementHandle.id"); } set { Verbatim.Expression("this.ElementHandle.id = value"); } } public string TagName { get { return (string)Verbatim.Expression("this.ElementHandle.tagName"); } set { Verbatim.Expression("this.ElementHandle.tagName = value"); } } public double Width { get { return (double)Verbatim.Expression("this.ElementHandle.width"); } set { Verbatim.Expression("this.ElementHandle.width = value"); } } #endregion Properties #region Protected Fields protected object ElementHandle; protected Element _selfReference; #endregion Protected Fields #region Public Properties public Element[] Children { get { return ((object[])Verbatim.Expression("Array.prototype.slice.call(this.ElementHandle.children)")).Select( elementObject => GetElement(elementObject)).ToArray(); } } public object DomObjectHandle { get { return ElementHandle; } } public Element FirstChild { get { return GetElement(Verbatim.Expression("this.ElementHandle.firstChild")); } } public string InnerHtml { get { return (string)Verbatim.Expression("this.ElementHandle.innerHTML"); } set { Verbatim.Expression("this.ElementHandle.innerHTML = value"); } } public Element NextSibling { get { return GetElement(Verbatim.Expression("this.ElementHandle.nextSibling")); } } [JSReplacement("$this.ElementHandle.nodeType")] public int NodeType { get; private set; } public string OuterHtml { get { return (string)Verbatim.Expression("this.ElementHandle.outerHTML"); } set { Verbatim.Expression("this.ElementHandle.outerHTML = value"); } } public Element Parent { get { return GetElement(Verbatim.Expression("this.ElementHandle.parent")); } } public StyleCollection StyleCollection { get; private set; } public string Style { get { return GetAttributeValue("style"); } set { SetAttributeValue("style", value); } } public string TextContent { get { return (string)Verbatim.Expression("this.ElementHandle.textContent"); } set { Verbatim.Expression("this.ElementHandle.textContent = value"); } } #endregion Public Properties #region Public Methods [JSReplacement("$this.ElementHandle.className += \" \" + $className")] public virtual void AddClass(string className) { } [JSReplacement("$this.ElementHandle.appendChild($childElement.ElementHandle)")] public virtual void AppendChild(Element childElement) { } [JSReplacement("$this.ElementHandle.blur()")] public virtual void Blur() { } [JSReplacement("$this.ElementHandle[$attributeName]")] public virtual string GetAttributeValue(string attributeName) { throw new RequiresJSILRuntimeException(); } [JSReplacement("$this.ElementHandle.removeChild($child.ElementHandle)")] public virtual void RemoveChild(Element child) { } public virtual void RemoveClass(string className) { var classNames = GetAttributeValue("className") .Split(' ', '\t') .Where(s => s != className); var names = string.Empty; foreach (var name in classNames) { names += " " + name; } SetAttributeValue("className", names); } [JSReplacement("$this.ElementHandle.style[$styleName]=$value")] public void SetStyle(string styleName, string value) { } #endregion Public Methods #region Internal Methods internal static Element GetById(string id) { var element = GetElement(Verbatim.Expression("document.getElementById(id)")); if (element == null) { throw new ArgumentOutOfRangeException("id"); } return element; } internal static Element GetElement(object handle) { if (handle == null) { return null; } var element = Verbatim.Expression("handle._selfReference"); if (element == null || element == Verbatim.Expression("undefined")) { return new Element(handle); } return (Element)element; } internal static T GetElement<T>(object handle) where T : Element, new() { if (handle == null) { return null; } var element = Verbatim.Expression("handle._selfReference"); if (element == null || element == Verbatim.Expression("undefined")) { return (T)Activator.CreateInstance(typeof(T), handle); // equivalent to: new T(handle); } return (T)element; } #endregion Internal Methods #region Protected Methods [JSReplacement("$this.ElementHandle[$attributeName] = $value")] protected virtual void SetAttributeValue(string attributeName, string value) { } #endregion Protected Methods } }
27.387952
118
0.532993
[ "Apache-2.0" ]
Terricide/SharpJS
ExaPhaser/Libraries/SharpJS.Dom/Element.cs
11,368
C#
using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using MediatR; using Moq; using Strive.Core.Services; using Strive.Core.Services.WhiteboardService; using Strive.Core.Services.WhiteboardService.Actions; using Strive.Core.Services.WhiteboardService.CanvasData; using Strive.Core.Services.WhiteboardService.PushActions; using Strive.Core.Services.WhiteboardService.Requests; using Strive.Core.Services.WhiteboardService.Responses; using Strive.Core.Services.WhiteboardService.UseCases; using Strive.Tests.Utils; using Xunit; namespace Strive.Core.Tests.Services.WhiteboardService.UseCases { public class PushActionUseCaseTests : ActionRequestTestBase { private readonly Mock<IMediator> _mediator = new(); private readonly Mock<ICanvasActionUtils> _actionUtils = new(); private readonly AddCanvasPushAction _addAction = new(new CanvasLine()); private PushActionUseCase Create() { return new(_mediator.Object, _actionUtils.Object); } [Fact] public async Task Handle_EmptyUpdate_ThrowException() { // arrange var useCase = Create(); var capturedRequest = _mediator.CaptureRequest<UpdateWhiteboardRequest, WhiteboardUpdatedResponse>(); await useCase.Handle( new PushActionRequest(ConferenceId, RoomId, WhiteboardId, ParticipantId, new DeleteCanvasPushAction(new[] {"1", "2"})), CancellationToken.None); // act var error = Assert.Throws<IdErrorException>(() => Execute(capturedRequest, CreateWhiteboard(WhiteboardCanvas.Empty, ImmutableDictionary<string, ParticipantWhiteboardState>.Empty, 1))); // assert Assert.Equal(WhiteboardError.WhiteboardActionHadNoEffect.Code, error.Error.Code); } [Fact] public async Task Handle_ValidAction_AddToUndo() { // arrange var useCase = Create(); var capturedRequest = _mediator.CaptureRequest<UpdateWhiteboardRequest, WhiteboardUpdatedResponse>(); await useCase.Handle(new PushActionRequest(ConferenceId, RoomId, WhiteboardId, ParticipantId, _addAction), CancellationToken.None); // act var updatedWhiteboard = Execute(capturedRequest, CreateWhiteboard(WhiteboardCanvas.Empty, ImmutableDictionary<string, ParticipantWhiteboardState>.Empty, 56)); // assert var undoAction = Assert.Single(updatedWhiteboard.ParticipantStates[ParticipantId].UndoList); Assert.IsType<DeleteCanvasAction>(undoAction.Action); Assert.Equal(56, undoAction.Version); } [Fact] public async Task Handle_ValidAction_UpdateWhiteboard() { // arrange var useCase = Create(); var capturedRequest = _mediator.CaptureRequest<UpdateWhiteboardRequest, WhiteboardUpdatedResponse>(); await useCase.Handle(new PushActionRequest(ConferenceId, RoomId, WhiteboardId, ParticipantId, _addAction), CancellationToken.None); // act var updatedWhiteboard = Execute(capturedRequest, CreateWhiteboard(WhiteboardCanvas.Empty, ImmutableDictionary<string, ParticipantWhiteboardState>.Empty, 56)); // assert Assert.Single(updatedWhiteboard.Canvas.Objects); } [Fact] public async Task Handle_ValidAction_ClearRedo() { // arrange var useCase = Create(); var capturedRequest = _mediator.CaptureRequest<UpdateWhiteboardRequest, WhiteboardUpdatedResponse>(); await useCase.Handle(new PushActionRequest(ConferenceId, RoomId, WhiteboardId, ParticipantId, _addAction), CancellationToken.None); // act var updatedWhiteboard = Execute(capturedRequest, CreateWhiteboard(WhiteboardCanvas.Empty, new Dictionary<string, ParticipantWhiteboardState> { { ParticipantId, new ParticipantWhiteboardState(ImmutableList<VersionedAction>.Empty, new[] { new VersionedAction(new AddCanvasAction(new[] { new CanvasObjectRef(new VersionedCanvasObject(_addAction.Object, "123", 0), null), }, ParticipantId), 45), }.ToImmutableList()) }, }, 56)); // assert Assert.Empty(updatedWhiteboard.ParticipantStates[ParticipantId].RedoList); } } }
39.666667
119
0.635171
[ "Apache-2.0" ]
Anapher/PaderConference
src/Services/ConferenceManagement/Strive.Core.Tests/Services/WhiteboardService/UseCases/PushActionUseCaseTests.cs
4,881
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Windows; using System.Windows.Media; using MahApps.Metro.ValueBoxes; namespace MahApps.Metro.Controls.Dialogs { /// <summary> /// An internal control that represents a message dialog. Please use MetroWindow.ShowMessage instead! /// </summary> public partial class ProgressDialog : BaseMetroDialog { /// <summary>Identifies the <see cref="Message"/> dependency property.</summary> public static readonly DependencyProperty MessageProperty = DependencyProperty.Register(nameof(Message), typeof(string), typeof(ProgressDialog), new PropertyMetadata(default(string))); public string Message { get { return (string)this.GetValue(MessageProperty); } set { this.SetValue(MessageProperty, value); } } /// <summary>Identifies the <see cref="IsCancelable"/> dependency property.</summary> public static readonly DependencyProperty IsCancelableProperty = DependencyProperty.Register(nameof(IsCancelable), typeof(bool), typeof(ProgressDialog), new PropertyMetadata(BooleanBoxes.FalseBox, (s, e) => { ((ProgressDialog)s).PART_NegativeButton.Visibility = (bool)e.NewValue ? Visibility.Visible : Visibility.Hidden; })); public bool IsCancelable { get { return (bool)this.GetValue(IsCancelableProperty); } set { this.SetValue(IsCancelableProperty, BooleanBoxes.Box(value)); } } /// <summary>Identifies the <see cref="NegativeButtonText"/> dependency property.</summary> public static readonly DependencyProperty NegativeButtonTextProperty = DependencyProperty.Register(nameof(NegativeButtonText), typeof(string), typeof(ProgressDialog), new PropertyMetadata("Cancel")); public string NegativeButtonText { get { return (string)this.GetValue(NegativeButtonTextProperty); } set { this.SetValue(NegativeButtonTextProperty, value); } } /// <summary>Identifies the <see cref="ProgressBarForeground"/> dependency property.</summary> public static readonly DependencyProperty ProgressBarForegroundProperty = DependencyProperty.Register(nameof(ProgressBarForeground), typeof(Brush), typeof(ProgressDialog), new FrameworkPropertyMetadata(default(Brush), FrameworkPropertyMetadataOptions.AffectsRender)); public Brush ProgressBarForeground { get { return (Brush)this.GetValue(ProgressBarForegroundProperty); } set { this.SetValue(ProgressBarForegroundProperty, value); } } internal ProgressDialog() : this(null) { } internal ProgressDialog(MetroWindow parentWindow) : this(parentWindow, null) { } internal ProgressDialog(MetroWindow parentWindow, MetroDialogSettings settings) : base(parentWindow, settings) { this.InitializeComponent(); } protected override void OnLoaded() { this.NegativeButtonText = this.DialogSettings.NegativeButtonText; this.SetResourceReference(ProgressBarForegroundProperty, this.DialogSettings.ColorScheme == MetroDialogColorScheme.Theme ? "MahApps.Brushes.Accent" : "MahApps.Brushes.ThemeForeground"); } internal CancellationToken CancellationToken => this.DialogSettings.CancellationToken; internal double Minimum { get { return this.PART_ProgressBar.Minimum; } set { this.PART_ProgressBar.Minimum = value; } } internal double Maximum { get { return this.PART_ProgressBar.Maximum; } set { this.PART_ProgressBar.Maximum = value; } } internal double ProgressValue { get { return this.PART_ProgressBar.Value; } set { this.PART_ProgressBar.IsIndeterminate = false; this.PART_ProgressBar.Value = value; this.PART_ProgressBar.ApplyTemplate(); } } internal void SetIndeterminate() { this.PART_ProgressBar.IsIndeterminate = true; } } }
41.857143
333
0.6719
[ "MIT" ]
CacoCode-zz/CodePlus.MahApps.Metro
src/MahApps.Metro/Controls/Dialogs/ProgressDialog.xaml.cs
4,397
C#
using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using TeamProjectManager.Common.Infrastructure; namespace TeamProjectManager.Modules.Security { [DataContract(Namespace = "http://schemas.teamprojectmanager.codeplex.com/permissionchange/2013/04")] public class PermissionChangePersistenceData { #region Properties [DataMember] public PermissionScope Scope { get; set; } [DataMember] public string Name { get; set; } [DataMember] public PermissionChangeAction Action { get; set; } #endregion #region Constructors public PermissionChangePersistenceData() { } public PermissionChangePersistenceData(PermissionChange permissionChange) : this(permissionChange.Permission.Scope, permissionChange.Permission.PermissionConstant, permissionChange.Action) { } public PermissionChangePersistenceData(PermissionScope scope, string name, PermissionChangeAction action) { this.Scope = scope; this.Name = name; this.Action = action; } #endregion #region Static Load & Save public static IList<PermissionChangePersistenceData> Load(string fileName) { return SerializationProvider.Read<PermissionChangePersistenceData[]>(fileName); } public static void Save(string fileName, IList<PermissionChangePersistenceData> data) { SerializationProvider.Write<PermissionChangePersistenceData[]>(data.ToArray(), fileName); } #endregion } }
29.758621
127
0.648899
[ "MIT" ]
BobSilent/TfsTeamProjectManager
TeamProjectManager.Modules.Security/PermissionChangePersistenceData.cs
1,728
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 application-autoscaling-2016-02-06.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.ApplicationAutoScaling.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.ApplicationAutoScaling.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for ScalableTargetAction Object /// </summary> public class ScalableTargetActionUnmarshaller : IUnmarshaller<ScalableTargetAction, XmlUnmarshallerContext>, IUnmarshaller<ScalableTargetAction, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> ScalableTargetAction IUnmarshaller<ScalableTargetAction, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public ScalableTargetAction Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; ScalableTargetAction unmarshalledObject = new ScalableTargetAction(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("MaxCapacity", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.MaxCapacity = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("MinCapacity", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.MinCapacity = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static ScalableTargetActionUnmarshaller _instance = new ScalableTargetActionUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static ScalableTargetActionUnmarshaller Instance { get { return _instance; } } } }
36.5
174
0.623707
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/ApplicationAutoScaling/Generated/Model/Internal/MarshallTransformations/ScalableTargetActionUnmarshaller.cs
3,577
C#
using Newtonsoft.Json; namespace UWPReactiveUI.Services.Models { public class HipsterParameters { [JsonProperty("paras")] public int Paragraphs { get; set; } [JsonProperty("type")] public string Type { get; set; } } }
18.928571
43
0.615094
[ "MIT" ]
Lordinaire/UWP_ReactiveUI_Sample
UWPReactiveUI.Services.Models/HipsterParameters.cs
267
C#
/* * DotAAS Part 2 | HTTP/REST | Asset Administration Shell Repository * * An exemplary interface combination for the use case of an Asset Administration Shell Repository * * OpenAPI spec version: Final-Draft * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; using Newtonsoft.Json; namespace AAS.API.Models { /// <summary> /// /// </summary> [DataContract] public partial class PolicyEnforcementPoint : IEquatable<PolicyEnforcementPoint> { /// <summary> /// Gets or Sets ExternalPolicyEnforcementPoint /// </summary> [Required] [DataMember(Name="externalPolicyEnforcementPoint")] public bool? ExternalPolicyEnforcementPoint { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class PolicyEnforcementPoint {\n"); sb.Append(" ExternalPolicyEnforcementPoint: ").Append(ExternalPolicyEnforcementPoint).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj.GetType() == GetType() && Equals((PolicyEnforcementPoint)obj); } /// <summary> /// Returns true if PolicyEnforcementPoint instances are equal /// </summary> /// <param name="other">Instance of PolicyEnforcementPoint to be compared</param> /// <returns>Boolean</returns> public bool Equals(PolicyEnforcementPoint other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return ( ExternalPolicyEnforcementPoint == other.ExternalPolicyEnforcementPoint || ExternalPolicyEnforcementPoint != null && ExternalPolicyEnforcementPoint.Equals(other.ExternalPolicyEnforcementPoint) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; // Suitable nullity checks etc, of course :) if (ExternalPolicyEnforcementPoint != null) hashCode = hashCode * 59 + ExternalPolicyEnforcementPoint.GetHashCode(); return hashCode; } } #region Operators #pragma warning disable 1591 public static bool operator ==(PolicyEnforcementPoint left, PolicyEnforcementPoint right) { return Equals(left, right); } public static bool operator !=(PolicyEnforcementPoint left, PolicyEnforcementPoint right) { return !Equals(left, right); } #pragma warning restore 1591 #endregion Operators } }
32.991803
112
0.599752
[ "MIT" ]
JMayrbaeurl/opendigitaltwins-aas-azureservices
src/aas-api-models/Models/PolicyEnforcementPoint.cs
4,025
C#
using System; using System.Collections.Generic; using System.Linq; using Elasticsearch.Net; using FluentAssertions; using NUnit.Framework; namespace Nest.Tests.Unit.ObjectInitializer.Mapping { [TestFixture] public class GetMappingRequestTests : BaseJsonTests { private readonly IElasticsearchResponse _status; public GetMappingRequestTests() { var request = new GetMappingRequest("my-index", "my-type"); var response = this._client.GetMapping(request); this._status = response.ConnectionStatus; } [Test] public void Url() { this._status.RequestUrl.Should().EndWith("/my-index/_mapping/my-type"); this._status.RequestMethod.Should().Be("GET"); } } }
22.225806
74
0.74746
[ "Apache-2.0" ]
Bloomerang/elasticsearch-net
src/Tests/Nest.Tests.Unit/ObjectInitializer/Mapping/GetMappingRequestTests.cs
691
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http.Formatting; using System.Web.Http; namespace StarDotOne { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services config.Formatters.Add(new BsonMediaTypeFormatter()); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
25.333333
64
0.600877
[ "Apache-2.0" ]
jongalloway/StarDotOne
StarDotOne/App_Start/WebApiConfig.cs
686
C#
using Discord; using Discord.Commands; using Discord.WebSocket; using System; using System.Threading.Tasks; using System.Timers; using System.Linq; using System.Collections; using System.Text; using System.Reflection; namespace ArbitesLog { class Program { public static void Main() => new Program().MainAsync().GetAwaiter().GetResult(); private readonly DiscordSocketClient _client; private readonly CommandService _commands; private readonly Config config; private Timer cleanupTimer; private CommandHandler commandHandler; public async Task MainAsync() { commandHandler = new CommandHandler(_client, _commands, config); await commandHandler.InitCommands(); InitLogger(); InitCleaner(); await _client.LoginAsync(TokenType.Bot, config.Token); await _client.StartAsync(); // Block this task until the program is closed. await Task.Delay(-1); } private Program() { Console.WriteLine($"ArbitesLog v{Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion}"); config = Startup.ConfigStart(); //configure SocketClient _client = new DiscordSocketClient(new DiscordSocketConfig { LogLevel = LogSeverity.Info, }); //Create and configure Command Service _commands = new CommandService(new CommandServiceConfig { LogLevel = LogSeverity.Info, CaseSensitiveCommands = false, }); _client.Log += Log; _commands.Log += Log; } private void InitLogger() { _client.MessageDeleted += HandleMessageDeleteAsync; _client.MessageUpdated += _client_MessageUpdated; _client.UserJoined += _client_UserJoined; _client.UserLeft += _client_UserLeft; _client.UserBanned += _client_UserBanned; _client.UserUnbanned += _client_UserUnbanned; _client.GuildMemberUpdated += _client_GuildMemberUpdated; _client.MessagesBulkDeleted += _client_MessagesBulkDeleted; } private async Task _client_MessagesBulkDeleted(System.Collections.Generic.IReadOnlyCollection<Cacheable<IMessage, ulong>> messages, ISocketMessageChannel channel) { ulong guildID = ((SocketTextChannel)channel).Guild.Id; StringBuilder fieldValue = new StringBuilder(); foreach (Cacheable<IMessage, ulong> cached in messages) { fieldValue.Append(cached.Id + ", "); } var origField = new EmbedFieldBuilder() .WithName(messages.Count + " Messages Deleted") .WithValue(fieldValue.ToString()); var footer = new EmbedFooterBuilder() .WithIconUrl(_client.CurrentUser.GetAvatarUrl()) .WithText("ArbitiesLog"); var embed = new EmbedBuilder() .AddField(origField) .WithFooter(footer) .WithColor(Color.Red) .Build(); GuildData guildData = await GuildManager.GetGuildData(guildID); await((SocketTextChannel)_client.GetChannel(guildData.LogChannel)).SendMessageAsync(embed: embed); } private async Task _client_GuildMemberUpdated(SocketUser arg1, SocketUser arg2) { ulong guildID = ((SocketGuildUser)arg1).Guild.Id; LogMessage msg = new LogMessage(LogSeverity.Info, "EventLogger", $"User {arg1.Id} in Guild {guildID} Updated!"); Log(msg); SocketGuildUser userStart = (SocketGuildUser)arg1; SocketGuildUser userEnd = (SocketGuildUser)arg2; string actionTaken = "Should Not Be Seen"; StringBuilder fieldValue = new StringBuilder(); if (userStart.Roles.Count != userEnd.Roles.Count) { if (userStart.Roles.Count < userEnd.Roles.Count) { //Role Added IEnumerable differentRoles = userEnd.Roles.Except(userStart.Roles); actionTaken = "Role(s) Added"; foreach (SocketRole role in differentRoles) { fieldValue.Append(role.Name + "\n"); } } else { //Role Removed IEnumerable differentRoles = userStart.Roles.Except(userEnd.Roles); actionTaken = "Role(s) Removed"; foreach (SocketRole role in differentRoles) { fieldValue.Append(role.Name + "\n"); } } } else if (userStart.Nickname != userEnd.Nickname) { actionTaken = "Nickname Changed"; fieldValue.Append(userStart.Nickname + " --> " + userEnd.Nickname); } var origField = new EmbedFieldBuilder() .WithName(actionTaken) .WithValue(fieldValue.ToString()); var footer = new EmbedFooterBuilder() .WithIconUrl(_client.CurrentUser.GetAvatarUrl()) .WithText("ArbitiesLog"); var embed = new EmbedBuilder() .WithImageUrl(userStart.GetAvatarUrl(ImageFormat.Auto, 512)) .AddField(origField) .WithFooter(footer) .WithColor(Color.Gold) .Build(); GuildData guildData = await GuildManager.GetGuildData(guildID); await ((SocketTextChannel)_client.GetChannel(guildData.LogChannel)).SendMessageAsync(embed: embed); } private async Task _client_UserUnbanned(SocketUser user, SocketGuild guild) { ulong guildID = guild.Id; LogMessage msg = new LogMessage(LogSeverity.Info, "EventLogger", $"User {user.Id} in Guild {guildID} Unbanned!"); Log(msg); var origField = new EmbedFieldBuilder() .WithName("User Unbanned") .WithValue(user.Username); var footer = new EmbedFooterBuilder() .WithIconUrl(_client.CurrentUser.GetAvatarUrl()) .WithText("ArbitiesLog"); var embed = new EmbedBuilder() .WithImageUrl(user.GetAvatarUrl(ImageFormat.Auto, 512)) .AddField(origField) .WithFooter(footer) .WithColor(Color.Green) .Build(); GuildData guildData = await GuildManager.GetGuildData(guildID); await((SocketTextChannel)_client.GetChannel(guildData.LogChannel)).SendMessageAsync(embed: embed); } private async Task _client_UserBanned(SocketUser user, SocketGuild guild) { ulong guildID = guild.Id; LogMessage msg = new LogMessage(LogSeverity.Info, "EventLogger", $"User {user.Id} in Guild {guildID} Banned!"); Log(msg); var origField = new EmbedFieldBuilder() .WithName("User Banned") .WithValue(user.Username); var footer = new EmbedFooterBuilder() .WithIconUrl(_client.CurrentUser.GetAvatarUrl()) .WithText("ArbitiesLog"); var embed = new EmbedBuilder() .WithImageUrl(user.GetAvatarUrl(ImageFormat.Auto, 512)) .AddField(origField) .WithFooter(footer) .WithColor(Color.Red) .Build(); GuildData guildData = await GuildManager.GetGuildData(guildID); await((SocketTextChannel)_client.GetChannel(guildData.LogChannel)).SendMessageAsync(embed: embed); } private async Task _client_UserLeft(SocketGuildUser user) { ulong guildID = user.Guild.Id; LogMessage msg = new LogMessage(LogSeverity.Info, "EventLogger", $"User {user.Id} Left Guild {guildID}!"); Log(msg); var origField = new EmbedFieldBuilder() .WithName("User Left") .WithValue(user.Username); var footer = new EmbedFooterBuilder() .WithIconUrl(_client.CurrentUser.GetAvatarUrl()) .WithText("ArbitiesLog"); var embed = new EmbedBuilder() .WithImageUrl(user.GetAvatarUrl(ImageFormat.Auto, 512)) .AddField(origField) .WithFooter(footer) .WithColor(Color.Red) .Build(); GuildData guildData = await GuildManager.GetGuildData(guildID); await ((SocketTextChannel)_client.GetChannel(guildData.LogChannel)).SendMessageAsync(embed: embed); } private async Task _client_UserJoined(SocketGuildUser user) { ulong guildID = user.Guild.Id; LogMessage msg = new LogMessage(LogSeverity.Info, "EventLogger", $"User {user.Id} Joined Guild {guildID}!"); Log(msg); var creationTime = user.CreatedAt.UtcDateTime; TimeSpan timeExisted = DateTimeOffset.UtcNow - creationTime; var origField = new EmbedFieldBuilder() .WithName("New User Joined") .WithValue(user.Username); var timeField = new EmbedFieldBuilder() .WithName("Account Age") .WithValue(timeExisted.ToString()); var footer = new EmbedFooterBuilder() .WithIconUrl(_client.CurrentUser.GetAvatarUrl()) .WithText("ArbitiesLog"); var embed = new EmbedBuilder() .WithImageUrl(user.GetAvatarUrl(ImageFormat.Auto, 512)) .AddField(origField) .AddField(timeField) .WithFooter(footer) .WithColor(Color.Green) .Build(); GuildData guildData = await GuildManager.GetGuildData(guildID); await((SocketTextChannel)_client.GetChannel(guildData.LogChannel)).SendMessageAsync(embed: embed); } private async Task _client_MessageUpdated(Cacheable<IMessage, ulong> origMsg, SocketMessage message, ISocketMessageChannel channel) { ulong guildID = ((SocketTextChannel)channel).Guild.Id; LoggedMessage logMsg = await MessageLogger.GetLog(origMsg.Id, guildID); var origField = new EmbedFieldBuilder() .WithName("Original Text of " + logMsg.MessageID.ToString()) .WithValue(logMsg.MessageContent[^1]) .WithIsInline(true); var newField = new EmbedFieldBuilder() .WithName("New Text Of " + logMsg.MessageID.ToString()) .WithValue(message.Content) .WithIsInline(true); var footer = new EmbedFooterBuilder() .WithIconUrl("https://cdn.discordapp.com/avatars/729417603625517198/254497db41bcb2143e7b69274a857bda.png") .WithText("ArbitiesLog"); var embed = new EmbedBuilder(); var em = embed.AddField(origField) .AddField(newField) .WithAuthor(_client.GetGuild(guildID).GetUser(logMsg.AuthorID)) .WithColor(Color.Gold) .WithFooter(footer) .WithTimestamp(logMsg.Timestamp) .Build(); logMsg.MessageContent.Add(message.Content); MessageLogger.UpdateLog(origMsg.Id, guildID, logMsg); GuildData guildData = await GuildManager.GetGuildData(guildID); await ((SocketTextChannel)_client.GetChannel(guildData.LogChannel)).SendMessageAsync(embed: em); } private void InitCleaner() { cleanupTimer = new Timer(GetCleanerOffset()) { AutoReset = false, Enabled = true, }; cleanupTimer.Elapsed += TimerEnded; cleanupTimer.Start(); } private double GetCleanerOffset() { return config.CleanupTime.TimeOfDay.TotalMilliseconds - DateTime.Now.TimeOfDay.TotalMilliseconds; } private async void TimerEnded(object source, ElapsedEventArgs args) { cleanupTimer.Interval = 8.64e+7; cleanupTimer.Start(); await RunCleanup(); } private async Task RunCleanup() { await DataManager.RunCleanup(config.MessageTimeToDie); } private async Task HandleMessageDeleteAsync(Cacheable<IMessage, ulong> message, ISocketMessageChannel channel) { ulong guildID = ((SocketTextChannel)channel).Guild.Id; LoggedMessage logMsg = await MessageLogger.GetLog(message.Id, guildID); var msgField = new EmbedFieldBuilder() .WithName("Message " + logMsg.MessageID.ToString()) .WithValue(logMsg.MessageContent[^1]) .WithIsInline(true); var footer = new EmbedFooterBuilder() .WithIconUrl("https://cdn.discordapp.com/avatars/729417603625517198/254497db41bcb2143e7b69274a857bda.png") .WithText("ArbitiesLog"); var embed = new EmbedBuilder(); var em = embed.AddField(msgField) .WithAuthor(_client.GetGuild(guildID).GetUser(logMsg.AuthorID)) .WithColor(Color.Red) .WithFooter(footer) .WithTimestamp(logMsg.Timestamp) .Build(); GuildData guildData = await GuildManager.GetGuildData(guildID); await ((SocketTextChannel)_client.GetChannel(guildData.LogChannel)).SendMessageAsync(embed: em); } public static Task Log(LogMessage message) { switch (message.Severity) { case LogSeverity.Critical: case LogSeverity.Error: Console.ForegroundColor = ConsoleColor.Red; break; case LogSeverity.Warning: Console.ForegroundColor = ConsoleColor.Yellow; break; case LogSeverity.Info: Console.ForegroundColor = ConsoleColor.White; break; case LogSeverity.Verbose: case LogSeverity.Debug: Console.ForegroundColor = ConsoleColor.DarkGray; break; } Console.WriteLine($"{DateTime.Now,-19} [{message.Severity,8}] {message.Source}: {message.Message} {message.Exception}"); Console.ResetColor(); return Task.CompletedTask; } } }
33.477528
164
0.725877
[ "MIT" ]
primebie1/ArbitesLog
ArbitesLog/Program.cs
11,920
C#
using System; using System.Data; using System.Collections.Generic; using Maticsoft.Common; using WalleProject.Model; namespace WalleProject.BLL { /// <summary> /// t_complainadvice /// </summary> public partial class t_complainadvice { private readonly WalleProject.DAL.t_complainadvice dal=new WalleProject.DAL.t_complainadvice(); public t_complainadvice() {} #region BasicMethod /// <summary> /// 得到最大ID /// </summary> public int GetMaxId() { return dal.GetMaxId(); } /// <summary> /// 是否存在该记录 /// </summary> public bool Exists(int comd_ID) { return dal.Exists(comd_ID); } /// <summary> /// 增加一条数据 /// </summary> public bool Add(WalleProject.Model.t_complainadvice model) { return dal.Add(model); } /// <summary> /// 更新一条数据 /// </summary> public bool Update(WalleProject.Model.t_complainadvice model) { return dal.Update(model); } /// <summary> /// 删除一条数据 /// </summary> public bool Delete(int comd_ID) { return dal.Delete(comd_ID); } /// <summary> /// 删除一条数据 /// </summary> public bool DeleteList(string comd_IDlist ) { return dal.DeleteList(comd_IDlist ); } /// <summary> /// 得到一个对象实体 /// </summary> public WalleProject.Model.t_complainadvice GetModel(int comd_ID) { return dal.GetModel(comd_ID); } /// <summary> /// 得到一个对象实体,从缓存中 /// </summary> public WalleProject.Model.t_complainadvice GetModelByCache(int comd_ID) { string CacheKey = "t_complainadviceModel-" + comd_ID; object objModel = Maticsoft.Common.DataCache.GetCache(CacheKey); if (objModel == null) { try { objModel = dal.GetModel(comd_ID); if (objModel != null) { int ModelCache = Maticsoft.Common.ConfigHelper.GetConfigInt("ModelCache"); Maticsoft.Common.DataCache.SetCache(CacheKey, objModel, DateTime.Now.AddMinutes(ModelCache), TimeSpan.Zero); } } catch{} } return (WalleProject.Model.t_complainadvice)objModel; } /// <summary> /// 获得数据列表 /// </summary> public DataSet GetList(string strWhere) { return dal.GetList(strWhere); } /// <summary> /// 获得数据列表 /// </summary> public List<WalleProject.Model.t_complainadvice> GetModelList(string strWhere) { DataSet ds = dal.GetList(strWhere); return DataTableToList(ds.Tables[0]); } /// <summary> /// 获得数据列表 /// </summary> public List<WalleProject.Model.t_complainadvice> DataTableToList(DataTable dt) { List<WalleProject.Model.t_complainadvice> modelList = new List<WalleProject.Model.t_complainadvice>(); int rowsCount = dt.Rows.Count; if (rowsCount > 0) { WalleProject.Model.t_complainadvice model; for (int n = 0; n < rowsCount; n++) { model = dal.DataRowToModel(dt.Rows[n]); if (model != null) { modelList.Add(model); } } } return modelList; } /// <summary> /// 获得数据列表 /// </summary> public DataSet GetAllList() { return GetList(""); } /// <summary> /// 分页获取数据列表 /// </summary> public int GetRecordCount(string strWhere) { return dal.GetRecordCount(strWhere); } /// <summary> /// 分页获取数据列表 /// </summary> public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex) { return dal.GetListByPage( strWhere, orderby, startIndex, endIndex); } /// <summary> /// 分页获取数据列表 /// </summary> //public DataSet GetList(int PageSize,int PageIndex,string strWhere) //{ //return dal.GetList(PageSize,PageIndex,strWhere); //} #endregion BasicMethod #region ExtensionMethod #endregion ExtensionMethod } }
21.011561
114
0.650894
[ "Apache-2.0" ]
MarkManYUN/WALLE-Project
BLL/t_complainadvice.cs
3,845
C#
using System; using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using AutoMapper; using MediatR; using Microsoft.Extensions.Logging; using Sidekick.Domain.Apis.PoePriceInfo.Models; using Sidekick.Domain.Apis.PoePriceInfo.Queries; using Sidekick.Domain.Settings; using Sidekick.Infrastructure.PoePriceInfo.Models; namespace Sidekick.Infrastructure.PoePriceInfo { public class GetPricePredictionHandler : IQueryHandler<GetPricePredictionQuery, PricePrediction> { private readonly IPoePriceInfoClient client; private readonly ISidekickSettings settings; private readonly IMapper mapper; private readonly ILogger logger; public GetPricePredictionHandler( IPoePriceInfoClient client, ISidekickSettings settings, IMapper mapper, ILogger<GetPricePredictionHandler> logger) { this.client = client; this.settings = settings; this.mapper = mapper; this.logger = logger; } public async Task<PricePrediction> Handle(GetPricePredictionQuery request, CancellationToken cancellationToken) { if (request.Item.Metadata.Rarity != Domain.Game.Items.Models.Rarity.Rare) { return null; } try { var encodedItem = Convert.ToBase64String(Encoding.UTF8.GetBytes(request.Item.Original.Text)); var response = await client.Client.GetAsync("?l=" + settings.LeagueId + "&i=" + encodedItem, cancellationToken); var content = await response.Content.ReadAsStreamAsync(); var result = await JsonSerializer.DeserializeAsync<PriceInfoResult>(content, client.Options); if (result.Min == 0 && result.Max == 0) { return null; } return mapper.Map<PricePrediction>(result); } catch (Exception e) { logger.LogWarning(e, "Error while trying to get price prediction from poeprices.info."); } return null; } } }
33.984615
128
0.628791
[ "MIT" ]
5c0r/Sidekick
src/Sidekick.Infrastructure/PoePriceInfo/GetPricePredictionHandler.cs
2,209
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("Server")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Server")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config.xml", Watch = true)] // 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("2a311a66-c414-4d66-84de-ba7b361e99e7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.736842
91
0.747283
[ "Apache-2.0" ]
pedrodaniel10/DAD
tuple-space/Server/Properties/AssemblyInfo.cs
1,475
C#
using Xunit; using PostmarkDotNet; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Postmark.Tests { public class ClientTemplateTests : ClientBaseFixture, IDisposable { protected override void Setup() { _client = new PostmarkClient(WRITE_TEST_SERVER_TOKEN, BASE_URL); } [Fact] public async void ClientCanCreateTemplate() { var name = Guid.NewGuid().ToString(); var subject = "A subject: " + Guid.NewGuid(); var htmlbody = "<b>Hello, {{name}}</b>"; var textBody = "Hello, {{name}}!"; var newTemplate = await _client.CreateTemplateAsync(name, subject, htmlbody, textBody); Assert.Equal(name, newTemplate.Name); } [Fact] public async void ClientCanEditTemplate() { var name = Guid.NewGuid().ToString(); var subject = "A subject: " + Guid.NewGuid(); var htmlbody = "<b>Hello, {{name}}</b>"; var textBody = "Hello, {{name}}!"; var newTemplate = await _client.CreateTemplateAsync(name, subject, htmlbody, textBody); var existingTemplate = await _client.GetTemplateAsync(newTemplate.TemplateId); await _client.EditTemplateAsync(existingTemplate.TemplateId, name + name, subject + subject, htmlbody + htmlbody, textBody + textBody); var updatedTemplate = await _client.GetTemplateAsync(existingTemplate.TemplateId); Assert.Equal(existingTemplate.Name + existingTemplate.Name, updatedTemplate.Name); Assert.Equal(existingTemplate.HtmlBody + existingTemplate.HtmlBody, updatedTemplate.HtmlBody); Assert.Equal(existingTemplate.Subject + existingTemplate.Subject, updatedTemplate.Subject); Assert.Equal(existingTemplate.TextBody + existingTemplate.TextBody, updatedTemplate.TextBody); } [Fact] public async void ClientCanDeleteTemplate() { var name = Guid.NewGuid().ToString(); var subject = "A subject: " + Guid.NewGuid(); var htmlbody = "<b>Hello, {{name}}</b>"; var textBody = "Hello, {{name}}!"; var newTemplate = await _client.CreateTemplateAsync(name, subject, htmlbody, textBody); await _client.DeleteTemplateAsync(newTemplate.TemplateId); var deletedTemplate = await _client.GetTemplateAsync(newTemplate.TemplateId); Assert.False(deletedTemplate.Active); } [Fact] public async void ClientCanGetTemplate() { var name = Guid.NewGuid().ToString(); var subject = "A subject: " + Guid.NewGuid(); var htmlbody = "<b>Hello, {{name}}</b>"; var textBody = "Hello, {{name}}!"; var newTemplate = await _client.CreateTemplateAsync(name, subject, htmlbody, textBody); var result = await _client.GetTemplateAsync(newTemplate.TemplateId); Assert.Equal(name, result.Name); Assert.Equal(htmlbody, result.HtmlBody); Assert.Equal(textBody, result.TextBody); Assert.Equal(subject, result.Subject); Assert.True(result.Active); Assert.True(result.AssociatedServerId > 0); Assert.Equal(newTemplate.TemplateId, result.TemplateId); } [Fact] public async void ClientCanGetListTemplates() { for (var i = 0; i < 10; i++) { await _client.CreateTemplateAsync("test " + i, "test subject" + i, "body"); } var result = await _client.GetTemplatesAsync(); Assert.Equal(10, result.TotalCount); var toDelete = result.Templates.First().TemplateId; await _client.DeleteTemplateAsync(toDelete); result = await _client.GetTemplatesAsync(); Assert.Equal(9, result.TotalCount); Assert.False(result.Templates.Any(k => k.TemplateId == toDelete)); var offsetResults = await _client.GetTemplatesAsync(5); Assert.True(result.Templates.Skip(5).Select(k => k.TemplateId).SequenceEqual(offsetResults.Templates.Select(k => k.TemplateId))); } [Fact] public async void ClientCanValidateTemplate() { var result = await _client.ValidateTemplateAsync("{{name}}", "<html><body>{{content}}{{company.address}}{{#each products}}{{/each}}{{^competitors}}There are no substitutes.{{/competitors}}</body></html>", "{{content}}", new { name = "Johnny", content = "hello, world!" }); Assert.True(result.AllContentIsValid); Assert.True(result.HtmlBody.ContentIsValid); Assert.True(result.TextBody.ContentIsValid); Assert.True(result.Subject.ContentIsValid); var inferredAddress = result.SuggestedTemplateModel.company.address; var products = result.SuggestedTemplateModel.products; Assert.NotNull(inferredAddress); Assert.Equal(3, products.Length); } [Fact] public async void ClientCanSendWithTemplate() { var template = await _client.CreateTemplateAsync("test template name", "test subject", "test html body"); var sendResult = await _client.SendEmailWithTemplateAsync(template.TemplateId, new { name = "Andrew" }, WRITE_TEST_SENDER_EMAIL_ADDRESS, WRITE_TEST_SENDER_EMAIL_ADDRESS, false); Assert.NotEqual(Guid.Empty, sendResult.MessageID); } [Fact] public async void ClientCanSendTemplateWithStringModel() { var template = await _client.CreateTemplateAsync("test template name", "test subject", "test html body"); var sendResult = await _client.SendEmailWithTemplateAsync(template.TemplateId, "{ \"name\" : \"Andrew\" }", WRITE_TEST_SENDER_EMAIL_ADDRESS, WRITE_TEST_SENDER_EMAIL_ADDRESS, false); Assert.NotEqual(Guid.Empty, sendResult.MessageID); } private Task Cleanup(){ return Task.Run(async () => { try { var tasks = new List<Task>(); var templates = await _client.GetTemplatesAsync(); foreach (var t in templates.Templates) { tasks.Add(_client.DeleteTemplateAsync(t.TemplateId)); } await Task.WhenAll(tasks); } catch { } }); } public void Dispose() { Cleanup().Wait(); } } }
40.993902
284
0.604641
[ "MIT" ]
OperatorOverload/postmark-dotnet
src/Postmark.Tests/ClientTemplateTests.cs
6,725
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; namespace Microsoft.AspNetCore.Components.WebAssembly.Authentication { internal class QueryStringHelper { public static string GetParameter(string queryString, string key) { if (string.IsNullOrEmpty(queryString) || queryString == "?") { return null; } var scanIndex = 0; if (queryString[0] == '?') { scanIndex = 1; } var textLength = queryString.Length; var equalIndex = queryString.IndexOf('='); if (equalIndex == -1) { equalIndex = textLength; } while (scanIndex < textLength) { var ampersandIndex = queryString.IndexOf('&', scanIndex); if (ampersandIndex == -1) { ampersandIndex = textLength; } if (equalIndex < ampersandIndex) { while (scanIndex != equalIndex && char.IsWhiteSpace(queryString[scanIndex])) { ++scanIndex; } var name = queryString[scanIndex..equalIndex]; var value = queryString.Substring(equalIndex + 1, ampersandIndex - equalIndex - 1); var processedName = Uri.UnescapeDataString(name.Replace('+', ' ')); if (string.Equals(processedName, key, StringComparison.OrdinalIgnoreCase)) { return Uri.UnescapeDataString(value.Replace('+', ' ')); } equalIndex = queryString.IndexOf('=', ampersandIndex); if (equalIndex == -1) { equalIndex = textLength; } } else { if (ampersandIndex > scanIndex) { var value = queryString[scanIndex..ampersandIndex]; if (string.Equals(value, key, StringComparison.OrdinalIgnoreCase)) { return string.Empty; } } } scanIndex = ampersandIndex + 1; } return null; } } }
33.636364
111
0.455212
[ "Apache-2.0" ]
1kevgriff/aspnetcore
src/Components/WebAssembly/WebAssembly.Authentication/src/QueryStringHelper.cs
2,592
C#
using System; using System.Collections.Generic; using System.Linq; namespace SourceLink { // https://github.com/ctaggart/SourceLink/blob/v1/SourceLink/SystemExtensions.fs public static class System { public static bool CollectionEquals<T>(this ICollection<T> a, ICollection<T> b) { if (a.Count != b.Count) return false; return a.SequenceEqual(b); } public static string ToHex(this byte[] bytes) { return BitConverter.ToString(bytes).Replace("-", "").ToLowerInvariant(); } } }
24.833333
87
0.607383
[ "MIT" ]
AndreAbrantes/SourceLink
dotnet-sourcelink/System.cs
598
C#
// *********************************************************************** // Assembly : OpenAC.Net.Sat // Author : RFTD // Created : 31-03-2016 // // Last Modified By : RFTD // Last Modified On : 23-10-2021 // *********************************************************************** // <copyright file="SatGeralConfig.cs" company="OpenAC .Net"> // The MIT License (MIT) // Copyright (c) 2016 Projeto OpenAC .Net // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // </copyright> // <summary></summary> // *********************************************************************** using OpenAC.Net.DFe.Core.Common; namespace OpenAC.Net.Sat { /// <summary> /// Classe com as configurações do SAT. /// </summary> public sealed class SatGeralConfig { #region Constructor /// <summary> /// Initializes a new instance of the <see cref="SatGeralConfig"/> class. /// </summary> public SatGeralConfig() { InfCFeVersaoDadosEnt = 0.07M; IdeCNPJ = @"11111111111111"; IdeNumeroCaixa = 1; IdeTpAmb = DFeTipoAmbiente.Homologacao; EmitCNPJ = @"11111111111111"; EmitIE = string.Empty; EmitIM = string.Empty; EmitCRegTrib = RegTrib.Normal; EmitCRegTribISSQN = RegTribIssqn.Nenhum; EmitIndRatISSQN = RatIssqn.Nao; IsUtf8 = false; ValidarNumeroSessaoResposta = false; NumeroTentativasValidarSessao = 1; } #endregion Constructor #region Propriedades public decimal InfCFeVersaoDadosEnt { get; set; } public string IdeCNPJ { get; set; } public int IdeNumeroCaixa { get; set; } public DFeTipoAmbiente IdeTpAmb { get; set; } public string EmitCNPJ { get; set; } public string EmitIE { get; set; } public string EmitIM { get; set; } public RegTrib EmitCRegTrib { get; set; } public RegTribIssqn EmitCRegTribISSQN { get; set; } public RatIssqn EmitIndRatISSQN { get; set; } public bool IsUtf8 { get; set; } public bool ValidarNumeroSessaoResposta { get; set; } public int NumeroTentativasValidarSessao { get; set; } public bool RemoverAcentos { get; set; } #endregion Propriedades } }
35.350515
83
0.603091
[ "MIT" ]
OpenAC-Net/OpenAC.Net.Sat
src/OpenAC.Net.Sat/Config/SatGeralConfig.cs
3,433
C#
using System; using System.Windows.Forms; namespace FamiStudio { static class Program { [STAThread] static void Main(string[] args) { Theme.Initialize(); PerformanceCounter.Initialize(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FamiStudioForm(args.Length > 0 ? args[0] : null)); } } }
22.95
82
0.601307
[ "MIT" ]
Jjagg/FamiStudio
FamiStudio/Source/Utils/Program.cs
461
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the elastictranscoder-2012-09-25.normal.json service model. */ using System; using System.Net; using Amazon.Runtime; namespace Amazon.ElasticTranscoder.Model { ///<summary> /// ElasticTranscoder exception /// </summary> #if !PCL && !NETSTANDARD [Serializable] #endif public class LimitExceededException : AmazonElasticTranscoderException { /// <summary> /// Constructs a new LimitExceededException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public LimitExceededException(string message) : base(message) {} /// <summary> /// Construct instance of LimitExceededException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public LimitExceededException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of LimitExceededException /// </summary> /// <param name="innerException"></param> public LimitExceededException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of LimitExceededException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public LimitExceededException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of LimitExceededException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public LimitExceededException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !PCL && !NETSTANDARD /// <summary> /// Constructs a new instance of the LimitExceededException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected LimitExceededException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } #endif } }
43.082474
178
0.649677
[ "Apache-2.0" ]
FoxBearBear/aws-sdk-net
sdk/src/Services/ElasticTranscoder/Generated/Model/LimitExceededException.cs
4,179
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace RosSharp.Urdf.Runtime { public class UrdfGeometryVisualRuntime : UrdfGeometryRuntime { public static void Create(Transform parent, GeometryTypes geometryType, Link.Geometry geometry = null, bool useColliderInVisuals = false) { GameObject geometryGameObject = null; switch (geometryType) { case GeometryTypes.Box: geometryGameObject = GameObject.CreatePrimitive(PrimitiveType.Cube); geometryGameObject.transform.DestroyImmediateIfExists<BoxCollider>(); break; case GeometryTypes.Cylinder: geometryGameObject = GameObject.CreatePrimitive(PrimitiveType.Cylinder); geometryGameObject.transform.DestroyImmediateIfExists<CapsuleCollider>(); break; case GeometryTypes.Sphere: geometryGameObject = GameObject.CreatePrimitive(PrimitiveType.Sphere); geometryGameObject.transform.DestroyImmediateIfExists<SphereCollider>(); break; case GeometryTypes.Mesh: if (geometry != null) geometryGameObject = CreateMeshVisual(geometry.mesh, useColliderInVisuals); //else, let user add their own mesh gameObject break; } if (geometryGameObject != null) { geometryGameObject.transform.SetParentAndAlign(parent); if (geometry != null) SetScale(parent, geometry, geometryType); } } private static GameObject CreateMeshVisual(Link.Geometry.Mesh mesh, bool useColliderInVisuals = false) { GameObject meshObject = UrdfAssetImporterRuntime.Instance.ImportUrdfAssetAsync(mesh.filename, useColliderInVisuals); return meshObject; } } }
46.534884
147
0.624188
[ "Apache-2.0" ]
xBambusekD/ros-sharp
Unity3D/Assets/RosSharp/Scripts/Urdf/Runtime/UrdfGeometryVisualRuntime.cs
2,001
C#
namespace Lexs4SearchRetrieveWebService { /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("WscfGen", "1.0.0.0")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://lexs.gov/digest/4.0")] public partial class ArrestInvolvedWeaponAssociationType : AssociationType { private ReferenceType2[] arrestReferenceField; private ReferenceType2[] weaponReferenceField; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("ArrestReference", Namespace="http://niem.gov/niem/domains/jxdm/4.1", Order=0)] public ReferenceType2[] ArrestReference { get { return this.arrestReferenceField; } set { this.arrestReferenceField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("WeaponReference", Order=1)] public ReferenceType2[] WeaponReference { get { return this.weaponReferenceField; } set { this.weaponReferenceField = value; } } } }
30.87234
134
0.558925
[ "Apache-2.0" ]
gtri-iead/LEXS-NET-Sample-Implementation-4.0
LEXS Search Retrieve Service Implementation/LexsSearchRetrieveCommon/ArrestInvolvedWeaponAssociationType.cs
1,451
C#
namespace SFA.DAS.Forecasting.Levy.Model.Levy { public class LevyDeclaration { } }
14.857143
46
0.625
[ "MIT" ]
SkillsFundingAgency/das-forecasting-tool
src/SFA.DAS.Forecasting.Levy.Model/Levy/LevyDeclaration.cs
106
C#
// Copyright (c) Daniel Crenna. All rights reserved. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, you can obtain one at http://mozilla.org/MPL/2.0/. using System; using System.Collections.Generic; using System.Runtime.Serialization; using BetterAPI.Metrics.Internal; namespace BetterAPI.Metrics { /// <summary> /// An atomic counter metric /// </summary> public sealed class CounterMetric : IMetric, IComparable<CounterMetric>, IComparable { private readonly AtomicLong _count = new AtomicLong(0); internal CounterMetric(MetricName metricName) { Name = metricName; } private CounterMetric(MetricName metricName, AtomicLong count) { Name = metricName; _count = count; } public long Count => _count.Get(); public int CompareTo(object obj) { if (ReferenceEquals(null, obj)) return 1; if (ReferenceEquals(this, obj)) return 0; return obj is CounterMetric other ? CompareTo(other) : throw new ArgumentException($"Object must be of type {nameof(CounterMetric)}"); } public int CompareTo(CounterMetric other) { if (ReferenceEquals(this, other)) return 0; if (ReferenceEquals(null, other)) return 1; return Name.CompareTo(other.Name); } [IgnoreDataMember] public MetricName Name { get; } public int CompareTo(IMetric other) { return other.Name.CompareTo(Name); } internal IMetric Copy() { var copy = new CounterMetric(Name, new AtomicLong(_count)); return copy; } public void Increment() { Increment(1); } public long Increment(long amount) { return _count.AddAndGet(amount); } public long Decrement() { return Decrement(1); } public long Decrement(long amount) { return _count.AddAndGet(0 - amount); } public void Clear() { _count.Set(0); } public static bool operator <(CounterMetric left, CounterMetric right) { return Comparer<CounterMetric>.Default.Compare(left, right) < 0; } public static bool operator >(CounterMetric left, CounterMetric right) { return Comparer<CounterMetric>.Default.Compare(left, right) > 0; } public static bool operator <=(CounterMetric left, CounterMetric right) { return Comparer<CounterMetric>.Default.Compare(left, right) <= 0; } public static bool operator >=(CounterMetric left, CounterMetric right) { return Comparer<CounterMetric>.Default.Compare(left, right) >= 0; } } }
28.018519
97
0.580965
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
danielcrenna/BetterAPI
src/BetterAPI/Metrics/CounterMetric.cs
3,026
C#
using CloneExtensions.UnitTests.Base; using Microsoft.VisualStudio.TestTools.UnitTesting; using CloneExtensions.UnitTests.Helpers; namespace CloneExtensions.UnitTests { [TestClass] public class NullableOfTTests : TestBase { [TestMethod] public void GetClone_NullableIntWithValue_ValueCloned() { AssertHelpers.GetCloneAndAssert(() => (int?)10); } [TestMethod] public void GetClone_NullableIntWithoutValue_NullCloned() { AssertHelpers.GetCloneAndAssert(() => (int?)null); } } }
25.347826
65
0.665523
[ "Apache-2.0" ]
MarcinJuraszek/CloneExtensions
src/CloneExtensions.UnitTests/NullableOfTTests.cs
585
C#
using System.Collections; using System.Collections.Generic; using CodeHelpers.Packed; namespace CodeHelpers.Mathematics.Enumerable { public readonly struct EnumerableSpace3D : IEnumerable<Int3> { /// <summary> /// Creates a foreach-loop compatible IEnumerable which yields all position/vector inside a 3D rectangular space /// starts at <paramref name="from"/> and ends at <paramref name="to"/> (Both inclusive). /// </summary> public EnumerableSpace3D(Int3 from, Int3 to) => enumerator = new Enumerator(from, to); readonly Enumerator enumerator; public Enumerator GetEnumerator() => enumerator; IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); IEnumerator<Int3> IEnumerable<Int3>.GetEnumerator() => GetEnumerator(); public struct Enumerator : IEnumerator<Int3> { internal Enumerator(Int3 from, Int3 to) { offset = from; Int3 difference = to - from; difference += difference.Signed; //Make inclusive enumerator = new Int3.LoopEnumerable.Enumerator(difference, true); } readonly Int3 offset; Int3.LoopEnumerable.Enumerator enumerator; object IEnumerator.Current => Current; public Int3 Current => enumerator.Current + offset; public bool MoveNext() => enumerator.MoveNext(); public void Reset() => enumerator.Reset(); public void Dispose() => enumerator.Dispose(); } } public readonly struct EnumerableSpace2D : IEnumerable<Int2> { /// <summary> /// Creates a foreach-loop compatible IEnumerable which yields all position/vector inside a 2D rectangular space /// starts at <paramref name="from"/> and ends at <paramref name="to"/> (Both inclusive). /// </summary> public EnumerableSpace2D(Int2 from, Int2 to) => enumerator = new Enumerator(from, to); readonly Enumerator enumerator; public Enumerator GetEnumerator() => enumerator; IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); IEnumerator<Int2> IEnumerable<Int2>.GetEnumerator() => GetEnumerator(); public struct Enumerator : IEnumerator<Int2> { internal Enumerator(Int2 from, Int2 to) { offset = from; Int2 difference = to - from; difference += difference.Signed; //Make inclusive enumerator = new Int2.LoopEnumerable.LoopEnumerator(difference, true); } readonly Int2 offset; Int2.LoopEnumerable.LoopEnumerator enumerator; object IEnumerator.Current => Current; public Int2 Current => enumerator.Current + offset; public bool MoveNext() => enumerator.MoveNext(); public void Reset() => enumerator.Reset(); public void Dispose() => enumerator.Dispose(); } } }
30.27907
114
0.719662
[ "MIT" ]
GaiGai613/CodeHelpers
Mathematics/Enumerable/EnumerableSpace.cs
2,604
C#
// Copyright (c) Philipp Wagner. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using NUnit.Framework; using TinyCsvParser.Mapping; using TinyCsvParser.Model; namespace TinyCsvParser.Test.Mapping { [TestFixture] public class CsvMappingTests { private class SampleEntity { public int PropertyInt { get; set; } public int GetOnlyPropertyInt { get; } } private class DuplicateMapping : CsvMapping<SampleEntity> { public DuplicateMapping() { MapProperty(0, x => x.PropertyInt); MapProperty(0, x => x.PropertyInt); } } [Test] public void DuplicateMappingTest() { Assert.Throws<InvalidOperationException>(() => new DuplicateMapping()); } private class WrongColumnMapping : CsvMapping<SampleEntity> { public WrongColumnMapping() { MapProperty(2, x => x.PropertyInt); } } [Test] public void MapEntity_Invalid_Column_Test() { var mapping = new WrongColumnMapping(); var result = mapping.Map(new TokenizedRow(1, new[] { "A", "1" })); Assert.IsFalse(result.IsValid); Assert.IsNotNull(result.Error); Assert.AreEqual("A|1", result.Error.UnmappedRow); } private class CorrectColumnMapping : CsvMapping<SampleEntity> { public CorrectColumnMapping() { MapProperty(0, x => x.PropertyInt); } } [Test] public void MapEntity_ConversionError_Test() { var mapping = new CorrectColumnMapping(); var result = mapping.Map(new TokenizedRow(1, new[] { string.Empty })); Assert.IsFalse(result.IsValid); Assert.AreEqual("Column 0 with Value '' cannot be converted", result.Error.Value); Assert.AreEqual(0, result.Error.ColumnIndex); Assert.AreEqual(string.Empty, result.Error.UnmappedRow); Assert.DoesNotThrow(() => result.ToString()); } [Test] public void MapEntity_ConversionSuccess_Test() { var mapping = new CorrectColumnMapping(); var result = mapping.Map(new TokenizedRow(1, new[] { "1" })); Assert.IsTrue(result.IsValid); Assert.AreEqual(1, result.Result.PropertyInt); Assert.DoesNotThrow(() => result.ToString()); } private class GetOnlyIntColumnMapping : CsvMapping<SampleEntity> { public GetOnlyIntColumnMapping() { MapProperty(0, x => x.GetOnlyPropertyInt); } } [Test] public void MapEntity_GetOnlyError_Test() { Assert.Throws<InvalidOperationException>(() => new GetOnlyIntColumnMapping()); } } }
27.330275
101
0.583082
[ "MIT" ]
JTOne123/TinyCsvParser
TinyCsvParser/TinyCsvParser.Test/Mapping/CsvMappingTests.cs
2,981
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Application.LogicLayer.Abstract; using Application.LogicLayer.ImplementedClass; using Application.LogicLayer.Interfaces; namespace Application.LogicLayer.Logic.BMI { public class BMIWeightIndex:BodyWeightIndex { public override ICalculatedData CalculateWeightIndex(PersonViewModel person) { //float divider = ; float Index = person.Weight/((person.Heigh/100)*(person.Heigh/100)); return new BMICalculatedData(Index); } } }
27.26087
83
0.714514
[ "Apache-2.0" ]
Foonesh/KMApp
Application.LogicLayer/Logic/BMI/BMIWeightIndex.cs
629
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ResourceHelper.cs" company="Itransition"> // Itransition (c) Copyright. All right reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Web; using System.Web.Mvc; using Framework.Core.Localization; using Framework.Mvc.Extensions; namespace Framework.Mvc.Helpers { /// <summary> /// Provides methods for resources retrieving. /// </summary> public static class ResourceHelper { #region Fields /// <summary> /// Resources scope separator. /// </summary> public static readonly String ScopeSeparator = "."; /// <summary> /// Slash separator. /// </summary> public static readonly char SlashSeparator = '\\'; /// <summary> /// View scope key. /// </summary> public static readonly String ViewScopeKey = "ViewScopeKey"; /// <summary> /// Areas constant. /// </summary> public static readonly String Areas = "Areas"; /// <summary> /// Areas built in framework. /// </summary> public static readonly String[] MainAreas = new[] { "admin", "navigation", "views" }; private const String Models = "Models"; private const String Controllers = "Controllers"; private const String ErrorMessages = "ErrorMessages"; #endregion /// <summary> /// Gets resource String using specified scope, key and culture. /// </summary> /// <remarks> /// <paramref name="translationMissing"/> handler will be called if resource can not be found. /// </remarks> /// <param name="context">The http context.</param> /// <param name="key">The resource key.</param> /// <param name="scope">The localization scope.</param> /// <param name="culture">The culture.</param> /// <param name="translationMissing">Translation missing fallback.</param> /// <returns>Localized String or <paramref name="translationMissing"/> result.</returns> public static String GetResourceString(HttpContextBase context, String key, String scope, CultureInfo culture, Func<String, String, String, String> translationMissing) { if (culture == null) { culture = CultureHelper.DefaultCulture; } var result = context.GetGlobalResourceObject(scope, key, culture) as String; if (result == null && translationMissing != null) { result = translationMissing(key, scope, culture.Name); } return result; } /// <summary> /// Translates property name using model scope. /// </summary> /// <param name="context">The http context.</param> /// <param name="modelType">Type of the model.</param> /// <param name="propertyName">Name of the proprty.</param> /// <returns> /// Localized String or <c>null</c>. /// </returns> public static String TranslatePropertyName(HttpContextBase context, Type modelType, String propertyName) { return GetResourceString(context, propertyName, GetModelScope(modelType), null, null); } /// <summary> /// Translates validation error message. /// </summary> /// <param name="context">The http context.</param> /// <param name="modelType">Type of the model.</param> /// <param name="propertyName">Name of the property.</param> /// <param name="validatorKey">The validator key.</param> /// <returns>Localized String or <c>null</c>.</returns> public static String TranslateErrorMessage(HttpContextBase context, Type modelType, String propertyName, String validatorKey) { var message = GetResourceString(context, validatorKey, GetModelSpecificMessagesScope(modelType, propertyName), null, null); if (String.IsNullOrEmpty(message)) { message = GetResourceString(context, validatorKey, GetCommonMessagesScope(), null, null); } return message; } /// <summary> /// Translates the error message and replace params. /// </summary> /// <param name="context">The context.</param> /// <param name="modelType">Type of the model.</param> /// <param name="propertyName">Name of the property.</param> /// <param name="validatorKey">The validator key.</param> /// <param name="validationParams">The validation params.</param> /// <returns>Localized String or <c>null</c>.</returns> public static String TranslateErrorMessage(HttpContextBase context, Type modelType, String propertyName, String validatorKey, String[] validationParams) { var message = GetResourceString(context, validatorKey, GetModelSpecificMessagesScope(modelType, propertyName), null, null); if (String.IsNullOrEmpty(message)) { message = GetResourceString(context, validatorKey, GetCommonMessagesScope(), null, null); } if (!String.IsNullOrEmpty(message)) { var propertyNameText = TranslatePropertyName(context, modelType, propertyName); return String.Format(message, propertyNameText, validationParams); } return String.Empty; } /// <summary> /// Generates resource key from <paramref name="chains"/>. /// </summary> /// <param name="chains">The chains.</param> /// <returns>Resource key generated from chains specified.</returns> public static String Combine(params String[] chains) { return String.Join(ScopeSeparator, chains); } /// <summary> /// Generates resource key from <paramref name="chains"/>. /// </summary> /// <param name="chains">The chains.</param> /// <returns>Resource key generated from chains specified.</returns> public static String Combine(IEnumerable<String> chains) { return String.Join(ScopeSeparator, chains); } /// <summary> /// Builds model localization scope by it's namespace and type ([AreaName.]Models.{Namespace}.{TypeName}). /// </summary> /// <param name="modelType">Type of the model.</param> /// <returns>Model localization scope.</returns> public static String GetModelScope(Type modelType) { // Adds namespace and class name to scope. var chains = modelType.Namespace.Split(Type.Delimiter).ToList(); chains.Add(modelType.Name); // Removes redudant chains. if (chains.Contains(Areas) || chains.Contains(Models)) { var modelScope = chains.SkipWhile(x => !Areas.Equals(x) && !Models.Equals(x)); if (modelScope.Any() && Areas.Equals(modelScope.First())) { modelScope = modelScope.Skip(1); } chains = modelScope.ToList(); } // Get real Area name var assembly = Assembly.GetAssembly(modelType); if (assembly.Location.Contains(Areas.ToUpper())) { var pathItems = assembly.Location.Split(SlashSeparator).SkipWhile(x => !Areas.ToUpper().Equals(x)); if (pathItems.Count() > 1) { chains.Insert(0, pathItems.Skip(1).First()); } } return Combine(chains); } /// <summary> /// Gets the model specific error messages localization scope. /// </summary> /// <param name="modelType">Type of the model.</param> /// <param name="propertyName">Name of the property.</param> /// <returns>ErrorMessages localization scope.</returns> public static String GetModelSpecificMessagesScope(Type modelType, String propertyName) { return Combine(new[] { GetModelScope(modelType), propertyName, ErrorMessages }); } /// <summary> /// Gets the common error messages localization scope. /// </summary> /// <returns>ErrorMessages localization scope.</returns> public static String GetCommonMessagesScope() { return Combine(new[] { Models, ErrorMessages }); } /// <summary> /// Builds controller localization scope by it's namespace and type ([AreaName.]Controllers.{ControllerName}). /// </summary> /// <param name="controller">The controller.</param> /// <returns>Controller localization scope.</returns> public static String GetControllerScope(Controller controller) { return GetControllerScope(controller.AreaName(), controller.ControllerName()); } /// <summary> /// Gets the controller scope. /// </summary> /// <param name="areaName">Name of the area.</param> /// <param name="controllerName">Name of the controller.</param> /// <returns>Controller localization scope.</returns> public static String GetControllerScope(String areaName, String controllerName) { var chains = new List<String>(); if (!String.IsNullOrEmpty(areaName)) { chains.Add(areaName); } chains.Add(Controllers); if (!String.IsNullOrEmpty(controllerName)) { chains.Add(controllerName); } return Combine(chains); } /// <summary> /// Builds view localization scope by view path (removes leading Areas directory). /// </summary> /// <param name="viewPath">The view path.</param> /// <returns>View localization scope.</returns> public static String GetViewScope(String viewPath) { var chains = PathHelper.SplitPath(PathHelper.TrimVirtualPathStart(viewPath)); chains = chains.SkipWhile(x => Areas.Equals(x)); return Path.GetFileNameWithoutExtension(Combine(chains)); } /// <summary> /// Builds view localization scope by view path (removes leading Areas directory). /// </summary> /// <param name="viewContext">The view context.</param> /// <returns>View localization scope.</returns> public static String GetViewScope(ViewContext viewContext) { var scope = String.Empty; if (viewContext.ViewData.ContainsKey(ViewScopeKey)) { scope = viewContext.ViewData[ViewScopeKey] as String; } else { var viewPage = viewContext.View as WebFormView; if (viewPage != null) { scope = GetViewScope(viewPage.ViewPath); viewContext.ViewData[ViewScopeKey] = scope; } } return scope; } /// <summary> /// Builds partial view localization scope by view path (removes leading Areas directory). /// </summary> /// <param name="viewContext">The view context.</param> /// <param name="partialViewName">Name of partial view.</param> /// <returns>View localization scope.</returns> public static String GetPartialViewScope(ViewContext viewContext, String partialViewName) { var scope = String.Empty; var viewPath = GetPartialViewPath(viewContext, partialViewName); if (!String.IsNullOrEmpty(viewPath)) { scope = GetViewScope(viewPath); } return scope; } private static String GetPartialViewPath(ViewContext viewContext, String partialViewName) { var viewPath = String.Empty; if (VirtualPathUtility.IsAppRelative(partialViewName)) { viewPath = partialViewName; } else { var viewResult = ViewEngines.Engines.FindPartialView(viewContext, partialViewName); if (viewResult.View != null) { var viewPage = viewResult.View as WebFormView; if (viewPage != null) { viewPath = viewPage.ViewPath; } } } return viewPath; } } }
38.723214
175
0.566136
[ "BSD-2-Clause" ]
coreframework/Core-Framework
Source/Framework.MVC/Helpers/ResourceHelper.cs
13,011
C#
// // This file was generated by the BinaryNotes compiler. // See http://bnotes.sourceforge.net // Any modifications to this file will be lost upon recompilation of the source ASN.1. // using GSF.ASN1; using GSF.ASN1.Attributes; using GSF.ASN1.Coders; namespace GSF.MMS.Model { [ASN1PreparedElement] [ASN1Null(Name = "RemoveFromUnitControl-Response")] public class RemoveFromUnitControl_Response : IASN1PreparedElement { private static readonly IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(RemoveFromUnitControl_Response)); public void initWithDefaults() { } public IASN1PreparedElementData PreparedData { get { return preparedData; } } } }
25.96875
162
0.672684
[ "MIT" ]
GridProtectionAlliance/gsf
Source/Libraries/GSF.MMS/Model/RemoveFromUnitControl_Response.cs
831
C#
using Microsoft.Extensions.Logging; using Slackbot.Net.SlackClients.Http.Extensions; using Slackbot.Net.SlackClients.Http.Models.Requests.OAuthAccess; using Slackbot.Net.SlackClients.Http.Models.Responses.OAuthAccess; namespace Slackbot.Net.SlackClients.Http; internal class SlackOAuthAccessClient : ISlackOAuthAccessClient { private readonly HttpClient _client; private readonly ILogger<SlackOAuthAccessClient> _logger; public SlackOAuthAccessClient(HttpClient client, ILogger<SlackOAuthAccessClient> logger) { _client = client; _logger = logger; } /// <inheritdoc/> public async Task<OAuthAccessResponse> OAuthAccess(OauthAccessRequest oauthAccessRequest) { var parameters = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("client_id", oauthAccessRequest.ClientId), new KeyValuePair<string, string>("client_secret", oauthAccessRequest.ClientSecret), new KeyValuePair<string, string>("code", oauthAccessRequest.Code) }; if (!string.IsNullOrEmpty(oauthAccessRequest.RedirectUri)) { parameters.Add(new KeyValuePair<string, string>("redirect_uri", oauthAccessRequest.RedirectUri)); } if (oauthAccessRequest.SingleChannel.HasValue) { parameters.Add(new KeyValuePair<string, string>("single_channel", oauthAccessRequest.SingleChannel.Value ? "true" : "false")); } return await _client.PostParametersAsForm<OAuthAccessResponse>(parameters,"oauth.access", s => _logger?.LogTrace(s)); } /// <inheritdoc/> public async Task<OAuthAccessResponseV2> OAuthAccessV2(OauthAccessRequestV2 oauthAccessRequest) { var parameters = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("code", oauthAccessRequest.Code) }; if (!string.IsNullOrEmpty(oauthAccessRequest.RedirectUri)) { parameters.Add(new KeyValuePair<string, string>("redirect_uri", oauthAccessRequest.RedirectUri)); } if (!string.IsNullOrEmpty(oauthAccessRequest.ClientId)) { parameters.Add(new KeyValuePair<string, string>("client_id", oauthAccessRequest.ClientId)); } if (!string.IsNullOrEmpty(oauthAccessRequest.ClientSecret)) { parameters.Add(new KeyValuePair<string, string>("client_secret", oauthAccessRequest.ClientSecret)); } return await _client.PostParametersAsForm<OAuthAccessResponseV2>(parameters,"oauth.v2.access", s => _logger?.LogTrace(s)); } }
38.724638
138
0.687126
[ "MIT" ]
dotnetbots/Slackbot.Net
source/src/Slackbot.Net.SlackClients.Http/SlackOAuthAccessClient.cs
2,672
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Security.Policy; using System.Text; using System.Threading.Tasks; namespace RiffData { /// <summary> /// The base class for all Chunk types. RiffChunk is one example of a specialization. /// Other chunk types are specific to the type of data they store, samples for which can /// be found in RiffWave, including DataChunk, FactChunk, and FmtChunk. /// </summary> public abstract class ChunkHeader { public const int HEADER_LEN = 8; /// <summary> /// The first four bytes of any chunk is the chunk ID, expressed as a FourCC string. /// </summary> public FourCCPtr id { get; private set; } /// <summary> /// The second set of four bytes give the total length of the data (not including the /// first 8 bytes of ID and BLEN fields) /// </summary> public Int32Ptr blen { get; private set; } /// <summary> /// Keeps track of allocated MappedPtr data AddPtr()'d to this chunk. /// </summary> public List<MappedPtr> body { get; private set; } /// <summary> /// Keeps track of other chunks that have been created and are contained by this chunk. /// </summary> List<ChunkHeader> chunks; public ChunkHeader(MappedFile f, string _id) { id = new FourCCPtr(f); id.Write(_id); blen = new Int32Ptr(f); blen.Write(0); body = new List<MappedPtr>(); chunks = new List<ChunkHeader>(); } /// <summary> /// Adds an allocated subchunk to a chunk /// </summary> /// <param name="ck"></param> public void AddChunk(ChunkHeader ck) { chunks.Add(ck); PlusLen(HEADER_LEN + ck.Length); } /// <summary> /// Adds allocated data to a chunk /// </summary> /// <typeparam name="T">A typed subclass of MappedPtr</typeparam> /// <param name="f">The mapped file in which to allocate the pointer</param> /// <returns>The newly allocated pointer</returns> public T AddPtr<T>(MappedFile f) where T : MappedPtr { T ptr = (T)Activator.CreateInstance(typeof(T), (MappedFile)f); return AddPtr<T>(ptr); } /// <summary> /// Adds a pre-allocated pointer to the body index for this chunk /// </summary> /// <typeparam name="T">The specific subclass of MappedPtr to return</typeparam> /// <param name="p">the pointer to index</param> /// <returns>the same pointer given in</returns> public T AddPtr<T>(T p) where T : MappedPtr { body.Add(p); PlusLen(p.Length); return (T)p; } /// <summary> /// Adds bytes to the chunk length header element /// </summary> /// <param name="nbytes"></param> public void PlusLen(int nbytes) { blen.Write(Length + nbytes); } /// <summary> /// Accessor for reading the chunk Id FourCC string /// </summary> public string Id { get { return id.Read(); } } /// <summary> /// Accessor for reading the length of the chunk /// </summary> public int Length { get { return blen.Read(); } } public string Dump(int indent = 0) { string result; string margin = new string(' ', indent); result = margin + "{'" + Id + "', " + blen.Read(); foreach (var p in body) { //result += ", " + p.GetType().Name; result += ", " + p.Dump(indent + 4); } foreach (var ck in chunks) { result += ",\r\n"; result += ck.Dump(indent + 4); } result += "}"; return result; } } }
32.086614
95
0.528834
[ "BSD-2-Clause" ]
ksmathers/RiffData
RiffData/ChunkHeader.cs
4,077
C#
namespace LinqToShopify.GraphQL.Admin.Context.Store.Types.Location.Enum { public enum LocationSortKeys { ID, NAME, RELEVANCE } }
15.333333
72
0.753623
[ "MIT" ]
Kakktuss/LinqToShopify
src/LinqToShopify/GraphQL/Admin/Context/Store/Types/Location/Enum/LocationSortKeys.cs
140
C#
namespace ETModel { public class SessionInfoComponent : Entity { public Session Session; } }
14
43
0.744898
[ "MIT" ]
ArkNX/ET
Server/Model/Module/Demo/SessionInfoComponent.cs
100
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34209 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace SurfaceDervivedData.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.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.645161
151
0.58473
[ "Apache-2.0" ]
ProjectDataClarity/SurfaceDerivedDataCSharp
SurfaceDervivedData/Properties/Settings.Designer.cs
1,076
C#
#if NET45 namespace Microsoft.ApplicationInsights.WindowsServer { using System; using System.Diagnostics.Tracing; using System.Globalization; using System.IO; using System.Linq; using Microsoft.ApplicationInsights.DataContracts; using Microsoft.ApplicationInsights.Extensibility.Implementation; using Microsoft.ApplicationInsights.WindowsServer.Azure; using Microsoft.ApplicationInsights.WindowsServer.Azure.Emulation; using Microsoft.ApplicationInsights.WindowsServer.Implementation; using Microsoft.VisualStudio.TestTools.UnitTesting; using Web.TestFramework; using Assert = Xunit.Assert; [TestClass] public class AzureRoleEnvironmentTelemetryInitializerTest { [TestMethod] public void AzureRoleEnvironmentTelemetryInitializerDoesNotOverrideRoleName() { var telemetryItem = new EventTelemetry(); AzureRoleEnvironmentContextReader.Instance = null; AzureRoleEnvironmentTelemetryInitializer initializer = new AzureRoleEnvironmentTelemetryInitializer(); telemetryItem.Context.Cloud.RoleName = "Test"; initializer.Initialize(telemetryItem); Assert.Equal("Test", telemetryItem.Context.Cloud.RoleName); } [TestMethod] public void AzureRoleEnvironmentTelemetryInitializerDoesNotOverrideRoleInstance() { var telemetryItem = new EventTelemetry(); AzureRoleEnvironmentTelemetryInitializer initializer = new AzureRoleEnvironmentTelemetryInitializer(); telemetryItem.Context.Cloud.RoleInstance = "Test"; initializer.Initialize(telemetryItem); Assert.Equal("Test", telemetryItem.Context.Cloud.RoleInstance); } [TestMethod] public void AzureRoleEnvironmentTelemetryInitializerDoesNotOverrideNodeName() { var telemetryItem = new EventTelemetry(); AzureRoleEnvironmentContextReader.Instance = null; AzureRoleEnvironmentTelemetryInitializer initializer = new AzureRoleEnvironmentTelemetryInitializer(); telemetryItem.Context.GetInternalContext().NodeName = "Test"; initializer.Initialize(telemetryItem); Assert.Equal("Test", telemetryItem.Context.GetInternalContext().NodeName); } [TestMethod] public void AzureRoleEnvironmentTelemetryInitializerSetsTelemetryContextPropertiesToNullWhenNotRunningInsideAzureCloudService() { // This test asssumes that it is not running inside a cloud service. // Its Ok even if Azure ServiceRunTime dlls are in the GAC, as IsAvailable() will return false, and hence // no context will be further attempted to be read. var telemetryItem = new EventTelemetry(); AzureRoleEnvironmentContextReader.Instance = null; AzureRoleEnvironmentContextReader.AssemblyLoaderType = null; AzureRoleEnvironmentTelemetryInitializer initializer = new AzureRoleEnvironmentTelemetryInitializer(); initializer.Initialize(telemetryItem); Assert.Null(telemetryItem.Context.Cloud.RoleName); Assert.Null(telemetryItem.Context.Cloud.RoleInstance); Assert.Null(telemetryItem.Context.GetInternalContext().NodeName); } [TestMethod] public void AzureRoleEnvironmentTelemetryInitializerDoNotPopulateContextIfRunningAzureWebApp() { try { // Set the ENV variable so as to trick app is running as Azure WebApp Environment.SetEnvironmentVariable("WEBSITE_SITE_NAME", "TestRoleName.AzureWebSites.net"); // Initialize telemetry using AzureRoleEnvironmentTelemetryInitializer var telemetryItem = new EventTelemetry(); AzureRoleEnvironmentTelemetryInitializer initializer = new AzureRoleEnvironmentTelemetryInitializer(); initializer.Initialize(telemetryItem); // As app is running as Azure WebApp, AzureRoleEnvironmentTelemetryInitializer will not populate any context. Assert.Null(telemetryItem.Context.Cloud.RoleName); Assert.Null(telemetryItem.Context.Cloud.RoleInstance); Assert.Null(telemetryItem.Context.GetInternalContext().NodeName); } finally { Environment.SetEnvironmentVariable("WEBSITE_SITE_NAME", null); } } [TestMethod] [Description("Validates that requested DLL was loaded into separate AppDomain and not to the current domain. This test will fail if not run with admin privileges.")] public void AzureRoleEnvironmentTelemetryInitializerLoadDllToSeparateAppDomain() { // A random dll which is not already loaded to the current AppDomain but dropped into bin folder. string dllPath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Microsoft.ApplicationInsights.Log4NetAppender.dll"); Assert.True(File.Exists(dllPath)); try { // Publish the dll to GAC to give a chance for AzureRoleEnvironmentTelemetryInitializer to load it to a new AppDomain new System.EnterpriseServices.Internal.Publish().GacInstall(dllPath); // Validate that the dll is not loaded to test AppDomaion to begin with. var retrievedAssembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(item => string.Equals(item.GetName().Name, "Microsoft.ApplicationInsights.Log4NetAppender", StringComparison.OrdinalIgnoreCase)); Assert.Null(retrievedAssembly); // TestAssemblyLoader will load a random assembly (Microsoft.ApplicationInsights.Log4NetAppender.dll) and populate TestRoleName, TestRoleInstanceId into the fields. AzureRoleEnvironmentContextReader.AssemblyLoaderType = typeof(TestAzureServiceRuntimeAssemblyLoader); AzureRoleEnvironmentContextReader.Instance = null; // Create initializer - this will internally create separate appdomain and load assembly into it. AzureRoleEnvironmentTelemetryInitializer initializer = new AzureRoleEnvironmentTelemetryInitializer(); // Validate that the dll is still not loaded to current appdomain. retrievedAssembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(item => string.Equals(item.GetName().Name, "Microsoft.ApplicationInsights.Log4NetAppender", StringComparison.OrdinalIgnoreCase)); Assert.Null(retrievedAssembly); // Validate that initializer has populated expected context properties. (set by TestAssemblyLoader) var telemetryItem = new EventTelemetry(); initializer.Initialize(telemetryItem); Assert.Equal("TestRoleName", telemetryItem.Context.Cloud.RoleName); Assert.Equal("TestRoleInstanceId", telemetryItem.Context.Cloud.RoleInstance); } finally { new System.EnterpriseServices.Internal.Publish().GacRemove(dllPath); } } } } #endif
52.330935
224
0.697828
[ "MIT" ]
Bhaskers-Blu-Org2/ApplicationInsights-dotnet
WEB/Src/WindowsServer/WindowsServer.Tests/AzureRoleEnvironmentTelemetryInitializerTest.cs
7,276
C#
namespace MassTransit.Configuration { public interface ISagaConnector { ISagaSpecification<T> CreateSagaSpecification<T>() where T : class, ISaga; ConnectHandle ConnectSaga<T>(IConsumePipeConnector consumePipe, ISagaRepository<T> repository, ISagaSpecification<T> specification) where T : class, ISaga; } }
30
139
0.7
[ "ECL-2.0", "Apache-2.0" ]
AlexanderMeier/MassTransit
src/MassTransit/Sagas/Configuration/ISagaConnector.cs
360
C#
using OpenCvSharp; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lightning.Core.Rendering { public interface IWindowHost : IDisposable { void ShowWindow(); void HideWindow(); } public interface IWindowHost<in TFrame> : IWindowHost { void WriteFrame(TFrame mat); } }
16.409091
54
0.761773
[ "MIT" ]
lightning-rmc/lightning
src/core/Lightning.Core/Rendering/IWindowHost.cs
361
C#
using Orchard.Hosting.Parameters; using System; using System.Collections.Generic; using System.Security; namespace Orchard.Hosting.HostContext { public class CommandParametersParser : ICommandParametersParser { [SecurityCritical] public CommandParameters Parse(IEnumerable<string> args) { var result = new CommandParameters { Arguments = new List<string>(), Switches = new Dictionary<string, string>() }; foreach (var arg in args) { // Switch? if (arg[0] == '/') { int index = arg.IndexOf(':'); var switchName = (index < 0 ? arg.Substring(1) : arg.Substring(1, index - 1)); var switchValue = (index < 0 || index >= arg.Length ? string.Empty : arg.Substring(index + 1)); if (string.IsNullOrEmpty(switchName)) { throw new ArgumentException(string.Format("Invalid switch syntax: \"{0}\". Valid syntax is /<switchName>[:<switchValue>].", arg)); } result.Switches.Add(switchName, switchValue); } else { result.Arguments.Add(arg); } } return result; } } }
32.068182
154
0.490432
[ "BSD-3-Clause" ]
freemsly/Orchard-2-Prototype-RC2
src/Orchard.Hosting.Console/HostContext/CommandParametersParser.cs
1,413
C#
using Newtonsoft.Json; using WeihanLi.Extensions; namespace WeihanLi.Common.Event; public interface IEventBase { /// <summary> /// Event publish time /// </summary> DateTimeOffset EventAt { get; } /// <summary> /// eventId /// </summary> string EventId { get; } } public abstract class EventBase : IEventBase { [JsonProperty] public DateTimeOffset EventAt { get; private set; } [JsonProperty] public string EventId { get; private set; } protected EventBase() { EventId = GuidIdGenerator.Instance.NewId(); EventAt = DateTimeOffset.UtcNow; } protected EventBase(string eventId) { EventId = eventId; EventAt = DateTimeOffset.UtcNow; } // https://www.newtonsoft.com/json/help/html/JsonConstructorAttribute.htm [JsonConstructor] protected EventBase(string eventId, DateTimeOffset eventAt) { EventId = eventId; EventAt = eventAt; } } public static class EventBaseExtensions { private static readonly JsonSerializerSettings _eventSerializerSettings = JsonSerializeExtension.SerializerSettingsWith(s => { s.TypeNameHandling = TypeNameHandling.Objects; }); public static string ToEventMsg<TEvent>(this TEvent @event) where TEvent : class, IEventBase { if (null == @event) { throw new ArgumentNullException(nameof(@event)); } return @event.ToJson(_eventSerializerSettings); } public static IEventBase ToEvent(this string eventMsg) { if (null == eventMsg) { throw new ArgumentNullException(nameof(eventMsg)); } return eventMsg.JsonToObject<IEventBase>(_eventSerializerSettings); } }
23.92
128
0.638796
[ "MIT" ]
JohnZhaoXiaoHu/WeihanLi.Common
src/WeihanLi.Common/Event/EventBase.cs
1,796
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 ModbusSlaveSimulation.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.709677
151
0.585502
[ "MIT" ]
GitHubDragonFly/ModbusSlaveSimulation
ModbusSlaveSimulation/Properties/Settings.Designer.cs
1,078
C#
using System.Collections.Generic; using StackExchange.Opserver.Data; using StackExchange.Opserver.Data.SQL; namespace StackExchange.Opserver.Views.SQL { public enum SQLViews { Servers = 0, Instance = 1, Active = 2, Top = 3, Connections = 4, Databases = 5 } public class DashboardModel { public SQLInstance CurrentInstance { get; set; } public string ErrorMessage { get; set; } public int Refresh { get; set; } public SQLViews View { get; set; } public enum LastRunInterval { FiveMinutes = 5 * 60, Hour = 60 * 60, Day = 24 * 60 * 60, Week = 7 * 24 * 60 * 60 } public List<SQLInstance.SQLConnectionInfo> Connections { get; set; } public Cache Cache { get; set; } } }
23.944444
76
0.558005
[ "MIT" ]
bonskijr/Opserver
Opserver/Views/SQL/Dashboard.Model.cs
864
C#
using Blazored.LocalStorage; using Flurl.Http; using FoodOnline.WebClient.Business.Services; using FoodOnline.WebClient.Services; using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.Components.WebAssembly.Hosting; using Microsoft.Extensions.DependencyInjection; using System.Threading.Tasks; namespace FoodOnline.WebClient.Business { public static class Program { public static async Task Main(string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); var services = builder.Services; builder.RootComponents.Add<App>("app"); services.AddSharedServices(); services.AddScoped<AuthenticationStateProvider, ApiAuthenticationStateProvider>(f => new ApiAuthenticationStateProvider(f.GetService<IFlurlClient>(), f.GetService<ILocalStorageService>(), "businessToken")); services.AddScoped<IAuthService, AuthService>(); await builder.Build().RunAsync(); } } }
36.928571
137
0.718569
[ "MIT" ]
panoukos41/FoodOnline
src/WebClient.Business/Program.cs
1,034
C#
/// OSVR-Unity Connection /// /// http://sensics.com/osvr /// /// <copyright> /// Copyright 2014 Sensics, Inc. /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// </copyright> using UnityEngine; namespace OSVR { namespace Unity { /// <summary> /// Class of static methods for converting from OSVR math/tracking types to Unity-native data types, including coordinate system change as needed. /// </summary> public class Math { public static Vector3 ConvertPosition(OSVR.ClientKit.Vec3 vec) { /// Convert to left-handed return new Vector3((float)vec.x, (float)vec.y, (float)-vec.z); } public static Vector2 ConvertPosition(OSVR.ClientKit.Vec2 vec) { return new Vector2((float)vec.x, (float)vec.y); } public static Quaternion ConvertOrientation(OSVR.ClientKit.Quaternion quat) { /// Wikipedia may say quaternions are not handed, but these needed modification. return new Quaternion(-(float)quat.x, -(float)quat.y, (float)quat.z, (float)quat.w); } public static Matrix4x4 ConvertPose(OSVR.ClientKit.Pose3 pose) { return Matrix4x4.TRS(Math.ConvertPosition(pose.translation), Math.ConvertOrientation(pose.rotation), Vector3.zero); } //Convert OSVR.ClientKit.Viewport to Rect public static Rect ConvertViewport(OSVR.ClientKit.Viewport viewport, OSVR.ClientKit.DisplayDimensions surfaceDisplayDimensions, int numDisplayInputs, int eyeIndex, int totalDisplayWidth) { //Unity expects normalized coordinates, not pixel coordinates if (numDisplayInputs == 1) { return new Rect((float)viewport.Left / (float)surfaceDisplayDimensions.Width, (float)viewport.Bottom / (float)surfaceDisplayDimensions.Height, (float)viewport.Width / (float)surfaceDisplayDimensions.Width, (float)viewport.Height / (float)surfaceDisplayDimensions.Height); } else if(numDisplayInputs == 2) { //with two inputs in fullscreen mode, viewports expect to fill the screen //Unity can only output to one window, so we offset the right eye by half the total width of the displays return new Rect(eyeIndex == 0 ? 0 : 0.5f + (float)viewport.Left / (float)totalDisplayWidth, (float)viewport.Bottom / (float)surfaceDisplayDimensions.Height, (float)viewport.Width / (float)totalDisplayWidth, (float)viewport.Height / (float)surfaceDisplayDimensions.Height); } else { Debug.LogError("[OSVR-Unity] More than two video inputs is not supported. Using default viewport."); return new Rect(0, 0, 0.5f, 1f); } } public static Rect ConvertViewportRenderManager(OSVR.ClientKit.Viewport viewport) { //Unity expects normalized coordinates, not pixel coordinates //@todo below assumes left and right eyes split the screen in half horizontally return new Rect(viewport.Left / viewport.Width, viewport.Bottom / viewport.Height, viewport.Width / viewport.Width, 1); } //Convert OSVR.ClientKit.Matrix44f to Matrix4x4 public static Matrix4x4 ConvertMatrix(OSVR.ClientKit.Matrix44f matrix) { Matrix4x4 matrix4x4 = new Matrix4x4(); matrix4x4[0, 0] = matrix.M0; matrix4x4[1, 0] = matrix.M1; matrix4x4[2, 0] = matrix.M2; matrix4x4[3, 0] = matrix.M3; matrix4x4[0, 1] = matrix.M4; matrix4x4[1, 1] = matrix.M5; matrix4x4[2, 1] = matrix.M6; matrix4x4[3, 1] = matrix.M7; matrix4x4[0, 2] = matrix.M8; matrix4x4[1, 2] = matrix.M9; matrix4x4[2, 2] = matrix.M10; matrix4x4[3, 2] = matrix.M11; matrix4x4[0, 3] = matrix.M12; matrix4x4[1, 3] = matrix.M13; matrix4x4[2, 3] = matrix.M14; matrix4x4[3, 3] = matrix.M15; return matrix4x4;// * Matrix4x4.Scale(new Vector3(1, -1, 1)); ; } } } }
45.901786
198
0.57732
[ "Apache-2.0" ]
JacksonTech/JVRCurriculum
UnityOSVRDemos/Assets/OSVRUnity/src/Math.cs
5,141
C#
using System; using System.Text; using System.Xml.Serialization; using CodeDead.Logger.Append.Configuration.File; namespace CodeDead.Logger.Append.File { /// <inheritdoc /> /// <summary> /// Abstract class containing the file appending logic /// Inherit this class to implement your own file appending logic /// </summary> [XmlInclude(typeof(CsvFileAppender))] [XmlInclude(typeof(DefaultFileAppender))] [XmlInclude(typeof(JsonFileAppender))] [XmlInclude(typeof(XmlFileAppender))] public abstract class FileAppender : LogAppender { #region Variables private string _filePath; #endregion #region Properties /// <summary> /// Gets or sets the encoding that should be used to write and retrieve data /// </summary> [XmlElement("TextEncoding")] public Encoding TextEncoding { get; set; } /// <summary> /// Gets or sets the path to which a Log object should be written /// </summary> [XmlElement("FilePath")] public string FilePath { get => _filePath; set => _filePath = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// Property that contains the FileConfiguration /// </summary> [XmlElement("FileConfiguration")] public FileConfiguration FileConfiguration { get; set; } #endregion } }
30.604167
87
0.622192
[ "MIT" ]
CodeDead/Logger
Logger/Append/File/FileAppender.cs
1,471
C#
using System.Collections.Generic; using System.Text.Json.Serialization; namespace Essensoft.AspNetCore.Payment.Alipay.Domain { /// <summary> /// KoubeiMarketingDataMallRecommendGetModel Data Structure. /// </summary> public class KoubeiMarketingDataMallRecommendGetModel : AlipayObject { /// <summary> /// 获取几条数据,最大值传入50,默认值10 /// </summary> [JsonPropertyName("count")] public long Count { get; set; } /// <summary> /// 获取的数据类型:big_item(商圈商品)、small_item(商圈下门店商品)、big_voucher(商圈券)、small_voucher(商圈下门店券) /// </summary> [JsonPropertyName("data_type")] public string DataType { get; set; } /// <summary> /// 设备ID /// </summary> [JsonPropertyName("device_id")] public string DeviceId { get; set; } /// <summary> /// 商圈ID /// </summary> [JsonPropertyName("mall_id")] public string MallId { get; set; } /// <summary> /// 店铺类目ID /// </summary> [JsonPropertyName("shop_category_ids")] public List<string> ShopCategoryIds { get; set; } /// <summary> /// 起始数据下标,默认值0 /// </summary> [JsonPropertyName("start")] public long Start { get; set; } /// <summary> /// 支付宝用户ID /// </summary> [JsonPropertyName("user_id")] public string UserId { get; set; } } }
26.907407
93
0.553338
[ "MIT" ]
LuohuaRain/payment
src/Essensoft.AspNetCore.Payment.Alipay/Domain/KoubeiMarketingDataMallRecommendGetModel.cs
1,593
C#
using System.Collections.Generic; using Essensoft.AspNetCore.Payment.Alipay.Response; namespace Essensoft.AspNetCore.Payment.Alipay.Request { /// <summary> /// alipay.user.antpaas.role.relation.save /// </summary> public class AlipayUserAntpaasRoleRelationSaveRequest : IAlipayRequest<AlipayUserAntpaasRoleRelationSaveResponse> { /// <summary> /// 保存账号绑定关系 /// </summary> public string BizContent { get; set; } #region IAlipayRequest Members private bool needEncrypt = false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AlipayObject bizModel; public void SetNeedEncrypt(bool needEncrypt) { this.needEncrypt = needEncrypt; } public bool GetNeedEncrypt() { return needEncrypt; } public void SetNotifyUrl(string notifyUrl) { this.notifyUrl = notifyUrl; } public string GetNotifyUrl() { return notifyUrl; } public void SetReturnUrl(string returnUrl) { this.returnUrl = returnUrl; } public string GetReturnUrl() { return returnUrl; } public void SetTerminalType(string terminalType) { this.terminalType = terminalType; } public string GetTerminalType() { return terminalType; } public void SetTerminalInfo(string terminalInfo) { this.terminalInfo = terminalInfo; } public string GetTerminalInfo() { return terminalInfo; } public void SetProdCode(string prodCode) { this.prodCode = prodCode; } public string GetProdCode() { return prodCode; } public string GetApiName() { return "alipay.user.antpaas.role.relation.save"; } public void SetApiVersion(string apiVersion) { this.apiVersion = apiVersion; } public string GetApiVersion() { return apiVersion; } public IDictionary<string, string> GetParameters() { var parameters = new AlipayDictionary { { "biz_content", BizContent } }; return parameters; } public AlipayObject GetBizModel() { return bizModel; } public void SetBizModel(AlipayObject bizModel) { this.bizModel = bizModel; } #endregion } }
23.04878
117
0.550617
[ "MIT" ]
LuohuaRain/payment
src/Essensoft.AspNetCore.Payment.Alipay/Request/AlipayUserAntpaasRoleRelationSaveRequest.cs
2,853
C#
using System.Web.Mvc; namespace NewsSystem.Client.MVC.App_Start { public class ViewEngineConfig { public static void RegisterViewEngine(ViewEngineCollection engines) { engines.Clear(); engines.Add(new RazorViewEngine()); } } }
22.153846
75
0.631944
[ "MIT" ]
todor-enikov/News-System-ASP.NET-MVC-Project
Source/NewsSystem.Client.MVC/App_Start/ViewEngineConfig.cs
290
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("ChoJSONReaderTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ChoJSONReaderTest")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f9560fc0-5dad-4f59-8ba1-46e3d7b183cf")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.027027
84
0.746979
[ "MIT" ]
Cinchoo/ChoETL
src/Test/ChoJSONReaderTest/Properties/AssemblyInfo.cs
1,410
C#
#if UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 #define UNITY_AUDIO_FEATURES_4_0 #else #define UNITY_AUDIO_FEATURES_4_1 #endif using UnityEngine; using System.Collections.Generic; #pragma warning disable 1591 // undocumented XML code warning public class AudioToolkitDemo : MonoBehaviour { public AudioClip customAudioClip; float musicVolume = 1; float ambienceVolume = 1; bool musicPaused = false; Vector2 playlistScrollPos = Vector2.zero; PoolableReference<AudioObject> introLoopOutroAudio; void OnGUI() { DrawGuiLeftSide(); DrawGuiRightSide(); DrawGuiBottom(); } void DrawGuiLeftSide() { var headerStyle = new GUIStyle( GUI.skin.label ); headerStyle.normal.textColor = new UnityEngine.Color( 1, 1, 0.5f ); string txt = string.Format( "ClockStone Audio Toolkit - Demo" ); GUI.Label( new Rect( 22, 10, 500, 20 ), txt, headerStyle ); int ypos = 10; int yposOff = 35; int buttonWidth = 200; int scrollbarWidth = 130; ypos += 30; GUI.Label( new Rect( 250, ypos, buttonWidth, 30 ), "Global Volume" ); AudioController.SetGlobalVolume( GUI.HorizontalSlider( new Rect( 250, ypos + 20, scrollbarWidth, 30 ), AudioController.GetGlobalVolume(), 0, 1 ) ); if ( GUI.Button( new Rect( 20, ypos, buttonWidth, 30 ), "Cross-fade to music track 1" ) ) { AudioController.PlayMusic( "MusicTrack1" ); } ypos += yposOff; GUI.Label( new Rect( 250, ypos + 10, buttonWidth, 30 ), "Music Volume" ); float musicVolumeNew = GUI.HorizontalSlider( new Rect( 250, ypos + 30, scrollbarWidth, 30 ), musicVolume, 0, 1 ); if ( musicVolumeNew != musicVolume ) { musicVolume = musicVolumeNew; AudioController.SetCategoryVolume( "Music", musicVolume ); } GUI.Label( new Rect( 250 + scrollbarWidth + 30, ypos + 10, buttonWidth, 30 ), "Ambience Volume" ); float ambienceVolumeNew = GUI.HorizontalSlider( new Rect( 250 + scrollbarWidth + 30, ypos + 30 , scrollbarWidth, 30 ), ambienceVolume, 0, 1 ); if ( ambienceVolumeNew != ambienceVolume ) { ambienceVolume = ambienceVolumeNew; AudioController.SetCategoryVolume( "Ambience", ambienceVolume ); } if ( GUI.Button( new Rect( 20, ypos, buttonWidth, 30 ), "Cross-fade to music track 2" ) ) { AudioController.PlayMusic( "MusicTrack2" ); } ypos += yposOff; if ( GUI.Button( new Rect( 20, ypos, buttonWidth, 30 ), "Stop Music" ) ) { AudioController.StopMusic( 0.3f ); } //if ( GUI.Button( new Rect( 250, ypos, buttonWidth, 30 ), "Stop Ambience" ) ) //{ // AudioController.StopAmbienceSound( 0.5f ); //} ypos += yposOff; bool musicPausedNew = GUI.Toggle( new Rect( 20, ypos, buttonWidth, 30 ), musicPaused, "Pause All Audio" ); if ( musicPausedNew != musicPaused ) { musicPaused = musicPausedNew; if ( musicPaused ) { AudioController.PauseAll( 0.1f ); } else AudioController.UnpauseAll( 0.1f ); } ypos += 20; if ( GUI.Button( new Rect( 20, ypos, buttonWidth, 30 ), "Play Sound with random pitch" ) ) { AudioController.Play( "RandomPitchSound" ); } ypos += yposOff; if ( GUI.Button( new Rect( 20, ypos, buttonWidth, 30 ), "Play Sound with alternatives" ) ) { AudioObject soundObj = AudioController.Play( "AlternativeSound" ); if ( soundObj != null ) soundObj.completelyPlayedDelegate = OnAudioCompleteleyPlayed; } ypos += yposOff; if ( GUI.Button( new Rect( 20, ypos, buttonWidth, 30 ), "Play Both" ) ) { AudioObject soundObj = AudioController.Play( "RandomAndAlternativeSound" ); if ( soundObj != null ) soundObj.completelyPlayedDelegate = OnAudioCompleteleyPlayed; } ypos += yposOff; GUI.Label(new Rect(20, ypos, 100, 20), "Playlists: "); ypos += 20; playlistScrollPos = GUI.BeginScrollView(new Rect(20, ypos, buttonWidth, 100), playlistScrollPos, new Rect(0, 0, buttonWidth, 33f*AudioController.Instance.musicPlaylists.Length)); for ( int i = 0; i < AudioController.Instance.musicPlaylists.Length; ++i ) { if ( GUI.Button( new Rect( 20, i * 33f, buttonWidth - 20, 30f ), AudioController.Instance.musicPlaylists[ i ].name ) ) { AudioController.SetCurrentMusicPlaylist( AudioController.Instance.musicPlaylists[ i ].name ); } } ypos += 105; GUI.EndScrollView(); if ( GUI.Button( new Rect( 20, ypos, buttonWidth, 30 ), "Play Music Playlist" ) ) { AudioController.PlayMusicPlaylist(); } ypos += yposOff; if ( AudioController.IsPlaylistPlaying() && GUI.Button( new Rect( 20, ypos, buttonWidth, 30 ), "Next Track on Playlist" ) ) { AudioController.PlayNextMusicOnPlaylist(); } ypos += 32; if ( AudioController.IsPlaylistPlaying() && GUI.Button( new Rect( 20, ypos, buttonWidth, 30 ), "Previous Track on Playlist" ) ) { AudioController.PlayPreviousMusicOnPlaylist(); } ypos += yposOff; AudioController.Instance.loopPlaylist = GUI.Toggle( new Rect( 20, ypos, buttonWidth, 30 ), AudioController.Instance.loopPlaylist, "Loop Playlist" ); ypos += 20; AudioController.Instance.shufflePlaylist = GUI.Toggle( new Rect( 20, ypos, buttonWidth, 30 ), AudioController.Instance.shufflePlaylist, "Shuffle Playlist " ); ypos += 20; AudioController.Instance.soundMuted = GUI.Toggle( new Rect( 20, ypos, buttonWidth, 30 ), AudioController.Instance.soundMuted, "Sound Muted" ); } bool wasClipAdded = false; bool wasCategoryAdded = false; void DrawGuiRightSide() { int ypos = 50; int yposOff = 35; int buttonWidth = 300; if ( !wasCategoryAdded ) { if ( customAudioClip != null && GUI.Button( new Rect( Screen.width - ( buttonWidth + 20 ), ypos, buttonWidth, 30 ), "Create new category with custom AudioClip" ) ) { var category = AudioController.NewCategory( "Custom Category" ); AudioController.AddToCategory( category, customAudioClip, "CustomAudioItem" ); wasClipAdded = true; wasCategoryAdded = true; } } else { if ( GUI.Button( new Rect( Screen.width - ( buttonWidth + 20 ), ypos, buttonWidth, 30 ), "Play custom AudioClip" ) ) { AudioController.Play( "CustomAudioItem" ); } if ( wasClipAdded ) { ypos += yposOff; if ( GUI.Button( new Rect( Screen.width - ( buttonWidth + 20 ), ypos, buttonWidth, 30 ), "Remove custom AudioClip" ) ) { if ( AudioController.RemoveAudioItem( "CustomAudioItem" ) ) { wasClipAdded = false; } } } } ypos = 130; #if !UNITY_AUDIO_FEATURES_4_1 BeginDisabledGroup( true ); #endif if ( GUI.Button( new Rect( Screen.width - ( buttonWidth + 20 ), ypos, buttonWidth, 30 ), "Play gapless audio loop" ) ) { AudioController.Play( "GaplessLoopTest" ).Stop( 1, 4 ); } ypos += yposOff; if ( GUI.Button( new Rect( Screen.width - ( buttonWidth + 20 ), ypos, buttonWidth, 30 ), "Play random loop sequence" ) ) { AudioController.Play( "RandomLoopSequence" ); } ypos += yposOff; if ( GUI.Button( new Rect( Screen.width - ( buttonWidth + 20 ), ypos, buttonWidth, 50 ), "Play intro-loop-outro sequence\ngatling gun" ) ) { introLoopOutroAudio = new PoolableReference<AudioObject>( AudioController.Play( "IntroLoopOutro_Gun" ) ); } ypos += 20; ypos += yposOff; BeginDisabledGroup( !(introLoopOutroAudio != null && introLoopOutroAudio.Get() != null) ); if ( GUI.Button( new Rect( Screen.width - ( buttonWidth + 20 ), ypos, buttonWidth, 30 ), "Finish gatling gun sequence" ) ) { introLoopOutroAudio.Get().FinishSequence(); } EndDisabledGroup(); #if !UNITY_AUDIO_FEATURES_4_1 EndDisabledGroup(); #endif } void DrawGuiBottom() { if ( GUI.Button( new Rect( Screen.width / 2 - 150, Screen.height - 40, 300, 30 ), "Video tutorial & more info..." ) ) { Application.OpenURL( "http://unity.clockstone.com" ); } } void OnAudioCompleteleyPlayed( AudioObject audioObj ) { Debug.Log( "Finished playing " + audioObj.audioID + " with clip " + audioObj.primaryAudioSource.clip.name ); } List<bool> disableGUILevels = new List<bool>(); void BeginDisabledGroup( bool condition ) { disableGUILevels.Add( condition ); GUI.enabled = !IsGUIDisabled(); } void EndDisabledGroup() { var count = disableGUILevels.Count; if ( count > 0 ) { disableGUILevels.RemoveAt( count - 1 ); GUI.enabled = !IsGUIDisabled(); } else Debug.LogWarning( "misplaced EndDisabledGroup" ); } bool IsGUIDisabled() { foreach ( var b in disableGUILevels ) { if ( b ) return true; } return false; } }
33.504918
176
0.560133
[ "Unlicense" ]
pacatum/Helmbet-RPS
Assets/AudioToolkit/Demo/AudioToolkitDemo.cs
10,219
C#
using System; using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Text.Json; using System.Linq; namespace KVL.Tests { [TestClass] public class TransactionTests { [TestMethod] public async Task TestCommitTransaction() { var kvl = KVLite.CreateJsonInMemory(); var key = Encoding.UTF8.GetBytes("key"); var value = JsonSerializer.Serialize(new {hello = "value"}); var value2 = JsonSerializer.Serialize("value"); using var trx = await kvl.BeginTransactionAsync(key); await kvl.Add(key, value); await kvl.Insert(key, "$.world", value2); await trx.CommitAsync(); var res = await kvl.Get(key); var expected = JsonSerializer.Serialize(new {hello = "value", world = "value"}); Assert.AreEqual(expected, res); } [TestMethod] public async Task TestRollbackTransaction() { var kvl = KVLite.CreateJsonInMemory(); var key = Encoding.UTF8.GetBytes("key"); var value = JsonSerializer.Serialize(new {hello = "value"}); var value2 = JsonSerializer.Serialize("value"); await kvl.Add(key, value); using var trx = await kvl.BeginTransactionAsync(key); await kvl.Insert(key, "$.world", value2); await trx.RollbackAsync(); var res = await kvl.Get(key); Assert.AreEqual(value, res); } [TestMethod] public async Task TestMulitpleInsertsPerTransaction() { var kvl = KVLite.CreateJsonInMemory(); var key = Encoding.UTF8.GetBytes("key"); var value = JsonSerializer.Serialize(new {hello = "value"}); using var trx = await kvl.BeginTransactionAsync(key); await kvl.Add(key, value); await kvl.Set(key, "$.world", "[0]"); await kvl.Insert(key, "$.world[#]", 1); await kvl.Set(key, "$.world[#]", 2); await trx.CommitAsync(); var expected = JsonSerializer.Serialize(new {hello = "value", world = new [] {0,1,2}}); var res = await kvl.Get(key); Assert.AreEqual(expected, res); } [TestMethod] public async Task TestDisposeRollsBack() { var kvl = KVLite.CreateJsonInMemory(); var key = Encoding.UTF8.GetBytes("key"); var value = JsonSerializer.Serialize(new {hello = "value"}); await kvl.Add(key, value); using (var trx = await kvl.BeginTransactionAsync(key)) { await kvl.Insert(key, "$.world", "[0]"); await kvl.Insert(key, "$.world[#]", 1); await kvl.Insert(key, "$.world[#]", 2); } var res = await kvl.Get(key); Assert.AreEqual(value, res); } [TestMethod] public async Task TestMultiThreadedTransactionOnSameKey() { var kvl = KVLite.CreateJsonInMemory(); var key = Encoding.UTF8.GetBytes("key"); var value = JsonSerializer.Serialize(new {hello = "value"}); var arrayValues = Enumerable.Range(0, 100); await kvl.Add(key, value); var tasks = arrayValues .Select(trxFunc); await Task.WhenAll(tasks); var res = await kvl.Get(key); var element = JsonDocument.Parse(res.Head()).RootElement; var prop = element .EnumerateObject() .Find(x => x.Name == "world").Head(); var values = arrayValues.ToHashSet(); foreach(var i in prop.Value.EnumerateArray()) { values.Remove(i.GetInt32()); } Assert.AreEqual(0, values.Count); async Task trxFunc(int i) { using var trx = await kvl.BeginTransactionAsync(key); await kvl.Insert(key, "$.world", "[]"); await kvl.Insert(key, "$.world[#]", i); await trx.CommitAsync(); } } [TestMethod] public async Task TestMultiThreadedTransactionOnSameKeyOneThrows() { var kvl = KVLite.CreateJsonInMemory(); var key = Encoding.UTF8.GetBytes("key"); var value = JsonSerializer.Serialize(new {hello = "value"}); var arrayValues = Enumerable.Range(0, 100); await kvl.Add(key, value); var tasks = arrayValues .Select(trxFunc); var t = await Assert.ThrowsExceptionAsync<Exception>(() => Task.WhenAll(tasks)); var res = await kvl.Get(key); var element = JsonDocument.Parse(res.Head()).RootElement; var prop = element .EnumerateObject() .Find(x => x.Name == "world").Head(); var values = arrayValues.ToHashSet(); foreach(var i in prop.Value.EnumerateArray()) { values.Remove(i.GetInt32()); } Assert.AreEqual(1, values.Count); async Task trxFunc(int i) { if (i == 50) throw new Exception("Boom"); using var trx = await kvl.BeginTransactionAsync(key); await kvl.Insert(key, "$.world", "[]"); await kvl.Insert(key, "$.world[#]", i); await trx.CommitAsync(); } } } }
33.981928
99
0.526325
[ "MIT" ]
Birnsen/KVLite
tests/TransactionTests.cs
5,641
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; namespace SegundoParcial { [XmlInclude(typeof(Manzana))] public class Manzana:Fruta,ISerializable { #region Atributo public double precio; #endregion #region Propiedades public override bool TieneCarozo { get { return true; } } public string Tipo { get { return "Manzana"; } } public string RutaArchivo { get { return "Manzana.Xml"; } set { throw new NotImplementedException(); } } #endregion #region Constructor public Manzana() { } public Manzana(float peso, ConsoleColor color, double precio):base(peso,color) { this.precio = precio; } #endregion #region Metodos protected override string FrutaToString() { StringBuilder sb = new StringBuilder(); sb.AppendLine(base.FrutaToString()); sb.Append("Precio: " + this.precio); return sb.ToString(); } public override string ToString() { return this.FrutaToString(); } public bool SerializarXML() { try { using (XmlTextWriter escritor = new XmlTextWriter(this.RutaArchivo,Encoding.UTF8)) { XmlSerializer serializar = new XmlSerializer(typeof(Manzana)); serializar.Serialize(escritor, this); return true; } } catch (Exception ex) { Console.WriteLine(ex.Message); return false; } } #endregion } }
22.01087
98
0.495309
[ "MIT" ]
ezequielfreire007/EjerciciosLab2
SegundoParcial/SegundoParcial/Manzana.cs
2,027
C#
using System.Web; using System.Web.Mvc; using System.Web.WebPages; using RazorGenerator.Mvc; [assembly: WebActivatorEx.PostApplicationStartMethod(typeof(MAB.ContextInspector.TestHarness.App_Start.RazorGeneratorMvcStart), "Start")] namespace MAB.ContextInspector.TestHarness.App_Start { public static class RazorGeneratorMvcStart { public static void Start() { var engine = new PrecompiledMvcEngine(typeof(RazorGeneratorMvcStart).Assembly) { UsePhysicalViewsIfNewer = HttpContext.Current.Request.IsLocal }; ViewEngines.Engines.Insert(0, engine); // StartPage lookups are done by WebPages. VirtualPathFactoryManager.RegisterVirtualPathFactory(engine); } } }
34.590909
137
0.718791
[ "MIT" ]
markashleybell/MAB.ContextInspector
MAB.ContextInspector.TestHarness/App_Start/RazorGeneratorMvcStart.cs
761
C#
using System; using System.Collections.Generic; using System.Linq; namespace Island { public class Program { static void Main(string[] args) { var heights = Console.ReadLine() .Split(' ') .Select(int.Parse) .ToArray(); var maxArea = 0; var biggerColumnsOnLeftCounts = new int[heights.Length]; var columnsOnLeft = new Stack<int>(heights.Length); columnsOnLeft.Push(0); for (int i = 1; i < heights.Length; i++) { var current = heights[i]; var leftmostBiggerColumnIndex = i; while (columnsOnLeft.Count > 0 && heights[columnsOnLeft.Peek()] >= current) { var j = columnsOnLeft.Pop(); var rightCount = i - j; var area = (biggerColumnsOnLeftCounts[j] + rightCount) * heights[j]; if (area > maxArea) { maxArea = area; } } leftmostBiggerColumnIndex = columnsOnLeft.Count == 0 ? 0 : columnsOnLeft.Peek() + 1; biggerColumnsOnLeftCounts[i] = i - leftmostBiggerColumnIndex; columnsOnLeft.Push(i); } while (columnsOnLeft.Count > 0) { var j = columnsOnLeft.Pop(); var right = heights.Length - j; var area = (biggerColumnsOnLeftCounts[j] + right) * heights[j]; if (area > maxArea) { maxArea = area; } } Console.WriteLine(maxArea); } } }
30.614035
100
0.461891
[ "MIT" ]
NaskoVasilev/Algorithms
Exam - 29 May 2016/Exam29May2016/Island/Program.cs
1,747
C#
#region Copyright // // DotNetNuke® - http://www.dotnetnuke.com // Copyright (c) 2002-2017 // by DotNetNuke Corporation // // 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 DotNetNuke.Services.Localization; namespace DotNetNuke.Entities.Content.Workflow.Exceptions { public class WorkflowNameAlreadyExistsException : WorkflowException { public WorkflowNameAlreadyExistsException() : base(Localization.GetString("WorkflowNameAlreadyExistsException", Localization.ExceptionsResourceFile)) { } } }
45.657143
117
0.752816
[ "MIT" ]
Expasys/Expasys.Web.Platform
DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowNameAlreadyExistsException.cs
1,601
C#
using XenAdmin.Alerts; using XenAdmin.Network; using XenAdmin.Commands; using XenAdmin.Controls; using XenAdmin.Plugins; using XenAPI; using System; using System.Windows.Forms; using System.ComponentModel; namespace XenAdmin { partial class MainWindow { /// <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) { Program.Exiting = true; XenAdmin.Core.Clip.UnregisterClipboardViewer(); pluginManager.PluginsChanged -= pluginManager_PluginsChanged; pluginManager.Dispose(); OtherConfigAndTagsWatcher.DeregisterEventHandlers(); ConnectionsManager.History.CollectionChanged -= History_CollectionChanged; Alert.DeregisterAlertCollectionChanged(XenCenterAlerts_CollectionChanged); XenAdmin.Core.Updates.DeregisterCollectionChanged(Updates_CollectionChanged); ConnectionsManager.XenConnections.CollectionChanged -= XenConnection_CollectionChanged; Properties.Settings.Default.SettingChanging -= new System.Configuration.SettingChangingEventHandler(Default_SettingChanging); SearchPage.SearchChanged -= SearchPanel_SearchChanged; if (disposing && (components != null)) { components.Dispose(); log.Debug("MainWindow disoposing license timer"); if (licenseTimer != null) licenseTimer.Dispose(); } log.Debug("Before MainWindow base.Dispose()"); base.Dispose(disposing); log.Debug("After MainWindow base.Dispose()"); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainWindow)); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.navigationPane = new XenAdmin.Controls.MainWindowControls.NavigationPane(); this.TheTabControl = new System.Windows.Forms.TabControl(); this.TabPageHome = new System.Windows.Forms.TabPage(); this.TabPageGeneral = new System.Windows.Forms.TabPage(); this.TabPageBallooning = new System.Windows.Forms.TabPage(); this.TabPageBallooningUpsell = new System.Windows.Forms.TabPage(); this.TabPageConsole = new System.Windows.Forms.TabPage(); this.TabPageCvmConsole = new System.Windows.Forms.TabPage(); this.TabPageStorage = new System.Windows.Forms.TabPage(); this.TabPagePhysicalStorage = new System.Windows.Forms.TabPage(); this.TabPageSR = new System.Windows.Forms.TabPage(); this.TabPageNetwork = new System.Windows.Forms.TabPage(); this.TabPageNICs = new System.Windows.Forms.TabPage(); this.TabPagePeformance = new System.Windows.Forms.TabPage(); this.TabPageHA = new System.Windows.Forms.TabPage(); this.TabPageHAUpsell = new System.Windows.Forms.TabPage(); this.TabPageSnapshots = new System.Windows.Forms.TabPage(); this.snapshotPage = new XenAdmin.TabPages.SnapshotsPage(); this.TabPageWLB = new System.Windows.Forms.TabPage(); this.TabPageWLBUpsell = new System.Windows.Forms.TabPage(); this.TabPageAD = new System.Windows.Forms.TabPage(); this.TabPageADUpsell = new System.Windows.Forms.TabPage(); this.TabPageGPU = new System.Windows.Forms.TabPage(); this.TabPagePvs = new System.Windows.Forms.TabPage(); this.TabPageSearch = new System.Windows.Forms.TabPage(); this.TabPageDockerProcess = new System.Windows.Forms.TabPage(); this.TabPageDockerDetails = new System.Windows.Forms.TabPage(); this.alertPage = new XenAdmin.TabPages.AlertSummaryPage(); this.updatesPage = new XenAdmin.TabPages.ManageUpdatesPage(); this.eventsPage = new XenAdmin.TabPages.HistoryPage(); this.TitleBackPanel = new XenAdmin.Controls.GradientPanel.GradientPanel(); this.TitleIcon = new System.Windows.Forms.PictureBox(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.TitleLabel = new System.Windows.Forms.Label(); this.LicenseStatusTitleLabel = new System.Windows.Forms.Label(); this.toolTipContainer1 = new XenAdmin.Controls.ToolTipContainer(); this.loggedInLabel1 = new XenAdmin.Controls.LoggedInLabel(); this.ToolStrip = new XenAdmin.Controls.ToolStripEx(); this.backButton = new System.Windows.Forms.ToolStripSplitButton(); this.forwardButton = new System.Windows.Forms.ToolStripSplitButton(); this.toolStripSeparator17 = new System.Windows.Forms.ToolStripSeparator(); this.AddServerToolbarButton = new XenAdmin.Commands.CommandToolStripButton(); this.toolStripSeparator11 = new System.Windows.Forms.ToolStripSeparator(); this.AddPoolToolbarButton = new XenAdmin.Commands.CommandToolStripButton(); this.newStorageToolbarButton = new XenAdmin.Commands.CommandToolStripButton(); this.NewVmToolbarButton = new XenAdmin.Commands.CommandToolStripButton(); this.toolStripSeparator12 = new System.Windows.Forms.ToolStripSeparator(); this.shutDownToolStripButton = new XenAdmin.Commands.CommandToolStripButton(); this.powerOnHostToolStripButton = new XenAdmin.Commands.CommandToolStripButton(); this.startVMToolStripButton = new XenAdmin.Commands.CommandToolStripButton(); this.RebootToolbarButton = new XenAdmin.Commands.CommandToolStripButton(); this.resumeToolStripButton = new XenAdmin.Commands.CommandToolStripButton(); this.SuspendToolbarButton = new XenAdmin.Commands.CommandToolStripButton(); this.ForceShutdownToolbarButton = new XenAdmin.Commands.CommandToolStripButton(); this.ForceRebootToolbarButton = new XenAdmin.Commands.CommandToolStripButton(); this.stopContainerToolStripButton = new XenAdmin.Commands.CommandToolStripButton(); this.startContainerToolStripButton = new XenAdmin.Commands.CommandToolStripButton(); this.restartContainerToolStripButton = new XenAdmin.Commands.CommandToolStripButton(); this.resumeContainerToolStripButton = new XenAdmin.Commands.CommandToolStripButton(); this.pauseContainerToolStripButton = new XenAdmin.Commands.CommandToolStripButton(); this.statusToolTip = new System.Windows.Forms.ToolTip(this.components); this.ToolBarContextMenu = new System.Windows.Forms.ContextMenuStrip(this.components); this.ShowToolbarMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.FileImportVMToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.importSearchToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.toolStripSeparator21 = new System.Windows.Forms.ToolStripSeparator(); this.importSettingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.exportSettingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator31 = new System.Windows.Forms.ToolStripSeparator(); this.pluginItemsPlaceHolderToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.viewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.customTemplatesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.templatesToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.localStorageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.ShowHiddenObjectsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator24 = new System.Windows.Forms.ToolStripSeparator(); this.pluginItemsPlaceHolderToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolbarToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.poolToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.AddPoolToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator(); this.addServerToolStripMenuItem = new XenAdmin.Commands.AddHostToSelectedPoolToolStripMenuItem(); this.removeServerToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.poolReconnectAsToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.disconnectPoolToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.toolStripSeparator27 = new System.Windows.Forms.ToolStripSeparator(); this.virtualAppliancesToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.toolStripSeparator30 = new System.Windows.Forms.ToolStripSeparator(); this.highAvailabilityToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.disasterRecoveryToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.drConfigureToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.DrWizardToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.VMSnapshotScheduleToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.exportResourceReportPoolToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.wlbReportsToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.wlbDisconnectToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.toolStripSeparator9 = new System.Windows.Forms.ToolStripSeparator(); this.changePoolPasswordToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.deleteToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.toolStripSeparator26 = new System.Windows.Forms.ToolStripSeparator(); this.pluginItemsPlaceHolderToolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem(); this.PoolPropertiesToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.HostMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.AddHostToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.toolStripMenuItem11 = new System.Windows.Forms.ToolStripSeparator(); this.RebootHostToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.powerOnToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.ShutdownHostToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.restartToolstackToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.connectDisconnectToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.ReconnectToolStripMenuItem1 = new XenAdmin.Commands.CommandToolStripMenuItem(); this.DisconnectToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.reconnectAsToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator(); this.connectAllToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.disconnectAllToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.addServerToPoolMenuItem = new XenAdmin.Commands.AddSelectedHostToPoolToolStripMenuItem(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.backupToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.restoreFromBackupToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.toolStripSeparator23 = new System.Windows.Forms.ToolStripSeparator(); this.maintenanceModeToolStripMenuItem1 = new XenAdmin.Commands.CommandToolStripMenuItem(); this.controlDomainMemoryToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.RemoveCrashdumpsToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.HostPasswordToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.ChangeRootPasswordToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.forgetSavedPasswordToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.toolStripSeparator25 = new System.Windows.Forms.ToolStripSeparator(); this.destroyServerToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.removeHostToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.toolStripSeparator15 = new System.Windows.Forms.ToolStripSeparator(); this.pluginItemsPlaceHolderToolStripMenuItem3 = new System.Windows.Forms.ToolStripMenuItem(); this.ServerPropertiesToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.VMToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.NewVmToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.startShutdownToolStripMenuItem = new XenAdmin.Commands.VMLifeCycleToolStripMenuItem(); this.resumeOnToolStripMenuItem = new XenAdmin.Commands.ResumeVMOnHostToolStripMenuItem(); this.relocateToolStripMenuItem = new XenAdmin.Commands.MigrateVMToolStripMenuItem(); this.startOnHostToolStripMenuItem = new XenAdmin.Commands.StartVMOnHostToolStripMenuItem(); this.toolStripSeparator20 = new System.Windows.Forms.ToolStripSeparator(); this.assignSnapshotScheduleToolStripMenuItem = new XenAdmin.Commands.AssignGroupToolStripMenuItemVMSS(); this.assignToVirtualApplianceToolStripMenuItem = new XenAdmin.Commands.AssignGroupToolStripMenuItemVM_appliance(); this.toolStripMenuItem9 = new System.Windows.Forms.ToolStripSeparator(); this.copyVMtoSharedStorageMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.MoveVMToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.snapshotToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.convertToTemplateToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.exportToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.enablePVSReadcachingToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.disablePVSReadcachingToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.toolStripMenuItem12 = new System.Windows.Forms.ToolStripSeparator(); this.installToolsToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.sendCtrlAltDelToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator(); this.uninstallToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.toolStripSeparator10 = new System.Windows.Forms.ToolStripSeparator(); this.pluginItemsPlaceHolderToolStripMenuItem4 = new System.Windows.Forms.ToolStripMenuItem(); this.VMPropertiesToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.toolStripMenuItem8 = new System.Windows.Forms.ToolStripSeparator(); this.StorageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.AddStorageToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.toolStripSeparator22 = new System.Windows.Forms.ToolStripSeparator(); this.RepairStorageToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.DefaultSRToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.virtualDisksToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.addVirtualDiskToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.attachVirtualDiskToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.reclaimFreedSpacetripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.toolStripSeparator19 = new System.Windows.Forms.ToolStripSeparator(); this.DetachStorageToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.ReattachStorageRepositoryToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.ForgetStorageRepositoryToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.DestroyStorageRepositoryToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.toolStripSeparator18 = new System.Windows.Forms.ToolStripSeparator(); this.pluginItemsPlaceHolderToolStripMenuItem5 = new System.Windows.Forms.ToolStripMenuItem(); this.SRPropertiesToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.templatesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.CreateVmFromTemplateToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.newVMFromTemplateToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.InstantVmToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.toolStripSeparator29 = new System.Windows.Forms.ToolStripSeparator(); this.exportTemplateToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.duplicateTemplateToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.toolStripSeparator16 = new System.Windows.Forms.ToolStripSeparator(); this.uninstallTemplateToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.toolStripSeparator28 = new System.Windows.Forms.ToolStripSeparator(); this.pluginItemsPlaceHolderToolStripMenuItem6 = new System.Windows.Forms.ToolStripMenuItem(); this.templatePropertiesToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.bugToolToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.healthCheckToolStripMenuItem1 = new XenAdmin.Commands.CommandToolStripMenuItem(); this.toolStripSeparator14 = new System.Windows.Forms.ToolStripSeparator(); //this.LicenseManagerMenuItem = new System.Windows.Forms.ToolStripMenuItem(); //this.toolStripSeparator13 = new System.Windows.Forms.ToolStripSeparator(); //this.installNewUpdateToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); //this.rollingUpgradeToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); //this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator(); this.pluginItemsPlaceHolderToolStripMenuItem7 = new System.Windows.Forms.ToolStripMenuItem(); this.preferencesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.windowToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.pluginItemsPlaceHolderToolStripMenuItem9 = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpTopicsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpContextMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem15 = new System.Windows.Forms.ToolStripSeparator(); this.viewApplicationLogToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem17 = new System.Windows.Forms.ToolStripSeparator(); this.xenSourceOnTheWebToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.xenCenterPluginsOnlineToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator(); this.pluginItemsPlaceHolderToolStripMenuItem8 = new System.Windows.Forms.ToolStripMenuItem(); this.aboutXenSourceAdminToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.MainMenuBar = new XenAdmin.Controls.MenuStripEx(); this.securityGroupsToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); this.MenuPanel = new System.Windows.Forms.Panel(); this.StatusStrip = new System.Windows.Forms.StatusStrip(); this.statusLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.statusProgressBar = new System.Windows.Forms.ToolStripProgressBar(); this.TabPageUSB = new System.Windows.Forms.TabPage(); this.disableCbtToolStripMenuItem = new XenAdmin.Commands.CommandToolStripMenuItem(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.TheTabControl.SuspendLayout(); this.TabPageSnapshots.SuspendLayout(); this.TitleBackPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.TitleIcon)).BeginInit(); this.tableLayoutPanel1.SuspendLayout(); this.toolTipContainer1.SuspendLayout(); this.ToolStrip.SuspendLayout(); this.ToolBarContextMenu.SuspendLayout(); this.MainMenuBar.SuspendLayout(); this.MenuPanel.SuspendLayout(); this.StatusStrip.SuspendLayout(); this.SuspendLayout(); // // splitContainer1 // this.splitContainer1.BackColor = System.Drawing.SystemColors.Control; resources.ApplyResources(this.splitContainer1, "splitContainer1"); this.splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel1; this.splitContainer1.Name = "splitContainer1"; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this.navigationPane); resources.ApplyResources(this.splitContainer1.Panel1, "splitContainer1.Panel1"); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.BackColor = System.Drawing.SystemColors.Control; this.splitContainer1.Panel2.Controls.Add(this.TheTabControl); this.splitContainer1.Panel2.Controls.Add(this.alertPage); this.splitContainer1.Panel2.Controls.Add(this.updatesPage); this.splitContainer1.Panel2.Controls.Add(this.eventsPage); this.splitContainer1.Panel2.Controls.Add(this.TitleBackPanel); resources.ApplyResources(this.splitContainer1.Panel2, "splitContainer1.Panel2"); this.splitContainer1.SplitterMoved += new System.Windows.Forms.SplitterEventHandler(this.splitContainer1_SplitterMoved); // // navigationPane // resources.ApplyResources(this.navigationPane, "navigationPane"); this.navigationPane.Name = "navigationPane"; this.navigationPane.NavigationModeChanged += new System.Action<XenAdmin.Controls.MainWindowControls.NavigationPane.NavigationMode>(this.navigationPane_NavigationModeChanged); this.navigationPane.NotificationsSubModeChanged += new System.Action<XenAdmin.Controls.MainWindowControls.NotificationsSubModeItem>(this.navigationPane_NotificationsSubModeChanged); this.navigationPane.TreeViewSelectionChanged += new System.Action(this.navigationPane_TreeViewSelectionChanged); this.navigationPane.TreeNodeBeforeSelected += new System.Action(this.navigationPane_TreeNodeBeforeSelected); this.navigationPane.TreeNodeClicked += new System.Action(this.navigationPane_TreeNodeClicked); this.navigationPane.TreeNodeRightClicked += new System.Action(this.navigationPane_TreeNodeRightClicked); this.navigationPane.TreeViewRefreshed += new System.Action(this.navigationPane_TreeViewRefreshed); this.navigationPane.TreeViewRefreshSuspended += new System.Action(this.navigationPane_TreeViewRefreshSuspended); this.navigationPane.TreeViewRefreshResumed += new System.Action(this.navigationPane_TreeViewRefreshResumed); // // TheTabControl // resources.ApplyResources(this.TheTabControl, "TheTabControl"); this.TheTabControl.Controls.Add(this.TabPageHome); this.TheTabControl.Controls.Add(this.TabPageGeneral); this.TheTabControl.Controls.Add(this.TabPageBallooning); this.TheTabControl.Controls.Add(this.TabPageBallooningUpsell); this.TheTabControl.Controls.Add(this.TabPageConsole); this.TheTabControl.Controls.Add(this.TabPageCvmConsole); this.TheTabControl.Controls.Add(this.TabPageStorage); this.TheTabControl.Controls.Add(this.TabPagePhysicalStorage); this.TheTabControl.Controls.Add(this.TabPageSR); this.TheTabControl.Controls.Add(this.TabPageNetwork); this.TheTabControl.Controls.Add(this.TabPageNICs); this.TheTabControl.Controls.Add(this.TabPagePeformance); this.TheTabControl.Controls.Add(this.TabPageHA); this.TheTabControl.Controls.Add(this.TabPageHAUpsell); this.TheTabControl.Controls.Add(this.TabPageSnapshots); this.TheTabControl.Controls.Add(this.TabPageWLB); this.TheTabControl.Controls.Add(this.TabPageWLBUpsell); this.TheTabControl.Controls.Add(this.TabPageAD); this.TheTabControl.Controls.Add(this.TabPageADUpsell); this.TheTabControl.Controls.Add(this.TabPageGPU); this.TheTabControl.Controls.Add(this.TabPagePvs); this.TheTabControl.Controls.Add(this.TabPageSearch); this.TheTabControl.Controls.Add(this.TabPageDockerProcess); this.TheTabControl.Controls.Add(this.TabPageDockerDetails); this.TheTabControl.Controls.Add(this.TabPageUSB); this.TheTabControl.Name = "TheTabControl"; this.TheTabControl.SelectedIndex = 4; // // TabPageHome // resources.ApplyResources(this.TabPageHome, "TabPageHome"); this.TabPageHome.Name = "TabPageHome"; this.TabPageHome.UseVisualStyleBackColor = true; // // TabPageGeneral // resources.ApplyResources(this.TabPageGeneral, "TabPageGeneral"); this.TabPageGeneral.Name = "TabPageGeneral"; this.TabPageGeneral.UseVisualStyleBackColor = true; // // TabPageBallooning // resources.ApplyResources(this.TabPageBallooning, "TabPageBallooning"); this.TabPageBallooning.Name = "TabPageBallooning"; this.TabPageBallooning.UseVisualStyleBackColor = true; // // TabPageBallooningUpsell // resources.ApplyResources(this.TabPageBallooningUpsell, "TabPageBallooningUpsell"); this.TabPageBallooningUpsell.Name = "TabPageBallooningUpsell"; this.TabPageBallooningUpsell.UseVisualStyleBackColor = true; // // TabPageConsole // resources.ApplyResources(this.TabPageConsole, "TabPageConsole"); this.TabPageConsole.Name = "TabPageConsole"; this.TabPageConsole.UseVisualStyleBackColor = true; // // TabPageCvmConsole // resources.ApplyResources(this.TabPageCvmConsole, "TabPageCvmConsole"); this.TabPageCvmConsole.Name = "TabPageCvmConsole"; this.TabPageCvmConsole.UseVisualStyleBackColor = true; // // TabPageStorage // resources.ApplyResources(this.TabPageStorage, "TabPageStorage"); this.TabPageStorage.Name = "TabPageStorage"; this.TabPageStorage.UseVisualStyleBackColor = true; // // TabPagePhysicalStorage // resources.ApplyResources(this.TabPagePhysicalStorage, "TabPagePhysicalStorage"); this.TabPagePhysicalStorage.Name = "TabPagePhysicalStorage"; this.TabPagePhysicalStorage.UseVisualStyleBackColor = true; // // TabPageSR // resources.ApplyResources(this.TabPageSR, "TabPageSR"); this.TabPageSR.Name = "TabPageSR"; this.TabPageSR.UseVisualStyleBackColor = true; // // TabPageNetwork // resources.ApplyResources(this.TabPageNetwork, "TabPageNetwork"); this.TabPageNetwork.Name = "TabPageNetwork"; this.TabPageNetwork.UseVisualStyleBackColor = true; // // TabPageNICs // resources.ApplyResources(this.TabPageNICs, "TabPageNICs"); this.TabPageNICs.Name = "TabPageNICs"; this.TabPageNICs.UseVisualStyleBackColor = true; // // TabPagePeformance // resources.ApplyResources(this.TabPagePeformance, "TabPagePeformance"); this.TabPagePeformance.Name = "TabPagePeformance"; this.TabPagePeformance.UseVisualStyleBackColor = true; // // TabPageHA // resources.ApplyResources(this.TabPageHA, "TabPageHA"); this.TabPageHA.Name = "TabPageHA"; this.TabPageHA.UseVisualStyleBackColor = true; // // TabPageHAUpsell // resources.ApplyResources(this.TabPageHAUpsell, "TabPageHAUpsell"); this.TabPageHAUpsell.Name = "TabPageHAUpsell"; this.TabPageHAUpsell.UseVisualStyleBackColor = true; // // TabPageSnapshots // this.TabPageSnapshots.Controls.Add(this.snapshotPage); resources.ApplyResources(this.TabPageSnapshots, "TabPageSnapshots"); this.TabPageSnapshots.Name = "TabPageSnapshots"; this.TabPageSnapshots.UseVisualStyleBackColor = true; // // snapshotPage // resources.ApplyResources(this.snapshotPage, "snapshotPage"); this.snapshotPage.Name = "snapshotPage"; this.snapshotPage.VM = null; // // TabPageWLB // resources.ApplyResources(this.TabPageWLB, "TabPageWLB"); this.TabPageWLB.Name = "TabPageWLB"; this.TabPageWLB.UseVisualStyleBackColor = true; // // TabPageWLBUpsell // resources.ApplyResources(this.TabPageWLBUpsell, "TabPageWLBUpsell"); this.TabPageWLBUpsell.Name = "TabPageWLBUpsell"; this.TabPageWLBUpsell.UseVisualStyleBackColor = true; // // TabPageAD // resources.ApplyResources(this.TabPageAD, "TabPageAD"); this.TabPageAD.Name = "TabPageAD"; this.TabPageAD.UseVisualStyleBackColor = true; // // TabPageADUpsell // resources.ApplyResources(this.TabPageADUpsell, "TabPageADUpsell"); this.TabPageADUpsell.Name = "TabPageADUpsell"; this.TabPageADUpsell.UseVisualStyleBackColor = true; // // TabPageGPU // resources.ApplyResources(this.TabPageGPU, "TabPageGPU"); this.TabPageGPU.Name = "TabPageGPU"; this.TabPageGPU.UseVisualStyleBackColor = true; // // TabPagePvs // resources.ApplyResources(this.TabPagePvs, "TabPagePvs"); this.TabPagePvs.Name = "TabPagePvs"; this.TabPagePvs.UseVisualStyleBackColor = true; // // TabPageSearch // resources.ApplyResources(this.TabPageSearch, "TabPageSearch"); this.TabPageSearch.Name = "TabPageSearch"; this.TabPageSearch.UseVisualStyleBackColor = true; // // TabPageDockerProcess // resources.ApplyResources(this.TabPageDockerProcess, "TabPageDockerProcess"); this.TabPageDockerProcess.Name = "TabPageDockerProcess"; this.TabPageDockerProcess.UseVisualStyleBackColor = true; // // TabPageDockerDetails // resources.ApplyResources(this.TabPageDockerDetails, "TabPageDockerDetails"); this.TabPageDockerDetails.Name = "TabPageDockerDetails"; this.TabPageDockerDetails.UseVisualStyleBackColor = true; // // alertPage // resources.ApplyResources(this.alertPage, "alertPage"); this.alertPage.BackColor = System.Drawing.SystemColors.Window; this.alertPage.Name = "alertPage"; // // updatesPage // resources.ApplyResources(this.updatesPage, "updatesPage"); this.updatesPage.BackColor = System.Drawing.SystemColors.Window; this.updatesPage.Name = "updatesPage"; // // eventsPage // resources.ApplyResources(this.eventsPage, "eventsPage"); this.eventsPage.BackColor = System.Drawing.SystemColors.Window; this.eventsPage.Name = "eventsPage"; // // TitleBackPanel // resources.ApplyResources(this.TitleBackPanel, "TitleBackPanel"); this.TitleBackPanel.BackColor = System.Drawing.Color.Transparent; this.TitleBackPanel.Controls.Add(this.TitleIcon); this.TitleBackPanel.Controls.Add(this.tableLayoutPanel1); this.TitleBackPanel.Name = "TitleBackPanel"; this.TitleBackPanel.Scheme = XenAdmin.Controls.GradientPanel.GradientPanel.Schemes.Title; // // TitleIcon // resources.ApplyResources(this.TitleIcon, "TitleIcon"); this.TitleIcon.Name = "TitleIcon"; this.TitleIcon.TabStop = false; // // tableLayoutPanel1 // resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1"); this.tableLayoutPanel1.Controls.Add(this.TitleLabel, 0, 0); this.tableLayoutPanel1.Controls.Add(this.LicenseStatusTitleLabel, 1, 0); this.tableLayoutPanel1.Controls.Add(this.toolTipContainer1, 3, 0); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; // // TitleLabel // resources.ApplyResources(this.TitleLabel, "TitleLabel"); this.TitleLabel.AutoEllipsis = true; this.TitleLabel.ForeColor = System.Drawing.SystemColors.HighlightText; this.TitleLabel.Name = "TitleLabel"; this.TitleLabel.UseMnemonic = false; // // LicenseStatusTitleLabel // resources.ApplyResources(this.LicenseStatusTitleLabel, "LicenseStatusTitleLabel"); this.LicenseStatusTitleLabel.ForeColor = System.Drawing.SystemColors.HighlightText; this.LicenseStatusTitleLabel.Name = "LicenseStatusTitleLabel"; this.LicenseStatusTitleLabel.UseMnemonic = false; // // toolTipContainer1 // resources.ApplyResources(this.toolTipContainer1, "toolTipContainer1"); this.toolTipContainer1.Controls.Add(this.loggedInLabel1); this.toolTipContainer1.Name = "toolTipContainer1"; // // loggedInLabel1 // resources.ApplyResources(this.loggedInLabel1, "loggedInLabel1"); this.loggedInLabel1.BackColor = System.Drawing.Color.Transparent; this.loggedInLabel1.Connection = null; this.loggedInLabel1.Name = "loggedInLabel1"; // // ToolStrip // resources.ApplyResources(this.ToolStrip, "ToolStrip"); this.ToolStrip.ClickThrough = true; this.ToolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.ToolStrip.ImageScalingSize = new System.Drawing.Size(24, 24); this.ToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.backButton, this.forwardButton, this.toolStripSeparator17, this.AddServerToolbarButton, this.toolStripSeparator11, this.AddPoolToolbarButton, this.newStorageToolbarButton, this.NewVmToolbarButton, this.toolStripSeparator12, this.shutDownToolStripButton, this.powerOnHostToolStripButton, this.startVMToolStripButton, this.RebootToolbarButton, this.resumeToolStripButton, this.SuspendToolbarButton, this.ForceShutdownToolbarButton, this.ForceRebootToolbarButton, this.stopContainerToolStripButton, this.startContainerToolStripButton, this.restartContainerToolStripButton, this.resumeContainerToolStripButton, this.pauseContainerToolStripButton}); this.ToolStrip.Name = "ToolStrip"; this.ToolStrip.Stretch = true; this.ToolStrip.TabStop = true; this.ToolStrip.MouseClick += new System.Windows.Forms.MouseEventHandler(this.MainMenuBar_MouseClick); // // backButton // this.backButton.Image = global::XenAdmin.Properties.Resources._001_Back_h32bit_24; resources.ApplyResources(this.backButton, "backButton"); this.backButton.Name = "backButton"; this.backButton.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never; this.backButton.ButtonClick += new System.EventHandler(this.backButton_Click); this.backButton.DropDownOpening += new System.EventHandler(this.backButton_DropDownOpening); // // forwardButton // this.forwardButton.Image = global::XenAdmin.Properties.Resources._001_Forward_h32bit_24; resources.ApplyResources(this.forwardButton, "forwardButton"); this.forwardButton.Margin = new System.Windows.Forms.Padding(0, 2, 0, 2); this.forwardButton.Name = "forwardButton"; this.forwardButton.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never; this.forwardButton.ButtonClick += new System.EventHandler(this.forwardButton_Click); this.forwardButton.DropDownOpening += new System.EventHandler(this.forwardButton_DropDownOpening); // // toolStripSeparator17 // resources.ApplyResources(this.toolStripSeparator17, "toolStripSeparator17"); this.toolStripSeparator17.Margin = new System.Windows.Forms.Padding(2, 0, 7, 0); this.toolStripSeparator17.Name = "toolStripSeparator17"; this.toolStripSeparator17.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never; // // AddServerToolbarButton // this.AddServerToolbarButton.Command = new XenAdmin.Commands.AddHostCommand(); resources.ApplyResources(this.AddServerToolbarButton, "AddServerToolbarButton"); this.AddServerToolbarButton.Image = global::XenAdmin.Properties.Resources._000_AddApplicationServer_h32bit_24; this.AddServerToolbarButton.Name = "AddServerToolbarButton"; this.AddServerToolbarButton.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never; // // toolStripSeparator11 // resources.ApplyResources(this.toolStripSeparator11, "toolStripSeparator11"); this.toolStripSeparator11.Margin = new System.Windows.Forms.Padding(2, 0, 7, 0); this.toolStripSeparator11.Name = "toolStripSeparator11"; this.toolStripSeparator11.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never; // // AddPoolToolbarButton // this.AddPoolToolbarButton.Command = new XenAdmin.Commands.NewPoolCommand(); resources.ApplyResources(this.AddPoolToolbarButton, "AddPoolToolbarButton"); this.AddPoolToolbarButton.Image = global::XenAdmin.Properties.Resources._000_PoolNew_h32bit_24; this.AddPoolToolbarButton.Name = "AddPoolToolbarButton"; this.AddPoolToolbarButton.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never; // // newStorageToolbarButton // this.newStorageToolbarButton.Command = new XenAdmin.Commands.NewSRCommand(); resources.ApplyResources(this.newStorageToolbarButton, "newStorageToolbarButton"); this.newStorageToolbarButton.Image = global::XenAdmin.Properties.Resources._000_NewStorage_h32bit_24; this.newStorageToolbarButton.Name = "newStorageToolbarButton"; this.newStorageToolbarButton.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never; // // NewVmToolbarButton // this.NewVmToolbarButton.Command = new XenAdmin.Commands.NewVMCommand(); resources.ApplyResources(this.NewVmToolbarButton, "NewVmToolbarButton"); this.NewVmToolbarButton.Image = global::XenAdmin.Properties.Resources._000_CreateVM_h32bit_24; this.NewVmToolbarButton.Name = "NewVmToolbarButton"; this.NewVmToolbarButton.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never; // // toolStripSeparator12 // resources.ApplyResources(this.toolStripSeparator12, "toolStripSeparator12"); this.toolStripSeparator12.Margin = new System.Windows.Forms.Padding(2, 0, 7, 0); this.toolStripSeparator12.Name = "toolStripSeparator12"; // // shutDownToolStripButton // this.shutDownToolStripButton.Command = new XenAdmin.Commands.ShutDownCommand(); resources.ApplyResources(this.shutDownToolStripButton, "shutDownToolStripButton"); this.shutDownToolStripButton.Name = "shutDownToolStripButton"; // // powerOnHostToolStripButton // this.powerOnHostToolStripButton.Command = new XenAdmin.Commands.PowerOnHostCommand(); resources.ApplyResources(this.powerOnHostToolStripButton, "powerOnHostToolStripButton"); this.powerOnHostToolStripButton.Name = "powerOnHostToolStripButton"; // // startVMToolStripButton // this.startVMToolStripButton.Command = new XenAdmin.Commands.StartVMCommand(); resources.ApplyResources(this.startVMToolStripButton, "startVMToolStripButton"); this.startVMToolStripButton.Name = "startVMToolStripButton"; // // RebootToolbarButton // this.RebootToolbarButton.Command = new XenAdmin.Commands.RebootCommand(); resources.ApplyResources(this.RebootToolbarButton, "RebootToolbarButton"); this.RebootToolbarButton.Name = "RebootToolbarButton"; // // resumeToolStripButton // this.resumeToolStripButton.Command = new XenAdmin.Commands.ResumeVMCommand(); resources.ApplyResources(this.resumeToolStripButton, "resumeToolStripButton"); this.resumeToolStripButton.Image = global::XenAdmin.Properties.Resources._000_Paused_h32bit_24; this.resumeToolStripButton.Name = "resumeToolStripButton"; // // SuspendToolbarButton // this.SuspendToolbarButton.Command = new XenAdmin.Commands.SuspendVMCommand(); resources.ApplyResources(this.SuspendToolbarButton, "SuspendToolbarButton"); this.SuspendToolbarButton.Image = global::XenAdmin.Properties.Resources._000_Paused_h32bit_24; this.SuspendToolbarButton.Name = "SuspendToolbarButton"; // // ForceShutdownToolbarButton // this.ForceShutdownToolbarButton.Command = new XenAdmin.Commands.ForceVMShutDownCommand(); resources.ApplyResources(this.ForceShutdownToolbarButton, "ForceShutdownToolbarButton"); this.ForceShutdownToolbarButton.Image = global::XenAdmin.Properties.Resources._001_ForceShutDown_h32bit_24; this.ForceShutdownToolbarButton.Name = "ForceShutdownToolbarButton"; // // ForceRebootToolbarButton // this.ForceRebootToolbarButton.Command = new XenAdmin.Commands.ForceVMRebootCommand(); resources.ApplyResources(this.ForceRebootToolbarButton, "ForceRebootToolbarButton"); this.ForceRebootToolbarButton.Image = global::XenAdmin.Properties.Resources._001_ForceReboot_h32bit_24; this.ForceRebootToolbarButton.Name = "ForceRebootToolbarButton"; // // stopContainerToolStripButton // this.stopContainerToolStripButton.Command = new XenAdmin.Commands.StopDockerContainerCommand(); resources.ApplyResources(this.stopContainerToolStripButton, "stopContainerToolStripButton"); this.stopContainerToolStripButton.Image = global::XenAdmin.Properties.Resources._001_ShutDown_h32bit_24; this.stopContainerToolStripButton.Name = "stopContainerToolStripButton"; // // startContainerToolStripButton // this.startContainerToolStripButton.Command = new XenAdmin.Commands.StartDockerContainerCommand(); resources.ApplyResources(this.startContainerToolStripButton, "startContainerToolStripButton"); this.startContainerToolStripButton.Image = global::XenAdmin.Properties.Resources._001_PowerOn_h32bit_24; this.startContainerToolStripButton.Name = "startContainerToolStripButton"; // // restartContainerToolStripButton // this.restartContainerToolStripButton.Command = new XenAdmin.Commands.RestartDockerContainerCommand(); resources.ApplyResources(this.restartContainerToolStripButton, "restartContainerToolStripButton"); this.restartContainerToolStripButton.Image = global::XenAdmin.Properties.Resources._001_Reboot_h32bit_24; this.restartContainerToolStripButton.Name = "restartContainerToolStripButton"; // // resumeContainerToolStripButton // this.resumeContainerToolStripButton.Command = new XenAdmin.Commands.ResumeDockerContainerCommand(); resources.ApplyResources(this.resumeContainerToolStripButton, "resumeContainerToolStripButton"); this.resumeContainerToolStripButton.Image = global::XenAdmin.Properties.Resources._000_Resumed_h32bit_24; this.resumeContainerToolStripButton.Name = "resumeContainerToolStripButton"; // // pauseContainerToolStripButton // this.pauseContainerToolStripButton.Command = new XenAdmin.Commands.PauseDockerContainerCommand(); resources.ApplyResources(this.pauseContainerToolStripButton, "pauseContainerToolStripButton"); this.pauseContainerToolStripButton.Image = global::XenAdmin.Properties.Resources._000_Paused_h32bit_24; this.pauseContainerToolStripButton.Name = "pauseContainerToolStripButton"; // // ToolBarContextMenu // this.ToolBarContextMenu.ImageScalingSize = new System.Drawing.Size(40, 40); this.ToolBarContextMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.ShowToolbarMenuItem}); this.ToolBarContextMenu.Name = "ToolBarContextMenu"; resources.ApplyResources(this.ToolBarContextMenu, "ToolBarContextMenu"); // // ShowToolbarMenuItem // this.ShowToolbarMenuItem.Checked = true; this.ShowToolbarMenuItem.CheckOnClick = true; this.ShowToolbarMenuItem.CheckState = System.Windows.Forms.CheckState.Checked; this.ShowToolbarMenuItem.Name = "ShowToolbarMenuItem"; resources.ApplyResources(this.ShowToolbarMenuItem, "ShowToolbarMenuItem"); this.ShowToolbarMenuItem.Click += new System.EventHandler(this.ShowToolbarMenuItem_Click); // // fileToolStripMenuItem // this.fileToolStripMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.FileImportVMToolStripMenuItem, this.importSearchToolStripMenuItem, this.toolStripSeparator21, this.importSettingsToolStripMenuItem, this.exportSettingsToolStripMenuItem, this.toolStripSeparator31, this.pluginItemsPlaceHolderToolStripMenuItem1, this.exitToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; resources.ApplyResources(this.fileToolStripMenuItem, "fileToolStripMenuItem"); // // FileImportVMToolStripMenuItem // this.FileImportVMToolStripMenuItem.Command = new XenAdmin.Commands.ImportCommand(); this.FileImportVMToolStripMenuItem.Name = "FileImportVMToolStripMenuItem"; resources.ApplyResources(this.FileImportVMToolStripMenuItem, "FileImportVMToolStripMenuItem"); // // importSearchToolStripMenuItem // this.importSearchToolStripMenuItem.Command = new XenAdmin.Commands.ImportSearchCommand(); this.importSearchToolStripMenuItem.Name = "importSearchToolStripMenuItem"; resources.ApplyResources(this.importSearchToolStripMenuItem, "importSearchToolStripMenuItem"); // // toolStripSeparator21 // this.toolStripSeparator21.Name = "toolStripSeparator21"; resources.ApplyResources(this.toolStripSeparator21, "toolStripSeparator21"); // // importSettingsToolStripMenuItem // this.importSettingsToolStripMenuItem.Name = "importSettingsToolStripMenuItem"; resources.ApplyResources(this.importSettingsToolStripMenuItem, "importSettingsToolStripMenuItem"); this.importSettingsToolStripMenuItem.Click += new System.EventHandler(this.importSettingsToolStripMenuItem_Click); // // exportSettingsToolStripMenuItem // this.exportSettingsToolStripMenuItem.Name = "exportSettingsToolStripMenuItem"; resources.ApplyResources(this.exportSettingsToolStripMenuItem, "exportSettingsToolStripMenuItem"); this.exportSettingsToolStripMenuItem.Click += new System.EventHandler(this.exportSettingsToolStripMenuItem_Click); // // toolStripSeparator31 // this.toolStripSeparator31.Name = "toolStripSeparator31"; resources.ApplyResources(this.toolStripSeparator31, "toolStripSeparator31"); // // pluginItemsPlaceHolderToolStripMenuItem1 // this.pluginItemsPlaceHolderToolStripMenuItem1.Name = "pluginItemsPlaceHolderToolStripMenuItem1"; resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem1, "pluginItemsPlaceHolderToolStripMenuItem1"); // // exitToolStripMenuItem // this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; resources.ApplyResources(this.exitToolStripMenuItem, "exitToolStripMenuItem"); this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click); // // viewToolStripMenuItem // this.viewToolStripMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.viewToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.customTemplatesToolStripMenuItem, this.templatesToolStripMenuItem1, this.localStorageToolStripMenuItem, this.ShowHiddenObjectsToolStripMenuItem, this.toolStripSeparator24, this.pluginItemsPlaceHolderToolStripMenuItem, this.toolbarToolStripMenuItem}); this.viewToolStripMenuItem.Name = "viewToolStripMenuItem"; resources.ApplyResources(this.viewToolStripMenuItem, "viewToolStripMenuItem"); // // customTemplatesToolStripMenuItem // this.customTemplatesToolStripMenuItem.Name = "customTemplatesToolStripMenuItem"; resources.ApplyResources(this.customTemplatesToolStripMenuItem, "customTemplatesToolStripMenuItem"); this.customTemplatesToolStripMenuItem.Click += new System.EventHandler(this.customTemplatesToolStripMenuItem_Click); // // templatesToolStripMenuItem1 // this.templatesToolStripMenuItem1.Name = "templatesToolStripMenuItem1"; resources.ApplyResources(this.templatesToolStripMenuItem1, "templatesToolStripMenuItem1"); this.templatesToolStripMenuItem1.Click += new System.EventHandler(this.templatesToolStripMenuItem1_Click); // // localStorageToolStripMenuItem // this.localStorageToolStripMenuItem.Name = "localStorageToolStripMenuItem"; resources.ApplyResources(this.localStorageToolStripMenuItem, "localStorageToolStripMenuItem"); this.localStorageToolStripMenuItem.Click += new System.EventHandler(this.localStorageToolStripMenuItem_Click); // // ShowHiddenObjectsToolStripMenuItem // this.ShowHiddenObjectsToolStripMenuItem.Name = "ShowHiddenObjectsToolStripMenuItem"; resources.ApplyResources(this.ShowHiddenObjectsToolStripMenuItem, "ShowHiddenObjectsToolStripMenuItem"); this.ShowHiddenObjectsToolStripMenuItem.Click += new System.EventHandler(this.ShowHiddenObjectsToolStripMenuItem_Click); // // toolStripSeparator24 // this.toolStripSeparator24.Name = "toolStripSeparator24"; resources.ApplyResources(this.toolStripSeparator24, "toolStripSeparator24"); // // pluginItemsPlaceHolderToolStripMenuItem // this.pluginItemsPlaceHolderToolStripMenuItem.Name = "pluginItemsPlaceHolderToolStripMenuItem"; resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem, "pluginItemsPlaceHolderToolStripMenuItem"); // // toolbarToolStripMenuItem // this.toolbarToolStripMenuItem.Name = "toolbarToolStripMenuItem"; resources.ApplyResources(this.toolbarToolStripMenuItem, "toolbarToolStripMenuItem"); this.toolbarToolStripMenuItem.Click += new System.EventHandler(this.ShowToolbarMenuItem_Click); // // poolToolStripMenuItem // this.poolToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.AddPoolToolStripMenuItem, this.toolStripSeparator8, this.addServerToolStripMenuItem, this.removeServerToolStripMenuItem, this.poolReconnectAsToolStripMenuItem, this.disconnectPoolToolStripMenuItem, this.toolStripSeparator27, this.virtualAppliancesToolStripMenuItem, this.toolStripSeparator30, this.highAvailabilityToolStripMenuItem, this.disasterRecoveryToolStripMenuItem, this.VMSnapshotScheduleToolStripMenuItem, this.exportResourceReportPoolToolStripMenuItem, this.wlbReportsToolStripMenuItem, this.wlbDisconnectToolStripMenuItem, this.toolStripSeparator9, this.changePoolPasswordToolStripMenuItem, this.toolStripMenuItem1, this.deleteToolStripMenuItem, this.toolStripSeparator26, this.pluginItemsPlaceHolderToolStripMenuItem2, this.PoolPropertiesToolStripMenuItem}); this.poolToolStripMenuItem.Name = "poolToolStripMenuItem"; resources.ApplyResources(this.poolToolStripMenuItem, "poolToolStripMenuItem"); // // AddPoolToolStripMenuItem // this.AddPoolToolStripMenuItem.Command = new XenAdmin.Commands.NewPoolCommand(); this.AddPoolToolStripMenuItem.Image = global::XenAdmin.Properties.Resources._000_PoolNew_h32bit_16; this.AddPoolToolStripMenuItem.Name = "AddPoolToolStripMenuItem"; resources.ApplyResources(this.AddPoolToolStripMenuItem, "AddPoolToolStripMenuItem"); // // toolStripSeparator8 // this.toolStripSeparator8.Name = "toolStripSeparator8"; resources.ApplyResources(this.toolStripSeparator8, "toolStripSeparator8"); // // addServerToolStripMenuItem // this.addServerToolStripMenuItem.Name = "addServerToolStripMenuItem"; resources.ApplyResources(this.addServerToolStripMenuItem, "addServerToolStripMenuItem"); // // removeServerToolStripMenuItem // this.removeServerToolStripMenuItem.Command = new XenAdmin.Commands.RemoveHostFromPoolCommand(); this.removeServerToolStripMenuItem.Name = "removeServerToolStripMenuItem"; resources.ApplyResources(this.removeServerToolStripMenuItem, "removeServerToolStripMenuItem"); // // poolReconnectAsToolStripMenuItem // this.poolReconnectAsToolStripMenuItem.Command = new XenAdmin.Commands.PoolReconnectAsCommand(); this.poolReconnectAsToolStripMenuItem.Name = "poolReconnectAsToolStripMenuItem"; resources.ApplyResources(this.poolReconnectAsToolStripMenuItem, "poolReconnectAsToolStripMenuItem"); // // disconnectPoolToolStripMenuItem // this.disconnectPoolToolStripMenuItem.Command = new XenAdmin.Commands.DisconnectPoolCommand(); this.disconnectPoolToolStripMenuItem.Name = "disconnectPoolToolStripMenuItem"; resources.ApplyResources(this.disconnectPoolToolStripMenuItem, "disconnectPoolToolStripMenuItem"); // // toolStripSeparator27 // this.toolStripSeparator27.Name = "toolStripSeparator27"; resources.ApplyResources(this.toolStripSeparator27, "toolStripSeparator27"); // // virtualAppliancesToolStripMenuItem // this.virtualAppliancesToolStripMenuItem.Command = new XenAdmin.Commands.VMGroupCommandVM_appliance(); this.virtualAppliancesToolStripMenuItem.Name = "virtualAppliancesToolStripMenuItem"; resources.ApplyResources(this.virtualAppliancesToolStripMenuItem, "virtualAppliancesToolStripMenuItem"); // // toolStripSeparator30 // this.toolStripSeparator30.Name = "toolStripSeparator30"; resources.ApplyResources(this.toolStripSeparator30, "toolStripSeparator30"); // // highAvailabilityToolStripMenuItem // this.highAvailabilityToolStripMenuItem.Command = new XenAdmin.Commands.HACommand(); this.highAvailabilityToolStripMenuItem.Name = "highAvailabilityToolStripMenuItem"; resources.ApplyResources(this.highAvailabilityToolStripMenuItem, "highAvailabilityToolStripMenuItem"); // // disasterRecoveryToolStripMenuItem // this.disasterRecoveryToolStripMenuItem.Command = new XenAdmin.Commands.DRCommand(); this.disasterRecoveryToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.drConfigureToolStripMenuItem, this.DrWizardToolStripMenuItem}); this.disasterRecoveryToolStripMenuItem.Name = "disasterRecoveryToolStripMenuItem"; resources.ApplyResources(this.disasterRecoveryToolStripMenuItem, "disasterRecoveryToolStripMenuItem"); // // drConfigureToolStripMenuItem // this.drConfigureToolStripMenuItem.Command = new XenAdmin.Commands.DRConfigureCommand(); this.drConfigureToolStripMenuItem.Name = "drConfigureToolStripMenuItem"; resources.ApplyResources(this.drConfigureToolStripMenuItem, "drConfigureToolStripMenuItem"); // // DrWizardToolStripMenuItem // this.DrWizardToolStripMenuItem.Command = new XenAdmin.Commands.DisasterRecoveryCommand(); this.DrWizardToolStripMenuItem.Name = "DrWizardToolStripMenuItem"; resources.ApplyResources(this.DrWizardToolStripMenuItem, "DrWizardToolStripMenuItem"); // // VMSnapshotScheduleToolStripMenuItem // this.VMSnapshotScheduleToolStripMenuItem.Command = new XenAdmin.Commands.VMGroupCommandVMSS(); this.VMSnapshotScheduleToolStripMenuItem.Name = "VMSnapshotScheduleToolStripMenuItem"; resources.ApplyResources(this.VMSnapshotScheduleToolStripMenuItem, "VMSnapshotScheduleToolStripMenuItem"); // // exportResourceReportPoolToolStripMenuItem // this.exportResourceReportPoolToolStripMenuItem.Command = new XenAdmin.Commands.ExportResourceReportCommand(); this.exportResourceReportPoolToolStripMenuItem.Name = "exportResourceReportPoolToolStripMenuItem"; resources.ApplyResources(this.exportResourceReportPoolToolStripMenuItem, "exportResourceReportPoolToolStripMenuItem"); // // wlbReportsToolStripMenuItem // this.wlbReportsToolStripMenuItem.Command = new XenAdmin.Commands.ViewWorkloadReportsCommand(); this.wlbReportsToolStripMenuItem.Name = "wlbReportsToolStripMenuItem"; resources.ApplyResources(this.wlbReportsToolStripMenuItem, "wlbReportsToolStripMenuItem"); // // wlbDisconnectToolStripMenuItem // this.wlbDisconnectToolStripMenuItem.Command = new XenAdmin.Commands.DisconnectWlbServerCommand(); this.wlbDisconnectToolStripMenuItem.Name = "wlbDisconnectToolStripMenuItem"; resources.ApplyResources(this.wlbDisconnectToolStripMenuItem, "wlbDisconnectToolStripMenuItem"); // // toolStripSeparator9 // this.toolStripSeparator9.Name = "toolStripSeparator9"; resources.ApplyResources(this.toolStripSeparator9, "toolStripSeparator9"); // // changePoolPasswordToolStripMenuItem // this.changePoolPasswordToolStripMenuItem.Command = new XenAdmin.Commands.ChangeHostPasswordCommand(); this.changePoolPasswordToolStripMenuItem.Name = "changePoolPasswordToolStripMenuItem"; resources.ApplyResources(this.changePoolPasswordToolStripMenuItem, "changePoolPasswordToolStripMenuItem"); // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; resources.ApplyResources(this.toolStripMenuItem1, "toolStripMenuItem1"); // // deleteToolStripMenuItem // this.deleteToolStripMenuItem.Command = new XenAdmin.Commands.DeletePoolCommand(); this.deleteToolStripMenuItem.Name = "deleteToolStripMenuItem"; resources.ApplyResources(this.deleteToolStripMenuItem, "deleteToolStripMenuItem"); // // toolStripSeparator26 // this.toolStripSeparator26.Name = "toolStripSeparator26"; resources.ApplyResources(this.toolStripSeparator26, "toolStripSeparator26"); // // pluginItemsPlaceHolderToolStripMenuItem2 // this.pluginItemsPlaceHolderToolStripMenuItem2.Name = "pluginItemsPlaceHolderToolStripMenuItem2"; resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem2, "pluginItemsPlaceHolderToolStripMenuItem2"); // // PoolPropertiesToolStripMenuItem // this.PoolPropertiesToolStripMenuItem.Command = new XenAdmin.Commands.PoolPropertiesCommand(); this.PoolPropertiesToolStripMenuItem.Image = global::XenAdmin.Properties.Resources.edit_16; this.PoolPropertiesToolStripMenuItem.Name = "PoolPropertiesToolStripMenuItem"; resources.ApplyResources(this.PoolPropertiesToolStripMenuItem, "PoolPropertiesToolStripMenuItem"); // // HostMenuItem // this.HostMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.AddHostToolStripMenuItem, this.toolStripMenuItem11, this.RebootHostToolStripMenuItem, this.powerOnToolStripMenuItem, this.ShutdownHostToolStripMenuItem, this.restartToolstackToolStripMenuItem, this.toolStripSeparator1, this.connectDisconnectToolStripMenuItem, this.addServerToPoolMenuItem, this.toolStripSeparator3, this.backupToolStripMenuItem, this.restoreFromBackupToolStripMenuItem, this.toolStripSeparator23, this.maintenanceModeToolStripMenuItem1, this.controlDomainMemoryToolStripMenuItem, this.RemoveCrashdumpsToolStripMenuItem, this.HostPasswordToolStripMenuItem, this.toolStripSeparator25, this.destroyServerToolStripMenuItem, this.removeHostToolStripMenuItem, this.toolStripSeparator15, this.pluginItemsPlaceHolderToolStripMenuItem3, this.ServerPropertiesToolStripMenuItem}); this.HostMenuItem.Name = "HostMenuItem"; resources.ApplyResources(this.HostMenuItem, "HostMenuItem"); // // AddHostToolStripMenuItem // this.AddHostToolStripMenuItem.Command = new XenAdmin.Commands.AddHostCommand(); this.AddHostToolStripMenuItem.Image = global::XenAdmin.Properties.Resources._000_AddApplicationServer_h32bit_16; this.AddHostToolStripMenuItem.Name = "AddHostToolStripMenuItem"; resources.ApplyResources(this.AddHostToolStripMenuItem, "AddHostToolStripMenuItem"); // // toolStripMenuItem11 // this.toolStripMenuItem11.Name = "toolStripMenuItem11"; resources.ApplyResources(this.toolStripMenuItem11, "toolStripMenuItem11"); // // RebootHostToolStripMenuItem // this.RebootHostToolStripMenuItem.Command = new XenAdmin.Commands.RebootHostCommand(); this.RebootHostToolStripMenuItem.Image = global::XenAdmin.Properties.Resources._001_Reboot_h32bit_16; this.RebootHostToolStripMenuItem.Name = "RebootHostToolStripMenuItem"; resources.ApplyResources(this.RebootHostToolStripMenuItem, "RebootHostToolStripMenuItem"); // // powerOnToolStripMenuItem // this.powerOnToolStripMenuItem.Command = new XenAdmin.Commands.PowerOnHostCommand(); resources.ApplyResources(this.powerOnToolStripMenuItem, "powerOnToolStripMenuItem"); this.powerOnToolStripMenuItem.Name = "powerOnToolStripMenuItem"; // // ShutdownHostToolStripMenuItem // this.ShutdownHostToolStripMenuItem.Command = new XenAdmin.Commands.ShutDownHostCommand(); resources.ApplyResources(this.ShutdownHostToolStripMenuItem, "ShutdownHostToolStripMenuItem"); this.ShutdownHostToolStripMenuItem.Name = "ShutdownHostToolStripMenuItem"; // // restartToolstackToolStripMenuItem // this.restartToolstackToolStripMenuItem.Command = new XenAdmin.Commands.RestartToolstackCommand(); this.restartToolstackToolStripMenuItem.Name = "restartToolstackToolStripMenuItem"; resources.ApplyResources(this.restartToolstackToolStripMenuItem, "restartToolstackToolStripMenuItem"); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1"); // // connectDisconnectToolStripMenuItem // this.connectDisconnectToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.ReconnectToolStripMenuItem1, this.DisconnectToolStripMenuItem, this.reconnectAsToolStripMenuItem, this.toolStripSeparator4, this.connectAllToolStripMenuItem, this.disconnectAllToolStripMenuItem}); this.connectDisconnectToolStripMenuItem.Name = "connectDisconnectToolStripMenuItem"; resources.ApplyResources(this.connectDisconnectToolStripMenuItem, "connectDisconnectToolStripMenuItem"); // // ReconnectToolStripMenuItem1 // this.ReconnectToolStripMenuItem1.Command = new XenAdmin.Commands.ReconnectHostCommand(); this.ReconnectToolStripMenuItem1.Name = "ReconnectToolStripMenuItem1"; resources.ApplyResources(this.ReconnectToolStripMenuItem1, "ReconnectToolStripMenuItem1"); // // DisconnectToolStripMenuItem // this.DisconnectToolStripMenuItem.Command = new XenAdmin.Commands.DisconnectHostCommand(); this.DisconnectToolStripMenuItem.Name = "DisconnectToolStripMenuItem"; resources.ApplyResources(this.DisconnectToolStripMenuItem, "DisconnectToolStripMenuItem"); // // reconnectAsToolStripMenuItem // this.reconnectAsToolStripMenuItem.Command = new XenAdmin.Commands.HostReconnectAsCommand(); this.reconnectAsToolStripMenuItem.Name = "reconnectAsToolStripMenuItem"; resources.ApplyResources(this.reconnectAsToolStripMenuItem, "reconnectAsToolStripMenuItem"); // // toolStripSeparator4 // this.toolStripSeparator4.Name = "toolStripSeparator4"; resources.ApplyResources(this.toolStripSeparator4, "toolStripSeparator4"); // // connectAllToolStripMenuItem // this.connectAllToolStripMenuItem.Command = new XenAdmin.Commands.ConnectAllHostsCommand(); this.connectAllToolStripMenuItem.Name = "connectAllToolStripMenuItem"; resources.ApplyResources(this.connectAllToolStripMenuItem, "connectAllToolStripMenuItem"); // // disconnectAllToolStripMenuItem // this.disconnectAllToolStripMenuItem.Command = new XenAdmin.Commands.DisconnectAllHostsCommand(); this.disconnectAllToolStripMenuItem.Name = "disconnectAllToolStripMenuItem"; resources.ApplyResources(this.disconnectAllToolStripMenuItem, "disconnectAllToolStripMenuItem"); // // addServerToPoolMenuItem // this.addServerToPoolMenuItem.Name = "addServerToPoolMenuItem"; resources.ApplyResources(this.addServerToPoolMenuItem, "addServerToPoolMenuItem"); // // toolStripSeparator3 // this.toolStripSeparator3.Name = "toolStripSeparator3"; resources.ApplyResources(this.toolStripSeparator3, "toolStripSeparator3"); // // backupToolStripMenuItem // this.backupToolStripMenuItem.Command = new XenAdmin.Commands.BackupHostCommand(); this.backupToolStripMenuItem.Name = "backupToolStripMenuItem"; resources.ApplyResources(this.backupToolStripMenuItem, "backupToolStripMenuItem"); // // restoreFromBackupToolStripMenuItem // this.restoreFromBackupToolStripMenuItem.Command = new XenAdmin.Commands.RestoreHostFromBackupCommand(); this.restoreFromBackupToolStripMenuItem.Name = "restoreFromBackupToolStripMenuItem"; resources.ApplyResources(this.restoreFromBackupToolStripMenuItem, "restoreFromBackupToolStripMenuItem"); // // toolStripSeparator23 // this.toolStripSeparator23.Name = "toolStripSeparator23"; resources.ApplyResources(this.toolStripSeparator23, "toolStripSeparator23"); // // maintenanceModeToolStripMenuItem1 // this.maintenanceModeToolStripMenuItem1.Command = new XenAdmin.Commands.HostMaintenanceModeCommand(); this.maintenanceModeToolStripMenuItem1.Name = "maintenanceModeToolStripMenuItem1"; resources.ApplyResources(this.maintenanceModeToolStripMenuItem1, "maintenanceModeToolStripMenuItem1"); // // controlDomainMemoryToolStripMenuItem // this.controlDomainMemoryToolStripMenuItem.Command = new XenAdmin.Commands.ChangeControlDomainMemoryCommand(); this.controlDomainMemoryToolStripMenuItem.Name = "controlDomainMemoryToolStripMenuItem"; resources.ApplyResources(this.controlDomainMemoryToolStripMenuItem, "controlDomainMemoryToolStripMenuItem"); // // RemoveCrashdumpsToolStripMenuItem // this.RemoveCrashdumpsToolStripMenuItem.Command = new XenAdmin.Commands.RemoveHostCrashDumpsCommand(); this.RemoveCrashdumpsToolStripMenuItem.Name = "RemoveCrashdumpsToolStripMenuItem"; resources.ApplyResources(this.RemoveCrashdumpsToolStripMenuItem, "RemoveCrashdumpsToolStripMenuItem"); // // HostPasswordToolStripMenuItem // this.HostPasswordToolStripMenuItem.Command = new XenAdmin.Commands.HostPasswordCommand(); this.HostPasswordToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.ChangeRootPasswordToolStripMenuItem, this.forgetSavedPasswordToolStripMenuItem}); this.HostPasswordToolStripMenuItem.Name = "HostPasswordToolStripMenuItem"; resources.ApplyResources(this.HostPasswordToolStripMenuItem, "HostPasswordToolStripMenuItem"); // // ChangeRootPasswordToolStripMenuItem // this.ChangeRootPasswordToolStripMenuItem.Command = new XenAdmin.Commands.ChangeHostPasswordCommand(); this.ChangeRootPasswordToolStripMenuItem.Name = "ChangeRootPasswordToolStripMenuItem"; resources.ApplyResources(this.ChangeRootPasswordToolStripMenuItem, "ChangeRootPasswordToolStripMenuItem"); // // forgetSavedPasswordToolStripMenuItem // this.forgetSavedPasswordToolStripMenuItem.Command = new XenAdmin.Commands.ForgetSavedPasswordCommand(); this.forgetSavedPasswordToolStripMenuItem.Name = "forgetSavedPasswordToolStripMenuItem"; resources.ApplyResources(this.forgetSavedPasswordToolStripMenuItem, "forgetSavedPasswordToolStripMenuItem"); // // toolStripSeparator25 // this.toolStripSeparator25.Name = "toolStripSeparator25"; resources.ApplyResources(this.toolStripSeparator25, "toolStripSeparator25"); // // destroyServerToolStripMenuItem // this.destroyServerToolStripMenuItem.Command = new XenAdmin.Commands.DestroyHostCommand(); this.destroyServerToolStripMenuItem.Name = "destroyServerToolStripMenuItem"; resources.ApplyResources(this.destroyServerToolStripMenuItem, "destroyServerToolStripMenuItem"); // // removeHostToolStripMenuItem // this.removeHostToolStripMenuItem.Command = new XenAdmin.Commands.RemoveHostCommand(); this.removeHostToolStripMenuItem.Name = "removeHostToolStripMenuItem"; resources.ApplyResources(this.removeHostToolStripMenuItem, "removeHostToolStripMenuItem"); // // toolStripSeparator15 // this.toolStripSeparator15.Name = "toolStripSeparator15"; resources.ApplyResources(this.toolStripSeparator15, "toolStripSeparator15"); // // pluginItemsPlaceHolderToolStripMenuItem3 // this.pluginItemsPlaceHolderToolStripMenuItem3.Name = "pluginItemsPlaceHolderToolStripMenuItem3"; resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem3, "pluginItemsPlaceHolderToolStripMenuItem3"); // // ServerPropertiesToolStripMenuItem // this.ServerPropertiesToolStripMenuItem.Command = new XenAdmin.Commands.HostPropertiesCommand(); this.ServerPropertiesToolStripMenuItem.Image = global::XenAdmin.Properties.Resources.edit_16; this.ServerPropertiesToolStripMenuItem.Name = "ServerPropertiesToolStripMenuItem"; resources.ApplyResources(this.ServerPropertiesToolStripMenuItem, "ServerPropertiesToolStripMenuItem"); // // VMToolStripMenuItem // this.VMToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.NewVmToolStripMenuItem, this.startShutdownToolStripMenuItem, this.resumeOnToolStripMenuItem, this.relocateToolStripMenuItem, this.startOnHostToolStripMenuItem, this.toolStripSeparator20, this.assignSnapshotScheduleToolStripMenuItem, this.assignToVirtualApplianceToolStripMenuItem, this.toolStripMenuItem9, this.copyVMtoSharedStorageMenuItem, this.MoveVMToolStripMenuItem, this.snapshotToolStripMenuItem, this.convertToTemplateToolStripMenuItem, this.exportToolStripMenuItem, this.disableCbtToolStripMenuItem, this.enablePVSReadcachingToolStripMenuItem, this.disablePVSReadcachingToolStripMenuItem, this.toolStripMenuItem12, this.installToolsToolStripMenuItem, this.sendCtrlAltDelToolStripMenuItem, this.toolStripSeparator5, this.uninstallToolStripMenuItem, this.toolStripSeparator10, this.pluginItemsPlaceHolderToolStripMenuItem4, this.VMPropertiesToolStripMenuItem}); this.VMToolStripMenuItem.Name = "VMToolStripMenuItem"; resources.ApplyResources(this.VMToolStripMenuItem, "VMToolStripMenuItem"); // // NewVmToolStripMenuItem // this.NewVmToolStripMenuItem.Command = new XenAdmin.Commands.NewVMCommand(); this.NewVmToolStripMenuItem.Image = global::XenAdmin.Properties.Resources._001_CreateVM_h32bit_16; this.NewVmToolStripMenuItem.Name = "NewVmToolStripMenuItem"; resources.ApplyResources(this.NewVmToolStripMenuItem, "NewVmToolStripMenuItem"); // // startShutdownToolStripMenuItem // this.startShutdownToolStripMenuItem.Name = "startShutdownToolStripMenuItem"; resources.ApplyResources(this.startShutdownToolStripMenuItem, "startShutdownToolStripMenuItem"); // // resumeOnToolStripMenuItem // this.resumeOnToolStripMenuItem.Name = "resumeOnToolStripMenuItem"; resources.ApplyResources(this.resumeOnToolStripMenuItem, "resumeOnToolStripMenuItem"); // // relocateToolStripMenuItem // this.relocateToolStripMenuItem.Name = "relocateToolStripMenuItem"; resources.ApplyResources(this.relocateToolStripMenuItem, "relocateToolStripMenuItem"); // // startOnHostToolStripMenuItem // this.startOnHostToolStripMenuItem.Name = "startOnHostToolStripMenuItem"; resources.ApplyResources(this.startOnHostToolStripMenuItem, "startOnHostToolStripMenuItem"); // // toolStripSeparator20 // this.toolStripSeparator20.Name = "toolStripSeparator20"; resources.ApplyResources(this.toolStripSeparator20, "toolStripSeparator20"); // // assignSnapshotScheduleToolStripMenuItem // this.assignSnapshotScheduleToolStripMenuItem.Name = "assignSnapshotScheduleToolStripMenuItem"; resources.ApplyResources(this.assignSnapshotScheduleToolStripMenuItem, "assignSnapshotScheduleToolStripMenuItem"); // // assignToVirtualApplianceToolStripMenuItem // this.assignToVirtualApplianceToolStripMenuItem.Name = "assignToVirtualApplianceToolStripMenuItem"; resources.ApplyResources(this.assignToVirtualApplianceToolStripMenuItem, "assignToVirtualApplianceToolStripMenuItem"); // // toolStripMenuItem9 // this.toolStripMenuItem9.Name = "toolStripMenuItem9"; resources.ApplyResources(this.toolStripMenuItem9, "toolStripMenuItem9"); // // copyVMtoSharedStorageMenuItem // this.copyVMtoSharedStorageMenuItem.Command = new XenAdmin.Commands.CopyVMCommand(); this.copyVMtoSharedStorageMenuItem.Name = "copyVMtoSharedStorageMenuItem"; resources.ApplyResources(this.copyVMtoSharedStorageMenuItem, "copyVMtoSharedStorageMenuItem"); // // MoveVMToolStripMenuItem // this.MoveVMToolStripMenuItem.Command = new XenAdmin.Commands.MoveVMCommand(); this.MoveVMToolStripMenuItem.Name = "MoveVMToolStripMenuItem"; resources.ApplyResources(this.MoveVMToolStripMenuItem, "MoveVMToolStripMenuItem"); // // snapshotToolStripMenuItem // this.snapshotToolStripMenuItem.Command = new XenAdmin.Commands.TakeSnapshotCommand(); this.snapshotToolStripMenuItem.Name = "snapshotToolStripMenuItem"; resources.ApplyResources(this.snapshotToolStripMenuItem, "snapshotToolStripMenuItem"); // // convertToTemplateToolStripMenuItem // this.convertToTemplateToolStripMenuItem.Command = new XenAdmin.Commands.ConvertVMToTemplateCommand(); this.convertToTemplateToolStripMenuItem.Name = "convertToTemplateToolStripMenuItem"; resources.ApplyResources(this.convertToTemplateToolStripMenuItem, "convertToTemplateToolStripMenuItem"); // // exportToolStripMenuItem // this.exportToolStripMenuItem.Command = new XenAdmin.Commands.ExportCommand(); this.exportToolStripMenuItem.Name = "exportToolStripMenuItem"; resources.ApplyResources(this.exportToolStripMenuItem, "exportToolStripMenuItem"); // // enablePVSReadcachingToolStripMenuItem // this.enablePVSReadcachingToolStripMenuItem.Command = new EnablePvsReadCachingCommand(); this.enablePVSReadcachingToolStripMenuItem.Name = "enablePVSReadcachingToolStripMenuItem"; resources.ApplyResources(this.enablePVSReadcachingToolStripMenuItem, "enablePVSReadcachingToolStripMenuItem"); // // disablePVSReadcachingToolStripMenuItem // this.disablePVSReadcachingToolStripMenuItem.Command = new DisablePvsReadCachingCommand(); this.disablePVSReadcachingToolStripMenuItem.Name = "disablePVSReadcachingToolStripMenuItem"; resources.ApplyResources(this.disablePVSReadcachingToolStripMenuItem, "disablePVSReadcachingToolStripMenuItem"); // // toolStripMenuItem12 // this.toolStripMenuItem12.Name = "toolStripMenuItem12"; resources.ApplyResources(this.toolStripMenuItem12, "toolStripMenuItem12"); // // installToolsToolStripMenuItem // this.installToolsToolStripMenuItem.Command = new XenAdmin.Commands.InstallToolsCommand(); this.installToolsToolStripMenuItem.Name = "installToolsToolStripMenuItem"; resources.ApplyResources(this.installToolsToolStripMenuItem, "installToolsToolStripMenuItem"); // // sendCtrlAltDelToolStripMenuItem // this.sendCtrlAltDelToolStripMenuItem.Name = "sendCtrlAltDelToolStripMenuItem"; resources.ApplyResources(this.sendCtrlAltDelToolStripMenuItem, "sendCtrlAltDelToolStripMenuItem"); this.sendCtrlAltDelToolStripMenuItem.Click += new System.EventHandler(this.sendCtrlAltDelToolStripMenuItem_Click); // // toolStripSeparator5 // this.toolStripSeparator5.Name = "toolStripSeparator5"; resources.ApplyResources(this.toolStripSeparator5, "toolStripSeparator5"); // // uninstallToolStripMenuItem // this.uninstallToolStripMenuItem.Command = new XenAdmin.Commands.DeleteVMCommand(); this.uninstallToolStripMenuItem.Name = "uninstallToolStripMenuItem"; resources.ApplyResources(this.uninstallToolStripMenuItem, "uninstallToolStripMenuItem"); // // toolStripSeparator10 // this.toolStripSeparator10.Name = "toolStripSeparator10"; resources.ApplyResources(this.toolStripSeparator10, "toolStripSeparator10"); // // pluginItemsPlaceHolderToolStripMenuItem4 // this.pluginItemsPlaceHolderToolStripMenuItem4.Name = "pluginItemsPlaceHolderToolStripMenuItem4"; resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem4, "pluginItemsPlaceHolderToolStripMenuItem4"); // // VMPropertiesToolStripMenuItem // this.VMPropertiesToolStripMenuItem.Command = new XenAdmin.Commands.VMPropertiesCommand(); this.VMPropertiesToolStripMenuItem.Image = global::XenAdmin.Properties.Resources.edit_16; this.VMPropertiesToolStripMenuItem.Name = "VMPropertiesToolStripMenuItem"; resources.ApplyResources(this.VMPropertiesToolStripMenuItem, "VMPropertiesToolStripMenuItem"); // // toolStripMenuItem8 // this.toolStripMenuItem8.Name = "toolStripMenuItem8"; resources.ApplyResources(this.toolStripMenuItem8, "toolStripMenuItem8"); // // StorageToolStripMenuItem // this.StorageToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.AddStorageToolStripMenuItem, this.toolStripSeparator22, this.RepairStorageToolStripMenuItem, this.DefaultSRToolStripMenuItem, this.toolStripSeparator2, this.virtualDisksToolStripMenuItem, this.reclaimFreedSpacetripMenuItem, this.toolStripSeparator19, this.DetachStorageToolStripMenuItem, this.ReattachStorageRepositoryToolStripMenuItem, this.ForgetStorageRepositoryToolStripMenuItem, this.DestroyStorageRepositoryToolStripMenuItem, this.toolStripSeparator18, this.pluginItemsPlaceHolderToolStripMenuItem5, this.SRPropertiesToolStripMenuItem}); this.StorageToolStripMenuItem.Name = "StorageToolStripMenuItem"; resources.ApplyResources(this.StorageToolStripMenuItem, "StorageToolStripMenuItem"); // // AddStorageToolStripMenuItem // this.AddStorageToolStripMenuItem.Command = new XenAdmin.Commands.NewSRCommand(); this.AddStorageToolStripMenuItem.Image = global::XenAdmin.Properties.Resources._000_NewStorage_h32bit_16; this.AddStorageToolStripMenuItem.Name = "AddStorageToolStripMenuItem"; resources.ApplyResources(this.AddStorageToolStripMenuItem, "AddStorageToolStripMenuItem"); // // toolStripSeparator22 // this.toolStripSeparator22.Name = "toolStripSeparator22"; resources.ApplyResources(this.toolStripSeparator22, "toolStripSeparator22"); // // RepairStorageToolStripMenuItem // this.RepairStorageToolStripMenuItem.Command = new XenAdmin.Commands.RepairSRCommand(); this.RepairStorageToolStripMenuItem.Image = global::XenAdmin.Properties.Resources._000_StorageBroken_h32bit_16; this.RepairStorageToolStripMenuItem.Name = "RepairStorageToolStripMenuItem"; resources.ApplyResources(this.RepairStorageToolStripMenuItem, "RepairStorageToolStripMenuItem"); // // DefaultSRToolStripMenuItem // this.DefaultSRToolStripMenuItem.Command = new XenAdmin.Commands.SetAsDefaultSRCommand(); this.DefaultSRToolStripMenuItem.Image = global::XenAdmin.Properties.Resources._000_StorageDefault_h32bit_16; this.DefaultSRToolStripMenuItem.Name = "DefaultSRToolStripMenuItem"; resources.ApplyResources(this.DefaultSRToolStripMenuItem, "DefaultSRToolStripMenuItem"); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; resources.ApplyResources(this.toolStripSeparator2, "toolStripSeparator2"); // // virtualDisksToolStripMenuItem // this.virtualDisksToolStripMenuItem.Command = new XenAdmin.Commands.VirtualDiskCommand(); this.virtualDisksToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.addVirtualDiskToolStripMenuItem, this.attachVirtualDiskToolStripMenuItem}); this.virtualDisksToolStripMenuItem.Name = "virtualDisksToolStripMenuItem"; resources.ApplyResources(this.virtualDisksToolStripMenuItem, "virtualDisksToolStripMenuItem"); // // addVirtualDiskToolStripMenuItem // this.addVirtualDiskToolStripMenuItem.Command = new XenAdmin.Commands.AddVirtualDiskCommand(); this.addVirtualDiskToolStripMenuItem.Name = "addVirtualDiskToolStripMenuItem"; resources.ApplyResources(this.addVirtualDiskToolStripMenuItem, "addVirtualDiskToolStripMenuItem"); // // attachVirtualDiskToolStripMenuItem // this.attachVirtualDiskToolStripMenuItem.Command = new XenAdmin.Commands.AttachVirtualDiskCommand(); this.attachVirtualDiskToolStripMenuItem.Name = "attachVirtualDiskToolStripMenuItem"; resources.ApplyResources(this.attachVirtualDiskToolStripMenuItem, "attachVirtualDiskToolStripMenuItem"); // // reclaimFreedSpacetripMenuItem // this.reclaimFreedSpacetripMenuItem.Command = new XenAdmin.Commands.TrimSRCommand(); this.reclaimFreedSpacetripMenuItem.Name = "reclaimFreedSpacetripMenuItem"; resources.ApplyResources(this.reclaimFreedSpacetripMenuItem, "reclaimFreedSpacetripMenuItem"); // // toolStripSeparator19 // this.toolStripSeparator19.Name = "toolStripSeparator19"; resources.ApplyResources(this.toolStripSeparator19, "toolStripSeparator19"); // // DetachStorageToolStripMenuItem // this.DetachStorageToolStripMenuItem.Command = new XenAdmin.Commands.DetachSRCommand(); this.DetachStorageToolStripMenuItem.Name = "DetachStorageToolStripMenuItem"; resources.ApplyResources(this.DetachStorageToolStripMenuItem, "DetachStorageToolStripMenuItem"); // // ReattachStorageRepositoryToolStripMenuItem // this.ReattachStorageRepositoryToolStripMenuItem.Command = new XenAdmin.Commands.ReattachSRCommand(); this.ReattachStorageRepositoryToolStripMenuItem.Name = "ReattachStorageRepositoryToolStripMenuItem"; resources.ApplyResources(this.ReattachStorageRepositoryToolStripMenuItem, "ReattachStorageRepositoryToolStripMenuItem"); // // ForgetStorageRepositoryToolStripMenuItem // this.ForgetStorageRepositoryToolStripMenuItem.Command = new XenAdmin.Commands.ForgetSRCommand(); this.ForgetStorageRepositoryToolStripMenuItem.Name = "ForgetStorageRepositoryToolStripMenuItem"; resources.ApplyResources(this.ForgetStorageRepositoryToolStripMenuItem, "ForgetStorageRepositoryToolStripMenuItem"); // // DestroyStorageRepositoryToolStripMenuItem // this.DestroyStorageRepositoryToolStripMenuItem.Command = new XenAdmin.Commands.DestroySRCommand(); this.DestroyStorageRepositoryToolStripMenuItem.Name = "DestroyStorageRepositoryToolStripMenuItem"; resources.ApplyResources(this.DestroyStorageRepositoryToolStripMenuItem, "DestroyStorageRepositoryToolStripMenuItem"); // // toolStripSeparator18 // this.toolStripSeparator18.Name = "toolStripSeparator18"; resources.ApplyResources(this.toolStripSeparator18, "toolStripSeparator18"); // // pluginItemsPlaceHolderToolStripMenuItem5 // this.pluginItemsPlaceHolderToolStripMenuItem5.Name = "pluginItemsPlaceHolderToolStripMenuItem5"; resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem5, "pluginItemsPlaceHolderToolStripMenuItem5"); // // SRPropertiesToolStripMenuItem // this.SRPropertiesToolStripMenuItem.Command = new XenAdmin.Commands.SRPropertiesCommand(); this.SRPropertiesToolStripMenuItem.Image = global::XenAdmin.Properties.Resources.edit_16; this.SRPropertiesToolStripMenuItem.Name = "SRPropertiesToolStripMenuItem"; resources.ApplyResources(this.SRPropertiesToolStripMenuItem, "SRPropertiesToolStripMenuItem"); // // templatesToolStripMenuItem // this.templatesToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.CreateVmFromTemplateToolStripMenuItem, this.toolStripSeparator29, this.exportTemplateToolStripMenuItem, this.duplicateTemplateToolStripMenuItem, this.toolStripSeparator16, this.uninstallTemplateToolStripMenuItem, this.toolStripSeparator28, this.pluginItemsPlaceHolderToolStripMenuItem6, this.templatePropertiesToolStripMenuItem}); this.templatesToolStripMenuItem.Name = "templatesToolStripMenuItem"; resources.ApplyResources(this.templatesToolStripMenuItem, "templatesToolStripMenuItem"); // // CreateVmFromTemplateToolStripMenuItem // this.CreateVmFromTemplateToolStripMenuItem.Command = new XenAdmin.Commands.CreateVMFromTemplateCommand(); this.CreateVmFromTemplateToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.newVMFromTemplateToolStripMenuItem, this.InstantVmToolStripMenuItem}); this.CreateVmFromTemplateToolStripMenuItem.Image = global::XenAdmin.Properties.Resources._001_CreateVM_h32bit_16; this.CreateVmFromTemplateToolStripMenuItem.Name = "CreateVmFromTemplateToolStripMenuItem"; resources.ApplyResources(this.CreateVmFromTemplateToolStripMenuItem, "CreateVmFromTemplateToolStripMenuItem"); // // newVMFromTemplateToolStripMenuItem // this.newVMFromTemplateToolStripMenuItem.Command = new XenAdmin.Commands.NewVMFromTemplateCommand(); this.newVMFromTemplateToolStripMenuItem.Image = global::XenAdmin.Properties.Resources._001_CreateVM_h32bit_16; this.newVMFromTemplateToolStripMenuItem.Name = "newVMFromTemplateToolStripMenuItem"; resources.ApplyResources(this.newVMFromTemplateToolStripMenuItem, "newVMFromTemplateToolStripMenuItem"); // // InstantVmToolStripMenuItem // this.InstantVmToolStripMenuItem.Command = new XenAdmin.Commands.InstantVMFromTemplateCommand(); this.InstantVmToolStripMenuItem.Name = "InstantVmToolStripMenuItem"; resources.ApplyResources(this.InstantVmToolStripMenuItem, "InstantVmToolStripMenuItem"); // // toolStripSeparator29 // this.toolStripSeparator29.Name = "toolStripSeparator29"; resources.ApplyResources(this.toolStripSeparator29, "toolStripSeparator29"); // // exportTemplateToolStripMenuItem // this.exportTemplateToolStripMenuItem.Command = new XenAdmin.Commands.ExportTemplateCommand(); this.exportTemplateToolStripMenuItem.Name = "exportTemplateToolStripMenuItem"; resources.ApplyResources(this.exportTemplateToolStripMenuItem, "exportTemplateToolStripMenuItem"); // // duplicateTemplateToolStripMenuItem // this.duplicateTemplateToolStripMenuItem.Command = new XenAdmin.Commands.CopyTemplateCommand(); this.duplicateTemplateToolStripMenuItem.Name = "duplicateTemplateToolStripMenuItem"; resources.ApplyResources(this.duplicateTemplateToolStripMenuItem, "duplicateTemplateToolStripMenuItem"); // // toolStripSeparator16 // this.toolStripSeparator16.Name = "toolStripSeparator16"; resources.ApplyResources(this.toolStripSeparator16, "toolStripSeparator16"); // // uninstallTemplateToolStripMenuItem // this.uninstallTemplateToolStripMenuItem.Command = new XenAdmin.Commands.DeleteTemplateCommand(); this.uninstallTemplateToolStripMenuItem.Name = "uninstallTemplateToolStripMenuItem"; resources.ApplyResources(this.uninstallTemplateToolStripMenuItem, "uninstallTemplateToolStripMenuItem"); // // toolStripSeparator28 // this.toolStripSeparator28.Name = "toolStripSeparator28"; resources.ApplyResources(this.toolStripSeparator28, "toolStripSeparator28"); // // pluginItemsPlaceHolderToolStripMenuItem6 // this.pluginItemsPlaceHolderToolStripMenuItem6.Name = "pluginItemsPlaceHolderToolStripMenuItem6"; resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem6, "pluginItemsPlaceHolderToolStripMenuItem6"); // // templatePropertiesToolStripMenuItem // this.templatePropertiesToolStripMenuItem.Command = new XenAdmin.Commands.TemplatePropertiesCommand(); this.templatePropertiesToolStripMenuItem.Image = global::XenAdmin.Properties.Resources.edit_16; this.templatePropertiesToolStripMenuItem.Name = "templatePropertiesToolStripMenuItem"; resources.ApplyResources(this.templatePropertiesToolStripMenuItem, "templatePropertiesToolStripMenuItem"); // // toolsToolStripMenuItem // this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.bugToolToolStripMenuItem, this.healthCheckToolStripMenuItem1, this.toolStripSeparator14, //this.LicenseManagerMenuItem, //this.toolStripSeparator13, //this.installNewUpdateToolStripMenuItem, //this.rollingUpgradeToolStripMenuItem, //this.toolStripSeparator6, this.pluginItemsPlaceHolderToolStripMenuItem7, this.preferencesToolStripMenuItem}); this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem"; resources.ApplyResources(this.toolsToolStripMenuItem, "toolsToolStripMenuItem"); // // bugToolToolStripMenuItem // this.bugToolToolStripMenuItem.Command = new XenAdmin.Commands.BugToolCommand(); this.bugToolToolStripMenuItem.Name = "bugToolToolStripMenuItem"; resources.ApplyResources(this.bugToolToolStripMenuItem, "bugToolToolStripMenuItem"); // // healthCheckToolStripMenuItem1 // this.healthCheckToolStripMenuItem1.Command = new XenAdmin.Commands.HealthCheckCommand(); this.healthCheckToolStripMenuItem1.Name = "healthCheckToolStripMenuItem1"; resources.ApplyResources(this.healthCheckToolStripMenuItem1, "healthCheckToolStripMenuItem1"); // // toolStripSeparator14 // this.toolStripSeparator14.Name = "toolStripSeparator14"; resources.ApplyResources(this.toolStripSeparator14, "toolStripSeparator14"); // // LicenseManagerMenuItem // //this.LicenseManagerMenuItem.Name = "LicenseManagerMenuItem"; //resources.ApplyResources(this.LicenseManagerMenuItem, "LicenseManagerMenuItem"); //this.LicenseManagerMenuItem.Click += new System.EventHandler(this.LicenseManagerMenuItem_Click); // // toolStripSeparator13 // //this.toolStripSeparator13.Name = "toolStripSeparator13"; //resources.ApplyResources(this.toolStripSeparator13, "toolStripSeparator13"); // // installNewUpdateToolStripMenuItem // //this.installNewUpdateToolStripMenuItem.Command = new XenAdmin.Commands.InstallNewUpdateCommand(); //this.installNewUpdateToolStripMenuItem.Name = "installNewUpdateToolStripMenuItem"; //resources.ApplyResources(this.installNewUpdateToolStripMenuItem, "installNewUpdateToolStripMenuItem"); // // rollingUpgradeToolStripMenuItem // //this.rollingUpgradeToolStripMenuItem.Command = new XenAdmin.Commands.RollingUpgradeCommand(); //this.rollingUpgradeToolStripMenuItem.Name = "rollingUpgradeToolStripMenuItem"; //resources.ApplyResources(this.rollingUpgradeToolStripMenuItem, "rollingUpgradeToolStripMenuItem"); // // toolStripSeparator6 // //this.toolStripSeparator6.Name = "toolStripSeparator6"; //resources.ApplyResources(this.toolStripSeparator6, "toolStripSeparator6"); // // pluginItemsPlaceHolderToolStripMenuItem7 // this.pluginItemsPlaceHolderToolStripMenuItem7.Name = "pluginItemsPlaceHolderToolStripMenuItem7"; resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem7, "pluginItemsPlaceHolderToolStripMenuItem7"); // // preferencesToolStripMenuItem // this.preferencesToolStripMenuItem.Name = "preferencesToolStripMenuItem"; resources.ApplyResources(this.preferencesToolStripMenuItem, "preferencesToolStripMenuItem"); this.preferencesToolStripMenuItem.Click += new System.EventHandler(this.preferencesToolStripMenuItem_Click); // // windowToolStripMenuItem // this.windowToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.pluginItemsPlaceHolderToolStripMenuItem9}); this.windowToolStripMenuItem.Name = "windowToolStripMenuItem"; resources.ApplyResources(this.windowToolStripMenuItem, "windowToolStripMenuItem"); // // pluginItemsPlaceHolderToolStripMenuItem9 // this.pluginItemsPlaceHolderToolStripMenuItem9.Name = "pluginItemsPlaceHolderToolStripMenuItem9"; resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem9, "pluginItemsPlaceHolderToolStripMenuItem9"); // // helpToolStripMenuItem // this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.helpTopicsToolStripMenuItem, this.helpContextMenuItem, this.toolStripMenuItem15, this.viewApplicationLogToolStripMenuItem, this.toolStripMenuItem17, this.xenSourceOnTheWebToolStripMenuItem, this.xenCenterPluginsOnlineToolStripMenuItem, this.toolStripSeparator7, this.pluginItemsPlaceHolderToolStripMenuItem8, this.aboutXenSourceAdminToolStripMenuItem}); this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; resources.ApplyResources(this.helpToolStripMenuItem, "helpToolStripMenuItem"); // // helpTopicsToolStripMenuItem // this.helpTopicsToolStripMenuItem.Name = "helpTopicsToolStripMenuItem"; resources.ApplyResources(this.helpTopicsToolStripMenuItem, "helpTopicsToolStripMenuItem"); this.helpTopicsToolStripMenuItem.Click += new System.EventHandler(this.helpTopicsToolStripMenuItem_Click); // // helpContextMenuItem // this.helpContextMenuItem.Image = global::XenAdmin.Properties.Resources._000_HelpIM_h32bit_16; this.helpContextMenuItem.Name = "helpContextMenuItem"; resources.ApplyResources(this.helpContextMenuItem, "helpContextMenuItem"); this.helpContextMenuItem.Click += new System.EventHandler(this.helpContextMenuItem_Click); // // toolStripMenuItem15 // this.toolStripMenuItem15.Name = "toolStripMenuItem15"; resources.ApplyResources(this.toolStripMenuItem15, "toolStripMenuItem15"); // // viewApplicationLogToolStripMenuItem // this.viewApplicationLogToolStripMenuItem.Name = "viewApplicationLogToolStripMenuItem"; resources.ApplyResources(this.viewApplicationLogToolStripMenuItem, "viewApplicationLogToolStripMenuItem"); this.viewApplicationLogToolStripMenuItem.Click += new System.EventHandler(this.viewApplicationLogToolStripMenuItem_Click); // // toolStripMenuItem17 // this.toolStripMenuItem17.Name = "toolStripMenuItem17"; resources.ApplyResources(this.toolStripMenuItem17, "toolStripMenuItem17"); // // xenSourceOnTheWebToolStripMenuItem // this.xenSourceOnTheWebToolStripMenuItem.Name = "xenSourceOnTheWebToolStripMenuItem"; resources.ApplyResources(this.xenSourceOnTheWebToolStripMenuItem, "xenSourceOnTheWebToolStripMenuItem"); this.xenSourceOnTheWebToolStripMenuItem.Click += new System.EventHandler(this.xenSourceOnTheWebToolStripMenuItem_Click); // // xenCenterPluginsOnlineToolStripMenuItem // this.xenCenterPluginsOnlineToolStripMenuItem.Name = "xenCenterPluginsOnlineToolStripMenuItem"; resources.ApplyResources(this.xenCenterPluginsOnlineToolStripMenuItem, "xenCenterPluginsOnlineToolStripMenuItem"); this.xenCenterPluginsOnlineToolStripMenuItem.Click += new System.EventHandler(this.xenCenterPluginsOnTheWebToolStripMenuItem_Click); // // toolStripSeparator7 // this.toolStripSeparator7.Name = "toolStripSeparator7"; resources.ApplyResources(this.toolStripSeparator7, "toolStripSeparator7"); // // pluginItemsPlaceHolderToolStripMenuItem8 // this.pluginItemsPlaceHolderToolStripMenuItem8.Name = "pluginItemsPlaceHolderToolStripMenuItem8"; resources.ApplyResources(this.pluginItemsPlaceHolderToolStripMenuItem8, "pluginItemsPlaceHolderToolStripMenuItem8"); // // aboutXenSourceAdminToolStripMenuItem // this.aboutXenSourceAdminToolStripMenuItem.Name = "aboutXenSourceAdminToolStripMenuItem"; resources.ApplyResources(this.aboutXenSourceAdminToolStripMenuItem, "aboutXenSourceAdminToolStripMenuItem"); this.aboutXenSourceAdminToolStripMenuItem.Click += new System.EventHandler(this.aboutXenSourceAdminToolStripMenuItem_Click); // // MainMenuBar // resources.ApplyResources(this.MainMenuBar, "MainMenuBar"); this.MainMenuBar.ClickThrough = true; this.MainMenuBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.viewToolStripMenuItem, this.poolToolStripMenuItem, this.HostMenuItem, this.VMToolStripMenuItem, this.StorageToolStripMenuItem, this.templatesToolStripMenuItem, this.toolsToolStripMenuItem, this.windowToolStripMenuItem, this.helpToolStripMenuItem}); this.MainMenuBar.Name = "MainMenuBar"; this.MainMenuBar.MenuActivate += new System.EventHandler(this.MainMenuBar_MenuActivate); this.MainMenuBar.MouseClick += new System.Windows.Forms.MouseEventHandler(this.MainMenuBar_MouseClick); // // securityGroupsToolStripMenuItem // this.securityGroupsToolStripMenuItem.Name = "securityGroupsToolStripMenuItem"; resources.ApplyResources(this.securityGroupsToolStripMenuItem, "securityGroupsToolStripMenuItem"); // // MenuPanel // this.MenuPanel.Controls.Add(this.MainMenuBar); resources.ApplyResources(this.MenuPanel, "MenuPanel"); this.MenuPanel.Name = "MenuPanel"; // // StatusStrip // resources.ApplyResources(this.StatusStrip, "StatusStrip"); this.StatusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.statusLabel, this.statusProgressBar}); this.StatusStrip.Name = "StatusStrip"; this.StatusStrip.ShowItemToolTips = true; // // statusLabel // this.statusLabel.AutoToolTip = true; resources.ApplyResources(this.statusLabel, "statusLabel"); this.statusLabel.Name = "statusLabel"; this.statusLabel.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never; this.statusLabel.Spring = true; // // statusProgressBar // resources.ApplyResources(this.statusProgressBar, "statusProgressBar"); this.statusProgressBar.Margin = new System.Windows.Forms.Padding(5); this.statusProgressBar.Name = "statusProgressBar"; this.statusProgressBar.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never; // // TabPageUSB // resources.ApplyResources(this.TabPageUSB, "TabPageUSB"); this.TabPageUSB.Name = "TabPageUSB"; this.TabPageUSB.UseVisualStyleBackColor = true; // disableCbtToolStripMenuItem // this.disableCbtToolStripMenuItem.Command = new XenAdmin.Commands.DisableChangedBlockTrackingCommand(); this.disableCbtToolStripMenuItem.Name = "disableCbtToolStripMenuItem"; resources.ApplyResources(this.disableCbtToolStripMenuItem, "disableCbtToolStripMenuItem"); // // MainWindow // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.Controls.Add(this.splitContainer1); this.Controls.Add(this.ToolStrip); this.Controls.Add(this.MenuPanel); this.Controls.Add(this.StatusStrip); this.DoubleBuffered = true; this.KeyPreview = true; this.MainMenuStrip = this.MainMenuBar; this.Name = "MainWindow"; this.Load += new System.EventHandler(this.MainWindow_Load); this.Shown += new System.EventHandler(this.MainWindow_Shown); this.ResizeEnd += new System.EventHandler(this.MainWindow_ResizeEnd); this.HelpRequested += new System.Windows.Forms.HelpEventHandler(this.MainWindow_HelpRequested); this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.MainWindow_KeyDown); this.Resize += new System.EventHandler(this.MainWindow_Resize); this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit(); this.splitContainer1.ResumeLayout(false); this.TheTabControl.ResumeLayout(false); this.TabPageSnapshots.ResumeLayout(false); this.TitleBackPanel.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.TitleIcon)).EndInit(); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.toolTipContainer1.ResumeLayout(false); this.toolTipContainer1.PerformLayout(); this.ToolStrip.ResumeLayout(false); this.ToolStrip.PerformLayout(); this.ToolBarContextMenu.ResumeLayout(false); this.MainMenuBar.ResumeLayout(false); this.MainMenuBar.PerformLayout(); this.MenuPanel.ResumeLayout(false); this.StatusStrip.ResumeLayout(false); this.StatusStrip.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.SplitContainer splitContainer1; private XenAdmin.Controls.ToolStripEx ToolStrip; private CommandToolStripButton NewVmToolbarButton; private CommandToolStripButton AddServerToolbarButton; private CommandToolStripButton RebootToolbarButton; private CommandToolStripButton SuspendToolbarButton; private CommandToolStripButton ForceRebootToolbarButton; private CommandToolStripButton ForceShutdownToolbarButton; private System.Windows.Forms.ToolTip statusToolTip; private CommandToolStripButton AddPoolToolbarButton; private CommandToolStripButton newStorageToolbarButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator11; private System.Windows.Forms.ToolStripSeparator toolStripSeparator12; private System.Windows.Forms.Label TitleLabel; private System.Windows.Forms.PictureBox TitleIcon; private XenAdmin.Controls.GradientPanel.GradientPanel TitleBackPanel; private System.Windows.Forms.ToolStripSeparator toolStripSeparator17; internal System.Windows.Forms.ToolStripSplitButton backButton; internal System.Windows.Forms.ToolStripSplitButton forwardButton; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.ContextMenuStrip ToolBarContextMenu; private System.Windows.Forms.ToolStripMenuItem ShowToolbarMenuItem; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private CommandToolStripMenuItem FileImportVMToolStripMenuItem; private CommandToolStripMenuItem importSearchToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator21; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem viewToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem poolToolStripMenuItem; private CommandToolStripMenuItem AddPoolToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator8; private CommandToolStripMenuItem PoolPropertiesToolStripMenuItem; private CommandToolStripMenuItem highAvailabilityToolStripMenuItem; private CommandToolStripMenuItem wlbReportsToolStripMenuItem; private CommandToolStripMenuItem wlbDisconnectToolStripMenuItem; private AddHostToSelectedPoolToolStripMenuItem addServerToolStripMenuItem; private CommandToolStripMenuItem removeServerToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator9; private CommandToolStripMenuItem deleteToolStripMenuItem; private CommandToolStripMenuItem disconnectPoolToolStripMenuItem; private CommandToolStripMenuItem exportResourceReportPoolToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem HostMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem11; private CommandToolStripMenuItem ServerPropertiesToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator15; private CommandToolStripMenuItem RebootHostToolStripMenuItem; private CommandToolStripMenuItem ShutdownHostToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private CommandToolStripMenuItem AddHostToolStripMenuItem; private CommandToolStripMenuItem removeHostToolStripMenuItem; private AddSelectedHostToPoolToolStripMenuItem addServerToPoolMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator3; private CommandToolStripMenuItem RemoveCrashdumpsToolStripMenuItem; private CommandToolStripMenuItem maintenanceModeToolStripMenuItem1; private CommandToolStripMenuItem backupToolStripMenuItem; private CommandToolStripMenuItem restoreFromBackupToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem VMToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator10; private CommandToolStripMenuItem VMPropertiesToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator20; private CommandToolStripMenuItem snapshotToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem9; private CommandToolStripMenuItem copyVMtoSharedStorageMenuItem; private CommandToolStripMenuItem exportToolStripMenuItem; private CommandToolStripMenuItem convertToTemplateToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem12; private CommandToolStripMenuItem installToolsToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator5; private CommandToolStripMenuItem uninstallToolStripMenuItem; internal System.Windows.Forms.ToolStripMenuItem StorageToolStripMenuItem; private CommandToolStripMenuItem AddStorageToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator18; private CommandToolStripMenuItem SRPropertiesToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator22; private CommandToolStripMenuItem RepairStorageToolStripMenuItem; private CommandToolStripMenuItem DefaultSRToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator19; private CommandToolStripMenuItem DetachStorageToolStripMenuItem; private CommandToolStripMenuItem ReattachStorageRepositoryToolStripMenuItem; private CommandToolStripMenuItem ForgetStorageRepositoryToolStripMenuItem; private CommandToolStripMenuItem DestroyStorageRepositoryToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.ToolStripMenuItem templatesToolStripMenuItem; private CommandToolStripMenuItem exportTemplateToolStripMenuItem; private CommandToolStripMenuItem duplicateTemplateToolStripMenuItem; private CommandToolStripMenuItem uninstallTemplateToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem; private CommandToolStripMenuItem bugToolToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator14; //private System.Windows.Forms.ToolStripMenuItem LicenseManagerMenuItem; //private CommandToolStripMenuItem installNewUpdateToolStripMenuItem; //private System.Windows.Forms.ToolStripSeparator toolStripSeparator6; private System.Windows.Forms.ToolStripMenuItem preferencesToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem windowToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem helpTopicsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem helpContextMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem15; private System.Windows.Forms.ToolStripMenuItem viewApplicationLogToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem17; private System.Windows.Forms.ToolStripMenuItem xenSourceOnTheWebToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator7; private System.Windows.Forms.ToolStripMenuItem aboutXenSourceAdminToolStripMenuItem; private XenAdmin.Controls.MenuStripEx MainMenuBar; private System.Windows.Forms.Panel MenuPanel; //private System.Windows.Forms.ToolStripSeparator toolStripSeparator13; private System.Windows.Forms.ToolStripSeparator toolStripSeparator24; private System.Windows.Forms.ToolStripMenuItem toolbarToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem ShowHiddenObjectsToolStripMenuItem; internal System.Windows.Forms.TabControl TheTabControl; private System.Windows.Forms.TabPage TabPageHome; internal System.Windows.Forms.TabPage TabPageSearch; internal System.Windows.Forms.TabPage TabPageGeneral; private System.Windows.Forms.TabPage TabPageBallooning; internal System.Windows.Forms.TabPage TabPageConsole; private System.Windows.Forms.TabPage TabPageStorage; private System.Windows.Forms.TabPage TabPagePhysicalStorage; private System.Windows.Forms.TabPage TabPageSR; private System.Windows.Forms.TabPage TabPageNetwork; private System.Windows.Forms.TabPage TabPageNICs; private System.Windows.Forms.TabPage TabPagePeformance; private System.Windows.Forms.TabPage TabPageHA; private System.Windows.Forms.TabPage TabPageHAUpsell; internal System.Windows.Forms.TabPage TabPageWLB; private System.Windows.Forms.TabPage TabPageWLBUpsell; private System.Windows.Forms.TabPage TabPageSnapshots; private System.Windows.Forms.TabPage TabPageDockerProcess; internal System.Windows.Forms.TabPage TabPageDockerDetails; private XenAdmin.TabPages.SnapshotsPage snapshotPage; private System.Windows.Forms.ToolStripMenuItem connectDisconnectToolStripMenuItem; private CommandToolStripMenuItem connectAllToolStripMenuItem; private CommandToolStripMenuItem DisconnectToolStripMenuItem; private CommandToolStripMenuItem disconnectAllToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem sendCtrlAltDelToolStripMenuItem; private CommandToolStripMenuItem virtualDisksToolStripMenuItem; private CommandToolStripMenuItem addVirtualDiskToolStripMenuItem; private CommandToolStripMenuItem attachVirtualDiskToolStripMenuItem; private CommandToolStripMenuItem NewVmToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator26; private System.Windows.Forms.ToolStripSeparator toolStripSeparator27; private System.Windows.Forms.ToolStripSeparator toolStripSeparator23; private System.Windows.Forms.ToolStripSeparator toolStripSeparator25; private System.Windows.Forms.ToolStripSeparator toolStripSeparator28; private System.Windows.Forms.ToolStripSeparator toolStripSeparator16; private CommandToolStripMenuItem templatePropertiesToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator29; private VMLifeCycleToolStripMenuItem startShutdownToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem8; private CommandToolStripMenuItem ReconnectToolStripMenuItem1; private XenAdmin.Controls.ToolTipContainer toolTipContainer1; private XenAdmin.Controls.LoggedInLabel loggedInLabel1; private CommandToolStripMenuItem reconnectAsToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator4; private CommandToolStripMenuItem poolReconnectAsToolStripMenuItem; internal System.Windows.Forms.TabPage TabPageAD; private System.Windows.Forms.TabPage TabPageGPU; private CommandToolStripMenuItem powerOnToolStripMenuItem; private CommandToolStripButton shutDownToolStripButton; private CommandToolStripButton startVMToolStripButton; private CommandToolStripButton powerOnHostToolStripButton; private CommandToolStripButton resumeToolStripButton; private MigrateVMToolStripMenuItem relocateToolStripMenuItem; private StartVMOnHostToolStripMenuItem startOnHostToolStripMenuItem; private ResumeVMOnHostToolStripMenuItem resumeOnToolStripMenuItem; private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem1; private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem; private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem2; private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem3; private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem4; private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem5; private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem6; private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem7; private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem9; private ToolStripMenuItem pluginItemsPlaceHolderToolStripMenuItem8; private TabPage TabPageBallooningUpsell; private ToolStripMenuItem xenCenterPluginsOnlineToolStripMenuItem; private CommandToolStripMenuItem MoveVMToolStripMenuItem; //private CommandToolStripMenuItem rollingUpgradeToolStripMenuItem; private CommandToolStripMenuItem changePoolPasswordToolStripMenuItem; private ToolStripSeparator toolStripSeparator30; private CommandToolStripMenuItem virtualAppliancesToolStripMenuItem; private AssignGroupToolStripMenuItemVM_appliance assignToVirtualApplianceToolStripMenuItem; private CommandToolStripMenuItem disasterRecoveryToolStripMenuItem; private CommandToolStripMenuItem DrWizardToolStripMenuItem; private CommandToolStripMenuItem drConfigureToolStripMenuItem; private CommandToolStripMenuItem securityGroupsToolStripMenuItem; private ToolStripSeparator toolStripMenuItem1; private CommandToolStripMenuItem HostPasswordToolStripMenuItem; private CommandToolStripMenuItem ChangeRootPasswordToolStripMenuItem; private CommandToolStripMenuItem forgetSavedPasswordToolStripMenuItem; private CommandToolStripMenuItem CreateVmFromTemplateToolStripMenuItem; private CommandToolStripMenuItem newVMFromTemplateToolStripMenuItem; private CommandToolStripMenuItem InstantVmToolStripMenuItem; private ToolStripMenuItem importSettingsToolStripMenuItem; private ToolStripMenuItem exportSettingsToolStripMenuItem; private ToolStripSeparator toolStripSeparator31; private CommandToolStripMenuItem destroyServerToolStripMenuItem; private CommandToolStripMenuItem restartToolstackToolStripMenuItem; private XenAdmin.Controls.MainWindowControls.NavigationPane navigationPane; private XenAdmin.TabPages.AlertSummaryPage alertPage; private XenAdmin.TabPages.ManageUpdatesPage updatesPage; private XenAdmin.TabPages.HistoryPage eventsPage; private ToolStripMenuItem customTemplatesToolStripMenuItem; private ToolStripMenuItem templatesToolStripMenuItem1; private ToolStripMenuItem localStorageToolStripMenuItem; private StatusStrip StatusStrip; private ToolStripStatusLabel statusLabel; private ToolStripProgressBar statusProgressBar; private CommandToolStripMenuItem reclaimFreedSpacetripMenuItem; private CommandToolStripButton startContainerToolStripButton; private CommandToolStripButton stopContainerToolStripButton; private CommandToolStripButton pauseContainerToolStripButton; private CommandToolStripButton resumeContainerToolStripButton; private CommandToolStripButton restartContainerToolStripButton; private CommandToolStripMenuItem healthCheckToolStripMenuItem1; private AssignGroupToolStripMenuItemVMSS assignSnapshotScheduleToolStripMenuItem; private CommandToolStripMenuItem VMSnapshotScheduleToolStripMenuItem; private TabPage TabPageADUpsell; private TabPage TabPageCvmConsole; private TabPage TabPagePvs; private CommandToolStripMenuItem controlDomainMemoryToolStripMenuItem; private CommandToolStripMenuItem enablePVSReadcachingToolStripMenuItem; private CommandToolStripMenuItem disablePVSReadcachingToolStripMenuItem; private TabPage TabPageUSB; private CommandToolStripMenuItem disableCbtToolStripMenuItem; private Label LicenseStatusTitleLabel; } }
62.300459
194
0.687671
[ "BSD-2-Clause" ]
GOMYWAY-NETWORKS-LLC/xenadmin
XenAdmin/MainWindow.Designer.cs
135,815
C#
// This file was automatically generated and may be regenerated at any // time. To ensure any changes are retained, modify the tool with any segment/component/group/field name // or type changes. namespace Machete.HL7Schema.V26.Maps { using V26; /// <summary> /// OUL_R22_RESULT (GroupMap) - /// </summary> public class OUL_R22_RESULTMap : HL7V26LayoutMap<OUL_R22_RESULT> { public OUL_R22_RESULTMap() { Segment(x => x.OBX, 0, x => x.Required = true); Segment(x => x.TCD, 1); Segment(x => x.SID, 2); Segment(x => x.NTE, 3); } } }
29
104
0.587774
[ "Apache-2.0" ]
ahives/Machete
src/Machete.HL7Schema/V26/Groups/Maps/OUL_R22_RESULTMap.cs
638
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; namespace NSprak.Language { public static class Symbols { public const char CommentStart = '#', StringBoundary = '\"', StringBoundaryAlternate = '\'', OpenBracket = '(', CloseBracket = ')', Comma = ',', DecimalPoint = '.', OpenSquareBracket = '[', CloseSquareBracket = ']', Minus = '-' ; public static readonly IReadOnlyList<char> KeySymbols; private readonly static HashSet<char> operatorCharacters; static Symbols() { KeySymbols = new char[] { OpenBracket, CloseBracket, OpenSquareBracket, CloseSquareBracket, Comma, Comma }; operatorCharacters = new HashSet<char>(Operator.All.SelectMany(x => x.Text.ToCharArray())); } public static bool IsKeyCharacter(char symbol) { return KeySymbols.Contains(symbol); } public static bool IsWordStart(char symbol) { return char.IsLetter(symbol) || symbol == '@' || symbol == '_'; } public static bool IsWordCharacter(char symbol) { return char.IsLetterOrDigit(symbol) || symbol == '@' || symbol == '_'; } public static bool IsStringStart(char symbol) { return symbol == StringBoundary || symbol == StringBoundaryAlternate; } public static bool IsNumberStart(char symbol) { // Question: does Sprak support decimal points at the start? return char.IsDigit(symbol) ; } public static bool IsNumberCharacter(char symbol) { // For now, simple decimals only. It might be worth implementing scientific notation // and alternate bases at some point, if sprak supports them return char.IsDigit(symbol) || symbol == DecimalPoint; } public static bool IsOperatorStart(char symbol) { return IsOperatorCharacter(symbol); } public static bool IsOperatorCharacter(char symbol) { return operatorCharacters.Contains(symbol); } public static bool IsCommentStart(char symbol) { return symbol == CommentStart; } public static bool IsUnkownStart(char symbol) { // Yup, I really need to remake this for general token types // as opposed to hardcoding each l'il thing if (IsKeyCharacter(symbol)) return false; if (IsWordStart(symbol)) return false; if (IsNumberStart(symbol)) return false; if (IsStringStart(symbol)) return false; if (IsOperatorStart(symbol)) return false; if (IsCommentStart(symbol)) return false; return true; } } }
27.350427
103
0.53875
[ "MIT" ]
Seti-0/NSprak
Source/NSprak/Language/Symbols.cs
3,202
C#
using System; using System.Collections.Generic; using System.Text; using MobExt.AndroidEnv.ControlsBase; using System.Drawing; using System.Runtime.InteropServices; using System.ComponentModel; using MobExt.ControlOperation; using MobExt.Common; using MobExt.Settings; using Android.Widget; using Android.Views; using Android.Content; namespace MobGE.MobControl { public class MobContextMenu : PopupMenu, IControlGlobalInit { public MobContextMenu(Context context, View anchor) : base(context, anchor) { Name = string.Empty; } public string Name { get; set; } public virtual void globalRead(IEnvironment pEnv, ISettings pSettings) { // // _isGlobalInited = true; InitForGlobal.read(this, getGlobalObjactName(), pEnv, pSettings); // } public virtual void globalWrite(IEnvironment pEnv, ISettings pSettings) { InitForGlobal.write(this, getGlobalObjactName(), pEnv, pSettings); } public virtual string getGlobalObjactName() { return string.Empty; } bool _isGlobalInited = false; public bool isGlobalInited() { return _isGlobalInited; } } }
22.215385
80
0.573407
[ "MIT" ]
rualb/ava-agent-xamarin
AvaGE/MobControl/MobContextMenu.cs
1,444
C#
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class BGController : MonoBehaviour { [SerializeField] RectTransform topDoor; [SerializeField] RectTransform bottomDoor; [SerializeField] float moveSpeed = 2f; [SerializeField] float yMaxTopDoor; [SerializeField] float yMinBottomDoor; [SerializeField] AudioClip soundOnDoorClosed; [SerializeField] string soundSourceName = "Sound for doors"; AudioSource audioSource; float minPosTopDoor; float maxPosBottomDoor; float imageHeight; public enum DoorMovingMode { Open = 1, Close = -1 } void Awake() { Messenger<Action>.AddListener(MyMenuEvents.OPEN_DOORS, StartMoveDoor); Messenger<Action>.AddListener(MyMenuEvents.CLOSE_DOORS, CloseDoors); Messenger<DoorMovingMode>.AddListener(MyMenuEvents.MOMENT_SWITCH_DOORS, OneMomentChageDoorsStatus); imageHeight = topDoor.rect.height * topDoor.localScale.y; float middlePos = yMaxTopDoor - (yMaxTopDoor - yMinBottomDoor) / 2f; minPosTopDoor = middlePos + imageHeight / 2; maxPosBottomDoor = middlePos - imageHeight / 2; } void Start() { audioSource = GameObject.Find(soundSourceName).GetComponent<AudioSource>(); audioSource.ignoreListenerVolume = true; DontDestroyOnLoad(audioSource.gameObject); } void OnDestroy() { Messenger<Action>.RemoveListener(MyMenuEvents.OPEN_DOORS, StartMoveDoor); Messenger<Action>.RemoveListener(MyMenuEvents.CLOSE_DOORS, CloseDoors); Messenger<DoorMovingMode>.RemoveListener(MyMenuEvents.MOMENT_SWITCH_DOORS, OneMomentChageDoorsStatus); } void StartMoveDoor(Action d) { StartCoroutine(DoorMoving(d, DoorMovingMode.Open)); } void CloseDoors(Action d) { StartCoroutine(DoorMoving(d, DoorMovingMode.Close)); } void OneMomentChageDoorsStatus(DoorMovingMode mode) { Vector2 tmp; if (mode == DoorMovingMode.Close) { tmp = topDoor.localPosition; tmp.y = minPosTopDoor; topDoor.localPosition = tmp; tmp = bottomDoor.localPosition; tmp.y = maxPosBottomDoor; bottomDoor.localPosition = tmp; BGStatus.status = BGStatus.Status.Closed; } else { tmp = topDoor.localPosition; tmp.y = yMaxTopDoor; topDoor.localPosition = tmp; tmp = bottomDoor.localPosition; tmp.y = yMinBottomDoor; bottomDoor.localPosition = tmp; BGStatus.status = BGStatus.Status.Opened; } } IEnumerator DoorMoving(Action d, DoorMovingMode mode) { while(true) { if ((mode == DoorMovingMode.Open && topDoor.localPosition.y < yMaxTopDoor) || (mode == DoorMovingMode.Close && topDoor.localPosition.y > minPosTopDoor)) topDoor.localPosition += (int)mode * Vector3.up * Time.deltaTime * moveSpeed; if ((mode == DoorMovingMode.Open && bottomDoor.localPosition.y > yMinBottomDoor) || (mode == DoorMovingMode.Close && bottomDoor.localPosition.y < maxPosBottomDoor )) bottomDoor.localPosition += (int)mode * Vector3.down * Time.deltaTime * moveSpeed; if (mode == DoorMovingMode.Close) { if (topDoor.localPosition.y <= minPosTopDoor && bottomDoor.localPosition.y >= maxPosBottomDoor) { Vector2 tmp = topDoor.localPosition; tmp.y = minPosTopDoor; topDoor.localPosition = tmp; tmp = bottomDoor.localPosition; tmp.y = maxPosBottomDoor; bottomDoor.localPosition = tmp; BGStatus.status = BGStatus.Status.Closed; if (audioSource != null && soundOnDoorClosed != null) { audioSource.PlayOneShot(soundOnDoorClosed); } break; } } else { if (topDoor.localPosition.y >= yMaxTopDoor && bottomDoor.localPosition.y <= yMinBottomDoor) { Vector2 tmp = topDoor.localPosition; tmp.y = yMaxTopDoor; topDoor.localPosition = tmp; tmp = bottomDoor.localPosition; tmp.y = yMinBottomDoor; bottomDoor.localPosition = tmp; BGStatus.status = BGStatus.Status.Opened; break; } } yield return null; } if (d != null) d.Invoke(); } }
30.91875
177
0.591672
[ "MIT" ]
logwinow/Portfolio
Hold at zero/Assets/Scripts/Main menu/BGController.cs
4,949
C#
namespace TradeBot.TwsAbstractions { public enum SecurityTypes { // Stock STK, // Option OPT, // Future FUT, // Index IND, // Future on an option FOP, // Forex pair CASH, // Combo order BAG, // Warrant WAR, // News events for underlying contracts NEWS } // Additional order types are documented here: // https://www.interactivebrokers.com/en/software/api/apiguide/tables/supported_order_types.htm public enum OrderTypes { // Limit LMT, // Market MKT } public enum TimeInForce { // Valid for the day only DAY, // Good until canceled // The order will continue to work within the system and in the marketplace until // it executes or is canceled. GTC orders will be automatically be cancelled under // the following conditions: If a corporate action on a security results in a stock // split (forward or reverse), exchange for shares, or distribution of shares. // If you do not log into your IB account for 90 days. // At the end of the calendar quarter following the current quarter. For example, // an order placed during the third quarter of 2011 will be canceled at the end of // the first quarter of 2012. If the last day is a non-trading day, the cancellation // will occur at the close of the final trading day of that quarter. For example, if the // last day of the quarter is Sunday, the orders will be cancelled on the preceding Friday. // Orders that are modified will be assigned a new “Auto Expire” date consistent with // the end of the calendar quarter following the current quarter. // Orders submitted to IB that remain in force for more than one day will not be reduced // for dividends. To allow adjustment to your order price on ex-dividend date, // consider using a Good-Til-Date/Time(GTD) or Good-after-Time/Date(GAT) order type, // or a combination of the two. GTC, // Immediate or Cancel // Any portion that is not filled as soon as it becomes available in the market is canceled. IOC, // Good until Date // It will remain working within the system and in the marketplace until it executes // or until the close of the market on the date specified. GTD, // Use OPG to send a market-on-open(MOO) or limit-on-open(LOO) order. OPG, // Fill-or-Kill // If the entire Fill-or-Kill order does not execute as soon as it becomes available, // then the entire order is canceled. FOK, // Day until Canceled DTC } public enum OrderActions { BUY, SELL } public enum Currencies { USD, GBP } public enum Exchanges { SMART } // Error codes are documented at: // http://interactivebrokers.github.io/tws-api/message_codes.html public static class ErrorCodes { public const int TICKER_NOT_FOUND = 200; // Occurs when cancelMktData has already been called for a tickerId. public const int TICKER_ID_NOT_FOUND = 300; public const int NOT_CONNECTED = 504; public const int MARKET_DATA_FARM_DISCONNECTED = 2103; public const int MARKET_DATA_FARM_CONNECTED = 2104; public const int HISTORICAL_DATA_FARM_DISCONNECTED = 2105; public const int HISTORICAL_DATA_FARM_CONNECTED = 2106; public const int HISTORICAL_DATA_FARM_INACTIVE = 2107; public const int MARKET_DATA_FARM_INACTIVE = 2108; // Occurs when an order will change the position in an account from long to short or from short to long. public const int CROSS_SIDE_WARNING = 2137; } }
35.303571
112
0.629489
[ "MIT" ]
mark-hennessy/tws-cli
TradeBot/TwsAbstractions/TwsApiConstants.cs
3,960
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.Runtime.InteropServices; internal static partial class Interop { internal static partial class libcrypto { [DllImport(Libraries.LibCrypto)] internal static extern void EVP_PKEY_free(IntPtr pkey); } }
27.2
101
0.742647
[ "MIT" ]
fffej/corefx
src/Common/src/Interop/Unix/libcrypto/Interop.EvpPkey.cs
408
C#
using NPOI.SS.UserModel; namespace NPOI.SS.FluentExtensions { /// <summary> /// Provides a data structure which can be used to accumulate /// styling options via a Fluent API, until they need to be applied /// to a cell. /// </summary> public partial class FluentStyle { /// <summary> /// Gets or sets the horizontal alignment. /// </summary> /// <value> /// The alignment. /// </value> public HorizontalAlignment? Alignment { get; set; } /// <summary> /// Gets or sets the border bottom style. /// </summary> /// <value> /// The border bottom. /// </value> public BorderStyle? BorderBottom { get; set; } /// <summary> /// Gets or sets the border diagonal. /// </summary> /// <value> /// The border diagonal. /// </value> public BorderDiagonal? BorderDiagonal { get; set; } /// <summary> /// Gets or sets the diagonal border color. /// </summary> /// <value> /// The color of the border diagonal. /// </value> public short? BorderDiagonalColor { get; set; } /// <summary> /// Gets or sets the diagonal border line style. /// </summary> /// <value> /// The border diagonal line style. /// </value> public BorderStyle? BorderDiagonalLineStyle { get; set; } /// <summary> /// Gets or sets the left border style. /// </summary> /// <value> /// The border left. /// </value> public BorderStyle? BorderLeft { get; set; } /// <summary> /// Gets or sets the right border style. /// </summary> /// <value> /// The border right. /// </value> public BorderStyle? BorderRight { get; set; } /// <summary> /// Gets or sets the top border style. /// </summary> /// <value> /// The border top. /// </value> public BorderStyle? BorderTop { get; set; } /// <summary> /// Gets or sets the color of the bottom border. /// </summary> /// <value> /// The color of the bottom border. /// </value> public short? BottomBorderColor { get; set; } /// <summary> /// Gets or sets the data format. /// </summary> /// <value> /// The data format. /// </value> public short? DataFormat { get; set; } /// <summary> /// Gets or sets the background fill color. /// </summary> /// <value> /// The color of the fill background. /// </value> public short? FillBackgroundColor { get; set; } /// <summary> /// Gets or sets the foreground fill color. /// </summary> /// <value> /// The color of the fill foreground. /// </value> public short? FillForegroundColor { get; set; } /// <summary> /// Gets or sets the fill pattern. /// </summary> /// <value> /// The fill pattern. /// </value> public FillPattern? FillPattern { get; set; } /// <summary> /// Gets or sets the indention. /// </summary> /// <value> /// The indention. /// </value> public short? Indention { get; set; } /// <summary> /// Gets or sets the color of the left border. /// </summary> /// <value> /// The color of the left border. /// </value> public short? LeftBorderColor { get; set; } /// <summary> /// Gets or sets the color of the right border. /// </summary> /// <value> /// The color of the right border. /// </value> public short? RightBorderColor { get; set; } /// <summary> /// Gets or sets the rotation. /// </summary> /// <value> /// The rotation. /// </value> public short? Rotation { get; set; } /// <summary> /// Gets or sets the shrink to fit setting. /// </summary> /// <value> /// The shrink to fit setting. /// </value> public bool? ShrinkToFit { get; set; } /// <summary> /// Gets or sets the color of the top border. /// </summary> /// <value> /// The color of the top border. /// </value> public short? TopBorderColor { get; set; } /// <summary> /// Gets or sets the vertical alignment. /// </summary> /// <value> /// The vertical alignment. /// </value> public VerticalAlignment? VerticalAlignment { get; set; } /// <summary> /// Gets or sets the wrap text setting. /// </summary> /// <value> /// The wrap text setting. /// </value> public bool? WrapText { get; set; } /// <summary> /// Gets or sets the format, e.g. "0.00%". /// If used, overrides the <see cref="DataFormat"/> property when the style is applied. /// </summary> /// <value> /// The format. /// </value> public string Format { get; set; } } }
29.173684
96
0.463107
[ "MIT" ]
PhilipDaniels/TestParser
NPOI.SS.FluentExtensions/FluentStyle.MainProperties.cs
5,545
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("22.08.2016 - 01. Second Nature")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("22.08.2016 - 01. Second Nature")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("53870994-7cca-4ceb-85d6-097b70f14d8b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.72973
84
0.740405
[ "MIT" ]
IvelinMarinov/SoftUni
04. C# Advanced - May2017/00. Exam Preparation/22.08.2016 - 01. Second Nature/Properties/AssemblyInfo.cs
1,436
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.IO; namespace Microsoft.SqlTools.ServiceLayer.LanguageExtensibility.Contracts { public enum ExternalLanguagePlatform { None, Windows, Linux } /// <summary> /// Language metadata /// </summary> public class ExternalLanguage { /// <summary> /// Language Name /// </summary> public string Name { get; set; } /// <summary> /// Language Owner /// </summary> public string Owner { get; set; } public List<ExternalLanguageContent> Contents { get; set; } /// <summary> /// Created Date /// </summary> public string CreatedDate { get; set; } } public class ExternalLanguageContent { public bool IsLocalFile { get; set; } /// <summary> /// Path to extension file /// </summary> public string PathToExtension { get; set; } /// <summary> /// Extension file name /// </summary> public string ExtensionFileName { get; set; } /// <summary> /// Platform name /// </summary> public ExternalLanguagePlatform PlatformId { get { return string.IsNullOrWhiteSpace(Platform) ? ExternalLanguagePlatform.None : (ExternalLanguagePlatform)Enum.Parse(typeof(ExternalLanguagePlatform), Platform, true); } } public string Platform { get; set; } /// <summary> /// Extension parameters /// </summary> public string Parameters { get; set; } /// <summary> /// Environment variables /// </summary> public string EnvironmentVariables { get; set; } } }
23.47619
180
0.560852
[ "MIT" ]
Bhaskers-Blu-Org2/sqltoolsservice
src/Microsoft.SqlTools.ServiceLayer/LanguageExtensibility/Contracts/ExternalLanguageModel.cs
1,974
C#
#if WITH_GAME #if PLATFORM_32BITS using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace UnrealEngine { public partial class UCurveVector { static readonly int FloatCurves__Offset; public FRichCurve FloatCurves { get{ CheckIsValid();return (FRichCurve)Marshal.PtrToStructure(_this.Get()+FloatCurves__Offset, typeof(FRichCurve));} } static UCurveVector() { IntPtr NativeClassPtr=GetNativeClassFromName("CurveVector"); FloatCurves__Offset=GetPropertyOffset(NativeClassPtr,"FloatCurves"); } } } #endif #endif
20.482759
119
0.76936
[ "MIT" ]
RobertAcksel/UnrealCS
Engine/Plugins/UnrealCS/UECSharpDomain/UnrealEngine/GeneratedScriptFile_Game_32bits/UCurveVector_FixSize.cs
594
C#
namespace TrafficManager.Patch._CitizenManager { using HarmonyLib; using JetBrains.Annotations; [HarmonyPatch(typeof(CitizenManager), "ReleaseCitizen")] [UsedImplicitly] public static class ReleaseCitizenPatch { /// <summary> /// Notifies the extended citizen manager about a released citizen. /// </summary> [HarmonyPostfix] [UsedImplicitly] public static void Postfix(CitizenManager __instance, uint citizen) { Constants.ManagerFactory.ExtCitizenManager.OnReleaseCitizen(citizen); } } }
34.235294
81
0.680412
[ "MIT" ]
CitiesSkylinesMods/TMPE
TLM/TLM/Patch/_CitizenManager/ReleaseCitizenPatch.cs
584
C#
namespace Poke.API.Interfaces { public interface IUnitOfWorkRepository { IEmployeeRepository UserRepository { get; } } }
21
52
0.666667
[ "MIT" ]
juniorricardo/netcore-tests
APIs/Poke.API/Interfaces/IUnitOfWorkRepository.cs
149
C#
using System; using System.Threading.Tasks; namespace CheatSheetConsoleApp { class Ex20_2_CacheTaskResult { internal static void Run() { //Mainメソッドはasyncにできない //非同期メソッドを同期的に待機する場合、GetAwaiter().GetResult() が使える ExecuteAsync().GetAwaiter().GetResult(); } static async Task ExecuteAsync() { //"Executing time consuming method..." は最初の1回のみ表示され //2回目以降はキャッシュされたTaskをすぐに返している var r1 = await GetAsync(); var r2 = await GetAsync(); var r3 = await GetAsync(); } static Task<int> cache; static Task<int> GetAsync() { async Task<int> inner() { Console.WriteLine("Executing time consuming method..."); await Task.Delay(3000); return 1; } cache = cache ?? inner(); return cache; } } }
21.128205
64
0.610437
[ "MIT" ]
tanaka-takayoshi/CSharpCheatSheet
CheatSheetConsoleApp/Ex20_2_CacheTaskResult.cs
960
C#
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Xml.Schema; using System.Xml.Serialization; namespace Workday.RevenueManagement { [GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")] [Serializable] public class Billing_InstallmentObjectType : INotifyPropertyChanged { private Billing_InstallmentObjectIDType[] idField; private string descriptorField; [method: CompilerGenerated] [CompilerGenerated] public event PropertyChangedEventHandler PropertyChanged; [XmlElement("ID", Order = 0)] public Billing_InstallmentObjectIDType[] ID { get { return this.idField; } set { this.idField = value; this.RaisePropertyChanged("ID"); } } [XmlAttribute(Form = XmlSchemaForm.Qualified)] public string Descriptor { get { return this.descriptorField; } set { this.descriptorField = value; this.RaisePropertyChanged("Descriptor"); } } protected void RaisePropertyChanged(string propertyName) { PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
22.262295
136
0.737113
[ "MIT" ]
matteofabbri/Workday.WebServices
Workday.RevenueManagement/Billing_InstallmentObjectType.cs
1,358
C#
#pragma checksum "C:\Users\apple\Documents\GitHub\GameManager\Shared\NavMenu.razor" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "51d7b10b6d2d1c15339dc75c1d87d5c7b62d94aa" // <auto-generated/> #pragma warning disable 1591 namespace GameManager.Shared { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; #nullable restore #line 1 "C:\Users\apple\Documents\GitHub\GameManager\_Imports.razor" using System.Net.Http; #line default #line hidden #nullable disable #nullable restore #line 2 "C:\Users\apple\Documents\GitHub\GameManager\_Imports.razor" using System.Net.Http.Json; #line default #line hidden #nullable disable #nullable restore #line 3 "C:\Users\apple\Documents\GitHub\GameManager\_Imports.razor" using Microsoft.AspNetCore.Components.Forms; #line default #line hidden #nullable disable #nullable restore #line 4 "C:\Users\apple\Documents\GitHub\GameManager\_Imports.razor" using Microsoft.AspNetCore.Components.Routing; #line default #line hidden #nullable disable #nullable restore #line 5 "C:\Users\apple\Documents\GitHub\GameManager\_Imports.razor" using Microsoft.AspNetCore.Components.Web; #line default #line hidden #nullable disable #nullable restore #line 6 "C:\Users\apple\Documents\GitHub\GameManager\_Imports.razor" using Microsoft.AspNetCore.Components.WebAssembly.Http; #line default #line hidden #nullable disable #nullable restore #line 7 "C:\Users\apple\Documents\GitHub\GameManager\_Imports.razor" using Microsoft.JSInterop; #line default #line hidden #nullable disable public partial class NavMenu : Microsoft.AspNetCore.Components.ComponentBase { #pragma warning disable 1998 protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) { __builder.OpenElement(0, "div"); __builder.AddAttribute(1, "class", "top-row pl-4 navbar navbar-dark"); __builder.AddMarkupContent(2, "\r\n "); __builder.AddMarkupContent(3, "<a class=\"navbar-brand\" href>GameManager</a>\r\n "); __builder.OpenElement(4, "button"); __builder.AddAttribute(5, "class", "navbar-toggler"); __builder.AddAttribute(6, "onclick", Microsoft.AspNetCore.Components.EventCallback.Factory.Create<Microsoft.AspNetCore.Components.Web.MouseEventArgs>(this, #nullable restore #line 3 "C:\Users\apple\Documents\GitHub\GameManager\Shared\NavMenu.razor" ToggleNavMenu #line default #line hidden #nullable disable )); __builder.AddMarkupContent(7, "\r\n <span class=\"navbar-toggler-icon\"></span>\r\n "); __builder.CloseElement(); __builder.AddMarkupContent(8, "\r\n"); __builder.CloseElement(); __builder.AddMarkupContent(9, "\r\n\r\n"); __builder.OpenElement(10, "div"); __builder.AddAttribute(11, "class", #nullable restore #line 8 "C:\Users\apple\Documents\GitHub\GameManager\Shared\NavMenu.razor" NavMenuCssClass #line default #line hidden #nullable disable ); __builder.AddAttribute(12, "onclick", Microsoft.AspNetCore.Components.EventCallback.Factory.Create<Microsoft.AspNetCore.Components.Web.MouseEventArgs>(this, #nullable restore #line 8 "C:\Users\apple\Documents\GitHub\GameManager\Shared\NavMenu.razor" ToggleNavMenu #line default #line hidden #nullable disable )); __builder.AddMarkupContent(13, "\r\n "); __builder.OpenElement(14, "ul"); __builder.AddAttribute(15, "class", "nav flex-column"); __builder.AddMarkupContent(16, "\r\n "); __builder.OpenElement(17, "li"); __builder.AddAttribute(18, "class", "nav-item px-3"); __builder.AddMarkupContent(19, "\r\n "); __builder.OpenComponent<Microsoft.AspNetCore.Components.Routing.NavLink>(20); __builder.AddAttribute(21, "class", "nav-link"); __builder.AddAttribute(22, "href", ""); __builder.AddAttribute(23, "Match", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<Microsoft.AspNetCore.Components.Routing.NavLinkMatch>( #nullable restore #line 11 "C:\Users\apple\Documents\GitHub\GameManager\Shared\NavMenu.razor" NavLinkMatch.All #line default #line hidden #nullable disable )); __builder.AddAttribute(24, "ChildContent", (Microsoft.AspNetCore.Components.RenderFragment)((__builder2) => { __builder2.AddMarkupContent(25, "\r\n <span class=\"oi oi-home\" aria-hidden=\"true\"></span> Home\r\n "); } )); __builder.CloseComponent(); __builder.AddMarkupContent(26, "\r\n "); __builder.CloseElement(); __builder.AddMarkupContent(27, "\r\n "); __builder.OpenElement(28, "li"); __builder.AddAttribute(29, "class", "nav-item px-3"); __builder.AddMarkupContent(30, "\r\n "); __builder.OpenComponent<Microsoft.AspNetCore.Components.Routing.NavLink>(31); __builder.AddAttribute(32, "class", "nav-link"); __builder.AddAttribute(33, "href", "counter"); __builder.AddAttribute(34, "ChildContent", (Microsoft.AspNetCore.Components.RenderFragment)((__builder2) => { __builder2.AddMarkupContent(35, "\r\n <span class=\"oi oi-plus\" aria-hidden=\"true\"></span> Counter\r\n "); } )); __builder.CloseComponent(); __builder.AddMarkupContent(36, "\r\n "); __builder.CloseElement(); __builder.AddMarkupContent(37, "\r\n "); __builder.OpenElement(38, "li"); __builder.AddAttribute(39, "class", "nav-item px-3"); __builder.AddMarkupContent(40, "\r\n "); __builder.OpenComponent<Microsoft.AspNetCore.Components.Routing.NavLink>(41); __builder.AddAttribute(42, "class", "nav-link"); __builder.AddAttribute(43, "href", "fetchdata"); __builder.AddAttribute(44, "ChildContent", (Microsoft.AspNetCore.Components.RenderFragment)((__builder2) => { __builder2.AddMarkupContent(45, "\r\n <span class=\"oi oi-list-rich\" aria-hidden=\"true\"></span> Fetch data\r\n "); } )); __builder.CloseComponent(); __builder.AddMarkupContent(46, "\r\n "); __builder.CloseElement(); __builder.AddMarkupContent(47, "\r\n "); __builder.CloseElement(); __builder.AddMarkupContent(48, "\r\n"); __builder.CloseElement(); } #pragma warning restore 1998 #nullable restore #line 28 "C:\Users\apple\Documents\GitHub\GameManager\Shared\NavMenu.razor" private bool collapseNavMenu = true; private string NavMenuCssClass => collapseNavMenu ? "collapse" : null; private void ToggleNavMenu() { collapseNavMenu = !collapseNavMenu; } #line default #line hidden #nullable disable } } #pragma warning restore 1591
40.770492
176
0.645088
[ "MIT" ]
lorfakl/GameManager
obj/Debug/netstandard2.1/Razor/Shared/NavMenu.razor.g.cs
7,461
C#
using System.Collections.Generic; using System.Linq; namespace Frank.Scheduler.Extensions { public static class EnumerableExtensions { public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> items, int maxItems = 256) { return items.Select((item, inx) => new { item, inx }) .GroupBy(x => x.inx / maxItems) .Select(g => g.Select(x => x.item)); } } }
27.875
105
0.591928
[ "MIT" ]
frankhaugen/Frank.Scheduler
Frank.Scheduler/Extensions/EnumerableExtensions.cs
448
C#
// Copyright (c) Jeremy W. Kuhne. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace WInterop.Handles { // https://msdn.microsoft.com/en-us/library/windows/desktop/aa446633.aspx // ACCESS_MASK // https://msdn.microsoft.com/en-us/library/windows/desktop/aa374892.aspx /// <summary> /// [GENERIC_MAPPING] /// </summary> public struct GenericMapping { public uint GenericRead; public uint GenericWrite; public uint GenericExecute; public uint GenericAll; } }
30.45
101
0.678161
[ "MIT" ]
JeremyKuhne/WInterop
src/WInterop.Desktop/Handles/GenericMapping.cs
611
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using System.IO; using System.Windows.Forms; using RCCM; using MathWorks.MATLAB.NET.Arrays; namespace RepeatabilityTest { public class RepeatabilityTest : IRCCMPluginActor { protected readonly ICamera camera; protected readonly Motor motor; protected string path; protected int repetitions; protected double distance; public bool Running { get; protected set; } protected readonly RCCMSystem rccm; protected Thread testThread; public RepeatabilityTest(RCCMSystem rccm, Dictionary<string, string> parameters) { this.rccm = rccm; this.Running = false; // Create instance values from provided map from parameter name to user inputted value // Camera string must be one of 4 options switch (parameters["Camera"].ToLower()) { case "wfov 1": this.camera = rccm.WFOV1; break; case "wfov 2": this.camera = rccm.WFOV2; break; case "nfov 1": this.camera = rccm.NFOV1; break; case "nfov 2": this.camera = rccm.NFOV2; break; default: throw new ArgumentException("Camera must be nfov/wfov 1/2"); } this.path = (string)Program.Settings.json[parameters["Camera"]]["image directory"] + string.Format("\\Repeatability-{0:yyyy-MM-dd_hh-mm-ss-tt-fff}", DateTime.Now); Directory.CreateDirectory(this.path); // Actuator string must be one of 8 options try { this.motor = this.rccm.motors[parameters["Actuator"]]; } catch (KeyNotFoundException e) { throw new ArgumentException("Actuator must be coarse X/Y or fine 1/2 X/Y"); } // Extract numeric value from user input for repititions and move distance this.repetitions = Int32.Parse(parameters["Repetitions"]); this.distance = Double.Parse(parameters["Distance"]); } public void Run() { try { // Set running to true so main GUI knows that plugin has not finished this.Running = true; this.testThread = Thread.CurrentThread; // Repeatedly move and snap image for (int i = 0; i < this.repetitions; i++) { this.camera.Snap(this.path + "\\repeatability-" + i + ".bmp"); // Move actuator out and back this.motor.MoveRel(this.distance); this.motor.WaitForEndOfMove(); Thread.Sleep(200); this.motor.MoveRel(-this.distance); this.motor.WaitForEndOfMove(); Thread.Sleep(200); } this.camera.Snap(this.path + "\\repeatability-" + this.repetitions + ".bmp"); var imgProccessing = new MatlabDFTRegistration.DFTRegistration(); MWArray[] argsOut = imgProccessing.get_offsets(2, this.path); double[,] dx = (double[,])argsOut[0].ToArray(); double[,] dy = (double[,])argsOut[1].ToArray(); double stdX = this.CalculateStdev(dx); double stdY = this.CalculateStdev(dy); MessageBox.Show(string.Format("Standard deviation x: {0:0.00}, y: {1:0.00}", stdX, stdY)); using (StreamWriter file = new StreamWriter(this.path + "\\results.csv")) { for (int r = 0; r < dx.GetLength(0); r++) { double dxi = this.camera.Scale * dx[r, 0]; double dyi = this.camera.Scale * dy[r, 0]; file.WriteLine(dxi.ToString() + "," + dyi.ToString()); } } } catch (ThreadInterruptedException e) { return; } } // Stops the test by interrupting the test thread public void Stop() { this.Running = false; if (this.testThread != null) { this.testThread.Interrupt(); } } private double CalculateStdev(double[,] nums) { double sum = 0; for (int i = 0; i < nums.GetLength(0); i++) { sum += nums[i,0]; } double mean = sum / nums.GetLength(0); double sumSq = 0; for (int i = 0; i < nums.GetLength(0); i++) { sumSq += Math.Pow(nums[i, 0] - mean, 2); } return this.camera.Scale * Math.Sqrt(sumSq / (nums.GetLength(0) - 1)); } } }
37.107143
106
0.495669
[ "MIT" ]
jmal0/RCCM
RCCM/Plugins/RepeatabilityTest/RepeatabilityTest/RepeatabilityTest.cs
5,197
C#