2011-07-24

How to Get Workflow History Programmatically

I introduced how to check workflow status in the last post.
Today, I introduce how to get workflow history from Workflow History List. You can find Workflow History List's URL by using SharePoint Designer.



Workflow History List is here. There are some columns associated with workflow.



The code is here. The code enables to get all workflow status associated each item in SharePoint site. You can modify the code to get a specific list's workflow status. I identify workflow history list item using "Workflow History Parent Instance" column and "Primary Item ID" column.(see "if" block.)

using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;

// This is Console Application //

SPSite site = new SPSite("http://sharepoint-site");
SPWeb web = site.OpenWeb();

foreach (SPList list in web.Lists)
{
    foreach(SPListItem item in list.Items)
    {
        foreach (SPWorkflow workflow in item.Workflows)
        {
            foreach (SPListItem worflowHistoryItem in workflow.HistoryList.Items)
            {
                if (("{" + workflow.InstanceId.ToString() + "}" == worflowHistoryItem["Workflow History Parent Instance"].ToString()) 
                    && (item.ID.ToString() == worflowHistoryItem["Primary Item ID"].ToString()))
                {
                    Console.WriteLine(item.Name + " : " + worflowHistoryItem["Description"]);
                }
            }
        }
    }
}

7 comments:

  1. Very bad practive to enumerate workflow.HistoryList.Items

    Use CAML instead

    ReplyDelete
    Replies
    1. hey can you help me in that ?
      ho can i get workflow history using CAML ?

      Delete
  2. not sure how this worked... you have 'worflow' for as a variable instead of 'workflow'. FAIL!

    ReplyDelete
    Replies
    1. grats. you found a missing 'k' and the poster found the workflow history list... you guys just wasted an hour of my 4 hours of personal web time D:

      Delete
  3. This post was helpful, thanks!

    Ignore the stupid remark from 'Anonymous' above. It doesn't FAIL 'Mrs. Anonymous' because workflowHistoryItem is defined as 'worflowHistoryItem' and referenced as 'worflowHistoryItem'.

    Your critique was sooooo helpful!

    \cbf

    ReplyDelete
  4. do not enumerate .listitems, bad practice at first sight

    ReplyDelete
  5. I have not tired this but at least the concept is really awesome and too cool :) Will surely try out when I can..but Thanks for the idea and the blog :)

    ReplyDelete