Ejemplo n.º 1
0
 public Battery(string model, Type? batteryType, uint? hoursIdle, uint? hoursTalk)
 {
     this.model = model;
     this.batteryType = batteryType;
     this.hoursIdle = hoursIdle;
     this.hoursTalk = hoursTalk;
 }
        FieldType BuildSingleField <TSource, TReturn>(
            string name,
            Func <ResolveEfFieldContext <TDbContext, TSource>, Task <IQueryable <TReturn> > > resolve,
            Func <ResolveEfFieldContext <TDbContext, TSource>, TReturn, Task>?mutate,
            IEnumerable <QueryArgument>?arguments,
            Type?graphType,
            bool nullable,
            string?description)
            where TReturn : class
        {
            Guard.AgainstNullWhiteSpace(nameof(name), name);
            Guard.AgainstNull(nameof(resolve), resolve);

            graphType ??= GraphTypeFinder.FindGraphType <TReturn>();
            Type?wrappedType;

            if (nullable)
            {
                wrappedType = graphType;
            }
            else
            {
                wrappedType = typeof(NonNullGraphType <>).MakeGenericType(graphType);
            }

            return(new FieldType
            {
                Name = name,
                Type = wrappedType,
                Description = description,

                Arguments = ArgumentAppender.GetQueryArguments(arguments),

                Resolver = new AsyncFieldResolver <TSource, TReturn?>(
                    async context =>
                {
                    var efFieldContext = BuildContext(context);

                    var names = GetKeyNames <TReturn>();

                    var query = await resolve(efFieldContext);
                    query = includeAppender.AddIncludes(query, context);
                    query = query.ApplyGraphQlArguments(context, names);
                    var single = await WrappedSingle(name, graphType, query, context);

                    if (single != null)
                    {
                        if (await efFieldContext.Filters.ShouldInclude(context.UserContext, single))
                        {
                            if (mutate != null)
                            {
                                await mutate.Invoke(efFieldContext, single);
                            }
                            return single;
                        }
                    }

                    if (nullable)
                    {
                        return null;
                    }

                    throw new ExecutionError("Not found");
                })
            });
        }
Ejemplo n.º 3
0
        protected override PropertyInfo?GetPropertyImpl(string name, BindingFlags bindingAttr, Binder?binder, Type?returnType, Type[]?types, ParameterModifier[]?modifiers)
        {
            // Unfortunately we cannot directly call the protected GetPropertyImpl on _typeInfo.
            PropertyInfo?property;

            if (types == null)
            {
                // if types is null, we can ignore binder and modifiers
                if (returnType == null)
                {
                    property = _typeInfo.GetProperty(name, bindingAttr);
                }
                else
                {
                    // Ideally we should call a GetProperty overload that takes name, returnType, and bindingAttr, but not types.
                    // But such an overload doesn't exist. On the other hand, this also guarantees that bindingAttr will be
                    // the default lookup flags if types is null but returnType is not.
                    Debug.Assert(bindingAttr == (BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public));

                    property = _typeInfo.GetProperty(name, returnType);
                }
            }
            else
            {
                property = _typeInfo.GetProperty(name, bindingAttr, binder, returnType, types, modifiers);
            }

            return(property);
        }
Ejemplo n.º 4
0
 public override bool IsAssignableFrom([NotNullWhen(true)] Type?c)
 {
     return(_typeInfo.IsAssignableFrom(c));
 }
Ejemplo n.º 5
0
 public TestInputCmdHandler(Type?forType = null, string name = "")
 {
     ForType   = forType;
     this.name = name;
 }
Ejemplo n.º 6
0
 public object?ConvertBack(object?value, Type?targetType, object?parameter, string?language)
 {
     // CastExceptions will occur when invalid value, or target type provided.
     return(ConvertBack((TTarget?)value, parameter, language));
 }
Ejemplo n.º 7
0
 public DynamicMethod(string name, Type?returnType, Type[]?parameterTypes) : this(name, returnType, parameterTypes, false)
 {
 }
Ejemplo n.º 8
0
 public DynamicMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type?returnType, Type[]?parameterTypes, Type owner, bool skipVisibility) : this(name, attributes, callingConvention, returnType, parameterTypes, owner, owner?.Module, skipVisibility, false, true)
 {
 }
Ejemplo n.º 9
0
 public IPermission?RemovePermission(Type?permClass)
 {
     return(RemovePermissionImpl(permClass));
 }
Ejemplo n.º 10
0
 public static bool FindTypeFromFile(this List <Type> types, string file, out Type?type)
 {
     var withoutExtension = file[..file.LastIndexOf('.')];
        public MCMv3PropertyDefinitionWithCustomFormatterWrapper(object @object) : base(@object)
        {
            var type = @object.GetType();

            CustomFormatter = AccessTools2.Property(type, nameof(CustomFormatter))?.GetValue(@object) as Type;
        }
Ejemplo n.º 12
0
 private static bool IsStepType(Type?t) => t != null && typeof(IStep).IsAssignableFrom(t);
Ejemplo n.º 13
0
        private void RunOneRoundOfInitialization()
        {
            int startedThisRound = 0;

            foreach ((Type discoveredStep, bool dependenciesInitialized) in _discoveredSteps)
            {
                if (_allStarted.Contains(discoveredStep))
                {
                    continue;
                }

                Type?stepBaseType = GetStepBaseType(discoveredStep);
                if (stepBaseType == null)
                {
                    throw new StepDependencyException($"Discovered step is not of step type {discoveredStep}");
                }

                if (_hasFinishedExecution[stepBaseType])
                {
                    continue;
                }

                if (!dependenciesInitialized)
                {
                    continue;
                }

                IStep?step;
                try
                {
                    step = Activator.CreateInstance(discoveredStep, _context) as IStep;
                }
                catch (Exception e)
                {
                    if (_logger.IsError)
                    {
                        _logger.Error($"Unable to create instance of Ethereum runner step of type {discoveredStep}", e);
                    }
                    continue;
                }

                if (step == null)
                {
                    if (_logger.IsError)
                    {
                        _logger.Error($"Unable to create instance of Ethereum runner step of type {discoveredStep}");
                    }
                    continue;
                }

                if (_logger.IsDebug)
                {
                    _logger.Debug($"Executing step: {step.GetType().Name}");
                }

                if (step is ISubsystemStateAware subsystemStateAware)
                {
                    subsystemStateAware.SubsystemStateChanged += SubsystemStateAwareOnSubsystemStateChanged;
                }

                Stopwatch stopwatch = Stopwatch.StartNew();
                Task      task      = step.Execute();
                startedThisRound++;
                Task continuationTask = task.ContinueWith(t =>
                {
                    stopwatch.Stop();

                    if (t.IsFaulted)
                    {
                        if (_logger.IsError)
                        {
                            _logger.Error($"Step {step.GetType().Name.PadRight(24)} failed after {stopwatch.ElapsedMilliseconds}ms", t.Exception);
                        }
                        _context.LogManager.GetClassLogger().Error($"FAILED TO INIT {stepBaseType.Name}", t.Exception);
                        _hasFinishedExecution[stepBaseType] = true;
                    }
                    else
                    {
                        if (_logger.IsInfo)
                        {
                            _logger.Info($"Step {step.GetType().Name.PadRight(24)} executed in {stopwatch.ElapsedMilliseconds}ms");
                        }
                        _hasFinishedExecution[stepBaseType] = true;
                    }
                });

                _allStarted.Add(discoveredStep);

                if (step.MustInitialize)
                {
                    _allPending.Add(continuationTask);
                }
                else
                {
                    _hasFinishedExecution[discoveredStep] = true;
                }
            }

            if (startedThisRound == 0 && _allPending.All(t => t.IsCompleted))
            {
                Interlocked.Increment(ref _foreverLoop);
                if (_foreverLoop > 100)
                {
                    if (_logger.IsWarn)
                    {
                        _logger.Warn($"Didn't start any initialization steps during initialization round and all previous steps are already completed.");
                    }
                }
            }
        }
Ejemplo n.º 14
0
 private Type?GetStepBaseType(Type?type) => IsStepType(type?.BaseType) ? GetStepBaseType(type?.BaseType) : type;
Ejemplo n.º 15
0
        public static string MakeVersionSafeName(string?name, ResourceScope from, ResourceScope to, Type?type)
        {
            ResourceScope fromResType = from & ResTypeMask;
            ResourceScope toResType   = to & ResTypeMask;

            if (fromResType > toResType)
            {
                throw new ArgumentException(SR.Format(SR.Argument_ResourceScopeWrongDirection, fromResType, toResType), nameof(from));
            }

            SxSRequirements requires = GetRequirements(to, from);

            if ((requires & (SxSRequirements.AssemblyName | SxSRequirements.TypeName)) != 0 && type == null)
            {
                throw new ArgumentNullException(nameof(type), SR.ArgumentNull_TypeRequiredByResourceScope);
            }

            // Add in process ID, CLR base address, and appdomain ID's.  Also, use a character identifier
            // to ensure that these can never accidentally overlap (ie, you create enough appdomains and your
            // appdomain ID might equal your process ID).
            StringBuilder safeName  = new StringBuilder(name);
            char          separator = '_';

            if ((requires & SxSRequirements.ProcessID) != 0)
            {
                safeName.Append(separator);
                safeName.Append('p');
                safeName.Append(Environment.ProcessId);
            }
            if ((requires & SxSRequirements.CLRInstanceID) != 0)
            {
                string clrID = GetCLRInstanceString();
                safeName.Append(separator);
                safeName.Append('r');
                safeName.Append(clrID);
            }
            if ((requires & SxSRequirements.AppDomainID) != 0)
            {
                safeName.Append(separator);
                safeName.Append("ad");
                safeName.Append(AppDomain.CurrentDomain.Id);
            }
            if ((requires & SxSRequirements.TypeName) != 0)
            {
                safeName.Append(separator);
                safeName.Append(type !.Name);
            }
            if ((requires & SxSRequirements.AssemblyName) != 0)
            {
                safeName.Append(separator);
                safeName.Append(type !.Assembly.FullName);
            }
            return(safeName.ToString());
        }
Ejemplo n.º 16
0
 public DynamicMethod(string name, Type?returnType, Type[]?parameterTypes, Type owner, bool skipVisibility) : this(name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, owner, skipVisibility)
 {
 }
Ejemplo n.º 17
0
 public IPermission?GetPermission(Type?permClass)
 {
     return(GetPermissionImpl(permClass));
 }
Ejemplo n.º 18
0
 public DynamicMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type?returnType, Type[]?parameterTypes, Module m, bool skipVisibility) : this(name, attributes, callingConvention, returnType, parameterTypes, null, m, skipVisibility, false, false)
 {
 }
Ejemplo n.º 19
0
 protected virtual IPermission?GetPermissionImpl(Type?permClass)
 {
     return(default(IPermission));
 }
Ejemplo n.º 20
0
 public static object GenerateValueExpression(this Foo model, string fieldName = nameof(Foo.Name), Type?fieldType = null) => Utility.GenerateValueExpression(model, fieldName, fieldType ?? typeof(string));
Ejemplo n.º 21
0
 public virtual Task <object> GetEntityAsync(Uri absoluteUri,
                                             string?role,
                                             Type?ofObjectToReturn)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 22
0
 public override Task <TEntity> NewAsync(IParent?parent, Type?variantType = null)
 {
     return(Task.FromResult(new TEntity()));
 }
 /// <summary>
 /// Specifies the PropertyEditorType.
 /// </summary>
 /// <typeparam name="TEditor">The type of the t editor.</typeparam>
 /// <returns>ModelBuilderPropertyEditorOptions.</returns>
 /// <autogeneratedoc />
 public ModelBuilderPropertyEditorOptions Editor <TEditor>()
     where TEditor : PropertyEditor
 {
     PropertyEditorType = typeof(TEditor);
     return(this);
 }
Ejemplo n.º 24
0
        protected sealed override PropertyInfo?GetPropertyImpl(string name, BindingFlags bindingAttr, Binder?binder, Type?returnType, Type[]?types, ParameterModifier[]?modifiers)
        {
            Debug.Assert(name != null);

            // GetPropertyImpl() is a funnel for two groups of api. We can distinguish by comparing "types" to null.
            if (types == null && returnType == null)
            {
                // Group #1: This group of api accept only a name and BindingFlags. The other parameters are hard-wired by the non-virtual api entrypoints.
                Debug.Assert(binder == null);
                Debug.Assert(modifiers == null);
                return(Query <PropertyInfo>(name, bindingAttr).Disambiguate());
            }
            else
            {
                // Group #2: This group of api takes a set of parameter types, a return type (both cannot be null) and an optional binder.
                QueryResult <PropertyInfo> queryResult = Query <PropertyInfo>(name, bindingAttr);
                ListBuilder <PropertyInfo> candidates  = default;
                foreach (PropertyInfo candidate in queryResult)
                {
                    if (types == null || (candidate.GetIndexParameters().Length == types.Length))
                    {
                        candidates.Add(candidate);
                    }
                }

                if (candidates.Count == 0)
                {
                    return(null);
                }

                // For perf and .NET Framework compat, fast-path these specific checks before calling on the binder to break ties.
                if (types == null || types.Length == 0)
                {
                    // no arguments
                    if (candidates.Count == 1)
                    {
                        PropertyInfo firstCandidate = candidates[0];
                        if (!(returnType is null) && !returnType.IsEquivalentTo(firstCandidate.PropertyType))
                        {
                            return(null);
                        }
                        return(firstCandidate);
                    }
                    else
                    {
                        if (returnType is null)
                        {
                            // if we are here we have no args or property type to select over and we have more than one property with that name
                            throw new AmbiguousMatchException();
                        }
                    }
                }

                if ((bindingAttr & BindingFlags.ExactBinding) != 0)
                {
                    return(System.DefaultBinder.ExactPropertyBinding(candidates.ToArray(), returnType, types, modifiers));
                }

                binder ??= Loader.GetDefaultBinder();

                return(binder.SelectProperty(bindingAttr, candidates.ToArray(), returnType, types, modifiers));
            }
        }
Ejemplo n.º 25
0
 public ITypeBuilder DefineType(string type, TypeAttributes typeAttributes, Type?baseType = null)
 {
     return(new AsmTypeBuilder(Emitter, ModuleName, type, false, (baseType != null) ? baseType.FullName : typeof(object).FullName));
 }
Ejemplo n.º 26
0
 public override bool IsEquivalentTo([NotNullWhen(true)] Type?other)
 {
     return(_typeInfo.IsEquivalentTo(other));
 }
Ejemplo n.º 27
0
 public override bool CanConvertTo(ITypeDescriptorContext?context, [NotNullWhen(true)] Type?destinationType) =>
 destinationType == typeof(string) ||
 base.CanConvertTo(context, destinationType);
Ejemplo n.º 28
0
 protected override PropertyInfo?GetPropertyImpl(string name, BindingFlags bindingAttr, Binder?binder,
                                                 Type?returnType, Type[]?types, ParameterModifier[]?modifiers)
 {
     throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
 }
Ejemplo n.º 29
0
 // FIXME: "Visibility is not restricted"
 public DynamicMethod(string name, Type?returnType, Type[]?parameterTypes, bool restrictedSkipVisibility)
     : this(name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, null, null, restrictedSkipVisibility, true, false)
 {
 }
        internal static bool TryBuildImmutableForArrayContract(Type underlyingType, Type collectionItemType, [NotNullWhen(true)] out Type?createdType, [NotNullWhen(true)] out ObjectConstructor <object>?parameterizedCreator)
        {
            if (underlyingType.IsGenericType())
            {
                Type   underlyingTypeDefinition = underlyingType.GetGenericTypeDefinition();
                string name = underlyingTypeDefinition.FullName;

                ImmutableCollectionTypeInfo definition = ArrayContractImmutableCollectionDefinitions.FirstOrDefault(d => d.ContractTypeName == name);
                if (definition != null)
                {
                    Type createdTypeDefinition = underlyingTypeDefinition.Assembly().GetType(definition.CreatedTypeName);
                    Type builderTypeDefinition = underlyingTypeDefinition.Assembly().GetType(definition.BuilderTypeName);

                    if (createdTypeDefinition != null && builderTypeDefinition != null)
                    {
                        MethodInfo mb = builderTypeDefinition.GetMethods().FirstOrDefault(m => m.Name == "CreateRange" && m.GetParameters().Length == 1);
                        if (mb != null)
                        {
                            createdType = createdTypeDefinition.MakeGenericType(collectionItemType);
                            MethodInfo method = mb.MakeGenericMethod(collectionItemType);
                            parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(method);
                            return(true);
                        }
                    }
                }
            }

            createdType          = null;
            parameterizedCreator = null;
            return(false);
        }
Ejemplo n.º 31
0
        [DynamicDependency(nameof(owner))]  // Automatically keeps all previous fields too due to StructLayout
        private DynamicMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type?returnType, Type[]?parameterTypes, Type?owner, Module?m, bool skipVisibility, bool anonHosted, bool typeOwner)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }
            if (returnType == null)
            {
                returnType = typeof(void);
            }
            if (owner == null && typeOwner)
            {
                throw new ArgumentNullException(nameof(owner));
            }
            if ((m == null) && !anonHosted)
            {
                throw new ArgumentNullException(nameof(m));
            }
            if (parameterTypes != null)
            {
                for (int i = 0; i < parameterTypes.Length; ++i)
                {
                    if (parameterTypes[i] == null)
                    {
                        throw new ArgumentException($"Parameter {i} is null");
                    }
                }
            }
            if (owner != null && (owner.IsArray || owner.IsInterface))
            {
                throw new ArgumentException("Owner can't be an array or an interface.");
            }

            if (m == null)
            {
                m = AnonHostModuleHolder.AnonHostModule;
            }

            this.name              = name;
            this.attributes        = attributes | MethodAttributes.Static;
            this.callingConvention = callingConvention;
            this.returnType        = returnType;
            this.parameters        = parameterTypes;
            this.owner             = owner;
            this.module            = m;
            this.skipVisibility    = skipVisibility;
        }