Micro-workflow engine-functional design

Source: Internet
Author: User

First, preface

In the previous article I gave you a description of my workflow model and basic design, this article I would like to explain in detail the function of my workflow and use examples. This workflow is mainly designed for developers, in order to let everyone have a global understanding, the design of the local function is not elaborate, the follow-up time I will continue to write articles to introduce to you.

Second, the function of the detailed and use the sample code

1, the configuration process engine , generally in the program startup process calls (in Global.asax.cs)

Initializes the process engine bpmconfiguration    . Instance ()    . Config (@ "C:\Configration\BpmConfig.xml")    . Start ();

If you do not specify a configuration file, the process configuration is read by default from app. Config or Web. config

Initializes the process engine bpmconfiguration    . Instance ()    . Start ();

It is also supported to launch multiple process engines at the same time to provide support for the SaaS program.

A tenant engine configuration bpmconfiguration    . Instance ("Tenanta")    
    . Start ();//b Tenant engine configuration bpmconfiguration    . Instance ("Tenantb")    . Config (@ "C:\BpmConfigB.xml")    . Start ();

The configuration in XML includes: Database connection, log profile, task schedule start delay, task schedule execution cycle, user relationship structure mapping, extension of variable type in process, etc.

2. Get The workflow context, which is the entry for the workflow, and all the functions are focused on this portal.

var bpm = new Bpmcontext ()    . UseTransaction (True)    . Setactor ("Xiangin");

Currently, the context is different for different engine instances

var bpm = new Bpmcontext ("Tenanta"), var bpm = new Bpmcontext ("Tenantb");

When constructing parameters is not passed, the default instance is returned.

3, transaction support , whether to open transactions, commit, rollback.

Bpm. UseTransaction (True); Bpm.commit (); BPM. Rollback ();


4. Process definition

New process definition BPM. Newprocessdefinition ("absence process")    . Setxmlfile (@ "C:\Definition\demo1.xml")    . Setcategory ("Category 1")    . Seteffectdate (DateTime.Now)    . Setexpiredate (DateTime.Now.AddDays ())    . Setmemo ("Memo1")    . Create ()   //Creates a process definition    . Parse ()    //Parse XML

When the process is created, the version number is automatically generated, starting from 1.0 by default, and when the process name is the same, a different version is generated.
In XML, different task nodes can be defined: Start node, automatic node, artificial node, decision node, divergence node, aggregation node, sub-process node, counter-sign node, waiting node, end node.
and connection Task node routing, staffing, variable definitions, event actions and other information, you can refer to my previous article in the XML definition

Load process definition var processdefinition = BPM. Loadprocessdefiniton ("1");p Rocessdefinition.deploy ();     Release process definition Processdefinition.revoke ();     Recall process Definition processdefinition.delete ();     Delete a process definition


5. Process examples

Initiating process instance var process = BPM. Newprocessintance ("Leave process", "Xiangin");p rocess. SetVariable ("project_id", 1399); Save process variables. Start ();   Start process. Suspend (); Suspends the process. Resume ();  Resume process. Cancel ();  Undo process. End ();     End

Here newprocessinstance there are three parameters on this method instance, the first one is the process definition ID, the second is the business ID to start, the third is the return stack point ID of the sub-process, and the non-subprocess can be ignored.

Start process var startTask = process. Start (); Starttask.setrecord ("SO20150903001");       Save Form Data (association) Starttask.setattach ("N", "" ");            Save the Attachment Information (association), can be multiple starttask.setvariable ("var1", "value1");    Save task variable starttask.signal ();                         Transfer to next step

Task. Setrecord is used to save the current form data ID, and the data itself is saved in the business table
Task. Setattach is used to save the attachment ID of the current node, and the attachment information is saved in the Attachment management table
Task. Signal the key method of process flow, triggering token token departure action According to the process definition

Approval task var task = BPM. Loadtaskinstance ("xx"); task. Setopinion (signresult.passed, "I Agree");  Set up approval comments task. Setreceiver ("Yan Manager");                    Sets the approver task for the next step. Signal ();                                Transfer to next step

This provides the Setreceiver method to set the next approver, normally defined in the process definition, is not required to set up, but consider in the actual application may have the task to the designated leadership approval, in the access OA can also set the next approver, This method is added and can be called when needed, note that applying this method overrides the setting of the owner property of the work item in the definition.

Task delegate var task1 = BPM. Loadtaskinstance ("Task1"); Assigncandidate ("Xiao Zheng, Xiao Hu");              Add task candidate Task1. Assigncandidate ("Saler", actortype.role); Add task candidate Task1. Assignto ("John Doe");                         Assign the task to John Doe

In my workflow, there can be only one owner (owner), one actual operator (actor) for a work task, but multiple candidates (candidate).
A candidate is a limited or a list of people currently assigned to work, and owner is the owner of the task, and the actor is the operator calculated after the owner considers the complex Commission relationship.
Task. Assigncandidate This method is used to add a task candidate, the second parameter is the object type, you can add a role, organization, user group, etc. directly.
Task. Assignto is the assignment of tasks, the assignment status of tasks includes the following States

public enum assignstatus{    //Pending    Pending,    //Claim, user claim task and receive task input data    Claim,    //Commission, delegate to another person (for example, Manager) in place of him or her to perform a task    depute,    //expires, does not process the approval task Expire,//renewal in the specified time period,    does not process this task within a given timeframe, the task is renewed in order to execute within another time period    Renew}

If the process is stuck to a node for a long time, we can send reminders messages
If a process node does take a long time to complete, I have designed a current work progress reporting interface

Work Reminders task. Urge ("very urgent, please manager ASAP, online etc!") ");//Report Current work Progress task. Report (0.6, "expected to be completed this week");

Task. Urge sends a reminders notification to the actual owner of the task and generates reminders history.
Task. Reports sends a progress report to the Subscriber of the task (all who are interested in the current process task).

Query variable var var0 = process. GetVariable ("project_id"); var var1 = Task1. GetVariable ("var1"); var var2 = Task1. Getvariable<datetime> ("var2"); var var3 = Task1. GetVariableObject ("Var3");

The variables are divided into three types:
Process variables persist over the entire process cycle
The task variable is persisted and exists in the current task
Temporary variables are not persisted to the database and only exist in the current execution context (ExecutionContext).
Set variable setvariable get variable getvariable
Supports arbitrary data types

6, the Chinese characteristics of the examination and approval methods , mainly including the signing, plus sign (before, add sign, and add sign), reduce the sign, free flow
Sign-off: A task involving multiple individuals to make decisions together
Add: This task I feel unsure, want to join a person or more people with me to make a decision (before the first sign in the order before the current decision-maker, after the signing order in the current decision-maker, and add the order in parallel processing)
To cancel a person's eligibility to participate in a decision, as opposed to adding a sign
Free flow: No in the process definition, the temporary added dynamic route sends the current work directly to the specified node for approval.
Transfer: The general approval node of single-person decision-making is turned into a multi-people joint decision-making of the counter-sign node, supporting the recursive counter-sign, that is, the countersigned node can continue to transfer the signing node.
Transfer approval: A general approval node that is converted into a single decision by a multi-person joint decision-making node

In my workflow, the following parameters are designed:
A operation mode, and when the row such as divergent nodes, enter the counter-sign node will be activated at the same time all the participants work tasks, the sequence is sequential, so there is a pre-plus and post-plus sign

public enum runmode{    //serial    Serial,    //parallel    Parallel}

B decision-making mode, according to the results of the sub-node how to go to the decision-signing node

public enum decisionmode{//    Organizer mode    Sponsor,         //voting mode    Vote,         //One vote passed    OnePass,         //one vote rejected    Oneveto}

Organizer mode: Need to set up a sponsor, the result of the organizer's decision-making, other people's decision only to provide reference
Voting mode: That is, to set a passing ratio, which is decided by the people to vote. Support to set the voting weights for everyone.
One vote passed: In fact, it can be seen as voting mode is set to a rate greater than 0%.
One vote veto: can be seen as a voting mode pass rate setting of 100%.
Of course, this is just a few of the commonly used patterns listed, but also to expand their own decision-making mode, only to inherit the implementation of my definition of the abstract class decision can be.

C Whether or not to wait, that is, there have been no votes, but the current vote has been able to determine the outcome of the case, need not wait for the other person to complete the vote before continuing to transfer the next step.

Two types of sign-off, one is defined in the process definition of the sign, one is the general approval node temporarily turned into a sign. In fact, the Chinese-style approval is to be flexible, if defined in the process definition, in fact, can not sign the node, with a number of ordinary nodes can also be implemented. The design of the sign-up node is mainly for the transfer of this scenario: is the current general approval node of the approver feel that they are not sure or do not want to take responsibility, can join the higher leadership or other people together to make decisions or provide reference.

Example: General approval transfer sign run mode set to parallel, decision mode is weighted vote, need to wait for everyone to vote, by line 65%

Transfer sign var task2 = BPM. Loadtaskinstance ("02"); Task2. Tocountersign (Runmode.parallel, Decisionmode.vote, True, 0.65M); Task2. Countersignadd (New Countersigner () {actor_id = "Zhang San", vote_weight = 1}), Task2. Countersignadd (New Countersigner () {actor_id = "John Doe", Vote_weight = 0.5}), Task2. Countersignadd (New Countersigner () {actor_id = "Small Five", vote_weight = 2});

Parallel mode is and add the sign, the pre-plus sign, post-Add the premise is the serial mode, assuming that TASK2 for serial, sponsor mode, the original approval man Xiangin

Pre-signed Task2. Countersignaddbefore ("Xiangin", new Countersigner () {actor_id = "Zhang San"});//Add sign Task2 after. Countersignaddafter ("Xiangin", new Countersigner () {actor_id = "John Doe", Is_sponsor = true});

The minus sign is relatively simple.

Minus sign Task2. Countersignremove ("Harry");

Sign-off node to general approval, directly make a person decision

Transfer approval Task2. Tosinglesign ("The Old King Next Door");

Free-flow mode, create a temporary path to jump directly to the specified node for approval

Free flow var task3 = BPM. Loadtaskinstance ("Task3"); Setfreeredirect ("General manager approval"); Task3. Signal ();


7. Fallback mechanism
Process fallback to the specified node

The process instance specifies any node fallback var process2 = BPM. Loadprocessinstance ("the");p Rocess2. Rollback ("Fill out the Absence form");

Task instance fallback to previous step

Current work task fallback to previous approval node var task4 = BPM. Loadtaskinstance ("Task4"); Rollback ();


8. Office of the Working Committee
Zhang San a task directly entrusted to John Doe to handle, support the recursive Commission relationship, that is, Zhang San entrusted to John Doe, John Doe entrusted to Harry, Harry entrusted to Zhao Liu ...

Bpm. Newdeputeservice ("Zhang San", "John Doe")   . Fortaskinstance ("task Instance ID")   . Depute ();

Delegate the entire process instance to John Doe, where all Zhang San tasks under this process instance are delegated to John Doe

Bpm. Newdeputeservice ("Zhang San", "John Doe")   . Forprocessinstance ("process instance ID")   . Depute ();

Delegate a task node in a process definition to John Doe, that is, all task instances created by this node are delegated to John Doe if they are Zhang San tasks

Bpm. Newdeputeservice ("Zhang San", "John Doe")   . Fortaskdefinition ("Task definition id")   . Depute ();

Delegate a process definition to John Doe, which is all the task instances created in the process, and if it is a Zhang San task, it will be delegated to John Doe during the effective period of the setup.

Bpm. Newdeputeservice ("Zhang San", "John Doe")   . Forprocessdefinition ("Process definition id")   . Setdaterange (DateTime.Now, DateTime.Now.AddDays (30))//during the effective period   . Setmemo ("Business this month, this process is entrusted to Li Shide Office")            //delegation of instructions   . Depute ();

Retract the delegate relationship, just replace the revoke with the depute action

Retract the work of the Commission BPM. Newdeputeservice ("Zhang San", "John Doe")   . Forprocessinstance ("process instance ID")   . Revoke ();


9. Follow subscription
This function is similar to a delegate, and will receive a process dynamic or task dynamic message alert after a subscription, such as: Process created, started, suspended ..., task created, assigned to, progress report, task completed, etc.

Focus on subscribing to BPM. Newsubscribeservice ("Zhang San")   . Fortaskinstance ("task Instance ID")   . Subscribe (); BPM. Newsubscribeservice ("Zhang San")   . Forprocessinstance ("process instance ID")   . Subscribe (); BPM. Newsubscribeservice ("Zhang San")   . Forprocessdefinition ("Process definition id")   . Subscribe (); BPM. Newsubscribeservice ("Zhang San", "John Doe", "Harry")   . Fortaskdefinition ("Task definition id")   . Subscribe ();

To unsubscribe, just change the subscribe to unsubscribe

Unsubscribe from BPM. Newsubscribeservice ("John Doe")   . Forprocessdefinition ("procurement process")   . Unsubscribe ();


10. Data query
Query I do not provide an interface, direct open database queries are more flexible than the interfaces I provide, such as:
A querying the published process definition

SELECT * from bpm_definition_process where state = ' Deploy '

Process definition states include

public enum processdefinitionstate{    //Create created    ,    //Parse    parse,    //release    Deploy,    //Recycle    Revoke,    //remove Delete    }

b My Process

SELECT * from bpm_instance_process where state = ' Run ' and starter = ' Xiangin '

Process status includes

public enum processstate{    //Creates create    ,    //runs run    ,    //Hangs    Pending,    //terminates    termination,    //Completed    Complete,    //Cancel the Cancel    }

c My to-dos

SELECT * from bpm_instance_task where state = ' Run ' and actor_id = ' Xiangin '

To-do tasks include tasks entrusted to you by others, and if you want to see only the tasks that belong to you, you can

SELECT * from bpm_instance_task where state = ' Run ' and owner_id = ' Xiangin '

Task status includes

public enum taskstate{    //Create, task has been created create    ,    //block, arrival line has blocking task not completed    Blocking,//    start    Run,       //Completed, the user has completed the task and provided the output data    of the task Complete,    //failed, user has completed the task and provided error message    Failure,    //fallback    Rollback}

D. Candidate information for the query task

SELECT * from bpm_instance_assignment where task_instance_id = ' id '

E to query My message

SELECT * from bpm_application_notify where state= ' unread ' and reciever_id = ' Xiangin '

Other queries are no longer examples.

Iii. Summary

I have said before that I developed this engine in order to do the project, there is a lightweight, easy to introduce a single DLL file (post-release size of 1.1M) of the workflow engine, interface is simple and easy to develop two times, support multi-database and powerful. From the beginning of the previous year to a simple version of the design and development of the basic form now, the test also took a lot of time, there may be problems not measured, but now basically stable. Next, if there is time, I will slowly introduce to you the design and implementation of functional details, and what features I have not considered the whole or opinion or what part of the need to learn more about the can give me a message.

Micro-workflow engine-functional design

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.