Pages

Tuesday, July 27, 2010

Working with Versions in SharePoint List programmatically

There are very few posts on working with Versions in SharePoint Lists Programmatically. While browsing through those posts I ran in to a question saying "How to get the Columns which changed in the SharePoint List?"

Problem Description:

How to get only the Updated Columns in a SharePoint List with respect to Versions? or maybe get the columns changed from the previous version with respect to the current Version?

Solution:

ArrayList alUpdatedFields = new ArrayList();

bool bItemChanged = false;

SPListItemCollection objItemColl = objList.GetItems(objQuery);

SPListItem objItem = objItemColl[0];

SPListItemVersionCollection objVersionColl = objItem.Versions;

if (objVersionColl != null && objVersionColl.Count > 0)
{
foreach (SPListItemVersion item in objVersionColl)
{
if (item.VersionLabel.ToString() != objItem["_UIVersionString"].ToString())
{
foreach (SPField objField in objItem.Fields)
{
if (!objField.ReadOnlyField && IsValueChanged(objField.Type, objItem[objField.InternalName], item[objField.InternalName]))
{
bItemChanged = true;
alUpdatedFields.Add(objField.Title);
}
}
if (bItemChanged)
{
break;
}
}
}
}


In the above code I am looking for the previously modified version compared to the current version and adding those fields to the Array List, instead we can have an HashTable to add the Field and its value as a key value pair.

if (item.VersionLabel.ToString() != objItem["_UIVersionString"].ToString()) //This condition is used to ignore the comparison of the current version with itself. you can add your own logic to compare it with the actually needed version

Below is the function to check if the value for a particular field has changed compared to other version:

private bool IsValueChanged(SPFieldType type, object FirstValue, object SecondValue)
{
if (string.IsNullOrEmpty(Convert.ToString(FirstValue)) && string.IsNullOrEmpty(Convert.ToString(SecondValue)))
{
return false;
}
else if (string.IsNullOrEmpty(Convert.ToString(FirstValue)))
{
return true;
}
else if (string.IsNullOrEmpty(Convert.ToString(SecondValue)))
{
return true;
}

switch (type)
{
case SPFieldType.DateTime:
return !Convert.ToDateTime(FirstValue).Date.Equals(Convert.ToDateTime(Convert.ToString(SecondValue)).Date);
case SPFieldType.User:
break;
case SPFieldType.Text:
case SPFieldType.Note:
return !Convert.ToString(FirstValue).ToUpper().Equals(Convert.ToString(SecondValue).ToUpper());
case SPFieldType.Boolean:
return !Convert.ToBoolean(FirstValue).Equals(Convert.ToBoolean(SecondValue));
case SPFieldType.Attachments:
break;
default:
return !FirstValue.Equals(SecondValue);
}

return false;
}

*Note: I have executed the code for the first item in the List, instead we can have it as a loop for multiple items.

No comments:

Post a Comment