Sharepoint: Update system properties using Server Object Model
This article discusses a useful SharePoint server object model code that will allows you to update system properties of a list Item (Created, Created By,Modified, Modified By). while migration from previous version of SharePoint to New Version the Created By field reset to the Account of the person performing the migration to overcome this issue I have written a small console application which will allow you to set the System Fields from Old site to New Site.
App.Config
- LogFileLocation : Provide a file system path where you wanted to store the log .
- SourceCSVLocation : provide a csv location path which contains the List name
- SourceSiteURL : Provide an url of source site e.g http://sp2010/sites/test1.
- TargetSiteURL: Provide an url of Target site e.g http://sp2013/sites/test1.
- ModifiedUser :** **Set Editor as System Account or if you want to replace it with any other account.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="LogFileLocation" value="C:\UpdateSystemFields\Logs" />
<add key="SourceCSVLocation" value="C:\UpdateSystemFields\List.csv" />
<add key="SourceSiteURL" value="http://sp2010/sites/test1" />
<add key="TargetSiteURL" value="http://sp2013/sites/test1" />
<add key="ModifiedUser" value="SHAREPOINT\system" />
</appSettings>
</configuration>
List.csv
ListName(header)
Employee
Customers
Finance
Program.cs File
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Configuration;
using System.IO;
using Microsoft.SharePoint;
using System.Collections;
using Microsoft.SharePoint.Utilities;
namespace UpdateSystemFields
{
class UpdateFields
{
//declare global variable for log file
static FileStream fileStream;
static StreamWriter writeExceptionFile;
//getting values of log file and siteurl inputfile from config file
static string strLogFileLocation = ConfigurationManager.AppSettings["LogFileLocation"];
static int intExceptionCount = 0;
static void Main(string[] args)
{
DataTable sourceDataTable = new DataTable();
string strFileName = strLogFileLocation + "BatchProcess_Log_" + DateTime.Now.ToString("MMddyyy") + ".txt";
fileStream = File.Open(strFileName, FileMode.Append, FileAccess.Write);
writeExceptionFile = new StreamWriter(fileStream);
try
{
writeExceptionFile.WriteLine("-------------------------------------------------------------------------------");
writeExceptionFile.WriteLine(DateTime.Now.ToString() + " Excecuting Process for Update System Fields..");
string strCSVPath = ConfigurationManager.AppSettings["SourceCSVLocation"];
if (!File.Exists(strCSVPath))
{
writeExceptionFile.WriteLine(DateTime.Now.ToString() + " Either strCSVPath directory path is incorrect or it does not exist !!!");
}
else
{
//Read site info from csv file, open site and get required data and then keep it in datatable
ReadFile(strCSVPath);
}
}
catch (Exception ex)
{
writeExceptionFile.WriteLine(DateTime.Now.ToString() + " Error has occured in Read CSV Process. Exception thrown : " + ex.Message.ToString());
intExceptionCount++;
}
finally
{
if (intExceptionCount > 0)
writeExceptionFile.WriteLine(DateTime.Now.ToString() + " UpdateProcess completed with " + intExceptionCount + " exceptions.");
else
writeExceptionFile.WriteLine(DateTime.Now.ToString() + " UpdateProcess completed successfully.");
writeExceptionFile.WriteLine("-------------------------------------------------------------------------------");
writeExceptionFile.WriteLine();
writeExceptionFile.WriteLine();
writeExceptionFile.Close();
fileStream.Close();
if (sourceDataTable != null)
sourceDataTable.Dispose();
if (writeExceptionFile != null)
writeExceptionFile.Dispose();
if (fileStream != null)
fileStream.Dispose();
}
}
/// <summary>
/// This method sets datatable structure for site information.
/// It first read the site value from csv file, retrieving neccesary info from site and keep information into table
/// </summary>
/// </summary>
/// <param name="strInputFilePath"></param>
/// <returns></returns>
private static void ReadFile(string strInputFilePath)
{
StreamReader objReader = new StreamReader(strInputFilePath);
string strLine = "";
string[] arrSiteURLs;
//Define report sturucture
System.Data.DataTable tblSite = new System.Data.DataTable();
tblSite.Columns.Add("ID", Type.GetType("System.Int32"));
tblSite.Columns.Add("ModifiedBy", Type.GetType("System.String"));
tblSite.Columns.Add("CreatedBy", Type.GetType("System.String"));
tblSite.Columns.Add("Modified", Type.GetType("System.String"));
tblSite.Columns.Add("Created", Type.GetType("System.String"));
try
{
while (strLine != null)
{
strLine = objReader.ReadLine();
try
{
if (strLine == "") strLine = null;
if (strLine != null && !strLine.ToUpper().Contains("LISTNAME"))
{
string strURL = ConfigurationManager.AppSettings["SourceSiteURL"];
using (SPSite oSite = new SPSite(strURL))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
SPList oList = oWeb.Lists[strLine];
SPQuery query = new SPQuery();
query.ViewAttributes = "Scope=\"RecursiveAll\"";
SPListItemCollection itemCollection = oList.GetItems(query);
DataTable responseTable = setValuesToTable(itemCollection, tblSite);
UpdateValuesinTargetList(responseTable, strLine);
}
}
}
}
catch (Exception ex)
{
writeExceptionFile.WriteLine(DateTime.Now.ToString() + " Error occured while opening Targett site : " + strLine + ". Exception thrown :" + ex.Message.ToString());
intExceptionCount++;
}
}
objReader.Close();
}
catch (Exception ex)
{
writeExceptionFile.WriteLine(DateTime.Now.ToString() + " Error occured in when reading site urls from input file. Exception thrown : " + ex.Message.ToString());
intExceptionCount++;
}
finally
{
if (objReader != null)
objReader.Dispose();
}
}
private static void UpdateValuesinTargetList(DataTable responseTable, string listName)
{
string strTargetURL = ConfigurationManager.AppSettings["TargetSiteURL"];
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite oSite = new SPSite(strTargetURL))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
string username = ConfigurationManager.AppSettings["ModifiedUser"];;
SPUser strEditor = oWeb.EnsureUser(username.ToString());
SPList oList = oWeb.Lists[listName];
writeExceptionFile.WriteLine("Updating List name"+listName +"by"+ strEditor);
intExceptionCount++;
SPQuery query = new SPQuery();
query.ViewAttributes = "Scope=RecursiveAll";
query.Query = "<Where><Eq><FieldRef Name='Editor'/><Value Type='User'>" + strEditor.Name + "</Value></Eq></Where>";
SPListItemCollection oItems = oList.GetItems(query);
foreach (SPListItem item in oItems)
{
DataRow[] dr = responseTable.Select("ID=" + item.ID);
if (dr.Length > 0)
{
string cretedby = dr[0]["CreatedBy"].ToString();
string modifiedby = dr[0]["ModifiedBy"].ToString();
item["Author"] = removeLastChar(cretedby.Split('#')[0].ToString());
item["Editor"] = removeLastChar(modifiedby.Split('#')[0].ToString());
item["Modified"] = Convert.ToDateTime(dr[0]["Modified"].ToString()).ToString("yyyy-MM-ddThh:mm:ssZ");
item["Created"] = Convert.ToDateTime(dr[0]["Created"].ToString()).ToString("yyyy-MM-ddThh:mm:ssZ");
item.Update();
}
}
}
}
});
}
catch (Exception ex)
{
writeExceptionFile.WriteLine(DateTime.Now.ToString() + " Error occured in when Updating Exception thrown : " + ex.Message.ToString());
intExceptionCount++;
}
}
public static int removeLastChar(string mystring)
{
string output = mystring.Remove(mystring.Length - 1, 1);
return int.Parse(output);
}
/// <summary>
/// This method retrieve site info and keep it into datatable
/// </summary>
/// <param name="oWebsite"></param>
/// <param name="tblSite"></param>
private static DataTable setValuesToTable(SPListItemCollection oItems, System.Data.DataTable tblSite)
{
DataRow dtRow;
if (oItems.Count > 0)
{
foreach (SPListItem oSPListItem in oItems)
{
dtRow = tblSite.NewRow();
dtRow["ID"] = oSPListItem.ID;
dtRow["ModifiedBy"] = oSPListItem["Editor"].ToString();
dtRow["CreatedBy"] = oSPListItem["Author"].ToString();
dtRow["Modified"] = oSPListItem["Modified"].ToString();
dtRow["Created"] = oSPListItem["Created"].ToString();
tblSite.Rows.Add(dtRow);
}
}
return tblSite;
}
}
}