Constraint UnrootedRequestRule() { DelegateInArgument<SendReply> sendReply = new DelegateInArgument<SendReply>(); DelegateInArgument<ValidationContext> context = new DelegateInArgument<ValidationContext>(); DelegateInArgument<Activity> activityInTree = new DelegateInArgument<Activity>(); Variable<bool> requestInTree = new Variable<bool> { Default = false }; return new Constraint<SendReply> { Body = new ActivityAction<SendReply, ValidationContext> { Argument1 = sendReply, Argument2 = context, Handler = new Sequence { Variables = { requestInTree }, Activities = { new If { Condition = new InArgument<bool>(ctx => sendReply.Get(ctx).Request != null), Then = new Sequence { Activities = { new ForEach<Activity> { Values = new GetWorkflowTree { ValidationContext = context, }, Body = new ActivityAction<Activity> { Argument = activityInTree, Handler = new If { Condition = new InArgument<bool>(ctx => activityInTree.Get(ctx) == sendReply.Get(ctx).Request), Then = new Assign<bool> { To = requestInTree, Value = true, } } } }, new AssertValidation { Assertion = new InArgument<bool>(ctx => requestInTree.Get(ctx)), IsWarning = false, Message = new InArgument<string>(ctx => string.Format(CultureInfo.CurrentCulture, System.Activities.Core.Presentation.SR.UnrootedRequestInSendReply, sendReply.Get(ctx).DisplayName)) } } } } } } } }; }
public static Constraint VerifyParentIsWorkflowActivity() { DelegateInArgument<Activity> element = new DelegateInArgument<Activity>(); DelegateInArgument<ValidationContext> context = new DelegateInArgument<ValidationContext>(); DelegateInArgument<Activity> parent = new DelegateInArgument<Activity>(); Variable<bool> result = new Variable<bool>(); return new Constraint<Activity> { Body = new ActivityAction<Activity, ValidationContext> { Argument1 = element, Argument2 = context, Handler = new Sequence { Variables = { result }, Activities = { new ForEach<Activity> { Values = new GetParentChain { ValidationContext = context, }, Body = new ActivityAction<Activity> { Argument = parent, Handler = new If { Condition = new InArgument<bool>((env) => parent.Get(env).IsWorkflowActivity()), Then = new Assign<bool> { Value = true, To = result, }, }, }, }, new AssertValidation { Assertion = new InArgument<bool>((env) => result.Get(env)), Message = new InArgument<string>((env) => $"{element.Get(env).GetType().GetFriendlyName()} can only be added inside a {typeof(WorkflowActivity<,>).GetFriendlyName()} activity."), PropertyName = new InArgument<string>((env) => element.Get(env).DisplayName), }, }, }, }, }; }
private static Activity CreatePrintProcessActivity(Variable<Collection<Process>> processes) { var proc = new DelegateInArgument<Process>("process"); return new Sequence { Activities = { // Loop over processes and print them out. new ForEach<Process> { Values = processes, Body = new ActivityAction<Process> { Argument = proc, Handler = new WriteLine { Text = new InArgument<string>(ctx => proc.Get(ctx).ToString()), } } }, // Print out a new line. new WriteLine(), } }; }
// Creates a workflow that uses FindInSqlTable activity with a more complex predicate to retrieve entities from a Sql Server Database static Activity CreateRetrieveWithComplexPredicateWF() { Variable<IList<Employee>> employees = new Variable<IList<Employee>>(); DelegateInArgument<Employee> employeeIterationVariable = new DelegateInArgument<Employee>(); return new Sequence() { Variables = { employees }, Activities = { new WriteLine { Text = "\r\nEmployees by Role and Location (more complex predicate)\r\n============================================" }, new FindInSqlTable<Employee> { ConnectionString = cnn, Predicate = new LambdaValue<Func<Employee, bool>>(c => new Func<Employee, bool>(emp => emp.Role.Equals("PM") && emp.Location.Equals("Redmond"))), Result = new OutArgument<IList<Employee>>(employees) }, new ForEach<Employee> { Values = new InArgument<IEnumerable<Employee>>(employees), Body = new ActivityAction<Employee>() { Argument = employeeIterationVariable, Handler = new WriteLine { Text = new InArgument<string>(env => employeeIterationVariable.Get(env).ToString()) } } } } }; }
// Creates a workflow that uses FindInTable activity without predicate to retrieve entities from a Sql Server Database static Activity CreateRetrieveWithoutPredicateWF() { Variable<IList<Role>> roles = new Variable<IList<Role>>(); DelegateInArgument<Role> roleIterationVariable = new DelegateInArgument<Role>(); return new Sequence() { Variables = { roles }, Activities = { new WriteLine { Text = "\r\nAll Roles (no predicates)\r\n==============" }, new FindInSqlTable<Role> { ConnectionString = cnn, Result = new OutArgument<IList<Role>>(roles) }, new ForEach<Role> { Values = new InArgument<IEnumerable<Role>>(roles), Body = new ActivityAction<Role>() { Argument = roleIterationVariable , Handler = new WriteLine { Text = new InArgument<string>(env => roleIterationVariable.Get(env).Name) } } } } }; }
static void Main(string[] args) { // iteration variable for the ForEach var item = new DelegateInArgument<object>(); // list of elements to iterate ArrayList list = new ArrayList(); list.Add("Bill"); list.Add("Steve"); list.Add("Ray"); // iterate through the list and show the elements Activity act = new ForEach { Values = new InArgument<IEnumerable>(ctx=>list), Body = new ActivityAction<object> { Argument = item, Handler = new WriteLine { Text = new InArgument<string>(c => item.Get(c).ToString()) } } }; WorkflowInvoker.Invoke(act); Console.WriteLine(""); Console.WriteLine("Press enter to exit..."); Console.ReadLine(); }
// Constraint is just an activity that contains validation logic. public static Constraint ConstraintError_IfShouldHaveThenOrElse() { DelegateInArgument<If> element = new DelegateInArgument<If>(); return new Constraint<If> { Body = new ActivityAction<If, ValidationContext> { Argument1 = element, Handler = new AssertValidation { Assertion = new InArgument<bool>(env => (element.Get(env).Then != null) || (element.Get(env).Else != null)), Message = new InArgument<string>("'If' activity should have either Then or Else activity set."), } } }; }
public static Constraint ConstraintWarning_PickHasOneBranch() { DelegateInArgument<Pick> element = new DelegateInArgument<Pick>(); return new Constraint<Pick> { Body = new ActivityAction<Pick, ValidationContext> { Argument1 = element, Handler = new AssertValidation { IsWarning = true, Assertion = new InArgument<bool>(env => (element.Get(env).Branches.Count == 0) || (element.Get(env).Branches.Count > 1)), Message = new InArgument<string>("This Pick activity has only one branch so the Pick itself is redundant."), } } }; }
/// <summary> /// Validates whether the Twilio activity is contained within a CallScope activity. /// </summary> /// <returns></returns> internal static Constraint<Activity> MustBeInsideCallScopeConstraint() { var activityBeingValidated = new DelegateInArgument<Activity>(); var validationContext = new DelegateInArgument<ValidationContext>(); var parent = new DelegateInArgument<Activity>(); var parentIsCallScope = new Variable<bool>(); return new Constraint<Activity>() { Body = new ActivityAction<Activity, ValidationContext>() { Argument1 = activityBeingValidated, Argument2 = validationContext, Handler = new Sequence() { Variables = { parentIsCallScope, }, Activities = { new ForEach<Activity>() { Values = new GetParentChain() { ValidationContext = validationContext, }, Body = new ActivityAction<Activity>() { Argument = parent, Handler = new If(env => parent.Get(env).GetType() == typeof(CallScope)) { Then = new Assign<bool>() { To = parentIsCallScope, Value = true, }, }, }, }, new AssertValidation() { Assertion = parentIsCallScope, Message = "Twilio activities must be nested inside of a CallScope", IsWarning = false, }, }, }, }, }; }
/// <summary> /// Validates whether the Leave activity is contained inside of an Enqueue activity. /// </summary> /// <returns></returns> Constraint<Leave> MustBeContainedInEnqueue() { var activityBeingValidated = new DelegateInArgument<Leave>(); var validationContext = new DelegateInArgument<ValidationContext>(); var outer = new DelegateInArgument<Activity>(); var enqueueIsOuter = new Variable<bool>(); return new Constraint<Leave>() { Body = new ActivityAction<Leave, ValidationContext>() { Argument1 = activityBeingValidated, Argument2 = validationContext, Handler = new Sequence() { Variables = { enqueueIsOuter, }, Activities = { new ForEach<Activity>() { Values = new GetParentChain() { ValidationContext = validationContext, }, Body = new ActivityAction<Activity>() { Argument = outer, Handler = new If(env => typeof(Enqueue).IsAssignableFrom(outer.Get(env).GetType())) { Then = new Assign<bool>() { To = enqueueIsOuter, Value = true, }, }, }, }, new AssertValidation() { Assertion = enqueueIsOuter, Message = "Leave must be contained inside of an Enqueue.", IsWarning = false, }, }, }, }, }; }
/// <summary> /// Validates whether the DialNoun activity is contained within a Dial activity. /// </summary> /// <returns></returns> Constraint<DialNoun> MustBeInsideDialActivityConstraint() { var activityBeingValidated = new DelegateInArgument<DialNoun>(); var validationContext = new DelegateInArgument<ValidationContext>(); var parent = new DelegateInArgument<Activity>(); var parentIsOuter = new Variable<bool>(); return new Constraint<DialNoun>() { Body = new ActivityAction<DialNoun, ValidationContext>() { Argument1 = activityBeingValidated, Argument2 = validationContext, Handler = new Sequence() { Variables = { parentIsOuter, }, Activities = { new ForEach<Activity>() { Values = new GetParentChain() { ValidationContext = validationContext, }, Body = new ActivityAction<Activity>() { Argument = parent, Handler = new If(env => parent.Get(env).GetType() == typeof(Dial)) { Then = new Assign<bool>() { To = parentIsOuter, Value = true, }, }, }, }, new AssertValidation() { Assertion = parentIsOuter, Message = "DialNouns must be nested inside Dial", IsWarning = false, }, }, }, }, }; }
static Activity CreateWF() { DelegateInArgument<string> current = new DelegateInArgument<string>(); IList<string> data = new List<string>(); for (int i = 1; i < 11; i++) { data.Add(string.Format("Branch {0}", i)); } Variable<int> waitTime = new Variable<int>(); return new Sequence { Variables = { waitTime }, Activities = { new ThrottledParallelForEach<string> { Values = new LambdaValue<IEnumerable<string>>(c => data), MaxConcurrentBranches = 3, Body = new ActivityAction<string> { Argument = current, Handler = new Sequence { Activities = { new WriteLine() { Text = new InArgument<string>(ctx => string.Format("Enter {0}", current.Get(ctx))) }, new Assign<int> { To = waitTime, Value = new InArgument<int>(ctx => new Random().Next(0, 2500)) }, new WriteLine() { Text = new InArgument<string>(ctx => string.Format("...{0} will wait for {1} millisenconds...", current.Get(ctx), waitTime.Get(ctx))) }, new Delay { Duration = new InArgument<TimeSpan>(ctx => new TimeSpan(0,0,0,0, waitTime.Get(ctx))) }, new WriteLine() { Text = new InArgument<string>(ctx => string.Format("......Exit {0}", current.Get(ctx))) }, } } } } } }; }
static Constraint CheckParent() { DelegateInArgument<CreateState> element = new DelegateInArgument<CreateState>(); DelegateInArgument<ValidationContext> context = new DelegateInArgument<ValidationContext>(); Variable<bool> result = new Variable<bool>(); DelegateInArgument<Activity> parent = new DelegateInArgument<Activity>(); return new Constraint<CreateState> { Body = new ActivityAction<CreateState,ValidationContext> { Argument1 = element, Argument2 = context, Handler = new Sequence { Variables = { result }, Activities = { new ForEach<Activity> { Values = new GetParentChain { ValidationContext = context }, Body = new ActivityAction<Activity> { Argument = parent, Handler = new If() { Condition = new InArgument<bool>((env) => object.Equals(parent.Get(env).GetType(),typeof(CreateCountry))), Then = new Assign<bool> { Value = true, To = result } } } }, new AssertValidation { Assertion = new InArgument<bool>(result), Message = new InArgument<string> ("CreateState has to be inside a CreateCountry activity"), } } } } }; }
public static Constraint VerifyParentIsObjectContextScope(Activity activity) { DelegateInArgument<Activity> element = new DelegateInArgument<Activity>(); DelegateInArgument<ValidationContext> context = new DelegateInArgument<ValidationContext>(); DelegateInArgument<Activity> child = new DelegateInArgument<Activity>(); Variable<bool> result = new Variable<bool>(); return new Constraint<Activity> { Body = new ActivityAction<Activity, ValidationContext> { Argument1 = element, Argument2 = context, Handler = new Sequence { Variables = { result }, Activities = { new ForEach<Activity> { Values = new GetParentChain { ValidationContext = context }, Body = new ActivityAction<Activity> { Argument = child, Handler = new If { Condition = new InArgument<bool>((env) => object.Equals(child.Get(env).GetType(), typeof(ObjectContextScope))), Then = new Assign<bool> { Value = true, To = result } } } }, new AssertValidation { Assertion = new InArgument<bool>(env => result.Get(env)), Message = new InArgument<string> (string.Format("{0} can only be added inside an ObjectContextScope activity.", activity.GetType().Name)), PropertyName = new InArgument<string>((env) => element.Get(env).DisplayName) } } } } }; }
static RangeEnumeration Enumerate(int start, int stop, int step) { Console.WriteLine("Starting enumeration of a series of numbers from {0} to {1} using steps of {2}", start, stop, step); DelegateInArgument<int> loopVariable = new DelegateInArgument<int>(); return new RangeEnumeration { Start = start, Stop = stop, Step = step, Body = new ActivityAction<int> { Argument = loopVariable, Handler = new WriteLine { Text = new InArgument<string>(context => "This is " + loopVariable.Get(context).ToString()), }, } }; }
static void Main(string[] args) { // iteration variable for the ForEach var item = new DelegateInArgument<object>(); // list of elements to iterate ArrayList list = new ArrayList(); list.Add("Bill"); list.Add("Steve"); list.Add("Ray"); // iterate through the list and show the elements Activity act = new ParallelForEach { Values = new InArgument<IEnumerable>(ctx => list), Body = new ActivityAction<object> { Argument = item, Handler = new InvokeMethod { TargetType = typeof(Program), MethodName = "ShowThreadId", RunAsynchronously = true, Parameters = { new InArgument<string>(c => item.Get(c).ToString()) } } } }; WorkflowInvoker.Invoke(act); Console.WriteLine(""); Console.WriteLine("Press enter to exit..."); Console.ReadLine(); }
public static Constraint SetReceiveRequestSendResponseScopeExecutionPropertyFactory() { DelegateInArgument<ReceiveRequestSendResponseScope> element = new DelegateInArgument<ReceiveRequestSendResponseScope>(); DelegateInArgument<ValidationContext> context = new DelegateInArgument<ValidationContext>(); DelegateInArgument<Activity> child = new DelegateInArgument<Activity>(); return new Constraint<ReceiveRequestSendResponseScope> { Body = new ActivityAction<ReceiveRequestSendResponseScope, ValidationContext> { Argument1 = element, Argument2 = context, Handler = new ForEach<Activity> { Values = new GetChildSubtree { ValidationContext = context, }, Body = new ActivityAction<Activity> { Argument = child, Handler = new If { Condition = new InArgument<bool>((env) => child.Get(env) is ISendResponse), Then = new ReceiveRequestSendResponseScope.ReceiveRequestSendResponseScopeExecutionPropertyFactorySetter { ISendResponse = new InArgument<ISendResponse>((env) => child.Get(env) as ISendResponse), ReceiveRequestSendResponseScope = new InArgument<ReceiveRequestSendResponseScope>((env) => element.Get(env)), }, }, }, }, }, }; }
public static Constraint VerifyReceiveRequestSendResponseScopeChildren() { DelegateInArgument<ReceiveRequestSendResponseScope> element = new DelegateInArgument<ReceiveRequestSendResponseScope>(); DelegateInArgument<ValidationContext> context = new DelegateInArgument<ValidationContext>(); DelegateInArgument<Activity> child = new DelegateInArgument<Activity>(); Variable<int> receiveRequestCounter = new Variable<int>(); Variable<int> sendResponseCounter = new Variable<int>(); return new Constraint<ReceiveRequestSendResponseScope> { Body = new ActivityAction<ReceiveRequestSendResponseScope, ValidationContext> { Argument1 = element, Argument2 = context, Handler = new Sequence { Variables = { receiveRequestCounter, sendResponseCounter, }, Activities = { new Assign<int> { Value = 0, To = receiveRequestCounter, }, new Assign<int> { Value = 0, To = sendResponseCounter, }, new ForEach<Activity> { Values = new GetChildSubtree { ValidationContext = context, }, Body = new ActivityAction<Activity> { Argument = child, Handler = new Sequence { Activities = { new If { Condition = new InArgument<bool>((env) => child.Get(env) is IReceiveRequest), Then = new Assign<int> { Value = new InArgument<int>((env) => receiveRequestCounter.Get(env) + 1), To = receiveRequestCounter }, }, new If { Condition = new InArgument<bool>((env) => child.Get(env) is ISendResponse), Then = new Assign<int> { Value = new InArgument<int>((env) => sendResponseCounter.Get(env) + 1), To = sendResponseCounter }, }, }, }, }, }, new AssertValidation { Assertion = new InArgument<bool>((env) => receiveRequestCounter.Get(env) == 1), Message = new InArgument<string> ($"{nameof(ReceiveRequestSendResponseScope)} activity must contain one and only one {nameof(ReceiveRequest)} activity"), PropertyName = new InArgument<string>((env) => element.Get(env).DisplayName) }, new AssertValidation { Assertion = new InArgument<bool>((env) => sendResponseCounter.Get(env) == 1), Message = new InArgument<string> ($"{nameof(ReceiveRequestSendResponseScope)} activity must contain one and only one {nameof(SendResponse)} activity"), PropertyName = new InArgument<string>((env) => element.Get(env).DisplayName) }, }, }, }, }; }
public static Constraint SetWorkflowInterfaceOperationNames() { DelegateInArgument<ReceiveRequestSendResponseScope> element = new DelegateInArgument<ReceiveRequestSendResponseScope>(); DelegateInArgument<ValidationContext> context = new DelegateInArgument<ValidationContext>(); DelegateInArgument<Activity> parent = new DelegateInArgument<Activity>(); DelegateInArgument<Activity> child = new DelegateInArgument<Activity>(); Variable<IOperationActivity> receiveRequest = new Variable<IOperationActivity>(); Variable<Type> workflowInterfaceType = new Variable<Type>(); Variable<Type> requestResultType = new Variable<Type>(); Variable<Type> responseParameterType = new Variable<Type>(); return new Constraint<ReceiveRequestSendResponseScope> { Body = new ActivityAction<ReceiveRequestSendResponseScope, ValidationContext> { Argument1 = element, Argument2 = context, Handler = new Sequence { Variables = { receiveRequest, workflowInterfaceType, requestResultType, responseParameterType, }, Activities = { new ForEach<Activity> { Values = new GetParentChain { ValidationContext = context, }, Body = new ActivityAction<Activity> { Argument = parent, Handler = new If { Condition = new InArgument<bool>((env) => parent.Get(env).IsWorkflowActivity()), Then = new Assign<Type> { Value = new InArgument<Type>((env) => parent.Get(env).GetWorkflowActivityType().GetGenericArguments()[(int)TypeParameterIndex.WorkflowInterface]), To = workflowInterfaceType, }, }, }, }, new ForEach<Activity> { Values = new GetChildSubtree { ValidationContext = context, }, Body = new ActivityAction<Activity> { Argument = child, Handler = new Sequence { Activities = { new If { Condition = new InArgument<bool>((env) => child.Get(env) is IReceiveRequest), Then = new Sequence { Activities = { new Assign<IOperationActivity> { Value = new InArgument<IOperationActivity>((env) => child.Get(env) as IOperationActivity), To = receiveRequest }, new Assign<Type> { Value = new InArgument<Type>((env) => (child.Get(env) as IReceiveRequest).RequestResultType), To = requestResultType }, }, }, }, new If { Condition = new InArgument<bool>((env) => child.Get(env) is ISendResponse), Then = new Assign<Type> { Value = new InArgument<Type>((env) => (child.Get(env) as ISendResponse).ResponseParameterType), To = responseParameterType }, }, }, }, }, }, new WorkflowInterfaceOperationNamesSetter { ReceiveRequest = new InArgument<IOperationActivity>((env) => receiveRequest.Get(env)), WorkflowInterfaceType = new InArgument<Type>((env) => workflowInterfaceType.Get(env)), RequestResultType = new InArgument<Type>((env) => requestResultType.Get(env)), ResponseParameterType = new InArgument<Type>((env) => responseParameterType.Get(env)), }, }, }, }, }; }
/// <summary> /// Creates the code for wrapping an activity. /// Returns a <see cref="System.Activities.Statements.TryCatch "/>activity that implements error handling logic /// </summary> /// <returns>The code for wrapping activity</returns> internal Activity CreateBody() { var exceptionArgument = new DelegateInArgument<Exception>(); return new TryCatch { Try = this.CreateInternalBody(), Catches = { new Catch<FailingBuildException> { Action = new ActivityAction<FailingBuildException> { Handler = new @If { Condition = new InArgument<bool>(env => this.IgnoreExceptions.Get(env)), Else = new Rethrow() } } }, new Catch<Exception> { Action = new ActivityAction<Exception> { Argument = exceptionArgument, Handler = new Sequence { Activities = { new @If { Condition = new InArgument<bool>(env => this.LogExceptionStack.Get(env)), Then = new LogBuildError { Message = new InArgument<string>(env => FormatLogExceptionStackMessage(exceptionArgument.Get(env))) } }, new @If { Condition = new InArgument<bool>(env => this.IgnoreExceptions.Get(env)), Else = new Rethrow() } } } } } } }; }
static Activity GetClientWorkflow() { Variable<PurchaseOrder> po = new Variable<PurchaseOrder>(); Variable<bool> invalidorder = new Variable<bool>() { Default = true }; Variable<string> replytext = new Variable<string>(); DelegateInArgument<FaultException<POFault>> poFault = new DelegateInArgument<FaultException<POFault>>(); DelegateInArgument<FaultException<ExceptionDetail>> unexpectedFault = new DelegateInArgument<FaultException<ExceptionDetail>>(); // submits a purchase order for the part and quantity stored in the po variable Send submitPO = new Send { Endpoint = new Endpoint { Binding = Constants.Binding, AddressUri = new Uri(Constants.ServiceAddress) }, ServiceContractName = Constants.POContractName, OperationName = Constants.SubmitPOName, KnownTypes = { typeof(POFault) }, Content = SendContent.Create(new InArgument<PurchaseOrder>(po)) }; return new CorrelationScope { Body = new Sequence { Variables = { invalidorder, po }, Activities = { // defines the original desired parts and quantity: 155 pencils new Assign<PurchaseOrder> { To = po, Value = new InArgument<PurchaseOrder>( (e) => new PurchaseOrder() { PartName = "Pencil", Quantity = 155 } ) }, new While { // loop until a valid order is submitted Condition = invalidorder, Variables = { replytext }, Body = new Sequence { Activities = { // print out the order that will be submitted new WriteLine { Text = new InArgument<string>((env) => string.Format("Submitting Order: {0} {1}s", po.Get(env).Quantity, po.Get(env).PartName)) }, // submit the order submitPO, new TryCatch { Try = new Sequence { Activities = { // receive the result of the order // if ReceiveReply gets a Fault message, then we will handle those faults below new ReceiveReply { Request = submitPO, Content = ReceiveContent.Create(new OutArgument<string>(replytext)) }, new WriteLine { Text = replytext }, // this order must be valid, so set invalidorder to false new Assign<bool> { To = invalidorder, Value = false } } }, Catches = { // catch a known Fault type: POFault new Catch<FaultException<POFault>> { Action = new ActivityAction<FaultException<POFault>> { Argument = poFault, Handler = new Sequence { Activities = { // print out the details of the POFault new WriteLine { Text = new InArgument<string>((env) => string.Format("\tReceived POFault: {0}", poFault.Get(env).Reason.ToString())) }, new WriteLine { Text = new InArgument<string>((env) => string.Format("\tPOFault Problem: {0}", poFault.Get(env).Detail.Problem)) }, new WriteLine { Text = new InArgument<string>((env) => string.Format("\tPOFault Solution: {0}", poFault.Get(env).Detail.Solution)) }, // update the order to buy Widgets instead new Assign<string> { To = new OutArgument<string>( (e) => po.Get(e).PartName ), Value = "Widget" } } } } }, // catch any unknown fault types new Catch<FaultException<ExceptionDetail>> { Action = new ActivityAction<FaultException<ExceptionDetail>> { Argument = unexpectedFault, Handler = new Sequence { Activities = { // print out the details of the fault new WriteLine { Text = new InArgument<string>((e) => string.Format("\tReceived Fault: {0}", unexpectedFault.Get(e).Message )) }, // update the order to buy 10 less of the item new Assign<int> { To = new OutArgument<int>( (e) => po.Get(e).Quantity ), Value = new InArgument<int>( (e) => po.Get(e).Quantity - 10 ) } } } } }, } } } } }, new WriteLine { Text = "Order successfully processed." } } } }; }
private Constraint ValidateActivitiesConstraint(string runtimeAssembly, PSWorkflowValidationResults validationResults) { DelegateInArgument<Activity> activityToValidate = new DelegateInArgument<Activity>(); DelegateInArgument<ValidationContext> validationContext = new DelegateInArgument<ValidationContext>(); return new Constraint<Activity> { Body = new ActivityAction<Activity, ValidationContext> { Argument1 = activityToValidate, Argument2 = validationContext, Handler = new AssertValidation { IsWarning = false, Assertion = new InArgument<bool>( env => ValidateActivity(activityToValidate.Get(env), runtimeAssembly, validationResults)), Message = new InArgument<string>( env => string.Format(CultureInfo.CurrentCulture, Resources.InvalidActivity, activityToValidate.Get(env).GetType().FullName)) } } }; }
// Create a validation to verify that there are no Persist activites inside of a NoPersistScope static Constraint VerifiyNoChildPersistActivity() { DelegateInArgument<NoPersistScope> element = new DelegateInArgument<NoPersistScope>(); DelegateInArgument<ValidationContext> context = new DelegateInArgument<ValidationContext>(); DelegateInArgument<Activity> child = new DelegateInArgument<Activity>(); Variable<bool> result = new Variable<bool>(); return new Constraint<NoPersistScope> { Body = new ActivityAction<NoPersistScope, ValidationContext> { Argument1 = element, Argument2 = context, Handler = new Sequence { Variables = { result }, Activities = { new ForEach<Activity> { Values = new GetChildSubtree { ValidationContext = context }, Body = new ActivityAction<Activity> { Argument = child, Handler = new If() { Condition = new InArgument<bool>((env) => object.Equals(child.Get(env).GetType(),typeof(Persist))), Then = new Assign<bool> { Value = true, To = result } } } }, new AssertValidation { Assertion = new InArgument<bool>(env => !result.Get(env)), Message = new InArgument<string> ("NoPersistScope activity can't contain a Persist activity"), PropertyName = new InArgument<string>((env) => element.Get(env).DisplayName) } } } } }; }
/// <summary> /// Create the structure of the activity for pausing between successive polling activities. /// </summary> /// <returns>An activity delegate.</returns> private static ActivityAction<int> CreateDelayBody() { var timeout = new DelegateInArgument<int> { Name = "FuncTimeout" }; return new ActivityAction<int> { Argument = timeout, Handler = new Delay { Duration = new InArgument<TimeSpan>(ctx => TimeSpan.FromSeconds(timeout.Get(ctx))) } }; }
// This scenario shows how to query for a set of entities from the database using EntitySql private static Activity EntitySqlQueryExample(string connStr) { Variable<IEnumerable<Customer>> londonCustomers = new Variable<IEnumerable<Customer>>(); DelegateInArgument<Customer> iterationVariable = new DelegateInArgument<Customer>(); // create and return the workflow return new ObjectContextScope { ConnectionString = new InArgument<string>(connStr), ContainerName = "NorthwindEntities", Variables = { londonCustomers }, Body = new Sequence { Activities = { new WriteLine { Text = "Executing query" }, // query for all customers that are in london new EntitySqlQuery<Customer> { EntitySql = @"SELECT VALUE Customer FROM NorthwindEntities.Customers AS Customer WHERE Customer.City = 'London' ORDER BY Customer.ContactName", Result = londonCustomers }, new WriteLine { Text = "Query executed - printing results: " }, new WriteLine { }, // iterate through the list of customers, and display them in the console new ForEach<Customer> { Values = londonCustomers, Body = new ActivityAction<Customer> { Argument = iterationVariable, Handler = new WriteLine { Text = new InArgument<String>(e => iterationVariable.Get(e).ContactName) } } } } } }; }
// This scenario shows how to query for a set of entities from the database using a Linq predicate private static Activity EntityLinqQueryExample(string connStr) { Variable<IEnumerable<Customer>> londonCustomers = new Variable<IEnumerable<Customer>>() { Name = "LondonCustomers" }; DelegateInArgument<Customer> iterationVariable = new DelegateInArgument<Customer>() { Name = "iterationVariable" }; return new ObjectContextScope { ConnectionString = new InArgument<string>(connStr), ContainerName = "NorthwindEntities", Variables = { londonCustomers }, Body = new Sequence { Activities = { new WriteLine { Text = "Executing query" }, // return all the customers that match with the provided Linq predicate new EntityLinqQuery<Customer> { Predicate = new LambdaValue<Func<Customer, bool>>(ctx => new Func<Customer, bool>(c => c.City.Equals("London"))), Result = londonCustomers }, new WriteLine { Text = "Query executed - printing results" }, new WriteLine { }, // iterate through the list of customers and display in the console new ForEach<Customer> { Values = londonCustomers, Body = new ActivityAction<Customer> { Argument = iterationVariable, Handler = new WriteLine { Text = new InArgument<String>(e => iterationVariable.Get(e).ContactName) } } } } } }; }
private static Constraint ConfirmWithNoTarget() { DelegateInArgument<Confirm> element = new DelegateInArgument<Confirm> { Name = "element" }; DelegateInArgument<ValidationContext> argument = 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" }; Constraint<Confirm> constraint = new Constraint<Confirm>(); ActivityAction<Confirm, ValidationContext> action = new ActivityAction<Confirm, ValidationContext> { Argument1 = element, Argument2 = argument }; Sequence sequence = new Sequence { Variables = { assertFlag, elements, index } }; If item = new If { Condition = new InArgument<bool>(env => element.Get(env).Target != null) }; Assign<bool> assign = new Assign<bool> { To = assertFlag, Value = 1 }; item.Then = assign; Sequence sequence2 = new Sequence(); Assign<IEnumerable<Activity>> assign2 = new Assign<IEnumerable<Activity>> { To = elements }; GetParentChain chain = new GetParentChain { ValidationContext = argument }; assign2.Value = chain; sequence2.Activities.Add(assign2); While @while = new While(env => !assertFlag.Get(env) && (index.Get(env) < elements.Get(env).Count<Activity>())); Sequence sequence3 = new Sequence(); If if2 = new If(env => elements.Get(env).ElementAt<Activity>(index.Get(env)).GetType() == typeof(CompensationParticipant)); Assign<bool> assign3 = new Assign<bool> { To = assertFlag, Value = 1 }; if2.Then = assign3; sequence3.Activities.Add(if2); Assign<int> assign4 = new Assign<int> { To = index, Value = new InArgument<int>(env => index.Get(env) + 1) }; sequence3.Activities.Add(assign4); @while.Body = sequence3; sequence2.Activities.Add(@while); item.Else = sequence2; sequence.Activities.Add(item); AssertValidation validation = new AssertValidation { Assertion = new InArgument<bool>(assertFlag), Message = new InArgument<string>(System.Activities.SR.ConfirmWithNoTargetConstraint) }; sequence.Activities.Add(validation); action.Handler = sequence; constraint.Body = action; return constraint; }
// Retrieve all roles from the database. Uses an ActivityFunc<DataReader, Role> to map the results // Performance decreases (since the mapping is done in multiple pulses) but mapping can be serialized // to Xaml and authored declaratively in the the designer. static void GetAllRolesUsingActivityFuncMapping() { DelegateInArgument<DbDataReader> reader = new DelegateInArgument<DbDataReader>() { Name = "readerInArgument" }; DelegateOutArgument<Role> roleOutArg = new DelegateOutArgument<Role>() { Name = "roleOutArgument" }; Activity dbQuery = new DbQuery<Role>() { ConfigName = "DbActivitiesSample", Sql = "SELECT * FROM Roles", MapperFunc = new ActivityFunc<System.Data.Common.DbDataReader,Role> { Argument = reader, Handler = new Sequence { Activities = { new Assign<Role> { To = roleOutArg, Value = new InArgument<Role>(c => new Role()) }, new Assign<string> { To = new OutArgument<string>(c => roleOutArg.Get(c).Code), Value = new InArgument<string>(c => reader.Get(c)["code"].ToString()) }, new Assign<string> { To = new OutArgument<string>(c => roleOutArg.Get(c).Name), Value = new InArgument<string>(c => reader.Get(c)["name"].ToString()) } } }, Result = roleOutArg } }; IDictionary<string, object> results = WorkflowInvoker.Invoke(dbQuery); IList<Role> roles = (IList<Role>)results["Result"]; foreach (Role role in roles) { Console.WriteLine(role.ToString()); } }
private static Activity CreateWf() { // variables. var pipeline = new DelegateInArgument<PSObject>() { Name = "Pipeline" }; var processName = new DelegateOutArgument<string>() { Name = "Process Name" }; var processes1 = new Variable<Collection<Process>> { Name = "Processes 1" }; var processes2 = new Variable<Collection<Process>> { Name = "Processes 2" }; var processes3 = new Variable<Collection<Process>> { Name = "Processes 3" }; var processNames = new Variable<Collection<string>> { Name = "Process Names" }; var errors = new Variable<Collection<ErrorRecord>> { Name = "Errors" }; var error = new DelegateInArgument<ErrorRecord> { Name = "Error" }; Sequence body = new Sequence() { Variables = { processes1, processes2, processes3, processNames, errors }, Activities = { // Simple PowerShell invocation. new WriteLine() { Text = "Simple PowerShell invocation. Launching notepad." }, new InvokePowerShell() { CommandText = "notepad" }, new WriteLine(), // Using PowerShell<T> to capture output. new WriteLine() { Text = "Getting process and then pass the output to a Collection." }, new InvokePowerShell<Process>() { CommandText = "Get-Process", Output = processes1, }, CreatePrintProcessActivity(processes1), // Do some post-processing after invocation. new WriteLine() { Text = "Getting the names of the processes." }, new InvokePowerShell<string>() { CommandText = "Get-Process", Output = processNames, InitializationAction = new ActivityFunc<PSObject,string> { Argument = pipeline, Result = processName, Handler = new Assign<string> { To = processName, Value = new LambdaValue<string>(ctx => ((Process) pipeline.Get(ctx).BaseObject).ToString()) } }, }, new WriteLine() { Text = new InArgument<string>(ctx => "The first process returned is: " + processNames.Get(ctx)[0]), }, new WriteLine(), // Passing data using an input pipeline. new WriteLine() { Text = "Passing data using an input pipeline and then extracting unique process names." }, new InvokePowerShell<Process>() { CommandText = "Get-Unique", Input = processes1, Output = processes2, }, CreatePrintProcessActivity(processes2), // Passing in a parameter to the command. new WriteLine() { Text = "Reverse sorting." }, new InvokePowerShell<Process>() { CommandText = "Sort-Object", Input = processes2, Output = processes3, Parameters = { { "descending", new InArgument<Boolean>(true) } } }, CreatePrintProcessActivity(processes3), // Run a command that results in errors. new WriteLine() { Text = "Returning errors." }, new InvokePowerShell<string>() { CommandText = "Write-Error", Errors = errors, Parameters = { { "message", new InArgument<string>("a short error message") } } }, new ForEach<ErrorRecord>() { Values = errors, Body = new ActivityAction<ErrorRecord> { Argument = error, Handler = new WriteLine() { Text = new InArgument<string>(ctx => "Error returned: " + error.Get(ctx).ToString()), }, } } } }; return body; }
// This sample shows how to use FindInCollection inside a workflow. // In this case, we are combining CollectionActivities (AddToCollection activity) // FindInCollection and ForEach. static void UseFindInCollectionInWorkflow() { // create workflow variables var employees = new Variable<IList<Employee>>(); var devsFromRedmond = new Variable<IList<Employee>>(); var iterationVariable = new DelegateInArgument<Employee>(); // create the Linq predicate for the find expression Func<Employee, bool> predicate = e => e.Role == "DEV" && e.Location.Equals("Redmond"); // create workflow program Activity sampleWorkflow = new Sequence { Variables = { employees, devsFromRedmond }, Activities = { new Assign<IList<Employee>> { To = employees, Value = new LambdaValue<IList<Employee>>(c => new List<Employee>()) }, new AddToCollection<Employee> { Collection = new InArgument<ICollection<Employee>>(employees), Item = new LambdaValue<Employee>(c => new Employee(1, "Employee 1", "DEV", "Redmond")) }, new AddToCollection<Employee> { Collection = new InArgument<ICollection<Employee>>(employees), Item = new LambdaValue<Employee>(c => new Employee(2, "Employee 2", "DEV", "Redmond")) }, new AddToCollection<Employee> { Collection = new InArgument<ICollection<Employee>>(employees), Item = new LambdaValue<Employee>(c => new Employee(3, "Employee 3", "PM", "Redmond")) }, new AddToCollection<Employee> { Collection = new InArgument<ICollection<Employee>>(employees), Item = new LambdaValue<Employee>(c => new Employee(4, "Employee 4", "PM", "China")) }, new FindInCollection<Employee> { Collections = new InArgument<IEnumerable<Employee>>(employees), Predicate = new LambdaValue<Func<Employee, bool>>(c => predicate), Result = new OutArgument<IList<Employee>>(devsFromRedmond) }, new ForEach<Employee> { Values = new InArgument<IEnumerable<Employee>>(devsFromRedmond), Body = new ActivityAction<Employee> { Argument = iterationVariable, Handler = new WriteLine { Text = new InArgument<string>(env => iterationVariable.Get(env).ToString()) } } } } }; // execute workflow WorkflowInvoker.Invoke(sampleWorkflow); }