Workflow Notes 3--bookmark and persistence

Source: Internet
Author: User

BookMark

We use in the normal workflow, not directly one go the entire workflow, usually a process to a node, the process node operator, may not immediately to deal with the process, and only when the processing process, the process will continue to go down. For the handlers of the different process nodes, he can handle different process nodes.

It's like we're reading, we need bookmarks to identify where I've seen it now, the workflow is the same, and I need to bookmark it to determine which process the people of different roles can handle.

1. In Project Windowsworkflowapp, create a new "code activity" bookmarkcodeactivity

Modifying the parameter type of the inheriting class to the Nativeactivity,execute method becomes the Nativeactivitycontext type. The code is as follows:

     Public Sealed classbookmarkcodeactivity:nativeactivity {//defines an activity input parameter for a string type         Publicinargument<string> BookmarkName {Get;Set; } //define an output parameter that is used for process judgment, equivalent to simulating the operation of a user's process node         Publicoutargument<int> Num {Get;Set; } //Create a bookmark to stop the process        protected Override voidExecute (Nativeactivitycontext context) {//1. Get the bookmark name            stringStrbookmarkname =context.            GetValue (BookmarkName); //2. Create a bookmarkContext. CreateBookMark (Strbookmarkname,NewBookmarkcallback (Preexecuteworkflow)); }        /// <summary>        ///Note that it is important to remember to override this property and return True, or the subsequent run will cause an error/// </summary>        protected Override BOOLCaninduceidle {Get            {                return true;//base. Caninduceidle;            }        }        /// <summary>        ///The method must be executed before continuing with the next state. /// </summary>        /// <param name= "context" ></param>        /// <param name= "Bookmark" >Bookmark</param>        /// <param name= "value" >the value passed over</param>         Public voidPreexecuteworkflow (nativeactivitycontext context, bookmark bookmark,Objectvalue) {context.        SetValue (Num, Convert.ToInt32 (value)); }}

2. Build Project Windowsworkflowapp

3. Double-click State1 to open, add code activity to State1, and create variable vnum.

4. Create input parameters Inputbookmarkname

5. Transformation Form1 Form

To modify the code that starts the workflow:

The Workflowapplication app will be extracted to the class below.

App =NewWorkflowapplication (NewActivity1 (),Newdictionary<string,Object>() {             {"InputName","God knife Zhang San"},{"Inputbookmarkname", Txtbookmarkname.text}}); App. Idle=Delegate(Workflowapplicationidleeventargs er) {Console.WriteLine ("Workflow {0} is idle.", er.                INSTANCEID); Syncevent.set (); //to wake up here and not let it, when a bookmark is created, the interface is stuck. };

Add code for the Continue execution button

        // wake up the bookmark execution Process        Private void Btncontinue_click (object  sender, EventArgs e)        {            //  The Preexecuteworkflow method is called and the value of Txtnum is passed            int. Parse (Txtnum.text));        }

6, double-click T1 to modify, add conditions to judge

Assuming that the value of the Vnum variable is equal to 5, the State2 continues to execute down.

7, add T3, when the value of vnum variable is not equal to 5, and then back to State1.

Double-click T3 to add a condition

8. The result of operation is as follows:

Workflow Persistence

1. Persist the workflow instance by creating a database. New Database workflowdb:

CREATE DATABASE [workflowdb]Containment=NONE on  PRIMARY(NAME=N'workflowdb', FILENAME=N'G:\DataBase\WorkFlowDB.mdf', SIZE=5120KB, MAXSIZE=UNLIMITED, FileGrowth=1024KB)LOG  on(NAME=N'Workflowdb_log', FILENAME=N'G:\DataBase\WorkFlowDB_log.ldf', SIZE=2048KB, MAXSIZE=2048GB, FileGrowth= Ten%)GO

2. Then create a new table to store the workflow's instance data, how do I create a new table?

Go to the%windir%\microsoft.net\framework\v4.xxx\sql\en folder to find the script, press WIN+R, run%windir%\Microsoft.NET\Framework

After you find these two SQL scripts, run the Sqlworkflowinstancestoreschema.sql file first in the database workflowdb, and then run the Sqlworkflowinstancestorelogic.sql file. After execution is complete, the following table is created in the database workflowdb.

The Instancestable table is the table used to store the workflow instance.

3. In Project Windowsworkflowapp, add a reference to the following two assemblies

4. Modify the Workflow startup code

Introducing namespaces

using System.Activities.DurableInstancing;  

To modify the Btnstartworkflow_click code:

            Sqlworkflowinstancestore store =    new Sqlworkflowinstancestore (@ "server=.\mssqlserver2012; database=workflowdb;uid=sa;pwd=yujie1127);             = store;

Only these two lines of code are required to perform the persistence work. So the next time I reopen the workflow, I need to find the workflow instance data from the database, and for the sake of simplicity, I'm going to put the primary key of the workflow instance directly to the from form interface, and usually at work, we use the data table to store the data information specifically.

5, change the FORM1 code, modify the Btncontinue_click

usingSystem;usingsystem.activities;usingSystem.Collections.Generic;usingSystem.Threading;usingSystem.Windows.Forms;usingSystem.Activities.DurableInstancing; namespacewindowsworkflowapp{ Public Partial classForm1:form { PublicForm1 () {InitializeComponent (); }        Static ReadOnly stringConnstr=@"server=.\mssqlserver2012;database=workflowdb;uid=sa;pwd=yujie1127"; //workflowapplication app;AutoResetEvent syncevent =NewAutoResetEvent (false); Private voidBtnstartworkflow_click (Objectsender, EventArgs e) {workflowapplication app=NewWorkflowapplication (NewActivity1 (),Newdictionary<string,Object>() {             {"InputName","God knife Zhang San"},{"Inputbookmarkname", Txtbookmarkname.text}}); Sqlworkflowinstancestore Store=NewSqlworkflowinstancestore (CONNSTR); App. Instancestore=store; Txtid.text=app.            Id.tostring ();            Workflowevent (app, syncevent); App.            Run ();        Syncevent.waitone (); }        Private Static voidWorkflowevent (workflowapplication app, AutoResetEvent syncevent) {#regionWorkflow Life Cycle Eventsapp. Unloaded=Delegate(Workflowapplicationeventargs er) {Console.WriteLine ("Workflow {0} unloaded.", er.            INSTANCEID);            }; App.completed=Delegate(Workflowapplicationcompletedeventargs er) {Console.WriteLine ("Workflow {0} completed.", er.                INSTANCEID);            Syncevent.set ();            }; App. Aborted=Delegate(Workflowapplicationabortedeventargs er) {Console.WriteLine ("Workflow {0} terminated.", er.            INSTANCEID);            }; App. Idle=Delegate(Workflowapplicationidleeventargs er) {Console.WriteLine ("Workflow {0} is idle.", er.                INSTANCEID); Syncevent.set (); //to wake up here and not let it, when a bookmark is created, the interface is stuck.             }; App. Persistableidle=Delegate(Workflowapplicationidleeventargs er) {Console.WriteLine ("Persistence of"); returnPersistableidleaction.unload;            }; App. OnUnhandledException=Delegate(Workflowapplicationunhandledexceptioneventargs er) {Console.WriteLine ("onunhandledexception in Workflow {0}\n{1}", er. InstanceId, er.                Unhandledexception.message); returnunhandledexceptionaction.terminate;            }; #endregion        }        //wake up the bookmark execution Process        Private voidBtncontinue_click (Objectsender, EventArgs e) {            #regionOld Code//this invokes the Preexecuteworkflow method and passes the value of the Txtnum.//app. Resumebookmark (txtbookmarkname.text, Int. Parse (Txtnum.text));             #endregionworkflowapplication App=NewWorkflowapplication (NewActivity1 ()); Sqlworkflowinstancestore Store=NewSqlworkflowinstancestore (CONNSTR); App. Instancestore=store;            Workflowevent (app, syncevent); App. Load (Guid.parse (Txtid.text)); //loading a workflow instance//continue with this workflow instanceApp. Resumebookmark (Txtbookmarkname.text,int.         Parse (Txtnum.text)); }    }}
View Code

6. We look at the data table, we have one more workflow instance data

7. Then close the application and restart

Find this ID from the database and fill it in.

We see that the entire workflow execution is complete and that the workflow instance data in the datasheet has been deleted.

SOURCE Download: Workflowconsoleapp3.zip

Workflow Notes 3--bookmark and persistence

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.