示例#1
0
        static void Main()
        {
            Variable<string> v = new Variable<string>();
            Sequence s = new Sequence()
            {
                Variables = { v },
                Activities =
                {
                    new Assign<string>()
                    {
                        To = v,
                        Value = "hello, world"
                    },
                    new Interop()
                    {
                        ActivityType = typeof(WriteLine),
                        ActivityProperties =
                        {
                            // Bind the Text property of the WriteLine to the Variable v
                            { "Text", new InArgument<string>(v) }
                        },
                        ActivityMetaProperties =
                        {
                            // Provide a value for the Name meta-property of the WriteLine
                            { "Name", "WriteLine" }
                        }
                    }
                }
            };

            WorkflowInvoker.Invoke(s);
            Console.WriteLine("Press [enter] to exit");
            Console.ReadLine();
        }
示例#2
0
 private static WorkflowService CreateService()
 {
     Variable<string> message = new Variable<string> { Name = "message" };
     Receive receiveString = new Receive
     {
         OperationName = "Print",
         ServiceContractName = XName.Get("IPrintService", "http://tempuri.org/"),
         Content = new ReceiveParametersContent
         {
             Parameters = 
             {
                 {"message", new OutArgument<string>(message)}
             }
         },
         CanCreateInstance = true
     };
     Sequence workflow = new Sequence()
     {
         Variables = { message },
         Activities =
         {    
             receiveString,    
             new WriteLine                        
             {    
                 Text = new InArgument<string>(env =>("Message received from Client: " + message.Get(env)))   
             },
         },
     };
     return new WorkflowService
     {
         Name = "PrintService",
         Body = workflow
     };
 }
        public void TestAsyncDoSomethingNotWaitInSequence()
        {
            System.Diagnostics.Debug.WriteLine("TestAsyncDoSomethingNotWaitInSequence");
            var a = new AsyncDoSomethingNotWait();
            var s = new System.Activities.Statements.Sequence()
            {
                Activities =
                {
                    new Plus()
                    {
                        X = 2, Y = 3
                    },
                    a,
                    new Multiply()
                    {
                        X = 3, Y = 7
                    },
                },
            };

            var r = WorkflowInvoker.Invoke(s);

            System.Diagnostics.Debug.WriteLine("After AsyncDoSomethingNotWait in Sequence invoke");
            //check the log file, the invoker will just run 3 activities one by one, and waiting for a to finish, though the key function of a is running in a new thread
            System.Threading.Thread.Sleep(1100);
        }
        public void Upload_ValidPackage_PackageUrl()
        {
            // Arrange 
            var keys = new Variable<StorageServiceKeys> { Default = null, Name = "Keys" };

            var sequence = new Sequence
            {
                Variables =
                {
                    keys
                },

                Activities =
                {
                    new GetStorageKeys
                    {
                        SubscriptionId = string.Empty,
                        CertificateThumbprintId = string.Empty,
                        ServiceName = string.Empty,
                        StorageKeys = keys
                    },
                    new UploadPackageToBlobStorage
                    {
                        SubscriptionId = string.Empty,
                        CertificateThumbprintId = string.Empty,
                        LocalPackagePath = string.Empty,
                        StorageServiceName = string.Empty,
                        StorageKeys = keys
                    }
                }
            };

            // Act
            IDictionary<string, object> results = WorkflowInvoker.Invoke(sequence, new Dictionary<string, object>());
        }
        public void TestAsyncHttpGetInSequence()
        {
            System.Diagnostics.Debug.WriteLine("TestAsyncHttpGetInSequence2");
            var a = new AsyncHttpGet()
            {
                Uri = "http://fonlow.com"
            };
            var s = new System.Activities.Statements.Sequence()
            {
                Activities =
                {
                    new WriteLine()
                    {
                        Text = "Before AsyncHttpGet", TextWriter = new InArgument <System.IO.TextWriter>((c) => new Fonlow.Utilities.TraceWriter())
                    },
                    a,
                    new WriteLine()
                    {
                        Text = "After AsyncHttpGet", TextWriter = new InArgument <System.IO.TextWriter>((c) => new Fonlow.Utilities.TraceWriter())
                    },
                },
            };

            var r = WorkflowInvoker.Invoke(s);

            System.Diagnostics.Debug.WriteLine("After AsyncHttpGet in Sequence invoke");
            //check the log file, the invoker will just run 3 activities one by one, and waiting for a to finish, though the key function of a is running in a new thread
        }
示例#6
0
        static void Main(string[] args)
        {
            Console.WriteLine("◆実行したいワークフローを選択してください。");
            Console.WriteLine(" 1: Sequenceのサンプル");
            Console.WriteLine(" 2: Flowchartのサンプル");
            Console.WriteLine(" 3: StateMachineのサンプル");
            Console.Write("何番を実行しますか?:");
            var num = Console.ReadLine();
            Console.WriteLine("");

            Activity act;

            if (num == "1")
            {
                act = new Sequence();
            }
            else if (num == "2")
            {
                act = new Flowchart();
            }
            else if (num == "3")
            {
                act = new StateMachine();
            }
            else
            {
                throw new NotSupportedException();
            }

            //ワークフローの実行
            WorkflowInvoker.Invoke(act);
        }
示例#7
0
        static void Main(string[] args)
        {
            var a = new AsyncHttpGet()
            {
                Uri = "http://fonlow.com"
            };
            var s = new System.Activities.Statements.Sequence()
            {
                Activities =
                {
                    new WriteLine()
                    {
                        Text = "Before AsyncHttpGet"
                    },
                    a,
                    new WriteLine()
                    {
                        Text = "After AsyncHttpGet"
                    },
                },
            };

            System.Activities.WorkflowInvoker.Invoke(s);
            // System.Activities.WorkflowInvoker.Invoke(new AsyncHttpGetWF());

            Console.ReadLine();
        }
示例#8
0
        private static Activity CreateRulesInterop()
        {
            //Create the variables needed to be passed into the 35 Ruleset
            Variable<int> discountLevel = new Variable<int> { Default = 1 };
            Variable<double> discountPoints = new Variable<double> { Default = 0.0 };
            Variable<string> destination = new Variable<string> { Default = "London" };
            Variable<double> price = new Variable<double> { Default = 1000.0 };
            Variable<double> priceOut = new Variable<double> { Default = 0.0 };

            Sequence result = new Sequence
            {
                Variables = {discountLevel, discountPoints, destination, price, priceOut},
                Activities =
                {
                    new WriteLine { Text = new InArgument<string>(env => string.Format("Price before applying Discount Rules = {0}", price.Get(env).ToString())) },
                    new WriteLine { Text = "Invoking Discount Rules defined in .NET 3.5"},
                    new Interop()
                    {
                        ActivityType = typeof(TravelRuleSet),
                        ActivityProperties =
                        {
                            //These bind to the dependency properties of the 35 custom ruleset
                            { "DiscountLevel", new InArgument<int>(discountLevel) },
                            { "DiscountPoints", new InArgument<double>(discountPoints) },
                            { "Destination", new InArgument<string>(destination) },
                            { "Price", new InArgument<double>(price) },
                            { "PriceOut", new OutArgument<double>(priceOut) }
                        }
                    },
                    new WriteLine {Text = new InArgument<string>(env => string.Format("Price after applying Discount Rules = {0}", priceOut.Get(env).ToString())) }
                }
            };
            return result;
        }
        public Activity Create(DependencyObject target)
        {
            string correlationHandleName = ActivityDesignerHelper.GenerateUniqueVariableNameForContext(target, correlationHandleNamePrefix);

            Variable<CorrelationHandle> requestReplyCorrelation = new Variable<CorrelationHandle> { Name = correlationHandleName };
           
            Send send = new Send
            {
                OperationName = "Operation1",
                ServiceContractName = XName.Get("IService", "http://tempuri.org/"),
                CorrelationInitializers =
                {
                    new RequestReplyCorrelationInitializer
                    {
                        CorrelationHandle = new VariableValue<CorrelationHandle> { Variable = requestReplyCorrelation }
                    }
                }
            };

            Sequence sequence = new Sequence()
            {
                Variables = { requestReplyCorrelation },
                Activities =
                {
                    send,
                    new ReceiveReply
                    {      
                        DisplayName = "ReceiveReplyForSend",
                        Request = send,
                    },
                }
            };
            return sequence;
        }
示例#10
0
        private static void CreateService()
        {
            Variable<string> message = new Variable<string> { Name = "message" };
            Variable<string> echo = new Variable<string> { Name = "echo" };

            Receive receiveString = new Receive
            {
                OperationName = "Echo",
                ServiceContractName = "Echo",
                CanCreateInstance = true,
                //parameters for receive
                Content = new ReceiveParametersContent
                {
                    Parameters =
                    {
                        {"message", new OutArgument<string>(message)}
                    }
                }
            };
            Sequence workflow = new Sequence()
            {
                Variables = { message, echo },
                Activities =
                    {
                        receiveString,
                        new WriteLine
                        {
                            Text = new InArgument<string>(env =>("Message received: " + message.Get(env)))
                        },
                        new Assign<string>
                        {
                            Value = new InArgument<string>(env =>("<echo> " + message.Get(env))),
                            To = new OutArgument<string>(echo)
                        },
                        //parameters for reply
                        new SendReply
                        {
                            Request = receiveString,
                            Content = new SendParametersContent
                            {
                                Parameters =
                                {
                                    { "echo", new InArgument<string>(echo) }
                                },
                            }
                        },
                        new WriteLine
                        {
                            Text = new InArgument<string>(env =>("Message sent: " + echo.Get(env)))
                        },
                    },
            };

            service = new WorkflowService
            {
                Name = "Echo",
                Body = workflow
            };
        }
        public void CanProcess_WithConstructor_MustPassRootActivityToCanProcessDelegate()
        {
            Activity root = null;
            var sequence = new Sequence();

            var testee = CreateTestee((a, r) => { root = r; return false; }, (a, r) => { });

            testee.CanProcess(new WriteLine(), sequence);

            root.Should().BeSameAs(sequence);
        }
示例#12
0
        static Activity CreateCodeOnlyWorkflow()
        {
            Variable<Employee> e1 = new Variable<Employee>("Employee1", ctx => new Employee("John", "Doe", 55000.0));
            Variable<Employee> e2 = new Variable<Employee>("Employee2", ctx => new Employee("Frank", "Kimono", 89000.0));
            Variable<SalaryStats> stats = new Variable<SalaryStats>("SalaryStats", ctx => new SalaryStats());
            Variable<Double> v1 = new Variable<double>();

            // The most efficient way of defining expressions in code is via LambdaValue and LambdaReference activities.
            // LambdaValue represents an expression that evaluates to an r-value and cannot be assigned to.
            // LambdaReference represents an expression that evaluates to an l-value and can be the target of an assignment.
            Sequence workflow = new Sequence()
            {
                Variables =
                {
                    e1, e2, stats, v1,
                },

                Activities =
                {
                    new WriteLine()
                    {
                        Text = new LambdaValue<string>(ctx => e1.Get(ctx).FirstName + " " + e1.Get(ctx).LastName + " earns " + e1.Get(ctx).Salary.ToString("$0.00")),
                    },
                    new WriteLine()
                    {
                        Text = new LambdaValue<string>(ctx => e2.Get(ctx).FirstName + " " + e2.Get(ctx).LastName + " earns " + e2.Get(ctx).Salary.ToString("$0.00")),
                    },
                    new Assign<double>()
                    {
                        To = new LambdaReference<double>(ctx => stats.Get(ctx).MinSalary),
                        Value = new LambdaValue<double>(ctx => Math.Min(e1.Get(ctx).Salary, e2.Get(ctx).Salary))
                    },
                    new Assign<double>()
                    {
                        To = new LambdaReference<double>(ctx => stats.Get(ctx).MaxSalary),
                        Value = new LambdaValue<double>(ctx => Math.Max(e1.Get(ctx).Salary, e2.Get(ctx).Salary))
                    },
                    new Assign<double>()
                    {
                        To = new LambdaReference<double>(ctx => stats.Get(ctx).AvgSalary),
                        Value = new LambdaValue<double>(ctx => (e1.Get(ctx).Salary + e2.Get(ctx).Salary) / 2.0)
                    },
                    new WriteLine()
                    {
                        Text = new LambdaValue<string>(ctx => String.Format(
                            "Salary statistics: minimum salary is {0:$0.00}, maximum salary is {1:$0.00}, average salary is {2:$0.00}",
                            stats.Get(ctx).MinSalary, stats.Get(ctx).MaxSalary, stats.Get(ctx).AvgSalary))
                    }
                },
            };

            return workflow;
        }
        public void GetExtensionsReturnsExtensionsCollection()
        {
            const string BookmarkName = "Test";

            var activity = new Sequence
                {
                    Activities =
                        {
                            new ActivityExtensionTest { AddExtensionProvider = true },
                            new TestBookmark<int> { BookmarkName = BookmarkName },
                            new ActivityExtensionTest { AddExtensionProvider = true },
                        }
                };

            var traceTrackingParticipant = new TraceTrackingParticipant();
            var listTrackingParticipant = new ListTrackingParticipant();

            var workflowApplication = new WorkflowApplication(activity);

            // Add a couple of singleton extensions
            workflowApplication.Extensions.Add(traceTrackingParticipant);
            workflowApplication.Extensions.Add(listTrackingParticipant);

            // foreach (var extension in workflowApplication.Extensions)
            // {
            // Doh! this won't work
            // foreach statement cannot operate on variables of type
            // 'System.Activities.Hosting.WorkflowInstanceExtensionManager'
            // because 'System.Activities.Hosting.WorkflowInstanceExtensionManager'
            // does not contain a public definition for 'GetEnumerator'
            // }

            // Run it so that the activity will create an extension
            workflowApplication.RunEpisode(BookmarkName, Constants.Timeout);

            // Resume and run to completion
            workflowApplication.ResumeEpisodeBookmark(BookmarkName, 1);

            // Now I can get the Singleton Extensions as a collection
            var extensions = workflowApplication.GetSingletonExtensions();
            Assert.IsNotNull(extensions);
            Assert.AreEqual(2, extensions.Count);

            // Note: Extensions created by AddDefaultExtensionProvider will not appear in the collection
            Assert.IsTrue(extensions.Contains(traceTrackingParticipant));
            Assert.IsTrue(extensions.Contains(listTrackingParticipant));

            foreach (var extension in extensions)
            {
                Debug.WriteLine("Found singleton extension " + extension);
            }
        }
        public ActivityInjectorTest()
        {
            this.extension = new Mock<IActivityInjectorExtension>();
            this.anotherExtension = new Mock<IActivityInjectorExtension>();
            this.injectOnKernelExtension = new Mock<IInjectOnKernelExtension>();

            this.activityResolver = new Mock<IActivityResolver>();

            this.rootActivity = new Sequence();
            this.childActivity = new TestActivityWithDependencyAndAttribute();

            this.testee = new ActivityInjector(this.activityResolver.Object, new List<IActivityInjectorExtension> { this.extension.Object, this.injectOnKernelExtension.Object, this.anotherExtension.Object });
        }
        public void TypeNameOptionAddsTypeFullName()
        {
            var activity = new Sequence();
            var host = WorkflowInvokerTest.Create(activity);
            var tracker = new ActivityStateTracker();
            host.Extensions.Add(tracker);

            host.TestActivity();

            var record = tracker.Records[0];

            var actual = record.ToFormattedString(TrackingOption.Default | TrackingOption.TypeName);
            var index = actual.IndexOf("(System.Activities.Statements.Sequence)", StringComparison.Ordinal);
            Assert.AreEqual(40, index);
        }
示例#16
0
        static Sequence CreateWorkflow()
        {
            Sequence workflow = new Sequence
            {
                Activities =
                {
                    new WriteActivity
                    {
                        BookmarkName = "hello"
                    }
                }
            };

            return workflow;
        }
        public void WhenIdleWithNoBookmarksContainsBookmarkShouldReturnFalseOnNoMatch()
        {
            var found = false;

            var activity = new Sequence { Activities = { new TestAsync { Sleep = 10 }, new WriteLine() } };

            var host = new WorkflowApplication(activity)
                {
                   Idle = args => found = args.ContainsBookmark("No Bookmarks Should Match")
                };

            host.RunEpisode(TimeSpan.FromMilliseconds(50000));

            Assert.IsFalse(found);
        }
        private static void runTerminate()
        {
            AutoResetEvent waitForWorkflow = new AutoResetEvent(false);

            System.Activities.Statements.Sequence seq = new System.Activities.Statements.Sequence()
            {
                Activities =
                {
                    new System.Activities.Statements.TerminateWorkflow
                    {
                        Exception = new InArgument <Exception>(context => new TAC.ApplicationException()),
                        Reason    = new InArgument <string>("just because"),
                    },
                    new System.Activities.Statements.WriteLine()
                    {
                        Text = "Hello"
                    },
                }
            };

            try
            {
                WorkflowApplication instance = new WorkflowApplication(seq)
                {
                    Completed = delegate(WorkflowApplicationCompletedEventArgs args)
                    {
                        Console.WriteLine("Completed workflow status: " + args.CompletionState);
                        if (args.CompletionState == ActivityInstanceState.Faulted)
                        {
                            Console.WriteLine("Termination Inner exception: " + args.TerminationException.InnerException.GetType());
                            Console.WriteLine("Termination exception Reason is: " + args.TerminationException.Message);
                            Console.WriteLine("Termination exception: " + args.TerminationException);
                        }
                        waitForWorkflow.Set();
                    }
                };
                Console.WriteLine("Starting");
                instance.Run();
                waitForWorkflow.WaitOne(); // Complete
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception is here!");
                Console.WriteLine("Type = {0} , Message = {1} , RealException is: {2}", e.GetType(), e.Message, e.InnerException.GetType());
            }

            Console.ReadLine();
        }
示例#19
0
        static Sequence CreateWorkflow()
        {
            Sequence workflow = new Sequence
            {
                DisplayName = "CreationService",
                Activities =
                {
                    new WriteLine
                    {
                        Text = "Hello World"
                    }
                }
            };

            return workflow;
        }
示例#20
0
        public static Activity CreateBody()
        {
            Variable<PurchaseOrder> purchaseOrder = new Variable<PurchaseOrder> { Name = "po" };

            Sequence sequence = new Sequence
            {
                Variables =
                {
                    purchaseOrder
                },

                Activities =
                {
                    new Receive
                    {
                        OperationName = "SubmitPurchaseOrder",
                        ServiceContractName = XName.Get(poContractDescription.Name),
                        CanCreateInstance = true,
                        Content = new ReceiveParametersContent
                        {
                            Parameters =
                            {
                                {"po", new OutArgument<PurchaseOrder>(purchaseOrder)}
                            }
                        }
                    },

                    new WriteLine
                    {
                       Text = new InArgument<string> (e=>"Order is received\nPO number = " + purchaseOrder.Get(e).PONumber
                           + " Customer Id = " + purchaseOrder.Get(e).CustomerId)
                    },

                    new Persist(),

                    new ExceptionThrownActivity(),

                    new WriteLine
                    {
                        Text = new InArgument<string>("Order processing is complete")
                    }
                }
            };

            return sequence;
        }
示例#21
0
        //  Workflow variable by Linq
        public void VariableByLinq()
        {
            // Linq treats local variable with special syntax.
            // See comment in LeafHelper.GetMemberAccessVariableExpression for more info.
            // The purpose test is to use real compiler generated lambda expression.
            Variable <string> var = new Variable <string>()
            {
                Name    = "var",
                Default = "Linq var test"
            };

            Expression <Func <ActivityContext, string> > expression = (env) => var.Get(env);

            System.Activities.Statements.Sequence expectedSequence = new System.Activities.Statements.Sequence()
            {
                Variables =
                {
                    var
                },
                Activities =
                {
                    new WriteLine()
                    {
                        Text = var
                    }
                }
            };

            System.Activities.Statements.Sequence actualSequence = new System.Activities.Statements.Sequence()
            {
                Variables =
                {
                    var
                },
                Activities =
                {
                    new WriteLine()
                    {
                        Text = ExpressionServices.Convert(expression)
                    }
                }
            };

            ExpressionTestRuntime.ValidateActivity(expectedSequence, actualSequence);
        }
        public void ModelChanged(object sender, ModelChangedEventArgs e)
        {
            //mainSequence = ((System.Activities.Presentation.Model.) (sender)).Root;

                mainSequence = (e.ModelChangeInfo).Value.Root.GetCurrentValue() as Sequence;

            //workflowDesigner.Context.Items.Load(mainSequence);

            //{
            //    ModelItem item = e.ItemsAdded.FirstOrDefault<ModelItem>();
            //    var test = item.GetCurrentValue() as HttpRequestActivity;

            //    if (test != null && test.Id == null)
            //    {
            //        //do whatever initialization logic is needed here
            //    }
            //}
        }
示例#23
0
        static void Main()
        {
            Sequence wf = new Sequence
            {
                Activities =
                {
                    new If
                    {
                        Condition = true
                    },
                    new Pick
                    {
                        Branches =
                        {
                            new PickBranch
                            {
                                Trigger = new WriteLine
                                {
                                    Text = "When this completes..."
                                },
                                Action = new WriteLine
                                {
                                    Text = "... do this."
                                }
                            }
                        }
                    }
                }
            };

            // ValidationSettings enables the host to customize the behavior of ActivityValidationServices.Validate.
            ValidationSettings validationSettings = new ValidationSettings
            {
                // AdditionalConstraints enables the host to add specific validation logic (a constraint) to a specify type of activity in the Workflow.
                AdditionalConstraints =
                    {
                        {typeof(If), new List<Constraint> {ConstraintsLibrary.ConstraintError_IfShouldHaveThenOrElse()}},
                        {typeof(Pick), new List<Constraint> {ConstraintsLibrary.ConstraintWarning_PickHasOneBranch()}}
                    }
            };

            ValidationResults results = ActivityValidationServices.Validate(wf, validationSettings);
            PrintResults(results);
        }
 public HttpRequestSequence(HttpRequestSequenceViewModel httpRequestSequenceViewModel, IEventAggregator eventAggregator, IFileService fileService)
 {
     mainSequence = new Sequence();
     this.httpRequestSequenceViewModel = httpRequestSequenceViewModel;
     this.eventAggregator = eventAggregator;
     this.fileService = fileService;
     httpRequestSequenceViewModel.MainSequence = mainSequence;
     DataContext = httpRequestSequenceViewModel;
     RegisterMetadata();
     InitializeComponent();
     AddDesigner();
     AddToolBox();
     //AddPropertyInspector();
     workflowDesigner.Context.Items.Subscribe<Selection>(SelectionChanged);
     var modelService = workflowDesigner.Context.Services.GetService<ModelService>();
     if (modelService != null)
     {
         modelService.ModelChanged += ModelChanged;
     }
 }
        public void WhenIdleWithBookmarkContainsBookmarkShouldReturnTrueOnMatch()
        {
            const string Expected = "TestBookmark";
            var found = false;

            var activity = new Sequence
                {
                   Activities = {
                                     new TestBookmark<int> { BookmarkName = Expected }, new WriteLine()
                                 }
                };

            var host = new WorkflowApplication(activity) { Idle = args => found = args.ContainsBookmark(Expected) };

            // Run the workflow until idle with the bookmark
            var result = host.RunEpisode(Expected, TimeSpan.FromMilliseconds(100));

            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(WorkflowIdleEpisodeResult));
            Assert.AreEqual(ActivityInstanceState.Executing, result.State);
            Assert.IsTrue(found);
        }
        public void FormatStringShouldBeInvoked()
        {
            const string Expected = "0: WorkflowInstance \"Sequence\" is Started";

            var activity = new Sequence();
            var host = WorkflowInvokerTest.Create(activity);
            var observer = new Observer();
            host.Extensions.Add(observer);
            WorkflowTrace.Options = TraceOptions.ThreadId;
            host.Extensions.Add(new TraceTrackingParticipant());

            try
            {
                host.TestActivity(Constants.Timeout);
                Assert.AreEqual(5, observer.Records.Count);
                Assert.AreEqual(Expected, observer.Records[0]);
            }
            finally
            {
                host.Tracking.Trace();
            }
        }
        public void GetRecordNumberNotIncludedWhenNoOptionRecordNumber()
        {
            // Arrange
            var activity = new Sequence();
            var host = WorkflowApplicationTest.Create(activity);
            host.TestWorkflowApplication.RunEpisode();
            var record = host.Tracking.Records.First();
            string actual = null;

            try
            {
                // Act
                actual = record.ToFormattedString(TrackingOption.None);

                // Assert
                Assert.IsFalse(actual.StartsWith("0: "));
            }
            finally
            {
                WorkflowTrace.Information("Actual is <{0}>", actual);
                host.Tracking.Trace();
            }
        }
        public void GetRecordNumberIncludedWhenOptionRecordNumber()
        {
            // Arrange
            var activity = new Sequence();
            var listTrackingParticipant = new ListTrackingParticipant();
            var host = new WorkflowInvokerTest(activity);
            host.Extensions.Add(listTrackingParticipant);
            host.TestActivity();
            var record = listTrackingParticipant.Records.First();

            try
            {
                // Act
                var actual = record.ToFormattedString(TrackingOption.RecordNumber);

                // Assert
                Assert.IsTrue(actual.StartsWith("0: "));
            }
            finally
            {
                listTrackingParticipant.Trace();
            }
        }
示例#29
0
        static WorkflowService GetService()
        {
            Variable<string> incomingMessage = new Variable<string> { Name = "inmessage" };
            Variable<int> outgoingMessage = new Variable<int> { Name = "outmessage" };
            Receive receiveSecureData = new Receive
            {
                OperationName = "AskQuestion",
                ServiceContractName = "ISecuredService",
                CanCreateInstance = true,
                Content = ReceiveContent.Create(new OutArgument<string>(incomingMessage))
            };
            Sequence SecuredWorkFlow = new Sequence()
            {
                Variables = { incomingMessage, outgoingMessage },
                Activities =
                {
                    receiveSecureData,
                    new WriteLine
                    {
                        Text = new InArgument<string>(env =>("Message received: " + incomingMessage.Get(env)))
                    },
                    new SendReply
                    {
                        Request = receiveSecureData,
                        Content = SendContent.Create(new InArgument<int>(4))
                    }
                }
            };

            WorkflowService service = new WorkflowService
            {
                Name = "SecuredService",
                Body = SecuredWorkFlow,
                ConfigurationName = "SecuredService"
            };
            return service;
        }
示例#30
0
        public void AbortShouldThrowObjectDisposed()
        {
            // Arrange
            TestTrace.Arrange();
            var activity = new Sequence();
            var workflow = new WorkflowP1(activity);

            try
            {
                // Act
                TestTrace.Act();
                workflow.Dispose();

                // Assert
                TestTrace.Assert();
                AssertHelper.Throws<ObjectDisposedException>(() => workflow.Abort());
            }
            finally
            {
                TestTrace.Finally();

                // Trace things here
            }
        }
示例#31
0
 private static Sequence CompileRules(RuleSet ruleSet)
 {
     var sequence = new Sequence();
     foreach (var rule in ruleSet.Rules)
     {
         var condition = CompileConditions(rule.TopCondition, ruleSet.Inputs);
         condition.Then = CompileActions(rule, ruleSet.Inputs);
         sequence.Activities.Add(condition);
     }
     return sequence;
 }
示例#32
0
        public void SetDelegateArgument()
        {
            // for using delegate argument

            TheStruct valueType             = new TheStruct();
            int       indiceValue           = 2;
            DelegateInArgument <int> indice = new DelegateInArgument <int>();
            Variable <TheStruct>     var    = VariableHelper.CreateInitialized <TheStruct>("var", valueType);
            TestValueTypeIndexerReference <TheStruct, int> valueTypeIndexerReference = new TestValueTypeIndexerReference <TheStruct, int>()
            {
                OperandLocationVariable = var,
            };

            valueTypeIndexerReference.Indices.Add(new TestArgument <int>(Direction.In, null, (env) => indice.Get(env)));

            int value = 321;
            TestAssign <int> testAssign = new TestAssign <int>()
            {
                ToLocation = valueTypeIndexerReference, Value = value
            };

            TestSequence seq = new TestSequence()
            {
                Activities =
                {
                    testAssign,
                    new TestWriteLine {
                        MessageExpression = ((ctx) => var.Get(ctx)[indiceValue].ToString())
                    }
                }
            };

            System.Activities.Statements.Sequence outerSeq = new System.Activities.Statements.Sequence()
            {
                Variables =
                {
                    var
                },
                Activities =
                {
                    new InvokeAction <int>()
                    {
                        Argument = indiceValue,
                        Action   = new ActivityAction <int>()
                        {
                            Argument = indice,
                            Handler  = seq.ProductActivity
                        }
                    }
                }
            };

            TestCustomActivity testActivity = TestCustomActivity <System.Activities.Statements.Sequence> .CreateFromProduct(outerSeq);

            UnorderedTraces traces = new UnorderedTraces()
            {
                Steps =
                {
                    new UserTrace(value.ToString())
                }
            };

            testActivity.ActivitySpecificTraces.Add(traces);
            ExpectedTrace expectedTrace = testActivity.GetExpectedTrace();

            expectedTrace.AddIgnoreTypes(typeof(ActivityTrace));

            TestRuntime.RunAndValidateWorkflow(testActivity, expectedTrace);
        }
示例#33
0
 private static Sequence CompileActions(Rule rule, Dictionary<string, Type> inputs)
 {
     var sequence = new Sequence();
     foreach (var action in rule.Actions)
     {
         Activity activity;
         switch (action.GetType().Name)
         {
             case "AssignAction":
                 activity = new Assign<string>
                     {
                         To = new OutArgument<string>(new VisualBasicReference<string>(action.LeftHandSide)),
                         Value = new InArgument<string>(action.Value)
                     };
                 break;
             default:
                 throw new Exception("The action type '" + action.GetType().Name + "' has not been implemented");
         }
         sequence.Activities.Add(activity);
     }
     return sequence;
 }
示例#34
0
        static void Main(string[] args)
        {
            //Create a WF with configuration errors
            Sequence wf = new Sequence()
            {
                Activities =
                {
                    new Sequence
                    {
                        DisplayName = "Sequence1"
                    },
                    new If
                    {
                        DisplayName = "If",
                        Condition = new InArgument<bool>(true)
                    },
                    new Switch<bool>
                    {
                        DisplayName = "Switch1",
                        Expression = new InArgument<bool>(true),
                        Default = new WriteLine()
                    },
                    new ForEach<int>
                    {
                        DisplayName = "ForEach2",
                        Values = new InArgument<IEnumerable<int>>((env) => new int[] { 1, 2, 3 })
                    },
                    new Parallel
                    {
                        DisplayName = "Parallel1"
                    },
                    new ParallelForEach<int>
                    {
                        DisplayName = "ParallelForEach1",
                        Values = new InArgument<IEnumerable<int>>((env) => new int[] { 1, 2, 3 })
                    },
                    new Pick
                    {
                        DisplayName = "Pick1",
                        Branches =
                        {
                            new PickBranch
                            {
                                Action = new WriteLine()
                            }
                        }
                    },
                    new Pick
                    {
                        DisplayName = "Pick2"
                    },
                    new WriteLine
                    {
                        DisplayName = "Wr"
                    }
                }
            };

            //Create an instance of Validation Settings.
            ValidationSettings settings = new ValidationSettings()
            {
                //Create value pairs constraints and activity types. We are providing a list of constraints that you want to apply on a specify activity type
                AdditionalConstraints =
                {
                    {typeof(Activity), new List<Constraint> {ConstraintLibrary.ActivityDisplayNameIsNotSetWarning()}},
                    {typeof(ForEach<int>), new List<Constraint> {ConstraintLibrary.ForEachPropertyMustBeSetError<int>()}},
                    {typeof(WriteLine), new List<Constraint> {ConstraintLibrary.WriteLineHasNoTextWarning()}},
                    {typeof(Pick), new List<Constraint> {ConstraintLibrary.PickHasNoBranchesWarning(), ConstraintLibrary.PickHasOneBranchWarning()}},
                    {typeof(Parallel), new List<Constraint> {ConstraintLibrary.ParallelHasNoBranchesWarning()}},
                    {typeof(Switch<bool>), new List<Constraint> {ConstraintLibrary.SwitchHasDefaultButNoCasesWarning<bool>(), ConstraintLibrary.SwitchHasNoCasesOrDefaultWarning<bool>()}},
                    {typeof(If), new List<Constraint> {ConstraintLibrary.IfShouldHaveThenOrElseError()}},
                    {typeof(Sequence), new List<Constraint> {ConstraintLibrary.SequenceIsEmptyWarning()}}
                }
            };

            //Call the Validate method with the workflow you want to validate, and the settings you want to use.
            ValidationResults results = ActivityValidationServices.Validate(wf, settings);
            //Print the validation errors and warning that were generated my ActivityValidationServices.Validate.
            PrintResults(results);
        }
示例#35
0
        // private static RoslynExpressionEditorService _expressionEditorService;
        // private static EditorService _expressionEditorServiceVB;
        public WFDesigner(ClosableTab tab, Workflow workflow, Type[] extratypes)
        {
            this.tab = tab;
            InitializeComponent();
            ;
            WfToolboxBorder.Child = InitializeActivitiesToolbox();
            Workflow = workflow;
            Workflow.OnIdleOrComplete += onIdleOrComplete;
            wfDesigner = new WorkflowDesigner();

            // Register the runtime metadata for the designer.
            new DesignerMetadata().Register();



            DesignerConfigurationService configService = wfDesigner.Context.Services.GetRequiredService <DesignerConfigurationService>();

            configService.TargetFrameworkName             = new System.Runtime.Versioning.FrameworkName(".NETFramework", new Version(4, 5));
            configService.AnnotationEnabled               = true;
            configService.AutoConnectEnabled              = true;
            configService.AutoSplitEnabled                = true;
            configService.AutoSurroundWithSequenceEnabled = true;
            configService.BackgroundValidationEnabled     = true;
            configService.MultipleItemsContextMenuEnabled = true;
            configService.MultipleItemsDragDropEnabled    = true;
            configService.NamespaceConversionEnabled      = true;
            configService.PanModeEnabled                    = true;
            configService.RubberBandSelectionEnabled        = true;
            configService.LoadingFromUntrustedSourceEnabled = false;

            //if (_expressionEditorServiceVB == null) _expressionEditorServiceVB = new EditorService();
            //wfDesigner.Context.Services.Publish<IExpressionEditorService>(_expressionEditorServiceVB);

            wfDesigner.Context.Services.Publish <IExpressionEditorService>(new EditorService());

            if (!string.IsNullOrEmpty(workflow.Xaml))
            {
                wfDesigner.Text = workflow.Xaml;
                wfDesigner.Load();
                //wfDesigner.Load(workflow.Filename);
            }
            else
            {
                Activity wf = new System.Activities.Statements.Sequence {
                };
                var ab      = new ActivityBuilder();
                ab.Name           = workflow.name;
                ab.Implementation = wf;
                AddVBNamespaceSettings(ab, typeof(Action),
                                       typeof(Microsoft.VisualBasic.Collection),
                                       typeof(System.Xml.XmlNode),
                                       typeof(OpenRPA.Workflow),
                                       typeof(OpenRPA.UIElement),
                                       typeof(System.Data.DataSet),
                                       typeof(System.Linq.Enumerable)
                                       );
                AddVBNamespaceSettings(ab, extratypes);

                //if (workflow.language == entity.workflowLanguage.CSharp)
                //{
                //    System.Activities.Presentation.Expressions.ExpressionActivityEditor.SetExpressionActivityEditor(ab, "C#");
                //}
                wfDesigner.Load(ab);
            }
            HasChanged = false;
            wfDesigner.ModelChanged += (sender, e) =>
            {
                HasChanged = true;
                onChanged?.Invoke(this);
            };

            WfDesignerBorder.Child = wfDesigner.View;
            WfPropertyBorder.Child = wfDesigner.PropertyInspectorView;

            OutputMessages = MainWindow.tracing.OutputMessages;
            TraceMessages  = MainWindow.tracing.TraceMessages;


            var modelItem = wfDesigner.Context.Services.GetService <ModelService>().Root;

            workflow.name = modelItem.GetValue <string>("Name");
            tab.Title     = workflow.name;

            wfDesigner.Context.Items.Subscribe <Selection>(new SubscribeContextCallback <Selection>(SelectionChanged));

            WeakEventManager <System.ComponentModel.INotifyPropertyChanged, System.ComponentModel.PropertyChangedEventArgs> .
            AddHandler(MainWindow.tracing, "PropertyChanged", traceOnPropertyChanged);
        }
示例#36
0
        static Activity CreateWF()
        {
            Variable<string> name = new Variable<string>();
            Sequence body = new Sequence
            {
                Variables = { name },
                Activities =
                {
                    new WriteLine { Text = "What is you name? (You have 5 seconds to answer)" },
                    new Pick
                    {
                       Branches =
                       {
                           new PickBranch
                            {
                               Trigger = new ReadString
                               {
                                   Result = name,
                                   BookmarkName = bookmarkName
                               },
                               Action = new WriteLine
                               {
                                   Text = new InArgument<string>(env => "Hello " + name.Get(env))
                               }
                           },
                           new PickBranch
                            {
                               Trigger = new Delay
                               {
                                   Duration = TimeSpan.FromSeconds(5)
                               },
                               Action = new WriteLine
                               {
                                   Text = "Time is up."
                               }
                           }
                       }
                   }
               }
            };

            return body;
        }
示例#37
0
        void CreateImplementation()
        {
            this.bodyClone = Activator.CreateInstance(this.Body.GetType()) as Activity;

            foreach (PropertyInfo pi in this.Body.GetType().GetProperties())
            {
                if (pi.CanWrite)
                {
                    pi.SetValue(this.bodyClone, pi.GetValue(this.Body, null), null);
                }

                if (pi.PropertyType.IsGenericType)
                {
                    Type argType = pi.PropertyType.GetGenericArguments()[0];
                    Type exprRefType = typeof(VisualBasicReference<>).MakeGenericType(argType);
                    Type exprValueType = typeof(VisualBasicValue<>).MakeGenericType(argType);

                    if (pi.PropertyType.GetGenericTypeDefinition() == typeof(InArgument<>))
                    {
                        // only expose InArguments that haven't already been bound
                        if (pi.GetValue(this.Body, null) == null)
                        {
                            // create the Variable and add it internally
                            string variableName = pi.Name;
                            Variable var = Variable.Create(variableName, argType, VariableModifiers.None);
                            this.variables.Add(var);

                            // create the OutArgument by calling the VisualBasicReference<>(string expressionText) constructor and set it on the Receive
                            OutArgument outArg = Argument.Create(argType, ArgumentDirection.Out) as OutArgument;
                            outArg.Expression = (ActivityWithResult)Activator.CreateInstance(exprRefType, variableName);
                            ((ReceiveParametersContent)receive.Content).Parameters.Add(pi.Name, outArg);

                            // create the InArgument by calling the VisualBasicReference<>(string expressionText) constructor and set it to the Variable
                            InArgument inArg = Argument.Create(argType, ArgumentDirection.In) as InArgument;
                            inArg.Expression = (ActivityWithResult)Activator.CreateInstance(exprValueType, variableName);
                            pi.SetValue(this.bodyClone, inArg, null);
                        }

                    }
                    else if (pi.PropertyType.GetGenericTypeDefinition() == typeof(OutArgument<>))
                    {
                        // create the Variable and add it internally
                        string variableName = pi.Name;
                        Variable var = Variable.Create(variableName, argType, VariableModifiers.None);
                        this.variables.Add(var);

                        if (pi.GetValue(this.Body, null) != null)
                        {
                            // copy the OutArgument
                            OutArgument refOutArg = ((OutArgument)pi.GetValue(this.Body, null));

                            string temp = refOutArg.Expression.ResultType.ToString();
                            InArgument assignInArg = Argument.Create(argType, ArgumentDirection.In) as InArgument;
                            assignInArg.Expression = (ActivityWithResult)Activator.CreateInstance(exprValueType, variableName);

                            Assign a = new Assign
                            {
                                To = refOutArg,
                                //To = OutArgument.CreateReference(varRef, pi.Name),
                                Value = assignInArg
                            };

                            assigns.Add(a);
                        }

                        // create an OutArgument by calling the VisualBasicReference<>(string expressionText) constructor and set it to the Variable
                        OutArgument outArg = Argument.Create(argType, ArgumentDirection.Out) as OutArgument;
                        outArg.Expression = (ActivityWithResult)Activator.CreateInstance(exprRefType, variableName);
                        pi.SetValue(this.bodyClone, outArg, null);

                        // create the InArgument by calling the VisualBasicReference<>(string expressionText) constructor and set it on the SendReply
                        InArgument inArg = Argument.Create(argType, ArgumentDirection.In) as InArgument;
                        inArg.Expression = (ActivityWithResult)Activator.CreateInstance(exprValueType, variableName);
                        ((SendParametersContent)reply.Content).Parameters.Add(variableName, inArg);

                    }
                }
            }

            // create internal Sequence and add the variables
            impl = new Sequence();
            foreach (Variable v in this.variables)
            {
                impl.Variables.Add(v);
            }

            // add the Receive
            receive.CanCreateInstance = this.CanCreateInstance;
            receive.OperationName = (this.DisplayName != "OperationScope" ? this.DisplayName : this.Body.DisplayName);
            impl.Activities.Add(receive);

            // add the activity which represents the operation body
            impl.Activities.Add(this.bodyClone);

            // add the Reply
            impl.Activities.Add(reply);

            // add any other Assigns to OutArguments
            foreach (Assign assignToOutArg in this.assigns)
            {
                impl.Activities.Add(assignToOutArg);
            }
        }
示例#38
0
        public void TestPersistenceWithBookmark()
        {
            var x  = 100;
            var y  = 200;
            var t1 = new Variable <int>("t1");

            var plus = new Plus()
            {
                X = x,
                Y = y,
                Z = t1,  //So Output Z will be assigned to t1
            };
            var bookmarkName = NewBookmarkName();
            var a            = new System.Activities.Statements.Sequence()
            {
                Variables =
                {
                    t1
                },
                Activities =
                {
                    new Multiply()
                    {
                        X = 3, Y = 7,
                    },

                    new ReadLine()
                    {
                        BookmarkName = bookmarkName,
                    },

                    plus,
                },
            };


            bool completed1 = false;
            bool unloaded1  = false;
            bool isIdle     = false;

            AutoResetEvent syncEvent = new AutoResetEvent(false);

            var app = new WorkflowApplication(a);

            app.InstanceStore   = WFDefinitionStore.Instance.Store;
            app.PersistableIdle = (eventArgs) =>
            {
                return(PersistableIdleAction.Unload);//so persist and unload
            };

            app.OnUnhandledException = (e) =>
            {
                return(UnhandledExceptionAction.Abort);
            };

            app.Completed = delegate(WorkflowApplicationCompletedEventArgs e)
            {
                unloaded1 = true;
            };

            app.Aborted = (eventArgs) =>
            {
            };

            app.Unloaded = (eventArgs) =>
            {
                unloaded1 = true;
                syncEvent.Set();
            };

            app.Idle = e =>
            {
                Assert.Equal(1, e.Bookmarks.Count);
                isIdle = true;
            };

            //  app.Persist();//This is optional, since Workflow runtime will persist when the execution reach to ReadLine.
            var id = app.Id;

            app.Run();
            syncEvent.WaitOne();

            Assert.False(completed1);
            Assert.True(unloaded1);
            Assert.True(isIdle);
            //At this point, DB WF/InstancesTable has a new record, and the value of column BlockingBookmark contains the bookmarkName

            //Now to use a new WorkflowApplication to load the persisted instance.
            LoadWithBookmarkAndComplete(a, id, bookmarkName, "abc");
            //The record is now deleted by WF runtime.
        }