示例#1
0
        public IEnumerable<IConceptInfo> CreateNewConcepts(IEnumerable<IConceptInfo> existingConcepts)
        {
            var newConcepts = new List<IConceptInfo>();

            ParameterInfo filterParameter;
            var filterNameElements = FilterName.Split('.');
            if (filterNameElements.Count() == 2)
                filterParameter = new ParameterInfo { Module = new ModuleInfo { Name = filterNameElements[0] }, Name = filterNameElements[1] };
            else
                filterParameter = new ParameterInfo { Module = Source.Module, Name = FilterName };

            if (!existingConcepts.OfType<DataStructureInfo>() // Existing filter parameter does not have to be a ParameterInfo. Any DataStructureInfo is allowed.
                .Any(item => item.Module.Name == filterParameter.Module.Name && item.Name == filterParameter.Name))
                    newConcepts.Add(filterParameter);

            var composableFilter = new ComposableFilterByInfo
            {
                Source = Source,
                Parameter = filterParameter.GetKeyProperties(),
                Expression = "(source, repository, parameter) => source.Where(" + Expression + ")"
            };

            newConcepts.Add(composableFilter);

            return newConcepts;
        }
示例#2
0
        public override string CreateUrl(ParameterInfo yeepay)
        {
            var info = yeepay as YeePayParasInfo;
            if (info == null) return "";
            //签名
            var sb = "Buy";
            sb += Configs.GetPartnerId();
            sb += info.OrderNum;
            sb += info.Amount.ToString("0.00");
            sb += info.Cur;
            sb += info.ProName;
            sb += info.ProCate;
            sb += info.ProDesc;
            sb += info.ReturnUrl;
            sb += info.Saf;
            sb += info.ExtentInfo;
            sb += info.FrpId;
            sb += (info.NeedResponse ? "1" : "0");
            var hmac = Digest.HmacSign(sb, Configs.GetKey());

            var url = Configs.RequestPayUrl;
            url += string.Format(Configs.Paras, Configs.GetPartnerId(),
                                 HttpUtility.UrlEncode(info.OrderNum, Configs.DefCoding), info.Amount.ToString("0.00"), info.Cur,
                                 HttpUtility.UrlEncode(info.ProName, Configs.DefCoding),
                                 HttpUtility.UrlEncode(info.ProCate, Configs.DefCoding),
                                 HttpUtility.UrlEncode(info.ProDesc, Configs.DefCoding),
                                 HttpUtility.UrlEncode(info.ReturnUrl, Configs.DefCoding),
                                 info.Saf, HttpUtility.UrlEncode(info.ExtentInfo, Configs.DefCoding), info.FrpId,
                                 (info.NeedResponse ? "1" : "0"), hmac);
            return url;
        }
示例#3
0
        public IEnumerable<IConceptInfo> CreateNewConcepts(IEnumerable<IConceptInfo> existingConcepts)
        {
            var filterParameter = new ParameterInfo
            {
                Module = Property.DataStructure.Module,
                Name = Property.Name + "_RegExMatchFilter",
            };

            string filterExpression = string.Format(@"(source, repository, parameter) =>
                {{
                    var items = source.Where(item => !string.IsNullOrEmpty(item.{0})).Select(item => new {{ item.ID, item.{0} }}).ToList();
                    var regex = new System.Text.RegularExpressions.Regex({1});
                    var invalidItemIds = items.Where(item => !regex.IsMatch(item.{0})).Select(item => item.ID).ToList();
                    return Filter(source, invalidItemIds);
                }}",
                Property.Name,
                CsUtility.QuotedString("^" + RegularExpression + "$"));

            var itemFilterRegExMatchProperty = new ComposableFilterByInfo
            {
                Expression = filterExpression,
                Parameter = filterParameter.Module.Name + "." + filterParameter.Name,
                Source = Property.DataStructure
            };

            var invalidDataRegExMatchProperty = new InvalidDataMarkPropertyInfo
            {
                DependedProperty = Property,
                FilterType = itemFilterRegExMatchProperty.Parameter,
                ErrorMessage = ErrorMessage,
                Source = Property.DataStructure
            };

            return new IConceptInfo[] { filterParameter, itemFilterRegExMatchProperty, invalidDataRegExMatchProperty };
        }
示例#4
0
	public static void ConvertParameters(EngineManager manager, ParameterInfo[] parameterInfo, ref object[] parameters)
	{
		for (int i = 0; i < parameterInfo.Length; i++)
		{
			if (Common.TypeInheritsFrom(parameterInfo[i].ParameterType, typeof(EngineObject)) && parameters[i].GetType() == typeof(int))
			{
				parameters[i] = manager.GetObject<EngineObject>((int)parameters[i]);
			}

			if (parameterInfo[i].ParameterType == typeof(object[]))
			{
				object[] tempObjects = new object[parameters.Length - i];

				for (int j = 0; j < tempObjects.Length; j++)
				{
					tempObjects[j] = parameters[i + j];
				}

				parameters[i] = tempObjects;

				object[] newParameters = new object[i + 1];
				for (int j = 0; j < newParameters.Length; j++)
				{
					newParameters[j] = parameters[j];
				}

				parameters = newParameters;
			}
		}
	}
示例#5
0
        public Expression<Func<object>> GetValueFactory(string key, ParameterInfo parameter = null)
        {
            Guard.EnsureIsNotNullOrEmpty("key", key);

            if (!Delegates.ContainsKey(key))
            {
                return null;
            }

            var expression = Delegates[key];
            var parameterExpression = expression.Parameters
                .SafeSelect(p => p)
                .FirstOrDefault();

            if (parameter.IsNull() || parameterExpression.IsNull())
            {
                return Expression.Lambda<Func<object>>(expression.Body, null);
            }

            var blockExpression = Expression.Block(
                new[] { parameterExpression },
// ReSharper disable AssignNullToNotNullAttribute
// ReSharper disable once PossibleNullReferenceException
                Expression.Assign(parameterExpression, Expression.Constant(parameter.Value)),
                //Expression.Constant(parameter.Value, parameter.Type)),
// ReSharper restore AssignNullToNotNullAttribute
                expression.Body);

            return Expression.Lambda<Func<object>>(blockExpression, null);
        }
    private void OnSerializing() {
        Animator animator = GetComponent<Animator>();

        // Store the current state for each layer
        layerData = new LayerInfo[animator.layerCount];
        for (int i = 0; i < animator.layerCount; i++) {
            layerData[i] = new LayerInfo {
                index = i,
                currentHash = animator.GetCurrentAnimatorStateInfo(i).shortNameHash,
                nextHash = animator.GetNextAnimatorStateInfo(i).shortNameHash,
                normalizedTimeCurrent = animator.GetCurrentAnimatorStateInfo(i).normalizedTime,
                normalizedTimeNext = animator.GetNextAnimatorStateInfo(i).normalizedTime,
                weight = animator.GetLayerWeight(i)
            };
        }

        // Store every parameter
        parameterData = new ParameterInfo[animator.parameterCount];
        for (int i = 0; i < animator.parameterCount; i++) {
            parameterData[i] = new ParameterInfo {
                number = animator.parameters[i].nameHash,
                type = animator.parameters[i].type,
                value = GetParameterValue(animator.parameters[i].nameHash, animator.parameters[i].type, animator)
            };
        }
    }
            public override void VisitParameter(ParameterAttribute parameter)
            {
                _parameterInfo = new ParameterInfo(CurrentProperty, parameter);
                _cmdletInfo.AddParameter(_parameterInfo);

                base.VisitParameter(parameter);
            }
示例#8
0
        public override string CreateUrl(ParameterInfo alipay)
        {
            var info = alipay as AlipayParasInfo;
            if (info == null) return "";
            //构造数组;
            //以下数组即是参与加密的参数,若参数的值不允许为空,若该参数为空,则不要成为该数组的元素
            string[] paras = {
                                 "service=" + Configs.Service,
                                 "partner=" + Configs.GetPartnerId(),
                                 "seller_email=" + Configs.GetSellerEmail(),
                                 "out_trade_no=" + info.OrderNum,
                                 "subject=" + info.ProName + "[" + info.Amount.ToString("0.00") + "]元",
                                 "body=" + info.ProName,
                                 "total_fee=" + info.Amount.ToString("0.00"),
                                 "show_url=" + info.ShowUrl,
                                 "payment_type=1",
                                 "notify_url=" + info.NotifyUrl,
                                 "return_url=" + info.ReturnUrl,
                                 "_input_charset=utf-8",
                                 "buyer_email=" + info.Account
                             };

            var sortedstr = Digest.BubbleSort(paras);

            //构造待md5摘要字符串
            var prestr = new StringBuilder();

            //以下是GET方式传递参数
            //构造支付Url;
            var parameter = new StringBuilder();

            parameter.Append(Configs.Getway);

            for (var i = 0; i < sortedstr.Length; i++)
            {
                if (i == sortedstr.Length - 1)
                {
                    prestr.Append(sortedstr[i]);

                }
                else
                {
                    prestr.Append(sortedstr[i] + "&");
                }
                var para = sortedstr[i].Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                //UTF-8格式的编码转换
                parameter.Append(para[0] + "=" + HttpUtility.UrlEncode(para[1], Encoding.UTF8) + "&");
            }

            prestr.Append(Configs.GetKey());

            //签名
            var sign = Digest.GetMd5(prestr.ToString(), "utf-8");


            parameter.Append("sign=" + sign + "&sign_type=" + Configs.SignType);

            //返回支付Url;
            return parameter.ToString();
        }
示例#9
0
 private ParameterInfo(ParameterInfo accessor, MemberInfo member)
 {
     this.MemberImpl = member;
     this.NameImpl = accessor.Name;
     this.ClassImpl = accessor.ParameterType;
     this.PositionImpl = accessor.Position;
     this.AttrsImpl = accessor.Attributes;
 }
示例#10
0
 private static object[] GetDefaultValuesForParameters(ParameterInfo[] paramTypes)
 {
     Object[] parameters = new Object[paramTypes.Length];
     for (int i = 0; i < paramTypes.Length; i++)
     {
         parameters[i] = Activator.CreateInstance(paramTypes[i].ParameterType);
     }
     return parameters;
 }
	static string ParameterName (ParameterInfo parameter)
	{
		switch (parameter.Name) {
		case "break":
		case "continue":
		case "finally":
			return "@" + parameter.Name;
		}

		return parameter.Name;
	}
        public sealed override ParameterInfo[] GetParameters()
        {
            if (ReflectionTrace.Enabled)
                ReflectionTrace.MethodBase_GetParameters(this);

            RuntimeParameterInfo[] runtimeParametersAndReturn = this.RuntimeParametersAndReturn;
            if (runtimeParametersAndReturn.Length == 1)
                return Array.Empty<ParameterInfo>();
            ParameterInfo[] result = new ParameterInfo[runtimeParametersAndReturn.Length - 1];
            for (int i = 0; i < result.Length; i++)
                result[i] = runtimeParametersAndReturn[i + 1];
            return result;
        }
示例#13
0
 public CalculatorBot(string token)
     : base("calculator", token)
 {
     var command = new CommandInfo("/start");
     command.StaticAcceptMessage = "Ok you started the calculator";
     Configuration.Commands.Add(command);
     Configuration.StaticUnknownCommandMessage = "Unknown command. Please try another command. Send /start to get a list of available comands.";
     var command2 = new CommandInfo("/newbrand");
     command2.StaticAcceptMessage = "New brand is saved.";
     var parameter = new ParameterInfo() { Name = "Name", Type = ParameterTypes.Text, Optional = false, StaticPrompt = "Ok, enter new brand name." };
     command2.Parameters.Add(parameter);
     Configuration.Commands.Add(command2);
 }
示例#14
0
    public static MySqlParameter[] GenerateParam(ParameterInfo[] methodParameters, params object[] Values)
    {
        int length = methodParameters.Length;
        MySqlParameter[] sqlParams = new MySqlParameter[length];

        for (int i = 0; i < length; i++)
        {
            MySqlParameter parameter = new MySqlParameter();
            parameter.ParameterName = "@" + methodParameters[i].Name;
            parameter.Value = Values[i];
            sqlParams[i] = parameter;
        }

        return sqlParams;
    }
        protected void AddValueFactory(ValueFactoryModelBase model, 
            string loaderKey, ParameterInfo parameter = null)
        {
            if (model.IsNull())
            {
                return;
            }

            Guard.EnsureIsNotNullOrEmpty("loaderKey", loaderKey);

            var valueExpression = ValueFactory.GetValueFactory(
                loaderKey, parameter);

            valueExpression.Do(() =>
                model.ValueFactories.Add(loaderKey, valueExpression.Compile()));
        }
        /// <summary>
        /// Creates a new instance of the StoredProcedureInfo class.
        /// This constructor is private; call the static GetInfo() method instead.
        /// </summary>
        /// <param name="connectionName">Name of the database connection.</param>
        /// <param name="schema">Name of the database schema.</param>
        /// <param name="procedureName">Name of the stored procedure.</param>
        private StoredProcedureInfo(string connectionName, string schema, string procedureName)
        {
            this.ConnectionName = connectionName;
            this.Schema = schema;
            this.ProcedureName = procedureName;

            // query the database for the procedure's parameters;
            // if the procedure doesn't exist, zero parameters will be found, successfully (no error)
            var parametersQuery = new StoredProcedureQuery("SelectStoredProcedureParameters", connectionName);
            parametersQuery.Parameters.Add("Schema", this.Schema);
            parametersQuery.Parameters.Add("ProcedureName", this.ProcedureName);

            DataSet results = parametersQuery.ReturnAllTables();
            var parameters = results.Tables[0];   // no rows if the procedure has no parameters
            var columnNames = results.Tables[1];  // no rows if the procedure has no TVPs; all TVPs' columns otherwise

            foreach (DataRow parameter in parameters.Rows)
            {
                var param = new ParameterInfo
                {
                    Name = parameter["ParameterName"] as string,
                    TypeString = parameter["DataType"] as string,
                    UserDefinedTypeName = parameter["UserDefinedTypeName"] as string,
                    MaxLength = parameter["MaxLength"] as int?
                };

                // TODO: switch this logic around when we internationalize the db to use nvarchar columns
                if (param.TypeString == "varchar")
                    param.Type = SqlDbType.VarChar;
                else if (param.TypeString == "char")
                    param.Type = SqlDbType.Char;
                else if (param.TypeString == "nvarchar")
                    param.Type = SqlDbType.NVarChar;
                else if (param.TypeString == "nchar")
                    param.Type = SqlDbType.NChar;
                else if (param.TypeString == "table type")
                {
                    param.Type = SqlDbType.Structured;

                    // get the table type's column names
                    param.ColumnNames = columnNames.Select("ParameterName = '" + param.Name + "'")
                        .Select(dr => dr["ColumnName"] as string).ToArray();
                }

                this.Parameters.Add(param);
            }
        }
示例#17
0
 public static string SharpKitMethodName(string methodName, ParameterInfo[] paramS, bool overloaded, int TCounts = 0)
 {
     string name = methodName;
     if (overloaded)
     {
         if (TCounts > 0)
             name += "T" + TCounts.ToString();
         for (int i = 0; i < paramS.Length; i++)
         {
             Type type = paramS[i].ParameterType;
             name += "$$" + SharpKitTypeName(type);
         }
         name = name.Replace("`", "T");
     }
     name = name.Replace("$", "_");
     return name;
 }
        // TODO, refactoring 
        public MethodVisitor(IClassRepository repository, ClassInfo classInfo,
                                    string name, string descriptor, string signature, string[] exceptions,
                                    bool isStatic, bool isFinal, Visibility visibility)
        {
            Repository = repository;
            ClassInfo = classInfo;
            Name = name;
            Descriptor = descriptor;
            IsStatic = isStatic;
            IsFinal = isFinal;
            Visibility = visibility;

            var slot = 0;
            if (!IsStatic)
            {
                var thisType = ClrType.FromDescriptor(classInfo.Name);
                methodThis = new ParameterInfo("this", thisType);

                //slots.Add(slot++, methodThis);
                slot ++;
                parameters.Add(methodThis);
            }

            var rightBraceIndex = descriptor.IndexOf(')');
            var parameterString = descriptor.Substring(1, rightBraceIndex - 1);

            if (parameterString.Length > 0)
            {
                var parameters1 = parameterString.Split(',');

                foreach (var parameter in parameters1)
                {
                    var parameterType = new Type(parameter);

                    //ParameterInfo parameterInfo = new ParameterInfo("param_" + slot, parameterType);
                    var parameterInfo = new ParameterInfo("param_" + slot, parameterType);
                    parameters.Add(parameterInfo);
                    //slots.Add(slot++, parameterInfo);
                    slot++;
                    if (ClrType.IsDoubleSlot(parameterType))
                    {
                        slot++;
                    }
                }
            }
        }
示例#19
0
        public ParameterEditForm(dao.QAParameter param, string paramType, bool autoStoreChanges)
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            if (param == null)
                throw new ArgumentNullException("param", "Cannot pass null parameter to ParameterEditForm");

            this._param = param;

            switch (paramType)
            {
                case BooleanParameterInfo.TYPE_WKT:
                    this._pinfo = new BooleanParameterInfo(param.Name, "", param.Value);
                    break;
                case IntegerParameterInfo.TYPE_WKT:
                    this._pinfo = new IntegerParameterInfo(param.Name, "", param.Value);
                    break;
                case DoubleParameterInfo.TYPE_WKT:
                    this._pinfo = new DoubleParameterInfo(param.Name, "", param.Value);
                    break;
                case StringParameterInfo.TYPE_WKT:
                    this._pinfo = new StringParameterInfo(param.Name, "", param.Value);
                    break;
                case ChooseLayerParameterInfo.TYPE_WKT:
                    this._pinfo = new ChooseLayerParameterInfo(param.Name, "", param.Value);
                    break;
                case ChooseTableParameterInfo.TYPE_WKT:
                    this._pinfo = new ChooseTableParameterInfo(param.Name, "", param.Value);
                    break;
                case UnitsParameterInfo.TYPE_WKT:
                    this._pinfo = new UnitsParameterInfo(param.Name, "", param.Value);
                    break;
                default:
                    this._pinfo = null;
                    break;
            }

            if (this._pinfo == null)
                throw new ArgumentException("Unknown type of ParameterInfo specified", "paramType");

            this._autoStore = autoStoreChanges;
        }
示例#20
0
        public override string CreateUrl(ParameterInfo mwAlipay)
        {
            var info = mwAlipay as MwAlipayInfo;
            if (info == null)
                return "";
            //请求业务参数详细
            string reqDataToken = "<direct_trade_create_req><notify_url>" + info.NotifyUrl + "</notify_url><call_back_url>" + info.ReturnUrl + "</call_back_url><seller_account_name>" + Config.GetSellerEmail() + "</seller_account_name><out_trade_no>" + info.OrderNum + "</out_trade_no><subject>" + HttpUtility.HtmlEncode(info.ProName) + "</subject><total_fee>" + info.Amount.ToString("0.00") + "</total_fee><merchant_url>" + info.ReturnUrl + "</merchant_url></direct_trade_create_req>";

            var sParaTempToken = new Dictionary<string, string>
                                     {
                                         {"partner", Config.GetPartnerId()},
                                         {"_input_charset", Config.Charset},
                                         {"sec_id", Config.SignType.ToUpper()},
                                         {"service", Config.ServiceTrade},
                                         {"format", Config.Format},
                                         {"v", Config.Version},
                                         {"req_id", info.OrderNum},
                                         {"req_data", reqDataToken}
                                     };
            var encoding = Encoding.GetEncoding(Config.Charset);
            sParaTempToken = Common.Utils.BuildParas(sParaTempToken, Config.GetKey(), Config.Charset);
            var paras = Common.Utils.CreateLinkString(sParaTempToken,encoding);
            var token = "";
            const string gateWay = Config.Getway + "_input_charset=" + Config.Charset;
            using (var http = new HttpHelper(gateWay, "POST", encoding, paras))
            {
                token = http.GetHtml();
            }
            //解析token
            var requestToken = Common.Utils.GetRequestToken(token,encoding);
            string reqData = "<auth_and_execute_req><request_token>" + requestToken + "</request_token></auth_and_execute_req>";
            var sParaTemp = new Dictionary<string, string>
                                {
                                    {"partner", Config.GetPartnerId()},
                                    {"_input_charset", Config.Charset.ToLower()},
                                    {"sec_id", Config.SignType.ToUpper()},
                                    {"service", Config.ServiceAuth},
                                    {"format", Config.Format},
                                    {"v", Config.Version},
                                    {"req_data", reqData}
                                };
            sParaTemp = Common.Utils.BuildParas(sParaTemp, Config.GetKey(), Config.Charset);

            return Common.Utils.BuildRequest(Config.Getway, sParaTemp);
        }
示例#21
0
        private static object FormatValue(ParameterInfo[] pInfos, int index, byte controlFlag, uint value)
        {
            var pInfo = (index < pInfos.Length) ? pInfos[index] : new ParameterInfo();
            var opType = (OpCodeFlag) (pInfo.Type == ParamType.Destination ? controlFlag & 3 : controlFlag >> 2 & 3);

            switch (opType)
            {
                case OpCodeFlag.Register:
                    return string.Concat('r', value + 1).PadRight(12);

                case OpCodeFlag.Constant:
                    return string.Concat('$', value).PadRight(12);

                case OpCodeFlag.MemoryAddress:
                    return string.Concat("[r", value + 1, ']').PadRight(12);

                case OpCodeFlag.None:
                    return string.Empty.PadRight(12);

                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
示例#22
0
 private static string Signature(string name, ParameterInfo[] allpi)
 {
     StringBuilder sb = new StringBuilder();
     sb.Append(name);
     sb.Append("(");
     bool first = true;
     foreach(ParameterInfo pi in allpi)
     {
         if(first)
         {
             first = false;
         }
         else
         {
             sb.Append(",");
         }
         sb.Append(pi.ParameterType.ToString());
         sb.Append(" ");
         sb.Append(pi.Name);
     }
     sb.Append(")");
     return sb.ToString();
 }
示例#23
0
        public override string CreateUrl(ParameterInfo unionPay)
        {
            var info = unionPay as UnionPayParasInfo;
            if (info == null)
                return "";
            UPOPSrv.LoadConf(HttpContext.Current.Server.MapPath("~/App_Data/xml/unionPay.config"));

            var paras = new Dictionary<string, string>
                            {
                                {"transType", "01"},
                                {"commodityUrl", Uri.EscapeUriString(info.ProductUrl)},
                                {"commodityName", info.ProductName},
                                {"commodityUnitPrice", info.UnitPrice.ToString()},
                                {"orderNumber", info.OrderNum},
                                {"orderAmount", (Math.Round(info.Amount, 2)*100).ToString("F0")},
                                {"orderCurrency", info.Cur},
                                {"orderTime", DateTime.Now.ToString("yyyyMMddHHmmss")},
                                {"customerIp", Utils.GetRealIp()},
                                {"frontEndUrl", info.ReturnUrl},
                                {"backEndUrl", info.NotifyUrl}
                            };
            var srv = new FrontPaySrv(paras);
            return srv.CreateHtml();
        }
示例#24
0
        /// <summary>
        /// Create a panel for the specific parameter
        /// </summary>
        /// <param name="param">the parameter to create panel for</param>
        /// <param name="defaultValue">The default value for the parameter</param>
        /// <returns>the panel</returns>
        private static ParamInputPanel CreatePanelForParameter(ParameterInfo param, object defaultValue)
        {
            ParamInputPanel panel = new ParamInputPanel();

            panel.Height = 50;
            panel.Width  = 400;
            Point textBoxStart = new Point(100, 10);

            #region add the label for the parameter
            Label paramNameLabel = new Label();
            paramNameLabel.AutoSize = true;
            panel.Controls.Add(paramNameLabel);
            paramNameLabel.Location = new Point(10, textBoxStart.Y);
            #endregion

            if (param == null)
            { // a generic parameter
                GenericParameter p = defaultValue as GenericParameter;

                paramNameLabel.Text = "";

                String[] options = Array.ConvertAll <Type, String>(p.AvailableTypes, delegate(Type t) { return(t.Name); });
                ComboBox combo   = new ComboBox();
                panel.Controls.Add(combo);
                combo.Location = textBoxStart;
                combo.Items.AddRange(options);
                combo.SelectedIndex    = Array.FindIndex <String>(options, p.SelectedType.ToString().Equals);
                panel.GetParamFunction =
                    delegate()
                {
                    return
                        (new GenericParameter(
                             p.AvailableTypes[Array.FindIndex <String>(options, combo.Text.ToString().Equals)],
                             p.AvailableTypes));
                };
            }
            else
            {
                Type paramType = param.ParameterType;
                paramNameLabel.Text = String.Format("{0}:", ParseParameterName(param));

                if (paramType.IsEnum)
                {
                    ComboBox combo = new ComboBox();
                    panel.Controls.Add(combo);
                    combo.Location = textBoxStart;
                    combo.Items.AddRange(Enum.GetNames(paramType));
                    combo.SelectedIndex = 0;
                    combo.Width         = 240;

                    panel.GetParamFunction =
                        delegate
                    {
                        return(Enum.Parse(paramType, combo.SelectedItem.ToString(), true));
                    };
                }
                else if (paramType == typeof(bool))
                {
                    ComboBox combo = new ComboBox();
                    panel.Controls.Add(combo);
                    combo.Location = textBoxStart;
                    combo.Items.AddRange(new String[] { "True", "False" });
                    combo.SelectedIndex    = 0;
                    panel.GetParamFunction =
                        delegate()
                    {
                        return(combo.SelectedItem.ToString().Equals("True"));
                    };
                }
                else if (paramType == typeof(UInt64) || paramType == typeof(int) || paramType == typeof(double))
                {
                    //Create inpout box for the int paramater
                    TextBox inputTextBox = new TextBox();
                    panel.Controls.Add(inputTextBox);
                    inputTextBox.Location = textBoxStart;
                    inputTextBox.Text     = defaultValue == null ? "0" : defaultValue.ToString();

                    panel.GetParamFunction =
                        delegate()
                    {
                        return(Convert.ChangeType(inputTextBox.Text, paramType));
                    };
                }
                else if (paramType == typeof(MCvScalar))
                {
                    TextBox[] inputBoxes = new TextBox[4];
                    int       boxWidth   = 40;

                    //Create input boxes for the scalar value
                    for (int i = 0; i < inputBoxes.Length; i++)
                    {
                        inputBoxes[i] = new TextBox();
                        panel.Controls.Add(inputBoxes[i]);
                        inputBoxes[i].Location = new Point(textBoxStart.X + i * (boxWidth + 5), textBoxStart.Y);
                        inputBoxes[i].Width    = boxWidth;
                        inputBoxes[i].Text     = "0.0";
                    }
                    panel.GetParamFunction =
                        delegate()
                    {
                        double[] values = new double[4];
                        for (int i = 0; i < inputBoxes.Length; i++)
                        {
                            values[i] = Convert.ToDouble(inputBoxes[i].Text);
                        }
                        return(new MCvScalar(values[0], values[1], values[2], values[3]));
                    };
                }
                else if (paramType == typeof(PointF))
                {
                    TextBox[] inputBoxes = new TextBox[2];
                    int       boxWidth   = 40;

                    //Create input boxes for the scalar value
                    for (int i = 0; i < 2; i++)
                    {
                        inputBoxes[i] = new TextBox();
                        panel.Controls.Add(inputBoxes[i]);
                        inputBoxes[i].Location = new Point(textBoxStart.X + i * (boxWidth + 5), textBoxStart.Y);
                        inputBoxes[i].Width    = boxWidth;
                        inputBoxes[i].Text     = "0.0";
                    }
                    panel.GetParamFunction =
                        delegate()
                    {
                        float[] values = new float[inputBoxes.Length];
                        for (int i = 0; i < inputBoxes.Length; i++)
                        {
                            values[i] = Convert.ToSingle(inputBoxes[i].Text);
                        }
                        return(new PointF(values[0], values[1]));
                    };
                }
                else if (paramType.GetInterface("IColor") == typeof(IColor))
                {
                    IColor t = Activator.CreateInstance(paramType) as IColor;
                    //string[] channelNames = ReflectColorType.GetNamesOfChannels(t);
                    TextBox[] inputBoxes = new TextBox[t.Dimension];
                    int       boxWidth   = 40;

                    //Create input boxes for the scalar value
                    for (int i = 0; i < inputBoxes.Length; i++)
                    {
                        inputBoxes[i] = new TextBox();
                        panel.Controls.Add(inputBoxes[i]);
                        inputBoxes[i].Location = new Point(textBoxStart.X + i * (boxWidth + 5), textBoxStart.Y);
                        inputBoxes[i].Width    = boxWidth;
                        inputBoxes[i].Text     = "0.0";
                    }
                    panel.GetParamFunction =
                        delegate()
                    {
                        double[] values = new double[4];
                        for (int i = 0; i < inputBoxes.Length; i++)
                        {
                            values[i] = Convert.ToDouble(inputBoxes[i].Text);
                        }
                        IColor color = Activator.CreateInstance(paramType) as IColor;
                        color.MCvScalar = new MCvScalar(values[0], values[1], values[2], values[3]);
                        return(color);
                    };
                }
                else
                {
                    throw new NotSupportedException(String.Format(Properties.StringTable.ParameterTypeIsNotSupported, paramType.Name));
                }
            }
            return(panel);
        }
示例#25
0
 private static bool IsCancellationToken(ParameterInfo parameter)
 {
     return(typeof(CancellationToken).IsAssignableFrom(parameter.ParameterType) ||
            typeof(CancellationToken?).IsAssignableFrom(parameter.ParameterType));
 }
示例#26
0
 public static Attribute[] GetCustomAttributes(ParameterInfo element) => (Attribute[])CustomAttribute.GetCustomAttributes(element, true);
示例#27
0
	/// <summary>
	/// Convert parameters to object array
	/// </summary>
	/// <param name="theMethodParametersList"></param>
	/// <param name="theParametersList"></param>
	/// <returns></returns>
	static object[] ConvertParameters (ParameterInfo[]theMethodParametersList, EventParameter[]theParametersList)
	{
		object [] anObjectList = new object[theMethodParametersList.Length];
		
		for (int i=0; i<theMethodParametersList.Length; i++)
		{
			if (typeof(UnityEngine.Object).IsAssignableFrom (theMethodParametersList [i].ParameterType))
			{
				// unity objects, regardless of type
				anObjectList [i] = theParametersList [i].itsValueUnityObject;
			} else if (SearchInstanceForVariable (typeof(EventParameter), theParametersList [i], "itsValue" + theMethodParametersList [i].ParameterType.Name, ref anObjectList [i]))
			{
				// other objects
			} else
			{
				// could not find
				Debug.LogError ("could not find variable for type:" + theMethodParametersList [i].ParameterType.Name);
			}
		}
		
		return anObjectList;
	}
示例#28
0
 /// <summary>
 /// Returns true if the parameter is able to provide a value to a particular site.
 /// </summary>
 /// <param name="pi">Constructor, method, or property-mutator parameter.</param>
 /// <param name="context">The component context in which the value is being provided.</param>
 /// <param name="valueProvider">If the result is true, the valueProvider parameter will
 /// be set to a function that will lazily retrieve the parameter value. If the result is false,
 /// will be set to null.</param>
 /// <returns>True if a value can be supplied; otherwise, false.</returns>
 public abstract bool CanSupplyValue(ParameterInfo pi, IComponentContext context, out Func <object> valueProvider);
示例#29
0
 public Parameter(ParameterInfo parameterInfo)
 {
     _parameterInfo = parameterInfo;
 }
示例#30
0
 public static Attribute[] GetCustomAttributes(ParameterInfo element, bool inherit) => (Attribute[])CustomAttribute.GetCustomAttributes(element, inherit);
示例#31
0
        /// <summary>
        /// Emits load of an array where all optional arguments are stored.
        /// Each optional argument is peeked from the PHP stack and converted before stored to the array.
        /// The resulting array is pushed on evaluation stack so it can be later passed as an argument to a method.
        /// </summary>
        /// <param name="builder">The builder.</param>
        /// <param name="start">The index of the first argument to be loaded.</param>
        /// <param name="param">The last parameter of the overload (should be an array).</param>
        /// <param name="optArgCount">The place where the number of optional arguments is stored.</param>
        /// <remarks>Assumes that the non-negative number of optional arguments has been stored to
        /// <paramref name="optArgCount"/> place.</remarks>
        public static void EmitPeekAllArguments(OverloadsBuilder /*!*/ builder, int start, ParameterInfo param, IPlace optArgCount)
        {
            Debug.Assert(start >= 0 && optArgCount != null && param != null);

            ILEmitter il         = builder.IL;
            Type      elem_type  = param.ParameterType.GetElementType();
            Type      array_type = Type.GetType(elem_type.FullName + "[]", true);
            Type      actual_type;

            // declares aux. variables:
            LocalBuilder loc_array = il.DeclareLocal(array_type);
            LocalBuilder loc_i     = il.DeclareLocal(typeof(int));
            LocalBuilder loc_elem  = il.DeclareLocal(elem_type);

            // creates an array for the arguments
            // array = new <elem_type>[opt_arg_count]:
            optArgCount.EmitLoad(il);
            il.Emit(OpCodes.Newarr, elem_type);
            il.Stloc(loc_array);

            Label for_end_label   = il.DefineLabel();
            Label condition_label = il.DefineLabel();

            // i = 0;
            il.Emit(OpCodes.Ldc_I4_0);
            il.Stloc(loc_i);

            // FOR (i = 0; i < opt_arg_count; i++)
            if (true)
            {
                il.MarkLabel(condition_label);

                // condition (i < opt_arg_count):
                il.Ldloc(loc_i);
                optArgCount.EmitLoad(il);
                il.Emit(OpCodes.Bge, for_end_label);

                // LOAD stack, i + start+1>:
                builder.Stack.EmitLoad(il);
                il.Ldloc(loc_i);
                il.LdcI4(start + 1);
                il.Emit(OpCodes.Add);

                if (elem_type == typeof(PhpReference))
                {
                    // CALL stack.PeekReferenceUnchecked(STACK);
                    il.Emit(OpCodes.Call, Methods.PhpStack.PeekReferenceUnchecked);
                    actual_type = typeof(PhpReference);
                }
                else
                {
                    // CALL stack.PeekValueUnchecked(STACK);
                    il.Emit(OpCodes.Call, Methods.PhpStack.PeekValueUnchecked);
                    actual_type = typeof(object);
                }

                // emits a conversion stuff (loads result into "elem" local variable):
                builder.EmitArgumentConversion(elem_type, actual_type, false, param);
                il.Stloc(loc_elem);

                // array[i] = elem;
                il.Ldloc(loc_array);
                il.Ldloc(loc_i);
                il.Ldloc(loc_elem);
                il.Stelem(elem_type);

                // i = i + 1;
                il.Ldloc(loc_i);
                il.Emit(OpCodes.Ldc_I4_1);
                il.Emit(OpCodes.Add);
                il.Stloc(loc_i);

                // GOTO condition;
                il.Emit(OpCodes.Br, condition_label);
            }
            // END FOR

            il.MarkLabel(for_end_label);

            // loads array to stack - consumed by the method call:
            il.Ldloc(loc_array);
        }
示例#32
0
        /// <summary>
        /// Generates command parameters.
        /// For some command types the command text can be changed during parameter generating.
        /// </summary>
        /// <param name="command">Command object.</param>
        /// <param name="method"><see cref="MethodInfo"/> type object</param>
        /// <param name="values">Array of values for the command parameters.</param>
        /// <param name="swCommandType"><see cref="SWCommandType"/> enumeration value</param>
        /// <param name="indexes">Array of parameter indices.</param>
        private static void GenerateCommandParameters(DbCommand command, MethodInfo method, object[] values, int[] indexes, SWCommandType swCommandType)
        {
            #region InsertUpdate parts declaration
            string sUpdatePart1             = "";
            string sUpdatePart2             = "";
            string sUpdate                  = "";
            string sInsertPart1             = "";
            string sInsertPart2             = "";
            string sInsert                  = "";
            string sAutoincrementColumnName = "";
            #endregion


            //DatabaseHelper db = new DatabaseHelper();
            ParameterInfo[] methodParameters = method.GetParameters();

            int sqlParamIndex = 0;
            for (int paramIndex = 0; paramIndex < methodParameters.Length; ++paramIndex)
            {
                indexes[paramIndex] = -1;
                ParameterInfo paramInfo = methodParameters[paramIndex];

                // create command parameter
                DbParameter sqlParameter = command.CreateParameter();

                // set default values
                string          paramName     = paramInfo.Name;
                SWParameterType paramCustType = SWParameterType.Default;
                object          v             = values[paramIndex];

                // get parameter attribute and set command parameter settings
                SWParameterAttribute paramAttribute = (SWParameterAttribute)Attribute.GetCustomAttribute(paramInfo, typeof(SWParameterAttribute));
                if (paramAttribute != null)
                {
                    paramCustType = paramAttribute.ParameterType;

                    if (paramAttribute.IsNameDefined)
                    {
                        paramName = sqlParameter.ParameterName;
                    }

                    if (paramAttribute.IsTypeDefined)
                    {
                        sqlParameter.DbType = (DbType)paramAttribute.SqlDbType;
                    }

                    if (paramAttribute.IsSizeDefined)
                    {
                        sqlParameter.Size = paramAttribute.Size;
                    }

                    //if (paramAttribute.IsScaleDefined)
                    //	sqlParameter.Scale = paramAttribute.Scale;

                    //if (paramAttribute.IsPrecisionDefined)
                    //	sqlParameter..Precision = paramAttribute.Precision;

                    if (CompareTreatAsNullValues(paramAttribute.TreatAsNull, v, paramInfo.ParameterType))
                    {
                        v = DBNull.Value;
                    }
                }


                // parameter direction
                if (paramCustType == SWParameterType.SPReturnValue)
                {
                    sqlParameter.Direction = ParameterDirection.ReturnValue;
                    sqlParameter.DbType    = DbType.Int32;
                }
                else if (paramInfo.ParameterType.IsByRef)
                {
                    sqlParameter.Direction = paramInfo.IsOut ? ParameterDirection.Output : ParameterDirection.InputOutput;
                }
                else
                {
                    sqlParameter.Direction = ParameterDirection.Input;
                }

                // generate parts of InsertUpdate expresion
                #region generate parts of InsertUpdate expresion
                if (paramCustType == SWParameterType.Identity)
                {
                    if (sAutoincrementColumnName.Length > 0)
                    {
                        throw new SqlWrapperException("Only one identity parameter is possible");
                    }
                    sAutoincrementColumnName = paramName;
                    Type reftype = GetRefType(paramInfo.ParameterType);
                    if (reftype == null)
                    {
                        throw new SqlWrapperException("Identity parameter must be ByRef parameter");
                    }

                    // check default value
                    if (paramAttribute.TreatAsNull.ToString() == SWParameterAttribute.NullReturnValueToken)
                    {
                        if (Convert.ToInt64(v) <= 0)
                        {
                            v = DBNull.Value;
                        }
                    }
                }

                if (swCommandType == SWCommandType.InsertUpdate)
                {
                    string fieldName    = "[" + paramName + "]";
                    string cmdparamName = "@" + paramName;

                    if (paramCustType != SWParameterType.Identity)
                    {
                        sInsertPart1 = AddWithDelim(sInsertPart1, ", ", fieldName);
                        sInsertPart2 = AddWithDelim(sInsertPart2, ", ", cmdparamName);
                    }
                    if ((paramCustType == SWParameterType.Key) || (paramCustType == SWParameterType.Identity))
                    {
                        sUpdatePart2 = AddWithDelim(sUpdatePart2, " and ", fieldName + "=" + cmdparamName);
                    }
                    if (paramCustType != SWParameterType.Identity)
                    {
                        sUpdatePart1 = AddWithDelim(sUpdatePart1, ", ", fieldName + "=" + cmdparamName);
                    }
                }
                #endregion

                // set parameter name
                sqlParameter.ParameterName = "@" + paramName;


                // set parameter value
                if (v == null)
                {
                    v = DBNull.Value;
                }
                sqlParameter.Value = values[paramIndex];                // this is to set a proper data type
                sqlParameter.Value = v;

                // add parameter to the command object
                command.Parameters.Add(sqlParameter);
                indexes[paramIndex] = sqlParamIndex;
                sqlParamIndex++;
            }

            // in case of InsertUpdate command type compile new command text
            #region generate InsertUpdate expresion
            if (swCommandType == SWCommandType.InsertUpdate)
            {
                string TableName   = command.CommandText;
                string CommandText = "";

                if (sUpdatePart2 == "")
                {
                    throw new SqlWrapperException("No Identity or Autoincrement field is defined.");
                }

                sInsert = String.Format(" insert into [{0}]({1}) values({2}) ", TableName, sInsertPart1, sInsertPart2);
                sUpdate = String.Format(" update [{0}] set {1} where {2} ", TableName, sUpdatePart1, sUpdatePart2);

                if (sAutoincrementColumnName == "")
                {
                    CommandText += String.Format("{0} if (@@rowcount = 0) {1}", sUpdate, sInsert);
                }
                else
                {
                    CommandText += String.Format("if(@{0} is NULL) begin {1} select @{0} = SCOPE_IDENTITY() end ", sAutoincrementColumnName, sInsert);
                    CommandText += String.Format("else begin {0} end", sUpdate);
                }

                command.CommandText = CommandText;
            }
            #endregion
        }
示例#33
0
    private bool signatureIsCompatible(ParameterInfo[] lhs, ParameterInfo[] rhs)
    {
        if(lhs == null || rhs == null)
            return false;

        if(lhs.Length != rhs.Length)
            return false;

        for(int i = 0; i < lhs.Length; i++)
        {
            if(!areTypesCompatible(lhs[i], rhs[i]))
                return false;
        }

        return true;
    }
 internal static bool IsDecorateeParameter(ParameterInfo parameter, Type decoratingType) =>
 IsDecorateeDependencyType(parameter.ParameterType, decoratingType) ||
 IsDecorateeFactoryDependencyType(parameter.ParameterType, decoratingType);
示例#35
0
        public static LinkedMemberInfo Create(LinkedMemberHierarchy hierarchy, [CanBeNull] LinkedMemberInfo parent, ParameterInfo parameterInfo)
        {
            ParameterData memberData;

            if (!parameterPool.TryGet(out memberData))
            {
                memberData = new ParameterData();
            }
            var created = Create(hierarchy, memberData);

            created.Setup(parent, parameterInfo);
            return(created);
        }
示例#36
0
        public static TDelegate BuildDelegate <TDelegate>(string sourceFilePath, string fullFunctionName, Assembly[] assemblies)
            where TDelegate : class
        {
            FileInfo fileInfo = new FileInfo(sourceFilePath);

            if (!fileInfo.Exists)
            {
                throw new Error("source file name not found: {0}", sourceFilePath);
            }

            Type delegateType = typeof(TDelegate);

            Error.Valid(IsDelegate(delegateType), "BuildDelegate<FUNC_TYPE>(), FUNC_TYPE is not a delegate");
            MethodInfo delegateMethodInfo = GetDelegateMethodInfo(delegateType);


            ParameterInfo[] delegateParameterInfos = delegateMethodInfo.GetParameters();
            ParameterInfo   delegateReturnInfos    = delegateMethodInfo.ReturnParameter;

            Assembler assembler = new Assembler();

            assembler.AddSharpmakeAssemblies();
            assembler.Assemblies.AddRange(assemblies);

            Assembly assembly = assembler.BuildAssembly(fileInfo.FullName);

            List <MethodInfo> matchMethods = new List <MethodInfo>();

            foreach (Type type in assembly.GetTypes())
            {
                MethodInfo[] methodInfos = type.GetMethods();

                foreach (MethodInfo methodInfo in methodInfos)
                {
                    string fullName = methodInfo.DeclaringType.FullName + "." + methodInfo.Name;
                    if (fullFunctionName == fullName &&
                        methodInfo.IsStatic && methodInfo.GetParameters().Length == delegateMethodInfo.GetParameters().Length)
                    {
                        ParameterInfo[] parameterInfos = methodInfo.GetParameters();
                        ParameterInfo   returnInfos    = methodInfo.ReturnParameter;

                        bool equal = (returnInfos.GetType() == delegateReturnInfos.GetType() &&
                                      parameterInfos.Length == delegateParameterInfos.Length);

                        if (equal)
                        {
                            for (int i = 0; i < parameterInfos.Length; ++i)
                            {
                                if (parameterInfos[i].GetType() != delegateParameterInfos[i].GetType())
                                {
                                    equal = false;
                                    break;
                                }
                            }
                        }
                        if (equal)
                        {
                            matchMethods.Add(methodInfo);
                        }
                    }
                }
            }

            if (matchMethods.Count != 1)
            {
                throw new Error("Cannot find method name {0} that match {1} in {2}", fullFunctionName, delegateMethodInfo.ToString(), sourceFilePath);
            }

            MethodInfo method = matchMethods[0];

            // bind the method
            Delegate returnDelegate;

            try
            {
                returnDelegate = method.CreateDelegate(delegateType);
                InternalError.Valid(returnDelegate != null);
            }
            catch (Exception e)
            {
                throw new InternalError(e);
            }

            TDelegate result = returnDelegate as TDelegate;

            InternalError.Valid(result != null, "Cannot cast built delegate into user delegate");

            return(result);
        }
示例#37
0
 public PropertyInfo Process(PropertyInfo[] properties, ConstructorInfo ctor, ParameterInfo argument)
 => Array.Find
 (
     properties,
     property => property.Name.Equals(argument.Name, StringComparison.InvariantCultureIgnoreCase)
 );
示例#38
0
 static bool IsParams(ParameterInfo param)
 {
     return param.GetCustomAttributes(typeof(ParamArrayAttribute), false).Length > 0;
 }
示例#39
0
 public static IEnumerable <T> GetAllAttributes <T>(this ParameterInfo provider) where T : Attribute
 {
     return(provider.GetCustomAttributes(typeof(T), true).OfType <T>());
 }
示例#40
0
 public static Attribute GetCustomAttribute(ParameterInfo element, Type attributeType) => GetAttr(element, attributeType, true);
示例#41
0
 /// <summary>
 /// Gets the advices at parameter level.
 /// </summary>
 /// <param name="provider">The provider.</param>
 /// <returns></returns>
 private static IEnumerable <TAttribute> GetAttributes <TAttribute>(ParameterInfo provider)
 {
     return(provider.GetCustomAttributes(false).OfType <TAttribute>());
 }
示例#42
0
        public static T GetAttribute <T>(this ParameterInfo provider) where T : Attribute
        {
            var atts = provider.GetCustomAttributes(typeof(T), true);

            return(atts.FirstOrDefault() as T);
        }
示例#43
0
    static bool HasOptionalParam(ParameterInfo[] infos)
    {
        for (int i = 0; i < infos.Length; i++)
        {
            if (IsParams(infos[i]))
            {
                return true;
            }
        }

        return false;
    }
示例#44
0
 public static bool HasAttribute <T>(this ParameterInfo provider) where T : Attribute
 {
     return(provider.IsDefined(typeof(T), true));
 }
示例#45
0
    static int ProcessParams(MethodBase md, int tab, bool beConstruct, bool beCheckTypes = false)
    {
        ParameterInfo[] paramInfos = md.GetParameters();
        bool beExtend = IsExtendFunction(md);

        if (beExtend)
        {
            ParameterInfo[] pt = new ParameterInfo[paramInfos.Length - 1];
            Array.Copy(paramInfos, 1, pt, 0, pt.Length);
            paramInfos = pt;
        }

        int count = paramInfos.Length;
        string head = string.Empty;
        PropertyInfo pi = null;
        int methodType = GetMethodType(md, out pi);
        int offset = ((md.IsStatic && !beExtend )|| beConstruct) ? 1 : 2;

        if (md.Name == "op_Equality")
        {
            beCheckTypes = true;
        }

        for (int i = 0; i < tab; i++)
        {
            head += "\t";
        }

        if ((!md.IsStatic && !beConstruct) || beExtend)
        {
            if (md.Name == "Equals")
            {
                if (!type.IsValueType && !beCheckTypes)
                {
                    CheckObject(head, type, className, 1);
                }
                else
                {
                    sb.AppendFormat("{0}{1} obj = ({1})ToLua.ToObject(L, 1);\r\n", head, className);
                }
            }
            else if (!beCheckTypes)// && methodType == 0)
            {
                CheckObject(head, type, className, 1);
            }
            else
            {
                ToObject(head, type, className, 1);
            }
        }

        for (int j = 0; j < count; j++)
        {
            ParameterInfo param = paramInfos[j];
            string arg = "arg" + j;
            bool beOutArg = param.Attributes == ParameterAttributes.Out;
            bool beParams = IsParams(param);
            Type t = GetGenericBaseType(md, param.ParameterType);
            ProcessArg(t, head, arg, offset + j, beCheckTypes, beParams ,beOutArg);
        }

        StringBuilder sbArgs = new StringBuilder();
        List<string> refList = new List<string>();
        List<Type> refTypes = new List<Type>();

        for (int j = 0; j < count; j++)
        {
            ParameterInfo param = paramInfos[j];

            if (!param.ParameterType.IsByRef)
            {
                sbArgs.Append("arg");
            }
            else
            {
                if (param.Attributes == ParameterAttributes.Out)
                {
                    sbArgs.Append("out arg");
                }
                else
                {
                    sbArgs.Append("ref arg");
                }

                refList.Add("arg" + j);
                refTypes.Add(GetRefBaseType(param.ParameterType));
            }

            sbArgs.Append(j);

            if (j != count - 1)
            {
                sbArgs.Append(", ");
            }
        }

        if (beConstruct)
        {
            sb.AppendFormat("{2}{0} obj = new {0}({1});\r\n", className, sbArgs.ToString(), head);
            string str = GetPushFunction(type);
            sb.AppendFormat("{0}ToLua.{1}(L, obj);\r\n", head, str);

            for (int i = 0; i < refList.Count; i++)
            {
                GenPushStr(refTypes[i], refList[i], head);
            }

            return refList.Count + 1;
        }

        string obj = (md.IsStatic && !beExtend) ? className : "obj";
        MethodInfo m = md as MethodInfo;

        if (m.ReturnType == typeof(void))
        {
            if (md.Name == "set_Item")
            {
                if (methodType == 2)
                {
                    string str = sbArgs.ToString();
                    string[] ss = str.Split(',');
                    str = string.Join(",", ss, 0, ss.Length - 1);

                    sb.AppendFormat("{0}{1}[{2}] ={3};\r\n", head, obj, str, ss[ss.Length - 1]);
                }
                else if (methodType == 1)
                {
                    sb.AppendFormat("{0}{1}.Item = arg0;\r\n", head, obj, pi.Name);
                }
                else
                {
                    sb.AppendFormat("{0}{1}.{2}({3});\r\n", head, obj, md.Name, sbArgs.ToString());
                }
            }
            else if (methodType == 1)
            {
                sb.AppendFormat("{0}{1}.{2} = arg0;\r\n", head, obj, pi.Name);
            }
            else
            {
                sb.AppendFormat("{3}{0}.{1}({2});\r\n", obj, md.Name, sbArgs.ToString(), head);
            }
        }
        else
        {
            Type retType = GetGenericBaseType(md, m.ReturnType);
            string ret = GetTypeStr(retType);

            if (md.Name.StartsWith("op_"))
            {
                CallOpFunction(md.Name, tab, ret);
            }
            else if (md.Name == "get_Item")
            {
                if (methodType == 2)
                {
                    sb.AppendFormat("{0}{1} o = {2}[{3}];\r\n", head, ret, obj, sbArgs.ToString());
                }
                else if (methodType == 1)
                {
                    sb.AppendFormat("{0}{1} o = {2}.Item;\r\n", head, ret, obj);
                }
                else
                {
                    sb.AppendFormat("{0}{1} o = {2}.{3}({4});\r\n", head, ret, obj, md.Name, sbArgs.ToString());
                }
            }
            else if (md.Name == "Equals")
            {
                if (type.IsValueType)
                {
                    sb.AppendFormat("{0}{1} o = obj.Equals({2});\r\n", head, ret, sbArgs.ToString());
                }
                else
                {
                    sb.AppendFormat("{0}{1} o = obj != null ? obj.Equals({2}) : arg0 == null;\r\n", head, ret, sbArgs.ToString());
                }
            }
            else if (methodType == 1)
            {
                sb.AppendFormat("{0}{1} o = {2}.{3};\r\n", head, ret, obj, pi.Name);
            }
            else
            {
                sb.AppendFormat("{0}{1} o = {2}.{3}({4});\r\n", head, ret, obj, md.Name, sbArgs.ToString());
            }

            bool isbuffer = IsByteBuffer(m);
            GenPushStr(m.ReturnType, "o", head, isbuffer);
        }

        for (int i = 0; i < refList.Count; i++)
        {
            GenPushStr(refTypes[i], refList[i], head);
        }

        if (!md.IsStatic && type.IsValueType && md.Name != "ToString")
        {
            sb.Append(head + "ToLua.SetBack(L, 1, obj);\r\n");
        }

        return refList.Count;
    }
示例#46
0
        private static object ResolveInvokeParameter(ParameterInfo param, Iterator <string> iter)
        {
            if (param.IsOptional && !iter.HasNext())
            {
                return(param.DefaultValue);
            }

            Type type = param.ParameterType;

            if (type == typeof(string[]))
            {
                List <string> values = new List <string>();
                while (iter.HasNext())
                {
                    values.Add(NextArg(iter));
                }
                return(values.ToArray());
            }

            if (type == typeof(string))
            {
                return(NextArg(iter));
            }

            if (type == typeof(float))
            {
                return(NextFloatArg(iter));
            }

            if (type == typeof(int))
            {
                return(NextIntArg(iter));
            }

            if (type == typeof(bool))
            {
                return(NextBoolArg(iter));
            }

            if (type == typeof(Vector2))
            {
                float x = NextFloatArg(iter);
                float y = NextFloatArg(iter);

                return(new Vector2(x, y));
            }

            if (type == typeof(Vector3))
            {
                float x = NextFloatArg(iter);
                float y = NextFloatArg(iter);
                float z = NextFloatArg(iter);

                return(new Vector3(x, y, z));
            }

            if (type == typeof(Vector4))
            {
                float x = NextFloatArg(iter);
                float y = NextFloatArg(iter);
                float z = NextFloatArg(iter);
                float w = NextFloatArg(iter);

                return(new Vector4(x, y, z, w));
            }

            if (type == typeof(int[]))
            {
                List <int> values = new List <int>();
                while (iter.HasNext())
                {
                    values.Add(NextIntArg(iter));
                }
                return(values.ToArray());
            }

            if (type == typeof(float[]))
            {
                List <float> values = new List <float>();
                while (iter.HasNext())
                {
                    values.Add(NextFloatArg(iter));
                }
                return(values.ToArray());
            }

            if (type == typeof(bool[]))
            {
                List <bool> values = new List <bool>();
                while (iter.HasNext())
                {
                    values.Add(NextBoolArg(iter));
                }
                return(values.ToArray());
            }

            throw new ReflectionException("Unsupported value type: " + type);
        }
示例#47
0
    private bool areTypesCompatible(ParameterInfo lhs, ParameterInfo rhs)
    {
        if(lhs.ParameterType.Equals(rhs.ParameterType))
            return true;

        if(lhs.ParameterType.IsAssignableFrom(rhs.ParameterType))
            return true;

        return false;
    }
示例#48
0
 public static Attribute GetCustomAttribute(ParameterInfo element, Type attributeType, bool inherit) => GetAttr(element, attributeType, inherit);
示例#49
0
    private Delegate createProxyEventDelegate(object target, Type delegateType, ParameterInfo[] eventParams, MethodInfo eventHandler)
    {
        var proxyMethod = typeof(AudioSubscription)
            .GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
            .Where(m =>
                m.IsDefined(typeof(ProxyEventAttribute), true ) &&
                signatureIsCompatible(eventParams, m.GetParameters())
            )
            .FirstOrDefault();

        if(proxyMethod == null)
            return null;

        handlerProxy = eventHandler;
        handlerParameters = eventHandler.GetParameters();

        var eventDelegate = Delegate.CreateDelegate( delegateType, this, proxyMethod, true );

        return eventDelegate;
    }
 public bool CanHandle(ParameterInfo parameter)
 => parameter.IsDefined(typeof(GlobalStateAttribute));