How to revert library items to its previous working condition.

There are some scenarios in day to day development, where current changes need to revert to  its previous working condition.
This can be achieved by finding the correct Version from Version-History of the item
and restore it accordingly.
The below code snippet is just for information, for files in document library and has the same approach for List Item as well.

Sample code Snippet…..

using (SPSite mksSite = new SPSite(“http://devsp:9900/”))
{
using (SPWeb mksWeb = mksSite.OpenWeb())
{
mksWeb.AllowUnsafeUpdates = true;
SPList lst = mksWeb.Lists[“helloListName”];
IEnumerable<SPListItem> demoLib = lst.Items.OfType<SPListItem>();
SPListItemCollection demoFormCollection = lst.Items;
XmlDocument itemVersionDoc = new XmlDocument();
using (WebClient client = new WebClient())
{
for (int i = 0; i < demoFormCollection.Count; i++)
{
SPListItem item = demoFormCollection[i];
byte[] fileByte = item.File.OpenBinary(SPOpenBinaryOptions.None);

// Validate your output if this is the correct one. THEN no further action required//

if (THE OUTPUT AFTER VALIDATION IS INCORRECT THEN)
{

IEnumerable<SPFileVersion> listItems = item.File.Versions.OfType<SPFileVersion>();

var allResults = listItems.OrderByDescending(prod => prod.ID);

foreach (var vitem in allResults)
{

bool needToFindOtherVersion = true;
{
if (needToFindOtherVersion)
{
//<MOST IMPORTANT> “_vti_history” IS THE PLACE FOR ALL THE VERSIONS//

client.Credentials = CredentialCache.DefaultCredentials;
fileByte = client.DownloadData(mksWeb.Url.TrimEnd(‘/’)
+ “/_vti_history/” + vitem.ID.ToString() + “/helloListName/” + item.Title);

//NOTE: fileByte is the OUTPUT from  VERSION HISTORY//

//CHECK IF THE OUTPUT IS THE CORRECT ONE AS PER REQUIREMENT//
if (THE OUTPUT AFTER VALIDATION IS INCORRECT THEN)
{
needToFindOtherVersion = true;
}
else
{
needToFindOtherVersion = false;

item.File.Versions.RestoreByLabel(vitem.VersionLabel);
Console.WriteLine(“Correct Version Restored Successfully.“);
break;
}
}

}
}

}
mksWeb.AllowUnsafeUpdates = false;
}

Advertisements