SharePoint 2007 Workflows - Writing an Ultra Basic WF

Posted on 7/9/2008 @ 12:18 AM in #SharePoint by | Feedback | 31037 views

Table of Contents for on SharePoint 2007 WF Authoring using Visual Studio.

1. Setting up your environment for writing VS2005 workflows.

2. Writing an ultra basic workflow, deploying it, and slicing dicing how it worked.

3. Making that workflow more complex, adding if/else, and a bunch of activities that sort of make it more interesting.

4. Adding user interaction to that workflow using Infopath forms.

5. Authoring SharePoint 2007 Workflows using VS2008.


Okay, so now that your environment is all set, we can begin writing an ultra basic WF.

The steps are more or less the same for a Sequential WF and a State Machine WF, but since all of us know what flowcharts are, and sequential WFs are very similar to flowcharts, I am going to use sequential WFs to demonstrate my point. What we are going to do, is write a simple workflow, and tie it to a simple custom list with 1 column - Title. This simple workflow when instantiated, changes the title of the list item to a number between 1 to 6 randomly (much like a dice). THATS IT (Keep it simple huh?). No other forms, no craziness. With such a basic WF, I will be able to demonstrate how this thing got built, how it got deployed, and how you can debug that sucker.

As an outline, you need to perform the following steps to author such a workflow -

  1. Create a project in VS2005 (For VS2008, please see instructions here)
  2. Think about your logic, and draw that on the WF designer.
  3. Fill in the code for your WF.
  4. Create a feature.xml
  5. Create a workflow.xml
  6. Deploy
  7. Try and run it.
  8. Debug

Let us take these 1 by 1.

1. Create a project in VS2005. (VS2008 instructions here)

Using VS2005, create a new project called RollOfDiceWF in VS2005. Base this project in the SharePoint Sequential WF template.

2. Think about your logic, and draw that on the WF Designer.

Okay, now in this workflow, I have no user input, and really no branching logic. All I need to do really is, calculate a random number between 1-6, and then simply update the list item's title column with that random number. Hmm .. sounds like a single activity that can get a hold of that item, and do the necessary updating should do the trick. Okay - I guess all I need to do is drop a single "Code Activity" on the WF Designer.

Now, the project that you just created, it's designer surface looks a bit like this to begin with -

This is quite interesting. What is "onWorkflowActivated1" doing there? Well - any sharepoint workflow, needs to have that as it's first activity. That activity will give you a whole bunch of goodness, such as access to the list item you will need shortly. On the toolbox, you will see a number of activities that you can choose from. Not all can be used in SharePoint workflows. Notably, any .NET 3.0 activity to do with Transactions or Compensation won't work in SharePoint 2007. Luckily, an activity you can indeed use, is the CodeActivity. Go ahead and drag drop the code activity on the surface of your workflow, right below "onWorkflowActivated1" as shown below.

Now, what is that red exclamation mark right next to the code activity? Well - it is telling you, that something is wrong. When you hover over it, it tells you that the Property ExecuteCode isn't set. This is where you need to write some code.

3. Fill in the code for your WF.

Okay, now how exactly you fill in the code, depends on the activities you dropped. Different activities have different needs. As I complicate this WF in further blogposts, I will have the opportunity to elucidate a few common scenarios. But, for now, just double click on the CodeActivity, and that should take you to a place, where you can write the code. Also, it will get rid of that exclamation mark. This works very much like ASP.NET (conceptually atleast). There is a .xoml file that is graphic in nature, and there is a .cs file, that is code-behind(ish). (Read WF Basics). So anytime you can right click on the surface of that WF, and choose "View Code" and it brings you back to the innards of your WF.

Now go ahead and modify the code to look like as below:

private void codeActivity1_ExecuteCode(object sender, EventArgs e)

{

    Random rnd = new Random() ;

    workflowProperties.Item["Title"] = rnd.Next(1, 6);

    workflowProperties.Item.Update();

}

As you can see, I am getting a random number between 1 and 6, and I am using workflowProperties.Item to access the List Item that this workflow is operating upon.

Thats it, the workflow is written. Now lets start talking about, what it will take to deploy this workflow.

4. Create a feature.xml

This visual studio template insists that you install your WF as a feature. Is that a bad thing? Heck no! WF's can contain many peices, especially if you are using forms, and custom activities. It's hella nice if the whole thing can be deployed/retracted as a solution/feature. So the next step is to go ahead and create a feature.xml. Well, under the DeploymentFiles\FeatureFiles folder - there already IS a feature.xml. You just need to add stuff to it.

Adding stuff to it is made a lot easier by using code snippets. The snippets intellisense probably won't work. What you need to do is, in VS2005, go to Tools --> Code Snippets Manager, and in the dialog box, choose XML, in the drop down, and click on "Add", and choose C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\Template\Xml.

Once intellisense is added in, go ahead and add the following snippet -

Insert Snippet > SharePoint Server Workflow > Feature.Xml Code

Once the feature is inserted, go ahead and modify the green place holders, so your feature.xml looks a bit like this -

<Feature  Id="7C5366F5-46EE-48bc-BF1E-ABBBE24DA04C"

          Title="Roll of Dice WF"

          Description="This feature is a workflow that rolls dice for you"

          Version="12.0.0.0"

          Scope="Site"

          ReceiverAssembly="Microsoft.Office.Workflow.Feature, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"

ReceiverClass="Microsoft.Office.Workflow.Feature.WorkflowFeatureReceiver"

xmlns="http://schemas.microsoft.com/sharepoint/">

  <ElementManifests>

    <ElementManifest Location="workflow.xml" />

  </ElementManifests>

  <Properties>

    <Property Key="GloballyAvailable" Value="true" />

 

    <!-- Value for RegisterForms key indicates the path to the forms relative to feature file location -->

    <!-- if you don't have forms, use *.xsn -->

    <Property Key="RegisterForms" Value="*.xsn" />

  </Properties>

</Feature>

 

Note that I put in a GUID at Id="". That is created using GUIDGEN, which can be accessed using Tools --> Create GUID in VS 2005 (this tool has been around since VC6 times).

5. Create a Workflow.xml

Similarly, edit the OOTB workflow.xml to as follows:

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">

  <Workflow

       Name="Roll Of Dice WF"

       Description="This workflow rolls dice for you"

       Id="92654684-543C-4045-981A-4E02FC9234E2"

       CodeBesideClass="RollofDiceWF.Workflow1"

       CodeBesideAssembly="RollofDiceWF, Version=1.0.0.0, Culture=neutral, PublicKeyToken=publicKeyToken"

       StatusUrl="_layouts/WrkStat.aspx">

 

    <Categories/>

    <!-- Tags to specify InfoPath forms for the workflow; delete tags for forms that you do not have -->

    <MetaData>

      <AssociateOnActivation>false</AssociateOnActivation>

    </MetaData>

  </Workflow>

</Elements>

Now, you would note that

a) I haven't put in the publicKeyToken yet. That is coming shortly.

b) I took out a bunch of stuff from this workflow.xml file. Well - we don't have any custom input forms, so you have to take that junk out. Otherwise, the WF won't work.

6. Deploy

Okay good. We're almost there.

In order to deploy, you need to do two things

a) Strongname the assembly.

Right click on the project, choose properties, and under signing, go ahead and create a new key. (This effectively strong names the assembly). Now go ahead and build the project. This will create the assembly, but won't actually deploy it yet. At this time, use a tool like Reflector to get the PublicKeyToken for the assembly, and update your Workflow.xml file with that public key token.

b) Actually deploy this WF ;-)

Now this is easy. Right click properties on the project, go to Build Events, and in the Post-Build event command line, change the last word from "NODEPLOY" to "DEPLOY".

(Seriously, that's it!)

Now, rebuild all the project. As a part of "Rebuild" the project will also deploy the solution & feature. The way it does all this, is by leveraging the PostBuildActions.bat that is a part of the project already. You can view the output of PostBuildActions.bat using Debug --> Output.

Should you choose to deploy this in production, simply change the project's configuration from Debug --> Release, and now it will create a .wsp for you. Pretty Nifty.

Great, now we can start playing with this.

7. Try and Run it

  • Go to the sharepoint site that this WF got deployed on (localhost:80), and create a new custom list. By default it has a single colum in it called "Title".
  • Go to list settings, workflow settings, and add an association of the Roll of Dice WF as shown below -

  • Go back to the list, and add a new List Item.
  • Click on the List Item, and choose Workflows.
  • Click on the RDWF link. (RDWF, because that was long descriptive (!) meaningful name I gave in the screenshot above).
  • You would note that the WF runs, as indicated by the SharePoint spinner, and the results are then shown as below -

Wow, I got a 5 in the first try. :-). Not bad!

Go ahead and peek around a bit. Look under Site Collection Features, you would see a feature for this workflow has been added and activated for you.

Also look under central administration > Operations > Solution Mgmt. You would see that the WF/Feature has been packaged up as a solution and deployed for you.

8. Debug

Life would be so much better if I never had to debug anything. But we all get stuck with debugging every now and then.

Debugging WFs is hella easy.

a) Go to project properties, under Debug, choose "Start Browser with URL", type in http://localhost.

b) Now set a breakpoint on the WF designer (yeah seriously, try it), and hit F5. VOILLA .. WF DEBUGGING. w00t!

The downer however is that managed code and WF cannot be debugged together (which really sucks). So, in order to debug inside an activity, you have to attach to w3wp.exe and uncheck workflow debugging.

Okay wow, this ultra simple WF has been a fairly long blogpost. Next I will complicate the WF a tad bit, but to save myself a whole amount of typing, I will simply reuse this above WF on build on top of it.

Read the next post - Complicating the above WF.

Sound off but keep it civil:

Older comments..


On 8/22/2007 2:03:47 PM Peter {faa780ce-0f0a-4c28-81d2-3667b71287fd} said ..
I'm in the process of building my first workflow application and something I've come across that weirds me out is all the data flow! I'm using InfoPath forms heavily (ok, so I'm sitting at 2 right now, but my grand total will be closer to 7) and pushing data from the "main list" to tasks, then filling in some extra data on the task and pushing data back to the "main list". And I've just now discovered the "ItemMetadata.xml" file, so apparently I'm going to be "pushing data" from the tasks (via this nutty file) to the InfoPath form. It's making me wish I was just working against "just" a database! What happened to that?

I guess I don't have much to say at this point, except that I am certainly looking forward to more workflow.


On 10/16/2007 9:04:11 AM Jacques said ..
I do not particularly like to install the sharepoint environment on my development laptop. How can I develop and deploy this solution without install WSS or MOSS 2007 on my laptop.


thanks


Jacques


On 10/16/2007 10:59:41 AM Sahil Malik said ..

On 12/14/2007 7:20:18 AM Teo said ..
stsadm installfeature and activatefeature worked fine, but then the error came: "failed on start(retrying)". Any hints ?

On 12/17/2007 12:15:12 PM Ahmed Mahmoud said ..
1-thank you very much this post was very good and it was easy to be understooood
2- those who are using internet explorer, you might get error displaying the initiatioform because you have to enable cookies and although you enabled it , the error still coming up . Don't pani this happens with the intenet explorer when your host name contains (_) underscore but if you are using firefox every thing will be fine

On 12/17/2007 6:00:48 PM Sahil Malik said ..
Thanks for the tip Ahmed

On 12/21/2007 3:37:33 PM Ahemd Mahmoud said ..
I was wondering sahil if you can recommend to me a well explained example of integrating WorkFlow with ASP.Net Forms and deploying it on SharePoint


On 12/21/2007 4:10:44 PM Sahil Malik said ..
Ahmed -

That has been on my TODO for a while. I'll try get that out.

Sahil


On 1/7/2008 11:44:53 AM A said ..
I followed your directions exactly. However after building with the flag changed from NODEPLOY to DEPLOY I get "You are not authorized to view this page" when trying to access the site. There are no entries in the logs, not even the Security log (which is odd given the nature of the error). Has anyone else saw this?


On 1/7/2008 11:54:37 AM A said ..
It seems I have found the answer to my own question. I will explain for others that may encounter it.

The problem was that I tryed following your stuff a bit too close. When I inserted the feature.xml snippet, it included an extra line "<ElementFile Location="MyForm.xsn"/>". So, I deleted it. This is what caused my problem.


On 1/7/2008 1:55:46 PM Sahil Malik said ..
A, Thanks for sharing.


On 1/8/2008 1:49:54 PM A said ..
Go ahead and ignore my last posting. Including that extra line caused the install procedure to error out which got the site working, but only because the feature was not causing an error.

My actual problem was that, being a paranoid individual, I have my "Projects" directory encrypted, so when the PostBuildActions.bat copied the feature.xml and the workflow.xml file into the FEATURES directory, the encryption went with it and thus SharePoint was not able to read those files giving me the "You are not authorized to view this page" error.

It is a strange scenario that very few people would likely encounter, but I thought I would explain anyway, if only to save a single other person from several hours of banging their head on a wall.

Now that I actaully have things working correctly, your article has proved very helpful.

Thanks.


On 1/8/2008 3:39:18 PM Sahil Malik said ..
A, I'm not ignoring. Just busier than Michael Jackson at a daycare. Wish I could help, but damn, between 3 hours of sleep over last 4 days, and helpin' ya .. I'm pickin' sleep.


On 1/17/2008 6:19:04 PM John Bailo said ..
I got all the way up to Step 7 in this (quite excellent) tutorial.

However, even though my .wsp file deployed and I can see it in Central Administration, the "Roll Of Dice WF" does not show up in the list of workflow templates. Is there any other deployment step, or is there something I need to do to enable this work flow for my generic list?


On 1/23/2008 4:11:35 AM Nikhil Khandelwal said ..
Check out VS 2008 to make workflow development easier. There is no need to perform so many steps - just run through a wizard and press F5 to create a simple, basic workflow. More details can be found at:


http://blogs.msdn.com/nikhil/archive/2008/01/15/sharepoint-workflow-feature-in-vs-2008.aspx


http://blogs.msdn.com/nikhil/archive/2008/01/19/sharepoint-workflow-feature-in-vs-2008-part-ii.aspx


Thanks,


Nikhil


On 2/4/2008 1:12:20 PM Mark said ..
Thanks for this great tutorial.

I followed all of the steps exactly was able to successfully build and deploy the workflow. The problem, however, is that when I test it, it does not work. Sharepoint says "Failed on Start".

Any advice on where to go from here?

Thanks!

-Mark


On 2/24/2008 7:13:36 AM Mehdi Chaouachi said ..
Same problem here !! I get the error "Failed on Start" . I tried everything from reinstalling the feature to creating everything from scratch!!! what is the problem here, can anybody help?


On 2/26/2008 1:48:58 AM Chris said ..
I have the exact same issue as John Bailo and I don't have access to VS2008!! Any ideas why this might be happening to both of us?


On 3/13/2008 8:54:05 AM junaid said ..
Hi

Its a great tutorial for beginner .i find it very useful sahil.thank you .......


On 3/21/2008 7:57:03 PM Yoyoma said ..
I also get the "failed to start" error. Any help would be appreciated because I'm not having much luck looking for another solution online. Other than that, the tutorial is cool beans.


On 3/27/2008 12:10:17 PM Helena Oliveira said ..
Thanks! Great post. It help me a lot...

Helena


On 3/31/2008 2:00:26 PM Paul Reed said ..
I have done all the steps but when I build for the first time it says.."the name 'workflowproperties' does not exist in the current context. Any ideas. I have all of the usings set correctly...strange.


On 4/15/2008 3:30:35 AM Gayatri said ..
I faced the failed on start (retrying) error, and to resolve the same, I checked the log files (c:\program files\common files\microsoft shared\web server extensions\12\log). This gave me the exact error message (Could not load file or assembly <my assembly name>. I checked the workflow.xml file for the declaration of the assembly and found that the version number matched the one deployed in the GAC - but the public key was not. The entire problem was due to oversight - so I just replaced the public key in the xml file and redeployed. Done!


On 4/29/2008 1:46:38 PM Matt said ..
I had the same problem with the "start (retrying)" error and got the same issue in the log file. I'd searched high and low for a solution without finding one that would work. Then the last post in this tutorial got me to re-examine my CodeBesideAssembly line and I noticed I'd written "PublicTokenKey" instead of "PublicKeyToken". (That said, I'm having other errors; but at least this one's resolved).


On 4/30/2008 1:56:42 PM Don said ..
Here is how I fixed the "Failed on Start" error. In the workflow.xml, there were two tags with the value of "RollofDiceWF", however I created my class as "RollOfDiceWF". Note the capital "O" in "Of." This resolved my problem.


On 5/12/2008 10:01:00 AM Moji said ..
when trying to save workflow in WDT it is giving this error 'saving failed'


On 5/23/2008 8:43:41 AM Sean said ..
I'm trying to deploy my workflow from a workstation that doesn't have SP installed on it. I know I have to change "//http:localhost" in the .bat file but my question I guess it what should I change it too? Also if theres any tutorial out there on deploying from a workstation that has VS 2005 running on XP that would be great.


On 6/6/2008 8:05:51 AM Naveen said ..
I'm getting the following error 'workflowproperties' does not exist in the current context. Please Help........!!!!!!!!!!!


On 6/28/2008 11:08:03 PM Jecoso Chou said ..
when i run into the following step:


Insert Snippet > SharePoint Server Workflow > Feature.Xml Code

I found no menu called “sharepoint server workflow”

Any hints?

My plat is WSS3.0+VS2005 and have instlled WF Extensions for VS 2005 as well as WSS SDK.

Any extention I must to instll?

Thank you very much


On 7/22/2008 6:21:11 AM Gaz said ..
It appears the snippets are now installed to "<system drive>:\Program Files\Microsoft Visual Studio 8\Xml\1033\Snippets"


On 7/30/2008 6:07:50 AM Tshepiso said ..
I'm getting the following error 'workflowproperties' does not exist in the current context.


On 9/5/2008 11:38:44 AM Mike said ..
I get the following error and i dont see my Roll of Dice workflow in workflow settings.


Can any body help me with the problem

The command "call "C:\Documents and Settings\Administrator\My Documents\RollOfDicWF\RollOfDicWF\\DeploymentFiles\PostBuildActions.bat" "Debug" "C:\Documents and Settings\Administrator\My Documents\RollOfDicWF\RollOfDicWF\" "RollOfDicWF" "C:\Documents and Settings\Administrator\My Documents\RollOfDicWF\RollOfDicWF\bin\Debug\" "RollOfDicWF" DEPLOY" exited with code 1053. RollOfDicWF


On 9/22/2008 8:42:10 PM SS said ..
Mine dyes during the execution. The following error in the log:


WinWF Internal Error, terminating workflow Id# 5424ff53-7c59-415d-a6a3-506d384cf808


System.ArgumentNullException: Value cannot be null. Parameter name: uriString

It's as if the item does not exist. It dies at the following line:


workflowProperties.Item["Title"] = rnd.Next(1, 6);

If i wrap in a try catch it completes successful. So i think I'm properly wired, but i must be missing something?

Any ideas? (vs2008, WSS 3.0, win2k3, fully updated, SharePoint SDK, etc installed)


On 12/18/2008 4:27:36 AM ali said ..
Hi, still wiating someone help about the error "Failed in start", why it is comming , i done every thing according to this post.


On 12/29/2008 5:15:13 AM Sami said ..
Hi All, I am having the same problem "Failed on start". Could anyone of you please write a solution to the problem. Thanks


On 1/20/2009 12:25:18 AM Raghavendra said ..
I don't get the DeploymentFiles folder when i create a new sequential workflow library project on VS2005 can you please let me know why?


If it is because a "SEQUENTIAL WORKFLOW LIBRARY" , I don'see any other templates like "Sequential Workflow" under Visual C# --> Sharepoint templates while creating a new project.


On 2/5/2009 1:46:11 PM softwareforgoats said ..
Here's a fix for the "workflowProperties does not exist in the current context" problem.

Add the following line to your class definition:

public Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties workflowProperties = new Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties();


On 7/10/2009 10:58:30 AM sid said ..
Hi,

Developed the project, made sure that I've changed the publictoken (using reflector) also made sure that "NODEPLOY" is "DEPLOY". Rebuild goes successfull. But no output. No error log and no workflow in workflow setting.

Mostly POSTBuild command is not getting executed correctly in my case. How to check if it goes fine or any other hint?

Thanks,


sid


On 7/14/2009 2:52:10 PM sid said ..
Hi Again,

I could figure out the problem.

Any of the paths (in PostBuildactions.bat) were not getting resolved. BUMMER!! I tell you.

When we create new project in Visual Studio, it builds and injects macros e.g. projectdir, targetdir etc...

Workaround: Replaced macros with hardcoded path and got it working.

Another learning: Everytime you tweak your workflow you have to rebuild, redeploy and reattach the workflow with the library. It won't refresh the attached instances for you.

Thanks Sahil for your post. Though it is an ultra basic workflow, it does provides adequate knowledge to get started.

Thanks,


Sraddhan


On 7/22/2010 12:26:54 PM Rahul Vartak said ..
Nice post Sahil...

Heres a list of steps I documented while having hands on SharePoint 2007 State machine workflows..

http://rahul-vartak.blogspot.com/2010/07/sharepoint-2007-state-machine-workflows.html

Hope this helps..:)


On 10/15/2010 6:19:06 AM Ric_30309 said ..
Thanks for this post. I wish I had found it before I waded through some of the examples.

I'm still building in 2005 because all the examples have been in that environment but I appreciated the clue that 2008 does a lot of the plumbing for you automatically.


On 12/9/2010 6:39:08 PM Mona said ..
Hi, i got "Error Occured " in status field.Any help will be really appreciated...