public static T GetValue <T>(object instance, string propPath) { Delegate runtimeDelegate; System.Linq.Expressions.ParameterExpression instanceParameter = System.Linq.Expressions.Expression.Parameter(instance.GetType(), "p"); string[] properties = propPath.Split('.'); System.Linq.Expressions.MemberExpression currentExpression = System.Linq.Expressions.Expression.PropertyOrField(instanceParameter, properties[0]); System.Linq.Expressions.LambdaExpression lambdaExpression = System.Linq.Expressions.Expression.Lambda(currentExpression, instanceParameter); for (int i = 1; i < properties.Length; i++) { currentExpression = System.Linq.Expressions.Expression.PropertyOrField(lambdaExpression.Body, properties[i]); lambdaExpression = System.Linq.Expressions.Expression.Lambda(currentExpression, instanceParameter); } runtimeDelegate = lambdaExpression.Compile(); return((T)runtimeDelegate.DynamicInvoke(instance)); }
/// <summary> /// Compile the string expression into a COExpression object. /// </summary> /// <param name="expression">The expression to compile.</param> /// <returns>Compiled COExpression object.</returns> public static COExpression <ClassificationObject> Compile <T>(String expression) where T : ClassificationObject { System.Linq.Expressions.LambdaExpression lambda = DynamicExpression.ParseLambda(typeof(T), typeof(bool), expression); return(ExpressionCasting <T> .ExpressionCast(lambda.Compile())); }
public static System.Func <T, TValue> GetGetter <T, TValue>(string fieldName) { System.Linq.Expressions.ParameterExpression p = System.Linq.Expressions.Expression.Parameter(typeof(T)); System.Linq.Expressions.MemberExpression prop = System.Linq.Expressions.Expression.PropertyOrField(p, fieldName); System.Linq.Expressions.UnaryExpression con = System.Linq.Expressions.Expression.Convert(prop, typeof(TValue)); System.Linq.Expressions.LambdaExpression exp = System.Linq.Expressions.Expression.Lambda(con, p); System.Func <T, TValue> getter = (System.Func <T, TValue>)exp.Compile(); return(getter); }
/// <summary> /// 条件返回 /// </summary> /// <returns></returns> public bool Condtion() { bool r = false; if (empty != null) { bool tmp = empty.Invoke(Statement.SqlContext.Context); r = !tmp;// } else { r = (bool)expression.Compile().DynamicInvoke(Statement.SqlContext.Context); } return(r); }
public static dynamic TryGetProperty(dynamic dynamicObject, String PropertyName, dynamic Default) { try { if (!HasProperty(dynamicObject, PropertyName)) { return(Default); } if (dynamicObject.GetType() == typeof(System.Web.Helpers.DynamicJsonObject)) { // good thing this type of documentation was easy to find System.Web.Helpers.DynamicJsonObject obj = (System.Web.Helpers.DynamicJsonObject)dynamicObject; Type scope = obj.GetType(); System.Dynamic.IDynamicMetaObjectProvider provider = obj as System.Dynamic.IDynamicMetaObjectProvider; if (provider != null) { System.Linq.Expressions.ParameterExpression param = System.Linq.Expressions.Expression.Parameter(typeof(object)); System.Dynamic.DynamicMetaObject mobj = provider.GetMetaObject(param); System.Dynamic.GetMemberBinder binder = (System.Dynamic.GetMemberBinder)Microsoft.CSharp.RuntimeBinder.Binder.GetMember(0, PropertyName, scope, new Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo[] { Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(0, null) }); System.Dynamic.DynamicMetaObject ret = mobj.BindGetMember(binder); System.Linq.Expressions.BlockExpression final = System.Linq.Expressions.Expression.Block( System.Linq.Expressions.Expression.Label(System.Runtime.CompilerServices.CallSiteBinder.UpdateLabel), ret.Expression ); System.Linq.Expressions.LambdaExpression lambda = System.Linq.Expressions.Expression.Lambda(final, param); Delegate del = lambda.Compile(); return(del.DynamicInvoke(obj)); } else { return(obj.GetType().GetProperty(PropertyName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).GetValue(obj, null)); } } else if (dynamicObject.GetType() == typeof(System.Collections.IDictionary)) { return((Dictionary <String, object>)dynamicObject[PropertyName]); } return(Default); } catch (Exception ex) { throw new Exception("Could not determine if dynamic object has property.", ex); } }
// NH-specific public static void AddAll(IList to, IList from) { System.Action addNull = null; foreach (object obj in from) { // There is bug in .NET, before version 4, where adding null to a List<Nullable<T>> through the non-generic IList interface throws an exception. // TODO: Everything but the to.Add(obj) should be conditionally compiled only for versions of .NET earlier than 4. if (obj == null) { if (addNull == null) { if (to.GetType().IsGenericType&& to.GetType().GetGenericTypeDefinition() == typeof(List <>) && to.GetType().GetGenericArguments()[0].IsGenericType && to.GetType().GetGenericArguments()[0].GetGenericTypeDefinition() == typeof(Nullable <>)) { MethodInfo addMethod = to.GetType().GetMethod("Add"); System.Linq.Expressions.MethodCallExpression addMethodCall = System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression.Constant(to), addMethod, System.Linq.Expressions.Expression.Constant(null, to.GetType().GetGenericArguments()[0])); System.Linq.Expressions.LambdaExpression addLambda = System.Linq.Expressions.Expression.Lambda(addMethodCall); addNull = (System.Action)addLambda.Compile(); } else { addNull = () => to.Add(null); } } addNull(); } else { to.Add(obj); } } }
public override DataTemplate SelectTemplate(object item, DependencyObject container) { if (ItemType.IsInstanceOfType(item)) { if (getPropertyValue == null) { System.Linq.Expressions.ParameterExpression instanceParameter = System.Linq.Expressions.Expression.Parameter(item.GetType(), "p"); System.Linq.Expressions.MemberExpression currentExpression = System.Linq.Expressions.Expression.PropertyOrField(instanceParameter, PropertyName); System.Linq.Expressions.LambdaExpression lambdaExpression = System.Linq.Expressions.Expression.Lambda(currentExpression, instanceParameter); getPropertyValue = lambdaExpression.Compile(); } return(SelectTemplateImpl(getPropertyValue.DynamicInvoke(item), container)); } return(base.SelectTemplate(item, container)); }
protected virtual ComparisonResult CompareStructural(QueryStructuralValue expected, object actual, string path, bool shouldThrow) { this.AddToLogBuffer("Verifying structural value. Path: {0}", path); if (actual == null) { if (expected.IsNull) { return(ComparisonResult.Success); } this.ThrowOrLogError(shouldThrow, "Expecting non-null value: {0} in '{1}. Got null instead.", expected, path); return(ComparisonResult.Failure); } if (expected.IsNull) { // if expected is null but actual is non-null this can be a result of the fact that entity was present in the ObjectStateManager and got attached even though // this particular query did not bring it back. if (this.LinqResultComparerContextAdapter.IsObjectTrackedByContext(actual)) { this.AddToLogBuffer("Verifying structural value. Path: {0} SKIPPED (Entity in Object State Manager)", path); return(ComparisonResult.Skipped); } else { this.ThrowOrLogError(shouldThrow, "Expecting null value in '{0}'. Actual: {1}[{2}].", path, actual, actual.GetType()); return(ComparisonResult.Failure); } } List <object> visited; if (!this.visitedEntities.TryGetValue(expected, out visited)) { visited = new List <object>(); this.visitedEntities.Add(expected, visited); } if (visited.Contains(actual)) { this.AddToLogBuffer("Verifying structural value. Path: {0} SKIPPED (Already visited)", path); return(ComparisonResult.Skipped); } visited.Add(actual); var expectedType = expected.Type as IQueryClrType; if (expectedType != null) { ExceptionUtilities.Assert(expectedType.ClrType != null, "Expecting non-null CLR type."); if (!expectedType.ClrType.IsAssignableFrom(actual.GetType())) { this.ThrowOrLogError(shouldThrow, "Types not match in {0}. Expecting: {1}. Actual: {2}.", path, expectedType.ClrType, actual.GetType()); return(ComparisonResult.Failure); } } bool comparisonSkippedForAnyProperty = false; var properties = actual.GetType().GetProperties(); IEnumerable <string> propertyNames = expected.MemberNames; #if WIN8 bool isAnonymousType = IsAnonymousType(actual.GetType()); int i = 0; #endif foreach (string expectedName in propertyNames) { #if WIN8 // In WIN8 we are using CSharpGenericTypeBuilder. Properties have fixed names such as Field1, Field2,... var actualProperty = isAnonymousType ? properties.ToArray()[i++] : properties.Where(p => p.Name == expectedName).SingleOrDefault(); #else var actualProperty = properties.Where(p => p.Name == expectedName).SingleOrDefault(); #endif if (actualProperty == null) { this.ThrowOrLogError(shouldThrow, "Expected property not found: {0} in '{1}'.", expectedName, path); return(ComparisonResult.Failure); } object actualValue = null; #if SILVERLIGHT CoreLinq.Expressions.ParameterExpression param = CoreLinq.Expressions.Expression.Parameter(typeof(Object), "param"); CoreLinq.Expressions.Expression convertedParam = CoreLinq.Expressions.Expression.Convert(param, actual.GetType()); CoreLinq.Expressions.LambdaExpression GetPropertyValueExp = CoreLinq.Expressions.Expression.Lambda(System.Linq.Expressions.Expression.Property(convertedParam, actualProperty), param); Delegate dynamicGetter = GetPropertyValueExp.Compile(); actualValue = dynamicGetter.DynamicInvoke(actual); #else actualValue = actualProperty.GetValue(actual, null); #endif QueryType expectedPropertyType = expected.Type.Properties.Where(p => p.Name == expectedName).Single().PropertyType; string newPath = path + "." + expectedName; var comparisonResult = this.CompareProperty(expected, expectedName, expectedPropertyType, actualValue, newPath, shouldThrow); if (comparisonResult == ComparisonResult.Failure) { visited.Remove(actual); return(ComparisonResult.Failure); } if (comparisonResult == ComparisonResult.Skipped) { comparisonSkippedForAnyProperty = true; } } if (comparisonSkippedForAnyProperty) { this.AddToLogBuffer("Verifying structural value. Path: {0} SKIPPED", path); return(ComparisonResult.Skipped); } else { this.AddToLogBuffer("Verifying structural value. Path: {0} SUCCESSFUL", path); return(ComparisonResult.Success); } }
internal static object GetAlgorithmFromConfig(string algorithm) { if (string.IsNullOrEmpty(algorithm)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(algorithm))); } object algorithmObject = null; object defaultObject = null; if (!s_algorithmDelegateDictionary.TryGetValue(algorithm, out Func <object> delegateFunction)) { lock (s_algorithmDictionaryLock) { if (!s_algorithmDelegateDictionary.ContainsKey(algorithm)) { try { algorithmObject = CryptoConfig.CreateFromName(algorithm); } catch (TargetInvocationException) { s_algorithmDelegateDictionary[algorithm] = null; } if (algorithmObject == null) { s_algorithmDelegateDictionary[algorithm] = null; } else { defaultObject = GetDefaultAlgorithm(algorithm); if (defaultObject != null && defaultObject.GetType() == algorithmObject.GetType()) { s_algorithmDelegateDictionary[algorithm] = null; } else { // Create a factory delegate which returns new instances of the algorithm type for later calls. Type algorithmType = algorithmObject.GetType(); System.Linq.Expressions.NewExpression algorithmCreationExpression = Linq.Expressions.Expression.New(algorithmType); Linq.Expressions.LambdaExpression creationFunction = Linq.Expressions.Expression.Lambda <Func <object> >(algorithmCreationExpression); delegateFunction = creationFunction.Compile() as Func <object>; if (delegateFunction != null) { s_algorithmDelegateDictionary[algorithm] = delegateFunction; } return(algorithmObject); } } } } } else { if (delegateFunction != null) { return(delegateFunction.Invoke()); } } // // This is a fallback in case CryptoConfig fails to return a valid // algorithm object. CrytoConfig does not understand all the uri's and // can return a null in that case, in which case it is our responsibility // to fallback and create the right algorithm if it is a uri we understand // switch (algorithm) { case SHA256String: case SecurityAlgorithms.Sha256Digest: return(SHA256.Create()); case SecurityAlgorithms.Sha1Digest: return(SHA1.Create()); case SecurityAlgorithms.HmacSha1Signature: return(new HMACSHA1()); default: break; } return(null); }
public MethodGraph SwitchImpl(System.Linq.Expressions.LambdaExpression expression, string newName = null, string oldName = null) { return(SwitchImpl(expression.Compile().Method, newName, oldName)); }
public MethodGraph(System.Linq.Expressions.LambdaExpression expression, TypeGraph parentGraph = null) : this(expression.Compile().Method, parentGraph) { }
} // End Function GetNamespaces static AccessorCache() { try { s_GetNamespaces = null; System.Linq.Expressions.ParameterExpression p = System.Linq.Expressions.Expression.Parameter(typeof(T)); System.Linq.Expressions.MemberExpression prop = System.Linq.Expressions.Expression.Property(p, "Namespaces"); System.Linq.Expressions.UnaryExpression con = System.Linq.Expressions.Expression.Convert(prop, typeof(System.Xml.Serialization.XmlSerializerNamespaces)); System.Linq.Expressions.LambdaExpression exp = System.Linq.Expressions.Expression.Lambda(con, p); s_GetNamespaces = (System.Func <T, System.Xml.Serialization.XmlSerializerNamespaces>)exp.Compile(); } catch (System.Exception ex) { System.Console.WriteLine(ex.Message); System.Console.WriteLine(ex.StackTrace); } } // End Static constructor
protected virtual ComparisonResult CompareStructural(QueryStructuralValue expected, object actual, string path, bool shouldThrow) { this.AddToLogBuffer("Verifying structural value. Path: {0}", path); if (actual == null) { if (expected.IsNull) { return(ComparisonResult.Success); } this.ThrowOrLogError(shouldThrow, "Expecting non-null value: {0} in '{1}. Got null instead.", expected, path); return(ComparisonResult.Failure); } if (expected.IsNull) { this.ThrowOrLogError(shouldThrow, "Expecting null value in '{0}'. Actual: {1}[{2}].", path, actual, actual.GetType()); return(ComparisonResult.Failure); } if (expected.Type is QueryEntityType) { if (this.visitedEntities.ContainsKey(expected)) { if (object.ReferenceEquals(this.visitedEntities[expected], actual)) { this.AddToLogBuffer("Comparing structural value. Path: {0}. Result - EQUAL (ALREADY VISITED)", path); return(ComparisonResult.Success); } else { this.ThrowOrLogError(shouldThrow, "Expecting different object in '{0}'. Expected: {1}. Actual: {2}.", path, this.visitedEntities[expected], actual); return(ComparisonResult.Failure); } } else { this.visitedEntities.Add(expected, actual); } } var expectedType = expected.Type as IQueryClrType; if (expectedType != null) { ExceptionUtilities.Assert(expectedType.ClrType != null, "Expecting non-null CLR type."); if (!expectedType.ClrType.IsAssignableFrom(actual.GetType())) { this.visitedEntities.Remove(expected); this.ThrowOrLogError(shouldThrow, "Types not match in {0}. Expecting: {1}. Actual: {2}.", path, expectedType.ClrType, actual.GetType()); return(ComparisonResult.Failure); } } var properties = actual.GetType().GetProperties(); IEnumerable <string> propertyNames = expected.MemberNames; foreach (string expectedName in propertyNames) { var actualProperty = properties.Where(p => p.Name == expectedName).SingleOrDefault(); if (actualProperty == null) { this.visitedEntities.Remove(expected); this.ThrowOrLogError(shouldThrow, "Expected property not found: {0} in '{1}'.", expectedName, path); return(ComparisonResult.Failure); } object actualValue = null; #if SILVERLIGHT CoreLinq.Expressions.ParameterExpression param = CoreLinq.Expressions.Expression.Parameter(typeof(Object), "param"); CoreLinq.Expressions.Expression convertedParam = CoreLinq.Expressions.Expression.Convert(param, actual.GetType()); CoreLinq.Expressions.LambdaExpression GetPropertyValueExp = CoreLinq.Expressions.Expression.Lambda(System.Linq.Expressions.Expression.Property(convertedParam, actualProperty), param); Delegate dynamicGetter = GetPropertyValueExp.Compile(); actualValue = dynamicGetter.DynamicInvoke(actual); #else actualValue = actualProperty.GetValue(actual, null); #endif QueryType expectedPropertyType = expected.Type.Properties.Where(p => p.Name == expectedName).Single().PropertyType; string newPath = path + "." + expectedName; var propertyComparisonResult = this.CompareProperty(expected, expectedName, expectedPropertyType, actualValue, newPath, shouldThrow); if (propertyComparisonResult == ComparisonResult.Failure) { this.visitedEntities.Remove(expected); return(ComparisonResult.Failure); } } this.AddToLogBuffer("Verifying structural value. Path: {0} SUCCESSFUL", path); return(ComparisonResult.Success); }
static ProviderExtensions() { System.Linq.Expressions.ParameterExpression p = System.Linq.Expressions.Expression.Parameter(typeof(System.Data.Common.DbConnection)); System.Linq.Expressions.MemberExpression prop = System.Linq.Expressions.Expression.Property(p, "DbProviderFactory"); System.Linq.Expressions.UnaryExpression con = System.Linq.Expressions.Expression.Convert(prop, typeof(System.Data.Common.DbProviderFactory)); System.Linq.Expressions.LambdaExpression exp = System.Linq.Expressions.Expression.Lambda(con, p); s_func = (Func <System.Data.Common.DbConnection, System.Data.Common.DbProviderFactory>)exp.Compile(); } // End Static Constructor