/// <summary>Updates the property and raises the changed event, but only if the new value does not equal the old value. </summary> /// <typeparam name="TClass">The type of the class with the property. </typeparam> /// <typeparam name="TProp">The type of the property. </typeparam> /// <param name="propertyNameExpression">The property name as lambda. </param> /// <param name="oldValue">A reference to the backing field of the property. </param> /// <param name="newValue">The new value. </param> /// <returns>True if the property has changed. </returns> public bool Set <TClass, TProp>(Expression <Func <TClass, TProp> > propertyNameExpression, ref TProp oldValue, TProp newValue) { return(Set(ExpressionUtilities.GetPropertyName(propertyNameExpression), ref oldValue, newValue)); }
/// <summary>Raises the property changed event. </summary> /// <typeparam name="TClass">The type of the class with the property. </typeparam> /// <param name="propertyNameExpression">The property name as lambda. </param> public void RaisePropertyChanged <TClass>(Expression <Func <TClass, object> > propertyNameExpression) { RaisePropertyChanged(new PropertyChangedEventArgs(ExpressionUtilities.GetPropertyName(propertyNameExpression))); }
/// <summary>Loads a property for a given item. </summary> /// <typeparam name="T">The type of the item. </typeparam> /// <typeparam name="TProperty">The type of the property. </typeparam> /// <param name="item">The item. </param> /// <param name="propertyName">The name of the property to load. </param> /// <param name="reload">Specifies whether to use the cached version (if available) or always reload the item. </param> /// <param name="included">The navigation properties to include in the item (e.g. eager load using EF). </param> /// <returns>The task. </returns> public Task LoadPropertyForItemAsync <T, TProperty>(T item, Expression <Func <T, object> > propertyName, bool reload = true, params string[] included) where T : IEntity <TIdentity> where TProperty : IEntity <TIdentity> { return(LoadPropertyForItemAsync <T, TProperty>(item, ExpressionUtilities.GetPropertyName(propertyName), reload, included)); }
public bool SetProperty <T>(Expression <Func <T> > propertyNameExpression, ref T oldValue, T newValue) { return(Set(ExpressionUtilities.GetPropertyName(propertyNameExpression), ref oldValue, newValue)); }
public TConfig DependsOn <TOtherProperty>(Expression <Func <TOwner, TOtherProperty> > property, string error = null) { Triggers.Add(ExpressionUtilities.GetPropertyName(property)); return(this as TConfig); }
public void RaisePropertyChanged <TClass>(System.Linq.Expressions.Expression <Func <TClass, object> > propertyNameExpression) { this.RaisePropertyChanged(ViewModelBase.\u200B(ExpressionUtilities.GetPropertyName <TClass>(propertyNameExpression))); }
// create a pre-compiled VBValueExpression, and also provides expressin type back to the caller. //[SuppressMessage(FxCop.Category.Design, FxCop.Rule.AvoidOutParameters, // Justification = "Design has been approved")] public static Activity CreatePrecompiledVisualBasicReference(Type targetType, string expressionText, IEnumerable <string> namespaces, IEnumerable <string> referencedAssemblies, LocationReferenceEnvironment environment, out Type returnType, out SourceExpressionException compileError, out VisualBasicSettings vbSettings) { LambdaExpression lambda = null; var namespacesSet = new HashSet <string>(); var assembliesSet = new HashSet <AssemblyName>(); compileError = null; returnType = null; if (namespaces != null) { foreach (var ns in namespaces) { if (ns != null) { namespacesSet.Add(ns); } } } if (referencedAssemblies != null) { foreach (var assm in referencedAssemblies) { if (assm != null) { assembliesSet.Add(new AssemblyName(assm)); } } } var vbhelper = new VisualBasicHelper(expressionText, assembliesSet, namespacesSet); if (targetType == null) { try { lambda = vbhelper.CompileNonGeneric(environment); if (lambda != null) { // inspect the expressionTree to see if it is a valid location expression(L-value) string extraErrorMessage; if (!ExpressionUtilities.IsLocation(lambda, targetType, out extraErrorMessage)) { var errorMessage = SR.InvalidLValueExpression; if (extraErrorMessage != null) { errorMessage += ":" + extraErrorMessage; } throw FxTrace.Exception.AsError( new SourceExpressionException(SR.CompilerErrorSpecificExpression(expressionText, errorMessage))); } returnType = lambda.ReturnType; } } catch (SourceExpressionException e) { compileError = e; returnType = typeof(object); } targetType = returnType; } else { var genericCompileMethod = typeof(VisualBasicHelper).GetMethod("Compile", new Type[] { typeof(LocationReferenceEnvironment) }); genericCompileMethod = genericCompileMethod.MakeGenericMethod(new Type[] { targetType }); try { lambda = (LambdaExpression)genericCompileMethod.Invoke(vbhelper, new object[] { environment }); // inspect the expressionTree to see if it is a valid location expression(L-value) string extraErrorMessage = null; if (!ExpressionUtilities.IsLocation(lambda, targetType, out extraErrorMessage)) { var errorMessage = SR.InvalidLValueExpression; if (extraErrorMessage != null) { errorMessage += ":" + extraErrorMessage; } throw FxTrace.Exception.AsError( new SourceExpressionException(SR.CompilerErrorSpecificExpression(expressionText, errorMessage))); } returnType = targetType; } catch (SourceExpressionException e) { compileError = e; returnType = typeof(object); } catch (TargetInvocationException e) { var se = e.InnerException as SourceExpressionException; if (se != null) { compileError = se; returnType = typeof(object); } else { throw FxTrace.Exception.AsError(e.InnerException); } } } vbSettings = new VisualBasicSettings(); if (lambda != null) { var typeReferences = new HashSet <Type>(); FindTypeReferences(lambda.Body, typeReferences); foreach (var type in typeReferences) { var tassembly = type.Assembly; if (tassembly.IsDynamic) { continue; } var assemblyName = VisualBasicHelper.GetFastAssemblyName(tassembly).Name; var importReference = new VisualBasicImportReference { Assembly = assemblyName, Import = type.Namespace }; vbSettings.ImportReferences.Add(importReference); } } var concreteHelperType = VisualBasicExpressionFactoryType.MakeGenericType(targetType); var expressionFactory = (VisualBasicExpressionFactory)Activator.CreateInstance(concreteHelperType); return(expressionFactory.CreateVisualBasicReference(expressionText)); }
public object Evaluate(IBindingEnvironment environment) { object obj = null; // TODO refactor compare to Add, case sensitive? IsListVerb(this.name)? if (this.type == null) { if (this.name == "Add") { obj = ExpressionUtilities.ResolveToList(this.expression, environment); } else { obj = this.expression.Evaluate(environment); } } object[] parameters = null; if (this.arguments != null) { List <object> values = new List <object>(); foreach (IExpression argument in this.arguments) { object value = argument.Evaluate(environment); if (argument is VariableVariableExpression) { if (value != null) { foreach (object val in (IEnumerable)value) { values.Add(val); } } } else { values.Add(value); } } parameters = values.ToArray(); } if (this.type != null) { return(TypeUtilities.InvokeTypeMember(this.type, this.name, parameters)); } if (obj is Type) { return(TypeUtilities.InvokeTypeMember((Type)obj, this.name, parameters)); } // TODO if undefined, do nothing if (obj == null) { return(null); } return(ObjectUtilities.GetValue(obj, this.name, parameters)); }
/// <summary>Raises the property changed event with <see cref="GraphPropertyChangedEventArgs"/> arguments. </summary> /// <param name="oldValue">The old value. </param> /// <param name="newValue">The new value. </param> /// <typeparam name="TClass">The type of the class with the property. </typeparam> /// <param name="propertyNameExpression">The property name as lambda. </param> public void RaisePropertyChanged <TClass>(Expression <Func <TClass, object> > propertyNameExpression, object oldValue, object newValue) { RaisePropertyChanged(new GraphPropertyChangedEventArgs(ExpressionUtilities.GetPropertyName(propertyNameExpression), oldValue, newValue)); }
/// <summary> /// Don't call this method directly unless you wan't to force this process /// </summary> public virtual void ProcessUnhandledSimpleVars(Expression currentNode, bool considerInits = false) { if (UnhandledNodes.Count == 0) { return; } Expression initExpression = null; //filter the nodes for only the onces of interest to us Func <Expression, bool> filter = n => { switch (n.NodeType) { case ExpressionType.MemberAccess: case ExpressionType.TypeAs: case ExpressionType.Convert: case ExpressionType.ConvertChecked: case ExpressionType.Unbox: case ExpressionType.Call when n is MethodCallExpression callExpr && ( callExpr.Method.Name.StartsWith("_As") && (callExpr.Method.DeclaringType == Defaults.CypherFuncsType || callExpr.Method.DeclaringType == Defaults.CypherExtensionFuncsType) || //._As and ._AsList() callExpr.Method.Name == "Get" && callExpr.Method.DeclaringType == Defaults.VarsType || //CypherVariables.Get() callExpr.Method.IsEquivalentTo( Defaults .CypherObjectIndexerInfo) //CypherVariables.Get("")[""] //|| (callExpr.Method.Name == "_" && callExpr.Method.DeclaringType == Defaults.ObjectExtensionsType) //._() ): { return(true); } case ExpressionType.MemberInit: case ExpressionType.New: case ExpressionType.ListInit when n.Type.IsDictionaryType(): { if (considerInits && initExpression == null) { //we only need one type init initExpression = n; return(true); } return(false); } } return(false); }; //repeatFilter: var _unhandledNodes = UnhandledNodes .AsEnumerable() .Reverse() .TakeWhile(filter) .ToList(); if (_unhandledNodes.Count == 0) { return; } var hasMemberAccess = _unhandledNodes.Any(n => n.NodeType == ExpressionType.MemberAccess); JObject initJObject = null; JToken initJValue = null; var initExprIdx = -1; string builtValue = null; if (considerInits && initExpression != null) { //remove it from the list initExprIdx = _unhandledNodes.IndexOf(initExpression); if (initExprIdx >= 0) { _unhandledNodes.Remove(initExpression); } if (!hasMemberAccess) { try { var executedValue = initExpression.ExecuteExpression <object>(); if (executedValue is JToken token) { initJValue = token; } } catch { } } } if (initJValue == null) { var removeVariable = false; if (!Utils.Utilities.HasVars(_unhandledNodes)) { if (!hasMemberAccess) //!_unhandledNodes.Any(n => n.NodeType == ExpressionType.MemberAccess)) { return; //we need at least one memberaccess for this to work } //it doesn't have a vars get call, so add one var randomVar = "_fev_" + Utils.Utilities.GetRandomVariableFor("fevr"); //create a CypherVariables.Get call for this variable var varsGetCallExpr = ExpressionUtilities.GetVarsGetExpressionFor(randomVar, currentNode.Type); _unhandledNodes.Insert(0, varsGetCallExpr); //this is just going to be the header removeVariable = true; } builtValue = ExpressionUtilities.BuildSimpleVarsCall(_unhandledNodes, QueryContext, Context.UseResolvedJsonName); if (string.IsNullOrWhiteSpace(builtValue)) { //error throw new InvalidOperationException( string.Format(Messages.InvalidVariableExpressionError, _unhandledNodes.Last(), builtValue ?? "")); } if (removeVariable) { var dotIdx = builtValue.IndexOf("."); dotIdx = dotIdx > 0 ? dotIdx : builtValue.Length; if (dotIdx > 0) { builtValue = builtValue.Remove(0, dotIdx); } //remove the dummy vars get node added earlier _unhandledNodes.RemoveAt(0); } if (considerInits && initExpression != null && initJObject == null && initJValue == null) { //build the init independently //but first check if we have a cached value already if (!QueryContext.FuncsCachedJTokens.TryGetValue(initExpression, out var existingJToken) || !(existingJToken is JObject existingJObject)) { initJObject = CypherUtilities.GetFinalProperties (Expression.Lambda(initExpression), QueryContext, out var hasFuncsInProps); if (existingJToken == null) { //cache this for later use in same query QueryContext.FuncsCachedJTokens[initExpression] = initJObject; } } else { initJObject = existingJObject; } } if (initJObject != null && initJObject.Count > 0) { try { initJValue = initJObject.SelectToken($"$.{builtValue.Trim().TrimStart('.')}"); } catch (Exception e) { } } } if (considerInits && initJValue == null) { //we didn't get what we came here for return; } if (considerInits && initExprIdx >= 0) { //replace it _unhandledNodes.Insert(initExprIdx, initExpression); } if (initJValue != null) { WriteArgument(Expression.Constant(initJValue, initJValue.GetType()), _unhandledNodes.LastOrDefault()); } else { Builder.Append(builtValue, _unhandledNodes.LastOrDefault()); } foreach (var node in _unhandledNodes) { Handled(node); } }
public static Activity CreatePrecompiledVisualBasicReference(Type targetType, string expressionText, IEnumerable <string> namespaces, IEnumerable <string> referencedAssemblies, LocationReferenceEnvironment environment, out Type returnType, out SourceExpressionException compileError, out VisualBasicSettings vbSettings) { LambdaExpression expression = null; HashSet <string> namespaceImportsNames = new HashSet <string>(); HashSet <AssemblyName> refAssemNames = new HashSet <AssemblyName>(); compileError = null; returnType = null; if (namespaces != null) { foreach (string str in namespaces) { if (str != null) { namespaceImportsNames.Add(str); } } } if (referencedAssemblies != null) { foreach (string str2 in referencedAssemblies) { if (str2 != null) { refAssemNames.Add(new AssemblyName(str2)); } } } VisualBasicHelper helper = new VisualBasicHelper(expressionText, refAssemNames, namespaceImportsNames); if (targetType == null) { try { expression = helper.CompileNonGeneric(environment); if (expression != null) { string str3; if (!ExpressionUtilities.IsLocation(expression, targetType, out str3)) { string invalidLValueExpression = System.Activities.SR.InvalidLValueExpression; if (str3 != null) { invalidLValueExpression = invalidLValueExpression + ":" + str3; } throw FxTrace.Exception.AsError(new SourceExpressionException(System.Activities.SR.CompilerErrorSpecificExpression(expressionText, invalidLValueExpression))); } returnType = expression.ReturnType; } } catch (SourceExpressionException exception) { compileError = exception; returnType = typeof(object); } targetType = returnType; } else { MethodInfo info = typeof(VisualBasicHelper).GetMethod("Compile", new Type[] { typeof(LocationReferenceEnvironment) }).MakeGenericMethod(new Type[] { targetType }); try { expression = (LambdaExpression)info.Invoke(helper, new object[] { environment }); string extraErrorMessage = null; if (!ExpressionUtilities.IsLocation(expression, targetType, out extraErrorMessage)) { string str6 = System.Activities.SR.InvalidLValueExpression; if (extraErrorMessage != null) { str6 = str6 + ":" + extraErrorMessage; } throw FxTrace.Exception.AsError(new SourceExpressionException(System.Activities.SR.CompilerErrorSpecificExpression(expressionText, str6))); } returnType = targetType; } catch (SourceExpressionException exception2) { compileError = exception2; returnType = typeof(object); } catch (TargetInvocationException exception3) { SourceExpressionException innerException = exception3.InnerException as SourceExpressionException; if (innerException == null) { throw FxTrace.Exception.AsError(exception3.InnerException); } compileError = innerException; returnType = typeof(object); } } vbSettings = new VisualBasicSettings(); if (expression != null) { HashSet <Type> typeReferences = new HashSet <Type>(); FindTypeReferences(expression.Body, typeReferences); foreach (Type type in typeReferences) { Assembly assembly = type.Assembly; if (!assembly.IsDynamic) { string name = VisualBasicHelper.GetFastAssemblyName(assembly).Name; VisualBasicImportReference item = new VisualBasicImportReference { Assembly = name, Import = type.Namespace }; vbSettings.ImportReferences.Add(item); } } } VisualBasicExpressionFactory factory = (VisualBasicExpressionFactory)Activator.CreateInstance(VisualBasicExpressionFactoryType.MakeGenericType(new Type[] { targetType })); return(factory.CreateVisualBasicReference(expressionText)); }
/// <summary> /// Get decorator expression /// </summary> /// <param name="scope"></param> /// <param name="request"></param> /// <returns></returns> protected virtual IActivationExpressionResult InternalGetDecoratorActivationExpression(IInjectionScope scope, IActivationExpressionRequest request) { return(ExpressionUtilities.CreateExpressionForDelegate(_delegate, false, InjectionScope, request, this)); }
protected override Expression VisitBinary(BinaryExpression node) { if (RootNode == null && (node.NodeType == ExpressionType.AndAlso || node.NodeType == ExpressionType.Equal) && SourceParameter != null) { //most likely predictate RootNode = node; var isAnonymousType = SourceParameter.Type.IsAnonymousType(); var isDictionaryType = SourceParameter.Type.IsDictionaryType(); //SetUsePredicateOnly = true; //sort out predicate Expression predicateExpression = null; //split the binary expressions var predicateVisitor = new PredicateExpressionVisitor { MakeRightNodeReplacements = true, RightNodeReplacements = new Dictionary <Expression, Expression> { { SourceParameter, ExpressionUtilities.GetVarsGetExpressionFor(SourceParameter.Name, SourceParameter.Type) } } }; predicateVisitor.Visit(node); PredicateAssignments = predicateVisitor.Assignments; var predicateInfoDict = new Dictionary <EntityMemberInfo, Expression>(); foreach (var assignment in PredicateAssignments) { var keyExpr = assignment.Key; var valueExpr = assignment.Value.UncastBox(out var castRemoved); var retrieved = ExpressionUtilities.GetSimpleMemberAccessStretch (EntityService, keyExpr, out var valExpr); //build the entity member infos EntityMemberInfo currentMember = null; var currentType = valExpr.Type; var foundRoot = false; foreach (var item in retrieved) { if (item == valExpr) { foundRoot = true; continue; } if (!foundRoot) { continue; } if (item is MemberExpression memberExpression) { currentMember = new EntityMemberInfo(EntityService, memberExpression.Member, currentMember, !currentType.IsAnonymousType() ? currentType : null); } else if (isDictionaryType && item is MethodCallExpression methodCallExpr && methodCallExpr.Method is var methodInfo && !methodInfo.IsExtensionMethod() && methodCallExpr.Object is var methodObjectExpr && methodObjectExpr?.Type.IsDictionaryType() == true && methodObjectExpr.Type .GetProperties( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) .Where(p => p.GetIndexParameters().Any()) .Select(p => p.GetGetMethod()) .Contains(methodInfo)) { var dictKey = methodCallExpr.Arguments[0].ExecuteExpression <object>().ToString(); currentMember = new EntityMemberInfo(EntityService, dictKey, valueExpr.Type, currentMember); } else if (currentMember != null && currentMember.MemberFinalType.IsGenericAssignableFrom(item.Type)) { currentMember.MemberFinalType = item.Type; } currentType = currentMember?.MemberFinalType ?? item.Type; }
public static PropertyChangedCallback BindToViewModel <TViewModel>(Expression <Func <TViewModel, object> > property) { return(BindToViewModel(ExpressionUtilities.GetPropertyName(property))); }
public void Execute(IContext context) { object value = this.expression.Evaluate(context); ExpressionUtilities.SetValue(this.leftValue, value, context); }
private Expression <Func <ActivityContext, TResult> > CompileLocationExpression(CodeActivityPublicEnvironmentAccessor publicAccessor, out string validationError) { Expression <Func <ActivityContext, TResult> > expressionTreeToReturn = null; validationError = null; try { expressionTreeToReturn = VisualBasicHelper.Compile <TResult>(this.ExpressionText, publicAccessor, true); // inspect the expressionTree to see if it is a valid location expression(L-value) string extraErrorMessage = null; if (!publicAccessor.ActivityMetadata.HasViolations && (expressionTreeToReturn == null || !ExpressionUtilities.IsLocation(expressionTreeToReturn, typeof(TResult), out extraErrorMessage))) { string errorMessage = SR.InvalidLValueExpression; if (extraErrorMessage != null) { errorMessage += ":" + extraErrorMessage; } expressionTreeToReturn = null; validationError = SR.CompilerErrorSpecificExpression(this.ExpressionText, errorMessage); } } catch (SourceExpressionException e) { validationError = e.Message; } return(expressionTreeToReturn); }
/// <summary> /// Create expression that calls a delegate /// </summary> /// <param name="scope">scope for the request</param> /// <param name="request">activation request</param> /// <returns></returns> protected virtual IActivationExpressionResult CreateExpression(IInjectionScope scope, IActivationExpressionRequest request) { return(ExpressionUtilities.CreateExpressionForDelegate(DelegateInstance, ShouldTrackDisposable(scope), scope, request)); }