In our last post, we talk about a developer’s introduction to Windows Workflow Foundation (WF4) in .NET 4 Beta. Now, we will continue our journey.... Here we go!!
Building your first workflow
Now that we have covered the core concepts around Activity and data flow, we can create a workflow using these concepts. We will start with a simple hello world workflow to focus on the concepts rather than the true value proposition of WF. To start, create a new Unit Test project in Visual Studio 2010. In order to use the core of WF, add a reference to the System.Activities assembly, and add using statements for System.Activities, System.Activities.Statements, and System.IO in the test class file.
Tour of the workflow activity palette
With any programming language, you expect to have core constructs for defining your application logic. When using a higher level development framework like WF, that expectation does not change. Just as you have statements in .NET languages such as If/Else, Switch and While, for managing control flow you also need those same capabilities when defining your logic in a declarative workflow. These capabilities come in the form of the base activity library that ships with the framework. In this section, we will give you a quick tour of the activities that ship with the framework to give you an idea of the functionality provided out of the box.
Activity Primitives and Collection Activities
When moving to a declarative programming model, it is easy to begin wondering how to do common object manipulation tasks that are second nature when writing code. For those tasks where you find yourself working with objects and needing to set properties, invoke commands or manage a collection of items, there are a set of activities designed specifically with those tasks in mind.
1. Assign : Assigns a value to a location – enabling setting variables.
2. Delay : Delays the path of execution for a specified amount of time.
3. InvokeMethod/InvokeMethod<T> : Invokes a method on a .NET object or static method on a .NET type, optionally with a return type of T.
4. WriteLine : Writes specified text to a text writer – defaults to Console.Out
5. AddToCollection<T> : Adds an item to a typed collection.
6. RemoveFromCollection<T> : Removes an item from a typed collection.
7. ClearCollection<T> : Removes all items from a collection.
8. ExistsInCollection<T> : Returns a Boolean value indicating if the specified item exists in the collection.
Control Flow Activities
When defining business logic or business processes, having control of the flow of execution is critical. Control flow activities include basics such as Sequence which provides a common container when you need to execute steps in order, and common branching logic such as the If and Switch activities. The control flow activities also include looping logic based on data (ForEach) and Conditions(While). Most important for simplifying complex programming are the parallel activities, which all enable multiple asynchronous activities to get work done at the same time.
1. Sequence : For executing activities in series
2. While/DoWhile : Executes a child activity while a condition (expression) is true
3. ForEach/ForEach<T> : Iterates over an enumerable collection and executes the child activity once for each item in the collection, waiting for the child to complete before starting the next iteration. ForEach<T> provides typed access to the individual item driving the iteration.
4. If : Executes one of two child activities depending on the result of the condition (expression).
5. Switch<T> : Evaluates an expression and schedules the child activity with a matching key.
6. Parallel : Schedules all child activities at once, but also provides a completion condition to enable the activity to cancel any outstanding child activities if certain conditions are met.
7. ParallelForEach/ParallelForEach<T> : Iterates over an enumerable collection and executes the child activity once for each item in the collection, scheduling all instances at the same time.
8. Pick : Schedules all child PickBranch activities and cancels all but the first to have its trigger complete. The PickBranch activity has both a Trigger and an Action; each is an Activity. When a trigger activity completes, the Pick cancels all its other child activities.
Flowchart
When designing Flowchart workflows there are several constructs that can be used to manage the flow of execution within the Flowchart. These constructs themselves provide simple steps, simple decision points based on a single condition, or a switch statement. The real power of the Flowchart is the ability to connect these node types into the desired flow.
1. Flowchart : The container for a series of flow steps, each flow step can be any activity or one of the following constructs, but to be executed, it must be connected within the Flowchart.
2. FlowDecision : Provides branching logic based on a condition.
3. FlowSwitch / FlowSwitch<T> : Enables multiple branches based on the value of an expression.
4. FlowStep : Represents a step in the Flowchart with the ability to be connected to other steps. This type is not shown in the toolbox as it is implicitly added by the designer. This activity wraps other activities in the workflow and provides the navigation semantics for the next step(s) in the workflow.
It is important to note that while there are specific activities for the Flowchart model, any other activities can be used within the workflow. Likewise, a Flowchart activity can be added to another activity to provide the execution and design semantics of a Flowchart, within that workflow. This means you can have a sequence with a several activities and a Flowchart right in the middle.
Messaging Activities
One of the major focuses in WF4 is tighter integration between WF and WCF. In terms of workflows, that means activities to model messaging operations such as sending and receiving messages. There are actually several different activities included in the framework for messaging, each with slightly different functionality and purpose.
1. Send/Receive : One way messaging activities to send or receive a message. These same activities are composed into request/response style interactions.
2. ReceiveAndSendReply : Models a service operation that receives a message and sends back a reply.
3. SendAndReceiveReply : Invokes a service operation and receives the response.
4. InitializeCorrelation : Allow for initializing correlation values explicitly as part of the workflow logic, rather than extracting the values from a message.
5. CorrelationScope : Defines a scope of execution where a correlation handle is accessible to receive and send activities simplifying the configuration of a handle that is shared by several messaging activities.
6. TransactedReceiveScope : Enables workflow logic to be included in the same transaction flowed into a WCF operation using the Receive activity.
Transactions and Error Handling
Writing reliable systems can be difficult, and requires that you do a good job of handling errors and managing to keep consistent state in your application. For a workflow, scopes for managing exception handling and transactions are modeled using activities with properties of type ActivityAction or Activity to enable developers to model error processing logic. Beyond these common patterns of consistency, WF4 also includes activities which allow you to model long running distributed coordination through compensation and confirmation.
1. CancellationScope : Used to allow the workflow developer to react if a body of work gets cancelled.
2. TransactionScope : Enables semantics similar to using a transaction scope in code by executing all child activities in the scope under a transaction.
3. TryCatch/Catch<T> : Used to model exception handling and catch typed exceptions.
4. Throw : Can be used to throw an exception from the activity.
5. Rethrow : Used to rethrow an exception, generally one that has been caught using the TryCatch activity.
6. CompensableActivity : Defines the logic for executing child activities that may need to have their actions compensated for after success. Provides a placeholder for the compensation logic, confirmation logic, and cancellation handling.
7. Compensate : Invokes the compensation handling logic for a compensable activity.
8. Confirm : Invokes the confirmation logic for a compensable activity.
Options for executing workflows
In order to execute a workflow, you need an Activity that defines the workflow. There are two typical ways to get an Activity that can be executed: create it in code or read in a XAML file and deserialize the content into an Activity. The first option is straightforward and I have already shown several examples. To load a XAML file you should use the ActivityXamlServices class which provides a static Load method. Simply pass in a Stream or XamlReader object and you get back the Activity represented in the XAML.
Once you have an Activity, the simplest way to execute it is by using the WorkflowInvoker class as I did in the unit tests earlier. The Invoke method of this class has a parameter of type Activity and returns an IDictionary<string, object>. If you need to pass arguments into the workflow, you first define them on the workflow and then pass the values along with the Activity, into the Invoke method as dictionary of name/value pairs. Likewise, any Out or In/Out arguments defined on the workflow will be returned as the result of executing the method. We provide an example of loading a workflow from a XAML file, passing arguments into the workflow and retrieving the resulting output arguments.
Activity mathWF;
using (Stream mathXaml = File.OpenRead("Math.xaml"))
{
mathWF = ActivityXamlServices.Load(mathXaml);
}
var outputs = WorkflowInvoker.Invoke(mathWF,
new Dictionary<string, object> {
{ "operand1", 5 },
{ "operand2", 10 },
{ "operation", "add" } });
Assert.AreEqual<int>(15, (int)outputs["result"], "Incorrect result returned");
Notice in this example that the Activity is loaded from a XAML file and it can still accept and return arguments. The workflow was developed using the designer in Visual Studio for ease, but could be developed in a custom designer and stored anywhere. The XAML could be loaded from a database, SharePoint library, or some other store before being handed to the runtime for execution.
Using the WorkflowInvoker provides the simplest mechanism for running short-lived workflows. It essentially makes the workflow act like a method call in your application, enabling you to more easily take advantage of all the benefits of WF without having to do a lot of work to host WF itself. This is especially useful when unit testing your activities and workflows as it reduces the test setup necessary to exercise a component under test.
Another common hosting class is the WorkflowApplication which provides a safe handle to a workflow that is executing in the runtime, and enables you to manage long running workflows more easily. With the WorkflowApplication, you can still pass arguments into the workflow in the same way as with the WorkflowInvoker, but you use the Run method to actually start the workflow running. At this point, the workflow begins executing on another thread and control returns to the calling code.
Because the workflow is now running asynchronously, in your hosting code you will likely want to know when the workflow completes, or if it throws an exception, etc. For these types of notifications, the WorkflowApplication class has a set of properties of type Action<T> that can be used like events to add code to react to certain conditions of the workflow execution including: aborted, unhandled exception, completed, idled, and unloaded. When you execute a workflow using WorkflowApplication, you can use code similar to that shown in Figure below using actions to handle the events.
WorkflowApplication wf = new WorkflowApplication(new Flowchart1());
wf.Completed = delegate(WorkflowApplicationCompletedEventArgs e)
{
Console.WriteLine("Workflow {0} complete", e.InstanceId);
};
wf.Aborted = delegate(WorkflowApplicationAbortedEventArgs e)
{
Console.WriteLine(e.Reason);
};
wf.OnUnhandledException =
delegate(WorkflowApplicationUnhandledExceptionEventArgs e)
{
Console.WriteLine(e.UnhandledException.ToString());
return UnhandledExceptionAction.Terminate;
};
wf.Run();
In this example, the goal of the host code, a simple console application, is to notify the user via the console when the workflow completes or if an error occurs. In a real system, the host will be interested in these events and will likely react to them differently to provide administrators with information about failures or to better manage the instances.
TO BE CONTINUED
Always stay with us…. Don’t go anywhere!! We will continue the final part..
Top Reasons to host your ASP.NET 4 Website with HostForLife.eu
There are many reasons why so many people choose HostForLife over any other web hosting provider each year. Whether you’re beginner or an experience webmaster, HostForLife offers the perfect solution for everyone.
You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added-benefits you can find when hosting with us:
1. World-class 24x7 Customer Support
Will your hosting company promptly answer questions and resolve issues - at 3 am on a Sunday? Even some providers claiming “24x7” support will not - but HostForLife will. Our outstanding uptime is backed by true 24x7 customer support. An expertly trained technician will respond to your query within one hour, round the clock. You will also get qualified answers. Other hosting companies typically have very low - level support staff during the night or weekends. HostForLife always has knowledgeable, top - level support standing by, day or night, to give you the answers you need.
2. Commitment to Outstanding Reliability
Reliability, Stability, and Performance of our servers remain out TOP priority. Even our basic service plans are equipped with standard service level agreements for 99.99% uptime. Advanced options raise the bar to 99.99%. Our state-of-the-art data centers combine servers and SAN storage with full redundancy and operational tools with proprietary service management techniques. Full backup and recovery capabilities are implemented, including redundant power supplies, cooling and connectionsto major data networks.
3. “Right-size” plans for maximum value
HostForLife offers a complete menu of services. IT professionals select only what they need - and leave behind what they don’t. The result is an optimal blend of cost and performance. We offer IT professionals more advanced features and the latest technology - ahead of other hosting companies.
4. Profitable, Stable, Debt-free Business
Financial stability is the bedrock of a hosting provider’s ability to deliver outstanding uptime, cost-effective service plans and world-class 24x7 support. HostForLife’s customers are assured of our financial integrity and stability - a stark contrast to the ups and downs they may have experienced with other providers.
5. The Best Account Management Tools
HostForLife revolutionized hosting with Plesk Control Panel, a Web-based interfaces that provides customers with 24x7 access to their server and site configuration tools. Some other hosting providers manually execute configuration requests, which can take days. Plesk completes requests in second. It is included free with each hosting account. Renowned for its comprehensive functionally - beyond other hosting control panels - and ease of use, Plesk Control Panel is available only to HostForLife’s customers.
6. 30-Day Money Back Guarantee
HostForLife 30 day money back guarantee ensures you have the ability to cancel your account anytime within your first 30 days under our full 30 day money back guarantee (less one-time account setup free). So what are you waiting for? Sign up today, risk free…
7. Simplicity with FREE 1-Click Installation
HostForLife was designed with ease of use in mind. From one click installations of your favourite website applications to our much talked about drag and drop website builder, you can rest assure your stay with us is going to be a smooth one. HostForLife offers the most extensive set of scripts on the web allowing you to build complicated websites with little or no programming knowledge at all. From blogs to forums to powerful e-commerce solutions, Super Green has something that is right for you.