In CSOM, basically, there is no direct property to get the versions of the items in a List. By using "Lists Web Service"(/_vti_bin/Lists.asmx), however, we can get the information of all the versions and properties of each item inside a Custom List or a Document Library.
To get the above-required functionality, first of all, we have added the "Lists Web Service" in the required project.
In this blog, I am going to share all the codes for getting the version details of list items by using "Lists Web Service". We all know how to add a service to a project.
We are using the below code to achieve the same. The code is self-explanatory because of the comments I have written before each snippet.
Source Code
using System;
using System.Net;
using System.Xml;
using Microsoft.SharePoint.Client;
namespace ConsoleAppTest {
class Program {
static void Main(string[] args) {
ClientContext context = null;
List list = null;
ListItemCollection itemCollection = null;
ListItem item = null;
string userName = string.Empty;
string password = string.Empty;
string dateHistory = string.Empty;
string commentHistory = string.Empty;
string editor = string.Empty;
string loginName = string.Empty;
try {
using(context = new ClientContext("https://Testsite.sharepoint.com")) {
userName = "UserName";
password = "PassWord";
// Setting credential for the above site
context.Credentials = new SharePointOnlineCredentials(userName, password);
context.Load(context.Web);
context.ExecuteQuery();
// Getting list by Title
list = context.Web.Lists.GetByTitle("List Title");
context.Load(list, L => L.Id);
// Getting all items from selected list using caml query
itemCollection = list.GetItems(CamlQuery.CreateAllItemsQuery());
//Loading selected list items
context.Load(itemCollection, IC => IC.Include(I => I.Id, I => I.DisplayName));
context.ExecuteQuery();
if (itemCollection != null && itemCollection.Count > 0) {
for (int iCount = 0; iCount < itemCollection.Count; iCount++) {
try {
item = itemCollection[iCount];
ListService.Lists listService = new ListService.Lists();
listService.Url = context.Url + "/_vti_bin/Lists.asmx";
listService.Credentials = context.Credentials;
//Getting all item versions from custon list item using List Web Service
XmlNode nodeVersions = listService.GetVersionCollection(list.Id.ToString(), item.Id.ToString(), "_UIVersionString");
//looping all versions and getting 'Modified' and 'Editor' property of each version
foreach(XmlNode xNode in nodeVersions) {
try {
dateHistory = xNode.Attributes["Modified"].Value;
dateHistory = FormatDateFromSP(dateHistory);
commentHistory = xNode.Attributes["_UIVersionString"].Value;
loginName = xNode.Attributes["Editor"].Value;
} catch {}
}
} catch (Exception ex) {}
}
}
}
} catch (Exception ex) {}
}
private static string FormatDateFromSP(string dateHistory) {
string result;
result = dateHistory.Replace("T", " ");
result = result.Replace("Z", "");
return result;
}
}
}
No comments:
Post a Comment