Monday, June 12, 2017

SharePoint List versioning using c#

We can also enable SharePoint List versioning using c#

using (SPSite spsite = new SPSite("http://win7/"))
{
SPWeb spweb = spsite.OpenWeb();
SPList list = spweb.Lists["CustomList"];
list.EnableVersioning = true;
list.Update();
}

Retrieve SPListItem versions using c#

using (SPSite spsite = new SPSite("http://win7/"))
{
SPWeb spweb = spsite.OpenWeb();
SPListItemCollection listitems = spweb.GetList("http://win7/Lists/CustomList").Items;

foreach (SPListItem listitem in listitems)
{
//listitem.Versions.RestoreByID(5);
foreach (SPListItemVersion versionItem in listitem.Versions)
{
Console.WriteLine("VersionId :" + versionItem.VersionId);
Console.WriteLine("VersionLabel :" + versionItem.VersionLabel);
Console.WriteLine("IsCurrentVersion :" + versionItem.IsCurrentVersion);
Console.WriteLine("ListItem.Title :" + versionItem.ListItem.Title);
Console.WriteLine("Created :" + versionItem.Created);
Console.WriteLine("CreatedBy :" + versionItem.CreatedBy);
Console.WriteLine("Level :" + versionItem.Level);
}
}
}

Retrieve SPListItem version changes using c#

using (SPSite spsite = new SPSite("http://win7/"))
{
SPWeb spweb = spsite.OpenWeb();
SPListItemCollection listitems = spweb.GetList("http://win7/Lists/CustomList").Items;

foreach (SPListItem listitem in listitems)
{
for (int i = 0; i < listitem.Versions.Count - 1; i++)
{
SPListItemVersion oldVersion = listitem.Versions[i];
SPListItemVersion latestVersion = listitem.Versions[i + 1];
foreach (SPField field in oldVersion.Fields)
{
if (field.ShowInVersionHistory == false)
{
continue;
}

if (latestVersion == null)
{
Console.WriteLine("  > {0} changed to \"{1}\"",
field.StaticName, oldVersion[field.StaticName]);
continue;
}

if (oldVersion[field.StaticName].Equals(latestVersion[field.StaticName]))
{
continue;
}

Console.WriteLine("  > {0} changed from \"{1}\" to \"{2}\"",
field.StaticName, latestVersion[field.StaticName], oldVersion[field.StaticName]);
}
}

}
}
Console.ReadLine();


No comments:

Post a Comment