コード例 #1
0
        public MethodBase Resolve(MethodReference methodReference, GenericBindingContext bindingContext)
        {
            Type declaringType = _typeResolver.Resolve(methodReference.DeclaringType);

            BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.ExactBinding;

            flags |= methodReference.HasThis ? BindingFlags.Instance : BindingFlags.Static;

            IEnumerable <MethodBase> candidates = IsConstructor(methodReference.Name)
                ? (IEnumerable <MethodBase>)declaringType.GetConstructors(flags)
                : declaringType.GetMethods(flags);

            MethodBase result;

            if (methodReference.IsGenericInstance)
            {
                MethodBase genericMethod = Resolve(methodReference.Resolve(), bindingContext);

                result = BindGenericArguments(methodReference, genericMethod);
            }
            else
            {
                TypeReference[] parameterTypes = methodReference.Parameters.Select(parameter =>
                                                                                   parameter.ParameterType).ToArray();

                result = FindMethod(candidates, methodReference.Name, parameterTypes,
                                    methodReference.HasGenericParameters, bindingContext);
            }

            return(result);
        }
コード例 #2
0
        public ReviewRule EvaluateRule <Model, Context>(
            RuleMetadata metadata, Model model, Context context)
        {
            var rule = typeResolver.Resolve <IRule <Model, Context> >(metadata.RuleType);

            return(new ReviewRule()
            {
                BusinessId = metadata.BusinessId,
                Message = rule.Message,
                IsSatisfied = rule.IsSatisfiedBy(model, context)
            });
        }
コード例 #3
0
    public object?Resolve(Type?type)
    {
        if (type == null)
        {
            throw new CommandRuntimeException("Cannot resolve null type.");
        }

        try
        {
            var obj = _resolver?.Resolve(type);
            if (obj != null)
            {
                return(obj);
            }

            // Fall back to use the activator.
            return(Activator.CreateInstance(type));
        }
        catch (CommandAppException)
        {
            throw;
        }
        catch (Exception ex)
        {
            throw CommandRuntimeException.CouldNotResolveType(type, ex);
        }
    }
コード例 #4
0
        public IMessage Parse(ConsumeResult <Guid, byte[]> consumeResult)
        {
            if (consumeResult is null)
            {
                throw new ArgumentNullException(nameof(consumeResult));
            }
            if (consumeResult.Message?.Headers is null)
            {
                throw new ArgumentNullException(nameof(consumeResult), "message headers are missing");
            }

            var messageTypeHeader = consumeResult.Message.Headers.FirstOrDefault(h => h.Key == HeaderNames.MessageType);

            if (messageTypeHeader is null)
            {
                throw new ArgumentException("invalid message type");
            }

            var messageTypeName = Encoding.UTF8.GetString(messageTypeHeader.GetValueBytes());
            var messageType     = _typeResolver.Resolve(messageTypeName);
            var decodedObj      = _serializer.Deserialize(consumeResult.Message.Value, messageType);

            if (decodedObj is not IMessage message)
            {
                throw new ArgumentException($"message has the wrong type: '{messageTypeName}'");
            }
            return(message);
        }
コード例 #5
0
        public object Resolve(Type type)
        {
            try
            {
                if (_resolver != null)
                {
                    var obj = _resolver.Resolve(type);
                    if (obj == null)
                    {
                        throw RuntimeException.CouldNotResolveType(type);
                    }
                    return(obj);
                }

                // Fall back to use the activator.
                return(Activator.CreateInstance(type));
            }
            catch (CommandAppException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw RuntimeException.CouldNotResolveType(type, ex);
            }
        }
コード例 #6
0
ファイル: CommandProcessor.cs プロジェクト: martijngr/MemGrow
        public CommandResult Handle(object command)
        {
            var     handlerType = typeof(ICommandHandler <>).MakeGenericType(command.GetType());
            dynamic handler     = _typeResolver.Resolve(handlerType);

            return(handler.Handle((dynamic)command));
        }
コード例 #7
0
 private Dictionary <VariableReference, LocalBuilder> AddVariables(IILGenerator generator,
                                                                   IEnumerable <VariableReference> variables)
 {
     return(variables.ToDictionary(
                variable => variable,
                variable => generator.DeclareLocal(_typeResolver.Resolve(variable.VariableType))));
 }
コード例 #8
0
        public void ShowSingleton <T>(object identifier, ITypeResolver resolvr)
            where T : WorkspaceVmBase
        {
            T wrkspce = (T)MainTabs.Where(x => x is T)
                        .FirstOrDefault(x => x.GetHashCode()
                                        == x.HashCodeFor(identifier));

            if (wrkspce == null)
            {
                try {
                    wrkspce = ForwardLogs(resolvr.Resolve <T>());
                }
                catch (Exception ex)
                {
                    Error_n("Error in ShowSingleton<T>()",
                            $"Unable to create instance of ‹{typeof(T).Name}›."
                            + L.F + ex.Details(false, false));
                    return;
                }
                MainTabs.Add(wrkspce);
                wrkspce.SetIdentifier(identifier);
                wrkspce.Refresh();
            }

            SetActiveWorkspace(wrkspce);
            return;
        }
コード例 #9
0
        /// <summary>
        /// Resolves the supplied <paramref name="typeName"/> to a
        /// <see cref="System.Type"/>
        /// instance.
        /// </summary>
        /// <param name="typeName">
        /// The (possibly partially assembly qualified) name of a
        /// <see cref="System.Type"/>.
        /// </param>
        /// <returns>
        /// A resolved <see cref="System.Type"/> instance.
        /// </returns>
        /// <exception cref="System.TypeLoadException">
        /// If the supplied <paramref name="typeName"/> could not be resolved
        /// to a <see cref="System.Type"/>.
        /// </exception>
        public Type Resolve(string typeName)
        {
            Guard.ArgumentNotNullOrEmpty("typeName", typeName);

            Type type = null;

            try
            {
                type = _typeCache[typeName] as Type;
                if (type == null)
                {
                    lock (_typeCache)
                    {
                        type = _typeCache[typeName] as Type;
                        if (type == null)
                        {
                            type = _typeResolver.Resolve(typeName);
                            _typeCache[typeName] = type;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex is TypeLoadException)
                {
                    throw;
                }

                ThrowHelper.ThrowTypeLoadExcetpion(ex, "ÀàÐͼÓÔØʧ°Ü", typeName);
            }

            return(type);
        }
コード例 #10
0
ファイル: TestHost.cs プロジェクト: ALealC/blip-sdk-csharp
        private IServiceContainer BuildServiceContainer(Application application, ITypeResolver typeResolver)
        {
            var serviceProviderType = typeResolver.Resolve(application.ServiceProviderType);
            var serviceProvider     = (IServiceProvider)Activator.CreateInstance(serviceProviderType);

            return(new OverridableServiceContainer(serviceProvider));
        }
コード例 #11
0
ファイル: YamlConverters.cs プロジェクト: Hadisalman/PSRule
            public IObjectDescriptor Read(object target)
            {
                var propertyValue = _PropertyInfo.GetValue(target);
                var actualType    = TypeOverride ?? _TypeResolver.Resolve(Type, propertyValue);

                return(new ObjectDescriptor(propertyValue, actualType, Type, ScalarStyle));
            }
コード例 #12
0
        public static IServiceContainer BuildServiceProvider(Application application, ITypeResolver typeResolver)
        {
            var localServiceProvider = new TypeServiceProvider();

            if (application.ServiceProviderType != null)
            {
                var serviceProviderType = typeResolver.Resolve(application.ServiceProviderType);
                if (serviceProviderType != null)
                {
                    if (!typeof(IServiceProvider).IsAssignableFrom(serviceProviderType))
                    {
                        throw new InvalidOperationException($"{application.ServiceProviderType} must be an implementation of '{nameof(IServiceProvider)}'");
                    }

                    if (serviceProviderType == typeof(TypeServiceProvider))
                    {
                        throw new InvalidOperationException($"{nameof(Application.ServiceProviderType)} type cannot be '{serviceProviderType.Name}'");
                    }

                    if (serviceProviderType.GetConstructors(BindingFlags.Instance | BindingFlags.Public).All(c => c.GetParameters().Length != 0))
                    {
                        throw new InvalidOperationException($"{nameof(Application.ServiceProviderType)} must have an empty public constructor");
                    }

                    localServiceProvider.SecondaryServiceProvider = (IServiceProvider)Activator.CreateInstance(serviceProviderType);
                }
            }

            if (localServiceProvider.SecondaryServiceProvider is IServiceContainer serviceContainer)
            {
                return(serviceContainer);
            }

            return(localServiceProvider);
        }
コード例 #13
0
        /// <summary>
        /// Resolve the service given its name and the optional parameters
        /// </summary>
        /// <returns>The resolved service</returns>
        /// <param name="serviceName">Service name.</param>
        /// <param name="parameters">Parameters.</param>
        public object Resolve(string serviceName, List <Parameter> parameters)
        {
            // now the service type is the full type name
            var serviceType = _typeResolver.Resolve(serviceName);

            // Decode the parameters into the relevant types..
            var namedParameters = parameters?.Select(parameter =>
            {
                var resolvedType = _typeResolver.Resolve(parameter.ValueType);
                var value        = JsonConvert.DeserializeObject(parameter.Value.ToString(), resolvedType);
                var np           = new NamedParameter(parameter.Name, value);
                return(np);
            });

            return(_container.Resolve(serviceType, namedParameters));
        }
コード例 #14
0
            public IObjectDescriptor Read(object target)
            {
                object obj  = _propertyInfo.ReadValue(target);
                Type   type = TypeOverride ?? _typeResolver.Resolve(Type, obj);

                return(new ObjectDescriptor(obj, type, Type, ScalarStyle));
            }
コード例 #15
0
        /// <summary>
        /// Resolves the supplied <paramref name="typeName"/> to a
        /// <see cref="System.Type"/>
        /// instance.
        /// </summary>
        /// <param name="typeName">
        /// The (possibly partially assembly qualified) name of a
        /// <see cref="System.Type"/>.
        /// </param>
        /// <returns>
        /// A resolved <see cref="System.Type"/> instance.
        /// </returns>
        /// <exception cref="System.TypeLoadException">
        /// If the supplied <paramref name="typeName"/> could not be resolved
        /// to a <see cref="System.Type"/>.
        /// </exception>
        public Type Resolve(string typeName)
        {
            if (typeName == null || typeName.Trim().Length == 0)
            {
                throw new TypeLoadException("Could not load type from string value '" + typeName + "'.");
            }
            Type type = null;

            try
            {
                if (!_typeCache.TryGetValue(typeName, out type))
                {
                    type = _typeResolver.Resolve(typeName);
                    _typeCache[typeName] = type;
                }
            }
            catch (Exception ex)
            {
                if (ex is TypeLoadException)
                {
                    throw;
                }
                throw new TypeLoadException("Could not load type from string value '" + typeName + "'.", ex);
            }
            return(type);
        }
コード例 #16
0
        public IMessage Resolve(IBasicProperties basicProperties, ReadOnlyMemory <byte> body)
        {
            if (basicProperties is null)
            {
                throw new ArgumentNullException(nameof(basicProperties));
            }
            if (basicProperties.Headers is null)
            {
                throw new ArgumentNullException(nameof(basicProperties), "message headers are missing");
            }

            if (!basicProperties.Headers.TryGetValue(HeaderNames.MessageType, out var tmp) ||
                tmp is not byte[] messageTypeBytes ||
                messageTypeBytes is null)
            {
                throw new ArgumentException("invalid message type");
            }

            var messageTypeName = Encoding.UTF8.GetString(messageTypeBytes);

            var dataType = _typeResolver.Resolve(messageTypeName);

            if (dataType is null)
            {
                throw new ArgumentException("unable to detect message type from headers");
            }

            var decodedObj = _decoder.Deserialize(body, dataType);

            if (decodedObj is not IMessage message)
            {
                throw new ArgumentException($"message has the wrong type: '{messageTypeName}'");
            }
            return(message);
        }
コード例 #17
0
        public T Deserialize <T>(XElement data, StreamingContext context)
        {
            var declaredType = typeof(T);
            var atr          = data.Attribute("type");
            var type         = atr != null?TypeResolver.Resolve(atr.Value) ?? declaredType : declaredType;

            if (!declaredType.IsAssignableFrom(type) || atr == null)
            {
                if (declaredType.IsClass || declaredType.IsValueType)
                {
                    type = declaredType;
                }
                else if (atr == null)
                {
                    Logger.Trace(() => data.ToString());
                    throw new FrameworkException(@"Couldn't resolve type from provided Xml. 
Root element should embed type attribute with class name or you should provide appropriate type T to Deserialize<T> method.
Trying to deserialize {0}.".With(declaredType.FullName));
                }
                else
                {
                    Logger.Trace(() => data.ToString());
                    throw new FrameworkException(@"Can't deserialize provided Xml to {0}. 
Type detected for Xml is {1}. Can't deserialize Xml to instance of {1}.".With(declaredType.FullName, type.FullName));
                }
            }
            var document = new XmlDocument();

            using (var newReader = data.CreateReader())
            {
                document.AppendChild(document.ReadNode(newReader));
                using (var oldReader = new XmlNodeReader(document.DocumentElement))
                    return((T)Deserialize(type, oldReader, context));
            }
        }
コード例 #18
0
        /// <summary>
        ///     Resolves the supplied <paramref name="typeName" /> to a
        ///     <see cref="System.Type" />
        ///     instance.
        /// </summary>
        /// <param name="typeName">
        ///     The (possibly partially assembly qualified) name of a
        ///     <see cref="System.Type" />.
        /// </param>
        /// <returns>
        ///     A resolved <see cref="System.Type" /> instance.
        /// </returns>
        /// <exception cref="System.TypeLoadException">
        ///     If the supplied <paramref name="typeName" /> could not be resolved
        ///     to a <see cref="System.Type" />.
        /// </exception>
        public Type Resolve(string typeName)
        {
            if (StringUtils.IsNullOrEmpty(typeName))
            {
                throw BuildTypeLoadException(typeName);
            }
            Type type;

            try
            {
                lock (_typeCache.SyncRoot)
                {
                    type = _typeCache[typeName] as Type;
                    if (type == null)
                    {
                        type = _typeResolver.Resolve(typeName);
                        _typeCache[typeName] = type;
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex is TypeLoadException)
                {
                    throw;
                }
                throw BuildTypeLoadException(typeName, ex);
            }
            return(type);
        }
コード例 #19
0
ファイル: MessageParser.cs プロジェクト: plunix/OpenSleigh
        public TM Resolve <TM>(IBasicProperties basicProperties, ReadOnlyMemory <byte> body)
            where TM : IMessage
        {
            if (basicProperties is null)
            {
                throw new ArgumentNullException(nameof(basicProperties));
            }
            if (basicProperties.Headers is null)
            {
                throw new ArgumentNullException(nameof(basicProperties), "message headers are missing");
            }

            if (!basicProperties.Headers.TryGetValue(HeaderNames.MessageType, out var tmp) ||
                tmp is not byte[] messageTypeBytes ||
                messageTypeBytes is null)
            {
                throw new ArgumentException("invalid message type");
            }

            var messageTypeName = Encoding.UTF8.GetString(messageTypeBytes);

            var dataType = _typeResolver.Resolve(messageTypeName);

            var decodedObj = _decoder.Decode(body, dataType);

            if (decodedObj is not TM message)
            {
                throw new ArgumentException($"type '{messageTypeName}' is not a valid message");
            }
            return(message);
        }
コード例 #20
0
ファイル: ObjectReconstructor.cs プロジェクト: anhzin/Dasync
        private Type ResolveType(TypeSerializationInfo info)
        {
            if (!_typeNameShortener.TryExpand(info.Name, out Type type))
            {
                if (_assemblyNameShortener.TryExpand(info.Assembly?.Name, out Assembly assembly))
                {
                    info.Assembly = assembly.ToAssemblySerializationInfo();
                }

                var infoForResolving = info.GenericArgs?.Length > 0
                    ? new TypeSerializationInfo
                {
                    Name     = info.Name,
                    Assembly = info.Assembly
                }
                    : info;
                type = _typeResolver.Resolve(infoForResolving);
            }

            if (type.IsGenericTypeDefinition())
            {
                var genericArguments = new Type[info.GenericArgs.Length];
                for (var i = 0; i < genericArguments.Length; i++)
                {
                    var genericArgument = ResolveType(info.GenericArgs[i]);
                    genericArguments[i] = genericArgument;
                }
                type = type.MakeGenericType(genericArguments);
            }

            return(type);
        }
コード例 #21
0
        /// <summary>
        /// Resolves the supplied <paramref name="typeName"/> to a
        /// <see cref="System.Type"/>
        /// instance.
        /// </summary>
        /// <param name="typeName">
        /// The (possibly partially assembly qualified) name of a
        /// <see cref="System.Type"/>.
        /// </param>
        /// <returns>
        /// A resolved <see cref="System.Type"/> instance.
        /// </returns>
        /// <exception cref="System.TypeLoadException">
        /// If the supplied <paramref name="typeName"/> could not be resolved
        /// to a <see cref="System.Type"/>.
        /// </exception>
        public Type Resolve(string typeName)
        {
            Check.Argument.IsNotEmpty("typeName", typeName);

            Type type = null;

            try
            {
                type = _typeCache[typeName] as Type;
                if (type == null)
                {
                    lock (_typeCache)
                    {
                        type = _typeCache[typeName] as Type;
                        if (type == null)
                        {
                            type = _typeResolver.Resolve(typeName);
                            _typeCache[typeName] = type;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex is TypeLoadException)
                {
                    throw;
                }

                ThrowHelper.ThrowTypeLoadExcetpion(ex, R.TypeLoadFail, typeName);
            }

            return(type);
        }
コード例 #22
0
        /// <summary>
        /// Gets a string attribute from the specified element with the given name
        /// </summary>
        /// <param name="element">Element to get the attribute from</param>
        /// <param name="name">Attribute name</param>
        /// <param name="resolver">Type name resolver</param>
        /// <param name="defaultType">Default type if not specified</param>
        /// <returns>Attribute value</returns>
        public static Type OptionalTypeAttribute(this XElement element, XName name, ITypeResolver resolver,
                                                 Type defaultType = null)
        {
            var attr = element.Attribute(name);

            return(attr == null ? defaultType : resolver.Resolve(attr.Value));
        }
コード例 #23
0
ファイル: JsonVisitor.cs プロジェクト: he-dev/reusable
 protected override JProperty VisitProperty(JProperty property)
 {
     return
         (SoftString.Comparer.Equals(property.Name, _typePropertyName)
             ? new JProperty(DefaultTypePropertyName, _typeResolver.Resolve(property.Value.Value <string>()))
             : base.VisitProperty(property));
 }
コード例 #24
0
        public object Resolve(Type type)
        {
            try
            {
                if (_resolver != null)
                {
                    var obj = _resolver.Resolve(type);
                    if (obj == null)
                    {
                        throw new CommandAppException($"Could not resolve type '{type.FullName}'.");
                    }
                    return(obj);
                }

                // Fall back to use the activator.
                return(Activator.CreateInstance(type));
            }
            catch (CommandAppException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new CommandAppException($"Could not resolve type '{type.FullName}'.", ex);
            }
        }
コード例 #25
0
        public static T SUT <T>(this ITypeResolver resolvr) where T : ILogSource
        {
            if (!resolvr.HasLifetimeScope)
            {
                resolvr.BeginLifetimeScope();
            }

            if (_growl == null)
            {
                _growl = new GrowlListener(nameof(MustExtensions));
            }

            var obj = resolvr.Resolve <T>();

            obj.LogAdded += (s, e) =>
            {
                if (e.ShowAs == ShowLogAs.Intro)
                {
                    _lastTitle = e.Title;
                    return;
                }

                if (e.ShowAs == ShowLogAs.Outro)
                {
                    e.Title = _lastTitle;
                }

                var m = ShortLog.Format(e);
                OutputHelper.WriteLine(m);
            };

            obj.LogAdded += _growl.HandleLogEvent;

            return(obj);
        }
コード例 #26
0
ファイル: FieldResolver.cs プロジェクト: yeswanthepuri/Smocks
        public FieldInfo Resolve(FieldReference fieldReference)
        {
            Type      declaringType = _typeResolver.Resolve(fieldReference.DeclaringType);
            var       flags         = BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public;
            FieldInfo result        = declaringType.GetField(fieldReference.Name, flags);

            return(result);
        }
コード例 #27
0
        public static T Resolve <T>(this ITypeResolver typeResolver)
        {
            if (typeResolver == null)
            {
                throw new ArgumentNullException(nameof(typeResolver));
            }

            return((T)typeResolver.Resolve(typeof(T), null, null));
        }
コード例 #28
0
        private static CommandSettings CreateSettings(ITypeResolver resolver, Type settingsType)
        {
            if (resolver.Resolve(settingsType) is CommandSettings settings)
            {
                return(settings);
            }

            throw CommandParseException.CouldNotCreateSettings(settingsType);
        }
コード例 #29
0
        public static object Resolve(this ITypeResolver typeResolver, Type type, object[] args)
        {
            if (typeResolver == null)
            {
                throw new ArgumentNullException(nameof(typeResolver));
            }

            return(typeResolver.Resolve(type, null, args));
        }
コード例 #30
0
        public static T Resolve <T>(this ITypeResolver typeResolver, object context, object[] args)
        {
            if (typeResolver == null)
            {
                throw new ArgumentNullException(nameof(typeResolver));
            }

            return((T)typeResolver.Resolve(typeof(T), context, args));
        }
コード例 #31
0
        public static PersistentReturnType Resolve(IReturnType source, ITypeResolver typeResolver)
        {
            if (source == null) return null;

            PersistentReturnType rt = new PersistentReturnType ();
            rt.FullyQualifiedName = typeResolver.Resolve (source.FullyQualifiedName);
            rt.pointerNestingLevel = source.PointerNestingLevel;
            rt.arrayDimensions = source.ArrayDimensions;
            return rt;
        }
コード例 #32
0
        public static PersistentClass Resolve(IClass sclass, ITypeResolver typeResolver)
        {
            PersistentClass cls = new PersistentClass ();

            cls.FullyQualifiedName = sclass.FullyQualifiedName;
            cls.Documentation = sclass.Documentation;

            cls.modifiers          = sclass.Modifiers;
            cls.classType          = sclass.ClassType;

            foreach (string t in sclass.BaseTypes)
                cls.baseTypes.Add (typeResolver.Resolve (t));

            foreach (IClass c in sclass.InnerClasses)
                cls.innerClasses.Add (PersistentClass.Resolve (c,typeResolver));

            foreach (IField f in sclass.Fields)
                cls.fields.Add (PersistentField.Resolve (f, typeResolver));

            foreach (IProperty p in sclass.Properties)
                cls.properties.Add (PersistentProperty.Resolve (p, typeResolver));

            foreach (IMethod m in sclass.Methods)
                cls.methods.Add (PersistentMethod.Resolve (m, typeResolver));

            foreach (IEvent e in sclass.Events)
                cls.events.Add (PersistentEvent.Resolve (e, typeResolver));

            foreach (IIndexer i in sclass.Indexer)
                cls.indexer.Add (PersistentIndexer.Resolve (i, typeResolver));

            cls.region = sclass.Region;
            return cls;
        }
        public static IEnumerable<object> GetDependencies(this IEnumerable<ParameterInfo> parameterInfos, ITypeResolver typeResolver)
        {
            Func<ParameterInfo, object> selector = parameterInfo => typeResolver.Resolve(parameterInfo.ParameterType);

            return parameterInfos.Select(selector);
        }