public IDev2Activity Parse(DynamicActivity activity, Guid resourceIdGuid, bool failOnException = false) { if (HasActivityInCache(resourceIdGuid)) { return(GetActivity(resourceIdGuid)); } var dynamicActivity = activity; if (dynamicActivity != null) { try { IDev2Activity act = _activityParser.Parse(dynamicActivity); if (_cache.TryAdd(resourceIdGuid, act)) { return(act); } } // ReSharper disable EmptyGeneralCatchClause catch (Exception err) //errors caught inside // ReSharper restore EmptyGeneralCatchClause { Dev2Logger.Log.Error(err); if (failOnException) { throw; } } } return(null); }
/// <summary> /// Validates the arguments in ChildArguments property against the arguments of specified dynamicActivity instance by adding a validation error /// to supplied metadata if the argument is wrong type, direction or does not exist. /// </summary> /// <param name="metadata">The metadata.</param> /// <param name="dynamicActivity">The dynamic activity.</param> private void Validate(NativeActivityMetadata metadata, DynamicActivity dynamicActivity) { foreach (string argumentKey in this.ChildArguments.Keys) { if (dynamicActivity.Properties.Contains(argumentKey)) { DynamicActivityProperty dynamicActivityProperty = dynamicActivity.Properties[argumentKey]; Argument arg = this.ChildArguments[argumentKey]; if (dynamicActivityProperty.Type.GetGenericTypeDefinition() == typeof(InArgument <>) && arg.Direction != ArgumentDirection.In) { metadata.AddValidationError(new ValidationError(string.Format(Resources.InvalidInArgumentDirectionValidationErrorText, argumentKey))); } else if (dynamicActivityProperty.Type.GetGenericTypeDefinition() == typeof(OutArgument <>) && arg.Direction != ArgumentDirection.Out) { metadata.AddValidationError(new ValidationError(string.Format(Resources.InvalidOutArgumentDirectionValidationErrorText, argumentKey))); } else if (dynamicActivityProperty.Type.GetGenericTypeDefinition() == typeof(InOutArgument <>) && arg.Direction != ArgumentDirection.InOut) { metadata.AddValidationError(new ValidationError(string.Format(Resources.InvalidInOutArgumentDirectionValidationErrorText, argumentKey))); } if (dynamicActivityProperty.Type.GetGenericArguments()[0] != arg.ArgumentType) { metadata.AddValidationError(new ValidationError(string.Format(Resources.InvalidIArgumentTypeValidationErrorText, argumentKey, dynamicActivityProperty.Type.GetGenericArguments()[0]))); } } else { metadata.AddValidationError(new ValidationError(string.Format(Resources.InvalidIArgumentValidationErrorText, argumentKey))); } } }
public void Run() { this.workflowDesigner.Flush(); MemoryStream ms = new MemoryStream(ASCIIEncoding.Default.GetBytes(this.workflowDesigner.Text)); DynamicActivity activityToRun = ActivityXamlServices.Load(ms) as DynamicActivity; this.workflowApplication = new WorkflowApplication(activityToRun); this.workflowApplication.Extensions.Add(this.output); this.workflowApplication.Completed = this.WorkflowCompleted; this.workflowApplication.Aborted = this.WorkflowAborted; this.workflowApplication.OnUnhandledException = this.WorkflowUnhandledException; StatusViewModel.SetStatusText(Resources.RunningStatus, this.workflowName); try { this.running = true; this.workflowApplication.Run(); } catch (Exception e) { this.output.WriteLine(ExceptionHelper.FormatStackTrace(e)); StatusViewModel.SetStatusText(Resources.ExceptionStatus, this.workflowName); this.running = false; } }
public static Activity CreateSalutationRules() { var inProperty = new DynamicActivityProperty { Name = "Person", Type = typeof(InArgument <Person>) }; var activity = new DynamicActivity() { Properties = { inProperty } }; Common.AddVbSetting(activity); var sequence = new Sequence(); activity.Implementation = () => sequence; // First rule var condition1 = new VisualBasicValue <bool>("Person.Gender = \"Male\""); var if1 = new If(new InArgument <bool>(condition1)); if1.Then = new Assign <string> { To = new OutArgument <string>(new VisualBasicReference <string>("Person.Salutation")), Value = new InArgument <string>("Mr") }; if1.Else = new Assign <string> { To = new OutArgument <string>(new VisualBasicReference <string>("Person.Salutation")), Value = new InArgument <string>("Miss") }; // Second rule var condition2 = new VisualBasicValue <bool>("Person.Gender = \"Female\" AND Person.Married"); var if2 = new If(new InArgument <bool>(condition2)); if2.Then = new Assign <string> { To = new OutArgument <string>(new VisualBasicReference <string>("Person.Salutation")), Value = new InArgument <string>("Mrs") }; // Third rule var condition3 = new VisualBasicValue <bool>("Person.Minor"); var if3 = new If(new InArgument <bool>(condition3)); if3.Then = new Assign <string> { To = new OutArgument <string>(new VisualBasicReference <string>("Person.Salutation")), Value = new InArgument <string>("To the parents of") }; // Priority is implicitly defined by the order in which we add the IF-activites sequence.Activities.Add(if1); sequence.Activities.Add(if2); sequence.Activities.Add(if3); return(activity); }
static void CompileExpressions(DynamicActivity dynamicActivity) { var activityName = dynamicActivity.Name; var activityType = activityName.Split('.').Last() + "_CompiledExpressionRoot"; var activityNamespace = string.Join(".", activityName.Split('.').Reverse().Skip(1).Reverse()); var settings = new TextExpressionCompilerSettings { Activity = dynamicActivity, Language = "C#", ActivityName = activityType, ActivityNamespace = activityNamespace, RootNamespace = "CSharpExpression", GenerateAsPartialClass = false, AlwaysGenerateSource = true, ForImplementation = true }; var results = new TextExpressionCompiler(settings).Compile(); if (results.HasErrors) { throw new Exception("Compilation failed."); } var compiledExpressionRoot = Activator.CreateInstance(results.ResultType, new object[] { dynamicActivity }) as ICompiledExpressionRoot; CompiledExpressionInvoker.SetCompiledExpressionRootForImplementation(dynamicActivity, compiledExpressionRoot); }
public Activity Parse(JsonElement node) { var implementation = node.GetProperty("implementation"); var innerActivity = _compositeActivityParser.Parse(implementation); var outerActivity = new DynamicActivity() { Name = "jkjkj", DisplayName = "jkj", Attributes = { }, Constraints = { }, Implementation = () => innerActivity, }; foreach (var argument in ParseArguments(node)) { outerActivity.Properties.Add(argument); } var result = ParseResult(node); if (result != null) { outerActivity.Properties.Add(result); } return(outerActivity); }
public static WorkflowApplication createInstance(string xamlString, Dictionary <string, object> dictionary, TrackingParticipant tracking) { WorkflowApplication instance = null; DynamicActivity dynamicActivity = tool.activityByXaml(xamlString) as DynamicActivity; if (dictionary != null) { instance = new WorkflowApplication(dynamicActivity, dictionary); } else { instance = new WorkflowApplication(dynamicActivity); } instance.Aborted = aborted; instance.Completed = completed; instance.OnUnhandledException = onUnhandledException; instance.PersistableIdle = persistableIdle; instance.Unloaded = unloaded; if (tracking != null) { instance.Extensions.Add(tracking); } return(instance); }
public static IDictionary <string, object> ExecuteXaml(string xamlFilepath, IDictionary <string, object> data) { string workflowXaml = File.ReadAllText(xamlFilepath); DynamicActivity workflow = Load(workflowXaml); return(WorkflowInvoker.Invoke(workflow, data)); }
internal static DynamicActivity ConvertToDynamicActivity(this ActivityBuilder activityBuilder) { DynamicActivity result = new DynamicActivity(); ActivityBuilderExtensions.ConvertActivityBuilderToDynamicActivity(activityBuilder, result); return(result); }
protected override void LoadAndExecute() { MemoryStream ms = new MemoryStream(ASCIIEncoding.Default.GetBytes(this.workflowDesigner.Text)); DynamicActivity workflowToRun = ActivityXamlServices.Load(ms) as DynamicActivity; WorkflowInspectionServices.CacheMetadata(workflowToRun); this.workflowApplication = new WorkflowApplication(workflowToRun); this.workflowApplication.Extensions.Add(this.output); this.workflowApplication.Completed = this.WorkflowCompleted; this.workflowApplication.OnUnhandledException = this.WorkflowUnhandledException; this.workflowApplication.Aborted = this.WorkflowAborted; this.workflowApplication.Extensions.Add(this.InitialiseVisualTrackingParticipant(workflowToRun)); try { this.running = true; this.workflowApplication.Run(); } catch (Exception e) { this.output.WriteLine(ExceptionHelper.FormatStackTrace(e)); StatusViewModel.SetStatusText(Resources.ExceptionInDebugStatus, this.workflowName); } }
/// <summary> /// Only invoke from the server! /// </summary> public void CompileExpressions <TResult>(DynamicActivity <TResult> dynamicActivity, Guid resourceID) { if (dynamicActivity != null) { FixAndCompileExpressions(dynamicActivity, resourceID); } }
void Awake() { instance = this; if (Growup) { btns.Add("Growup", Growup); } if (Continuous) { btns.Add("Continuous", Continuous); } if (Leveling) { btns.Add("Leveling", Leveling); } if (Recharge) { btns.Add("Recharge", Recharge); } if (Consumption) { btns.Add("Consumption", Consumption); } if (Returnmoney) { btns.Add("Returnmoney", Returnmoney); } }
/// <summary> /// Only invoke from the server! /// </summary> public void CompileExpressions <TResult>(DynamicActivity <TResult> dynamicActivity) { if (dynamicActivity != null) { FixAndCompileExpressions(dynamicActivity); } }
/// <summary> /// Only invoke from the server! /// </summary> public void CompileExpressions(DynamicActivity dynamicActivity) { if (dynamicActivity != null) { FixAndCompileExpressions(dynamicActivity); } }
/// <summary> /// Gets or sets the arguments of the child workflow. /// </summary> /// <value> /// The child arguments. /// </value> /// <summary> /// Creates and validates a description of the activity’s arguments, variables, child activities, and activity delegates. /// </summary> /// <param name="metadata">The activity’s metadata that encapsulates the activity’s arguments, variables, child activities, and activity delegates.</param> protected override void CacheMetadata(NativeActivityMetadata metadata) { foreach (string argumentKey in this.ChildArguments.Keys) { Argument argument = this.ChildArguments[argumentKey]; RuntimeArgument runtimeArgument = new RuntimeArgument(argumentKey, argument.ArgumentType, argument.Direction); metadata.Bind(argument, runtimeArgument); metadata.AddArgument(runtimeArgument); } try { DynamicActivity dynamicActivity = this.LoadDynamicActivityFromCache(); if (dynamicActivity != null) { this.Validate(metadata, dynamicActivity); } else { metadata.AddValidationError(Resources.SpecifyValidWorkflowValidationErrorText); } } catch (Exception ex) { metadata.AddValidationError(string.Format(Resources.FailedToLoadWorkflowValidationErrorText, ex.Message)); } }
public static void CompileExpressions(DynamicActivity dynamicActivity, params Assembly[] references) { // See https://docs.microsoft.com/en-us/dotnet/framework/windows-workflow-foundation/csharp-expressions string activityName = dynamicActivity.Name; string activityType = activityName.Split('.').Last() + "_CompiledExpressionRoot"; string activityNamespace = string.Join(".", activityName.Split('.').Reverse().Skip(1).Reverse()); TextExpressionCompilerSettings settings = new TextExpressionCompilerSettings { Activity = dynamicActivity, Language = "C#", ActivityName = activityType, ActivityNamespace = activityNamespace, RootNamespace = null, GenerateAsPartialClass = false, AlwaysGenerateSource = true, ForImplementation = true }; // add assembly references TextExpression.SetReferencesForImplementation(dynamicActivity, references.Select(a => (AssemblyReference)a).ToList()); // Compile the C# expression. var results = new TextExpressionCompiler(settings).Compile(); if (results.HasErrors) { throw new Exception("Compilation failed."); } // attach compilation result to live activity var compiledExpression = (ICompiledExpressionRoot)Activator.CreateInstance(results.ResultType, new object[] { dynamicActivity }); CompiledExpressionInvoker.SetCompiledExpressionRootForImplementation(dynamicActivity, compiledExpression); }
private void InitializeComponents() { RuntimeTriggers = new List <IUmlTrigger>(); Resources = new List <ISharedResource>(); RuntimeData = new ExpandoObject(); // Setup the behavior to start machine execution. ExecuteBehavior = new DynamicActivity("Execute", EnterInitialNode) { LogType = LogType }; ExecuteBehavior.Faulted += HandleExecuteInitialBehaviorFaulted; // This makes every QuitTransition reactive to this machine's "Quitting" event. FinishTransitionTrigger = new QuitHandlingTrigger("Finishing", this) { LogType = LogType }; // This allows a QuitTransition to fire if the machine's CompletionCause is set or if it finishes. DefaultFinishConstraint = new DynamicConstraint <DynamicActivityMachine>("Default Finish Constraint", this, CheckMachineCanFinish) { SuppressLogging = true }; // This ensures that a CompletionCause is set (not pending) before FinalNode is entered (and before its completion behavior is run). FinishTransitionEffect = new DynamicActivity("SetCompletionCauseFinished", RunFinishTransitionEffect) { LogType = LogType }; // This ensures that the machine's state is still running and that a completion cause is still pending. DefaultContinueConstraint = new DynamicConstraint <DynamicActivityMachine>("Default Continue Constraint", this, CheckMachineCanNotFinish) { SuppressLogging = true }; }
public bool Initialize(string workflowCode) { if (string.IsNullOrEmpty(workflowCode)) { return(false); } //throw new OperationException("WorkflowCode is null."); string workflowXaml; using (var mgr = (IXamlManager <BPWorkflow>)IoC.Instance.Resolve <IBaseManager <BPWorkflow> >()) { var wf = mgr.Get(workflowCode); if (wf == null) { //throw new OperationException("Workflow с кодом '{0}' не существует!", workflowCode); return(false); } workflowXaml = mgr.GetXaml(workflowCode); } if (string.IsNullOrEmpty(workflowXaml)) { //throw new DeveloperException("Получили пустой workflow."); return(false); } using (var reader = new StringReader(workflowXaml)) _activity = (DynamicActivity)ActivityXamlServices.Load(reader); return(true); }
public PolicyExpressionEvaluator(string expression) { var paramVariable = new Variable <Policy>(ParamName); var resultVariable = new Variable <double>(ResultName); var daRoot = new DynamicActivity() { Name = "DemoExpressionActivity", Properties = { new DynamicActivityProperty() { Name = ParamName, Type = typeof(InArgument <Policy>) }, new DynamicActivityProperty() { Name = ResultName, Type = typeof(OutArgument <double>) } }, Implementation = () => new Assign <double>() { To = new ArgumentReference <double>() { ArgumentName = ResultName }, Value = new InArgument <double>(new CSharpValue <double>(expression)) } }; CSharpExpressionTools.CompileExpressions(daRoot, typeof(Policy).Assembly); this.Activity = daRoot; }
/// <summary> /// Creates a default routine. /// </summary> /// <returns>Default routine</returns> public virtual DynamicActivity CreateDefaultRoutine() { DynamicActivity da = new DynamicActivity() { Implementation = () => new Sequence { } }; // add in arguments foreach (var item in SystemInArguments) { da.Properties.Add(new DynamicActivityProperty { Name = item.Name, Type = typeof(InArgument <>).MakeGenericType(item.ArgumentType) }); } // add out arguments foreach (var item in SystemOutArguments) { da.Properties.Add(new DynamicActivityProperty { Name = item.Name, Type = typeof(OutArgument <>).MakeGenericType(item.ArgumentType) }); } return(da); }
public static Activity CreateSalutationRules(List <SalutationAssignmentRule> rules) { var inProperty = new DynamicActivityProperty { Name = "Person", Type = typeof(InArgument <Person>) }; var activity = new DynamicActivity() { Properties = { inProperty } }; Common.AddVbSetting(activity); var sequence = new Sequence(); activity.Implementation = () => sequence; // Sort descending - those added first are lowest priority var sortedRules = rules.OrderByDescending(p => p.Priority).ToList(); // Convert to if-activities and add to sequence foreach (var inRule in sortedRules) { var outRule = RuleConverter.ToIfActivity(inRule); sequence.Activities.Add(outRule); } return(activity); }
private static void AttachNewInstance(Type compiledResultType, DynamicActivity dynamicActivity) { /* * https://docs.microsoft.com/en-us/dotnet/framework/windows-workflow-foundation/csharp-expressions */ // Create an instance of the new compiled expression type. ICompiledExpressionRoot compiledExpressionRoot = Activator .CreateInstance ( compiledResultType , new object[] { dynamicActivity } ) as ICompiledExpressionRoot; // Attach it to the activity. CompiledExpressionInvoker .SetCompiledExpressionRootForImplementation ( dynamicActivity , compiledExpressionRoot ); }
private static bool TryGetCompiledResultType ( DynamicActivity activity , out Type type ) { type = null; var settings = GetCompilerSettings(activity); var results = new TextExpressionCompiler (settings) .Compile(); var r = results.HasErrors; if (!r) { type = results .ResultType; r = (type == null); } if (r) { throw new Exception("Compilation failed."); } return(r); }
GetCompilerSettings ( DynamicActivity dynamicActivity ) { // activityName is the Namespace.Type of the activity that contains the // C# expressions. For Dynamic Activities this can be retrieved using the // name property , which must be in the form Namespace.Type. string activityName = dynamicActivity.Name; // Split activityName into Namespace and Type.Append _CompiledExpressionRoot to the type name // to represent the new type that represents the compiled expressions. // Take everything after the last . for the type name. string activityType = activityName.Split('.').Last() + "_CompiledExpressionRoot"; // Take everything before the last . for the namespace. string activityNamespace = string.Join(".", activityName.Split('.').Reverse().Skip(1).Reverse()); return (new TextExpressionCompilerSettings { Activity = dynamicActivity, Language = "C#", ActivityName = activityType, ActivityNamespace = activityNamespace, RootNamespace = null, GenerateAsPartialClass = false, AlwaysGenerateSource = true, ForImplementation = true }); }
/// <summary> /// Creates a new Workflow Application instance and executes the Current Workflow /// </summary> private void CmdWorkflowRun(object sender, ExecutedRoutedEventArgs e) { //get workflow source from designer CustomWfDesigner.Instance.Flush(); MemoryStream workflowStream = new MemoryStream(ASCIIEncoding.Default.GetBytes(CustomWfDesigner.Instance.Text)); ActivityXamlServicesSettings settings = new ActivityXamlServicesSettings() { CompileExpressions = true }; DynamicActivity activityExecute = ActivityXamlServices.Load(workflowStream, settings) as DynamicActivity; //configure workflow application consoleExecutionLog.Text = String.Empty; consoleOutput.Text = String.Empty; _executionLog = new CustomTrackingParticipant(); _wfApp = new WorkflowApplication(activityExecute); _wfApp.Extensions.Add(_executionLog); _wfApp.Completed = WfExecutionCompleted; //execute _wfApp.Run(); //enable timer for real-time logging _timer.Start(); }
public IDev2Activity Parse(DynamicActivity dynamicActivity, List <IDev2Activity> seenActivities) { try { var chart = WorkflowInspectionServices.GetActivities(dynamicActivity).FirstOrDefault() as Flowchart; if (chart != null) { if (chart.StartNode == null) { return(null); } var start = chart.StartNode as FlowStep; if (start != null) { var tool = ParseTools(start, seenActivities); return(tool.FirstOrDefault()); } var flowstart = chart.StartNode as FlowSwitch <string>; if (flowstart != null) { return(ParseSwitch(flowstart, seenActivities).FirstOrDefault()); } var flowdec = chart.StartNode as FlowDecision; return(ParseDecision(flowdec, seenActivities).FirstOrDefault()); } return(null); } catch (InvalidWorkflowException e) { Dev2Logger.Log.Error(e); throw; } }
public static void ParameterlessDelay() { //Define the input argument for the activity var textOut = new InArgument <string>(); //Create the activity, property, and implementation Activity dynamicWorkflow = new DynamicActivity() { Implementation = () => new Sequence() { Activities = { new Delay() { Duration = new InArgument <TimeSpan>(new TimeSpan(200)) }, new WriteLine() { Text = new InArgument <string>("Delay was successful.") } } } }; //Execute the activity with a parameter dictionary WorkflowInvoker.Invoke(dynamicWorkflow); }
public static void RunDynamicWriteLine() { //Define the input argument for the activity var textOut = new InArgument <string>(); //Create the activity, property, and implementation Activity dynamicWorkflow = new DynamicActivity() { Properties = { new DynamicActivityProperty { Name = "Text", Type = typeof(InArgument <String>), Value = textOut } }, Implementation = () => new Sequence() { Activities = { new WriteLine() { Text = new InArgument <string>(env => textOut.Get(env)) } } } }; //Execute the activity with a parameter dictionary WorkflowInvoker.Invoke(dynamicWorkflow, new Dictionary <string, object> { { "Text", "Hello World!" } }); }
private static void ValidateWorlflow(string xamlFile) { List <string> listError = new List <string>(); DynamicActivity activity = null; try { // load the xaml activity = System.Activities.XamlIntegration.ActivityXamlServices.Load(new StringReader(xamlFile)) as DynamicActivity; } catch (Exception ex) { listError.Add("In the workflow contains following errors and warnings :"); listError.Add(ex.Message); // logger.Error("Unable to load workflow", ex); // throw new InvalidWorkflowException("Workflow is not valid", ex); } // validate the activity through ActivityValidationServices System.Activities.Validation.ValidationResults results = System.Activities.Validation.ActivityValidationServices.Validate(activity); // checking whether workflow has any errors or not if (results.Errors.Count > 0) { listError.Add("In the workflow contains following errors and warnings :"); foreach (System.Activities.Validation.ValidationError error in results.Errors) { listError.Add(error.Message); } // adding worklfow warnings in the listError foreach (System.Activities.Validation.ValidationError warning in results.Warnings) { listError.Add(warning.Message); } } }
public WorkflowEntity() { MemoryStream workflowStream = new MemoryStream(ASCIIEncoding.Default.GetBytes(Helpers.CustomWfDesigner.Instance.Text)); activityExecute = ActivityXamlServices.Load(workflowStream) as DynamicActivity; _wfApp = new WorkflowApplication(activityExecute); wfElementToSourceLocationMap = UpdateSourceLocationMappingInDebuggerService(activityExecute); }