Example #1
0
        public void FlowDecisionAsStartElement()
        {
            TestFlowchart flowchart1 = new TestFlowchart("flowChart1");

            TestWriteLine w2True  = new TestWriteLine("True", "True will execute");
            TestWriteLine w2False = new TestWriteLine("False", "False wont execute");

            Variable <int> margin = VariableHelper.CreateInitialized <int>("Margin", 10);

            flowchart1.Variables.Add(margin);
            TestFlowConditional flowDecision = new TestFlowConditional(HintTrueFalse.True);

            flowDecision.ConditionExpression = (context => margin.Get(context) > 0);
            TestFlowElement tCond = flowchart1.AddConditionalLink(null, flowDecision, w2True, w2False);

            TestRuntime.RunAndValidateWorkflow(flowchart1);
        }
Example #2
0
//<Snippet1>
        static Activity CreateWF()
        {
            Variable <string> name = new Variable <string>();
            Sequence          body = new Sequence
            {
                Variables  = { name },
                Activities =
                {
                    new WriteLine {
                        Text = "What is your 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);
        }
Example #3
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);

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

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

            ExpressionTestRuntime.ValidateActivity(expectedSequence, actualSequence);
        }
Example #4
0
 private void OnBodyComplete(NativeActivityContext context, ActivityInstance completedInstance)
 {
     IEnumerator<NMElement> _enum = _elements.Get(context);
     if (_enum == null) return;
     bool more = _enum.MoveNext();
     if (more)
     {
         context.ScheduleAction<NMElement>(Body, _enum.Current, OnBodyComplete);
     }
     else
     {
         if (LoopAction != null)
         {
             var allelements = context.GetValue(_allelements);
             context.ScheduleActivity(LoopAction, LoopActionComplete);
         }
     }
 }
Example #5
0
        private void OnBodyComplete(NativeActivityContext context, ActivityInstance completedInstance)
        {
            IEnumerator <SAPElement> _enum = _elements.Get(context);
            bool more = _enum.MoveNext();

            if (more && !breakRequested)
            {
                IncIndex(context);
                context.ScheduleAction <SAPElement>(Body, _enum.Current, OnBodyComplete);
            }
            else
            {
                if (LoopAction != null && !breakRequested)
                {
                    context.ScheduleActivity(LoopAction, LoopActionComplete);
                }
            }
        }
Example #6
0
        /// <summary>
        /// Gets the code for the activity that is responsible for getting the location and executable name
        /// of the devenv version we need
        /// </summary>
        /// <param name="devEnvPathVariable">the variable that holds the dev env path</param>
        /// <param name="logFileLocationVariable">the variable that holds the complete path of the log filePath</param>
        /// <param name="devEnvCommandPathVariable">the variable that holds the path+exec name to be executed</param>
        /// <param name="devEnvArgumentsVariable">the arguments that holds the arguments to be passed to devenv</param>
        /// <returns>the activity</returns>
        private GetDevEnvCallingParameters GetDevEnvCallingParametersBody(Variable <string> devEnvPathVariable, Variable <string> logFileLocationVariable, Variable <string> devEnvCommandPathVariable, Variable <string> devEnvArgumentsVariable)
        {
            return(new GetDevEnvCallingParameters
            {
                DevEnvPath = new InArgument <string>(env => devEnvPathVariable.Get(env)),

                FilePath = new InArgument <string>(env => this.FilePath.Get(env)),
                ProjectPath = new InArgument <string>(env => this.ProjectPath.Get(env)),
                Configuration = new InArgument <string>(env => this.Configuration.Get(env)),
                ProjectConfiguration = new InArgument <string>(env => this.ProjectConfiguration.Get(env)),
                Platform = new InArgument <string>(env => this.Platform.Get(env)),
                Action = new InArgument <VSDevEnvAction>(this.Action),
                OutputFile = new InArgument <string>(logFileLocationVariable),

                DevEnvCommandPath = new OutArgument <string>(devEnvCommandPathVariable),
                Arguments = new OutArgument <string>(devEnvArgumentsVariable)
            });
        }
Example #7
0
        private void OnBodyComplete(NativeActivityContext context, ActivityInstance completedInstance)
        {
            var session = _elements.Get(context);

            if (session == null)
            {
                return;
            }
            string WorkflowInstanceId = context.WorkflowInstanceId.ToString();

            if (session.WorkflowInstanceId != WorkflowInstanceId)
            {
                return;
            }
            session.Disconnect();
            GenericTools.RunUI(session.Close);
            RunPlugin.Sessions.Remove(session);
        }
Example #8
0
        public void WhileInfiniteLoopFaultAfterHundredLoops()
        {
            TestSequence  outerSequence = new TestSequence("sequence1");
            TestSequence  innerSequence = new TestSequence("Seq");
            TestIncrement increment     = new TestIncrement("test increment");

            TestSequence inNestedSequence = new TestSequence("Sequence in Nested while");
            TestThrow <ArithmeticException> throwTestActivity = new TestThrow <ArithmeticException>();


            Variable <int> counter = VariableHelper.CreateInitialized <int>("counter", 0);

            TestWhile whileAct = new TestWhile("while act")
            {
                ConditionExpression = ((env) => ((int)counter.Get(env)) < 200),
                Body = innerSequence,
                HintIterationCount = 200,
            };

            inNestedSequence.Activities.Add(whileAct);
            inNestedSequence.Activities.Add(throwTestActivity);

            TestWhile whileActNested = new TestWhile("while act")
            {
                ConditionExpression = ((env) => (true)),
                Body = inNestedSequence,
                HintIterationCount = 200,
            };

            TestWriteLine writeLine = new TestWriteLine("write hello")
            {
                Message = "Its a small world after all"
            };

            increment.CounterVariable = counter;

            innerSequence.Activities.Add(writeLine);
            innerSequence.Activities.Add(increment);

            outerSequence.Variables.Add(counter);
            outerSequence.Activities.Add(whileActNested);

            TestRuntime.RunAndValidateAbortedException(outerSequence, typeof(ArithmeticException), new Dictionary <string, string>());
        }
        private void Continue(NativeActivityContext context, Bookmark bookmark, object obj)
        {
            var eventArgs = obj as WorkflowNotificationEventArgs;

            if (eventArgs == null || string.CompareOrdinal(eventArgs.NotificationType, WorkflowNotificationObserver.NotificationType.ContentChanged) != 0)
            {
                return;
            }

            ReleaseWait(context, eventArgs.NodeId);

            var count = counter.Get(context) - 1;

            counter.Set(context, count);
            if (count > 0)
            {
                context.CreateBookmark(bookmark.Name, new BookmarkCallback(Continue));
            }
        }
Example #10
0
        public void AddSameElementToParentAndChild()
        {
            TestFlowchart   flowchart1 = new TestFlowchart("flowChart1");
            TestFlowchart   flowchart2 = new TestFlowchart("flowChart2");
            TestWriteLine   w1         = new TestWriteLine("W1", "Executing W1");
            TestFlowElement fStep      = new TestFlowStep(w1);

            flowchart2.Elements.Add(fStep);

            Variable <int> margin = VariableHelper.CreateInitialized <int>("Margin", 10);

            flowchart1.Variables.Add(margin);
            TestFlowConditional flowDecision = new TestFlowConditional(HintTrueFalse.True);

            flowDecision.ConditionExpression = (context => margin.Get(context) > 0);
            TestFlowElement tCond = flowchart1.AddConditionalLink(null, flowDecision, fStep, flowchart2);

            TestRuntime.ValidateInstantiationException(flowchart1, string.Format(ErrorStrings.FlowNodeCannotBeShared, flowchart1.DisplayName, flowchart2.DisplayName));
        }
Example #11
0
        private void ActionFailed(NativeActivityFaultContext faultContext, Exception propagatedexception, ActivityInstance propagatedfrom)
        {
            Int32 currentAttemptCount = _attemptCount.Get(faultContext);
            Int32 maxAttempts         = MaxAttempts.Get(faultContext);

            Type[] exceptionType = ExceptionType.Get(faultContext);

            //Increment and track the count
            currentAttemptCount++;
            _attemptCount.Set(faultContext, currentAttemptCount);

            if (currentAttemptCount >= maxAttempts)
            {
                // There are no further attempts to make
                return;
            }

            if (ShouldRetryAction(exceptionType, propagatedexception) == false)
            {
                _log.Error("Will only retry exception of type '" + exceptionType.ToCSV() + "'. Unhandled type of '" + propagatedexception.GetType().FullName + "' was found.", propagatedexception);
                return;
            }

            faultContext.CancelChild(propagatedfrom);
            faultContext.HandleFault();

            TimeSpan retryInterval = _delayOverrideForUnitTests == null?RetryInterval.Get(faultContext) : _delayOverrideForUnitTests.Value;

            _log.Debug("Retrying in " + retryInterval.TotalSeconds + " seconds due to " + propagatedexception.GetType().FullName + ". " + currentAttemptCount + " of " + maxAttempts);

            if (retryInterval == TimeSpan.Zero)
            {
                ExecuteAttempt(faultContext);
            }
            else
            {
                // We are going to wait before trying again
                _delayDuration.Set(faultContext, retryInterval);
                faultContext.ScheduleActivity(
                    _internalDelay,
                    DelayCompleted);
            }
        }
        private void Continue(NativeActivityContext context, Bookmark bookmark, object obj)
        {
            var eventArgs = obj as WorkflowNotificationEventArgs;

            if (eventArgs.NotificationType != WorkflowNotificationObserver.CONTENTCHANGEDNOTIFICATIONTYPE)
            {
                return;
            }

            ReleaseWait(context, eventArgs.NodeId);

            var count = counter.Get(context) - 1;

            counter.Set(context, count);
            if (count > 0)
            {
                context.CreateBookmark(bookmark.Name, new BookmarkCallback(Continue));
            }
        }
Example #13
0
        private void BookmarkCallback(NativeActivityContext context, Bookmark bookmark, object bookmarkData)
        {
            _iteration.Set(context, _iteration.Get(context) + 1);

            string dataString = bookmarkData as string;

            if (dataString != null)
            {
                Console.WriteLine("Interation: {0}; Bookmark {1} resumed with data: {2}", _iteration.Get(context).ToString(), bookmark.Name, dataString);
                if (string.Compare(dataString, "stop", true) == 0)
                {
                    context.RemoveBookmark(bookmark.Name);
                }
            }
            else
            {
                Console.WriteLine("Iteration: {0}; Bookmark {1} resumed with data that is not a string", _iteration.Get(context).ToString(), bookmark.Name);
            }
        }
Example #14
0
        public void IfInWhileWithPersistence()
        {
            //  Test case description:
            //  Above scenario with persistence to see if there will be any change in the behavior and if we are able
            //  tp preserve the state and the rules fine.

            Variable <int> count = new Variable <int> {
                Name = "Counter", Default = 0
            };

            TestWhile whileAct = new TestWhile
            {
                Variables = { count },
                Body      = new TestSequence
                {
                    Activities =
                    {
                        new TestIf(HintThenOrElse.Then)
                        {
                            Condition    = true,
                            ThenActivity = new TestBlockingActivity("Bookmark"),
                        },
                        new TestIncrement {
                            CounterVariable = count, IncrementCount = 1
                        }
                    }
                },
                ConditionExpression = (e => count.Get(e) < 1),
                HintIterationCount  = 1
            };

            JsonFileInstanceStore.FileInstanceStore jsonStore = new JsonFileInstanceStore.FileInstanceStore(".\\~");

            using (TestWorkflowRuntime runtime = TestRuntime.CreateTestWorkflowRuntime(whileAct, null, jsonStore, PersistableIdleAction.None))
            {
                runtime.ExecuteWorkflow();
                runtime.WaitForIdle();
                runtime.PersistWorkflow();
                runtime.ResumeBookMark("Bookmark", null);
                runtime.WaitForCompletion();
            }
        }
Example #15
0
        public void UseBaseTypeAsDerivedType()
        {
            Variable <Derived> result = new Variable <Derived>()
            {
                Name = "Result"
            };
            Variable <string> output = new Variable <string>()
            {
                Name = "Output"
            };

            TestInvokeMethod invokeMethod = new TestInvokeMethod
            {
                TargetObjectVariable = result,
                MethodName           = "MethodInDerivedType"
            };

            invokeMethod.SetResultVariable <string>(output);

            //Base b = new Derived();
            //string result = (b as Derived).MethodInDerivedType
            TestSequence seq = new TestSequence
            {
                Variables  = { result, output },
                Activities =
                {
                    new TestAs <Base, Derived>
                    {
                        OperandExpression = context => new Derived(),
                        Result            = result
                    },
                    invokeMethod,
                    new TestWriteLine
                    {
                        MessageExpression = (e => output.Get(e)),
                        HintMessage       = "Ola"
                    }
                }
            };

            TestRuntime.RunAndValidateWorkflow(seq);
        }
        protected virtual void OnExecutedCompleted(NativeActivityContext context, bool hasError, bool isResumable)
        {
            var dataListExecutionID    = DataListExecutionID.Get(context);
            IDataListCompiler compiler = DataListFactory.CreateDataListCompiler();
            var dataObject             = context.GetExtension <IDSFDataObject>();

            if (dataObject.ForceDeleteAtNextNativeActivityCleanup)
            {
                // Used for web-pages to signal a force delete after checks of what would become a zombie datalist ;)
                dataObject.ForceDeleteAtNextNativeActivityCleanup = false; // set back
                compiler.ForceDeleteDataListByID(dataListExecutionID);
            }

            if (!dataObject.IsDebugNested)
            {
                dataObject.ParentInstanceID = _previousParentInstanceID;
            }

            dataObject.NumberOfSteps = dataObject.NumberOfSteps + 1;
            //Disposes of all used data lists

            int threadID = Thread.CurrentThread.ManagedThreadId;

            if (dataObject.IsDebugMode())
            {
                List <Guid> datlistIds;
                if (!dataObject.ThreadsToDispose.TryGetValue(threadID, out datlistIds))
                {
                    dataObject.ThreadsToDispose.Add(threadID, new List <Guid> {
                        dataObject.DataListID
                    });
                }
                else
                {
                    if (!datlistIds.Contains(dataObject.DataListID))
                    {
                        datlistIds.Add(dataObject.DataListID);
                        dataObject.ThreadsToDispose[threadID] = datlistIds;
                    }
                }
            }
        }
Example #17
0
        public void DecisionTrueEvaluation()
        {
            TestFlowchart  flowchart = new TestFlowchart("Flow1");
            Variable <int> counter   = VariableHelper.CreateInitialized <int>("counter", 3);

            flowchart.Variables.Add(counter);


            TestWriteLine writeLine1 = new TestWriteLine("hello1", "Hello1");
            TestWriteLine writeLine2 = new TestWriteLine("hello2", "Hello2");
            TestWriteLine writeLine3 = new TestWriteLine("hello3", "Hello3");

            TestFlowConditional flowDecision = new TestFlowConditional();

            flowDecision.ConditionExpression = ((env) => (counter.Get(env) == 3));

            flowchart.AddConditionalLink(writeLine1, flowDecision, writeLine2, writeLine3);

            TestRuntime.RunAndValidateWorkflow(flowchart);
        }
Example #18
0
        public void FlowDecisionWithTrueElementNullEvaluationTrue()
        {
            // This is a valid testcase and we don't expect error.
            TestFlowchart flowchart1 = new TestFlowchart("flowChart1");

            TestWriteLine w2True  = new TestWriteLine("True", "True will execute");
            TestWriteLine w2False = new TestWriteLine("False", "False wont execute");

            Variable <int> margin = new Variable <int> {
                Name = "margin", Default = 10
            };

            flowchart1.Variables.Add(margin);
            TestFlowConditional flowDecision = new TestFlowConditional((HintTrueFalse[])null); // null here means neither True or False will happen as the action is null

            flowDecision.ConditionExpression = (context => margin.Get(context) > 0);
            TestFlowElement tCond = flowchart1.AddConditionalLink(null, flowDecision, null, w2False);

            TestRuntime.RunAndValidateWorkflow(flowchart1);
        }
Example #19
0
        public void FlowDecisionConnectedToFlowStep()
        {
            TestFlowchart  flowchart = new TestFlowchart("Flow1");
            Variable <int> counter   = VariableHelper.CreateInitialized <int>("counter", 3);

            flowchart.Variables.Add(counter);


            TestWriteLine writeLine1 = new TestWriteLine("hello1", "Hello1");
            TestWriteLine writeLine2 = new TestWriteLine("hello2", "Hello2");
            TestWriteLine writeLine3 = new TestWriteLine("hello3", "Hello3");

            TestFlowConditional flowDecision = new TestFlowConditional(HintTrueFalse.True);

            flowDecision.ConditionExpression = (context => counter.Get(context) > 0);

            flowchart.AddStartLink(writeLine1);
            flowchart.AddConditionalLink(writeLine1, flowDecision, writeLine2, writeLine3);
            TestRuntime.RunAndValidateWorkflow(flowchart);
        }
        public void SetPublicPropertyOnValueType()
        {
            //
            //  Test case description:
            //  Set a public property on value type.

            TheStruct valueType = new TheStruct
            {
                PublicProperty = 123
            };

            Variable <TheStruct> var = new Variable <TheStruct>()
            {
                Default = valueType, Name = "var"
            };
            TestValueTypePropertyReference <TheStruct, int> valueTypePropertyReference = new TestValueTypePropertyReference <TheStruct, int>()
            {
                PropertyName            = "PublicProperty",
                OperandLocationVariable = var,
            };

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

            TestSequence seq = new TestSequence()
            {
                Variables  = { var },
                Activities =
                {
                    testAssign,
                    new TestWriteLine {
                        MessageExpression = ((ctx) => var.Get(ctx).PublicProperty.ToString()),HintMessage                                                                 = value.ToString()
                    }
                }
            };

            TestRuntime.RunAndValidateWorkflow(seq);
        }
        public void SetPublicEnumFieldOnValueType()
        {
            //
            //  Test case description:
            //  Set a public enum field on value type.

            TheStruct valueType = new TheStruct
            {
                enumField = FileAccess.Write
            };

            Variable <TheStruct> var = new Variable <TheStruct>()
            {
                Default = valueType, Name = "var"
            };
            TestValueTypeFieldReference <TheStruct, FileAccess> valueTypeFieldReference = new TestValueTypeFieldReference <TheStruct, FileAccess>()
            {
                FieldName = "enumField",
                OperandLocationVariable = var,
            };

            System.IO.FileAccess value = System.IO.FileAccess.ReadWrite;
            TestAssign <System.IO.FileAccess> testAssign = new TestAssign <FileAccess>()
            {
                ToLocation = valueTypeFieldReference, Value = value
            };

            TestSequence seq = new TestSequence()
            {
                Variables  = { var },
                Activities =
                {
                    testAssign,
                    new TestWriteLine {
                        MessageExpression = ((ctx) => var.Get(ctx).enumField.ToString()),HintMessage                                                            = value.ToString()
                    }
                }
            };

            TestRuntime.RunAndValidateWorkflow(seq);
        }
        public void ThrowFromIndexer()
        {
            //
            //  Test case description:
            //  Throw from ‘this’ property

            TheStruct valueType = new TheStruct();

            Variable <TheStruct> var = new Variable <TheStruct>()
            {
                Default = valueType, Name = "var"
            };
            TestValueTypeIndexerReference <TheStruct, int> valueTypeIndexerReference = new TestValueTypeIndexerReference <TheStruct, int>()
            {
                OperandLocationVariable = var,
            };

            valueTypeIndexerReference.Indices.Add(new TestArgument <float>(Direction.In, null, 2));

            int value = 321;
            TestAssign <int> testAssign = new TestAssign <int>()
            {
                ToLocation      = valueTypeIndexerReference,
                Value           = value,
                ExpectedOutcome = Outcome.UncaughtException(typeof(Exception)),
            };

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

            TestRuntime.RunAndValidateAbortedException(seq, typeof(Exception), null);
        }
        public static TestSequence GetTraceableBoolResultActivity(ITestBoolReturningActivity activity, string expectedResult)
        {
            Variable <bool> result = new Variable <bool>()
            {
                Name = "Result"
            };

            activity.Result = result;

            return(new TestSequence()
            {
                Variables = { result },
                Activities =
                {
                    (TestActivity)activity,
                    new TestWriteLine {
                        MessageExpression = e => result.Get(e).ToString(),HintMessage                                 = expectedResult
                    }
                }
            });
        }
Example #24
0
        private void OnBranchComplete(NativeActivityContext context, ActivityInstance completedInstance)
        {
            if (this.CompletionCondition != null && !_hasCompleted.Get(context))
            {
                // If we haven't completed, we've been requested to cancel, and we've had a child
                // end in a non-Closed state then we should cancel ourselves.
                if (completedInstance.State != ActivityInstanceState.Closed && context.IsCancellationRequested)
                {
                    context.MarkCanceled();
                    _hasCompleted.Set(context, true);
                    return;
                }

                if (_onConditionComplete == null)
                {
                    _onConditionComplete = new CompletionCallback <bool>(OnConditionComplete);
                }

                context.ScheduleActivity(this.CompletionCondition, _onConditionComplete);
            }
        }
        public static TestSequence GetTraceableUnaryExpressionActivity <TOperand, TResult>(ITestUnaryExpression <TOperand, TResult> unaryActivity, string expectedResult)
        {
            Variable <TResult> result = new Variable <TResult>()
            {
                Name = "Result"
            };

            unaryActivity.Result = result;

            return(new TestSequence()
            {
                Variables = { result },
                Activities =
                {
                    (TestActivity)unaryActivity,
                    new TestWriteLine {
                        MessageExpression = e => result.Get(e).ToString(),HintMessage                            = expectedResult
                    }
                }
            });
        }
        public static TestSequence GetTraceablePropertyValue <TOperand, TResult>(TestPropertyValue <TOperand, TResult> propertyValue, string expectedResult)
        {
            Variable <TResult> result = new Variable <TResult>()
            {
                Name = "Result"
            };

            propertyValue.Result = result;

            return(new TestSequence
            {
                Variables = { result },
                Activities =
                {
                    propertyValue,
                    new TestWriteLine {
                        MessageExpression = e => result.Get(e).ToString(),HintMessage                                          = expectedResult
                    }
                }
            });
        }
Example #27
0
        private TestSequence GetTraceableTestNew <T>(TestNew <T> testNew, string expectedResult)
        {
            Variable <T> result = new Variable <T>()
            {
                Name = "Result"
            };

            testNew.Result = result;

            return(new TestSequence
            {
                Variables = { result },
                Activities =
                {
                    testNew,
                    new TestWriteLine {
                        MessageExpression = e => result.Get(e).ToString(),HintMessage                                                = expectedResult
                    }
                }
            });
        }
Example #28
0
        public void Cancel(NativeActivityContext context)
        {
            bool bookmarkResumed = _bookmarkResumed.Get(context);

            if (!bookmarkResumed)
            {
                CancellationTokenSource cancellationTokenSource = _cancellationTokenSource.Get(context);

                cancellationTokenSource.Cancel();
                cancellationTokenSource.Dispose();
            }

            context.MarkCanceled();
            // Overriding the Cancel method inhibits the propagation of cancellation requests to children.
            context.CancelChildren();

            if (!bookmarkResumed)
            {
                _noPersistHandle.Get(context).Exit(context);
            }
        }
Example #29
0
        public void SetPublicPropertyOnAStruct()
        {
            TheStruct myStruct = new TheStruct {
                PublicProperty = 23
            };
            Variable <TheStruct> customType = new Variable <TheStruct>()
            {
                Name = "Custom", Default = myStruct
            };

            TestPropertyReference <TheStruct, int> propReference = new TestPropertyReference <TheStruct, int>
            {
                OperandVariable = customType,
                PropertyName    = "PublicProperty"
            };

            TestSequence seq = new TestSequence
            {
                Variables  = { customType },
                Activities =
                {
                    new TestAssign <int> {
                        ToLocation = propReference, Value = 27
                    },
                    new TestWriteLine    {
                        MessageExpression = e => customType.Get(e).publicField.ToString(), HintMessage = "0"
                    }
                }
            };

            string error = string.Format(ErrorStrings.TargetTypeIsValueType, typeof(PropertyReference <TheStruct, int>).Name, propReference.DisplayName);

            List <TestConstraintViolation> constraints = new List <TestConstraintViolation>();

            constraints.Add(new TestConstraintViolation(
                                error,
                                propReference.ProductActivity));

            TestRuntime.ValidateWorkflowErrors(seq, constraints, error);
        }
Example #30
0
        public void IfConditionExpressionInConstructor()
        {
            Variable <bool> var = new Variable <bool>("var", false);

            TestSequence seq = new TestSequence()
            {
                Activities =
                {
                    new TestIf(env => var.Get(env).Equals(true), HintThenOrElse.Else)
                    {
                        ThenActivity = new TestWriteLine("w",    "I'm Funny"),
                        ElseActivity = new TestWriteLine("w2",   "I'm not Funny!")
                    }
                },
                Variables =
                {
                    var
                }
            };

            TestRuntime.RunAndValidateWorkflow(seq);
        }
Example #31
0
        static Constraint CompensateWithNoTarget()
        {
            DelegateInArgument<Compensate> element = new DelegateInArgument<Compensate> { Name = "element" };
            DelegateInArgument<ValidationContext> validationContext = new DelegateInArgument<ValidationContext> { Name = "validationContext" };
            Variable<bool> assertFlag = new Variable<bool> { Name = "assertFlag" };
            Variable<IEnumerable<Activity>> elements = new Variable<IEnumerable<Activity>>() { Name = "elements" };
            Variable<int> index = new Variable<int>() { Name = "index" };

            return new Constraint<Compensate>
            {
                Body = new ActivityAction<Compensate, ValidationContext>
                {
                    Argument1 = element,
                    Argument2 = validationContext,
                    Handler = new Sequence
                    {
                        Variables = 
                        {
                            assertFlag,
                            elements,
                            index
                        },
                        Activities =
                        {
                            new If
                            {
                                Condition = new InArgument<bool>((env) => element.Get(env).Target != null),
                                Then = new Assign<bool>
                                {
                                    To = assertFlag,
                                    Value = true
                                },
                                Else = new Sequence
                                {
                                    Activities = 
                                    {
                                        new Assign<IEnumerable<Activity>>
                                        {
                                            To = elements,
                                            Value = new GetParentChain
                                            {
                                                ValidationContext = validationContext,
                                            },
                                        },
                                        new While(env => (assertFlag.Get(env) != true) && index.Get(env) < elements.Get(env).Count())
                                        {
                                            Body = new Sequence
                                            {
                                                Activities = 
                                                {
                                                    new If(env => (elements.Get(env).ElementAt(index.Get(env))).GetType() == typeof(CompensationParticipant))
                                                    {
                                                        Then = new Assign<bool>
                                                        {
                                                            To = assertFlag,
                                                            Value = true                                                            
                                                        },
                                                    },
                                                    new Assign<int>
                                                    {
                                                        To = index,
                                                        Value = new InArgument<int>(env => index.Get(env) + 1)
                                                    },
                                                }
                                            }
                                        }
                                    }
                                }                                
                            },
                            new AssertValidation
                            {
                                Assertion = new InArgument<bool>(assertFlag),
                                Message = new InArgument<string>(SR.CompensateWithNoTargetConstraint)   
                            }
                        }
                    }
                }
            };
        }
Example #32
0
        /// <summary>
        /// 创建人工节点
        /// </summary>
        /// <param name="setting"></param>
        /// <param name="displayName"></param>
        /// <param name="actioner"></param>
        /// <param name="humanResultTo"></param>
        /// <param name="nexts"></param>
        /// <param name="defaultFlowNode"></param>
        /// <returns></returns>
        public static FlowStep CreateHuman(ActivitySetting setting
            , string displayName
            , IActionersHelper actioner//Activity<string[]> actioner
            , Variable<string> humanResultTo
            , IDictionary<string, FlowNode> nexts
            , FlowNode defaultFlowNode)
        {
            var human = CreateHuman(setting, displayName, actioner, humanResultTo);
            var step = new FlowStep();
            step.Action = human;

            if (nexts == null && defaultFlowNode == null) return step;

            //设置finish cases
            //HACK:在进入switch之前就已经计算出任务结果
            var flowSwitch = new FlowSwitch<string>(o => humanResultTo.Get(o));
            if (defaultFlowNode != null)
                flowSwitch.Default = defaultFlowNode;
            if (nexts != null)
                nexts.ToList().ForEach(o => flowSwitch.Cases.Add(o.Key, o.Value));
            step.Next = flowSwitch;
            return step;
        }
Example #33
0
        /// <summary>
        /// 创建SubProcess子流程节点
        /// </summary>
        /// <param name="setting"></param>
        /// <param name="displayName"></param>
        /// <param name="serverScript">节点执行内容脚本</param>
        /// <param name="finishRule">节点完成规则</param>
        /// <param name="serverScriptResultTo">执行内容的结果输出到指定变量</param>
        /// <param name="serverResultTo">节点执行结果输出到变量</param>
        /// <param name="nexts"></param>
        /// <param name="defaultFlowNode"></param>
        /// <returns></returns>
        public static FlowStep CreateSubProcess(ActivitySetting setting
            , string displayName
            , IDictionary<string, string> finishRule
            , Variable<string> resultTo
            , IDictionary<string, FlowNode> nexts
            , FlowNode defaultFlowNode)
        {
            var server = CreateSubProcess(setting, displayName, finishRule, resultTo);
            var step = new FlowStep();
            step.Action = server;

            if (nexts == null && defaultFlowNode == null) return step;

            //设置finish cases
            var flowSwitch = new FlowSwitch<string>(o => resultTo.Get(o));
            if (defaultFlowNode != null)
                flowSwitch.Default = defaultFlowNode;
            if (nexts != null)
                nexts.ToList().ForEach(o => flowSwitch.Cases.Add(o.Key, o.Value));
            step.Next = flowSwitch;
            return step;
        }