Persistence operation 1 of WF4.0: SQL server storage

Source: Internet
Author: User
Can a non-persistent WF be called a complete WF? The answer is no. If the WF cannot be persistent, the process needs to be executed once and all operations must be performed once, but is the actual workflow like this? The answer is also no. A voting process requires multiple judges to vote and then determine the leader with the highest votes to enter

Can a WF without durability be called a complete WF? The answer is no. If WF cannot be durable, the process needs to be executed once, all operations must go on once. But is the actual workflow like this? The answer is also no. A voting process requires multiple judges to vote and then determine the leader with the highest votes to enter

NoPersistentCan a fully-qualified WF be called? The answer is no. If WF cannotPersistentThen the process needs to be executed once.OperationIt takes a while to proceed. But is the actual workflow like this? The answer is also no. A voting process requires multiple judges to vote and then determine the leader with the highest votes to enter the next process.PersistentThe data used by each judge in this process (the public data to be processed in the process may be simple or complex) is completely different, even everyone is different. We need to record data in each step and perform summary analysis at the end of the process. Obviously, the process does not proceed step by step based on the original idea, therefore, we need to maintain a pending state before all the votes are completed. The process will be completed only after all the votes are completed.Persistent.

PersistentBookMark for analysis:

InPersistentPreviously, I mentioned the need to suspend the status. Why do you need to suspend the status?Operation. In WF, a BookMark is a BookMark. As the name suggests, it stores a BookMark and ends temporarily. If you need to locate the last stop point based on the BookMark, continue.Operation.

PersistentInstanceStore for analysis:

This class is provided by WFPersistentOfOperation, WF already contains a SqlWorkflowInstanceStore that implements it, which is used to save it to the database. Of course, this article also introduces another method that uses XMLMethod. There are some requirements for such databases to be saved. The SQL scripts used are provided by Microsoft, which will be described in the following sections.

PersistentPersistenceParticipant:

PersistenceParticipant class or the PersistenceIOParticipant class (derived class of the PersistenceParticipant class), implements abstract methods, and then add an instance of the class as a workflow instance extension. ">PersistentA sex participant is derived from the PersistenceParticipant class or the PersistenceIOParticipant class (a derived class of the PersistenceParticipant class) to implement an abstract method, and then an instance of the class is added as a workflow instance extension. WorkflowApplication and WorkflowServiceHost look for such extensions when persisting an instance and invoke appropriate methods at appropriate times. "> WorkflowApplication and WorkflowServiceHost search for such extensions when the instance is retained, and call appropriate methods at the appropriate time. According to the MSDN explanation, we can see that this class is customized.PersistentClass to be inheritedMethodPersistentWe will use SQLMethodYou do not need to customize the specific information.

WorkflowApplication and WorkflowServiceHost look for such extensions when persisting an instance and invoke appropriate methods at appropriate times. ">

By now, our key technical analysis has been completed. One BookMark class, one InstanceStore class, and three customized PersistenceParticipant classes are used together to complete ourPersistent.

PersistentBusiness Analysis for implementation:

Step 1: Let's first analyze a process. If there are several judges to vote, we need all the judges to vote before the process can proceed to the next step, the voting here can be considered that the judges need to log on to the system to vote, and the voting order and time are not sure,
The Analysis and Design workflow is as follows:

A process that includes DoWhile and Foreach. DoWhile controls whether multiple approvals are performed. ForEach is used to traverse all judges and create multiple bookmarks. Note the Parallel loop used here, synchronize the process of creating bookmarks. If ForEach is used, only one bookmarks will be created;

Create bookmarks in If to synchronize the process.PersistentAt the same time, each activation of one or morePersistentUntil the process ends.

PersistentBookMark class:

This type of code is relatively simple and can be directly pasted out.

 public sealed class WaitForVote
 
  : NativeActivity
  
       {        public InArgument
   
     UserId { get; set; }        public InOutArgument
    
      InOutRequestForExpert { get; set; }        protected override void Execute(NativeActivityContext context)        {            string name =  this.UserId.Get(context).ToString();            context.CreateBookmark(name, new BookmarkCallback(OnReadComplete));        }        void OnReadComplete(NativeActivityContext context, Bookmark bookmark, object state)        {              string[] input = (string[])state;            context.SetValue(this.Result, input);            RequestForExpert requestForExpert = context.GetValue(InOutRequestForExpert);            requestForExpert.ExpertList.Find((ExpertInfo expert) => { return expert.UserId == input[0]; }).IsConfirmed=true;            context.SetValue(InOutRequestForExpert ,requestForExpert);        }        protected override bool CanInduceIdle        {            get            {                return true;            }        }
    
   
  
 

This class inherits NativeActivity. For more information about this class, see MSDN.
This class consists of the following parts:
1. An InArguement parameter, used to receive the name of the bookmarks
2. Rewrite the Execute method to create bookmarks. The parameters passed are used as the name of the bookmarks, and the activation callback method is specified.
3. specify an activation callback Method for BookMark. You can pass a value when activating a BookMark. In this method, you can process the value and pass it to the page (InOutRequestForExpert is the value that the page passes to the BookMark, modify this method and return to the page)
4. Set the CanInduceIdle attribute to true.Persistent.

PersistentImplementation of the host class:

Interface IExpertHost {////// Create and run a WorkFlow instance /////////
 WorkflowApplication CreateAndRun (RequestForExpert rfe );////// Load the WorkFlow instance /////////
 WorkflowApplication LoadInstance (Guid instanceId );////// Can the current project be voted //////Instance id///Judge No.///
 Bool CanVoteToInstance (Guid instanceId, string userId );////// Vote //////WorkFlow instance id///Project No.///User ID///Recommendation judge no.Void Vote (Guid instanceId, string userId, string selUserId );}

First, let's look at the implementation of CreateAndRun:
An Enumeration type is defined to indicatePersistentSQLMethodOr XMLMethod

 public enum StoreType    {        Sql, Xml    }

Public WorkflowApplication CreateAndRun (RequestForExpert rfe) {IDictionary
 
  
Inputs = new Dictionary
  
   
(); Inputs. add ("InRequestForExpert", rfe); // instantiate the workflow object Activity wf = new ExpertWorkFlow (); WorkflowApplication instance = new WorkflowApplication (wf, inputs); instance. persistableIdle + = OnIdleAndPersistable; instance. completed + = OnWorkflowCompleted; instance. idle + = OnIdle ;//
   PersistentGetSqlInstanceStore (instance, StoreType. SQL); instance. Run (); return instance ;}///
   /// SetPersistentInformatizationMethod//////
   Private void GetSqlInstanceStore (WorkflowApplication instance, StoreType storeType) {switch (storeType) {case StoreType. SQL: SqlWorkflowInstanceStore sqlInstanceStore = new SqlWorkflowInstanceStore (connectionString); InstanceView view = sqlInstanceStore. execute (sqlInstanceStore. createInstanceHandle (), new CreateWorkflowOwnerCommand (), TimeSpan. fromSeconds (30); // sets the default instance owner sqlInstanceStore. defaultInstanceOwner = view. instanceOwner; instance. instanceStore = sqlInstanceStore; break; case StoreType. xml: XmlWorkflowInstanceStore store = new XmlWorkflowInstanceStore (instance. id); instance. instanceStore = store; break; default: break ;}}
  
 

    // executed when instance goes idle        public void OnIdle(WorkflowApplicationIdleEventArgs e)        {        }        public PersistableIdleAction OnIdleAndPersistable(WorkflowApplicationIdleEventArgs e)        {            return PersistableIdleAction.Unload;        }        // executed when instance is persisted        public void OnWorkflowCompleted(WorkflowApplicationCompletedEventArgs e)        {        }

A WorkFlowApplication workflow application object is created in the preceding method, and the PersistableIdle is bound. This function describes how to usePersistentInformatizationMethodIn this example, Unload is used to uninstall andPersistentSo that the instance will not be locked during Load.

SetPersistentInformatizationMethodSQL is used hereMethodOfStorage, InStorageThe method mainly specifies the database to be saved. This database is not a general database and requires a special SQL script. Do not worry that this script is already in your computer, open the directory "C: \ Windows \ Microsoft. NET \ Framework \ v4.0.30319 \ SQL \ en"

Create a database named WorkflowInstanceStore (customizable). Execute the second file before executing the first file.

Next let's look at other methods:

////// Load the workflow ////////////
 Public WorkflowApplication LoadInstance (Guid instanceId) {WorkflowApplication instance = new WorkflowApplication (new ExpertWorkFlow (); instance. completed + = OnWorkflowCompleted; instance. persistableIdle + = OnIdleAndPersistable; instance. idle + = OnIdle ;//PersistentGetSqlInstanceStore (instance, StoreType. SQL); instance. Load (instanceId); return instance ;}////// Check whether the current judge can vote and whether the judge has voted ////////////
 Public bool CanVoteToInstance (Guid instanceId, string userId) {WorkflowApplication instance = LoadInstance (instanceId); // The foreach (BookmarkInfo item in instance) is not voted unless the current bookmarks exist. getBookmarks () {if (item. bookmarkName. equals (userId) {return true;} return false ;}////// Vote //////Workflow instance Id///User ID///Recommended user IDPublic void Vote (Guid instanceId, string userId, string selUserId) {WorkflowApplication instance = LoadInstance (instanceId); // unless the current bookmarks exist, no foreach (BookmarkInfo item in instance. getBookmarks () {if (item. bookmarkName. equals (userId) {instance. resumeBookmark (userId, new string [] {userId, selUserId}) ;}} instance. unload ();}

A method used to load a workflow, and a method used to determine whether a vote can be performed (if the bookmarks corresponding to the current judges still exist, you can vote. Note that the names of the bookmarks here are the judges Id, however, this is not important. You can decide what to use in your own program.

You need to use the same value for bookmarks to find the bookmarks.) One is the voting method (mainly used to activate bookmarks ).

PersistentImplementation:
Here, the work of WorkFlow has been completed to see how to call it. Here I use WCF to combine WorkFlow with the Web end, so I added a WCF project WFWCF (included in the source code) and added the WCF IExpertWCF

[ServiceContract] public interface IExpertWCF {////// Create a workflow //////[OperationContract] void CreateWorkFlow (RequestForExpert rfe );////// Vote ////////////[OperationContract] void Vote (Guid instanceId, string userId, string selUserId);} public class ExpertWCF: IExpertWCF {private string ConnectionString = ConfigurationManager. connectionStrings ["ApplicationServices"]. connectionString ;////// Create workFlow //////Public void CreateWorkFlow (RequestForExpert rfe) {ExpertProcessHost host = new ExpertProcessHost (); host. CreateAndRun (rfe );}////// Vote ////////////Public void Vote (Guid instanceId, string userId, string selUserId) {ExpertProcessHost host = new ExpertProcessHost (); host. Vote (instanceId, projectId, userId, selUserId );}}

The method is very simple. A method for creating a workflow, a method for voting, can be directly called by instantiating the ExpertProcessHost object.
Finally, let's look at the page design.

Homepage, used to create a Workflow

Click the button to claim the following data (different data values) in the database, and the Id column is the InstanceId to be used on the voting page.

On the voting page, enter the InstanceId and click "Vote" to vote and activate the corresponding user's bookmarks (the user here is fixed and can be modified by themselves, and the InstanceId can be obtained through debugging, or from the InstancesTable table of the database). When all bookmarks are activated, the process ends and the database automatically deletes the data. So far, SQLMethodOfPersistentThe next article will introduce the XMLMethodOfPersistentInformatizationOperation.

The source code is in the next article.

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.