private static bool TryEvaluateExpression <T>(Activity <T> expression, LocationReferenceEnvironment locationReferenceEnvironment, ActivityContext context, out object result) { T local; if (!expression.TryGetValue(context, out local)) { result = System.Activities.SR.DebugInfoTryGetValueFailed; return(false); } Activity rootActivity = local as Activity; context.Activity = rootActivity; if ((rootActivity != null) && !rootActivity.IsRuntimeReady) { WorkflowInspectionServices.CacheMetadata(rootActivity, locationReferenceEnvironment); } IExpressionContainer container = local as IExpressionContainer; if (container == null) { result = System.Activities.SR.DebugInfoNotAnIExpressionContainer; return(false); } Expression <Func <ActivityContext, object> > expression2 = container.Expression as Expression <Func <ActivityContext, object> >; if (expression2 == null) { result = System.Activities.SR.DebugInfoNoLambda; return(false); } result = expression2.Compile()(context); return(true); }
public object EvaluateExpression(string expressionString) { int num; object obj2; if (int.TryParse(expressionString, out num)) { return(num); } LocalInfo info = null; if ((this.cachedLocalInfos != null) && this.cachedLocalInfos.TryGetValue(expressionString, out info)) { return(info); } LocationReferenceEnvironment publicEnvironment = this.activityInstance.Activity.PublicEnvironment; ActivityContext context = new ActivityContext(this.activityInstance, null); try { if (!TryEvaluateExpression(expressionString, null, publicEnvironment, context, out obj2)) { return(System.Activities.SR.DebugInfoCannotEvaluateExpression(expressionString)); } } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } context.Dispose(); return(System.Activities.SR.DebugInfoCannotEvaluateExpression(expressionString)); } try { object obj3; if (TryEvaluateExpression(expressionString, obj2.GetType(), publicEnvironment, context, out obj3)) { LocalInfo info2 = new LocalInfo { Name = expressionString, Location = obj3 as System.Activities.Location }; this.cachedLocalInfos[expressionString] = info2; return(info2); } } catch (Exception exception2) { if (Fx.IsFatal(exception2)) { throw; } } finally { context.Dispose(); } return(obj2); }
// Recompile the VBReference passed in, with its current LocationReferenceEnvironment context // in a weakly-typed manner (the argument VBReference's type argument is ignored) //[SuppressMessage(FxCop.Category.Design, FxCop.Rule.AvoidOutParameters, // Justification = "Design has been approved")] public static Activity RecompileVisualBasicReference(ActivityWithResult visualBasicReference, out Type returnType, out SourceExpressionException compileError, out VisualBasicSettings vbSettings) { ITextExpression textExpression = visualBasicReference as ITextExpression; if (textExpression == null || textExpression.Language != VisualBasicHelper.Language) { // the argument must be of type VisualBasicReference<> throw FxTrace.Exception.AsError(new ArgumentException()); } string expressionText = textExpression.ExpressionText; LocationReferenceEnvironment environment = visualBasicReference.GetParentEnvironment(); List <string> namespaces; List <string> referencedAssemblies; GetAllImportReferences(visualBasicReference, out namespaces, out referencedAssemblies); return(CreatePrecompiledVisualBasicReference( null, expressionText, namespaces, referencedAssemblies, environment, out returnType, out compileError, out vbSettings)); }
internal ValidationContext(ActivityUtilities.ChildActivity owner, ActivityUtilities.ActivityCallStack parentChain, ProcessActivityTreeOptions options, LocationReferenceEnvironment environment) { this.owner = owner; this.parentChain = parentChain; this.options = options; this.environment = environment; }
static bool FindLocationReferencesFromEnvironment(LocationReferenceEnvironment environment, string targetName) { LocationReference foundLocationReference = null; LocationReferenceEnvironment currentEnvironment; bool foundMultiple = false; currentEnvironment = environment; while (currentEnvironment != null) { foreach (LocationReference reference in currentEnvironment.GetLocationReferences()) { if (string.Equals(reference.Name, targetName, StringComparison.OrdinalIgnoreCase)) { if (foundLocationReference != null) { foundMultiple = true; return(foundMultiple); } foundLocationReference = reference; } } currentEnvironment = currentEnvironment.Parent; } return(foundMultiple); }
private void ProcessLocationReferences() { Stack <LocationReferenceEnvironment> environments = new Stack <LocationReferenceEnvironment>(); // // Build list of location by enumerating environments // in top down order to match the traversal pattern of TextExpressionCompiler LocationReferenceEnvironment current = this.accessor.ActivityMetadata.Environment; while (current != null) { environments.Push(current); current = current.Parent; } foreach (LocationReferenceEnvironment environment in environments) { foreach (LocationReference reference in environment.GetLocationReferences()) { if (this.textExpression.RequiresCompilation) { this.accessor.CreateLocationArgument(reference, false); } this.locationReferences.Add(new InlinedLocationReference(reference, this.metadata.CurrentActivity)); } } // Scenarios like VBV/R needs to know if they should run their own compiler // during CacheMetadata. If we find a compiled expression root, means we're // already compiled. So set the IsStaticallyCompiled flag to true bool foundCompiledExpressionRoot = this.TryGetCompiledExpressionRootAtDesignTime(this.expressionActivity, this.metadataRoot, out this.compiledRoot, out this.expressionId); if (foundCompiledExpressionRoot) { foreach (var environment in environments) { environment.CompileExpressions = true; } // For compiled C# expressions we create temp auto generated arguments // for all locations whether they are used in the expressions or not. // The TryGetReferenceToPublicLocation method call above also generates // temp arguments for all locations. // However for VB expressions, this leads to inconsistency between build // time and run time as during build time VB only generates temp arguments // for locations that are referenced in the expressions. To maintain // consistency the we call the CreateRequiredArguments method seperately to // generates auto arguments only for locations that are referenced. if (textExpression.Language == "VB") { IList <string> requiredLocationNames = this.compiledRoot.GetRequiredLocations(this.expressionId); this.CreateRequiredArguments(requiredLocationNames); } } }
static void Compile(IDynamicActivity dynamicActivity, LocationReferenceEnvironment environment) { string language = null; if (RequiresCompilation(dynamicActivity, environment, out language)) { //TextExpressionCompiler compiler = new TextExpressionCompiler(GetCompilerSettings(dynamicActivity, language)); //TextExpressionCompilerResults results = compiler.Compile(); //if (results.HasErrors) //{ // StringBuilder messages = new StringBuilder(); // messages.Append("\r\n"); // messages.Append("\r\n"); // foreach (TextExpressionCompilerError message in results.CompilerMessages) // { // messages.Append("\t"); // if (results.HasSourceInfo) // { // messages.Append(string.Concat(" ", SR.ActivityXamlServiceLineString, " ", message.SourceLineNumber, ": ")); // } // messages.Append(message.Message); // } // messages.Append("\r\n"); // messages.Append("\r\n"); // InvalidOperationException exception = new InvalidOperationException(SR.ActivityXamlServicesCompilationFailed(messages.ToString())); // foreach (TextExpressionCompilerError message in results.CompilerMessages) // { // exception.Data.Add(message, message.Message); // } // throw CoreWf.Internals.FxTrace.Exception.AsError(exception); //} //Type compiledExpressionRootType = results.ResultType; //ICompiledExpressionRoot compiledExpressionRoot = Activator.CreateInstance(compiledExpressionRootType, new object[] { dynamicActivity }) as ICompiledExpressionRoot; //CompiledExpressionInvoker.SetCompiledExpressionRootForImplementation(dynamicActivity, compiledExpressionRoot); //EBW NULLED throw new NotImplementedException(System.Reflection.MethodBase.GetCurrentMethod().Name + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName); } }
private LocationReference FindLocationReference(string name) { LocationReference returnValue = null; LocationReferenceEnvironment current = this.accessor.ActivityMetadata.Environment; while (current != null) { if (current.TryGetLocationReference(name, out returnValue)) { return(returnValue); } current = current.Parent; } return(returnValue); }
private static void Compile(IDynamicActivity dynamicActivity, LocationReferenceEnvironment environment) { #if NET45 string language = null; if (RequiresCompilation(dynamicActivity, environment, out language)) { TextExpressionCompiler compiler = new TextExpressionCompiler(GetCompilerSettings(dynamicActivity, language)); TextExpressionCompilerResults results = compiler.Compile(); if (results.HasErrors) { StringBuilder messages = new StringBuilder(); messages.Append("\r\n"); messages.Append("\r\n"); foreach (TextExpressionCompilerError message in results.CompilerMessages) { messages.Append("\t"); if (results.HasSourceInfo) { messages.Append(string.Concat(" ", SR.ActivityXamlServiceLineString, " ", message.SourceLineNumber, ": ")); } messages.Append(message.Message); } messages.Append("\r\n"); messages.Append("\r\n"); InvalidOperationException exception = new InvalidOperationException(SR.ActivityXamlServicesCompilationFailed(messages.ToString())); foreach (TextExpressionCompilerError message in results.CompilerMessages) { exception.Data.Add(message, message.Message); } throw FxTrace.Exception.AsError(exception); } Type compiledExpressionRootType = results.ResultType; ICompiledExpressionRoot compiledExpressionRoot = Activator.CreateInstance(compiledExpressionRootType, new object[] { dynamicActivity }) as ICompiledExpressionRoot; CompiledExpressionInvoker.SetCompiledExpressionRootForImplementation(dynamicActivity, compiledExpressionRoot); } #endif }
public Type FindVariable(string name) { LocationReference reference = null; bool flag = false; bool flag2 = false; for (LocationReferenceEnvironment environment = this.environmentProvider; (environment != null) && !flag2; environment = environment.Parent) { foreach (LocationReference reference2 in environment.GetLocationReferences()) { if (string.Equals(reference2.Name, name, StringComparison.OrdinalIgnoreCase)) { if (flag) { flag2 = true; break; } flag = true; reference = reference2; } } } if (flag2) { this.errorMessage = System.Activities.SR.AmbiguousVBVariableReference(name); return(null); } if (!flag) { return(null); } Type type = reference.Type; HashSet <Type> typeReferences = null; VisualBasicHelper.EnsureTypeReferenced(type, ref typeReferences); foreach (Type type2 in typeReferences) { if (!this.assemblies.Contains(type2.Assembly)) { return(null); } } return(type); }
private static Activity GetRoot(Activity activity, out bool isImplementation) { isImplementation = false; Activity root = null; if (activity != null) { if (activity.MemberOf == null) { throw FxTrace.Exception.Argument("activity", SR.ActivityIsUncached); } LocationReferenceEnvironment environment = activity.GetParentEnvironment(); isImplementation = activity.MemberOf != activity.RootActivity.MemberOf; root = environment.Root; } return(root); }
private static bool RequiresCompilation(IDynamicActivity dynamicActivity, LocationReferenceEnvironment environment, out string language) { language = null; if (!((Activity)dynamicActivity).IsMetadataCached) { IList <ValidationError> validationErrors = null; if (environment == null) { environment = new ActivityLocationReferenceEnvironment { CompileExpressions = true }; } try { ActivityUtilities.CacheRootMetadata((Activity)dynamicActivity, environment, ProcessActivityTreeOptions.FullCachingOptions, null, ref validationErrors); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } throw FxTrace.Exception.AsError(new InvalidOperationException(SR.CompiledExpressionsCacheMetadataException(dynamicActivity.Name, e.ToString()))); } } DynamicActivityVisitor vistor = new DynamicActivityVisitor(); vistor.Visit((Activity)dynamicActivity, true); if (!vistor.RequiresCompilation) { return(false); } if (vistor.HasLanguageConflict) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.DynamicActivityMultipleExpressionLanguages(vistor.GetConflictingLanguages().AsCommaSeparatedValues()))); } language = vistor.Language; return(true); }
void ValidateWorkflow(WorkflowInstanceExtensionManager extensionManager) { if (!WorkflowDefinition.IsRuntimeReady) { LocationReferenceEnvironment localEnvironment = this.hostEnvironment; if (localEnvironment == null) { LocationReferenceEnvironment parentEnvironment = null; if (extensionManager != null && extensionManager.SymbolResolver != null) { parentEnvironment = extensionManager.SymbolResolver.AsLocationReferenceEnvironment(); } localEnvironment = new ActivityLocationReferenceEnvironment(parentEnvironment); } IList <ValidationError> validationErrors = null; ActivityUtilities.CacheRootMetadata(WorkflowDefinition, localEnvironment, ProcessActivityTreeOptions.FullCachingOptions, null, ref validationErrors); ActivityValidationServices.ThrowIfViolationsExist(validationErrors); } }
public static Activity RecompileVisualBasicValue(ActivityWithResult visualBasicValue, out Type returnType, out SourceExpressionException compileError, out VisualBasicSettings vbSettings) { IVisualBasicExpression expression = visualBasicValue as IVisualBasicExpression; if (expression == null) { throw FxTrace.Exception.AsError(new ArgumentException()); } string expressionText = expression.ExpressionText; LocationReferenceEnvironment parentEnvironment = visualBasicValue.GetParentEnvironment(); HashSet <VisualBasicImportReference> allImportReferences = VisualBasicHelper.GetAllImportReferences((parentEnvironment != null) ? parentEnvironment.Root : null); HashSet <string> namespaces = new HashSet <string>(); HashSet <string> referencedAssemblies = new HashSet <string>(); foreach (VisualBasicImportReference reference in allImportReferences) { namespaces.Add(reference.Import); referencedAssemblies.Add(reference.Assembly); } return(CreatePrecompiledVisualBasicValue(null, expressionText, namespaces, referencedAssemblies, parentEnvironment, out returnType, out compileError, out vbSettings)); }
static bool TryEvaluateExpression( string expressionString, Type locationValueType, // Non null for Reference type (location) LocationReferenceEnvironment locationReferenceEnvironment, CodeActivityContext context, out object result) { expressionString = string.Format(CultureInfo.InvariantCulture, "[{0}]", expressionString); Type activityType; if (locationValueType != null) { activityType = typeof(Activity <>).MakeGenericType(typeof(Location <>).MakeGenericType(locationValueType)); } else { activityType = typeof(Activity <object>); } // General expression. ActivityWithResultConverter converter = new ActivityWithResultConverter(activityType); ActivityWithResult expression = converter.ConvertFromString( new TypeDescriptorContext { LocationReferenceEnvironment = locationReferenceEnvironment }, expressionString) as ActivityWithResult; if (locationValueType != null) { Type locationHelperType = typeof(LocationHelper <>).MakeGenericType(locationValueType); LocationHelper helper = (LocationHelper)Activator.CreateInstance(locationHelperType); return(helper.TryGetValue(expression, locationReferenceEnvironment, context, out result)); } else { return(TryEvaluateExpression(expression, locationReferenceEnvironment, context, out result)); } }
static bool TryEvaluateExpression( ActivityWithResult element, LocationReferenceEnvironment locationReferenceEnvironment, CodeActivityContext context, out object result) { // value is some expression type and needs to be opened context.Reinitialize(context.CurrentInstance, context.CurrentExecutor, element, context.CurrentInstance.InternalId); if (element != null && !element.IsRuntimeReady) { WorkflowInspectionServices.CacheMetadata(element, locationReferenceEnvironment); } if (element == null || !element.IsFastPath) { result = SR.DebugInfoNotSkipArgumentResolution; return(false); } result = element.InternalExecuteInResolutionContextUntyped(context); return(true); }
internal InternalActivityValidationServices(ValidationSettings settings, Activity toValidate) { _settings = settings; _rootToValidate = toValidate; _environment = settings.Environment; }
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) => Impl.CreatePrecompiledReference(targetType, expressionText, namespaces, referencedAssemblies, environment, out returnType, out compileError, out vbSettings);
public static IDictionary <object, DynamicUpdateMapItem> CalculateImplementationMapItems(Activity activityDefinitionToBeUpdated, LocationReferenceEnvironment environment) { return(InternalCalculateMapItems(activityDefinitionToBeUpdated, environment, true)); }
static IDictionary <object, DynamicUpdateMapItem> InternalCalculateMapItems(Activity workflowDefinitionToBeUpdated, LocationReferenceEnvironment environment, bool forImplementation) { if (workflowDefinitionToBeUpdated == null) { throw FxTrace.Exception.ArgumentNull("workflowDefinitionToBeUpdated"); } DynamicUpdateMapBuilder.Preparer preparer = new DynamicUpdateMapBuilder.Preparer(workflowDefinitionToBeUpdated, environment, forImplementation); return(preparer.Prepare()); }
// 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; HashSet <string> namespacesSet = new HashSet <string>(); HashSet <AssemblyName> assembliesSet = new HashSet <AssemblyName>(); compileError = null; returnType = null; if (namespaces != null) { foreach (string ns in namespaces) { if (ns != null) { namespacesSet.Add(ns); } } } if (referencedAssemblies != null) { foreach (string assm in referencedAssemblies) { if (assm != null) { assembliesSet.Add(new AssemblyName(assm)); } } } VisualBasicHelper 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)) { string 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 { MethodInfo 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)) { string 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) { SourceExpressionException 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) { HashSet <Type> typeReferences = new HashSet <Type>(); FindTypeReferences(lambda.Body, typeReferences); foreach (Type type in typeReferences) { Assembly tassembly = type.Assembly; if (tassembly.IsDynamic) { continue; } string assemblyName = VisualBasicHelper.GetFastAssemblyName(tassembly).Name; VisualBasicImportReference importReference = new VisualBasicImportReference { Assembly = assemblyName, Import = type.Namespace }; vbSettings.ImportReferences.Add(importReference); } } Type concreteHelperType = VisualBasicExpressionFactoryType.MakeGenericType(targetType); VisualBasicExpressionFactory expressionFactory = (VisualBasicExpressionFactory)Activator.CreateInstance(concreteHelperType); return(expressionFactory.CreateVisualBasicReference(expressionText)); }
static bool TryEvaluateExpression( string expressionString, Type locationValueType, // Non null for Reference type (location) LocationReferenceEnvironment locationReferenceEnvironment, CodeActivityContext context, out object result) { expressionString = string.Format(CultureInfo.InvariantCulture, "[{0}]", expressionString); Type activityType; if (locationValueType != null) { activityType = typeof(Activity<>).MakeGenericType(typeof(Location<>).MakeGenericType(locationValueType)); } else { activityType = typeof(Activity<object>); } // General expression. ActivityWithResultConverter converter = new ActivityWithResultConverter(activityType); ActivityWithResult expression = converter.ConvertFromString( new TypeDescriptorContext { LocationReferenceEnvironment = locationReferenceEnvironment }, expressionString) as ActivityWithResult; if (locationValueType != null) { Type locationHelperType = typeof(LocationHelper<>).MakeGenericType(locationValueType); LocationHelper helper = (LocationHelper)Activator.CreateInstance(locationHelperType); return helper.TryGetValue(expression, locationReferenceEnvironment, context, out result); } else { return TryEvaluateExpression(expression, locationReferenceEnvironment, context, out result); } }
internal InternalActivityValidationServices(ValidationSettings settings, Activity toValidate) { this.settings = settings; this.rootToValidate = toValidate; this.environment = settings.Environment; }
internal static void RunConstraints(ActivityUtilities.ChildActivity childActivity, ActivityUtilities.ActivityCallStack parentChain, IList <Constraint> constraints, ProcessActivityTreeOptions options, bool suppressGetChildrenViolations, ref IList <ValidationError> validationErrors) { if (constraints != null) { Activity toValidate = childActivity.Activity; LocationReferenceEnvironment environment = toValidate.GetParentEnvironment(); Dictionary <string, object> inputDictionary = new Dictionary <string, object>(2); for (int constraintIndex = 0; constraintIndex < constraints.Count; constraintIndex++) { Constraint constraint = constraints[constraintIndex]; // there may be null entries here if (constraint == null) { continue; } inputDictionary[Constraint.ToValidateArgumentName] = toValidate; ValidationContext validationContext = new ValidationContext(childActivity, parentChain, options, environment); inputDictionary[Constraint.ToValidateContextArgumentName] = validationContext; IDictionary <string, object> results = null; try { results = WorkflowInvoker.Invoke(constraint, inputDictionary); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } ValidationError constraintExceptionValidationError = new ValidationError(SR.InternalConstraintException(constraint.DisplayName, toValidate.GetType().FullName, toValidate.DisplayName, e.ToString()), false) { Source = toValidate, Id = toValidate.Id }; ActivityUtilities.Add(ref validationErrors, constraintExceptionValidationError); } if (results != null) { if (results.TryGetValue(Constraint.ValidationErrorListArgumentName, out object resultValidationErrors)) { IList <ValidationError> validationErrorList = (IList <ValidationError>)resultValidationErrors; if (validationErrorList.Count > 0) { if (validationErrors == null) { validationErrors = new List <ValidationError>(); } string prefix = ActivityValidationServices.GenerateValidationErrorPrefix(childActivity.Activity, parentChain, options, out Activity source); for (int validationErrorIndex = 0; validationErrorIndex < validationErrorList.Count; validationErrorIndex++) { ValidationError validationError = validationErrorList[validationErrorIndex]; validationError.Source = source; validationError.Id = source.Id; if (!string.IsNullOrEmpty(prefix)) { validationError.Message = prefix + validationError.Message; } validationErrors.Add(validationError); } } } } if (!suppressGetChildrenViolations) { validationContext.AddGetChildrenErrors(ref validationErrors); } } } }
public abstract bool TryGetValue(Activity expression, LocationReferenceEnvironment locationReferenceEnvironment, CodeActivityContext context, out object result);
public Expression <Func <ActivityContext, T> > Compile <T>(LocationReferenceEnvironment environment) { CompilerResults results; Type type = typeof(T); this.environment = environment; if (this.referencedAssemblies == null) { this.referencedAssemblies = new HashSet <Assembly>(); } this.referencedAssemblies.UnionWith(DefaultReferencedAssemblies); List <Import> importList = new List <Import>(); foreach (string str in this.namespaceImports) { if (!string.IsNullOrEmpty(str)) { importList.Add(new Import(str)); } } HashSet <Type> typeReferences = null; EnsureTypeReferenced(type, ref typeReferences); foreach (Type type2 in typeReferences) { this.referencedAssemblies.Add(type2.Assembly); } VisualBasicScriptAndTypeScope scriptScope = new VisualBasicScriptAndTypeScope(this.environment, this.referencedAssemblies.ToList <Assembly>()); IImportScope importScope = new VisualBasicImportScope(importList); CompilerOptions options = new CompilerOptions { OptionStrict = OptionStrictSetting.On }; CompilerContext context = new CompilerContext(scriptScope, scriptScope, importScope, options); HostedCompiler cachedHostedCompiler = GetCachedHostedCompiler(this.referencedAssemblies); lock (cachedHostedCompiler) { try { results = cachedHostedCompiler.CompileExpression(this.textToCompile, context, type); } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } FxTrace.Exception.TraceUnhandledException(exception); throw; } } if (scriptScope.ErrorMessage != null) { throw FxTrace.Exception.AsError(new SourceExpressionException(System.Activities.SR.CompilerErrorSpecificExpression(this.textToCompile, scriptScope.ErrorMessage))); } if ((results.Errors != null) && (results.Errors.Count > 0)) { StringBuilder builder = new StringBuilder(); builder.AppendLine(); foreach (Microsoft.Compiler.VisualBasic.Error error in results.Errors) { builder.AppendLine(error.Description); } throw FxTrace.Exception.AsError(new SourceExpressionException(System.Activities.SR.CompilerErrorSpecificExpression(this.textToCompile, builder.ToString()))); } LambdaExpression codeBlock = results.CodeBlock; if (codeBlock == null) { return(null); } Expression expression = this.Rewrite(codeBlock.Body, null); ParameterExpression[] parameters = new ParameterExpression[] { FindParameter(expression) ?? ExpressionUtilities.RuntimeContextParameter }; return(Expression.Lambda <Func <ActivityContext, T> >(expression, parameters)); }
private Expression Rewrite(Expression expression, ReadOnlyCollection <ParameterExpression> lambdaParameters) { Func <Expression, Expression> selector = null; Func <ElementInit, ElementInit> func2 = null; Func <MemberBinding, MemberBinding> func3 = null; Func <Expression, Expression> func4 = null; Func <Expression, Expression> func5 = null; Func <Expression, Expression> func6 = null; Func <Expression, Expression> func7 = null; Func <Expression, Expression> func8 = null; if (expression == null) { return(null); } switch (expression.NodeType) { case ExpressionType.Add: case ExpressionType.AddChecked: case ExpressionType.And: case ExpressionType.AndAlso: case ExpressionType.Coalesce: case ExpressionType.Divide: case ExpressionType.Equal: case ExpressionType.ExclusiveOr: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.LeftShift: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.Modulo: case ExpressionType.Multiply: case ExpressionType.MultiplyChecked: case ExpressionType.NotEqual: case ExpressionType.Or: case ExpressionType.OrElse: case ExpressionType.Power: case ExpressionType.RightShift: case ExpressionType.Subtract: case ExpressionType.SubtractChecked: { BinaryExpression expression2 = (BinaryExpression)expression; return(Expression.MakeBinary(expression2.NodeType, this.Rewrite(expression2.Left, lambdaParameters), this.Rewrite(expression2.Right, lambdaParameters), expression2.IsLiftedToNull, expression2.Method, (LambdaExpression)this.Rewrite(expression2.Conversion, lambdaParameters))); } case ExpressionType.ArrayLength: case ExpressionType.Convert: case ExpressionType.ConvertChecked: case ExpressionType.Negate: case ExpressionType.NegateChecked: case ExpressionType.Not: case ExpressionType.Quote: case ExpressionType.TypeAs: { UnaryExpression expression17 = (UnaryExpression)expression; return(Expression.MakeUnary(expression17.NodeType, this.Rewrite(expression17.Operand, lambdaParameters), expression17.Type, expression17.Method)); } case ExpressionType.ArrayIndex: { MethodCallExpression expression10 = expression as MethodCallExpression; if (expression10 == null) { BinaryExpression expression11 = (BinaryExpression)expression; return(Expression.ArrayIndex(this.Rewrite(expression11.Left, lambdaParameters), this.Rewrite(expression11.Right, lambdaParameters))); } if (func4 == null) { func4 = a => this.Rewrite(a, lambdaParameters); } return(Expression.ArrayIndex(this.Rewrite(expression10.Object, lambdaParameters), expression10.Arguments.Select <Expression, Expression>(func4))); } case ExpressionType.Call: { MethodCallExpression expression12 = (MethodCallExpression)expression; if (func5 == null) { func5 = a => this.Rewrite(a, lambdaParameters); } return(Expression.Call(this.Rewrite(expression12.Object, lambdaParameters), expression12.Method, expression12.Arguments.Select <Expression, Expression>(func5))); } case ExpressionType.Conditional: { ConditionalExpression expression3 = (ConditionalExpression)expression; return(Expression.Condition(this.Rewrite(expression3.Test, lambdaParameters), this.Rewrite(expression3.IfTrue, lambdaParameters), this.Rewrite(expression3.IfFalse, lambdaParameters))); } case ExpressionType.Constant: return(expression); case ExpressionType.Invoke: { InvocationExpression expression4 = (InvocationExpression)expression; if (selector == null) { selector = a => this.Rewrite(a, lambdaParameters); } return(Expression.Invoke(this.Rewrite(expression4.Expression, lambdaParameters), expression4.Arguments.Select <Expression, Expression>(selector))); } case ExpressionType.Lambda: { LambdaExpression expression5 = (LambdaExpression)expression; return(Expression.Lambda(expression5.Type, this.Rewrite(expression5.Body, expression5.Parameters), expression5.Parameters)); } case ExpressionType.ListInit: { ListInitExpression expression6 = (ListInitExpression)expression; if (func2 == null) { func2 = ei => Expression.ElementInit(ei.AddMethod, (IEnumerable <Expression>)(from arg in ei.Arguments select this.Rewrite(arg, lambdaParameters))); } return(Expression.ListInit((NewExpression)this.Rewrite(expression6.NewExpression, lambdaParameters), expression6.Initializers.Select <ElementInit, ElementInit>(func2))); } case ExpressionType.MemberAccess: { MemberExpression expression8 = (MemberExpression)expression; return(Expression.MakeMemberAccess(this.Rewrite(expression8.Expression, lambdaParameters), expression8.Member)); } case ExpressionType.MemberInit: { MemberInitExpression expression9 = (MemberInitExpression)expression; if (func3 == null) { func3 = b => this.Rewrite(b, lambdaParameters); } return(Expression.MemberInit((NewExpression)this.Rewrite(expression9.NewExpression, lambdaParameters), expression9.Bindings.Select <MemberBinding, MemberBinding>(func3))); } case ExpressionType.UnaryPlus: { UnaryExpression expression18 = (UnaryExpression)expression; return(Expression.UnaryPlus(this.Rewrite(expression18.Operand, lambdaParameters), expression18.Method)); } case ExpressionType.New: { NewExpression expression15 = (NewExpression)expression; if (expression15.Constructor != null) { if (func8 == null) { func8 = a => this.Rewrite(a, lambdaParameters); } return(Expression.New(expression15.Constructor, expression15.Arguments.Select <Expression, Expression>(func8))); } return(expression); } case ExpressionType.NewArrayInit: { NewArrayExpression expression13 = (NewArrayExpression)expression; if (func6 == null) { func6 = e => this.Rewrite(e, lambdaParameters); } return(Expression.NewArrayInit(expression13.Type.GetElementType(), expression13.Expressions.Select <Expression, Expression>(func6))); } case ExpressionType.NewArrayBounds: { NewArrayExpression expression14 = (NewArrayExpression)expression; if (func7 == null) { func7 = e => this.Rewrite(e, lambdaParameters); } return(Expression.NewArrayBounds(expression14.Type.GetElementType(), expression14.Expressions.Select <Expression, Expression>(func7))); } case ExpressionType.Parameter: { ParameterExpression expression7 = (ParameterExpression)expression; if ((lambdaParameters == null) || !lambdaParameters.Contains(expression7)) { string name = expression7.Name; for (LocationReferenceEnvironment environment = this.environment; environment != null; environment = environment.Parent) { foreach (LocationReference reference in environment.GetLocationReferences()) { if (string.Equals(reference.Name, name, StringComparison.OrdinalIgnoreCase)) { LocationReference reference3; LocationReference locationReference = reference; if (this.metadata.HasValue && this.metadata.Value.TryGetInlinedLocationReference(reference, out reference3)) { locationReference = reference3; } return(ExpressionUtilities.CreateIdentifierExpression(locationReference)); } } } return(expression7); } return(expression7); } case ExpressionType.TypeIs: { TypeBinaryExpression expression16 = (TypeBinaryExpression)expression; return(Expression.TypeIs(this.Rewrite(expression16.Expression, lambdaParameters), expression16.TypeOperand)); } case ExpressionType.Assign: { BinaryExpression expression22 = (BinaryExpression)expression; return(Expression.Assign(this.Rewrite(expression22.Left, lambdaParameters), this.Rewrite(expression22.Right, lambdaParameters))); } case ExpressionType.Block: { BlockExpression expression19 = (BlockExpression)expression; List <ParameterExpression> list = new List <ParameterExpression>(); foreach (ParameterExpression expression20 in expression19.Variables) { list.Add((ParameterExpression)this.Rewrite(expression20, lambdaParameters)); } List <Expression> list2 = new List <Expression>(); foreach (Expression expression21 in expression19.Expressions) { list2.Add(this.Rewrite(expression21, lambdaParameters)); } return(Expression.Block((IEnumerable <ParameterExpression>)list, (IEnumerable <Expression>)list2)); } } return(expression); }
public VisualBasicScriptAndTypeScope(LocationReferenceEnvironment environmentProvider, List <Assembly> assemblies) { this.environmentProvider = environmentProvider; this.assemblies = assemblies; }
internal object EvaluateExpression(string expressionString) { // This is to shortcircuit a common case where // internally, vsdebugger calls our EE with literal "0" int intResult; if (int.TryParse(expressionString, out intResult)) { return(intResult); } // At refresh, Expression Evaluator may re-evaluate locals/arguments. // To speed up the process, locals/arguments are cached. LocalInfo cachedLocalInfo = null; if (this.cachedLocalInfos != null && this.cachedLocalInfos.TryGetValue(expressionString, out cachedLocalInfo)) { return(cachedLocalInfo); } Activity activity = activityInstance.Activity; LocationReferenceEnvironment locationReferenceEnvironment = activity.PublicEnvironment; // a temporary context for EvaluateExpression // We're not using the executor so it's ok that it's null CodeActivityContext context = new CodeActivityContext(activityInstance, null); object result; try { // First try as R-Value if (!TryEvaluateExpression(expressionString, null, locationReferenceEnvironment, context, out result)) { return(SR.DebugInfoCannotEvaluateExpression(expressionString)); } } catch (Exception ex) { // ---- all exceptions, this exception is generated by user typing input in either // Watch window or Immediate windows. Exception should not affect the current runtime. // Except for fatal exception. if (Fx.IsFatal(ex)) { throw; } context.Dispose(); return(SR.DebugInfoCannotEvaluateExpression(expressionString)); } // Now try expression as an L-Value if possible. try { object resultLocation; if (TryEvaluateExpression(expressionString, result.GetType(), locationReferenceEnvironment, context, out resultLocation)) { LocalInfo localInfo = new LocalInfo() { Name = expressionString, Location = resultLocation as Location }; this.cachedLocalInfos[expressionString] = localInfo; return(localInfo); } } catch (Exception ex) { // ---- all exceptions, this exception is generated by user typing input in either // Watch window or Immediate windows. Exception should not affect the current runtime. // Except for fatal exception. if (Fx.IsFatal(ex)) { throw; } } finally { context.Dispose(); } return(result); }
internal static void RunConstraints(ActivityUtilities.ChildActivity childActivity, ActivityUtilities.ActivityCallStack parentChain, IList <Constraint> constraints, ProcessActivityTreeOptions options, bool suppressGetChildrenViolations, ref IList <ValidationError> validationErrors) { if (constraints != null) { Activity activity = childActivity.Activity; LocationReferenceEnvironment parentEnvironment = activity.GetParentEnvironment(); Dictionary <string, object> inputs = new Dictionary <string, object>(2); for (int i = 0; i < constraints.Count; i++) { Constraint workflow = constraints[i]; if (workflow != null) { object obj2; inputs["ToValidate"] = activity; ValidationContext context = new ValidationContext(childActivity, parentChain, options, parentEnvironment); inputs["ToValidateContext"] = context; IDictionary <string, object> dictionary2 = null; try { dictionary2 = WorkflowInvoker.Invoke(workflow, inputs); } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } ValidationError data = new ValidationError(System.Activities.SR.InternalConstraintException(workflow.DisplayName, activity.GetType().FullName, activity.DisplayName, exception.ToString()), false) { Source = activity, Id = activity.Id }; ActivityUtilities.Add <ValidationError>(ref validationErrors, data); } if ((dictionary2 != null) && dictionary2.TryGetValue("ViolationList", out obj2)) { IList <ValidationError> list = (IList <ValidationError>)obj2; if (list.Count > 0) { Activity activity2; if (validationErrors == null) { validationErrors = new List <ValidationError>(); } string str = GenerateValidationErrorPrefix(childActivity.Activity, parentChain, out activity2); for (int j = 0; j < list.Count; j++) { ValidationError item = list[j]; item.Source = activity2; item.Id = activity2.Id; if (!string.IsNullOrEmpty(str)) { item.Message = str + item.Message; } validationErrors.Add(item); } } } if (!suppressGetChildrenViolations) { context.AddGetChildrenErrors(ref validationErrors); } } } } }
private static bool TryEvaluateExpression(string expressionString, Type locationValueType, LocationReferenceEnvironment locationReferenceEnvironment, ActivityContext context, out object result) { Type type; expressionString = string.Format(CultureInfo.InvariantCulture, "[{0}]", new object[] { expressionString }); if (locationValueType != null) { type = typeof(Activity <>).MakeGenericType(new Type[] { typeof(Location <>).MakeGenericType(new Type[] { locationValueType }) }); } else { type = typeof(Activity <object>); } ActivityWithResultConverter converter = new ActivityWithResultConverter(type); TypeDescriptorContext context2 = new TypeDescriptorContext { LocationReferenceEnvironment = locationReferenceEnvironment }; ActivityWithResult expression = converter.ConvertFromString(context2, expressionString) as ActivityWithResult; if (locationValueType != null) { LocationHelper helper = (LocationHelper)Activator.CreateInstance(typeof(LocationHelper).MakeGenericType(new Type[] { locationValueType })); return(helper.TryGetValue(expression, locationReferenceEnvironment, context, out result)); } return(TryEvaluateExpression <object>(expression, locationReferenceEnvironment, context, out result)); }
static bool TryEvaluateExpression( ActivityWithResult element, LocationReferenceEnvironment locationReferenceEnvironment, CodeActivityContext context, out object result) { // value is some expression type and needs to be opened context.Reinitialize(context.CurrentInstance, context.CurrentExecutor, element, context.CurrentInstance.InternalId); if (element != null && !element.IsRuntimeReady) { WorkflowInspectionServices.CacheMetadata(element, locationReferenceEnvironment); } if (element == null || !element.IsFastPath) { result = SR.DebugInfoNotSkipArgumentResolution; return false; } result = element.InternalExecuteInResolutionContextUntyped(context); return true; }