Search This Blog

Friday, October 17, 2014

Out Of Box && Sequential && State Machine Work Flow Type(All) With Scenarios And Example

1- sequential  Workflows
SharePoint provides a set of workflows:
  1. Out-of-the-box Workflows
    1. Approval
    2. Collect Feedback
    3. Collect Signature
  2. SharePoint Designer Workflows
  3. Visual Studio Workflows
    1. Sequential
    2. State Machine

“People are often confused what should be the best workflow for given scenario.”

I would suggest the following Priority of choosing workflows:
  1. Go first with Out-of-the-box workflow
  2. If not possible, Go with Designer workflow
  3. If still not possible, Go with Visual Studio workflow

Scenario 1: Document Approval

Following is a simple use case:
  1. Employee creates a Document
  2. Document needs Approval from Manager
  3. End of Workflow

Solution

We can use the Out-of-the-box workflow to address the scenario.
  • SharePoint Approval Workflow
image
Even if multiple Approvers are needed, we can still use the Approval workflow.
image

Scenario 2: Expense Submission

Following is a another use case:
  1. Employee submits Expense Item
  2. If Expense Amount > $1000
    1. Send Notification to Manager
    2. Else end the Workflow
Scenario Type: Sequential until Completion

Solution

There are no out-of-the-box workflows to address this scenario.
The type of workflows appropriate are marked in bold:
  1. Out-of-the-box Workflows
  2. SharePoint Designer Workflows
  3. Visual Studio
    1. Sequential Workflows
    2. State-Machine Workflows
Designer Workflow would include an If Condition and Email Action:
image

Scenario 3: New Employee Hire

This is a bit complex scenario.  Following are the steps involved:
  1. Candidate Submits Resume, which is captured in a List
  2. Forward to HR Manager
  3. HR Manager validates & proceed the document to Technical Interviewer
  4. Interviewer conducts Interview
    1. If Interview is Passed, proceed to Hiring Manager
      1. Hiring Manager proceeds with Offer Letter
      2. Candidate accepts the Offer
        1. Candidate joins the Company, Convert Candidate to Employee
        2. Proceed to Payroll Manager
        3. Proceed to Infrastructure Department for System, Email, Credential Allocation
        4. Notify Employee Manager
        5. End of Workflow
      3. Candidate rejects the Offer, End of Workflow
    2. If Interview is Failed, End of Workflow
Scenario Type: Sequential with Manual Intervention

Solution

The type of workflows appropriate are marked in bold:
  1. Out-of-the-box Workflows
  2. SharePoint Designer Workflows
  3. Visual Studio
    1. Sequential Workflows
    2. State-Machine Workflows
Please note that the above Scenario have a Sequential flow.

Visual Representation

We can visually represent the above steps as:
image

Status Column

We can introduce the Status column in various stages of the flow, as shown below:
image
The type of workflows appropriate are marked in bold:
  1. Out-of-the-box Workflows
  2. SharePoint Designer Workflows
  3. Visual Studio
    1. Sequential Workflows
    2. State-Machine Workflows
Designer Workflow would not be perfect fit for this scenario.  But we can create a Designer Workflow with multiple If Conditions & Email Actions.  
The tricky part here is to invoke the workflow on:
  1. Item creation event
  2. Item updating event
Additionally, we have to ensure a Resting State to prevent duplicate execution of Actions on the update event.
Following is the workflow Conditions & Actions within SharePoint Designer.
image
image
We need to make sure the workflow is invoked on creation & updating.
image
Please note the following:
  1. Designer workflow starts on item creation & stops after completing a condition & corresponding action.
  2. Another update even triggers a new workflow instance creation & stops after completing a condition & corresponding action.
State Machine Workflow would be perfect fit for this scenario as State change triggers the execution of set of actions. 
In the case of State Machine workflow, the Intermediate States are persisted.  Based on each state change, further actions are invoked.  Plus, a state can go back to a previous state creating a loop.
Summary
Out-of-the-box Workflows are preferred for the most cases.
Designer Workflows are the next option to Out-of-the-box Workflows, with less deployment hassles.
Visual Studio > Sequential Workflows are Good for Sequential Actions until Completion.
Visual Studio > State Machine Workflows are Good for State based Operations & Looping back.

Create a New Workflow for a SharePoint 2010 Document Library





















































































































































The window shows a workflow in progress. You click Home























































***********************************************************************************************************When Add Item In LIst Work Flow Status Is Show Completed 
Create a Sequential workflow using visual Studio 2010 in SharePoint 2010
***********************************************************************
In this post we will discuss how to create a sequential workflow using Visual Studio 2010 in SharePoint 2010.
Also you can check out:




Follow below steps to create the sequential workflow:

1. Create New Project using visual studio 2010.

2. In the New Project dialog box, Select the SharePoint and then select the 2010.

3. Now select the Sequential Workflow Template.

4. Enter the name of Workflow and then click ok. See in fig


5. Now enter the site url that you want to use it for debugging.

6. Select Deploy as a farm solution and then click Next.

7. Now leave the name of workflow and select the List Workflow. See in fig


8. Click on Next

9. Now select the list or library to associate your workflow. See in fig


10. Specify the conditions for how your workflow should be started. See in fig.


11. Click on Finish.
12. See the following code for Workflow1.cs
 using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Drawing;
using System.Linq;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.WorkflowActions;
namespace WorkflowProject1.Workflow1
{
    public sealed partial class Workflow1 : SequentialWorkflowActivity
    {
        public Workflow1()
        {
            InitializeComponent();
        }
         public Guid workflowId = default(System.Guid);
        public SPWorkflowActivationProperties workflowProperties = new SPWorkflowActivationProperties();
    }
}
13. And see the onWorkflowActivated1 properties. See in fig

14. Now Save the solution and click on Deploy.

15. Now Open your SharePoint site and go to custom list to which the workflow is associated by you.

16. Create a new item and you could be able to see a new column name which shows the status of workflow. See in fig.


17. In this project I have not added any activity so the workflow status will show completed. 

*****************************************************************************
Using Worng Title THen To send Email To  Administrator
******************************************************
Creating a Sequential WorkFlow in Visual Studio with some extra bits
In this article I am going to post how to create a simple sequential workflow with Visual Studio 2010 for Sharepoint 2010. The goal of this project is to change the Title of the documents when someone inserts a bad word. It is basically a parent control for our document library [“Shared Documents”].
What do we need?
  1. Visual Studio 2010.
  2. Sharepoint 2010.
  3. A list called Shared Documents (it comes by default).
  4. 20 minutes of your time.
Step 1Go so Visual Studio 2010->New Project->Sharepoint->2010->Empty Sharepoint Project, call it netsourcecodeWorkflows, click ok and deploy as farm solution. Go to your project right click->Add->New Item…->Sharepoint->2010->Sequential Workflow-> call it NSCParentalWorkflow.
image
Step 2Select List Workflow because we will be working with one list. Click Next
image
Step 3Select Shared Documents. Click Next
image
Step 4Leave the default values are they are. Click Finish.image
Step 5Now go your workflow (NSCParentalWorkflow.cs) double click and open the designer. Drag and drop an activity “While” just below OnWorkFlowActivated. Double click in the While activity->Properties->Condition->select Code Condition->Condition—>Type isWorkflowFinish and return.
image
Step 6Double Click on “onWorkflowActivated1”, that will create an event for you.
image 
Step 7Now get one of the events from the tool bar menu, for example “onWorkflowItemChanged”, drag and drop inside the while. Single click in the event and go to Properties->Correlation Token->select workflowToken. Now do a double click to create the event. You should see something like this:
image
Step 8It is time to add the logic behind, but before that, we should find a bunch of bad words for our parental control. Because in our “virtual” company we have English people and Spaniards, we should check both languages. Anyway this is a list of bad words, combined.
  • Fuck (en)
  • Cunt (en)
  • Mother Fucker (en)
  • Piece of Shit (en)
  • Bastard (en)
  • Joder (es)
  • Gilipollas (es)
  • Puta (es)
  • Mierda (es)
  • Cabron (es)
Our workflow will check the Title, if some one tries tries to change it with a bad word it will set the filename and it will send and email to the administrator.
Step 9Go to NSCParentalWorkflow.cs right click –> View code. Remove all the code inside and paste this one:
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Drawing;
using System.Linq;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.WorkflowActions;

namespace netsourcecodeWorkFlows.NSCParentalWorkFlow
{
    public sealed partial class NSCParentalWorkFlow : SequentialWorkflowActivity
    {
        public NSCParentalWorkFlow()
        {
            InitializeComponent();
        }

        public Guid workflowId = default(System.Guid);
        public SPWorkflowActivationProperties workflowProperties = new SPWorkflowActivationProperties();

        private bool isWorkFlowActive;

        private void OnWhile(object sender, ConditionalEventArgs e)
        {
            e.Result = isWorkFlowActive;
        }

        private void onWorkflowActivated1_Invoked(object sender, ExternalDataEventArgs e)
        {
            isWorkFlowActive = true;
           
            CheckTitle();
        }

        private void onWorkflowItemChanged1_Invoked(object sender, ExternalDataEventArgs e)
        {
            CheckTitle();
        }

        private void CheckTitle()
        {
            string _sTitle = workflowProperties.Item["Title"]!=null?workflowProperties.Item["Title"].ToString():"";
            string _sFileRef = workflowProperties.Item["FileLeafRef"].ToString();

            switch (_sTitle.ToLower())
            {
                case "fuck":
                case "bastard":
                case "cunt":
                case "mother Fucker":
                case "piece of Shit":
                case "joder":
                case "gilipollas":
                case "puta":
                case "mierda":
                case "cabron":
                    {
                        workflowProperties.Item["Title"] = _sFileRef;
                        workflowProperties.Item.Update();
                        isWorkFlowActive = false;
                        SendEmailToAdministrator();
                        break;
                    }
                default: break;
            }          
        }

        public void SendEmailToAdministrator()
        {
            System.Collections.Specialized.StringDictionary _aHeaders = new System.Collections.Specialized.StringDictionary();

            _aHeaders.Add("to", "admin@netsourcecode.com");
            _aHeaders.Add("from", "admin@netsourcecode.com");
            _aHeaders.Add("subject", "This guy is inserting bad words into our DMS");
            string _sBody = SPContext.Current.Web.CurrentUser.Email;

            Microsoft.SharePoint.Utilities.SPUtility.SendEmail(workflowProperties.Web, _aHeaders, _sBody);
        }
    }
}

Step 10Deploy the project, add an item, and try to edit a document and insert a bad word. The Title will revert itself to the file name.

Click the Icon to download the Icon.
image

********************************************************************
When created or uploaded in a particular list or document library Email Is Send
**************************************************************
If we want to alert user when a new item is created or uploaded in a particular list or document library, we can do this by using workflow.
First, we have to create a new project in Visual Studio 2008 by click on
File-->New-->Project.
Then, select Visual C#-->Office-->2007-->SharePoint 2007 Sequential Workflow.
Now, give a name of the Workflow and click on Ok. It will go to the next screen named "New Office SharePoint Workflow". We are providing the site url where we want to debug the Workflow and click on Next. Now we have to select the Library or List from the drop down list. Workflow will work on the selected list. Now click on Next.
This screen will give us the option to select the workflow starting process. Here, We are selecting all the options and click on Finish.
Now we are in the workflow design screen. Just double click ononWorkflowActivated1 and it will take us toonWorkflowActivated1_Invoked event.
We have to add Microsoft.SharePoint.Utilities Namespace with the existing Namespaces. This Namespace will help us to send Email.
Now, inside the onWorkflowActivated1_Invoked event, we have to write the following code:-
SPUtility.SendEmail(workflowProperties.Web, true, true, "Email Address where to send the mail", "Subject Of the Mail", "Body Of The Mail");
We have to debug the solution then, and after that workflow will work

*******************************************************

Seqential workflow in SharePoint 2010 using Visual studio 2010

*******************************************************
n this article we will work on developing sequential workflow in SharePoint 2010 usingVisual studio 2010.
let start creating new project of type Sequential Workflow ,under SharePoint 2010 in Visual studio 2010.


Deploy as form Solution. Click Next

Name workflow as devendra Sequential workflow and select site workflow.
click on Next

CLick Next.

CLick Next.


Click on Finish.
It will show the below project structure.

Go to tool box. Select Create Task under SharePoint workflow

Drag and drop below onworkflowActivated .

Click on the redmark in Createtask1 control

Click on Activity ‘createTask1’ does not have Correlation property set.
Give the Correlation token as Task token.
Select Owner ActivityName as Workflow1.

Click on TaskProperties.Select Bind to new member.
Select create Field. Click OK.

Go to workflow.cs[design] --> right click --> View Code
It will redirect to the code file workflow.cs file you can see the filed you have added just now.
If you check the Bind to existing member you can the Field added it.


Click on TaskID from the properties of CreateTask activity. Select Bind to new member.
Select create Field. Click Ok.
Go to workflow.cs[desgin]-->right click -->View Code
It will redirect to the code file workflow.cs file you can see the filed you have added just now.

Go to Workflow1.cs-Desgin.
Double click on Create Task Activity.It will generate a method called createTask1_MethodInvoking.
Write the below code in the method.

       private void createTask1_MethodInvoking(object sender, EventArgs e)
  {
      createTask1_TaskId1 = Guid.NewGuid();

      createTask1_TaskProperties1.Title = "New Task";
      createTask1_TaskProperties1.Description = "Please complete this ASAP";
      createTask1_TaskProperties1.AssignedTo = workflowProperties.Originator;

  }

The above code create the task for user we runs the workflow.
Go to ToolBox select LogtoHistoryListActivity under Sharepoint workflow

Drag and drop the LogtoHistoryListActivity to workflow.cs[design] file below create task

Click on logToHistoryActivity1 Press F4 to see the properties.
Click on History Description.

Click OK.
Check the properties logToHistoryActivity1

Right click on logToHistoryActivity1.
Click on Generate Handlers.

A method will get generate with the name logToHistoryListActivity1_MethodInvoking
Paste the below code inside the method.
private void logToHistoryListActivity1_MethodInvoking(object sender, EventArgs e)
  {
  logToHistoryListActivity1_HistoryDescription1 = "Work Flow is Running on " + workflowProperties.Web.Url;
  }

Select the project. Right click and Deploy.

Go to Site Actions->View AllsiteContent.

Select Site Workflows.

Click on Devendra Seqential workflow.


Click on status completed.
You can see the web site URL under Description.

You can check the task also has been created in task list for the user who has run the workflow.
*****************************************************************************************
2- State Machine  Work Flow

How To... Create and debug a state machine workflow in SharePoint 2010 using Visual Studio 2010 and c# Part 1

Part 1 Creating the Visual Studio 2010 solution for our workflow

This is Part 1 of 4 for creating a state machine workflow using SharePoint 2010 with Visual Studio 2010 and c#. To read the introductions please click here.
Let’s get started and create our workflow using Visual Studio 2010.
We will now create our Visual studio solution and do a little bit of spring cleaning in the solution to make it easier to work with.
Creating the VS project.
  • Load up Visual Studio 2010
  • Select new project
  • Select c#
  • Select SharePoint
  • Select SharePoint 2010
  • Select the state machine workflow template
  • Call the project DevJobsStateWorkflow


  • Then click the ok button.
The SharePoint customization wizard will now appear
  • Select the URL for your team site (where your DevJobs libray exists)
  • Select Deploy as a farm solution. (sandboxed solution should be greyed out)
  • Click next
On the ‘specify the workflow name for debugging’ screen:
  • Change the workflow name to DevJobsStateWorkflow
  • Select List workflow

  • Click next.
Select the lists you will use whilst debugging:
  • Select DEVJobs in the library or list to associate yr workflow.
  • Click next.
    On the specify the conditions for how your workflow is started screen
  • Check a user manually starts the workflow
  • Check the workflow starts when an item is created.

  • Click Finish.

The solution will now be created. That’s the simple bit done ;-)

Solution Tidy up – Time for a Spring Clean

By default our project will name the workflow as workflow1 everywhere which is meaningless, useless and generic for all new workflows. So let’s give it a semi meaningful name for our simple solution.

Let us start by renaming the workflow to be called ‘WorkFlowDevJobs’
  • Right click WorkFlow1 and rename to WorkFlowDevJobs


  • Open the WorkFlow1.cs class file and go to code view
  • Perform a global replace for Workflow1 replacing with WorkFlowDevJobs.
  • Press CTRL+Shift+H for the replace in files dialog



  • Select the replace all option
  • Rebuild the solution and make sure no errors occur. If you do get errors run for the hills before your computers epto plasmatic computer core overheats and explodes ;-) just trying to make this semi interesting ;-)
  • The solution should be error free – Save then Close the solution.

Click here for Part 2

SharePoint 2010 State Machine Workflows using Visual Studio 2010 Part 1


Most Popular Content All  |  Today  |  This Week  |  This Month
1 Vote

Part 1 – Building a State Machine Workflow using Visual Studio 2010

Demo project

Introduction

Workflows are systems that manage the execution of a business process. They are primarily described as a process that manages the flow of work among various individuals, or divisions, or multiple organizations.
As compared to Sequential Workflows which always progresses forward and never goes back (although using a while loop you can reiterate through same steps multiple times), the State Machine Workflows moves from one state to another, until the workflow concludes by reaching the completed state.
In this example we will simulate the hiring process for an organization. Our workflow will have following steps.
  1. Interview Application Received.
  2. Initial Clearance.
  3. Technical Clearance.
  4. HR Clearance.
  5. Accepted.
  6. Rejected.
  7. Completed.
Before starting with workflow we must have a list (or a library) named Candidates on in our SharePoint Application. Metadata related to the list will have following columns.
  1. Title
  2. Technology
  3. Experience (in months)
  4. Status
You can add columns as required.
State Machine Workflows are essentially event driven workflows. We create a task and attach an event handler to it. We then wait till the task is performed, and after the task is completed; we make a decision based on the user input.

Implementation

Step 1

In Visual Studio, select a SharePoint 2010 State Machine Workflow template. Fill in the details related to Name and Solution etc., and click Ok. Refer Fig 1.1.
Fig 1.1
In next window enter the URL of the site we want our workflow to run on, and click on “Next” button. Workflows can only be deployed as a Farm solution, so we do not have an option to deploy it as a Sandbox Solution.
In the next Window give the name for the workflow, and select a type of workflow we want to create. We will select a List Workflow for this example.
The next window gives us an option of associating our workflow to a list or a document library. We can choose not to associate our workflow by unchecking the association check box. However, we will have to associate the workflow to a list or library manually later on in that case. In our example we will associate the workflow with the Candidates list.
The next window allows us to set a trigger for our workflow. In our example we want our workflow to automatically start when an item is created in the Candidates list. So we will choose that as an option and click on “Finish” button.
Step 2

Let us have closer look at the Solution Explorer.
The references required for the workflow are automatically added into the solution by the IDE. We may manually add references as and when required.
Feature1 is a feature in which our workflow will be deployed. This feature can be activated and deactivated from Site Settings
Elements .xml will be used to configure various properties of our workflow. We will have a detailed look at this file later on in the tutorial.
Workflow1.cs is the code behind file of our workflow. All the server side code goes into this file. Refer Fig 1.2

Fig 1.2
Before we go any further we need to configure the Feature Receiver of our workflow. To do that click on the Workflow Design file and press ‘F4’. This opens up the properties window of workflow. In the properties window we can see Feature Receiver Property. Open the tree node of the property and it has two properties viz. Assembly and Class Name.
Type in the following values for these properties. Please make sure that you look up the latest version of the assembly available for Microsoft.Office.Workflow.Feature and the Public Key Token related to it.
For Assembly: Microsoft.Office.Workflow.Feature, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c
For Class Name: Microsoft.Office.Workflow.Feature.WorkflowFeatureReceiver
Step 3

We will design our workflow now. On the designer surface of the workflow, drag drop “State” activity. As discusses earlier, we have 9 activities in our workflow, drop in total of 7 “State” activities from the toolbox and give them appropriate names. Refer Fig 1.3.
Fig 1.3
We need to set an initial state and a completed state for our workflow. As we want “InterviewApplicationReceived” state to be our initial state, right click on it and choose “Set as Initial State” option in context menu. Similarly right click “Completed” state and choose “Set as completed state”. This is makes “Completed” state as the final state of our workflow.
Step 4

We need to initiate our workflow. For initiating the workflow we drop an “EventDrivenActivity” in the initial state of the workflow, i.e. “InterviewApplicationReceived” state. There are two ways of add the event driven activity to our state. Either you can drag-drop the activity from the toolbox or simply right click the state and click “Add EventDriven” in the context menu.
After adding the activity, double click on the activity to go to the details of activity, give it an appropriate name from properties window. We name it as “eventDrivenActivityInitial” in our workflow.
Next step is to drop “OnWorkflowActivated” Event handler to our event driven activity. Drag and drop the “OnWorkflowActivated” event handler from the toolbox onto the activity canvas. The properties window shows properties associated with the event handler.
Fig 1.4
Let us go through the properties of the OnWorkflowActivated event handler. Most of these properties are common to all the event handler activities. Refer Fig 1.4.
A workflow instance interacts with several SharePoint objects (task lists, and documents or items) during its lifetime. In SharePoint you can have many workflow instances running at the same time and interacting with several objects at the same time. To be able to identify which workflow instance is interacting with which object, you must use an identifier that links one particular workflow instance to one particular SharePoint object. Each workflow instance must be bound to its own items.  Such an identifier is called a Correlation Token. A correlation token links a workflow instance to its documents, items, and tasks. It prevents confusion between different workflow instances. We need have one correlation token for the workflow and one for each task we create during the workflow, so that when a user completes a task we have a unique identifier with which to receive any input from the user into the workflow. Make sure correlation token names are not repeated in different task. Type “InitialToken” (though the name of token can be anything you want, we generally prefer nomenclature of Task name suffixed by Token). Choose the Owner Activity as “InterviewApplicationReceived” State.
Invoked event of the OnWorkflowActivated will be fired when the workflow is activated. We can write the logic related to workflow activation in this event. In this example we use “onWorkflowActivatedInitial_Invoked” as the method name. The Visual Studio IDE will create write an event handler block in the code behind file once you press tab key after typing in the method name.
Next, click on the ellipsis in WorkflowProperties property. This opens a pop-up, choose workflowProperties from “Bind to an existing member” tab. If workflowProperties cannot be found in this tab, move to the next tab i.e. “Bind to a new member”, select “Create Field” radio button and type “workflowProperties” in new member name textbox, and press Ok.
Next drop “SetState” Activity (choose from 3.0 tab of toolbox, there is SetState under SharePoint tab as well) just below the event handler. Set the target state name as “Initial Clearance” State. This completes the configuration of our initial state.
Step 5

Now let us configure the Initial Clearance State. Here we are going to add the “StateInitialization” activity. In StateInitialization activity, we will create the task, and configure the details like participants, due date, etc.
So drag a “StateInitialization” activity (from 3.0 tab of the toolbox) and drop it inside the Initial Clearance State. We will name this activity as “stateInitializationInitialClearanceActivity”. Double click the activity and drag “Create Task” activity (from SharePoint tab of the toolbox) and drop it inside the state initialization activity. Rename the Create Task activity to “createTaskInitialClearance”. Create a new correlation token by typing token name in the properties window. We will name the token as “InitialClearanceToken” and set owner activity as Initial Clearance State.
We need to bind a method with “Method Invoking” event. The nomenclature for method invoking event will be task name followed by an underscore (_) appened by methodInvoking, so for Initial Clearance task the method name will be “createTaskInitialClearance_MethodInvoking”.
Next we need to set the values to both TaskId and TaskProperties. Click the ellipsis in the TaskId property. It opens up a pop-up window. In “Bind to a new member” tab, choose “Create Field” radio option. Enter the name in textbox and click Ok. We create a TaskId with name “createTaskInitialClearanceTaskId”. Similarly for TaskProperties create a new field (not property) with name “createTaskInitialClearanceTaskProperties”. We are done with configuration of Create Task and State Initialization.
Step 6

Drag an Event Driven activity (from 3.0 tab of the toolbox) and drop it inside the Initial Clearance State. Name it as “eventDrivenActivityInitialClearance”. Double click the Event Driven activity, and drop “OnTaskChanged” activity (from SharePoint tab of the toolbox) and name it “onTaskChangedInitialClearance”. Create fields for AfterProperties and BeforeProperties (follow the process similar to creating TaskId and TaskProperties) with names “onTaskChangedInitialClearanceAfterProperties” and “onTaskChangedInitialClearanceBeforeProperties” respectively.
Now in Correlation Token field, choose the same token that we had associated the Create Task activity with. That allows the workflow instance to understand with which task this event handler is associated with. In our case we will choose “InitialClearanceToken” as the correlation token. Most of the workflow errors are related to incorrect assigning of the correlation token. Hence we need to be extra careful when working with the correlation tokens.
Associate a method with Invoked event of the activity, we type in “onTaskChangedInitialClearance_Invoked” as the method name. We also need to bind the TaskId for this activity but we won’t be creating a new TaskId, instead we will bind the TaskId that we created in the Create Task activity. For that choose “Bind to an existing member tab” in the pop-up, select the TaskId that we had created in Create Task activity, and click Ok.
So to re-cap of what we have achieved so far, we created State, added a StateInitialization activity. Inside the StateInitialization Activity, we created a Task and gave it a correlation token. On MethodInvoking event of the CreateTask activity we have associated a method. We will write some logic in this method. Then we added an EventDriven activity to the State. In the EventDriven activity we have dropped an OnTaskChanged activity. We created the required fields for this activity, and gave it the same correlation token that we created in CreateTask activity. We associated a method with Invoked event of the OnTaskChanged activity. This method will be fired when user performs the task assigned to him.
Step 7

Now once the user performs a task, in this scenario, when the user indicates whether the received resume is approved or rejected, we need to perform some action based on it. A default task list item looks like Fig 1.5. We can customize the task list item, and use InfoPath form or an ASPX form instead of the default task list item.
                              Fig 1.5
For now if user types in “Approved” in the description column of the task, then we will proceed with next step of the workflow; else we will stop the workflow. So we drop an IfElse Activity (From 3.0 tab of the toolbox) below the OnTaskChanged activity, inside the EventDriven activity.
Select IfElseBranchActivity1, in properties window we have a Condition Property, select Code Condition for condition. Open the Condition tree node, in the left node property, type the name of the method which will have the logic to handle the condition. For this example we type in “InitialClearanceApprovalProcess” as the code condition. Now drop SetState Activity (from 3.0 tab of the toolbox) inside the IfElseBranchActivity1 and select the next state as the TargetStateName. In this example, “TechnicalClearance” will be the target state. Leave the IfElseBranchActivity2 as it is.
Step 8

We are done with the designing part of the workflow for this state, now we need to write the logic in code-behind file. So right click on the designer and select View Code from the context menu, or simply press F7 on the designer surface.
You can see all the fields and methods that we created from designer surface have been created in the code-behind file.
The first method is associated with OnWorkflowActivated activity. We won’t add any implementation logic in this method as of now.
Next, the method associated with Initial Clearance State -> Event Driven -> OnTaskChanged. We have associated a method “onTaskChangedInitialClearance_Invoked” with this event. In this method we will write the logic of the process we want to follow once the user has completed the task.Next, the method associated with Initial Clearance State -> State Initialization -> Create Task. We have associated a method “createTaskInitialClearance_MethodInvoking” with this event. In this event we will configure the title of the task, the users or group that will perform the task, due date of the task, and other such details.
private void createTaskInitialClearance_MethodInvoking(object sender, EventArgs e)
{
            try
            {
                        //Create a new TaskId for the Task
                       this.createTaskInitialClearanceTaskId = Guid.NewGuid();
                        //TaskProperties field is used to configure the Task Details.
                       this.createTaskInitialClearanceTaskProperties.Title = “Initial Clearance”;
                        //Assign a Task to a user or to a group. We assign the task to HR-Group
                        this.createTaskInitialClearanceTaskProperties.AssignedTo = “HRGroup”;
                        this.createTaskInitialClearanceTaskProperties.DueDate = DateTime.Today.AddDays(5.0);
             }
             catch (Exception ex)
             {
                         //throw ex;
             }
}
If we have a look at onTaskChangedInitialClearanceAfterProperties and onTaskChangedInitialClearanceBeforeProperties field, they are objects of SPWorkflowTaskProperties Class. As the name suggest this class represents the properties of a Workflow Task. We will assign the values from task to these objects so that we can use them other methods.
In this example we will set the task as complete, by setting the value for  PercentComplete Property to 1.0 .
private void onTaskChangedInitialClearance_Invoked(object sender, ExternalDataEventArgs e
{
try
{
                    this.onTaskChangedInitialClearanceAfterProperties =
                     this.onTaskChangedInitialClearance.AfterProperties;
                     this.onTaskChangedInitialClearanceBeforeProperties =
                     this.onTaskChangedInitialClearance.BeforeProperties;
                      //Set the PercentComplete property to 1.0 (i.e. 100%) to indicates task completion.
                      this.onTaskChangedInitialClearanceAfterProperties.PercentComplete = (float)1.0;
}
catch (Exception ex)
{
//throw ex;
}
}
Now we will implement the logic for Code Condition. The IfElse Activity for the task was associated with the InitialClearanceApprovalProcess method.
private void InitialClearanceApprovalProcess(object sender, ConditionalEventArgs e)
{
         try
        {
        if (this.onTaskChangedInitialClearanceAfterProperties.PercentComplete == 1.0)
       {
             if (this.onTaskChangedInitialClearanceAfterProperties.Description.Contains(“Approved”))
            {
                  e.Result = true;
            }
            else
           {
                 e.Result = false;
           }
      }
      else
     {
           e.Result = false;
      }
  }
catch (Exception ex) {}
}
We have set the result of if-else to true if user types in “Approved” in the description field of the task item, else the result is set to false. In later part of this tutorial we will see how to use a custom task form to get these values. So we can have a drop-down control for user to indicate whether the candidate it approved or rejected.
Step 9

That’s all the code we have to write to completely configure one task. Perform Step 5 to Step 8 for the remaining tasks.
You can see below a snapshot of the completed workflow.
Build and deploy the workflow.



No comments:

Post a Comment