Have you ever created a custom Workflow with Visual Studio which triggers off a change from an InfoPath Form? Have you ever ran into the situation where your Workflow seems to end up with the old InfoPath Form values after the Form has been resubmitted to the SharePoint Form Library? On a recent project we discovered this particular issue was happening on a SharePoint site which was patched with the latest Cumulative Updates released after Service Pack 2. While this issue did not appear in the vanilla Service Pack 2 version of SharePoint Server 2007 (running on Windows Server 2003 with SQL Server 2005), we did find ourselves working towards a fix for our client's patched environment. What did we do? We turned to the SPQuery object for help. This article is the first in our SPQuery Hacks series.
Winning the Race Conditions
In general, the SPQuery object is a great and efficient way (albeit more advanced way) of selecting a single item from a SharePoint list or library when you don't have an ID. In our case, we have the ID already, but we just needed to get the latest value from a simple text column as it switched from one value to another when the user edited the associated InfoPath Form. The Workflow infrastructure was returning the old values causing our Workflow to stop running because it didn't detect the change from the user. This is how we solved the problem:
Fetch the Same Item Again
Instead of using SPWorkflowActivationProperties.Item to read values from the Form's promoted properties, we used an SPQuery to get a second instance of the SPListItem which represented our InfoPath Form using the code snippet below:
// First: Open new SPSite and new SPWeb with using statements
// Then: Fetch a new SPList reference as list with the code below
// Be safe: get the internal name of the built-in ID column
string idInternalName = list.Fields["ID"].InternalName;
// Get the ID of your item from the Workflow properties
int id = workflowProperties.ItemId;
// Construct a new SPQuery object and write the CAML
SPQuery query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name='" + idInternalName + "' /><Value Type='Text'>" + id + "</Value></Eq></Where>";
// Run the SPQuery against your new SPList reference
SPListItemCollection itemCol = list.GetItems(query);
// Your new SPListItem reference!
SPListItem item = itemCol;
Use the New SPListItem Reference
After getting your new object reference (remember, this is actually the same item your Workflow is already running on), use this object instance to populate your serializable Workflow class variables to use in the remaining Workflow activities:
this._status = (string)item["Status"]; // Replace "Status" with your field
While this all seems a bit overkill for fetching one little string value, it does the trick and your Workflow can continue running using the latest value promoted from the InfoPath Form to make the right decisions as it executes.