Presentation is loading. Please wait.

Presentation is loading. Please wait.

Windows 7 | Presenter Mode

Similar presentations


Presentation on theme: "Windows 7 | Presenter Mode"— Presentation transcript:

1 Windows 7 | Presenter Mode
Monday, April 17, 2017 Custom Activities

2 Developing Custom Activities
Custom activities are workflow’s extensibility mechanism, and their unit of encapsulation and re-use. Other platforms like WebForms have controls, workflow uses Activities. You can build custom activities to suit a variety of needs. You can build custom activities to define a custom control flow beyond that provided in the .NET 4 toolbox. Do you want an activity that completes when two of its three child sequences are completes, or that automatically retries a sequence after an error? Build a custom activity. Most commonly, you will build custom activities to implement custom business logic- more specifically you build custom activities when you really need to do something in code. For example, you might build an activity that knows how to save content to the file system or performs image manipulation. You may also create activities to build a vocabulary for designing workflow services in your problem domain. The idea is once you invested the time in coding these activities, future workflow just drop them into the design and configure them…no more code required. Why? Unit of encapsulation & re-use Model custom control flow Implement custom business logic Save to file system Process images Expand vocabulary of activities with domain specific activities

3 Activity Class Hierarchy
Windows 7 | Presenter Mode Monday, April 17, 2017 Custom activities are built by deriving from one of these four classes. At the top of the hierarchy is Activity which is the base type for all activities, and is also the default base class when you are building a XAML only custom activity that sequences other activities to define its logic. When you need to put code to run when an activity executes, you will typically derive from CodeActivity. When you want the execution of the activity to follow an asynchronous pattern, such as making an asynchronous web request, you should derive from AsyncCodeActivity which will support you in implementing this with BeginExecute…EndExecute methods. When you need to build a composite activity that provides control flow over other activities, such as the 2 out of 3 activity we mentioned earlier you will need to derive from NativeActivity. You can also use NativeActivty for building atomic activities that do not execute other child activities. Because it’s very common for custom activities to return a value as the result of their execution, each of these classes has an equivalent generic form that specifies the type of the return value. CodeActivity<Int32> for example, is used to define a custom activity whose result is an integer. Activity Activity<T> & & NativeActivity<T> NativeActivity & CodeActivity<T> CodeActivity AsyncCodeActivity AsyncCode Approaches: Code-based Atomic Activities – CodeActivity, Async & Native Code-based Composite Activities - NativeActivity XAML-based Composite Activities - Activity

4 XAML-based Composite Activities
Windows 7 | Presenter Mode Monday, April 17, 2017 Anytime you are creating a workflow, you are creating a composite activity! You can define your own custom composition of activities without using any code, completely in XAML. This is the type of activity you get when you create a new Activity Library project or add an Activity to your project in Visual Studio. If you’re unfamiliar with XAML, here’s a snippet that should get you warmed to seeing you the sequence defined by MyActivity shown in the diagram is actually described in XAML. Notice that the first element is Activity and it has the Class attribute of MyActivity. You read this as MyActivity inherits from Activity. Then you define implementation by adding a Sequence activity that contains our three DoWork activities. DoWork1 DoWork2 DoWork3 MyActivity <p:Activity x:Class=MyActivity” …> <p:Sequence …> <my:DoWork1 ...> <my:DoWork2 ...> <my:DoWork3 ...> </p:Sequence> </p:Activity>

5 Code-Based Atomic Activities
Windows 7 | Presenter Mode Monday, April 17, 2017 The most common type of activity you will build simply executes some logic expressed in code. The activity may take input and may return a result. To build such an activity, derive from System.Activities.CodeActivity and override the Execute method. Put your logic inside of the execute body. If you need to pass data into the execute method, you must define InArguments as properties in the class and get their values in the execute method. If you need to return a result you can define one or more OutArguments in the class and set their values in the execute method. Alternately you could inherit from CodeActivity<T>, your override Execute method would now return the type T and in the body of the execute you would simply return the value. The context that is passed in as a parameter to the Execute method provides access to a small subset of the runtime features. One use of the context is to get and set the values of arguments emit custom tracking records to the monitoring infrastructure. In the above snippet, our activity is configured with some text to write out in a custom tracking record. It gets the value from the TextToLog argument and uses the context to emit the tracking record. Derive from CodeActivity Override Execute method Use the Code Activity Execution Context public InArgument<string> TextToLog {get;set;} public class SimpleLogActivity: CodeActivity { protected override void Execute(CodeActivityExecutionContext context) { //activity logic goes here context.Track(new UserTrackingRecord(“Activity says: “ + TextToLog.Get(context))); } … }

6 Code-based Composite Activities
Windows 7 | Presenter Mode Monday, April 17, 2017 When you want to build activities that perform more complex scheduling of their child activities, you will want to derive from NativeActivity. The main difference from CodeActivity is that the NativeActivityContext passed in provides you with the functionality for scheduling the execution of your child activities, among other features required by advanced scenarios. Native Activity Use Similar to Code Activity Context enables more advanced scenarios public sealed class MyNativeActivity : NativeActivity { protected override void Execute(NativeActivityContext c) }

7 Using Arguments & Variables in Custom Activities
Windows 7 | Presenter Mode Monday, April 17, 2017 DoWork WorkToDo Result Variables: Using Arguments & Variables in Custom Activities Irrespective of whether you are using code based or XAML based activities, when you need to interchange data with the custom activity and the workflow that hosts it, you will do so by means of arguments. You define arguments as properties in code for the code based approaches, as we showed for the CodeActivity. You define arguments using the Arguments tab on the Workflow Designer in Visual Studio when you are building a XAML based activity. Arguments get data in or out of a custom activity Variables provide the means for a composite custom activity to share data with its children OutArgument InArgument

8 Creating a Simple Custom Activity
Windows 7 | Presenter Mode Monday, April 17, 2017 Open the AdderService project Add a new CodeActivity called ArithmeticAdd. Within the Code Activity's code file, add three InArgument<Int32> for the operands and previous result: public InArgument<Int32> Operand1 { get; set; } public InArgument<Int32> Operand2 { get; set; } public InArgument<Int32> PrevResult { get; set; } Change the base class to CodeActivity<Int32> Delete the Execute body and re-override it to get the proper signature Within the Execute body, get the operand values, add them to previious result and return the sum: return Operand1.Get(context) + Operand2.Get(context) + PrevResult.Get(context); Create a copy of SessionfulAdderService.xamlx and call it ArithmeticAdderService.xamlx. Build the solution. Open ArithmeticAdderService.xamlx. Delete the Assign activity. In place of the assign drop a ArithmeticAdd activity. Map the parameters of the ArithmeticAdd to operand1, operand2, prevresult and result (names will match). Set ArithmeticAdderService.xamlx as the Start Page. F5 run the solution and try a few additions in WCF Test Client. Creating a Simple Custom Activity Implementing the ArithmeticAdd Activity

9 Using ADO.NET for CRUD from Custom Activities
As an example of building a custom activity, consider an activity that can before CRUD operations against SQL Server database using ADO.NET. To build this, you would inherit from CodeActivity. In the code file for this class, you would define the InArguments such as the Connection String name, the SQL or Stored Procedure to Execute and the values of any parameters needed by the SQL or stored procedure. You would define Out Arguments for capturing either returned value, dataset or number of records affected. Within the Execute method body you acquire the connection string from the ambient config (in the case of workflow services, this is probably the connection string defined in web.config). You woul then open the connection to the database, execute the command passing in the values from the in arguments and write the results to the out arguments and close the connection. Inherit from CodeActivity Override Execute method Use DataReader, Command or DataAdapter CRUD Activity: CodeActivity In Arguments Out Arguments If using Integrated Security, ensure AppPool Identity has DB access Execute Get Connection String (web.config) Open Connection Perform CRUD ops Write values to Output Arguments Close Connection

10 Database Activity Pack
Windows 7 | Presenter Mode Monday, April 17, 2017 Database Activity Pack While the previous was a good example scenario for a custom activity, you no longer have to write custom activities for database access thanks to the Database Activity Pack. The Database Acitivty Pack includes three activities that perform CRUD operations using ADO.NET, and can be used to run either a SQL query or stored procedure. The ExecuteSqlNonQuery, likes it’s cousin in ADO.NET is designed to execute a SQL Statement or Stored Procedure without returning an recordset of results. It will return the number of rows affected, however. ExecuteSqlQuery and ExecuteSqlQuery<T> both execute a SQL Statement or Store Procedure and use a Data Reader to loop over the records returned in the result set. They both expose a body that loops over each record in the reader, allowing you to capture the values of the records into your workflow variables, before the data reader is closed when the activity completes. ExecuteSqlQuery<T> provides a strongly typed result collection, in the form of a List<T>, whereas ExecuteSqlQuery provides no result collection- you must capture the records within its body using the collection activities from WF 4 like AddToCollection. It’s critical to note that you should not assign the IDataRecord available in the body directly to a variable in your workflow, because when the ExecuteSqlQuery/ExecuteSqlQuery<T> completes the data reader that provides that record will have been closed. All of these activities pull their connection string information from config- in the case of using these in a Workflow Service, these are coming from web.config. Set of custom Activities Perform CRUD using ADO.NET Enable using SQL or Stored Procedure for command Support mapping returned record collection to collection variable in workflow Pull connection string from config Define complex mapping as activity sequence Easily process one record at a time Provides Out Argument as List<T> Returns # of Rows Affected

11 DB Activities with Transactions
You can use the DB Activities with transactions. The CUD activity can be part of a Transaction that extends across various activities, for example you need to insert a record, update a record and delete a record all in one transaction. You can have an activity join in to an ambient transaction either by using the TransactionScope or TransactedReceiveScope activities. You would place your transaction aware activities inside of the body of either of these scope activities. If the scope activity completes, the transaction is committed and the workflow is persisted (in that same transaction to ensure consistency). If an exception occurs before the scope activity completes, the transaction will be rolled back. Creates or Joins Ambient Transaction Transaction Scope Isolation Level Join ambient transaction No persistence within transaction No explicit rollback or commit activities OOB NativeActivityContext can get current transaction (if needed) TransactedReceiveScope activity supports flow-in of distributed transactions in workflow services Timeout Create Activity Exceptions thrown cause implicit rollback Update Activity Delete Activity Completion of Transaction Scope implicitly commits transaction & persists workflow

12 Using the Database Activity Pack
Windows 7 | Presenter Mode Monday, April 17, 2017 Open the AdderService project. Open DatabaseAdderService.xamlx, point out this is a copy of the SessionfulAdderService we used previously. Select the Lookup Previous Value activity, which is used to load the result of any addition performed previously from the database. Examine the Connection property by bringing up the dialog. Point out the value for this comes from the web.config. Examine the Command property and bring up the dialog. Point out the use of ADO.NET syntax for naming the Click the Parameters… button. Observe that this is how we pass in a value from workflow to the query. Exit the dialogs. Examine the body of the activity, this is how we get the value of a record and assign to a variable in the workflow. Point out the IF condition is used to guide whether we will need to perform an insert or an update, depending on whether a record already exists for the session in the table. Select the Insert Result activity, view the Command property and point out how we write the INSERT statement. Click the Parameters button to show how we pass in the values to insert. Exit the dialogs and select the Update Result activity. Examine the Command, and show the UPDATE statement syntax. Click the Parameters to show how we pass in the values which drive the update. Exit the dialogs. Point out that entire sequence is within a TransactedReceiveScope and therefore implicitly runs within a single transaction. Set the DatabaseAdderService.xamlx as the Start Page. F5 run the solution and try a few additions in WCF Test Client. Observe that when using the same session name, the value continues to be summed. Using the Database Activity Pack

13 Custom Activity Design Time Experience
Many of the built-in activities have a rich appearance in the Workflow Designer because they take advantage the Workflow Design Time extensibility features. Activity Designers allow you to control the what appears on the workflow design surface for your activity. These WPF based controls enable you add any WPF controls within the “box” of your activity, and enable you define additional behavior for actions taken on the activity at design time (such as when any property changes or the activity is moved). A control commonly used in a custom activity designer is the ExpressionTextBox. This control is part of the WF 4 presentation classes, and is what allows you specify Visual Basic expressions for the Arguments of your custom activity. It provides support for syntax coloring, statement completion and intellisense when used within Visual Studio (it is also supported for defining expressions outside of VS in the re-hosted scenario, but it does not have these last three features). While custom Activity Designers allow you fine grain control over the configuration of your activity on the Workflow Design surface, you can also control how custom activity properties appear in the Property Grid. This is an often overlooked UI extensibility point that is worth considering. With it you can define Category Editors that allow batch editing of multiple properties using a single complex UI to guide users in editing a lot of individual, but related properties. You also have control over the presentation of how each property row appears in the property grid, with in-line property value editors. If your property requires a richer editing experience, your in-line property value editor can display a pop-up (as shown on the slide) similar to how a combo box works, or can display a full blown dialog. Finally, you can define Validation logic on your activities that can check the value of properties on your activity, as well validate the entire workflow tree. These can be very useful in enforcing best practice use of your custom activity, as we show in the example that shows a validation warning when the activity is not contained within a TryCatch activity or does not have its DisplayName property set. Note that a custom activity does not have to implement any of these in order to function, but by doing so you can enhance and simplify the workflow design experience. Activity Designers WPF Based Validate individual properties or entire activity tree Validation Expression support Customize presentation & design time behavior Category Editors allow “batch” editing of multiple properties with single complex UI Custom Inline, Pop-Up & Dialog Property Value Editors Property Grid Extensibility

14 Lab 4 Custom Activities


Download ppt "Windows 7 | Presenter Mode"

Similar presentations


Ads by Google