Sunteți pe pagina 1din 71

have been amazed at how many hits and questions the 'how-to' article I posted on

creating a SharePoint 2007 workflow with Visual Studio 2005 and InfoPath 2007
got. That article was based on Beta2 of SharePoint 2007, and although most of the
steps are still the same, I decided to rewrite the article now that RTM is out. There
were so many questions on the previous post that it was difficult for me to answer
them all, so I've got to thank other people who tried out the workflow and got it to
work for coming along and helping others. At the end of this article I've a link to
forum post where I think we can put questions about this guide. That way people
can sign up to alerts and we can hopefully get peoples questions answered in a
much more organised way. So here it is, buckle down and good luck...
[after thought - this post and capturing all the images has taken almost 5 hours. If
you are reposting it somewhere else (ie stealing it!), please at least give a link
back! And if you like the post also please give me a link ;-) ]
Getting Started
The first thing you need to get right is your development environment. I'm working
on Virtual PC 2007 which has Windows 2003 server and MOSS installed on the
image. This image is also my development environment so I've installed Office
2007 Pro Plus, and Visual Studio 2005 directly onto Windows Server 2003.
Once Visual Studio 2005 is on we need to install the necessary components to be
able to work with Windows Workflow Foundation. Download and install the Visual
Studio 2005 Extensions for .NET Framework 3.0.
Once you have downloaded and installed those components you'll be able to create
Workflow type projects but we need the SharePoint workflow templates. To get
these, download and install the Microsoft Office SharePoint Server 2007 SDK which
also includes the Enterprise Starter Kit.
Now that we have these two things installed in the Create New Project box in VS
2005 you should be able to create a SharePoint Sequential Workflow and a
SharePoint State Machine Workflow.
So that's the setup done, now lets just recap what it is we'd like our workflow to do.
This is copied from the original workflow article:
We want to allow our workflow to be associated with a list or document library.
When a document is created or changed (this is a setting chosen upon binding the
workflow to the list/library), a person specified will have a task created for them,
with some pre-defined instructions and comments. When clicking the task the user
will have a designed form where they will have instructions present, and can decide
whether to complete the task with a checkbox.
From the above we’re going to need 2 InfoPath forms. Number 1 is used when
binding our workflow to a list/library where we’ll enter the user who’ll get the task,
and a few instructions and a comment. The second form is when the user clicks on
the task. In this form they can add comments and click a checkbox to complete the
workflow.
This project is basically the HelloWorldSequential workflow from the ECM starter kit,
but it's a nice walk through of how to put it together yourself!
Lets go and create our workflow project in Visual Studio 2005. We're going to be
using a sequential workflow template, and lets give it a name of NicksWorkflow
Once the project is created you'll see in the Solution Explorer that there's a new
folder called Deployment Files. This is where you'll now find feature.xml and
workflow.xml. We'll dig into how to deploy our workflow in the next blog post so
don't worry about these for now.
As with the previous article, before we start writing any code we want to create our
two InfoPath 2007 forms. We want to do it this way as we're going to generate a
C# class from one of our forms to help with the passing of data to and from it. The
first form we are going to create is the initiation form. This captures information
such as who we want the task to be assigned to, a field for instructions to them and
a comments textbox.
Initiation Form
1, Open up InfoPath 2007 and from the first form select 'Design a form template...'
2, Click OK to create a blank form template...

3, From the top menu bar click Insert->Layout Table... and then select your table to
have 2 columns and 4 rows...

4, Add three textboxes and a button to the columns in the right, and a description
in the cells to the left of each textbox. We need to also give each textbox a proper
name, do this by double clicking on it, and entering the new name into Field Name

Once you've renamed your textboxes and given the button a Label value of submit,
your InfoPath form should look something like this:
5, Data from InfoPath forms is represented by XML. To make it easier for us to get
our hands on the XML data we require we can give the XmlElement that holds these
control values a better name. From the Design Tasks toolbar click on Data Source...

Double click on myFields

And in the following form that opens up enter InitForm as the Name value...
Click OK to close that.
6, Now we need to configure what happens when people click on the submit button.
Double click on the submit button to bring up it's properties, from the General tab
click on the Rules button

In the following form, click Add to create a new rule. Click 'Add Action', and from
the following form chose 'Submit using a data connection' from the drop down, then
click the Add button just below:

In the next wizzard chose the following options to submit your data:
and then the hosting environment as the destination

Leave the name as Submit and click Finish. And then OK on the 'Add Action Form'

Now we want to add another action, so back in the Rule form click 'Add Action...'
This time the action 'Close this form' and make sure the checkbox is not selected...
Clicking OK takes us back to our Rules form. That's the two actions we want to add
for our Submit button. With them both together they should look like this:

Click OK to close this form.


7, Now we need to ensure our form can be viewed in a browser as this is how
InitForm will be used when setting up a workflow.
Go back to our Design Tasks toolbar, and click 'Design Checker'

From the Design Checker pane chose 'Change Compatibility Settings...'

Click the checkbox to allow our form to be opened in a browser, also enter the url
for MOSS 2007 to help verify compatibility...
While you are in this form, click on the Browser category, and ensure the language
selected is infact a language pack that you have installed on your MOSS server...

One final step is to go to the 'Security and Trust' category. In here untick to
automatically determine the level of security, and select Domain...

Click OK to close the 'Form Options' form. Now we need to save our form. Save it
directly to the C:\ as DemoInitiation.xsn. Once saved we can publish it by going
File->Publish, chose to publish it 'To a network location' and then chose
the location of your VS 2005 project, and the "Deployment Files/Feature Files"
folder.

Click Next, remove the path as the alternate access location. You will get a warning
when clicking next on that form but that is ok. If you do not remove the alternate
access path you will have problems when publishing your form to work with
workflow. Finally Publish and Close.
When we submit our forum to SharePoint we need to be able to get the data from
the submitted form to be able to use in our workflow. To help do this we can
generate a class using xsd.exe based off the form schema file. First we need to
save our InfoPath form as Source Files. File -> Save as Source Files. Browse to the
location you want to save the file (c: is a nice easy place), and click OK. By default
the source files are saved as filename myschema.xsd. Once saved close InfoPath.
Now open up a Visual Studio 2005 command prompt and navigate to where you
saved myschema.xsd. From the prompt type xsd myschema.xsd /c

this generates a c# class file called myschema.cs. Rename the file to InitForm.cs,
and add it to you VS 2005 workflow project. If you take a look inside the classes
code you’ll see the name of the class is the same that we gave to the forms field
collection.

Edit Task Form


Now we need to jump back into InfoPath 2007 so we can create our form that
enables users to edit the task they get assigned to complete the workflow.
1, Open InfoPath 2007 again and create a blank form as we did before. On this
form we’re going to want an instructions textbox where we’ll place the instructions
entered when we bound the workflow to a list/library, a checkbox to check to say
the workflow is complete, and an ok button. Lay it all out and rename the fields to
something like below...
Underneath the isFinished tooltip is simply some text of 'Completed'.
2, Add the same rules to the OK button as you did to the submit button for the
DemoInitiation form (ie submit to a hosted environment, and then close).
3, When this Edit form opens we’re going to want to pass some data to it (ie the
instructions), we do this by creating a task schema and adding it as a secondary
data source.
Open up notepad and add the following:
<z:row xmlns:z="#RowsetSchema" />
In this file we need to define every property that we are going to pass to the Task
Edit form. To do this, add an attribute comprised of the prefix ows_ and the name
of the task property. Set the attribute equal to an empty string. So to pass the
instructions to the Task Edit form that were added when we bound the workflow to
the list/library we add the following attribute:
ows_instruction=””
So your finished notepad text should be:
<z:row xmlns:z="#RowsetSchema" ows_instructions="" />

It doesn't matter where you save the file, just make sure it's called
ItemMetadata.xml (yes it does matter about the case with this).
4, Now we need to add the task schema to our Edit Task form as a secondary data
source. Back in InfoPath, in the Design Tasks pane select Data Source, and then
click 'Manage Data Connection'.
In the form that opens you'll see there is a Submit data connection already. On the
form Click Add to create a new data connection. On the wizzard form that opens
click so the new connection receives data...

Select XML Document as the data source to receive data from...


Then browse and select the ItemMetadata.xml file you created in Notepad in step
3...

Leave the option selected to include this file as a data source...

Click Next, and then Finish. The data connections form should now look as below:

Click Close to get that job done!


5, Now we need to bind the data that we are receiving from our new data
connection to the necessary fields. Double click the instructions textbox and on the
Data tab, under Default Value, click the formula button (underlined in red)...

On the Insert Formula dialog box, click Insert a Field or Group. In the Select a Field
or Group dialog box, select your ItemMetadata data connection from the drop down
menu. Select the ows_MetaInfo_instructions element.

Click OK. On the Insert Formula dialog box, click OK. On the Properties dialog box,
click OK.

6, Now we need to do the same things as we did with the initiation form, set the
form as browser enabled also entering the url of our MOSS server, check the
language setting of the form, and also set the Trust Level as Domain.
Save the form to c:\ again (or whever you saved it), and publish it to your VS
workflow project, "Deployment Files\Feature Files" directory again.
And that's it for InfoPath, our forms are created and ready to use!!!
Back to Visual Studio 2005
Now we can get down to some coding! In the solution explorer double click on
Workflow1.cs and up will open the workflow designer view. If you open up the
toolbox you'll see three new groups of components, SharePoint - Workflow Tasks,
SharePoint - Workflow, and Windows Workflow.
As you can see on the Workflow1.cs design surface it already creates the first
workflow step for us with a onWorkFlowActivated action. This will always be the first
Workflow action of any workflow. Below this action is an arrow and a kind of stop
sign. We can drag and drop any new workflow actions from the tool box and place
them on the arrow. Before we do that though there are a few properties we can
check before we get going. If you go into the code view of Workflow1.cs you’ll see
public sealed partial class Workflow1: SharePointSequentialWorkflowActivity
{
public Workflow1()
{
InitializeComponent();
}
public Guid workflowId = default(System.Guid);
public Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties
workflowProperties = new
Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties();
}
This is all created for you because you used a template project. If you view the
properties of work onWorkflowActivated1 you’ll see the following important
properties set for you:
CorrelationToken : workflowToken
OwnerActivityName : Workflow1
WorkflowProperties – expand this
Name : Workflow1
Path : workflowProperties – again this is a variable that was created for us and
set from the code above.
We also get an event for this control. When this fires we’ll want to setup any initial
variable values that are required for the workflow. Type into the Invoked space
onWorkflowActivated and press enter. You’ll see it goes to the code view and
creates our event handler for us with the correct interface. We’ll come back to this
later.
Now to add our first workflow control. Now that the workflow has actually started
the first thing we want to do is create a task for the person who’s been set to
complete it. Remember we defined this when attaching the workflow to an actual
list in SharePoint. To do this drag and drop a CreateTask control just below our
onWorkflowActivated1 control.

We need to set a few properties for this control. First type in the Correlation Token
as taskToken. Upon pressing enter you’ll see that you can expand this property to
reveal OwnerActivityName which once again should be set as Workflow1.
Next we’ll set the TaskId and TaskProperties which can be accomplished in a couple
of ways. First method is to click on the default value of TaskId (0000–0000….
or something) and you’ll see three ellipses on a button appear. Click on this and it’ll
open a dialogue box for you. Click on the ‘Bind to a new member’ tab and click the
'Create Field' radio button.
Click OK. In the propeties window of createTask1 you’ll see now that not only have
2 pairs of name and values gone into the TaskId property, but you can expand them
out to set them seperately. Also if you switch to code view, you’ll see that a variable
called createTask1_TaskId1 (the name that was entered in the 'new member name'
textbox) has been added to our code for us.
Follow the same procedure for TaskProperties. Switch back to the code view again
and you’ll see the variable created for us. If you go back to the createTask1
properties view and click the ellipses for TaskProperties again, you can see in the
‘Bind to an existing member’ that this property is bound to taskProps in our
Workflow1 class. So as well as using this dialog box and the ‘Bind to a new
member’ tab, we could have gone into our code view, created the
createTask1_TaskId1 and createTask2_TaskProperties1 variables ourselves, and
then used the Bind to an existing member view to set the values of the properties.
Final thing to do is create the event that fires when this activity executes. In the
Method Invoking field enter createTask and click enter. Again is creates our event
handler and interface for us. Again we’ll come back to this is a little while. Finally
we need to set the CorrelationToken as taskToken (just type it in). The same token
name will be used in other task activities that we drag onto our workflow. Using the
same token ensures we are working with the same task. Here is how the properties
window for createTask1 should be looking:
Now that our task has been created for the assigned user, we need to add some
waiting functionality to enable the workflow to wait for the task to be completed by
the user. We do this using the While workflow component.
Drag and drop a While component from the Windows Workflow section in the
toolbox between the createTask1 and the end of the workflow. In the properties
window select Code Condition as the Condition property's value and then expand
the field. Then type notFinished into the extra field presented and press enter. This
will create an event handler for you in code where you check whether the While
condition has been met (ie has the user completed their task).
Now we want to add an activity to the centre of our While loop. Here we’ll place an
onTaskChanged. This basically means that the While loop will execute and check
our code condition, every time our task is edited. It won’t be able to exit out of the
While loop until our method notFinished returns false (which means it is finished!).
Drag an onTaskChanged component and drop it in the middle of our While loop.
You’ll see in the properties window there are quite a few things we need to set:
AfterProperties = click the ellipses and bind to a new Field member
BeforeProperties = click the ellipses and bind to a new Field member
CorrelationToken = select taskToken from the drop down
Invoked = onTaskChanged. When you’ve typed it in press enter to create the event
handler for you.
TaskId = click the ellipses and bind to the existing member
called createTask1_TaskId1

The properties window for onTaskChanged should now look as below, make sure
you set the Correlation Token:
The final component we want to add to our workflow is the CompleteTask activity.
Drag and drop a CompleteTask component between the While component and the
stop workflow activity. In the properties set the Correlation Token to taskToken from
the drop down. Again with the TaskId click the elipses and bind it to
createdTask1_TaskId1.
Now we’ve added all the components to our workflow. Our workflow designer
should look as below:
Now we’ve got all our components added, and event handlers and methods created,
we need to add some code to Workflow1.cs.
Right click on Workflow1.cs and click View Code. The first bit of code we need to
add declares a few variables we are going to need in our workflow. Just above the
onWorkflowActivated method add:
private String assignee = default(String);
private String instructions = default(String);
private String comments = default(String);
These three values are ones that we are going to get from our DemoInitiation form.
These properties are passed to the workflow as an XML string represented by the
InitiationData property of the SPWorkflowActivationProperties object. To access
these properties we need to parse this XML string. This is where we make use of
the generated class based on the schema of our initiation form that we did in step 4
and added to our project as InitForm.cs. To get these values add the following code
to the onWorkflowActivated method:
workflowId = workflowProperties.WorkflowId;
XmlSerializer serializer = new XmlSerializer(typeof(InitForm));
XmlTextReader reader = new XmlTextReader(new
System.IO.StringReader(workflowProperties.InitiationData));
InitForm initform = (InitForm) serializer.Deserialize(reader);
assignee = initform.assignee;
instructions = initform.instructions;
comments = initform.comments;
The next method we need to add some code to is createTask Method. Here we want
to set some properties of a task as this method fires just before the task does
actually get created. Here’s the code:
createTask1_TaskId1 = Guid.NewGuid();
createTask1_TaskProperties1.Title = "Demo Task";
createTask1_TaskProperties1.AssignedTo = assignee;
createTask1_TaskProperties1.Description = instructions;
createTask1_TaskProperties1.ExtendedProperties["comments"] = comments;
createTask1_TaskProperties1.ExtendedProperties["instructions"] = instructions;
as you can see there are a predefined properties such as Title and AssignedTo to
use, and if there’s any other properties you want to name and create yourself you
can use the ExtendedProperties. This is a hash table so you can name things as you
like.
The final bit of code we need to add is probably the most complex to get our heads
around. We need to add a private Boolean variable called isFinished. Place this just
above the notFinished method:
private bool isFinished;
Now our While loop calls the notFinished method. One of the objects passed in is
ConditionalEventArgs which has a property called result. If result is set to false, the
while loop will end, if result is set to true, the while loop continues. As you should
be able to work out, the variable above we created isFinished will be true once the
task has been finished. Therefore we have to negate it to set it’s value to the
ConditionalEventArgs result property. In the notFinished method type the following
code:
e.Result = !isFinished;
The last thing we need to do is actually set isFinished when our task gets edited ie
when onTaskChanged event files. In here we just need to parse out the isFinished
value from our onTaskChanged1_AfterProperties1 object. At the code below to the
onTaskChanged method:
isFinished =
bool.Parse(onTaskChanged1_AfterProperties1.ExtendedProperties["isFinished"].ToSt
ring());
And that’s it. Build your solutions, and hopefully everything compiles succesfully.
Now I was also going to include instructions on how to deploy this workflow, but I’m
going to save that for a few days time.
If you find any errors in the post please let me know...
posted on Sunday, February 25, 2007 7:27 PM

Get email alerts when this blog is updated!

Feedback

How to Create a SharePoint 2007 Workflow using Visual Studio


2008 Beta (Example)
A lot of people have complained that access to the Virtual Labs that I mentioned
earlier in my blog is very slow and unstable. So this tutorial that I’m about to give
you is based on the case in Microsoft Virtual Labs. I’ve also had a lot of requests of
posting example code for creating workflows in VS2008 Beta (last one from Stephen
Korow). You’re about the witness an evolution in building workflows for Microsoft, no
need for command line deployment, specific configuration of workflow features, and
dealing with workflow and feature xml files.

What I’m about to show you I did and tested in the following environment:

• Microsoft Windows server 2003 R2 Enterprise Edition


• Microsoft Office SharePoint Server 2007 Enterprise Edition
• MS SQL 2005 Enterprise Edition
• Visual Studio 2008 Team Suite Beta 2
• Code was done in C# only
(Note: Not that you need this exact environment. Link to the source code and word
template can be found at the end of this article)

1. In your SharePoint 2007 create a Document Library (unless you


already have one) which is easily achieved by choosing “Create” from
the “Site Actions” menu (located in the top right corner) and then
choosing” Document Library”, give it a name and click “Create”.
Now you need to create a mock contract template in Word 2007 for your
Document Library

2. When in your Document Library, click the Settings dropdown and


select Document Library Settings.

3. On the Customize Documents page, locate the Columns section.

4. Create a Buyer custom column:


o Click Create Column.
o Type in the column name: “Buyer”.
o Select the type Single line of text.
o For the “Require that this column contains information setting”
click Yes.
o Click Ok to add the new column.

5. Add two more columns: a “Seller” column that is type Single line of
text and a “Purchase Price” column that is type Currency. Both columns
should be required.
6. Return to the document library home page

7. On the New dropdown in the document library, click Document.

8. A new document appears in Word. Observe that there are text boxes
for the custom columns from the document library:
9. On the Office menu click Save As. Save the document as %PATH OF
YOUR CHOICE%\Contract.docx. If you are prompted to confirm saving
to the new Word 2007 file format, click “Ok”.

10. Insert content controls for each of the server properties:


o Place the selection in the document where you want the content
control to be placed.
o Select the Insert tab on the ribbon.
o Click Quick Parts, then click Document Property, and then click
Buyer.
o Repeat these steps to add content controls in the document for
the Seller and the Purchase Price properties.
o For now, leave the content controls empty – do not add text to
them.
11. On the Office menu, click Exit Word. When prompted to save changes
to the document, click “Yes”.

12. Return to the document library in Internet Explorer, click Settings and
then select Document Library Settings.

13. On the “Customize Documents” page, locate the “Content Types”


section and click the Document link.
14. NB. If you can’t locate the “Content Types” section, in the “General
Settings” section locate “Advanced Settings” in there switch the radio
button under “Allow management of content types” to “Yes”, now when
you come back to the “Customize Documents” page you should be
able to locate the “Content Types” section.
15. On the “List Content Type: Document page”, click the “Advanced
Settings” link.
16. Select the Upload a new document template radio button and then
click Browse. Browse to select %PATH OF YOUR
CHOICE%\Contract.docx and then click Ok.

17. In Internet Explorer, return to the document library.

18. Upload a new document:


o In the document library, click the “New” dropdown and then click
“Document”. Word starts and loads a new document based on
the contract template you created.
o Fill in the values for Title, Buyer, Seller and Purchase Price. You
can fill in the values on the document properties bar (just below
the ribbon) or you can fill in the content controls: the end result
will be the same.
o Once all required fields have been filled in, on the Office menu,
click Save.
o Save the document with a filename of your choice to the
document library. If you receive a message that the document
must be checked in for it to be visible to others, click OK.
o On the Office menu, click Close. When prompted to check in the
document, click “Yes”.
o In the Check In dialog, click Ok to accept the version defaults. Exit
Word.
o Your new document appears in the document library. Notice that
the Buyer, Seller and Purchase Price columns reflect the values
you entered in the Word document.

19. You may upload additional documents if you wish.

20. Close Internet Explorer.


Now comes the fun part, creating the workflow itself

21. Start Visual Studio.

22. On the File menu, click New and then click Project. The New Project
dialog appears.
23. In the list of Project Types, expand Visual C#. Expand Office and then
select 2007.

24. Select the SharePoint Sequential Workflow project type.

25. Name the project ContractWorkflow, specify the default location and
click “OK”.

26. The New SharePoint Workflow wizard appears. Change the workflow
name to Purchase Contract, use your local site where you created your
Document Library (eg http://localhost/yoursite) for debugging and click
“Next”.
27. Click Next to accept the default lists for debugging.

28. h. Click Finish to accept the default conditions for how a workflow is
started (the default selections are Manually by users and When an item
is created).

29. The new workflow appears in the designer.


Add a CreateTask Activity to the Workflow

30. If the toolbox is not displayed, then on the View menu, click Toolbox.

31. From the SharePoint Workflow tab on the control toolbox, drag a
CreateTask activity and drop it onto the workflow designer between

onWorkflowActivated1 and the end of the workflow ( ). The new


activity is named createTask1 by default.
Note: If you can't find the Create Task Activity on the toolbox (which is more
than likely with VS2008 Beta 2) you need to add it manually by right clicking
on the toolbar (whichever section, "General" for example) and select
"Choose Items" from the menu.
The following menu selection box will show:

Tick CreateTask option and OnTaskChanged while you're at it, you'll need it
later.
32. Configure the TaskID property of createTask1:
o In the Properties window, click the ellipsis for the value of the
TaskID property. The Bind ‘TaskID’ to an activity’s property dialog
appears.
o Type the new member name myTaskId, ensure that the Create
property radio button is selected and click OK.
33. Configure the TaskProperties property of createTask1:
o In the Properties window, click the ellipsis for the value of the
TaskProperties property. The Bind “TaskProperties” to an
activity’s property dialog appears.
o Type the new member name “myTaskProperties”, ensure that the
Create property radio button is selected and click OK.

34. In the properties window, select the MethodInvoking handler. Type


MyTaskCreation and press the Enter key. The code window appears.

35. Add code to the MyTaskCreation event handler and also add the
CustomFieldText function.

private void MyTaskCreation(object sender, EventArgs e)


{
try
{
myTaskID = Guid.NewGuid();
myTaskProperties = new
Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties();
myTaskProperties.PercentComplete = (float) 0.0;
myTaskProperties.AssignedTo =
System.Threading.Thread.CurrentPrincipal.Identity.Name;
myTaskProperties.DueDate = DateTime.Now.AddDays(7);
myTaskProperties.StartDate = DateTime.Now;
myTaskProperties.Title = "Purchase Contract Workflow Task";
myTaskProperties.Description = String.Format("This is a contract
for an offer to purchase real " + "estate between {0} [Buyer] and {1}
[Seller]. " + "The offer amount is {2}.",
CustomFieldValue("Buyer"),
CustomFieldValue("Seller"),
CustomFieldValue("Purchase Price"));
}
catch (Exception ex)
{
//Add exception handling
throw (new Exception("Unable to initialize task.", ex));
}
}

private string CustomFieldValue(string fieldName)


{
try
{
object item = this.workflowProperties.Item[fieldName];
string s =
this.workflowProperties.Item.Fields[fieldName].GetFieldValueAsText(item);
return s;
}
catch (Exception ex)
{
return String.Empty;
}
}

36. On the View menu, click Designer to return to the workflow designer.

37. In the Properties window, select the text box for the CorrelationToken
property value. Type myTaskToken and press the Enter key.

38. Expand the CorrelationToken property to display the


OwnerActivityName subproperty.

39. For the OwnerActivityName subproperty, select Workflow1 in the


dropdown.
Add a While Activity to the Workflow

40. If the toolbox is not showing, then on View menu, click Toolbox.

41. From the Windows Workflow v3.0 tab of the toolbox, drag a While
activity and drop it between createTask1 and the end of the workflow (

). The new activity is named whileActivity1 by default.

42. In the Properties window, locate the Condition property for


whileActivity1.
43. Select Code Condition in the property value.

44. Expand the Condition property to display the Condition subproperty.

• 1. For the Condition subproperty, type myTaskNotCompleted and press the


Enter key. The myTaskNotCompleted event handler appears in the code
window.

• 2. In the Workflow1 class, add the taskCompleted variable at the class-level.

private bool taskCompleted = false;

• 3. Add code to the myTaskNotCompleted event handler that will return a


result indicating whether or not the task has completed; the task is
completed when its PercentComplete property is 1.0.
private void MyTaskNotCompleted(object sender, ConditionalEventArgs
e)
{
e.Result = !taskCompleted;
}

Add an OnTaskChanged Activity to the Workflow


48. On the View menu, click Designer.

49. If the toolbox is not visible, then on the View menu, click Toolbox.

50. From the SharePoint Workflow tab on the toolbox, drag an


OnTaskChanged activity and drop it in the center of whileActivity1. The
new activity is named onTaskChanged1 by default.

51. In the Properties window, set the CorrelationToken property of


onTaskChanged1 to myTaskToken.
52. Set the AfterProperties property of onTaskChanged1:
o In the Properties window, select the ellipsis for the AfterProperties
property.
o On the Bind ‘AfterProperties’ to an activity’s property dialog,
select the Bind to new member tab.
o Name the new member afterMyTaskPropertyChange, ensure that
the Create Property radio button is selected and click OK.

53. Set the TaskId property of onTaskChanged1:


o In the Properties window, select the ellipsis for the TaskId
property.
o On the Bind to an existing member tab, select the myTaskId
property and click OK.

54. Double-click onTaskChanged1 in the workflow designer. The Invoked event


handler for onTaskChanged1 appears in the code window.

55. Add code to onTaskChanged1_Invoked that will set the


taskCompleted variable to true when the PercentComplete property of the
task is 1.0.

private void onTaskChanged1_Invoked(object sender,


ExternalDataEventArgs e)
{
if (afterMyTaskPropertyChange.PercentComplete == 1.0)
{
taskCompleted = true;
}
}

56. In the Workflow1 class, set breakpoints on the MyTaskCreation and


onTaskChanged1_Invoked methods.

Note: To set the breakpoints, select the first line of each method in the code
windowand press the F9 key.
57. Press F5 to start debugging the project.

Note: Watch the output window as the project is built and deployed. The
output window shows you many of the steps that VSTO takes for deploying
the workflow solution - without VSTO, these are all steps that you would take
manually. One of the SharePoint requirements for a new workflow solution is
that the SharePoint worker process and IIS must be restarted; thus
build/deploy times may vary.

58. Internet Explorer starts and displays the document library with the
document(s) that you uploaded.

Note: You might encounter the following warning (below), if you do, click “No” do as
it said and start again.

59. Select the dropdown for a document and choose Workflows.


60. In the list of workflows select Purchase Contract to start the workflow
for the document.
61. Once the workflow starts, you will hit the breakpoint for
MyTaskCreation. Press F5 to continue.

62. When you return to the documents library, observe that the Purchase
Contract column for the document shows that the workflow is In
Progress.

63. Click the In Progress link to display the workflow status.

64. Click the Purchase Contract Workflow Task link to display the task. The
task properties were initialized in the MyTaskCreation method;
especially note that the Description property of the task contains the
data that you entered into the Word document for the buyer, seller and
purchase price.
65. Click Edit Item to edit the task.

66. Change the Status to In Progress and change the % Complete value to
50% and click OK.

67. Because the task property has changed, you will hit the breakpoint at
the onTaskChanged1_Invoked method.
68. Press F10 to step through the code; observe that the
PercentComplete=1.0 condition is not met so the taskCompleted
variable is not set to true. Press F5 to continue.

69. Complete the task:


o In the workflow status window, click the Purchase Contract
Workflow Task.
o Click Edit Item, change the % Complete to 100% and click OK.
o You will hit the breakpoint at onTaskChanged1_Invoked once
again.
o However, when you step through the code, you will observe that
the PercentComplete=1.0 condition is met and that the
taskCompleted variable is set to true this time.
o Press F5 to continue.

70. Return to the document library and observe that the Purchase
Contract status now shows Complete.

71. You can test the workflow with other documents in the document
library. You may also upload new documents to the library and observe
how the workflow automatically starts as soon as new documents are
uploaded.

72. Close Internet Explorer to stop debugging.


http://dotnet.org.za/zlatan/default.aspx
Walkthrough: Creating Office SharePoint Server 2007 Workflows
in Visual Studio 2005
When you create workflows for Microsoft Office SharePoint Server 2007, you have the option to create the various
forms that allow users to interact with a workflow by using a variety of technologies. This walkthrough
demonstrates how to use Microsoft Office InfoPath 2007 to create those forms. The option to use Microsoft Office
InfoPath 2007 is only available when you are also using Microsoft Office SharePoint Server 2007. For Windows
SharePoint Services 3.0, it is necessary to use ASPX forms to collect data from the workflow initiator. Using
Microsoft Office InfoPath 2007 enables users to interact with the workflows by using 2007 Microsoft Office system
client applications, such as Microsoft Office Excel 2007, Microsoft Office Word 2007, Microsoft Office PowerPoint
XML Format, and InfoPath Forms Services, as well as through a Web browser.

In this walkthrough, we will create a simple workflow that uses InfoPath forms. When initiated, the workflow will
assign a task to the selected user, and then wait until that user completes the task. The workflow uses one custom
InfoPath form to collect initiation data from the user who starts the workflow, and another form to enable the
assigned user to edit the workflow task and mark the task as complete.

Following are the tasks that are described in this walkthrough:

• Designing custom InfoPath forms for workflow initiation and task editing.

• Creating a workflow from existing workflow activities.

• Passing information between the custom forms and the workflow itself.

• Creating, updating, and completing a workflow task by using workflow activities.

Prerequisites

To complete this walkthrough, you need to install the following:

• Microsoft Visual Studio 2005 Tools for the 2007 Microsoft Office System, with Visual Studio 2005
Extensions for Windows Workflow Foundation.

• Microsoft Office SharePoint Server 2007

• Microsoft Office InfoPath 2007

• Microsoft Office SharePoint Server 2007 Software Development Kit (SDK)

Note:

As with all Microsoft Office SharePoint Server 2007 development, you should create your workflows by
using a development environment that closely resembles the environment where the code will be
deployed. While it is not always possible to completely replicate a production environment by using
developer resources, making sure that the two environments are as similar as possible will greatly
simplify your development and debugging processes. For example, the Microsoft Office SharePoint
Server 2007-specific workflow activities require that Windows SharePoint Services and Microsoft Office
SharePoint Server 2007 be installed on the computer you use to develop the workflows.

Scenario

The example workflow you create in this walkthrough is a basic one. When a user starts the workflow, Microsoft
Office SharePoint Server 2007 displays a custom initiation form which is used to collect three pieces of information
from the user who started the workflow. The following information will be used in processing the workflow:

• The Windows SharePoint Services login name of the person who will be assigned tasks by the workflow.

• Any instructions for completing the task.

• Any other comments the workflow initiator wants to provide.

The workflow then creates a task and assigns it to the specified user. That user can edit the workflow task by using
a custom task edit form. The task edit form contains a check box where the user can mark the task as complete.
Each time the user edits the task, the workflow checks to verify whether the task has been marked as complete.
After it is marked complete, the workflow sets the task to completed status in Microsoft Office SharePoint Server
2007 and ends the workflow activity.

Next Steps

Step 1: Create the Workflow Initiation Form

Step 1: Create the Workflow Initiation Form


By using Microsoft Office InfoPath 2007, you can create workflow forms that run in 2007 Microsoft Office system
client applications—such as Microsoft Office Excel 2007, Microsoft Office Word 2007, Microsoft Office PowerPoint
XML Format, and InfoPath Forms Services itself—as well as in a Web browser.

The steps in this procedure follow procedures described in How to: Design an InfoPath Form for a Workflow in
Office SharePoint Server 2007.

Note:

This procedure assumes you are familiar with adding controls to a Microsoft Office InfoPath 2007 form
and configuring those controls.

To create the workflow initiation form

1. Open Microsoft Office InfoPath 2007. In the Fill Out a Form dialog box, click Design a Form.

2. In the Design a Form dialog box, select Blank, select Enable browser-compatible features only, and

then click OK.

3. In the Design Tasks pane, click Controls.

4. On the form, add the following controls to capture the information the workflow requires:

a. On the form surface, type Assign Task To:, press Enter and then drag a text box control onto

the form below the label. Right-click the text box control, and then select Text Box Properties.
For Field Name, type assignee, and then click OK.

b. Type Instructions:, press Enter, and then drag another text box control onto the form. Right-

click the text box control, and select Text Box Properties. For Field Name, type instructions,
and then click OK.
c. Type Comments:, press Enter, and then drag another text box control onto the form. Right-click

the text box control, and then select Text Box Properties. For Field Name, type comments,
and then click OK.

d. Drag a button control onto the form. Right-click the button control and then select Button

Properties. On the General tab, for Label, type submit, and then click OK.

When finished, your form should resemble the following figure.

Notice that we have named the text fields assignee, instructions, and comments. These text field
names will be used later to populate the SPWorkflowActivationProperties that are called from the
onWorkflowActivated activity in the workflow code. When the form submits its data to Microsoft Office
SharePoint Server 2007, Office SharePoint Server 2007 starts a new workflow instance and adds these
custom properties to the SPWorkflowActivationProperties object as name and value pairs. Your
workflow code can then retrieve the data by accessing those name and value pairs.

For more information, see How to: Design a Workflow Form to Use Association and Initiation Data.

5. Give the form fields collection a unique name. From the Design Tasks pane, click Data Source. You will

see the field names you entered for the controls on the form designer. Right-click myFields and select
Properties. In the Field or Group Properties dialog, type InitForm for the Name property.

Later in this procedure, you will extract the schema from this form to create a schema (.xsd) file. This
schema then becomes the basis for the class you will create and reference in the onWorkflowActivation
activity. The form fields collection name will become the name of the root element of the schema file. The
class that is generated from the schema file, in turn, will have the same name as the schema file root
element.

Specifying a unique name for the fields collection as we did previously, rather than using the default name
of myfields, will help ensure that the class generated from the form schema file will also have a unique
name. This is especially important when you are programming a workflow that deserializes multiple forms.
6. Add rules to the Submit button: One rule submits the form information to the hosting environment (in

this case, Office SharePoint Server 2007); the other closes the form when the user clicks Submit.

a. Right-click the button, and then select Button Properties.

b. In the Button Properties dialog box, on the General tab, click Rules, then click Add.

c. Click Add Action, and then click Submit using a data connection. Click Add.

d. In the Data Connection Wizard, select Create a new connection to and submit data, and

then click Next.

e. Under How do you want to submit your data, select To the hosting environment, and then

click Next. Click Finish, and then click OK.

f. Add another rule: On the Rules dialog box, click Add and then click Add Action.

g. Select Close the Form from the list of predefined actions. Make sure If changes have not

been saved, prompt user to save is not selected.

h. Click OK to exit from the various dialog boxes.

7. Set the security level of the form to Domain.

a. On the Tools menu, select Forms Options, and then select Security and Trust.

b. Clear Automatically determine security level, and then select Domain.

8. Publish the form.

a. Save the form.

b. On the File menu, click Publish.

c. In the Publishing Wizard, select To a network location, and then click Next.

d. Browse to the network location where you want to publish the form, and then click OK.

e. For Form Name, type InitiationForm, and then click Next.

f. Click Next.

g. Click Publish, and then click Close.

9. Generate a new class file, based on the form schema (.xsd) file.

a. On the File menu, click Save as Source Files. Browse to the location where you want to save

the form source files, and then click OK.

Note:

Do not specify an alternate path to the form. Doing this will cause an error that prevents you from
publishing the form to the server.

b. Click Publish, and then click Close.

10. Generate a new class file, based on the form schema (.xsd) file.
a. On the File menu, click Save as Source Files. Browse to the location where you want to save

the form source files, and then click OK.

InfoPath saves a collection of form source files, including the schema file, to the specified
location. The form schema file is always named myschema.xsd.
b. Use the Microsoft .NET Framework 2.0 command-line tool--xsd.exe--to generate a new class file
from the form schema.

By default, Visual Studio 2005 installs the xsd.exe command-line tool to the following location,
where C: represents your hard disk:
C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin

c. Open a Visual Studio Command Prompt window. Click the Start button, select All Programs,

select Microsoft Visual Studio 2005, select Visual Studio Tools, and then click Visual Studio
2005 Command Prompt.

d. Navigate to the location of the form schema (.xsd) file, and then run the following command:

Copy Code

xsd myschema.xsd /c /l:CS


or

Copy Code

xsd myschema.xsd /c /l:VB


depending on the language you are using to develop your workflow.

This command generates a new class file based on the form schema. The file will be created with
the same name as the schema file. In this case it would be myschema.cs. The base class
created in the file will have the same name as the root element of the schema, which was given
the same name as the form fields collection. In this walkthrough the name is InitForm.

e. In Visual Studio, add the new class file to your workflow project.

Next Steps

Step 2: Creating the Workflow Task Edit Form

Step 2: Creating the Workflow Task Edit Form


Next, you need to create a form that enables workflow users to interact with the workflow task that is assigned to
them.

This step in the walkthrough follows procedures described in How to: Design a Workflow Task Form to Use Task
Data.

Note:

This procedure assumes you are familiar with adding controls to an Microsoft Office InfoPath 2007 form
and configuring those controls.

Prerequisites
Step 1: Create the Workflow Initiation Form

To create the workflow task edit form

1. Open Microsoft Office InfoPath 2007.

2. In the Getting Started dialog box, click Design a Form Template.

3. In the Design a Form Template dialog box, ensure that the Form Template radio button is selected.

Select the Blank template, and then click OK.

4. In the Design Tasks pane, click Controls. Add the following controls to your form:

5. When finished, your form should resemble the following figure.

6.

7. Add rules to the OK button.

a. Right-click the button you added to the form, and then select Button Properties.

b. In the Button Properties dialog box, on the General tab, click Rules.

c. In the Rules dialog box, click Add.

d. In the Rule dialog box, click Add Action, and then click Submit using a data connection.

Click Add.

e. In the Data Connection Wizard, select Create a new connection to and submit data, and

then click Next.

f. Under How do you want to submit your data, select To the hosting environment, such as

an ASP.NET page or a hosting application, and then click Next. Click Finish, and then click
OK.

g. Add another rule: On the Rules dialog box, click Add, then click Add Action.

h. Select Close the Form from the list of predefined actions. Make sure If changes have not

been saved, prompt user to save is not selected.


i. Click OK to exit from the various dialog boxes.

8. Create a schema file for your workflow task schema.

Control Type Name Data Type

Text Box Instructions Text (string)

Check Box isFinished True/False (Boolean)

Button OK N/A

9. When finished, your form should resemble the following figure.

10.

11. Add rules to the OK button.


a. Right-click the button you added to the form, and then select Button Properties.

b. In the Button Properties dialog box, on the General tab, click Rules.

c. In the Rules dialog box, click Add.

d. In the Rule dialog box, click Add Action, and then click Submit using a data connection.

Click Add.

e. In the Data Connection Wizard, select Create a new connection to and submit data, and

then click Next.

f. Under How do you want to submit your data, select To the hosting environment, such as

an ASP.NET page or a hosting application, and then click Next. Click Finish, and then click
OK.

g. Add another rule: On the Rules dialog box, click Add, then click Add Action.

h. Select Close the Form from the list of predefined actions. Make sure If changes have not

been saved, prompt user to save is not selected.


i. Click OK to exit from the various dialog boxes.

12. Create a schema file for your workflow task schema.

Note:

Since this form is used to interact with the workflow, you want to prevent Office InfoPath 2007 from
prompting the user to save. Leaving it selected could cause exceptions to be thrown during the
execution of the workflow

a. Click OK to exit from the various dialog boxes.

13. Create a schema file for your workflow task schema.

Adding the workflow task schema to your form as a secondary data source enables Microsoft Office
SharePoint Server 2007 to provide the form with task data, which is used to prepopulate field values after
the form is loaded. The first step is to create an XML schema file that represents your workflow task
schema. For more information, see How to: Design a Workflow Task Form to Use Task Data.

a. Using the text editor of your choice, or Visual Studio, create a file named

ItemMetadata.xml.
b. Add the following element to the file:

Note:

The file name ItemMetadata.xml is case-sensitive.

c. Add the following element to the file:

Xml

Copy Code

<?xml version=”1.0” encoding=”utf-8”?>


<z:row xmlns:z="#RowsetSchema"
/>
d. In the ItemMetadata.xml file, define each task property that you want to use as data in
your form. To do this, add the prefix ows_ as an attribute and also add the name of the task
property. Set the attribute equal to an empty string.

In this case, you want to display the instructions that the user entered in the initiation form.
Remember that these instructions were added to the workflow task as extended properties when
it was created.

The following code demonstrates how to access the extended property from code.

C#

Copy Code

private void createTask(object sender, EventArgs e)


{

taskProps.ExtendedProperties["instructions"] = instructions;
}
For this reason, you need to add an attribute for the instructions task property. Your completed
ItemMetadata.xml should contain the following text.
Xml

Copy Code

<z:row xmlns:z="#RowsetSchema"
ows_instructions=""
/>
e. Save the finished ItemMetadata.xml file to your hard disk.

14. Add the workflow task schema to your form as a secondary data source.

a. In Microsoft Office InfoPath 2007, on the Design Tasks pane, select Data Source, and then

click Manage Data Connections.

b. On the Data Connections dialog box, click Add.

c. In the Data Connection Wizard, select Create a new connection to and Receive data. Click

Next.

d. Select XML Document, and then click Next.

e. Browse to the location where you saved your ItemMetadata.xml file, select it, and click
Open. Click Next.

f. Select Include the data as a resource file in the form template, and then click Next.

g. Enter ItemMetadata.xml as the data connection name, and make sure Automatically retrieve

data when form is opened is selected. Click Finish, then click Close.

After you include the ItemMetadata.xml file as a resource file in the form template, you no
longer need the file in your workflow solution.

ItemMetadata.xml is required as a secondary data source for task forms. If you do not add
ItemMetadata.xml as a secondary data source, the form generates an error when it opens.

15. Data-bind the Instructions text box control to the instructions elements in the workflow task schema.
a. Double-click the Instructions text box control.

b. In the Properties dialog box, on the Data tab, under Default Value, click the Formula button.

c. In the Insert Formula dialog box, click Insert a Field or Group.

d. In the Select a Field or Group dialog box, select your ItemMetadata data connection.

e. Select the ows_instructions element.


f. Click OK. On the Insert Formula dialog box, click OK. In the Text Box Properties dialog box,

click OK.

The Instructions text box control is now bound to the instructions workflow task property.
When Microsoft Office SharePoint Server 2007 loads your task form, the form displays the task
instructions in the text box.

16. Notice that we used a Boolean value to add a check box named isFinished to the form. This now
becomes an extended property of the workflow task, and is passed to the workflow by Office SharePoint
Server 2007. Remember, each time the user edits the task, the workflow code responds to the task
change event, and uses this property to determine if the task is complete.

17. C#

18. Copy Code

19.private void onTaskChanged(object sender, EventArgs e)


20.{
21. notFinished =
22. !
bool.Parse(afterProps.ExtendedProperties["isFinished"].ToString());
23.}
24. Set the security level of the form to Domain.
a. On the Tools menu, click Form Options.

b. In the Form Options dialog box, in the Category list, click Security and Trust.

c. Under Security Level, clear the Automatically determine security level check box, and then

click Domain.

d. Click OK to save the changes and close the Form Options dialog box.

25. Publish the form.

a. On the File menu, click Save As. In the Save As dialog box, type TaskForm.xsn as the file

name. Save the form to the location of your choice. You will browse to this location in future
steps in order to add the file as a resource to the workflow project.

b. On the File menu, click Publish.

c. In the Publishing Wizard, select To a network location, and then click Next.

d. Click Browse.

e. In the Browse dialog box, navigate to the folder where you want to publish the form. Type

TaskForm as the file name and then click OK.

f. In the Publishing Wizard, type TaskForm for the form template name and click Next.

g. Click Publish, and Close.

Next Steps

Step 3: Create the Workflow


Step 3: Create the Workflow
In the first two parts of this walkthrough, you created the workflow initiation and task edit forms by using Microsoft
Office InfoPath 2007. In the last step of this walkthrough, you will create a sequential workflow project and the
code components of the workflow by using Visual Studio 2005 Designer for Windows Workflow Foundation.

Prerequisites

To complete this procedure, you must have completed the following procedures:

Step 1: Create the Workflow Initiation Form



Step 2: Creating the Workflow Task Edit Form

Note:

As with all Microsoft Office SharePoint Server 2007 development, you should create your workflows by
using a development environment that closely resembles the environment where the code will be
deployed. While it is not always possible to completely replicate a production environment by using
developer resources, making sure that the two environments are as similar as possible will greatly
simplify your development and debugging processes. For example, the Microsoft Office SharePoint
Server 2007-specific workflow activities require that Windows SharePoint Services and Microsoft Office
SharePoint Server 2007 be installed on the computer you use to develop the workflows.

To create a new Office SharePoint Server 2007 workflow project

1. Open Visual Studio 2005.

2. On the File menu, select New, and then click Project.

3. In the New Project window, view the Project types pane to find the development language choices.

4. Expand the language that you will use to develop your workflow.

5. Select the SharePoint option.

6. In the Templates pane, select SharePoint Sequential Workflow.

7. Name your project, and then click OK.

Visual Studio 2005 Designer for Windows Workflow Foundation opens a new workflow project. This
workflow project contains the necessary references to Windows SharePoint Services 3.0, and contains
workflow activities on the toolbox that were specifically designed for Windows SharePoint Services 3.0
workflows.

8. In order to programmatically access the XML schema that represents the forms you created in the first
two procedures, add the class file that you created earlier to your project.

In Solution Explorer, right-click your project name. Select Add then Existing Item. Using the Add
Existing Item dialog box, browse to the file location where you created your InitForm.cs file or
InitForm.vb file and click Add.

Adding and configuring workflow activities

Now that your new workflow project has been created, it is time to start designing your workflow.

In this workflow, there are a total of 5 activities.


Activity Description

OnWorkflowActivated Executes when the workflow is activated.

CreateTask Creates a workflow task and assigns it to a user.

While Executes the activities that it contains until a specific condition is no longer
true.

OnTaskChanged Executes when a workflow task is modified.

CompleteTask Sets the workflow task as complete.

To set the properties of the OnWorkflowActivation activity

1. Set the Invoked property of the OnWorkflowActivated activity.

When you created your workflow project by using the Windows SharePoint Services Sequential Workflow
project template, Visual Studio 2005 automatically added the first activity to your design surface and
created a method in the code-behind file. This first activity is called OnWorkflowActivated and has a
default name of onWorkflowActivated1. All Windows SharePoint Services 3.0 workflows must start with
this activity.

If the graphical representation of the workflow is not displayed, in Solutions Explorer, double-click the
Workflow1.cs file. If the workflow designer still does not have the OnWorkflowActivated activity
prepopulated, ensure that you used the correct Windows SharePoint Services Sequential Workflow
template.

a. In the workflow designer window, select the onWorkflowActivated1 activity.

b. In the Properties window, for the Invoked property type onWorkflowActivated and press

Enter. Visual Studio will open the code-behind file and create the OnWorkflowActivated
method if it does not already exist.

2. Ensure that the code file contains the correct references. If they are not present, add the following using
statements.

Notice in the properties window that the CorrelationToken and Path properties are set to
workflowToken and workflowProperties, respectively. These are workflow variables. They allow the
workflow engine to route data to the appropriate workflow instance. The workflowProperties variable
object is initialized when the workflow instance is activated. This includes properties that are common
to all workflows, such as the workflow instance identifier (ID) and the list item that the workflow
instance is running on. It can also include custom properties passed to a custom workflow initiation
form. In this case, the workflowProperties variable contains the initiation properties of the workflow
instance.

3. Ensure that the code file contains the correct references. If they are not present, add the following using
statements.

C#

Copy Code
using System.Xml;
using System.Xml.Serialization;
using Microsoft.SharePoint.Workflow
4. Add the following string variable declarations to the Workflow1 class

C#

Copy Code

private String assignee = default(String);


private String instructions = default(String);
private String comments = default(String);
5. Add the following code to the Workflow1 class file

Copy Code

namespace WorkflowLibrary1
{
public sealed partial class Workflow1:
SharePointSequentialWorkflowActivity
{
public Workflow1()
{
InitializeComponent(); }
public Guid workflowID = default(System.Guid);
public
Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties
workflowProps = new
Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties();
}
6. Add the following code to the onWorkflowActivated method.

C#

Copy Code

private void onWorkflowActivated(object sender, ExternalDataEventArgs e)


{
workflowID = workflowProps.WorkflowId;
XmlSerializer serializer = new XmlSerializer(typeof(InitForm));
XmlTextReader reader = new XmlTextReader (new
System.IO.StringReader(workflowProps.InitiationData));
InitForm initform = (InitForm) serializer.Deserialize(reader);
assignee = initform.assignee;
instructions = initform.instructions;
comments = initform.comments;
}
To add a CreateTask activity

1. From the Visual Studio 2005 Toolbox, in the Windows SharePoint Services section, drag a CreateTask

activity onto the workflow design surface and drop it immediately under the onWorkflowActivated1
activity.

2. Set the CreateTask activity properties.

a. With the CreateTask activity selected, view the Properties window.

b. For the CorrelationToken property, type taskToken.

c. For the MethodInvoking property, type createTask.

3. Ensure that your code file has the following declarations. Visual Studio 2005 should create these
automatically, but add them if they are not there.

Notice that the taskToken, taskId and taskProps are variable names. The taskToken variable is a
correlation token that enables Office SharePoint Server 2007 to route data to the appropriate task
within the workflow instance. The taskId variable is a GUID that identifies the task within the workflow
instance. The taskProps variable contains the properties that are used to initialize the task.

4. Ensure that your code file has the following declarations. Visual Studio 2005 should create these
automatically, but add them if they are not there.

Copy Code

public Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties afterProps


= new Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties();public
Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties beforeProps =
new Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties();
5. Add the following code to the code-behind page.

C#

Copy Code

private void createTask(object sender, EventArgs e)


{
taskID = Guid.NewGuid();
taskProps.Title = “Demo Task”;
taskProps.AssignedTo = assignee;
taskProps.Description = instructions;
taskProps.ExtendedProperties[“comments”] = comments;
taskProps.ExtendedProperties[“instructions”] = instructions;
}
At this point in the workflow process, the task has been created and assigned to a user. Now you must add
activities that enable the workflow to wait for the task to be completed by that user. You do this by using activities
that represent logic flow controls for your workflow.

To add a While Activity

1. From the Visual Studio 2005 toolbox, drag a While activity onto the workflow design surface and drop it

immediately under the createTask1 activity.

The While activity causes the activities inside it to loop, as long as the condition it evaluates resolves to
true. In this example, you will use it to loop around the task edit event until the user explicitly completes
the task.

2. Set the properties for the While activity.

a. Set the Condition property to Code Condition.

When you set this property to Code Condition, it indicates to the workflow that a custom
function has been created and should be used to process the while1 activity.

When you set the Condition subproperty to notFinished, this specifies the method that should
run. The method must return a Boolean value.

To add an OnTaskChanged activity

1. From the Visual Studio 2005 toolbox, drag an OnTaskChanged activity on to the workflow design surface

and drop it within the while1 activity loop.

2. Set the properties for the onTaskChanged1 activity.

a. Expand the AfterProperties property collection. For the Name property, type Workflow1 and

the Path property type afterProps.

b. Expand the BeforeProperties property collection. For the Name property, type Workflow1 and

the Path property, type beforeProps.

c. For the CorrelationToken property, type taskToken and the CorrelationTokenPath property,

type Workflow1.

d. For the Invoked property, type onTaskChanged. This method will be called when the

onTaskChanged1activity is executed.

e. Expand the TaskId property collection. For the Name property, type Workflow1 and for the

Path property, type taskId.

3. Visual Studio 2005 will automatically add the appropriate variable declarations to the workflow code.
However, if they are not created automatically, add the following code to the class.

Notice that the CorrleationToken and TaskId properties are set to the variables used in the
createTask1 activity. This setting binds this activity to the same task that was created by the
createTask1 activity, and ensures that the workflow is receiving the change event for the correct task.
Also notice that afterProps and beforeProps are object variables. The afterProps variable
represents the task properties after the task change event has occurred, while beforeProps
represents the task properties before the task change event occurred.

4. Visual Studio 2005 will automatically add the appropriate variable declarations to the workflow code.
However, if they are not created automatically, add the following code to the class.

C#

Copy Code

public Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties afterProps


= new Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties();
public Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties
beforeProps = new
Microsoft.SharePoint.Workflow.SPWorkflowTaskProperties();
5. Add code to the onTaskChanged method.

a. Add the following variable declaration to the workflow partial class:

C#

Copy Code

private bool isFinished = false


b. Add code to set the iisFinished variable. This information is passed to the workflow from the

task edit form.

c. C#

d. Copy Code

e. private void onTaskChanged(object sender, ExternalDataEventArgs e)


{
isFinished =
bool.Parse(afterProps.ExtendedProperties[“isFinished”].ToString()
);
}
6. Add code to the notFinished method.

Remember that the task edit form contains a check box named isFinished. The check box value is a
Boolean value that is stored as a custom property in the afterProps variable. The onTaskChanged
method needs to access this custom property in the afterProps variable.

a. C#

b. Copy Code

c. private void onTaskChanged(object sender, ExternalDataEventArgs e)


{
isFinished =
bool.Parse(afterProps.ExtendedProperties[“isFinished”].ToString()
);
}
7. Add code to the notFinished method.

Each time the task is changed, the while1 activity invokes this method to determine whether its condition
is met. As long as the Result property of the ConditionalEventArgs object evaluates to true, the
while1 activity will continue to wait.

Add code that sets the Result property of the ConditionalEventArgs object.

C++

Copy Code

private void notFinished(object sender, ConditionalEventArgs e)


{
e.Result
}
Now, each time the user edits the task, the onTaskChanged1 activity handles the task changed event. It
invokes the onTaskChanged method, which examines the task properties and sets the isFinished
variable to represent whether the user marked the task as complete. The while1 activity then invokes the
notFinished method, which sets the result of the event to the opposite of the isFinished variable. If
isFinished returns false, the event result is set to true, and the while1 activity keeps waiting for task
changes; if isFinished is equal to true, the event result is set to false, and the while1 activity
completes, and the workflow continues to the next activity.

To add a CompleteTask activity

1. From the Visual Studio 2005 toolbox, drag a CompleteTask activity onto the workflow design surface and

drop it immediately under the while1 activity.

2. Set the properties for the CompleteTask activity.

a. For the CorrelationToken property, type taskToken.

b. For the CorrelationToken Path property type Workflow1.

c. For the TaskId Name property type Workflow1 and the TaskId Path property type taskId.

Notice that the CorrelationToken and TaskId properties are set to the variables used in the
createTask1 activity. This binds this activity to the same task that was created by the createTask1
activity.

Now that your workflow is complete, you are ready to test, debug, and deploy your workflow and the forms that
accompany it.

Next Steps
To make the workflow available for association with document libraries in Office SharePoint Server 2007, you must
still compile the workflow assembly, install the workflow as a Feature, and activate the workflow Feature on the
selected site.

How to: Deploy a Workflow Template


Once you've created your workflow template and any necessary workflow forms, you still have to compile, install,
and activate the workflow before you can actually use it in Windows SharePoint Services.

The basic steps for this are as follows:

• Compile your workflow template as a strong-named assembly.

For more information on compiling and strong-naming your assembly, refer to the Visual Studio 2005
online help.

• Create the feature definition file that provides Windows SharePoint Services with the information
necessary to deploy your workflow at the specified scope.

• Create the workflow definition file that provides Windows SharePoint Services with the information
necessary to instantiate and run the workflow.

• Set the deploy property so that building the solution deploys the workflow files to the correct location,
copies the workflow assembly to the global assembly cache (GAC), and activates the workflow feature in
Windows SharePoint Services.

Note:

The following procedures assume you have created your workflow template using the Windows
SharePoint Services workflow project template. This project template, included in the Workflow Starter
Kit, contains developer features specifically to help you create, deploy, and activate workflows for
Windows SharePoint Services. The Workflow Starter Kit is available from the Microsoft Download
Center.

To Create a Feature Definition File in a Windows SharePoint Services Workflow Project


1. In Visual Studio 2005, open your Windows SharePoint Services workflow project, and in the Solution

Explorer window, double-click the feature.xml file.

2. Right-click anywhere in the feature.xml file, select Insert Snippet, select Windows SharePoint

Services Workflow, and then click Feature.xml code.

3. Replace the highlighted placeholder text with the information from your workflow project. Placeholder text
is formatted in all capital letters. This includes:

• A GUID to serve as the feature ID. This must be different than the workflow ID specified in the
workflow definition file.

• The workflow template title.

• A description of the workflow template.

• The file path, relative to this file, of the workflow definition file. The project default is
'workflow.xml.'
For more information on feature definition XML, see Feature.XML Files. For more information about
creating a Windows SharePoint Services 3.0 feature, see Working with Features.

4. Save your files.

To Create a Workflow Definition File in a Windows SharePoint Services Workflow Project


1. In Visual Studio 2005, open your Windows SharePoint Services workflow project, and in the Solution

Explorer window, double-click the workflow.xml file.

2. Right-click anywhere in the workflow.xml file, select Insert Snippet, select Windows SharePoint

Services Workflow, and then click workflow.xml code.

3. Replace placeholders with the information from your workflow project. Once you replace a placeholder
once, it's replaced throughout the XML. This includes:

• The workflow name, description, and unique identifier. This unique identified is for the workflow
itself, not the Feature in which the workflow is included.

• The code beside assembly and class name of the workflow assembly.

• Locations of workflow and task forms used by the workflow.

For more information on creating workflow definition XML files, see Workflow Definition Schema.

4. Save your files.

To Install and Activate Your Workflow Template Using PostBuildActions.bat


1. In Visual Studio 2005, open your Windows SharePoint Services workflow project.

2. In the Solution Explorer window, right-click the project title, and select Properties.

3. On the Build Events tab, edit the Post-build command line string to deploy your workflow solution. By

default, this parameter is specified as 'NODEPLOY'.

To deploy your workflow solution, the command line should read:

call "$(ProjectDir)\Deployment Files\PostBuildActions.bat" "$(ConfigurationName)" "$(ProjectDir)"


"$(TargetDir)" "$(TargetName)"
DEPLOY > BuildActions.log

Note:

When the NODEPLOY parameter is specified, the workflow assembly is compiled but not deployed.

1. On the Build menu, select Build Solution.

Once Visual Studio has built your workflow solution, it calls the PostBuildActions batch file, which
automates moving your workflow solution files to the correct locations for Windows SharePoint Services,
and activating the workflow feature.

In Debug build mode, this batch file does the following:

• Creates the feature directory at the appropriate location on the server.


• Copies the feature XML and workflow definition XML files into the feature directory.

• Copies the compiled workflow assembly into the Global Assembly Cache (GAC).

• Activates the feature in Windows SharePoint Services.

In Release build mode, this batch file creates and deploys a .wsp solution file that can be used for
deployment on a production server. It does the following:

Replaces placeholder text in the manifest.xml and wsp_structure.ddf files with the information from your
workflow project. This includes:

• The feature directory name.

• The feature XML file name.

• The workflow definition XML file name.

• The name and relative path of the compiled workflow assembly.

Once you have activated your workflow template, it is available for administrators to associate with lists
and document libraries on the site where it was activated.

Using a User Tasks web part for collaboration and


document approval in SharePoint
Learn how you can add and use a User Tasks web part in WSS 3.0 or MOSS 2007 to notify
users that a certain action is required of them, such as approving a document or providing
input for collaboration.
It is common in document management scenarios to have multiple people approving a document.
In such a case, you can assign a task to a user so that the user knows that there is a document for
him/her to approve.
The out-of-the-box (OOTB) Approval Workflow in Microsoft Office SharePoint Server 2007
uses this method to notify users that there is a document to be approved.
You can use the User Tasks web part in SharePoint to notify a user that there is a document that
requires approval and/or allow a user to instantly see which tasks have been assigned to him/her.
The User Tasks web part is available in both WSS 3.0 and MOSS 2007.
The User Tasks web part, just like the Relevant Documents web part, is part of the suite of
document management web parts available in SharePoint.
Figure 1. A User Tasks web part in SharePoint displaying a document approval task for the current user.

The User Tasks web part can be seen as a view of all tasks that are assigned to the currently
logged on user.
For example, if your organization uses several independent Tasks lists on a SharePoint site and
tasks are added to these lists and assigned to a particular user, you can add a User Tasks web part
on the home page of the SharePoint site, so that the user, to whom the tasks have been assigned,
can see all of the tasks that have been assigned to him/her as soon as he/she logs onto the
SharePoint site.
To add a User Tasks web part to the home page of a SharePoint site:
1. Go to the home page of the SharePoint site to which you want to add a User
Tasks web part.
2. On the Site Actions menu, click Edit Page.
3. On the home page of the SharePoint site on one of the web part zones, click
Add a Web Part.
4. On the Add Web Parts web page dialog, select the User Tasks web part,
and click Add.
5. On the home page of the SharePoint site, click Exit Edit Mode.
To test the User Tasks web part, you can create two Tasks lists, add tasks for a particular user to
each Tasks list, log on as that user, and then check whether the tasks you created appear in the
User Tasks web part.
A second option to test the User Tasks web part would be to create a SharePoint Designer
workflow that runs on a document library and uses the Collect Data from a User workflow
action to assign a task to a particular user.

Visual Studio workflow: Copy a document from one


SharePoint document library to another
Learn how you can create a Visual Studio workflow to copy a document from one
SharePoint document library to another on the same or a different site.

Workflow description
This article demonstrates how you can create a Visual Studio workflow that can be manually
started on a document in a SharePoint document library to copy that document to another
document library on the same or another SharePoint site.
Creating the custom SharePoint workflow
1. In SharePoint, create 2 document libraries: One to copy documents from and
another one to store the copied documents in. Note: These document
libraries do not have to be located on the same site.
2. In Visual Studio, create a SharePoint Sequential Workflow. If you are
unsure as to which steps you have to take to create a SharePoint workflow,
refer to the tutorials in the Visual Studio workflows for SharePoint mini
course.
3. Add a Code activity to the workflow.

Figure 1. SharePoint Sequential Workflow with a code activity to copy a


document to a library.
4. Write the following code in the ExecuteCode event handler of the Code activity:
// Get the item the workflow is running on
SPListItem item = workflowProperties.Item;

// Set the name of the document library and site


// where to copy the document to
string siteUrl = "http://<ServerName>/<SiteName>/";
string libName = "DocLibForCopies";

// Open the site


using (SPSite site = new SPSite(siteUrl))
{
using (SPWeb web = site.OpenWeb())
{
if (item.File != null)
{
// Copy the document to the library
SPFolder library = web.Folders[libName];
library.Files.Add(
item.Name, item.File.OpenBinary());
library.Update();
}
}
}
where ServerName is the name of your SharePoint server, SiteName the name of the site
on which the second document library is located, and DocLibForCopes the name of the
second document library to which documents will be copied.
5. Attach the workflow to the document library that contains the documents you
want to copy, and select the Allow this workflow to be manually started
by an authenticated user with Edit Item Permissions check box when
attaching the workflow to the document library.

Testing the workflow


Now whenever you manually start the workflow on a document in the first document library, that
document will be copied to the second document library and the workflow will end.
To manually start the workflow:
1. Hover over a document in the first document library until a drop-down list box
appears, click on the down arrow, and select Workflows from the context
menu that appears.

Figure 2. Accessing the workflows that can run on a document in a


SharePoint document library.
2. On the Workflows page under Start a New Workflow, click the workflow
you want to start.
Figure 3. Manually starting a SharePoint workflow.

S-ar putea să vă placă și