Наследование: ICustomAttributeProvider, _ParameterInfo
        /// <summary>
        /// 参数解析
        /// </summary>
        /// <param name="paramters"></param>
        /// <param name="nvs"></param>
        /// <returns></returns>
        public static object[] Convert(ParameterInfo[] paramters, NameValueCollection nvs)
        {
            List<object> args = new List<object>();
            var obj = ConvertJsonObject(nvs);

            foreach (ParameterInfo info in paramters)
            {
                var type = GetElementType(info.ParameterType);

                var property = obj.Properties().SingleOrDefault(p => string.Compare(p.Name, info.Name, true) == 0);
                if (property != null)
                {
                    try
                    {
                        //获取Json值
                        var jsonValue = CoreHelper.ConvertJsonValue(type, property.Value.ToString(Formatting.None));
                        args.Add(jsonValue);
                    }
                    catch (Exception ex)
                    {
                        throw new RESTfulException((int)HttpStatusCode.BadRequest, string.Format("Parameter [{0}] did not match type [{1}].",
                            info.Name, CoreHelper.GetTypeName(type)));
                    }
                }
                else
                {
                    throw new RESTfulException((int)HttpStatusCode.BadRequest, "Parameter [" + info.Name + "] is not found.");
                }
            }

            return args.ToArray();
        }
Пример #2
1
        public static MethodBuilder DefineMethod(this TypeBuilder typeBuilder, MethodInfo method, MethodAttributes? attributes = null, ParameterInfo[] parameters = null)
        {
            Type[] parametersTypes = null;
            MethodBuilder methodBuilder = null;

            parameters = parameters ?? method.GetParameters();
            parametersTypes = parameters.ToArray(parameter => parameter.ParameterType);
            attributes = attributes ?? method.Attributes & ~MethodAttributes.Abstract;
            methodBuilder = typeBuilder.DefineMethod(method.Name, attributes.Value, method.ReturnType, parametersTypes);

            parameters.ForEach(1, (parameter, i) => {
                var parameterBuilder = methodBuilder.DefineParameter(i, parameter.Attributes, parameter.Name);

                if (parameter.IsDefined<ParamArrayAttribute>()) {
                    parameterBuilder.SetCustomAttribute<ParamArrayAttribute>();
                }
                else if (parameter.IsOut) {
                    parameterBuilder.SetCustomAttribute<OutAttribute>();
                }
                else if (parameter.IsOptional) {
                    parameterBuilder.SetCustomAttribute<OptionalAttribute>()
                                    .SetConstant(parameter.DefaultValue);
                }
            });

            return methodBuilder;
        }
 public SqlCallProcedureInfo(MethodInfo method, ISerializationTypeInfoProvider typeInfoProvider)
 {
     if (method == null) {
         throw new ArgumentNullException("method");
     }
     if (typeInfoProvider == null) {
         throw new ArgumentNullException("typeInfoProvider");
     }
     SqlProcAttribute procedure = GetSqlProcAttribute(method);
     schemaName = procedure.SchemaName;
     name = procedure.Name;
     timeout = procedure.Timeout;
     deserializeReturnNullOnEmptyReader = procedure.DeserializeReturnNullOnEmptyReader;
     deserializeRowLimit = procedure.DeserializeRowLimit;
     deserializeCallConstructor = procedure.DeserializeCallConstructor;
     SortedDictionary<int, SqlCallParameterInfo> sortedParams = new SortedDictionary<int, SqlCallParameterInfo>();
     outArgCount = 0;
     foreach (ParameterInfo parameterInfo in method.GetParameters()) {
         if ((parameterInfo.GetCustomAttributes(typeof(SqlNameTableAttribute), true).Length > 0) || (typeof(XmlNameTable).IsAssignableFrom(parameterInfo.ParameterType))) {
             if (xmlNameTableParameter == null) {
                 xmlNameTableParameter = parameterInfo;
             }
         } else {
             SqlCallParameterInfo sqlParameterInfo = new SqlCallParameterInfo(parameterInfo, typeInfoProvider, ref outArgCount);
             sortedParams.Add(parameterInfo.Position, sqlParameterInfo);
         }
     }
     parameters = sortedParams.Select(p => p.Value).ToArray();
     returnTypeInfo = typeInfoProvider.GetSerializationTypeInfo(method.ReturnType);
     if ((procedure.UseReturnValue != SqlReturnValue.Auto) || (method.ReturnType != typeof(void))) {
         useReturnValue = (procedure.UseReturnValue == SqlReturnValue.ReturnValue) || ((procedure.UseReturnValue == SqlReturnValue.Auto) && (typeInfoProvider.TypeMappingProvider.GetMapping(method.ReturnType).DbType == SqlDbType.Int));
     }
 }
Пример #4
0
        private static void AddFunctionsForScript(GenericMenu menu, SerializedProperty listener, UnityEventDrawer.ValidMethodMap method, string targetName)
        {
            PersistentListenerMode mode1 = method.mode;

            UnityEngine.Object     objectReferenceValue = listener.FindPropertyRelative("m_Target").objectReferenceValue;
            string                 stringValue          = listener.FindPropertyRelative("m_MethodName").stringValue;
            PersistentListenerMode mode2            = UnityEventDrawer.GetMode(listener.FindPropertyRelative("m_Mode"));
            SerializedProperty     propertyRelative = listener.FindPropertyRelative("m_Arguments").FindPropertyRelative("m_ObjectArgumentAssemblyTypeName");
            StringBuilder          stringBuilder    = new StringBuilder();
            int length = method.methodInfo.GetParameters().Length;

            for (int index = 0; index < length; ++index)
            {
                System.Reflection.ParameterInfo parameter = method.methodInfo.GetParameters()[index];
                stringBuilder.Append(string.Format("{0}", (object)UnityEventDrawer.GetTypeName(parameter.ParameterType)));
                if (index < length - 1)
                {
                    stringBuilder.Append(", ");
                }
            }
            bool on = objectReferenceValue == method.target && stringValue == method.methodInfo.Name && mode1 == mode2;

            if (on && mode1 == PersistentListenerMode.Object && method.methodInfo.GetParameters().Length == 1)
            {
                on &= method.methodInfo.GetParameters()[0].ParameterType.AssemblyQualifiedName == propertyRelative.stringValue;
            }
            string formattedMethodName = UnityEventDrawer.GetFormattedMethodName(targetName, method.methodInfo.Name, stringBuilder.ToString(), mode1 == PersistentListenerMode.EventDefined);

            menu.AddItem(new GUIContent(formattedMethodName), on, new GenericMenu.MenuFunction2(UnityEventDrawer.SetEventFunction), (object)new UnityEventDrawer.UnityEventFunction(listener, method.target, method.methodInfo, mode1));
        }
        /// <summary>
        /// Get the type of command option from a method parameter info.
        /// </summary>
        private static ApplicationCommandOptionType TypeFromMethodParameter(ParameterInfo methodParameter)
        {
            if (methodParameter.ParameterType == _intType || methodParameter.ParameterType == _intNullableType)
            {
                return(ApplicationCommandOptionType.Integer);
            }
            if (methodParameter.ParameterType == _stringType)
            {
                return(ApplicationCommandOptionType.String);
            }
            if (methodParameter.ParameterType == _boolType || methodParameter.ParameterType == _boolNullableType)
            {
                return(ApplicationCommandOptionType.Boolean);
            }
            if (methodParameter.ParameterType.IsAssignableFrom(_guildChannelType))
            {
                return(ApplicationCommandOptionType.Channel);
            }
            if (methodParameter.ParameterType.IsAssignableFrom(_rolelType))
            {
                return(ApplicationCommandOptionType.Role);
            }
            if (methodParameter.ParameterType.IsAssignableFrom(_guildUserType))
            {
                return(ApplicationCommandOptionType.User);
            }

            throw new Exception($"Got parameter type other than int, string, bool, guild, role, or user. {methodParameter.Name}");
        }
Пример #6
0
        public object Bind(IDictionary<string, string> parameters, ParameterInfo parameterInfo)
        {
            if (parameters.ContainsKey(parameterInfo.Name) && !string.IsNullOrEmpty(parameters[parameterInfo.Name]))
                return XDocument.Parse(parameters[parameterInfo.Name]);

            return null;
        }
Пример #7
0
        public bool HasDataFor(System.Reflection.ParameterInfo parameter)
        {
            Type       parameterType = parameter.ParameterType;
            MemberInfo method        = parameter.Member;
            Type       fixtureType   = method.ReflectedType;

            if (!Reflect.HasAttribute(method, NUnitFramework.TheoryAttribute, true))
            {
                return(false);
            }

            if (parameterType == typeof(bool) || parameterType.IsEnum)
            {
                return(true);
            }

            foreach (MemberInfo member in fixtureType.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))
            {
                if (Reflect.HasAttribute(member, DatapointAttribute, true) &&
                    GetTypeFromMemberInfo(member) == parameterType)
                {
                    return(true);
                }
                else if (Reflect.HasAttribute(member, DatapointsAttribute, true) &&
                         GetElementTypeFromMemberInfo(member) == parameterType)
                {
                    return(true);
                }
            }

            return(false);
        }
		public int CalculateParamPoints(SmartDispatcherController controller, ParameterInfo parameterInfo)
		{
			if (String.IsNullOrEmpty(parameterName))
				parameterName = parameterInfo.Name;

			return String.IsNullOrEmpty(controller.Request.Params[parameterName]) ? 0 : 100;
		}
Пример #9
0
        private static void AddFunctionsForScript(GenericMenu menu, SerializedProperty listener, ValidMethodMap method, string targetName)
        {
            PersistentListenerMode mode = method.mode;

            UnityEngine.Object     objectReferenceValue = listener.FindPropertyRelative("m_Target").objectReferenceValue;
            string                 stringValue          = listener.FindPropertyRelative("m_MethodName").stringValue;
            PersistentListenerMode mode2    = GetMode(listener.FindPropertyRelative("m_Mode"));
            SerializedProperty     property = listener.FindPropertyRelative("m_Arguments").FindPropertyRelative("m_ObjectArgumentAssemblyTypeName");
            StringBuilder          builder  = new StringBuilder();
            int length = method.methodInfo.GetParameters().Length;

            for (int i = 0; i < length; i++)
            {
                System.Reflection.ParameterInfo info = method.methodInfo.GetParameters()[i];
                builder.Append($"{GetTypeName(info.ParameterType)}");
                if (i < (length - 1))
                {
                    builder.Append(", ");
                }
            }
            bool on = ((objectReferenceValue == method.target) && (stringValue == method.methodInfo.Name)) && (mode == mode2);

            if ((on && (mode == PersistentListenerMode.Object)) && (method.methodInfo.GetParameters().Length == 1))
            {
                on &= method.methodInfo.GetParameters()[0].ParameterType.AssemblyQualifiedName == property.stringValue;
            }
            string text = GetFormattedMethodName(targetName, method.methodInfo.Name, builder.ToString(), mode == PersistentListenerMode.EventDefined);

            if (< > f__mg$cache1 == null)
            {
Пример #10
0
        /// <summary>
        /// Gets a customization that associates a <see cref="ListFavoringConstructorQuery"/> with
        /// the <see cref="Type"/> of the parameter.
        /// </summary>
        /// <param name="parameter">The parameter for which the customization is requested.</param>
        /// <returns>
        /// A customization that associates a <see cref="ListFavoringConstructorQuery"/> with the
        /// <see cref="Type"/> of the parameter.
        /// </returns>
        public override ICustomization GetCustomization(ParameterInfo parameter)
        {
            if (parameter == null)
                throw new ArgumentNullException("parameter");

            return new ConstructorCustomization(parameter.ParameterType, new ListFavoringConstructorQuery());
        }
Пример #11
0
        private static object HandleArgumentNotResolved(ParsingContext context, ParameterInfo parameterInfo)
        {
            var attribute = parameterInfo.GetCustomAttribute<ArgumentAttribute>();
            if(attribute == null)
            {
                throw new ArgumentException(string.Format("Could not resolve argument: {0}", parameterInfo.Name));
            }

            var startPosition = context.CurrentPosition;
            var separatorPosition = attribute.Separator == '\0' ? -1 : context.Packet.Data.DataAsString.IndexOf(attribute.Separator, startPosition);
            var length = (separatorPosition == -1 ? context.Packet.Data.DataAsString.Length : separatorPosition) - startPosition;
            var valueToParse = context.Packet.Data.DataAsString.Substring(startPosition, length);

            context.CurrentPosition += length + 1;

            switch(attribute.Encoding)
            {
                case ArgumentAttribute.ArgumentEncoding.HexNumber:
                    return Parse(parameterInfo.ParameterType, valueToParse, NumberStyles.HexNumber);
                case ArgumentAttribute.ArgumentEncoding.DecimalNumber:
                    return Parse(parameterInfo.ParameterType, valueToParse);
                case ArgumentAttribute.ArgumentEncoding.BinaryBytes:
                    return context.Packet.Data.DataAsBinary.Skip(startPosition).ToArray();
                case ArgumentAttribute.ArgumentEncoding.HexBytesString:
                    return valueToParse.Split(2).Select(x => byte.Parse(x, NumberStyles.HexNumber)).ToArray();
                default:
                    throw new ArgumentException(string.Format("Unsupported argument type: {0}", parameterInfo.ParameterType.Name));
            }
        }
Пример #12
0
        /// <summary>
        /// Build a form to be used as parameters for the specified method
        /// </summary>
        /// <param name="type"></param>
        /// <param name="wrapperTagName"></param>
        /// <param name="methodName"></param>
        /// <param name="defaults"></param>
        /// <param name="registerProxy"></param>
        /// <param name="paramCount"></param>
        /// <returns></returns>
        public TagBuilder MethodForm(Type type, string wrapperTagName, string methodName, Dictionary <string, object> defaults, bool registerProxy, out int paramCount)
        {
            Args.ThrowIfNull(type, "InvocationType");
            if (registerProxy)
            {
                ServiceProxySystem.Register(type);
            }

            MethodInfo method = type.GetMethod(methodName);

            defaults = defaults ?? new Dictionary <string, object>();

            System.Reflection.ParameterInfo[] parameters = method.GetParameters();
            paramCount = parameters.Length;
            TagBuilder form = new TagBuilder(wrapperTagName);

            for (int i = 0; i < parameters.Length; i++)
            {
                System.Reflection.ParameterInfo parameter = parameters[i];
                object defaultValue  = defaults.ContainsKey(parameter.Name) ? defaults[parameter.Name] : null;
                string defaultString = defaultValue == null ? string.Empty : defaultValue.ToString();

                TagBuilder label = new TagBuilder("label")
                                   .Html(string.Format(this.LabelFormat, parameter.Name.PascalSplit(" ")))
                                   .Css(this.LabelCssClass);

                bool addLabel  = this.AddLabels;
                bool addValue  = true;
                bool wasObject = false;
                bool handled   = false;
                TryBuildPrimitiveInput(parameter, defaultValue, ref addValue, ref handled, out TagBuilder toAdd, out Type paramType);

                if (!handled)
                {
                    string legend = GetLegend(paramType);
                    toAdd     = FieldsetFor(paramType, defaultValue, legend);
                    addLabel  = false;
                    addValue  = false;
                    wasObject = true;
                }

                toAdd.DataSet("parameter-name", parameter.Name)
                .DataSetIf(!wasObject, "type", parameter.ParameterType.Name.ToLowerInvariant())
                .ValueIf(!string.IsNullOrEmpty(defaultString) && addValue, defaultString);

                if (addLabel)
                {
                    form.Child(label).BrIf(this.Layout == ParameterLayouts.BreakAfterLabels);
                }

                form.Child(toAdd).BrIf(
                    this.Layout != ParameterLayouts.NoBreaks &&
                    i != parameters.Length - 1 &&
                    !wasObject);
            }

            return(form.DataSet("method", methodName)
                   .FirstChildIf(wrapperTagName.Equals("fieldset"), new TagBuilder("legend")
                                 .Text(GetLegend(method))));
        }
Пример #13
0
        /// <summary>
        /// Get the type of command option from a method parameter info.
        /// </summary>
        private static ApplicationCommandOptionType TypeFromMethodParameter(ParameterInfo methodParameter)
        {
            if (methodParameter.ParameterType == typeof(int) || methodParameter.ParameterType == typeof(int?))
            {
                return(ApplicationCommandOptionType.Integer);
            }
            if (methodParameter.ParameterType == typeof(string))
            {
                return(ApplicationCommandOptionType.String);
            }
            if (methodParameter.ParameterType == typeof(bool) || methodParameter.ParameterType == typeof(bool?))
            {
                return(ApplicationCommandOptionType.Boolean);
            }
            if (methodParameter.ParameterType == typeof(SocketGuildChannel))
            {
                return(ApplicationCommandOptionType.Channel);
            }
            if (methodParameter.ParameterType == typeof(SocketRole))
            {
                return(ApplicationCommandOptionType.Role);
            }
            if (methodParameter.ParameterType == typeof(SocketGuildUser))
            {
                return(ApplicationCommandOptionType.User);
            }

            throw new Exception($"Got parameter type other than int, string, bool, guild, role, or user. {methodParameter.Name}");
        }
        private bool TryInvokeMemberWithNamedParameters(InvokeMemberBinder binder, object[] args, out object result,
                                                        MethodInfo method, ParameterInfo[] parameters)
        {
            var fixedArgs = new List<object>();
            for (int i = 0; i < parameters.Length; i++)
            {
                if (parameters[i].RawDefaultValue == DBNull.Value)
                {
                    fixedArgs.Add(args[i]);
                }
                else
                {
                    var index = binder.CallInfo.ArgumentNames.IndexOf(parameters[i].Name);
                    if (index > -1)
                    {
                        if (!parameters[i].ParameterType.IsInstanceOfType(args[index]))
                        {
                            result = null;
                            return false;
                        }
                    }
                    else
                    {
                        fixedArgs.Add(parameters[i].RawDefaultValue);
                    }
                }
            }

            result = method.Invoke(_adapter, fixedArgs.ToArray());
            return true;
        }
Пример #15
0
      private ParameterInputDialog(ParameterInfo[] paramInfo, Object[] paramList)
      {
         InitializeComponent();

         int panelsHeight = 0;

         _paramValue = new object[paramInfo.Length];

         _paramInfo = paramInfo;
         _paramPanel = new ParamInputPanel[paramInfo.Length];

         for (int i = 0; i < paramInfo.Length; i++)
         {
            ParamInputPanel panel = CreatePanelForParameter(
               paramInfo[i],
               (paramList == null || i >= paramList.Length) ? null : paramList[i]);
            parameterInputPanel.Controls.Add(panel);
            panel.Location = new Point(0, i * panel.Height);
            _paramPanel[i] = panel;

            panelsHeight += panel.Height;
         }

         Height = panelsHeight + 100;
      }
Пример #16
0
		internal bool ConvertArgs (object[] args, ParameterInfo[] pinfo, CultureInfo culture, bool exactMatch)
		{
			if (args == null) {
				if (pinfo.Length == 0)
					return true;
				
				throw new TargetParameterCountException ();
			}

			if (pinfo.Length != args.Length)
				throw new TargetParameterCountException ();
			
			for (int i = 0; i < args.Length; ++i) {
				var arg = args [i];
				var pi = pinfo [i];
				if (arg == Type.Missing) {
					args [i] = pi.DefaultValue;
					continue;
				}

				if (arg != null && arg.GetType () == pi.ParameterType)
					continue;

				if (exactMatch)
					return false;

				object v = ChangeType (arg, pi.ParameterType, culture);
				if (v == null && args [i] != null)
					return false;
	
				args [i] = v;
			}

			return true;
		}
Пример #17
0
        public object Bind(IDictionary<string, string> parameters, ParameterInfo parameterInfo)
        {
            if (parameters.ContainsKey(parameterInfo.Name) && !string.IsNullOrEmpty(parameters[parameterInfo.Name]))
                return new UUID(StringToByteArray(parameters[parameterInfo.Name]));

            return null;
        }
Пример #18
0
        public bool HasDataFor(System.Reflection.ParameterInfo parameter)
        {
            Type       parameterType = parameter.ParameterType;
            MemberInfo method        = parameter.Member;
            Type       fixtureType   = method.ReflectedType;

            if (!Reflect.HasAttribute(method, NUnitFramework.TheoryAttribute, true))
            {
                return(false);
            }

            foreach (FieldInfo field in fixtureType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))
            {
                if (field.FieldType == parameterType)
                {
                    if (Reflect.HasAttribute(field, DatapointAttribute, true))
                    {
                        return(true);
                    }
                }
                else if (field.FieldType.IsArray && field.FieldType.GetElementType() == parameterType)
                {
                    if (Reflect.HasAttribute(field, DatapointsAttribute, true))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Пример #19
0
        private static bool CheckIfParametersEquals(ParameterInfo[] parameters, params Type[] targets)
        {
            if (parameters.Length != targets.Length)
                return false;

            return !parameters.Where((each, index) => each.ParameterType != targets[index]).Any();
        }
 internal override void Analyze(RuleAnalysis analysis, MemberInfo member, CodeExpression targetExpression, RulePathQualifier targetQualifier, CodeExpressionCollection argumentExpressions, ParameterInfo[] parameters, List<CodeExpression> attributedExpressions)
 {
     if (!analysis.ForWrites)
     {
         base.AnalyzeReadWrite(analysis, targetExpression, targetQualifier, argumentExpressions, parameters, attributedExpressions);
     }
 }
Пример #21
0
        private List <Attribute> ReadParameterCustomAttributes(System.Reflection.ParameterInfo parameter)
        {
            List <Attribute> cachedAttributes    = null;
            bool             getMemberAttributes = false;

            // Now edit the attributes returned from the base type
            using (new ReadLock(this._lock))
            {
                if (!this._parameters.TryGetValue(parameter, out cachedAttributes))
                {
                    // If there is nothing for this parameter Cache any attributes for the DeclaringType
                    if (!this._memberInfos.TryGetValue(parameter.Member.DeclaringType, out cachedAttributes))
                    {
                        // If there is nothing for this parameter look to see if the declaring Member has been cached yet?
                        // need to do it outside of the lock, so set the flag we'll check it in a bit
                        getMemberAttributes = true;
                    }
                    cachedAttributes = null;
                }
            }

            if (getMemberAttributes)
            {
                GetCustomAttributes(parameter.Member.DeclaringType, EmptyList);

                // We should have run the rules for the enclosing parameter so we can again
                using (new ReadLock(this._lock))
                {
                    this._parameters.TryGetValue(parameter, out cachedAttributes);
                }
            }

            return(cachedAttributes);
        }
Пример #22
0
        internal static object ExtractParameterFromDictionary(ParameterInfo parameterInfo, IDictionary<string, object> parameters, MethodInfo methodInfo)
        {
            object value;

            if (!parameters.TryGetValue(parameterInfo.Name, out value))
            {
                // the key should always be present, even if the parameter value is null
                string message = String.Format(CultureInfo.CurrentCulture, MvcResources.ReflectedActionDescriptor_ParameterNotInDictionary,
                                               parameterInfo.Name, parameterInfo.ParameterType, methodInfo, methodInfo.DeclaringType);
                throw new ArgumentException(message, "parameters");
            }

            if (value == null && !TypeHelpers.TypeAllowsNullValue(parameterInfo.ParameterType))
            {
                // tried to pass a null value for a non-nullable parameter type
                string message = String.Format(CultureInfo.CurrentCulture, MvcResources.ReflectedActionDescriptor_ParameterCannotBeNull,
                                               parameterInfo.Name, parameterInfo.ParameterType, methodInfo, methodInfo.DeclaringType);
                throw new ArgumentException(message, "parameters");
            }

            if (value != null && !parameterInfo.ParameterType.IsInstanceOfType(value))
            {
                // value was supplied but is not of the proper type
                string message = String.Format(CultureInfo.CurrentCulture, MvcResources.ReflectedActionDescriptor_ParameterValueHasWrongType,
                                               parameterInfo.Name, methodInfo, methodInfo.DeclaringType, value.GetType(), parameterInfo.ParameterType);
                throw new ArgumentException(message, "parameters");
            }

            return value;
        }
Пример #23
0
        private static void BuildParameter(ParameterBuilder builder, System.Reflection.ParameterInfo paramInfo, int position, int count, CommandService service)
        {
            var attributes = paramInfo.GetCustomAttributes();
            var paramType  = paramInfo.ParameterType;

            builder.Name = paramInfo.Name;

            builder.IsOptional   = paramInfo.IsOptional;
            builder.DefaultValue = paramInfo.HasDefaultValue ? paramInfo.DefaultValue : null;

            foreach (var attribute in attributes)
            {
                // TODO: C#7 type switch
                if (attribute is SummaryAttribute)
                {
                    builder.Summary = (attribute as SummaryAttribute).Text;
                }
                else if (attribute is OverrideTypeReaderAttribute)
                {
                    builder.TypeReader = GetTypeReader(service, paramType, (attribute as OverrideTypeReaderAttribute).TypeReader);
                }
                else if (attribute is ParameterPreconditionAttribute)
                {
                    builder.AddPrecondition(attribute as ParameterPreconditionAttribute);
                }
                else if (attribute is ParamArrayAttribute)
                {
                    builder.IsMultiple = true;
                    paramType          = paramType.GetElementType();
                }
                else if (attribute is RemainderAttribute)
                {
                    if (position != count - 1)
                    {
                        throw new InvalidOperationException("Remainder parameters must be the last parameter in a command.");
                    }

                    builder.IsRemainder = true;
                }
            }

            builder.ParameterType = paramType;

            if (builder.TypeReader == null)
            {
                var        readers = service.GetTypeReaders(paramType);
                TypeReader reader  = null;

                if (readers != null)
                {
                    reader = readers.FirstOrDefault().Value;
                }
                else
                {
                    reader = service.GetDefaultTypeReader(paramType);
                }

                builder.TypeReader = reader;
            }
        }
Пример #24
0
 public ProcedureParameter(ParameterInfo info)
 {
     Type = info.ParameterType;
     Name = info.Name;
     bool hasDefaultValue = info.IsOptional && (info.Attributes & ParameterAttributes.HasDefault) == ParameterAttributes.HasDefault;
     DefaultValue = hasDefaultValue ? info.DefaultValue : DBNull.Value;
 }
Пример #25
0
        public ReflectionParameter(ParameterInfo parameterInfo, IMember member)
            : base(parameterInfo.Name)
        {
            Type type = parameterInfo.ParameterType;

            this.ReturnType = ReflectionReturnType.Create(member, type, false);

            if (type.IsByRef && parameterInfo.IsOut) {
                this.Modifiers = ParameterModifiers.Out;
            } else if (type.IsByRef) {
                this.Modifiers = ParameterModifiers.Ref;
            }

            if (parameterInfo.IsOptional) {
                this.Modifiers |= ParameterModifiers.Optional;
            }
            if (type.IsArray && type != typeof(Array)) {
                foreach (CustomAttributeData data in CustomAttributeData.GetCustomAttributes(parameterInfo)) {
                    if (data.Constructor.DeclaringType.FullName == typeof(ParamArrayAttribute).FullName) {
                        this.Modifiers |= ParameterModifiers.Params;
                        break;
                    }
                }
            }
        }
Пример #26
0
        /// <summary>
        /// Gets the property value from the first matched property. The match is made by the name and the type of the specified parameter.
        /// </summary>
        /// <remarks>The property match is done by the name and type, where the name is matched case insensitive and the type of the 
        /// parameter type should be assignable from the property type.</remarks>
        /// <param name="command">The command.</param>
        /// <param name="parameterInfo">The parameter info.</param>
        /// <exception cref="ArgumentNullException">Thrown when <i>command</i> or <i>parameterInfo</i> is null.</exception>
        /// <returns>The value from the first matched property.</returns>
        public static object GetPropertyValueBasedOnParameterInfo(ICommand command, ParameterInfo parameterInfo)
        {
            if (command == null) throw new ArgumentNullException("command");
            if (parameterInfo == null) throw new ArgumentNullException("parameterInfo");

            // Initialize result with the default value based on the type.
            var type = parameterInfo.ParameterType;
            object result = type.IsValueType ? Activator.CreateInstance(type) : null;

            // Get all properties that match name of the specified parameter and where the property type
            // is assignable from the parameter type.
            var query = from prop in command.GetType().GetProperties()
                        where prop.Name.Equals(parameterInfo.Name, StringComparison.InvariantCultureIgnoreCase) &&
                              parameterInfo.ParameterType.IsAssignableFrom(prop.PropertyType)
                        select prop;

            // Get the first property, if found.
            var propertyInfo = query.FirstOrDefault();

            // If there is a property found, get the value from it.
            if (propertyInfo != null)
            {
                result = propertyInfo.GetValue(command, null);
            }

            return result;
        }
 public NodeInfo(Type type, string name, MemberTypes mtype, ParameterInfo[] parameters)
 {
     this.NodeType = type;
     this.Name = name;
     this.MemberType = mtype;
     this.Parameters = parameters;
 }
Пример #28
0
        /// <summary>
        /// Gets the row of values. Each one will be converted (if posible) to the type of
        /// the corresponding argument in the test method.
        /// </summary>
        /// <param name="parameters">List of parameters.</param>
        /// <returns>The row of values.</returns>
        public Object[] GetRow(ParameterInfo[] parameters)
        {
            object[] args = new object[parameters.Length];

            // If the lengths are different a TargetParameterCountException exception will be thrown
            if (row.Length == parameters.Length)
            {
                for (int i = 0; i < row.Length; i++)
                {
                    FormatParameter(parameters, args, i);
                }
                return args;
            }
            else if (parameters[parameters.Length - 1].ParameterType == typeof(Object[]))
            {
                // Test function has params object[] argument
                for (int i = 0; i < parameters.Length - 1; i++)
                {
                    FormatParameter(parameters, args, i);
                }
                if (row.Length - parameters.Length > 0)
                {
                    // Copy remaining parameters to object[]
                    object[] paramsArray = new object[row.Length - (parameters.Length - 1)];
                    Array.Copy(row, parameters.Length - 1, paramsArray, 0, row.Length - parameters.Length);
                    args[parameters.Length - 1] = paramsArray;
                }
                else
                {
                    args[parameters.Length - 1] = new object[0];
                }
                return args;
            }
            return row;
        }
Пример #29
0
 /// <summary>
 ///             Calculates the param points. Implementers should return value equals or greater than
 ///             zero indicating whether the parameter can be bound successfully. The greater the value (points)
 ///             the more successful the implementation indicates to the framework
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="controller">The controller.</param>
 /// <param name="controllerContext">The controller context.</param>
 /// <param name="parameterInfo">The parameter info.</param>
 /// <returns>
 /// </returns>
 public int CalculateParamPoints(IEngineContext context, IController controller, IControllerContext controllerContext, ParameterInfo parameterInfo)
 {
     var token = context.Request[parameterName];
     if (CanConvert(parameterInfo.ParameterType, token))
         return 10;
     return 0;
 }
Пример #30
0
        private object ResolveMethodParameter(ParameterInfo methodParameterInfo, IDictionary<string, object> queryParameters, NancyContext context)
        {
            if (IsQueryParameter(methodParameterInfo, queryParameters))
                return GetValueFromQueryParameters(methodParameterInfo, queryParameters);

            return GetValueFromRequestBody(methodParameterInfo, context);
        }
Пример #31
0
        public ParameterWrapper(ActionBinder binder, ParameterInfo info)
            : this(binder, info.ParameterType)
        {
            _name = SymbolTable.StringToId(info.Name ?? "<unknown>");

            _isParams = info.IsDefined(typeof(ParamArrayAttribute), false);
        }
Пример #32
0
    /// <summary>
    /// Gets or creates a new <see cref="CILParameter"/> based on native <see cref="System.Reflection.ParameterInfo"/>.
    /// </summary>
    /// <param name="param">The native parameter.</param>
    /// <param name="ctx">The current reflection context.</param>
    /// <returns><see cref="CILParameter"/> wrapping existing native <see cref="System.Reflection.ParameterInfo"/>.</returns>
    /// <exception cref="ArgumentNullException">If <paramref name="param"/> or <paramref name="ctx"/> is <c>null</c>.</exception>
    public static CILParameter NewWrapper(this System.Reflection.ParameterInfo param, CILReflectionContext ctx)
    {
        ArgumentValidator.ValidateNotNull("Module", param);
        ArgumentValidator.ValidateNotNull("Reflection context", ctx);

        return(((CILReflectionContextImpl)ctx).Cache.GetOrAdd(param));
    }
Пример #33
0
 public UrlDateTimeHandler(ParameterInfo fromUrlParameter)
 {
     if (fromUrlParameter != null) {
     _fromUrlParamType = fromUrlParameter.ParameterType;
     _fromUrlDateTimeProperties = GetDateTimeProperties(_fromUrlParamType);
       }
 }
        /// <summary>
        /// 生成模型
        /// </summary>
        /// <param name="request">请求数据</param>
        /// <param name="parameter">参数</param>       
        /// <returns></returns>
        public object BindModel(HttpRequest request, ParameterInfo parameter)
        {
            var name = parameter.Name;
            var targetType = parameter.ParameterType;

            if (targetType.IsClass == true && targetType.IsArray == false && targetType != typeof(string))
            {
                return ConvertToClass(request, parameter);
            }

            // 转换为数组
            var values = request.GetValues(name);
            if (targetType.IsArray == true)
            {
                return Converter.Cast(values, targetType);
            }

            // 转换为简单类型 保留参数默认值
            var value = values.FirstOrDefault();
            if (value == null && parameter.DefaultValue != DBNull.Value)
            {
                return parameter.DefaultValue;
            }
            return Converter.Cast(value, targetType);
        }
Пример #35
0
        private static Expression[] ArgumentConvertHelper(Expression[] arguments, ParameterInfo[] parameters) {
            Debug.Assert(arguments != null);
            Debug.Assert(arguments != null);

            Expression[] clone = null;
            for (int arg = 0; arg < arguments.Length; arg++) {
                Expression argument = arguments[arg];
                if (!CompatibleParameterTypes(parameters[arg].ParameterType, argument.Type)) {
                    // Clone the arguments array if needed
                    if (clone == null) {
                        clone = new Expression[arguments.Length];
                        // Copy the expressions into the clone
                        for (int i = 0; i < arg; i++) {
                            clone[i] = arguments[i];
                        }
                    }

                    argument = ArgumentConvertHelper(argument, parameters[arg].ParameterType);
                }

                if (clone != null) {
                    clone[arg] = argument;
                }
            }
            return clone ?? arguments;
        }
        private static ParameterAnnotationInfo ExtractParameter(Expression expression, ParameterInfo parameter)
        {
            var methodCallExpression = AssertCallOnSpecialClass(expression);

            var methodName = methodCallExpression.Method.Name;
            switch (methodName)
            {
                case nameof(Annotations.FormatString):
                    return new ParameterAnnotationInfo(parameter.Name, isFormatString: true, isNotNull: true);

                case nameof(Annotations.NullableFormatString):
                    return new ParameterAnnotationInfo(parameter.Name, isFormatString: true, canBeNull: true);

                case nameof(Annotations.Some):
                    return new ParameterAnnotationInfo(parameter.Name);

                case nameof(Annotations.NotNull):
                    return new ParameterAnnotationInfo(parameter.Name, isNotNull: true);

                case nameof(Annotations.CanBeNull):
                    return new ParameterAnnotationInfo(parameter.Name, canBeNull: true);

                default:
                    throw new ArgumentException($"Expression '{expression}' call an unsupported method : {methodName}. {usageInfo}",
                        nameof(expression));
            }
        }
        public SlackBinding(ParameterInfo parameter, SlackAttribute attribute, SlackConfiguration config, INameResolver nameResolver, BindingProviderContext context)
        {
            _parameter = parameter;
            _attribute = attribute;
            _config = config;
            _nameResolver = nameResolver;
            
            if(!string.IsNullOrEmpty(_attribute.WebHookUrl))
            {
                _webHookUrlBindingTemplate = CreateBindingTemplate(_attribute.WebHookUrl, context.BindingDataContract);
            }

            if (!string.IsNullOrEmpty(_attribute.Text))
            {
                _textBindingTemplate = CreateBindingTemplate(_attribute.Text, context.BindingDataContract);
            }

            if (!string.IsNullOrEmpty(_attribute.Username))
            {
                _usernameBindingTemplate = CreateBindingTemplate(_attribute.Username, context.BindingDataContract);
            }

            if (!string.IsNullOrEmpty(_attribute.IconEmoji))
            {
                _iconEmojiBindingTemplate = CreateBindingTemplate(_attribute.IconEmoji, context.BindingDataContract);
            }

            if (!string.IsNullOrEmpty(_attribute.Channel))
            {
                _channelBindingTemplate = CreateBindingTemplate(_attribute.Channel, context.BindingDataContract);
            }
        }
Пример #38
0
		public void Initialize(ParameterInfo parameter)
		{
			_type = parameter.ParameterType;
			MethodInfo m = (MethodInfo)parameter.Member;
			Type c = m.DeclaringType;
			if (_name == null) _name = c.Namespace + "." + c.Name + "." + m.Name + "(" + parameter.Name + ")";
		}
Пример #39
0
 public bool GetParameterValue(ParameterInfo paramInfo, int paramLoc, ref Object parameter)
 {
     var ParamName = paramInfo.Name;
     if (!_hashParams.ContainsKey(ParamName)) return false;
     parameter = _hashParams[ParamName];
     return true;
 }
Пример #40
0
        //This is where ParameterImports will be handled
        protected override IEnumerable <object> GetCustomAttributes(System.Reflection.ParameterInfo parameter, IEnumerable <object> declaredAttributes)
        {
            IEnumerable <object> attributes       = base.GetCustomAttributes(parameter, declaredAttributes);
            List <Attribute>     cachedAttributes = ReadParameterCustomAttributes(parameter);

            return(cachedAttributes == null ? attributes : attributes.Concat(cachedAttributes));
        }
		protected override void ImplementInvokeMethodOnTarget(AbstractTypeEmitter @class, ParameterInfo[] parameters, MethodEmitter invokeMethodOnTarget, MethodInfo callbackMethod, Reference targetField)
		{
			invokeMethodOnTarget.CodeBuilder.AddStatement(
				new ExpressionStatement(
					new MethodInvocationExpression(SelfReference.Self, InvocationMethods.EnsureValidTarget)));
			base.ImplementInvokeMethodOnTarget(@class, parameters, invokeMethodOnTarget, callbackMethod, targetField);
		}
Пример #42
0
        public static CustomPropertyInfo GetFromParamInfo(System.Reflection.ParameterInfo info)
        {
            if (info == null)
            {
                return(null);
            }

            CustomPropertyInfo retInfo = new CustomPropertyInfo();

            retInfo.PropertyName = info.Name;
            if (info.IsOut || info.ParameterType.IsByRef)
            {
                retInfo.PropertyType = EngineNS.Rtti.RttiHelper.GetTypeFromTypeFullName(info.ParameterType.FullName.Remove(info.ParameterType.FullName.Length - 1));
            }
            else
            {
                //retInfo.PropertyType = CSUtility.Program.GetTypeFromTypeFullName(info.ParameterType.FullName);
                retInfo.PropertyType = info.ParameterType;
            }

            foreach (var att in info.GetCustomAttributes(true))
            {
                retInfo.PropertyAttributes.Add(att as Attribute);
            }
            retInfo.DefaultValue = CodeGenerateSystem.Program.GetDefaultValueFromType(retInfo.PropertyType);
            retInfo.CurrentValue = retInfo.DefaultValue;
            return(retInfo);
        }
Пример #43
0
        string GetArgument(bcl.ParameterInfo arg)
        {
            if (arg.ParameterType.IsGenericParameter)
            {
            }

            return(TypeUtils.ToFriendlyName(arg.ParameterType) + " " + arg.Name);
        }
Пример #44
0
        public Parameter(IMember declaringMember, SR.ParameterInfo pinfo, XmlNode docNode)
        {
            this.name            = pinfo.Name;
            returnType           = new ReturnType(pinfo.ParameterType);
            this.declaringMember = declaringMember;

            try { LoadXml(docNode); } catch { }
        }
Пример #45
0
 public override void GetParameterInfo(int parameter, out string name, out string display, out string description)
 {
     EnsureParameters();
     System.Reflection.ParameterInfo param = parameters[parameter];
     name        = param.Name;
     display     = string.Format(System.Globalization.CultureInfo.InstalledUICulture, "{0} {1}", param.ParameterType.Name, param.Name);
     description = param.Name;
 }
        private static void BuildParameter(ParameterBuilder builder, System.Reflection.ParameterInfo paramInfo, int position, int count, CommandService service, IServiceProvider services)
        {
            var attributes = paramInfo.GetCustomAttributes();
            var paramType  = paramInfo.ParameterType;

            builder.Name = paramInfo.Name;

            builder.IsOptional   = paramInfo.IsOptional;
            builder.DefaultValue = paramInfo.HasDefaultValue ? paramInfo.DefaultValue : null;

            foreach (var attribute in attributes)
            {
                switch (attribute)
                {
                case SummaryAttribute summary:
                    builder.Summary = summary.Text;
                    break;

                case OverrideTypeReaderAttribute typeReader:
                    builder.TypeReader = GetTypeReader(service, paramType, typeReader.TypeReader, services);
                    break;

                case ParamArrayAttribute _:
                    builder.IsMultiple = true;
                    paramType          = paramType.GetElementType();
                    break;

                case ParameterPreconditionAttribute precon:
                    builder.AddPrecondition(precon);
                    break;

                case NameAttribute name:
                    builder.Name = name.Text;
                    break;

                case RemainderAttribute _:
                    if (position != count - 1)
                    {
                        throw new InvalidOperationException($"Remainder parameters must be the last parameter in a command. Parameter: {paramInfo.Name} in {paramInfo.Member.DeclaringType.Name}.{paramInfo.Member.Name}");
                    }

                    builder.IsRemainder = true;
                    break;

                default:
                    builder.AddAttributes(attribute);
                    break;
                }
            }

            builder.ParameterType = paramType;

            if (builder.TypeReader == null)
            {
                builder.TypeReader = service.GetDefaultTypeReader(paramType)
                                     ?? service.GetTypeReaders(paramType)?.FirstOrDefault().Value;
            }
        }
Пример #47
0
    public static void Dispatch(System.Object target, DynamicServerAction dynamicServerAction)
    {
        MethodInfo method = getDispatchMethod(target.GetType(), dynamicServerAction);

        if (method == null)
        {
            throw new InvalidActionException();
        }

        List <string> missingArguments = null;

        System.Reflection.ParameterInfo[] methodParams = method.GetParameters();
        object[] arguments = new object[methodParams.Length];
        if (methodParams.Length == 1 && methodParams[0].ParameterType == typeof(ServerAction))
        {
            ServerAction serverAction = dynamicServerAction.ToObject <ServerAction>();
            serverAction.dynamicServerAction = dynamicServerAction;
            arguments[0] = serverAction;
        }
        else
        {
            for (int i = 0; i < methodParams.Length; i++)
            {
                System.Reflection.ParameterInfo pi = methodParams[i];
                if (dynamicServerAction.ContainsKey(pi.Name))
                {
                    try {
                        arguments[i] = dynamicServerAction.GetValue(pi.Name).ToObject(pi.ParameterType);
                    } catch (ArgumentException ex) {
                        throw new ToObjectArgumentActionException(
                                  parameterName: pi.Name,
                                  parameterType: pi.ParameterType,
                                  parameterValueAsStr: dynamicServerAction.GetValue(pi.Name).ToString(),
                                  ex: ex
                                  );
                    }
                }
                else
                {
                    if (!pi.HasDefaultValue)
                    {
                        if (missingArguments == null)
                        {
                            missingArguments = new List <string>();
                        }
                        missingArguments.Add(pi.Name);
                    }
                    arguments[i] = Type.Missing;
                }
            }
        }
        if (missingArguments != null)
        {
            throw new MissingArgumentsActionException(missingArguments);
        }
        method.Invoke(target, arguments);
    }
Пример #48
0
        public string ParseExtraString(string extraString, System.Reflection.ParameterInfo parameterInfo)
        {
            if (parameterInfo.ParameterType.IsEnum)
            {
                extraString = extraString.Replace("%values%", string.Join(", ", parameterInfo.ParameterType.GetEnumNames().Select(n => n.ToLower())));
            }

            return(extraString);
        }
Пример #49
0
        protected string BuildParameterDescription(System.Reflection.ParameterInfo parameterInfo)
        {
            //get parameter name and attribute
            string           paramName  = parameterInfo.Name;
            SummaryAttribute summAttrib = parameterInfo.GetCustomAttribute(typeof(SummaryAttribute)) as SummaryAttribute;
            //get parameter template
            string paramTmpl = _botStrings.getString("common", "parameter_description");

            return(String.Format(paramTmpl, paramName, summAttrib.Text));
        }
Пример #50
0
        /**
         * @brief build dictionary of internal functions from an interface.
         * @param iface = interface with function definitions
         * @param inclSig = true: catalog by name with arg sig, eg, llSay(integer,string)
         *                 false: catalog by simple name only, eg, state_entry
         * @returns dictionary of function definition tokens
         */
        public InternalFuncDict(Type iface, bool inclSig)
            : base(false)
        {
            /*
             * Loop through list of all methods declared in the interface.
             */
            System.Reflection.MethodInfo[] ifaceMethods = iface.GetMethods();
            foreach (System.Reflection.MethodInfo ifaceMethod in ifaceMethods)
            {
                string key = ifaceMethod.Name;

                /*
                 * Only do ones that begin with lower-case letters...
                 * as any others can't be referenced by scripts
                 */
                if ((key[0] < 'a') || (key[0] > 'z'))
                {
                    continue;
                }

                try {
                    /*
                     * Create a corresponding TokenDeclVar struct.
                     */
                    System.Reflection.ParameterInfo[] parameters = ifaceMethod.GetParameters();
                    TokenArgDecl argDecl = new TokenArgDecl(null);
                    for (int i = 0; i < parameters.Length; i++)
                    {
                        System.Reflection.ParameterInfo param = parameters[i];
                        TokenType type = TokenType.FromSysType(null, param.ParameterType);
                        TokenName name = new TokenName(null, param.Name);
                        argDecl.AddArg(type, name);
                    }
                    TokenDeclVar declFunc = new TokenDeclVar(null, null, null);
                    declFunc.name    = new TokenName(null, key);
                    declFunc.retType = TokenType.FromSysType(null, ifaceMethod.ReturnType);
                    declFunc.argDecl = argDecl;

                    /*
                     * Add the TokenDeclVar struct to the dictionary.
                     */
                    this.AddEntry(declFunc);
                } catch (Exception except) {
                    string msg = except.ToString();
                    int    i   = msg.IndexOf("\n");
                    if (i > 0)
                    {
                        msg = msg.Substring(0, i);
                    }
                    Console.WriteLine("InternalFuncDict*: {0}:     {1}", key, msg);

                    ///??? IGNORE ANY THAT FAIL - LIKE UNRECOGNIZED TYPE ???///
                }
            }
        }
Пример #51
0
        /// <summary>
        /// Determine, that given parameter needs wrapping.
        /// </summary>
        /// <param name="par">Parameter which wrapping is determined.</param>
        /// <returns>True if parameter needs wrapping, false otherwise.</returns>
        private bool needWrapping(System.Reflection.ParameterInfo par)
        {
            var parType  = par.ParameterType;
            var instType = typeof(Instance);

            var isInstance        = instType == parType;
            var hasInstanceParent = instType.IsSubclassOf(parType);


            return(!isInstance && !hasInstanceParent);
        }
 public AxParameterData(System.Reflection.ParameterInfo info, bool ignoreByRefs)
 {
     this.paramInfo  = info;
     this.Name       = info.Name;
     this.type       = info.ParameterType;
     this.typeName   = AxWrapperGen.MapTypeName(info.ParameterType);
     this.isByRef    = info.ParameterType.IsByRef && !ignoreByRefs;
     this.isIn       = info.IsIn && !ignoreByRefs;
     this.isOut      = (info.IsOut && !this.isIn) && !ignoreByRefs;
     this.isOptional = info.IsOptional;
 }
Пример #53
0
 /// <summary>
 /// Builds a <see cref="ParameterInfo"/> from a reflected <see cref="System.Reflection.ParameterInfo"/>.
 /// </summary>
 public static ParameterInfo FromParameter(System.Reflection.ParameterInfo parameter)
 {
     return(new ParameterInfo
     {
         Name = parameter.Name,
         IsRemainder = parameter.GetCustomAttribute <RemainderAttribute>() != null,
         IsParamsArray = parameter.ParameterType.IsArray && parameter.GetCustomAttribute <ParamArrayAttribute>() != null,
         Type = parameter.ParameterType,
         DefaultValue = parameter.DefaultValue
     });
 }
Пример #54
0
 internal SimpleParameter(System.Reflection.ParameterInfo para, ParameterAttribute paraConfig) : base(para, paraConfig)
 {
     if (paraConfig == null)
     {
         if (para.Name.Length == 1)
         {
             paraConfig = new ParameterAttribute {
                 ShortName = (char)para.Name.First()
             }
         }
     }
     ;
Пример #55
0
    public static void Dispatch(System.Object target, dynamic serverCommand)
    {
        MethodInfo method = getDispatchMethod(target.GetType(), serverCommand);

        if (method == null)
        {
            throw new InvalidActionException();
        }

        List <string> missingArguments = null;

        System.Reflection.ParameterInfo[] methodParams = method.GetParameters();
        object[] arguments = new object[methodParams.Length];
        if (methodParams.Length == 1 && methodParams[0].ParameterType == typeof(ServerAction))
        {
            arguments[0] = serverCommand.ToObject(methodParams[0].ParameterType);
        }
        else
        {
            for (int i = 0; i < methodParams.Length; i++)
            {
                System.Reflection.ParameterInfo pi = methodParams[i];
                // allows for passing in a ServerAtion as a dynamic to ProcessControlCommand
                if (serverCommand.GetType() == pi.ParameterType)
                {
                    arguments[i] = serverCommand;
                }
                else if (serverCommand.ContainsKey(pi.Name))
                {
                    arguments[i] = serverCommand[pi.Name].ToObject(pi.ParameterType);
                }
                else
                {
                    if (!pi.HasDefaultValue)
                    {
                        if (missingArguments == null)
                        {
                            missingArguments = new List <string>();
                        }
                        missingArguments.Add(pi.Name);
                    }
                    arguments[i] = Type.Missing;
                }
            }
        }
        if (missingArguments != null)
        {
            throw new MissingArgumentsActionException(missingArguments);
        }

        method.Invoke(target, arguments);
    }
Пример #56
0
            Parameter LoadParameter(System.Reflection.ParameterInfo refParameter)
            {
                Parameter parameter = new Parameter
                {
                    Name            = refParameter.Name,
                    ParameterType   = GetTypeFullName(refParameter.ParameterType),
                    HasDefaultValue = false, // refParameter.HasDefaultValue,
                    DefaultValue    = null,  //(refParameter.HasDefaultValue ? refParameter.DefaultValue : null),
                    Attributes      = refParameter.Attributes,
                };

                return(parameter);
            }
Пример #57
0
 public ParameterBinder(System.Reflection.ParameterInfo pi)
 {
     Info = pi;
     BindAttribute[] bas = Functions.GetParemeterAttributes <BindAttribute>(pi, false);
     if (bas.Length > 0)
     {
         Binder = bas[0];
     }
     ViewStateAttribute[] vsa = Functions.GetParemeterAttributes <ViewStateAttribute>(pi, false);
     if (vsa.Length > 0)
     {
         ViewState = vsa[0];
     }
 }
Пример #58
0
        // parse form input
        private object[] GetFormArguments(Queue <string> inputValues)
        {
            object[] result = new object[ParameterInfos.Length]; // holder for results

            for (int i = 0; i < ParameterInfos.Length; i++)
            {
                System.Reflection.ParameterInfo param = ParameterInfos[i];
                Type   currentParameterType           = param.ParameterType;
                object parameterValue = GetParameterValue(inputValues, currentParameterType);

                result[i] = parameterValue;
            }
            return(result);
        }
        static StackObject *get_ParameterType_0(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 1);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Reflection.ParameterInfo instance_of_this_method = (System.Reflection.ParameterInfo) typeof(System.Reflection.ParameterInfo).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags) 0);
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.ParameterType;

            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
        public bool TryGetProvider(System.Reflection.ParameterInfo pi, ICreationContext context, out Func <object> valueProvider)
        {
            IComponentRegistration registration;

            if (context.TryGetRegistered(pi.ParameterType, out registration))
            {
                valueProvider = delegate() { return(MatchTypes(pi, context.Get(registration))); };
                return(true);
            }
            else
            {
                valueProvider = null;
                return(false);
            }
        }