private Delegate ConstructOperation(string defaultValueCodeSnippet)
        {
            if (defaultValueCodeSnippet.IsNullOrWhiteSpace())
            {
                return(null);
            }

            int opi = defaultValueCodeSnippet.IndexOf("=>");

            if (opi < 0)
            {
                return(null);
            }

            string           param  = defaultValueCodeSnippet.Substring(0, opi).NTrim();
            string           body   = defaultValueCodeSnippet.Substring(opi + 2).NTrim();
            LambdaExpression lambda = DynamicExpression.ParseLambda(typeof(object), body);

            return(lambda.Compile());
        }
示例#2
0
        /// <summary>
        /// Sets length validation rule(s) to string properties according to appropriate database model
        /// </summary>
        /// <typeparam name="TObject">Object type</typeparam>
        /// <param name="dbContext">Database context</param>
        /// <param name="filterPropertyNames">Properties to skip</param>
        protected virtual void SetStringPropertiesMaxLength <TObject>(IDbContext dbContext, params string[] filterPropertyNames)
        {
            if (dbContext == null)
            {
                return;
            }

            var dbObjectType = typeof(TObject);

            var names = typeof(T).GetProperties()
                        .Where(p => p.PropertyType == typeof(string) && !filterPropertyNames.Contains(p.Name))
                        .Select(p => p.Name).ToArray();

            var maxLength  = dbContext.GetColumnsMaxLength(dbObjectType.Name, names);
            var expression = maxLength.Keys.ToDictionary(name => name, name => DynamicExpression.ParseLambda <T, string>(name, null));

            foreach (var expr in expression)
            {
                RuleFor(expr.Value).Length(0, maxLength[expr.Key]);
            }
        }
示例#3
0
        protected virtual void SetDecimalMaxValue <TObject>(IDbContext dbContext)
        {
            if (dbContext == null)
            {
                return;
            }

            var dbObjectType = typeof(TObject);

            var names = typeof(T).GetProperties()
                        .Where(p => p.PropertyType == typeof(decimal))
                        .Select(p => p.Name).ToArray();

            var maxValues  = dbContext.GetDecimalMaxValue(dbObjectType.Name, names);
            var expression = maxValues.Keys.ToDictionary(name => name, name => DynamicExpression.ParseLambda <T, decimal>(name, null));

            foreach (var expr in expression)
            {
                RuleFor(expr.Value).IsDecimal(maxValues[expr.Key]).WithMessage(string.Format("The value is out of range. Maximum value is {0}.99", maxValues[expr.Key] - 1));
            }
        }
        public void ParseLambda_NewArrayInit()
        {
            DateTime dt = DateTime.Now;

            var expr = DynamicExpression.ParseLambda(
                typeof(Func <DateTime, object[]>),
                new []
            {
                Expression.Parameter(typeof(DateTime), "dt")
            },
                null,
                "array(dt.Year, dt.Month, 15, \"ala ma kota\", dt.Ticks, dt.Date.Ticks)"
                );


            Assert.AreEqual(typeof(object[]), expr.ReturnType);
            Assert.AreEqual(typeof(Func <DateTime, object[]>), expr.Type);
            var texpr = (Expression <Func <DateTime, object[]> >)expr;
            var fun   = texpr.Compile();
            var res   = fun(dt);
        }
示例#5
0
        public static string Eval(string input, string[,] customTags)
        {
            int end = input.IndexOf('}');

            if (end != input.Length - 1)
            {
                return(input);
            }
            else
            {
                string expression = input.Substring(1, end - 1);
                var    parameters = new List <ParameterExpression>();
//				var x = Expression.Parameter(typeof(int), "x");
//				parameters.Add(x);
                string stringExpression = "(" + expression + ").ToString()";
                var    e = DynamicExpression.ParseLambda(parameters.ToArray(), typeof(string),
                                                         stringExpression, null);
                Delegate function = e.Compile();
                return((string)function.DynamicInvoke());
            }
        }
示例#6
0
        protected virtual void MaksimumDecimalDeğeriAyarla <TObject>(IDbContext dbContext)
        {
            if (dbContext == null)
            {
                return;
            }

            var dbObjectType = typeof(TObject);

            var names = typeof(T).GetProperties()
                        .Where(p => p.PropertyType == typeof(decimal))
                        .Select(p => p.Name).ToArray();

            var maxValues  = dbContext.GetDecimalMaxValue(dbObjectType.Name, names);
            var expression = maxValues.Keys.ToDictionary(name => name, name => DynamicExpression.ParseLambda <T, decimal>(name, null));

            foreach (var expr in expression)
            {
                RuleFor(expr.Value).Decimal(maxValues[expr.Key]).WithMessage(string.Format("Değer aralık dışında. Maksimum değer {0} .99'dır.", maxValues[expr.Key] - 1));
            }
        }
示例#7
0
        private Delegate ConstructOperation(object value, Type targetType)
        {
            if (_defaultValueCodeSnippet.IsNullOrEmpty())
            {
                return(null);
            }

            int opi = this._defaultValueCodeSnippet.IndexOf("=>");

            if (opi < 0)
            {
                return(null);         // throw new Exception("No lambda operator =>");
            }
            string param          = this._defaultValueCodeSnippet.Substring(0, opi).NTrim();
            string body           = this._defaultValueCodeSnippet.Substring(opi + 2).NTrim();
            ParameterExpression p = Expression.Parameter(
                value.GetType(), param);
            LambdaExpression lambda = DynamicExpression.ParseLambda(
                new ParameterExpression[] { p }, targetType, body, value);

            return(lambda.Compile());
        }
        public void ParseLambda_NewDictionary()
        {
            //this does not work - didnt figure oout how to make useful lambda with dictionary initialization
            DateTime dt = DateTime.Now;

            var expr = DynamicExpression.ParseLambda(
                typeof(Func <DateTime, Dictionary <string, object> >),
                new[]
            {
                Expression.Parameter(typeof(DateTime), "dt")
            },
                typeof(Dictionary <string, object>),
                "dictionary(dt.Year as y, dt.Month as m, 15 as fifteen, \"ala ma kota\" as text, dt.Ticks, dt.Date.Ticks as rounded_ticks)"
                );


            Assert.AreEqual(typeof(Dictionary <string, object>), expr.ReturnType);
            Assert.AreEqual(typeof(Func <DateTime, Dictionary <string, object> >), expr.Type);
            var texpr = (Expression <Func <DateTime, Dictionary <string, object> > >)expr;
            var fun   = texpr.Compile();
            var res   = fun(dt);
        }
        public static dynamic GroupByMany <TElement>(this IEnumerable <TElement> elements,
                                                     IEnumerable <Group> groupSelectors)
        {
            //create a new list of Kendo Group Selectors
            var selectors = new List <GroupSelector <TElement> >(groupSelectors.Count());

            foreach (var selector in groupSelectors)
            {
                //compile the Dynamic Expression Lambda for each one
                var expression =
                    DynamicExpression.ParseLambda(typeof(TElement), typeof(object), selector.Field);
                //add it to the list
                selectors.Add(new GroupSelector <TElement>
                {
                    Selector   = (Func <TElement, object>)expression.Compile(),
                    Field      = selector.Field,
                    Aggregates = selector.Aggregates
                });
            }
            //call the actual group by method
            return(elements.GroupByMany(selectors.ToArray()));
        }
示例#10
0
        private void btnDraw_Click(object sender, EventArgs e)
        {
            btnDraw.Enabled = false;
            var f = ((Expression <Func <double, double, double> >)
                     DynamicExpression.ParseLambda(
                         new[] { Expression.Parameter(typeof(double), "x"), Expression.Parameter(typeof(double), "y") },
                         typeof(double), tbFunction.Text)).Compile();

            Func <string, double> cd = x => Convert.ToDouble(x, CultureInfo.InvariantCulture);

            plotter.Scale  = cd(tbScale.Text);
            plotter.Step   = cd(tbStep.Text);
            plotter.FrontY = cd(tbFront.Text);
            plotter.BackY  = cd(tbBack.Text);

            var bmp = new Bitmap(pnPlot.Width, pnPlot.Height);

            using (var g = Graphics.FromImage(bmp))
                plotter.DrawSurface(f, pnPlot.Width, pnPlot.Height, g);
            pnPlot.Image    = bmp;
            btnDraw.Enabled = true;
        }
示例#11
0
        public static IQueryable GroupBy(this IQueryable source, string keySelector, string elementSelector, params object[] values)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (keySelector == null)
            {
                throw new ArgumentNullException("keySelector");
            }
            if (elementSelector == null)
            {
                throw new ArgumentNullException("elementSelector");
            }
            LambdaExpression keyLambda     = DynamicExpression.ParseLambda(source.ElementType, null, keySelector, values);
            LambdaExpression elementLambda = DynamicExpression.ParseLambda(source.ElementType, null, elementSelector, values);

            return(source.Provider.CreateQuery(
                       Expression.Call(
                           typeof(Queryable), "GroupBy",
                           new Type[] { source.ElementType, keyLambda.Body.Type, elementLambda.Body.Type },
                           source.Expression, Expression.Quote(keyLambda), Expression.Quote(elementLambda))));
        }
示例#12
0
        /// <summary>
        /// Sets max value validation rule(s) to decimal properties according to appropriate database model
        /// </summary>
        /// <typeparam name="TObject">Object type</typeparam>
        /// <param name="dbContext">Database context</param>
        protected virtual void SetDecimalMaxValue <TObject>(IDbContext dbContext)
        {
            var localizationService = EngineContext.Current.Resolve <ILocalizationService>();

            if (dbContext == null)
            {
                return;
            }

            var dbObjectType = typeof(TObject);

            var names = typeof(T).GetProperties()
                        .Where(p => p.PropertyType == typeof(decimal))
                        .Select(p => p.Name).ToArray();

            var maxValues  = dbContext.GetDecimalMaxValue(dbObjectType.Name, names);
            var expression = maxValues.Keys.ToDictionary(name => name, name => DynamicExpression.ParseLambda <T, decimal>(name, null));

            foreach (var expr in expression)
            {
                RuleFor(expr.Value).IsDecimal(maxValues[expr.Key]).WithMessage(string.Format(localizationService.GetResource("Nop.Web.Framework.Validators.MaxDecimal"), maxValues[expr.Key] - 1));
            }
        }
示例#13
0
 public override object GetProperty(Guid id, string propertyName)
 {
     try {
         PropertyInfo property = typeof(T).GetProperty(propertyName);
         if (property == null)
         {
             throw new ApplicationException("Property " + propertyName + " for " + typeof(T).Name + " could not be found, GetProperty failed.");
         }
         else
         {
             using (DataContext dataContext = DBLinqContext.CreateDBLinqDataContext(m_storageType, m_dbConnStr)) {
                 Table <T> table    = dataContext.GetTable <T>();
                 string    idString = id.ToString();
                 Expression <Func <T, Object> > mySelect = DynamicExpression.ParseLambda <T, Object>(property.Name);
                 var query = (from asset in table where asset.Id == idString select asset).Select(mySelect);
                 return(query.FirstOrDefault());
             }
         }
     }
     catch (Exception excp) {
         logger.Error("Exception DBLinqAssetPersistor GetProperty (for " + typeof(T).Name + "). " + excp.Message);
         throw;
     }
 }
        public List <SIPDialogueAsset> GetCalls(string whereExpression, int offset, int count)
        {
            try
            {
                Customer customer = AuthoriseRequest();

                string authorisedExpression = GetAuthorisedWhereExpression(customer, whereExpression);
                //logger.Debug("SIPProvisioningWebService GetCalls for " + customerSession.Customer.CustomerUsername + " and where: " + authoriseExpression + ".");

                if (authorisedExpression.IsNullOrBlank())
                {
                    return(SIPDialoguePersistor.Get(null, null, offset, count));
                }
                else
                {
                    return(SIPDialoguePersistor.Get(DynamicExpression.ParseLambda <SIPDialogueAsset, bool>(authorisedExpression), null, offset, count));
                }
            }
            catch (Exception excp)
            {
                logger.Error("Exception GetCalls. " + excp.Message);
                throw;
            }
        }
示例#15
0
 public void TestMethod1()
 {
     var expr = DynamicExpression.ParseLambda <double, double>("Math.Sin(@0)", 1.0);
     //Assert.AreEqual(typeof(int), expr.Type);
     //Assert.IsTrue(expr.NodeType == ExpressionType.Constant);
 }
示例#16
0
 public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
 {
     return (Expression<Func<T, bool>>)DynamicExpression.ParseLambda(typeof(T), typeof(bool), "@0(it) or @1(it)", first, second);
 }
        public static Type GetExpressionResultType(Type type, string propertyOrExpression)
        {
            LambdaExpression lambda = DynamicExpression.ParseLambda(type, null, propertyOrExpression, null);

            return(lambda.Body.Type);
        }
        public void TestParseCDRCountLambdaExpression()
        {
            var whereExpression = DynamicExpression.ParseLambda <SIPCDRAsset, bool>(@"Dst == ""123""");

            Assert.IsNotNull(whereExpression);
        }
示例#19
0
        /// <summary>
        /// 动态Linq方式实现行转列
        /// </summary>
        /// <param name="list">数据</param>
        /// <param name="DimensionList">维度列</param>
        /// <param name="DynamicColumn">动态列</param>
        /// <returns>行转列后数据</returns>
        public static List <dynamic> DynamicLinq <T>(List <T> list, List <string> DimensionList, string DynamicColumn, out List <string> AllDynamicColumn) where T : class
        {
            //获取所有动态列
            var           columnGroup   = list.GroupBy(DynamicColumn, "new(it as Vm)") as IEnumerable <IGrouping <dynamic, dynamic> >;
            List <string> AllColumnList = new List <string>();

            foreach (var item in columnGroup)
            {
                if (!string.IsNullOrEmpty(item.Key))
                {
                    AllColumnList.Add(item.Key);
                }
            }
            AllDynamicColumn = AllColumnList;
            var dictFunc = new Dictionary <string, Func <T, bool> >();

            foreach (var column in AllColumnList)
            {
                var func = DynamicExpression.ParseLambda <T, bool>(string.Format("{0}==\"{1}\"", DynamicColumn, column)).Compile();
                dictFunc[column] = func;
            }

            //获取实体所有属性
            Dictionary <string, PropertyInfo> PropertyInfoDict = new Dictionary <string, PropertyInfo>();
            Type type          = typeof(T);
            var  propertyInfos = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
            //数值列
            List <string> AllNumberField = new List <string>();

            foreach (var item in propertyInfos)
            {
                PropertyInfoDict[item.Name] = item;
                if (item.PropertyType == typeof(int) || item.PropertyType == typeof(double) || item.PropertyType == typeof(float))
                {
                    AllNumberField.Add(item.Name);
                }
            }

            //分组
            var            dataGroup             = list.GroupBy(string.Format("new ({0})", string.Join(",", DimensionList)), "new(it as Vm)") as IEnumerable <IGrouping <dynamic, dynamic> >;
            List <dynamic> listResult            = new List <dynamic>();
            IDictionary <string, object> itemObj = null;
            T vm2 = default(T);

            foreach (var group in dataGroup)
            {
                itemObj = new ExpandoObject();
                var listVm = group.Select(e => e.Vm as T).ToList();
                //维度列赋值
                vm2 = listVm.FirstOrDefault();
                foreach (var key in DimensionList)
                {
                    itemObj[key] = PropertyInfoDict[key].GetValue(vm2);
                }

                foreach (var column in AllColumnList)
                {
                    vm2 = listVm.FirstOrDefault(dictFunc[column]);
                    if (vm2 != null)
                    {
                        foreach (string name in AllNumberField)
                        {
                            itemObj[name + column] = PropertyInfoDict[name].GetValue(vm2);
                        }
                    }
                }
                listResult.Add(itemObj);
            }
            return(listResult);
        }
        public void TestParseLikeFromLambdaExpression()
        {
            var whereExpression = DynamicExpression.ParseLambda <SIPCDRAsset, bool>(@"FromHeader.Contains(""123"")");

            Assert.IsNotNull(whereExpression);
        }