Esempio n. 1
0
 public static void RegisterMethod(MethodInfo method)
 {
     if (method == null)
         throw new ArgumentNullException("method");
     methods.Add(method);
     foreach (RegistrarMethodHandler handler in methodhandlers)
     {
         handler(method);
     }
     if (method.IsDefined(typeof(RegistrarTypeHandlerAttribute),false))
     {
         RegistrarTypeHandler handler = (RegistrarTypeHandler)Delegate.CreateDelegate(typeof(RegistrarTypeHandler),method);
         typehandlers.Add(handler);
         foreach (Type type in types)
         {
             handler(type);
         }
     }
     if (method.IsDefined(typeof(RegistrarMethodHandlerAttribute),false))
     {
         RegistrarMethodHandler handler = (RegistrarMethodHandler)Delegate.CreateDelegate(typeof(RegistrarMethodHandler),method);
         methodhandlers.Add(handler);
         foreach (MethodInfo method2 in methods)
         {
             handler(method2);
         }
     }
 }
Esempio n. 2
0
        public static PhpMemberAttributes GetMemberAttributes(MethodInfo/*!*/ info)
        {
            PhpMemberAttributes value = PhpMemberAttributes.None;

            if (info.IsPublic) value |= PhpMemberAttributes.Public;
            else if (info.IsFamily) value |= PhpMemberAttributes.Protected;
            else if (info.IsPrivate) value |= PhpMemberAttributes.Private;

            if (info.IsStatic)
            {
                value |= (PhpMemberAttributes.Static | PhpMemberAttributes.AppStatic);
            }

            // "finalness" and "abstractness" is stored as attributes, if the method is static, not in MethodInfo
            // (static+abstract, static+final are not allowed in CLR)
            //Debug.Assert(!(info.IsStatic && (info.IsFinal || info.IsAbstract)), "User static method cannot have CLR final or abstract modifier.");

            if (info.IsAbstract || info.IsDefined(typeof(PhpAbstractAttribute), false))
                value |= PhpMemberAttributes.Abstract;

            if (info.IsFinal || info.IsDefined(typeof(PhpFinalAttribute), false))
                value |= PhpMemberAttributes.Final;

            return value;
        }
        /// <summary>
        /// 应该保存审计
        /// </summary>
        /// <param name="methodInfo">方法信息</param>
        /// <param name="configuration">审计配置</param>
        /// <param name="abpSession">Abp会话</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns></returns>
        public static bool ShouldSaveAudit(MethodInfo methodInfo, IAuditingConfiguration configuration, IAbpSession abpSession, bool defaultValue = false)
        {
            //审计配置为null,或审计配置未启用,则返回false
            if (configuration == null || !configuration.IsEnabled)
            {
                return false;
            }

            //如果未启用匿名用户,并且AbpSession为null或用户Id为空,返回false
            if (!configuration.IsEnabledForAnonymousUsers && (abpSession == null || !abpSession.UserId.HasValue))
            {
                return false;
            }

            //如果方法信息为null
            if (methodInfo == null)
            {
                return false;
            }

            //如果方法信息不为公共方法
            if (!methodInfo.IsPublic)
            {
                return false;
            }

            //如果方法使用了AuditedAttribute审计自定义属性,则返回true
            if (methodInfo.IsDefined(typeof(AuditedAttribute)))
            {
                return true;
            }

            //如果方法使用了DisableAuditingAttribute禁用审计自定义属性,则返回false
            if (methodInfo.IsDefined(typeof(DisableAuditingAttribute)))
            {
                return false;
            }

            //获取声明该成员的类
            var classType = methodInfo.DeclaringType;
            if (classType != null)
            {
                if (classType.IsDefined(typeof(AuditedAttribute)))
                {
                    return true;
                }

                if (classType.IsDefined(typeof(DisableAuditingAttribute)))
                {
                    return false;
                }

                if (configuration.Selectors.Any(selector => selector.Predicate(classType)))
                {
                    return true;
                }
            }

            return defaultValue;
        }
        public bool ShouldSaveAudit(MethodInfo methodInfo, bool defaultValue = false)
        {
            if (!_configuration.IsEnabled)
            {
                return false;
            }

            if (!_configuration.IsEnabledForAnonymousUsers && (AbpSession?.UserId == null))
            {
                return false;
            }

            if (methodInfo == null)
            {
                return false;
            }

            if (!methodInfo.IsPublic)
            {
                return false;
            }

            if (methodInfo.IsDefined(typeof(AuditedAttribute), true))
            {
                return true;
            }

            if (methodInfo.IsDefined(typeof(DisableAuditingAttribute), true))
            {
                return false;
            }

            var classType = methodInfo.DeclaringType;
            if (classType != null)
            {
                if (classType.IsDefined(typeof(AuditedAttribute), true))
                {
                    return true;
                }

                if (classType.IsDefined(typeof(DisableAuditingAttribute), true))
                {
                    return false;
                }

                if (_configuration.Selectors.Any(selector => selector.Predicate(classType)))
                {
                    return true;
                }
            }

            return defaultValue;
        }
Esempio n. 5
0
        /// <summary>
        ///  <see cref="MethodInfo"/> 标记 <see cref="AuditedAttribute"/> 或者 <see cref="IAuditingConfiguration"/> 已经 将进行拦截,开启审计功能
        /// </summary>
        /// <param name="methodInfo"></param>
        /// <param name="configuration"></param>
        /// <param name="owSession"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static bool ShouldSaveAudit(MethodInfo methodInfo, IAuditingConfiguration configuration, IOwSession owSession, bool defaultValue = false)
        {
            if (configuration == null || !configuration.IsEnabled)
            {
                return false;
            }

            if (!configuration.IsEnabledForAnonymousUsers && (owSession == null || !owSession.UserId.HasValue))
            {
                return false;
            }

            if (methodInfo == null)
            {
                return false;
            }

            if (!methodInfo.IsPublic)
            {
                return false;
            }

            if (methodInfo.IsDefined(typeof(AuditedAttribute)))
            {
                return true;
            }

            if (methodInfo.IsDefined(typeof(DisableAuditingAttribute)))
            {
                return false;
            }
            //获取父类信息,判断是否开启审计
            var classType = methodInfo.DeclaringType;
            if (classType != null)
            {
                if (classType.IsDefined(typeof(AuditedAttribute)))
                {
                    return true;
                }

                if (classType.IsDefined(typeof(DisableAuditingAttribute)))
                {
                    return false;
                }

                if (configuration.Selectors.Any(selector => selector.Predicate(classType)))
                {
                    return true;
                }
            }

            return defaultValue;
        }
Esempio n. 6
0
        public ActionMethod(MethodInfo methodInfo)
        {
            _methodInfo = methodInfo;

            _filterAttributes = (ActionFilterAttribute[]) methodInfo.GetCustomAttributes(typeof(ActionFilterAttribute), false);

            OrderedAttribute.Sort(_filterAttributes);

            if (_methodInfo.IsDefined(typeof(LayoutAttribute), false))
                _defaultLayoutName = ((LayoutAttribute)_methodInfo.GetCustomAttributes(typeof(LayoutAttribute), false)[0]).LayoutName ?? "";

            if (_methodInfo.IsDefined(typeof(ViewAttribute), false))
                _defaultViewName = ((ViewAttribute)_methodInfo.GetCustomAttributes(typeof(ViewAttribute), false)[0]).ViewName ?? "";
        }
Esempio n. 7
0
        public LateBoundMethod CreateGet(MethodInfo method)
        {
            ParameterExpression instanceParameter = Expression.Parameter(typeof(object), "target");
            ParameterExpression argumentsParameter = Expression.Parameter(typeof(object[]), "arguments");

            MethodCallExpression call;
            if (!method.IsDefined(typeof(ExtensionAttribute), false))
            {
                // instance member method
                call = Expression.Call(
                    Expression.Convert(instanceParameter, method.DeclaringType),
                    method,
                    CreateParameterExpressions(method, instanceParameter, argumentsParameter));
            }
            else
            {
                // static extension method
                call = Expression.Call(
                    method,
                    CreateParameterExpressions(method, instanceParameter, argumentsParameter));
            }

            Expression<LateBoundMethod> lambda = Expression.Lambda<LateBoundMethod>(
                Expression.Convert(call, typeof(object)),
                instanceParameter,
                argumentsParameter);

            return lambda.Compile();
        }
        public static bool ShouldValidate(
            this IAbpAntiForgeryManager manager,
            IAbpAntiForgeryWebConfiguration antiForgeryWebConfiguration,
            MethodInfo methodInfo, 
            HttpVerb httpVerb, 
            bool defaultValue)
        {
            if (!antiForgeryWebConfiguration.IsEnabled)
            {
                return false;
            }

            if (methodInfo.IsDefined(typeof(ValidateAbpAntiForgeryTokenAttribute), true))
            {
                return true;
            }

            if (ReflectionHelper.GetSingleAttributeOfMemberOrDeclaringTypeOrDefault<DisableAbpAntiForgeryTokenValidationAttribute>(methodInfo) != null)
            {
                return false;
            }

            if (antiForgeryWebConfiguration.IgnoredHttpVerbs.Contains(httpVerb))
            {
                return false;
            }

            if (methodInfo.DeclaringType?.IsDefined(typeof(ValidateAbpAntiForgeryTokenAttribute), true) ?? false)
            {
                return true;
            }

            return defaultValue;
        }
        /// <summary>
        /// Does the supplied <paramref name="method"/> satisfy this matcher?
        /// </summary>
        /// <param name="method">The candidate method.</param>
        /// <param name="targetType">The target <see cref="System.Type"/> (may be <see langword="null"/>,
        /// in which case the candidate <see cref="System.Type"/> must be taken
        /// to be the <paramref name="method"/>'s declaring class).</param>
        /// <returns>
        /// 	<see langword="true"/> if this this method matches statically.
        /// </returns>
        /// <remarks>
        /// 	<p>
        /// Must be implemented by a derived class in order to specify matching
        /// rules.
        /// </p>
        /// </remarks>
        public override bool Matches(MethodInfo method, Type targetType)
        {
            if (method.IsDefined(attributeType, true))
            {
                // Checks whether the attribute is defined on the method or a super definition of the method
                // but does not check attributes on implemented interfaces.
                return true;
            }
            else
            {
                
                    Type[] parameterTypes = ReflectionUtils.GetParameterTypes(method);

                    // Also check whether the attribute is defined on a method implemented from an interface.
                    // First find all interfaces for the type that contains the method.
                    // Next, check each interface for the presence of the attribute on the corresponding
                    // method from the interface.
                    foreach (Type interfaceType in method.DeclaringType.GetInterfaces())
                    {
                        MethodInfo intfMethod = interfaceType.GetMethod(method.Name, parameterTypes);
                        if (intfMethod != null && intfMethod.IsDefined(attributeType, true))
                        {
                            return true;
                        }
                    }
                
                return false;
            }
        }
 /// <summary>
 /// Construct from a MethodInfo
 /// </summary>
 /// <param name="method"></param>
 public ParameterizedMethodSuite(MethodInfo method)
     : base(method.ReflectedType.FullName, method.Name)
 {
     Method = method;
     _isTheory = method.IsDefined(typeof(TheoryAttribute), true);
     this.MaintainTestOrder = true;
 }
        private Boolean AllowsUnauthorized(Type authorizedControllerType, MethodInfo method)
        {
            if (method.IsDefined(typeof(AuthorizeAttribute), false)) return false;
            if (method.IsDefined(typeof(AllowAnonymousAttribute), false)) return true;
            if (method.IsDefined(typeof(AllowUnauthorizedAttribute), false)) return true;

            while (authorizedControllerType != typeof(Controller))
            {
                if (authorizedControllerType.IsDefined(typeof(AuthorizeAttribute), false)) return false;
                if (authorizedControllerType.IsDefined(typeof(AllowAnonymousAttribute), false)) return true;
                if (authorizedControllerType.IsDefined(typeof(AllowUnauthorizedAttribute), false)) return true;

                authorizedControllerType = authorizedControllerType.BaseType;
            }

            return true;
        }
		protected virtual bool IsActionMethod(MethodInfo method)
        {
            Precondition.Require(method, () => Error.ArgumentNull("method"));

            if (method.IsDefined(typeof(IgnoreActionAttribute), false))
                return false;

            return (!method.IsAbstract && !method.IsSpecialName && !method.ContainsGenericParameters &&
                typeof(Controller).IsAssignableFrom(method.GetBaseDefinition().DeclaringType));
        }
        /// <inheritdoc/>
        public bool AcceptMethod(MethodInfo methodInfo)
        {
            if (methodInfo.IsDefined(typeof (NonInterceptedAttribute), false))
                return false;

            if (methodInfo.DeclaringType != typeof (object))
                return true;

            return !String.Equals(methodInfo.Name, DestructorMethodName);
        }
        public static bool IsExtensionMethod(System.Reflection.MethodInfo method)
        {
            Type mType           = method.DeclaringType;
            Type v_extensionType = typeof(ExtensionAttribute);

            return(mType.IsSealed() &&
                   !mType.IsGenericType() &&
                   !mType.IsNested() &&
                   method.IsDefined(v_extensionType, false));
        }
Esempio n. 15
0
		// These methods might be more commonly overridden for a given C++ ABI:

		public virtual MethodType GetMethodType (CppTypeInfo typeInfo, MethodInfo imethod)
		{
			if (IsInline (imethod) && !IsVirtual (imethod) && typeInfo.Library.InlineMethodPolicy == InlineMethods.NotPresent)
				return MethodType.NotImplemented;
			else if (imethod.IsDefined (typeof (ConstructorAttribute), false))
				return MethodType.NativeCtor;
			else if (imethod.Name.Equals ("Alloc"))
				return MethodType.ManagedAlloc;
			else if (imethod.IsDefined (typeof (DestructorAttribute), false))
				return MethodType.NativeDtor;

			return MethodType.Native;
		}
Esempio n. 16
0
        public AstReflectedMethod(MethodInfo method)
        {
            Argument.RequireNotNull("method", method);
            this.Method = method;
            this.ReturnType = method.ReturnType != typeof(void)
                            ? new AstReflectedType(method.ReturnType)
                            : (IAstTypeReference)AstVoidType.Instance;

            this.ParameterTypes = method.GetParameters()
                                        .Select(p => (IAstTypeReference)new AstReflectedType(p.ParameterType))
                                        .ToArray()
                                        .AsReadOnly();

            this.Location = method.IsDefined<ExtensionAttribute>(false) ? MethodLocation.Extension : MethodLocation.Target;
        }
Esempio n. 17
0
 private static bool GetMethodStep(MethodInfo methodInfo, out MethodStep step)
 {
     step = null;
     if (methodInfo.IsDefined(typeof (CommonMethodAtr), false))
     {
         if(IsParamterValid(methodInfo))
         {
             step = new MethodStep()
                 {
                     MethodInfo=methodInfo,
                     Type = (methodInfo.GetCustomAttributes(typeof(CommonMethodAtr), false)[0] as CommonMethodAtr).Type
                 };
             return true;
         }
     }
     return false;
 }
Esempio n. 18
0
        public static string GetSignature(MethodInfo m, bool correct)
        {
            var ps = m.GetParameters();
            var pss = ps.AsEnumerable();
            if (correct && ps.Length > 0 && ps[0].ParameterType == typeof(IQueryProvider))
                pss = pss.Skip(1);

            var gens = m.IsGenericMethod ? string.Format("<{0}>", string.Join(", ", m.GetGenericArguments().Select(a => GetTypeName(a, correct)).ToArray())) : "";

            var pars = string.Join(", ", pss.Select(p => (p.IsDefined(typeof(ParamArrayAttribute)) ? "params " : "") + GetTypeName(p.ParameterType, correct) + " " + p.Name).ToArray());
            if (m.IsDefined(typeof(ExtensionAttribute)))
            {
                if (pars.StartsWith("IQbservable") || pars.StartsWith("IQueryable"))
                    pars = "this " + pars;
            }

            return string.Format("{0} {1}{2}({3})", GetTypeName(m.ReturnType, correct), m.Name, gens, pars);
        }
        public static string GetMethodArgumentsSignature(this MethodInfo method, bool invokable)
        {
            var isExtensionMethod = method.IsDefined(typeof(System.Runtime.CompilerServices.ExtensionAttribute), false);
            var methodParameters  = method.GetParameters().AsEnumerable();

            // If this signature is designed to be invoked and it's an extension method
            if (isExtensionMethod && invokable)
            {
                // Skip the first argument
                methodParameters = methodParameters.Skip(1);
            }

            var methodParameterSignatures = methodParameters.Select(param => {
                var signature = string.Empty;

                if (param.ParameterType.IsByRef)
                {
                    signature = "ref ";
                }
                else if (param.IsOut)
                {
                    signature = "out ";
                }
                else if (isExtensionMethod && param.Position == 0)
                {
                    signature = "this ";
                }

                if (!invokable)
                {
                    signature += TypeSignatureTools.GetSignature(param.ParameterType) + " ";
                }

                signature += param.Name;

                return(signature);
            });

            var methodParameterString = "(" + string.Join(", ", methodParameterSignatures) + ")";

            return(methodParameterString);
        }
Esempio n. 20
0
        public AstReflectedMethod(MethodInfo method, Reflector reflector)
        {
            Argument.RequireNotNull("reflector", reflector);
            Argument.RequireNotNull("method", method);

            this.Method = method;
            this.ReturnType = method.ReturnType != typeof(void)
                            ? reflector.Reflect(method.ReturnType)
                            : AstVoidType.Instance;

            this.parameterTypes = new Lazy<ReadOnlyCollection<IAstTypeReference>>(
                () => method.GetParameters()
                            .Select(p => reflector.Reflect(p.ParameterType))
                            .ToArray()
                            .AsReadOnly()
            );

            this.genericParameterTypes = new Lazy<ReadOnlyCollection<IAstTypeReference>>(
                () => method.IsGenericMethodDefinition ? method.GetGenericArguments().Select(reflector.Reflect).ToArray().AsReadOnly() : No.Types
            );

            this.Location = method.IsDefined<ExtensionAttribute>(false) ? MethodLocation.Extension : MethodLocation.Target;
        }
Esempio n. 21
0
 private bool IsExtensionMethod(System.Reflection.MethodInfo m)
 {
     return(m.IsDefined(typeof(ExtensionAttribute), true));
 }
Esempio n. 22
0
        private static Expression[] CreateParameterExpressions(MethodInfo method, Expression instanceParameter, Expression argumentsParameter)
        {
            var expressions = new List<UnaryExpression>();
            var realMethodParameters = method.GetParameters();
            if (method.IsDefined(typeof(ExtensionAttribute), false))
            {
                Type extendedType = method.GetParameters()[0].ParameterType;
                expressions.Add(Expression.Convert(instanceParameter, extendedType));
                realMethodParameters = realMethodParameters.Skip(1).ToArray();
            }

            expressions.AddRange(realMethodParameters.Select((parameter, index) =>
                Expression.Convert(
                    Expression.ArrayIndex(argumentsParameter, Expression.Constant(index)),
                    parameter.ParameterType)));

            return expressions.ToArray();
        }
        private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameters, Type attributeType, MethodInfo currentCallback, ref Type prevAttributeType)
        {
            if (!method.IsDefined(attributeType, false))
            return false;

              if (currentCallback != null)
            throw new Exception("Invalid attribute. Both '{0}' and '{1}' in type '{2}' have '{3}'.".FormatWith(CultureInfo.InvariantCulture, method, currentCallback, GetClrTypeFullName(method.DeclaringType), attributeType));

              if (prevAttributeType != null)
            throw new Exception("Invalid Callback. Method '{3}' in type '{2}' has both '{0}' and '{1}'.".FormatWith(CultureInfo.InvariantCulture, prevAttributeType, attributeType, GetClrTypeFullName(method.DeclaringType), method));

              if (method.IsVirtual)
            throw new Exception("Virtual Method '{0}' of type '{1}' cannot be marked with '{2}' attribute.".FormatWith(CultureInfo.InvariantCulture, method, GetClrTypeFullName(method.DeclaringType), attributeType));

              if (method.ReturnType != typeof(void))
            throw new Exception("Serialization Callback '{1}' in type '{0}' must return void.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method));

              if (attributeType == typeof(OnErrorAttribute))
              {
            if (parameters == null || parameters.Length != 2 || parameters[0].ParameterType != typeof(StreamingContext) || parameters[1].ParameterType != typeof(ErrorContext))
              throw new Exception("Serialization Error Callback '{1}' in type '{0}' must have two parameters of type '{2}' and '{3}'.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method, typeof (StreamingContext), typeof(ErrorContext)));
              }
              else
              {
            if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != typeof(StreamingContext))
              throw new Exception("Serialization Callback '{1}' in type '{0}' must have a single parameter of type '{2}'.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method, typeof(StreamingContext)));
              }

              prevAttributeType = attributeType;

              return true;
        }
        /// <summary>
        /// Invokes the member method.
        /// </summary>
        /// <param name="instance">The object instance.</param>
        /// <param name="method">The method.</param>
        /// <param name="argValues">The argument values.</param>
        /// <returns>
        /// The result of invoking the method
        /// </returns>
        protected override object InvokeMemberMethod(object instance, MethodInfo method, object[] argValues)
        {
            ExceptionUtilities.CheckArgumentNotNull(method, "method");
            ExceptionUtilities.CheckArgumentNotNull(argValues, "argValues");

            if (method.IsDefined(typeof(ExtensionAttribute), true))
            {
                argValues = new object[] { instance }
                    .Concat(argValues)
                    .ToArray();
            }

            this.SpatialOperationsManager.IfValid(m => m.RegisterOperations());
            return base.InvokeMemberMethod(instance, method, argValues);
        }
Esempio n. 25
0
 public bool IsDefinedMethodOverrideHitInherit() => AttributedOverride.IsDefined(typeof(MyAttribute), true);
 public static bool IsAsyncOperation(MethodInfo method)
 {
     return AsyncStateMachineAttribute != null && method.IsDefined(AsyncStateMachineAttribute, false);
 }
Esempio n. 27
0
 public bool IsDefinedMethodBaseHitInherit() => AttributedBase.IsDefined(typeof(MyAttribute), true);
Esempio n. 28
0
 private static bool IsExtensionMethod(MethodInfo methodInfo)
 {
     return(methodInfo.IsDefined(typeof(ExtensionAttribute), true));
 }
Esempio n. 29
0
 public static bool HasUnitOfWorkAttribute(MethodInfo methodInfo)
 {
     return methodInfo.IsDefined(typeof(UnitOfWorkAttribute), true);
 }
Esempio n. 30
0
 public override bool IsDefined(Type attributeType, bool inherit)
 {
     return(_realMethod.IsDefined(attributeType, inherit));
 }
Esempio n. 31
0
 public bool IsDefinedMethodBaseMissInherit() => NonAttributedBase.IsDefined(typeof(MyAttribute), true);
Esempio n. 32
0
        private IEnumerable<ParameterDescriptor> GetParameters(MethodInfo method, StoreFunctionKind storeFunctionKind)
        {
            Debug.Assert(method != null, "method is null");

            foreach (var parameter in method.GetParameters())
            {
                if (method.IsDefined(typeof(ExtensionAttribute), false) && parameter.Position == 0)
                {
                    continue;
                }

                if (parameter.IsOut || parameter.ParameterType.IsByRef)
                {
                    throw new InvalidOperationException(
                        string.Format(
                            "The parameter '{0}' is an out or ref parameter. To map Input/Output database parameters use the 'ObjectParameter' as the parameter type.",
                            parameter.Name));
                }

                var parameterType = parameter.ParameterType;

                var isObjectParameter = parameter.ParameterType == typeof (ObjectParameter);
                if (isObjectParameter)
                {
                    var paramType = (ParameterTypeAttribute)Attribute.GetCustomAttribute(parameter, typeof (ParameterTypeAttribute));

                    if (paramType == null)
                    {
                        throw new InvalidOperationException(
                            string.Format(
                                "Cannot infer type for parameter '{0}'. All ObjectParameter parameters must be decorated with the ParameterTypeAttribute.",
                                parameter.Name));
                    }

                    parameterType = paramType.Type;
                }

                var unwrappedParameterType = Nullable.GetUnderlyingType(parameterType) ?? parameterType;

                var parameterEdmType =
                    unwrappedParameterType.IsEnum
                        ? FindEnumType(unwrappedParameterType)
                        : GetEdmPrimitiveTypeForClrType(unwrappedParameterType);

                if (parameterEdmType == null)
                {
                    throw
                        new InvalidOperationException(
                            string.Format(
                                "The type '{0}' of the parameter '{1}' of function '{2}' is invalid. Parameters can only be of a type that can be converted to an Edm scalar type",
                                unwrappedParameterType.FullName, parameter.Name, method.Name));
                }

                if (storeFunctionKind == StoreFunctionKind.ScalarUserDefinedFunction &&
                    parameterEdmType.BuiltInTypeKind != BuiltInTypeKind.PrimitiveType)
                {
                    throw new InvalidOperationException(
                        string.Format(
                            "The parameter '{0}' is of the '{1}' type which is not an Edm primitive type. Types of parameters of store scalar functions must be Edm primitive types.",
                            parameter.Name, parameterEdmType));
                }

                yield return new ParameterDescriptor(parameter.Name, parameterEdmType, isObjectParameter);
            }
        }
Esempio n. 33
0
 /// <summary>
 /// a function is static if it's a static .NET method and it's defined on the type or is an extension method 
 /// with StaticExtensionMethod decoration.
 /// </summary>
 private static bool IsStaticFunction(Type type, MethodInfo mi) {            
     return mi.IsStatic &&       // method must be truly static
         !mi.IsDefined(typeof(WrapperDescriptorAttribute), false) &&     // wrapper descriptors are instance methods
         (mi.DeclaringType.IsAssignableFrom(type) || mi.IsDefined(typeof(StaticExtensionMethodAttribute), false)); // or it's not an extension method or it's a static extension method
 }
Esempio n. 34
0
File: Utils.cs Progetto: klenin/Yuzu
 public void MaybeAdd(MethodInfo m, Type attr)
 {
     if (m.IsDefined(attr, false))
         Actions.Add(new MethodAction { Info = m, Run = obj => m.Invoke(obj, null) });
 }
        static bool IsValidAddon(MethodInfo mi, ParameterInfo[] parameters)
        {
            if (parameters.Length == 1) {
                var param = parameters[0];

                return mi.ReturnType == typeof(void)
                    && !mi.IsDefined(typeof(AddAttribute), false)
                    && !param.IsOut
                    && !param.ParameterType.IsByRef;
            }

            return false;
        }
Esempio n. 36
0
 /// <summary>
 /// Returns true if the method specified by the argument
 /// is an async method.
 /// </summary>
 public static bool IsAsyncMethod(MethodInfo method)
 {
     return method.IsDefined(typeof(System.Runtime.CompilerServices.AsyncStateMachineAttribute));
 }
        private MetadataParameter[] GetResponseParameters(MethodInfo method, string actionName)
        {
            var parameters = new List<MetadataParameter>();

            // add common parameters
            parameters.Add(new MetadataParameter("action", _helper.ToJsonType(typeof(string)), "Action name: " + actionName, true));
            if (method.IsDefined(typeof(ActionAttribute), true))
            {
                parameters.Add(new MetadataParameter("status", _helper.ToJsonType(typeof(string)), "Operation execution status (success or error).", true));
                parameters.Add(new MetadataParameter("requestId", _helper.ToJsonType(typeof(object)), "Request unique identifier as specified in the request message.", false));
            }

            // add parameters list from the XML response element
            var methodElement = _wsXmlCommentReader.GetMethodElement(method);
            var responseElement = methodElement == null ? null : methodElement.Element("response");
            if (responseElement != null)
            {
                _helper.AdjustParameters(parameters, responseElement, JsonMapperEntryMode.ToJson);
            }

            return parameters.ToArray();
        }
Esempio n. 38
0
 private static bool IsMethodDecoratedWithAliasingAttribute(MethodInfo methodInfo)
 {
     return methodInfo.IsDefined(typeof(ActionNameSelectorAttribute), true /* inherit */);
 }
        /// <summary>
        /// Return the method signature as a string.
        /// </summary>
        /// <param name="method">The Method</param>
        /// <param name="callable">Return as an callable string(public void a(string b) would return a(b))</param>
        /// <returns>Method signature</returns>
        public static string GetSignature(this MethodInfo method, bool callable = false)
        {
            var firstParam = true;
            var sigBuilder = new StringBuilder();

            if (callable == false)
            {
                if (method.IsPublic)
                {
                    sigBuilder.Append("public ");
                }
                else if (method.IsPrivate)
                {
                    sigBuilder.Append("private ");
                }
                else if (method.IsAssembly)
                {
                    sigBuilder.Append("internal ");
                }
                if (method.IsFamily)
                {
                    sigBuilder.Append("protected ");
                }
                if (method.IsStatic)
                {
                    sigBuilder.Append("static ");
                }
                sigBuilder.Append(TypeName(method.ReturnType));
                sigBuilder.Append(' ');
            }
            sigBuilder.Append(method.Name);

            // Add method generics
            if (method.IsGenericMethod)
            {
                sigBuilder.Append("<");
                foreach (var g in method.GetGenericArguments())
                {
                    if (firstParam)
                    {
                        firstParam = false;
                    }
                    else
                    {
                        sigBuilder.Append(", ");
                    }
                    sigBuilder.Append(TypeName(g));
                }
                sigBuilder.Append(">");
            }
            sigBuilder.Append("(");
            firstParam = true;
            var secondParam = false;

            foreach (var param in method.GetParameters())
            {
                if (firstParam)
                {
                    firstParam = false;
                    if (method.IsDefined(typeof(System.Runtime.CompilerServices.ExtensionAttribute), false))
                    {
                        if (callable)
                        {
                            secondParam = true;
                            continue;
                        }
                        sigBuilder.Append("this ");
                    }
                }
                else if (secondParam == true)
                {
                    secondParam = false;
                }
                else
                {
                    sigBuilder.Append(", ");
                }
                if (param.ParameterType.IsByRef)
                {
                    sigBuilder.Append("ref ");
                }
                else if (param.IsOut)
                {
                    sigBuilder.Append("out ");
                }
                if (!callable)
                {
                    sigBuilder.Append(TypeName(param.ParameterType));
                    sigBuilder.Append(' ');
                }
                sigBuilder.Append(param.Name);
            }
            sigBuilder.Append(")");
            return(sigBuilder.ToString());
        }