/// <summary> /// This demonstrates how to plug a query expression into an EntitySet. It prints all customers and the /// value of their purchases, filtering the purchases according to a specified predicate. /// </summary> static void QueryCustomers (Expression<Func<Purchase, bool>> purchasePredicate) { var data = new DemoData (); // We do two special things to make this query work: // (1) Call AsExpandable() on the Customer table // (2) Call Compile() on the supplied predicate when it's used within an EntitySet. // AsExpandable() returns a wrapper that strips away the call to Compile when the query is run. var query = from c in data.Customers.AsExpandable () where c.Purchases.Any (purchasePredicate.Compile ()) select new { c.Name, FilteredPurchases = from p in c.Purchases.Where (purchasePredicate.Compile ()) select p.Price }; foreach (var customerResult in query) { Console.WriteLine (customerResult.Name); foreach (decimal price in customerResult.FilteredPurchases) Console.WriteLine (" $" + price); } }
public List<Tool> GetTools(Expression<Func<Tool, bool>> predicate) { if(predicate != null) { var preComp = predicate.Compile(); predicate = o => preComp(o) && o.Active == true; return ausv1Context.Tools.Where(predicate.Compile()).ToList(); } return ausv1Context.Tools.Where(o => o.Active == true).ToList(); }
/// <summary> /// Задает значение свойству и сообщает о его изменении только если новое значение отличается. /// </summary> /// <typeparam name="TValue">Тип устанавливаемого значения</typeparam> /// <param name="propertyExpression">Лямбда для получения имени свойства</param> /// <param name="value">Устанавливаемое значение</param> /// <param name="callerMemberName">Имя свойства</param> /// <returns>Возвращает true если значение свойства было изменено</returns> protected bool SetProperty <TValue>(Expression <Func <TValue> > propertyExpression, TValue value, [CallerMemberName] string callerMemberName = null) { var func = propertyExpression.Compile(); var funcValue = func(); if (Equals(funcValue, value)) { return(false); } var propertyName = GetPropertyName(propertyExpression); var owner = GetContainer(propertyExpression); var ownerType = owner.GetType(); var fieldInfo = GetFieldRecursively(ownerType, propertyName); if (fieldInfo != null) { fieldInfo.SetValue(owner, value); OnPropertyChanged(callerMemberName); return(true); } var propertyInfo = ownerType.GetProperty(propertyName); if (propertyInfo != null) { propertyInfo.SetValue(owner, value); OnPropertyChanged(callerMemberName); return(true); } throw new NotSupportedException(propertyExpression.ToString()); }
public IEnumerable<User> Find(Expression<Func<User, bool>> where) { using (var db = new UserContext()) { return db.Users.Where(where.Compile()).ToArray(); } }
public static IObservable <TR> Bind <T, TR>(this T viewModel, System.Linq.Expressions.Expression <Func <T, TR> > outExpr, bool activate = false) where T : INotifyPropertyChanged { var expr = (System.Linq.Expressions.MemberExpression)outExpr.Body; var prop = (System.Reflection.PropertyInfo)expr.Member; var name = prop.Name; var comp = outExpr.Compile(); var ret = Observable.FromEventPattern <PropertyChangedEventHandler, PropertyChangedEventArgs>(t => viewModel.PropertyChanged += t, t => viewModel.PropertyChanged -= t) .Where(x => string.Equals(x.EventArgs.PropertyName, name)) .Select(x => comp(viewModel)); if (!activate) { return(ret); } var o = Observable.Create <TR>(obs => { try { obs.OnNext(comp(viewModel)); } catch (Exception e) { obs.OnError(e); } obs.OnCompleted(); return(Disposable.Empty); }); return(o.Concat(ret)); }
private async Task TestFilter(Expression<Func<Order, bool>> predicate) { var table = Client.GetTable<Order>(); var items = await table.Where(predicate).OrderBy(o => o.Id).ToListAsync(); var expected = Orders.Where(predicate.Compile()).OrderBy(o => o.Id).ToArray(); ComparisonHelper.CompareAssert(expected, items); }
public static void CheckExpression(Expression<Func<Boolean>> expression) { if (!expression.Compile()()) { throw new MalformedException(string.Concat("Bad file format, expecting ", expression.ToString().Replace("() => ", string.Empty))); } }
public static T Eval <T>(this Expression expression) { Expression <Func <T> > lamda = Expression.Lambda <Func <T> >(expression); T result = lamda.Compile()(); return(result); }
public static void Bind <T, TR>(this T viewModel, System.Linq.Expressions.Expression <Func <T, TR> > outExpr, Action <TR> b, bool activateNow = false) where T : INotifyPropertyChanged { var expr = (System.Linq.Expressions.MemberExpression)outExpr.Body; var prop = (System.Reflection.PropertyInfo)expr.Member; var name = prop.Name; var comp = outExpr.Compile(); viewModel.PropertyChanged += (sender, e) => { if (e.PropertyName.Equals(name)) { try { b(comp(viewModel)); } catch (Exception ex) { Console.WriteLine(ex); } } }; if (activateNow) { try { b(comp(viewModel)); } catch (Exception ex) { Console.WriteLine(ex); } } }
public static void BindCollection <T>(this T viewModel, System.Linq.Expressions.Expression <Func <T, INotifyCollectionChanged> > outExpr, Action <NotifyCollectionChangedEventArgs> b, bool activateNow = false) where T : INotifyPropertyChanged { var exp = outExpr.Compile(); var m = exp(viewModel); m.CollectionChanged += (sender, e) => { try { b(e); } catch (Exception ex) { Console.WriteLine(ex); } }; if (activateNow) { try { b(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } catch (Exception ex) { Console.WriteLine(ex); } } }
static void Main() { System.Linq.Expressions.Expression <Action> expression = () => #endif ( from currentTest in Enumerable.Range(0, Convert.ToInt32(Console.ReadLine())) let numberOfVertexAndEdges = Console.ReadLine().Split() let numberOfVertex = Convert.ToInt32(numberOfVertexAndEdges[0]) let numberOfEdges = Convert.ToInt32(numberOfVertexAndEdges[1]) select ( from e in Enumerable.Range(0, numberOfEdges) let edge = Console.ReadLine().Split() let firstVertex = Convert.ToInt32(edge[0]) - 1 let secondVertex = Convert.ToInt32(edge[1]) - 1 select new { firstVertex, secondVertex } ).Aggregate(Enumerable.Range(0, numberOfVertex).ToArray(), (comp, newEdge) => ( from v in comp select v == comp[newEdge.firstVertex] ? Math.Min(v, comp[newEdge.secondVertex]) : v == comp[newEdge.secondVertex] ? Math.Min(v, comp[newEdge.firstVertex]) : v ).ToArray() ).ToList().Distinct().Count() ).ToList().ForEach(result => Console.WriteLine(result)) #if !SATORI ; expression.Compile().Invoke(); }
private void AssertJiraHttpLink(Expression<Func<IHttpInterfaceConfiguration, string>> configPropertyAccessor) { IHttpInterfaceConfiguration httpConfig = JiraConfig.Instance.HttpInterfaceConfiguration; Assert.AreEqual( ExpectedUrlFrom(configPropertyAccessor), configPropertyAccessor.Compile().Invoke(httpConfig)); }
private void EntryTokenizeFormats(string token, Func<string[],string[]> tokenizer, Expression<Func<string[]>> expression) { var key = ExpressionHelper.GetExpressionText(expression); var formats = tokenizer(expression.Compile().Invoke().ToArray()); TokenizeFormats[token + ":" + key] = formats; }
public static Vector GradientDescent( Expression<Func<Vector, double>> function, Expression<Func<Vector, Vector>> gradient, Vector x0, int iter, double stepSize, out Vector trajectory) { trajectory = Vector.Zeros(iter); var x = x0; var obj = double.MaxValue; var f = function.Compile(); var g = gradient.Compile(); for (int i = 0; i < iter; i++) { // calculate gradient var grad = g(x); // get step size (avoid overstepping) var eta = stepSize / System.Math.Sqrt(iter + 1); // take step x = x - eta * grad; // calculate objective trajectory[i] = f(x); // sanity check (don't want to take too many steps) if (System.Math.Abs(obj - trajectory[i]) < MIN_DIFF) break; // start again obj = trajectory[i]; } return x; }
public static void AddRequestProperty(Expression<Func<HttpRequestBase, object>> expression) { var property = ReflectionHelper.GetProperty(expression); _systemProperties.Add(property); _requestProperties[property.Name] = expression.Compile(); }
protected internal virtual string GetFriendlyName(Type type, Expression<Func<Type, string>> nameFunctionExpression) { if(type == null) throw new ArgumentNullException("type"); if(nameFunctionExpression == null) throw new ArgumentNullException("nameFunctionExpression"); if(type.IsGenericParameter) return type.Name; var name = nameFunctionExpression.Compile().Invoke(type); if(!type.IsGenericType) return name; name = name.Substring(0, name.IndexOf("`", StringComparison.OrdinalIgnoreCase)); var genericArgumentFriendlyName = string.Empty; foreach(var genericArgument in type.GetGenericArguments()) { if(!string.IsNullOrEmpty(genericArgumentFriendlyName)) genericArgumentFriendlyName += ", "; genericArgumentFriendlyName += this.GetFriendlyName(genericArgument, nameFunctionExpression); } return string.Format(CultureInfo.InvariantCulture, "{0}<{1}>", name, genericArgumentFriendlyName); }
private static Func <object, object, object> CreateFunc(string program) { var assemblyName = new AssemblyName(Guid.NewGuid().ToString()) { Version = new Version(1, 0) }; AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Program"); ParameterExpression valueParameter = Expression.Parameter(typeof(object), "value"); ParameterExpression parameterParameter = Expression.Parameter(typeof(object), "parameter"); AstHelper astHelper = AstHelper.Default(moduleBuilder); astHelper.Variables.Add("value", valueParameter); astHelper.Variables.Add("parameter", parameterParameter); Expression rootExpression = ProgramExpression.Compile(astHelper, program); Expression <Func <object, object, object> > lambda = Expression.Lambda <Func <object, object, object> >(Expression.Convert(rootExpression, typeof(object)), valueParameter, parameterParameter); return(lambda.Compile()); }
public static void NotNullOrEmpty(Expression<Func<string>> expr) { if (!string.IsNullOrEmpty(expr.Compile()())) return; var param = (MemberExpression)expr.Body; throw new ArgumentNullException("The parameter '" + param.Member.Name + "' cannot be null or empty."); }
public RouteTarget(Expression<Func<IServiceLocator, object>> controllerExpr) { _controllerExpr = controllerExpr; _controllerFunc = _controllerExpr.Compile(); ControllerType = ((_controllerExpr.Body as MethodCallExpression)?.Arguments?[0] as ConstantExpression)?.Value as Type; }
public void AddHttpMethodFilter(Expression<Func<ActionCall, bool>> filter, string method) { _httpMethodFilters.Add(new HttpMethodFilter{ Filter = filter.Compile(), Description = filter.Body.ToString(), Method = method }); }
private static void DoAction(Expression<Action> action) { Console.Write("Executing {0} ... ", action.Body.ToString()); var act = action.Compile(); act.Invoke(); Console.WriteLine(); }
private Action<FunctionContext> CompileTree(Expression<Action<FunctionContext>> lambda) { if (this.CompileInterpretDecision == CompileInterpretChoice.AlwaysCompile) { return lambda.Compile(); } int compilationThreshold = (this.CompileInterpretDecision == CompileInterpretChoice.NeverCompile) ? 0x7fffffff : -1; return (Action<FunctionContext>) new LightCompiler(compilationThreshold).CompileTop(lambda).CreateDelegate(); }
public IEnumerable<Call> FindCalls(Expression<Func<CallInput, bool>> filter) { if (filter == null) { throw new ArgumentNullException("filter"); } var predicate = filter.Compile(); return from call in _calls where predicate.Invoke(call.Input) select call; }
private static void ArgumentIsTrueOrFalse(Expression<Func<bool>> expression, bool throwCondition, string exceptionMessage) { ArgumentNotNull(expression, nameof(expression)); if (expression.Compile().Invoke() == throwCondition) { var paramName = expression.GetMemberName(); throw new ArgumentException(exceptionMessage, paramName); } }
public void Property_ReturnsTheValueForTheSpecificCityType(ICity city, Expression<Func<ICity, int>> property, int expectedValue) { // :::: ACT :::: var actualValue = property.Compile().Invoke(city); // :::: ASSERT :::: actualValue.Should().Be(expectedValue); }
private static Action BuildAction(Expression<Func<bool>> spec) { return () => { if (!spec.Compile()()) { throw new AssertionException("Failed:" + SpecDescriber.DescribeSpec(spec)); } }; }
public static void Assert(Expression<Func<bool>> assertion) { Func<bool> compiled = assertion.Compile(); bool evaluatedValue = compiled(); if (!evaluatedValue) { throw new InvalidOperationException( string.Format("'{0}' is not met.", Normalize(assertion.ToString()))); } }
public static IObservable <Unit> BindCollection <T>(this T viewModel, System.Linq.Expressions.Expression <Func <T, INotifyCollectionChanged> > outExpr, bool activate = false) where T : INotifyPropertyChanged { var exp = outExpr.Compile(); var m = exp(viewModel); var ret = Observable.FromEventPattern <NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>(t => m.CollectionChanged += t, t => m.CollectionChanged -= t) .Select(_ => Unit.Default); return(activate ? ret.StartWith(Unit.Default) : ret); }
public void setName(string name,Expression<Func<string,bool>> exp) { if (name == "leo") { var func=exp.Compile(); if (func(name)) { System.Console.WriteLine(name); } } }
public IEnumerable<DalRole> GetByPredicate(Expression<Func<DalRole, bool>> f) { Func<DalRole, bool> func = f.Compile(); IEnumerable<DalRole> users = context.Set<Roles>().Where(u => true).AsEnumerable().Select(role => new DalRole() { Id = role.id, Name = role.Name }).AsEnumerable(); List<DalRole> result = users.Where(user => func(user)).ToList(); return result; }
public void False(Expression<Func<bool>> matchFunc) { this.commandProvider.Act(() => { var compiledFunc = matchFunc.Compile(); if (compiledFunc()) { throw new FluentExpectFailedException("Expected expression [{0}] to return false.", matchFunc.ToExpressionString()); } }); }
public virtual MetadataDefinitionGroupProjection WithTracking(Expression<Func<TrackingBase, Func<TrackingBase>>> tb) { SetUpdated(); return new MetadataDefinitionGroupProjection { Description = Description, Identity = Identity, Name = Name, Tracking = tb.Compile().Invoke(Tracking).Invoke() }; }
protected void given_remote_resource(string uri, Expression<Func<IClientRequest, IClientResponse>> handler) { Client.Resources[uri.ToUri()] = new MemoryResource { Operations = { { handler.Parameters[0].Name, handler.Compile() } } }; }
public DelegateCommand(Action<object> executeMethod, Expression<Func<object, bool>> canExecuteMethod) { _executeWithParameterMethod = executeMethod; if (canExecuteMethod == null) { _canExecuteWithParameterMethod = ((obj) => true); } else { _canExecuteWithParameterMethod = canExecuteMethod.Compile(); } }
public static void That(Expression<Func<bool>> assertion, string msg = null) { var compiled = assertion.Compile(); bool ok = false; try { ok = compiled(); } catch (Exception e) { throw Err(assertion, msg ?? "failed with exception", e); } if (!ok) throw Err(assertion, msg ?? "failed", null); }
public ReusableValidator(Expression<Func<string>> property) { var lambda = property as LambdaExpression; var member = lambda.Body as MemberExpression; PropertyName = member.Member.Name; Check = () => { var value = property.Compile().Invoke(); return blacklistedWords.Any(x => (value ?? string.Empty).ToUpperInvariant().Contains(x.ToUpperInvariant())); }; }
public Task<dynamic> VerifyCredentials(Expression<Func<VerifyCredentials, VerifyCredentials>> request = null) { var verifyCredentials = new VerifyCredentials(AccessToken, AccessTokenSecret, ConsumerKey, ConsumerSecret); // if request was specified process it if (request != null) { Func<VerifyCredentials, VerifyCredentials> func = request.Compile(); verifyCredentials = func.Invoke(verifyCredentials); } Task<dynamic> result = TwitterEngine.MakeRequest(verifyCredentials); return result; }
public Task<dynamic> CreateTweet(String status, Expression<Func<CreateTweet, CreateTweet>> request = null) { var update = new CreateTweet(status, AccessToken, AccessTokenSecret, ConsumerKey, ConsumerSecret); // if request was specified process it if (request != null) { Func<CreateTweet, CreateTweet> func = request.Compile(); update = func.Invoke(update); } Task<dynamic> result = TwitterEngine.MakeRequest(update); return result; }
public static IObservable <TR> Bind <T, TR>(this T viewModel, System.Linq.Expressions.Expression <Func <T, TR> > outExpr, bool activate = false) where T : INotifyPropertyChanged { var expr = (System.Linq.Expressions.MemberExpression)outExpr.Body; var prop = (System.Reflection.PropertyInfo)expr.Member; var name = prop.Name; var comp = outExpr.Compile(); var ret = Observable.FromEventPattern <PropertyChangedEventHandler, PropertyChangedEventArgs>(t => viewModel.PropertyChanged += t, t => viewModel.PropertyChanged -= t) .Where(x => string.Equals(x.EventArgs.PropertyName, name)) .Select(x => comp(viewModel)); return(activate ? ret.StartWith(comp(viewModel)) : ret); }
public void test_block_return_its_last_value() { // this test demostrates that only one of the blocks in the // path to the root should reference each variable used in the // child nodes. If one block below references the same variable // then it's not the same variable. ParameterExpression x = Expression.Parameter(typeof(int)); ParameterExpression y = Expression.Parameter(typeof(int)); BlockExpression expression = Expression.Block(new[] { x, y }, Expression.Block( Expression.Assign(x, Expression.Constant(1)), Expression.Block(Expression.Assign(y, x), y))); Expression <Func <int> > lamda = Expression.Lambda <Func <int> >(expression); int result = lamda.Compile()(); Assert.AreEqual(1, result); }
private static Func <TIn, TOut> GetFunc() { ParameterExpression parameterExpression = Expression.Parameter(typeof(TIn), "p"); List <MemberBinding> memberBindingList = new List <MemberBinding>(); foreach (var item in typeof(TOut).GetProperties()) { if (!item.CanWrite) { continue; } MemberExpression property = Expression.Property(parameterExpression, typeof(TIn).GetProperty(item.Name)); MemberBinding memberBinding = Expression.Bind(item, property); memberBindingList.Add(memberBinding); } MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList.ToArray()); Expression <Func <TIn, TOut> > lambda = Expression.Lambda <Func <TIn, TOut> >(memberInitExpression, new ParameterExpression[] { parameterExpression }); return(lambda.Compile()); }