Wednesday, March 30, 2011

How to programmatically get content approval information on a list item

Today, as I was working on a custom list form for SharePoint, I needed to get some information on versioning and content approval for the items in the list. It turned out to be quite straight-forward. Here is what I did.


Getting the versions

The versioning information is accessed through the SPListItem.Versions property. This will give you access to the SPListItemVersionCollection, which contains all the versions that the current user has access to. Notice the emphasize. If you access the versions with elevated privileges you will see all versions, including drafts.

A user with read-only privileges will se only approved versions.

The versions collection is ordered with the latest version first. This means that if you do the following:

foreach (SPListItemVersion myVersion in myListItem.Versions)
{
  Console.WriteLine(myVersion.VersionLabel);
}

you will get a result similar to this (in this case three versions have been made).

3.0
2.0
1.0

To get the field values for a given version you access them through an indexer on the version. As index you use either an integer, or the internal name of the field. The version also has a Fields collection, which you can use in the following manner:

foreach (SPField field in myVersion.Fields)
{
  Console.WriteLine(
    "Field {0}: {1}",
    field.InternalName,
    myVersion[field.InternalName]);
}

This seems somewhat counter-intuitive to me - I would have expected the field values to be accessed by myVersion.Fields[guid or internal name].

Getting the approval information

Approved versions are basically like all other versions: The approval information is stored in the version fields. Of special interest for approval is the field _ModerationStatus:

  • 0 equals Approved
  • 1 equals Rejected
  • 2 equals Pending

By combining this with other information in the version you could get the approved versions and the approval information by doing the following:

foreach (SPListItemVersion myVersion in myListItem.Versions)
{
  if (myVersion["_ModerationStatus"].ToString() == "0")
  {
    Console.WriteLine(
      "Date: {0} Ver.: {1} Approver: {2} Comments: {3}",
      myVersion.Created,
      myVersion.VersionLabel,
      myVersion.CreatedBy.LookupValue,
      myVersion["_ModerationComments"]);
  }
}

which in my example yields the following output:

Date: 30-03-2011 19:06:46 Ver.: 4.0 Approver: MyDomain\tmj Comments: My last comment.
Date: 30-03-2011 19:06:03 Ver.: 3.0 Approver: MyDomain\tmj Comments: My next comment.
Date: 30-03-2011 19:05:17 Ver.: 1.0 Approver: MyDomain\tmj Comments: My first comment.

In the above we can see that I did not approve version 2.0, therefore it is not shown in the output.

No comments:

Post a Comment