microsoft press windows workflow foundation step by step phần 7 pps

57 519 0
microsoft press windows workflow foundation step by step phần 7 pps

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Chapter 10 Event Activities 215 Figure 10-2 Adding a new watched stock Selecting a symbol in the ticker symbol list enables the Remove button. Clicking the Remove button removes the item from the watched stock list. The removal action is shown in Figure 10-3. The stocks you are monitoring are stored in the application’s Settings file (in XML form). The next time you execute eBroker, it will “remember” your stocks and begin checking anew. Figure 10-3 Removing an existing watched stock In Figure 10-2, you see that the application needs to know how many shares you currently have so that it can calculate the total value of the shares you own. These figures are used to cal- culate the current market value. If you later want to adjust the number of shares (by buying and selling stock), select the stock in the market value list and click either Buy! or Sell! The dialog box you see in Figure 10-4 will request the number of shares you want to buy or sell, and the workflow will be notified. Figure 10-4 Dialog box requesting number of shares to buy or sell The Add dialog box in Figure 10-2 also requests buy and sell “trigger” amounts. The workflow contains business logic that uses these values to notify you when not you should buy or sell shares in any of the companies you are currently monitoring. If the stock price exceeds the sell trigger value, a red flag is displayed in the market list. If the stock price drops below the buy trigger value, a green flag appears. You can buy and sell shares at any time the flags are just visual indicators. You see a couple of flags in Figure 10-5. 216 Part II Working with Activities Figure 10-5 The eBroker user interface indicating buy/sell recommendations Note DO NOT think for a microsecond that the simulation I’ve provided here in any way truly simulates any stock market or company on the planet. The simulation is completely fab- ricated for demonstration purposes only. Each of these four buttons (Add, Remove, Buy! and Sell!) fires an event to the workflow, pro- viding the appropriate content, which includes the watched stock to add or remove and the number of shares to buy or sell (so that the total market value is accurate). There is a fifth event, Stop, that is used to stop the simulation from executing. This event is fired by the Quit button. Much of the application has been written for you, allowing you to concentrate on the workflow-related aspects. Here is the bigger picture. First, you’ll complete the interface the workflow and host will use for communication. Then you’ll use wca.exe to create activities based on the CallExternalMethod activity and the HandleExternalEvent activity. With these in hand, you’ll lay out the actual workflow, using each of the activities you’ve seen in this chapter. You’ll see how the local communication service glues the host application and workflow com- munication process together. And finally, you’ll briefly examine and add code to the eBroker user interface source file to direct it to interact with the workflow. Let’s get started! Creating the Communication Interface We need a single method, MarketUpdate, to return market information to the user interface, as well as five events. The events—AddTicker, RemoveTicker, BuyStock, SellStock, and Stop—are used to drive the workflow. The single method and five events are plugged into an interface, which we’ll build first. Everything related to the local communications service hinges on this interface. Creating a workflow data communication interface 1. Open Visual Studio, and open the eBroker application’s solution from the book samples. You’ll find the solution in \Workflow\Chapter10\. Click File, Open, and then finally Chapter 10 Event Activities 217 Project/Solution. Using the resulting Open Project dialog box, browse your computer’s file system until you find this chapter’s sample and open its solution file. Note As with the most sample applications in this book, the eBroker sample applica- tion comes in two forms: incomplete and complete. You can follow along and add code to the incomplete version, or you can open the complete version and verify that the code I mention here is in place. 2. You will find that three projects have been added to the solution. In Visual Studio Solution Explorer, expand the eBrokerService project and open the IWFBroker.cs file for editing. 3. Locate the namespace definition. After the opening brace for the eBrokerService namespace, add this code and then save the file: [ExternalDataExchange] public interface IWFBroker { void MarketUpdate(string xmlMarketValues); event EventHandler<TickerActionEventArgs> AddTicker; event EventHandler<TickerActionEventArgs> RemoveTicker; event EventHandler<SharesActionEventArgs> BuyStock; event EventHandler<SharesActionEventArgs> SellStock; event EventHandler<StopActionEventArgs> Stop; } 4. Compile the project by pressing Shift+F6 or by selecting Build eBrokerService from the main Visual Studio Build menu. Correct compilation errors, if any. Don’t forget the ExternalDataExchange attribute. Without it you cannot successfully transfer information between workflow and host using the data transfer mechanism I describe here. Before you create the communication activities (using wca.exe), take a moment to open and glance through the event arguments you see in the eBrokerService project. MarketUpdateEventArgs is really no more than a strongly typed version of System.Workflow.ExternalDataEventArgs, as is StopActionEventArgs. These event argument classes convey no data. However, TickerActionEventArgs and SharesActionEventArgs both convey information to the workflow. TickerActionEventArgs carries XML representing the stock to add or remove, while SharesActionEventArgs carries the ticker symbol as a primary key, as well as the number of shares to buy or sell. Tip Designing the event arguments is important because the event arguments carry data from the host to the workflow. Moreover, wca.exe examines the event arguments and builds bindings into the derived classes that allow you to access the data from the event arguments as if the data were intrinsic to the derived activity. Put another way, if the event argument has a property named OrderNumber, the class that wca.exe builds would have a property named OrderNumber. Its value would come from the underlying event’s event argument and would be assigned automatically for you. 218 Part II Working with Activities Now let’s use wca.exe to create the communication activities. Creating the communication activities 1. To begin, click the Start button and then the Run button to activate the Run dialog box. Windows Vista users who have not installed the Run command on the Start button can run the command prompt by selecting the All Programs button from the Start menu. When the programs appear, select Accessories and then Command Prompt. 2. Type cmd in the Open combo box control, and click OK. This activates the Command Shell. 3. Change directories so that you can directly access the eBrokerService assembly in the book’s downloaded sample code. Typically, the command to type is as follows: cd "\Workflow\Chapter10\eBroker\eBrokerService\bin\Debug". However, your specific directory might vary. 4. As you did in Chapter 8, type the following at the command-line prompt (including the double quotes): "<%Program Files%>\Microsoft SDKs\Windows\v6.0 \Bin\Wca.exe" /n:eBrokerFlow eBrokerService.dll. (Note that <%Program Files%> represents the location of your Program Files directory, typically "C:\Program Files".) Press the Enter key. 5. wca.exe loads the assembly it finds in eBrokerService.dll and scans the interfaces it locates for one decorated with the ExternalDataExchange attribute, which in this case is IWFBroker. The methods are parsed out and turned into classes derived from the CallExternalMethod activity and stored in the file named IWFBroker.Invokes.cs. The events are similarly turned into classes derived from the HandleExternalEvent activity and placed in IWFBroker.Sinks.cs. Rename the “invokes” file by typing this command on the command line: ren IWFBroker.Invokes.cs ExternalMethodActivities.cs. 6. Rename the “sinks” file by typing the following at the command-line prompt: ren IWFBroker.Sinks.cs ExternalEventHandlers.cs. 7. Move both files from the current directory into the workflow project’s directory using this command: move External*.cs \ \ \eBrokerFlow. 8. Now return to Visual Studio and add the newly created files to the eBrokerFlow work- flow project. Right-click the eBrokerFlow project name in Solution Explorer and select Add, then Existing Item. From the resulting Add Existing Item dialog box, select the files to add and then click Add. Be sure to add both ExternalMethodActivities.cs and ExternalEventHandlers.cs to the project. 9. Compile the eBrokerFlow project by pressing Shift+F6, and fix any compilation errors that might have occurred. Once you have a successful compilation, verify that Visual Studio placed the custom activities (in the C# files you just loaded) into the Toolbox. To do this, open Workflow1.cs for editing in the visual designer by selecting the file and then clicking the View Designer toolbar button in Solution Explorer. With the workflow Chapter 10 Event Activities 219 loaded into the visual workflow designer, open the Toolbox and look for the custom events. You should find AddTicker, BuyStock, and so forth loaded at the head of the Tool- box tool list. Note As a reminder, if after compiling the workflow solution the new activities don’t appear in the Toolbox, closing and then opening the eBroker solution will force them to load. You’ll need them in the next section. Creating the broker workflow 1. In the eBrokerFlow project, if you didn’t already open Workflow1.cs for editing in the visual designer, do so now. Select the file in Solution Explorer and click the View Designer button on the toolbar. 2. To begin the workflow, insert a Code activity that will be used to assign the desired time duration to a Delay activity (which you’ll insert later), as well as to initialize some internal data structures. Drag an instance of the Code activity onto the visual workflow designer’s surface. Once you’ve done this, type Initialize into the ExecuteCode property to create the Initialize event handler in the workflow code. After Visual Studio inserts the event handler, return to the workflow visual designer to continue adding activities. Note Although the user interface doesn’t allow you to change this, there is a setting for a delay in the workflow that governs the Delay activity in this step. This delay rep- resents the time elapsed between successive stock value queries. In reality, you’d not check more often than every 15 or 20 minutes, if that often. But to see the values actually shift and change, the delay between the simulated stock-market value checks is set to 7 seconds. The delay value is stored in Settings. 3. Next drag an instance of EventHandlingScope onto the visual workflow designer’s surface and drop it. 220 Part II Working with Activities 4. Remember that you need to provide an event handler as well as a child activity for EventHandlingScope to execute while it waits for the event. Let’s set up the event handler first. To access the event handlers, move the mouse pointer to the tiny rectangular icon below the first e in eventHandlingScope1. (The rectangle is known as a “Smart Tag.”) The Smart Tag is transformed into a larger, darker rectangle with a down arrow. Click the down arrow to activate a small window with four icons: View EventHandling- Scope, View Cancel Handler, View Fault Handlers, and View Event Handlers. Click the rightmost icon to activate the Event Handlers view. The user interface you see is a lot like the user interface associated with fault handlers that you saw in Chapter 7, “Basic Activity Operations.” Chapter 10 Event Activities 221 Drag an instance of the EventDriven activity onto the visual workflow designer’s surface and drop it into the center rectangle (where you see the text “Drop Event Driven Activity Here”). 5. Now return to the Toolbox and look for the Stop activity in the eBrokerFlow Compo- nents section. Drag an instance of this activity onto the visual workflow designer’s sur- face, and drop it into the EventDriven activity you added in the preceding step. If you want to wait for multiple events, you can drag and drop them at this time. In our case, only the Stop event is desired. 222 Part II Working with Activities 6. You’ve just added the event that the EventHandlingScope activity will wait for to cease execution (conveniently named “Stop”). Next you need to add the child activity that EventHandlingScope will execute while waiting for the Stop activity to fire. To do this, you need to return to eventHandlingScopeActivity1’s event handling scope view by repeating the first part of step 4. However, instead of selecting the right icon, select the left icon. 7. Once you click the leftmost icon (“View EventHandlingScope”) and are presented with the EventHandlingScope activity’s container-based user interface, drag an instance of the While activity onto the visual workflow designer’s surface and drop it in the center of your EventHandlingScope activity. 8. Assign its Condition property to be a Code Condition, rather than a Declarative Rule Condition, and assign the event handler the name TestContinue. Once Visual Studio Chapter 10 Event Activities 223 adds the TestContinue event handler, return to the visual workflow designer to add more activities. 9. The While activity accepts only a single child activity, so drop an instance of the Sequence activity into the While activity you just placed in your workflow. 10. You need a Code activity at this point to perform the Monte Carlo stock-value simulation, so drag an instance of Code onto the designer’s surface and drop it into the Sequence activity you added in the preceding step. Use the Properties window to rename it updateMarket. 224 Part II Working with Activities 11. Assign the updateMarket Code activity’s ExecuteCode property to be UpdateMarketValues. After Visual Studio adds the method and switches you to the code editor, return to the visual workflow designer to continue laying out your workflow. 12. With the results of the simulation complete (after you add the code to actually perform the simulation), you need to communicate the potentially revised values to the host application. To do this, move the mouse pointer to the Toolbox and find the MarketUp- date activity you created from IWFBroker and drag it onto the designer’s surface. Drop it into the Sequence activity following the Code activity you placed in the preceding step. 13. The MarketUpdate activity needs to send a small XML snippet to the host. To do that, it must bind to the field or property that, at the time, contains the XML it will forward. To do this, select the xmlMarketValues property in the Visual Studio Properties pane and click the Browse (…) button to activate the Bind ‘xmlMarketValues’ To An Activity’s Property dialog box. Click the Bind To A New Member tab, click Create Property, and [...]... line of code: Console.WriteLine("Waiting for workflow completion."); 14 To create a workflow instance, add this code following the line of code you just located: // Create the workflow instance WorkflowInstance instance = workflowRuntime.CreateWorkflow(typeof(ParallelFlow .Workflow1 )); // Start the workflow instance instance.Start(); 15 Compile the solution by pressing F6 Correct any compilation errors... completed Listen activity appears as you see here 25 Compile your workflow by pressing Shift+F6, and correct any errors before adding code The visual aspects of the workflow development are now complete 26 Open the Workflow1 .cs file for editing within Visual Studio 27 Visual Studio added quite a bit of code for you, so first locate the Workflow1 constructor and insert this code following the constructor... Visual Studio and it will open it for you 2 After Visual Studio has opened the ParallelHelloWorld solution, look for and open the Workflow1 workflow for editing in the visual workflow designer Select Workflow1 .cs in Solution Explorer, and click the View Designer button The visual workflow designer appears, and you can begin adding activities Chapter 11 Parallel Activities 243 3 Open the Toolbox, and drag... change? 0 -79 , no 80-99, if (rand.Next(0, 99) >= 80) { // Yes, update the price Next roll: // value increase or decrease? 0-49, // 50-99, decrease multiplier = 1; if (rand.Next(0, 99) >= 50) { // Decrease the price multiplier = -1; } // if does the yes will the increase // Next roll, by how much? We'll calculate it // as a percentage of the current share value // 0 -74 , 1% change 75 -89, 2% change 90- 97, //... If you share objects or collections of objects between workflow and host application, you run the risk of introducing multithreaded data access problems since the workflow and host application will share references to the same objects If this is an issue for your application, consider cloning the objects as they’re moved between workflow and host (by implementing ICloneable within your data class), or... System.Collections.Generic; System.Text; System.Threading; System .Workflow. Activities; System .Workflow. Runtime; System.Data; namespace eBrokerService { public sealed class BrokerDataConnector : IWFBroker { private string _dataValue = null; private static WorkflowBrokerDataService _service = null; private static object _syncLock = new object(); public static WorkflowBrokerDataService BrokerDataService { get { return... describes the mechanism the workflow uses to invoke the MarketUpdate method To see the host invoke an event designed to ripple down to the workflow which might or might not carry data in the event arguments—look at this code snippet This code is used by the Quit button to exit the application private void cmdQuit_Click(object sender, EventArgs e) { // Stop the processing // Remove from workflow eBrokerService.BrokerDataConnector... eBrokerService.BrokerDataConnector dataConnector = (eBrokerService.BrokerDataConnector)_workflowRuntime.GetService( typeof(eBrokerService.BrokerDataConnector)); dataConnector.RaiseStop(_workflowInstance.InstanceId); // Just quit Application.Exit(); } To fire the events that carry data to the workflow, you first retrieve the connector using the workflow runtime’s GetService method Note the service is cast to its appropriate... you are inserting you probably recognize as initialization code When the workflow is started, you’ll pass the workflow a dictionary of watched stock items contained in a collection of Tickers items keyed by the stock ticker symbol, such as “CONT.” You also need to provide the polling interval, which is the amount of time the workflow waits before rechecking the stock-market values private Dictionary . here. 25. Compile your workflow by pressing Shift+F6, and correct any errors before adding code. The visual aspects of the workflow development are now complete. 26. Open the Workflow1 .cs file for. -1; } // if // Next roll, by how much? We'll calculate it // as a percentage of the current share value. // 0 -74 , .1% change. 75 -89, .2% change. 90- 97, // .3% change. And 98-99,. eventHandlingScopeActivity1’s event handling scope view by repeating the first part of step 4. However, instead of selecting the right icon, select the left icon. 7. Once you click the leftmost icon (“View

Ngày đăng: 06/08/2014, 02:20

Từ khóa liên quan

Mục lục

  • Part II: Working with Activities

    • Chaper 10: Event Activities

      • Host-to-Workflow Communication

        • Creating the Communication Interface

        • Chapter 10 Quick Reference

        • Chaper 11: Parallel Activities

          • Using the Parallel Activity

          • Using the SynchronizationScope Activity

          • Using the ConditionedActivityGroup (CAG) Activity

          • Chapter 11 Quick Reference

          • Chaper 12: Policy and Rules

            • Policy and Rules

              • Implementing Rules

              • Rule Attributes

              • The Update Statement

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan