Migrating SharePoint ListItems

private void StartMigration()
{
StartProcess(txtSiteUrl.Text);

}

void StartProcess(string srcUrl)
{
Start_Export(srcUrl);
}

private void Start_Export(string srcUrl)
{
#region “Main”

string SourceSiteName = srcUrl.Substring(srcUrl.LastIndexOf(“/”) + 1);

string sourceUrl = srcUrl;
string destURL = srcUrl;

if (!string.IsNullOrEmpty(sourceUrl) && !string.IsNullOrEmpty(destURL))
{
string secAdminID = string.Empty;
//gvr.Cells[“SecondaryAdmin”].Value.ToString();

string destsiterelUrl = destURL.Replace(ConfigurationManager.AppSettings[“AppRootUrl”].ToString(), “”);

string DestinationSite = string.Empty;

DestinationSite = destURL;

FistSubThread(sourceUrl, SourceSiteName);

}

#endregion

}
private void FistSubThread(string sourceUrl, string SourceSiteName)
{

// DataGridViewRow gvr = (DataGridViewRow)objectGVR;

string newGuid = string.Empty;
DirectoryInfo dirinfo = null;
DirectoryInfo dirLogFiles = null;
SPExport exp = null;
SPExportSettings settings = null;

SPImportSettings impSettings = null;
SPImport imp = null;

string processPath = string.Empty;
string LogFileDirectory = string.Empty;
string LogFilePath = string.Empty;

SPWeb destWeb = null;
SPList mgList = null;

lblStatus.Text = “In Progress”;
lblStatus.Refresh();
lblStatus.Update();

bool executed = false;

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite mgSite = new SPSite(sourceUrl))
{
using (SPWeb mgWeb = mgSite.OpenWeb())
{
tgWeb = mgWeb;
try
{
mgList = mgWeb.Lists[txtSourceList.Text.Trim()];
tgList = mgWeb.Lists[txtTargetList.Text.Trim()];
}
catch (Exception exc)
{
// break;
}

try
{

//foreach (SPField field in mgList.Fields)
//{
// if (field.Type == SPFieldType.Lookup)
// {
// //expObj.ExcludeChildren = true;

// SPFieldLookup lookupField = (SPFieldLookup)field;
// //arrlookupList.Add(mgList.Title + “:” + lookupField.LookupList + “:” + lookupField.InternalName + “:” + lookupField.LookupField);
// try
// {
// Guid lookupGuid = new Guid(lookupField.LookupList);
// if (!string.IsNullOrEmpty(lookupField.LookupList))
// {
// string lookupListName = string.Empty;
// // using (SPSite mgSite = new SPSite(txtSourceUrl.Text))
// // {
// // using (SPWeb mgWeb = mgSite.OpenWeb())
// // {
// SPList lkList = mgWeb.Lists[new Guid(lookupField.LookupList)];
// lookupListName = lkList.Title;
// // }
// // }

// dtLookupLists.Rows.Add(mgList.Title, lookupListName, lookupField.InternalName, lookupField.LookupField, lookupField.Title);
// dtLookupLists.AcceptChanges();
// }
// }
// catch { }
// }
//}

if (chkID.Checked)
{

string camlQuery = string.Empty;
int totListCount = 0;

string startID = txtStartID.Text.Trim();
string endID = txtEndID.Text.Trim();

if (chkStatus.Checked)
{
string statusField = cmbStatus.SelectedItem.ToString();
string statusValue = txtStatusValue.Text.Trim();

camlQuery = @”<Where>
<And>
<Geq>
<FieldRef Name=’ID’ />
<Value Type=’Integer’>” + Convert.ToInt32(startID) + @”</Value>
</Geq>
<And>
<Leq>
<FieldRef Name=’ID’ />
<Value Type=’Integer’>” + Convert.ToInt32(endID) + @”</Value>
</Leq>
<Eq>
<FieldRef Name='” + statusField + @”‘ />
<Value Type=’Choice’>” + statusValue + @”</Value>
</Eq>
</And>
</And>
</Where>
<OrderBy><FieldRef Name=’Modified’ Ascending=’FALSE’ />
</OrderBy>”;
}
else
{
camlQuery = @”<Where>
<And>
<Geq>
<FieldRef Name=’ID’ />
<Value Type=’Integer’>” + Convert.ToInt32(startID) + @”</Value>
</Geq>
<Leq>
<FieldRef Name=’ID’ />
<Value Type=’Integer’>” + Convert.ToInt32(endID) + @”</Value>
</Leq>
</And>
</Where>
<OrderBy><FieldRef Name=’Modified’ Ascending=’FALSE’ />
</OrderBy>”;
}
SPQuery query = new SPQuery();
query.Query = camlQuery;
query.QueryThrottleMode = SPQueryThrottleOption.Override;
SPListItemCollection totItems = mgList.GetItems(query);

if (totItems != null)
{
totListCount = totItems.Count;

if (totListCount >= Convert.ToInt32(ConfigurationManager.AppSettings[“MinCount”]) && totListCount < Convert.ToInt32(ConfigurationManager.AppSettings[“ViewThreshold”]))
{

foreach (SPListItem mgItm in totItems)
{
newGuid = Guid.NewGuid().ToString();

LogFilePath = ConfigurationManager.AppSettings[“LogFilePath”] + “\\Logs-” + newGuid + “-” + SourceSiteName;

dirinfo = System.IO.Directory.CreateDirectory(ConfigurationManager.AppSettings[“ProcessingFolderPath”].ToString() + “\\” + newGuid);
dirLogFiles = System.IO.Directory.CreateDirectory(LogFilePath);

processPath = dirinfo.FullName;
LogFileDirectory = dirLogFiles.FullName;

settings = new SPExportSettings();

switch (ConfigurationManager.AppSettings[“IncludeSecurity”].ToString())
{
case “None”:
settings.IncludeSecurity = SPIncludeSecurity.None;
break;
case “All”:
settings.IncludeSecurity = SPIncludeSecurity.All;
break;
case “WssOnly”:
settings.IncludeSecurity = SPIncludeSecurity.WssOnly;
break;
}

switch (ConfigurationManager.AppSettings[“IncludeVersions”].ToString())
{
case “All”:
settings.IncludeVersions = SPIncludeVersions.All;
break;
case “CurrentVersion”:
settings.IncludeVersions = SPIncludeVersions.CurrentVersion;
break;
case “LastMajorAndMinor”:
settings.IncludeVersions = SPIncludeVersions.LastMajorAndMinor;
break;
case “LastMajor”:
settings.IncludeVersions = SPIncludeVersions.LastMajor;
break;
}

switch (ConfigurationManager.AppSettings[“ExportMethod”].ToString())
{
case “ExportAll”:
settings.ExportMethod = SPExportMethodType.ExportAll;
break;
case “ExportChanges”:
settings.ExportMethod = SPExportMethodType.ExportChanges;
break;
}

settings.FileCompression = ConfigurationManager.AppSettings[“FileCompression”].ToString() == “true” ? true : false;
settings.OverwriteExistingDataFile = ConfigurationManager.AppSettings[“OverwriteExistingDataFile”].ToString() == “true” ? true : false;
settings.LogExportObjectsTable = ConfigurationManager.AppSettings[“LogExportObjectsTable”].ToString() == “true” ? true : false;
settings.ExcludeDependencies = ConfigurationManager.AppSettings[“ExcludeDependencies”].ToString() == “true” ? true : false;

settings.FileLocation = processPath;
settings.LogFilePath = LogFileDirectory + “\\” + ConfigurationManager.AppSettings[“ExportLogFileName”].ToString();

// SetExportObjectList(ref settings, sourceUrl, mgList);

SPExportObject expObj = new SPExportObject();

expObj.IncludeDescendants = SPIncludeDescendants.All;

// expObj.Url = expObjUrl;
// expObj.p
// expObj
expObj.Id = mgItm.UniqueId;
settings.SiteUrl = sourceUrl;

expObj.Type = SPDeploymentObjectType.ListItem;
settings.ExportObjects.Add(expObj);

exp = new SPExport(settings);
//exp.Settings = settings;

exp.Run();

// Import starts

imp = new SPImport();

imp.Started += new EventHandler<SPDeploymentEventArgs>(imp_Started);

//imp.Error +=new EventHandler<SPDeploymentErrorEventArgs>(imp_Error);
//imp.Canceled +=new EventHandler<SPDeploymentEventArgs>(imp_Canceled);

impSettings = new SPImportSettings();
impSettings.FileLocation = processPath;

impSettings.SiteUrl = sourceUrl;
impSettings.LogFilePath = LogFileDirectory + “\\” + ConfigurationManager.AppSettings[“ImportLogFileName”].ToString();

switch (ConfigurationManager.AppSettings[“UserInfoDateTime”].ToString())
{
case “None”:
impSettings.UserInfoDateTime = SPImportUserInfoDateTimeOption.None;
break;
case “ImportAll”:
impSettings.UserInfoDateTime = SPImportUserInfoDateTimeOption.ImportAll;
break;
case “ReplaceUserWithSystemAccount”:
impSettings.UserInfoDateTime = SPImportUserInfoDateTimeOption.ReplaceUserWithSystemAccount;
break;

}

switch (ConfigurationManager.AppSettings[“UpdateVersions”].ToString())
{
case “Append”:
impSettings.UpdateVersions = SPUpdateVersions.Append;
break;
case “Ignore”:
impSettings.UpdateVersions = SPUpdateVersions.Ignore;
break;
case “Overwrite”:
impSettings.UpdateVersions = SPUpdateVersions.Overwrite;
break;

}

switch (ConfigurationManager.AppSettings[“impSettings.IncludeSecurity”].ToString())
{
case “All”:
impSettings.IncludeSecurity = SPIncludeSecurity.All;
break;
case “Ignore”:
impSettings.IncludeSecurity = SPIncludeSecurity.None;
break;
case “Overwrite”:
impSettings.IncludeSecurity = SPIncludeSecurity.WssOnly;
break;

}

impSettings.RetainObjectIdentity = ConfigurationManager.AppSettings[“RetainObjectIdentity”].ToString() == “true” ? true : false;
impSettings.FileCompression = ConfigurationManager.AppSettings[“impSettings.FileCompression”].ToString() == “true” ? true : false;

imp.ObjectImported += OnObjectImported;

try
{

try
{

imp.Settings = impSettings;

imp.Run();

}
catch (ThreadAbortException tex)
{

if (!Directory.Exists(ConfigurationManager.AppSettings[“ErrorLogFilePath”].ToString()))
Directory.CreateDirectory(ConfigurationManager.AppSettings[“ErrorLogFilePath”].ToString());

//File.AppendAllText(impSettings.LogFilePath, tex.Message);

}
catch (Exception ex)
{

if (!Directory.Exists(ConfigurationManager.AppSettings[“ErrorLogFilePath”].ToString()))
Directory.CreateDirectory(ConfigurationManager.AppSettings[“ErrorLogFilePath”].ToString());

}

finally
{
imp.Dispose();
}

}
catch (ThreadAbortException tex)
{
//File.AppendAllText(impSettings.LogFilePath, tex.Message);

if (!Directory.Exists(ConfigurationManager.AppSettings[“ErrorLogFilePath”].ToString()))
Directory.CreateDirectory(ConfigurationManager.AppSettings[“ErrorLogFilePath”].ToString());

}
catch (Exception ex)
{

if (!Directory.Exists(ConfigurationManager.AppSettings[“ErrorLogFilePath”].ToString()))
Directory.CreateDirectory(ConfigurationManager.AppSettings[“ErrorLogFilePath”].ToString());

}
finally
{

if (dirinfo.Exists)
dirinfo.Delete(true);
}
}
}
}
}
else
{

for (int itemCount = 0; itemCount < CheckedListBoxMonths.CheckedItems.Count; itemCount++)
{

string camlQuery = string.Empty;
int totListCount = 0;

string chk = CheckedListBoxMonths.CheckedItems[itemCount].ToString();

string selectedMonth = chk.Substring(0, 3);
string selectedYear = chk.Substring(3, 4);

DateTime FrDate = Convert.ToDateTime(“01-” + selectedMonth + “-” + selectedYear);
DateTime tDate = Convert.ToDateTime(DateTime.DaysInMonth(FrDate.Year, FrDate.Month).ToString() + “-” + selectedMonth + “-” + selectedYear);
string FromDate = Microsoft.SharePoint.Utilities.SPUtility.CreateISO8601DateTimeFromSystemDateTime(FrDate);
string ToDate = Microsoft.SharePoint.Utilities.SPUtility.CreateISO8601DateTimeFromSystemDateTime(tDate);
string subFolderName = chk;
string fieldIternalName = mgList.Fields[cmbDateFields.SelectedItem.ToString()].InternalName;

camlQuery = @”<Where>
<And>
<Geq>
<FieldRef Name='” + fieldIternalName + @”‘ />
<Value Type=’DateTime’>” + FromDate + @”</Value>
</Geq>
<Leq>
<FieldRef Name='” + fieldIternalName + @”‘ />
<Value Type=’DateTime’>” + ToDate + @”</Value>
</Leq>
</And>
</Where>
<OrderBy><FieldRef Name=’Modified’ Ascending=’FALSE’ />
</OrderBy>”;

SPQuery query = new SPQuery();
query.Query = camlQuery;
//query.QueryThrottleMode = SPQueryThrottleOption.Override;
SPListItemCollection totItems = mgList.GetItems(query);

if (totItems != null)
{
totListCount = totItems.Count;

if (totListCount >= Convert.ToInt32(ConfigurationManager.AppSettings[“MinCount”]) && totListCount < Convert.ToInt32(ConfigurationManager.AppSettings[“ViewThreshold”]))
{

foreach (SPListItem mgItm in totItems)
{
newGuid = Guid.NewGuid().ToString();

LogFilePath = ConfigurationManager.AppSettings[“LogFilePath”] + “\\Logs-” + newGuid + “-” + SourceSiteName;

dirinfo = System.IO.Directory.CreateDirectory(ConfigurationManager.AppSettings[“ProcessingFolderPath”].ToString() + “\\” + newGuid);
dirLogFiles = System.IO.Directory.CreateDirectory(LogFilePath);

processPath = dirinfo.FullName;
LogFileDirectory = dirLogFiles.FullName;

settings = new SPExportSettings();

switch (ConfigurationManager.AppSettings[“IncludeSecurity”].ToString())
{
case “None”:
settings.IncludeSecurity = SPIncludeSecurity.None;
break;
case “All”:
settings.IncludeSecurity = SPIncludeSecurity.All;
break;
case “WssOnly”:
settings.IncludeSecurity = SPIncludeSecurity.WssOnly;
break;
}

switch (ConfigurationManager.AppSettings[“IncludeVersions”].ToString())
{
case “All”:
settings.IncludeVersions = SPIncludeVersions.All;
break;
case “CurrentVersion”:
settings.IncludeVersions = SPIncludeVersions.CurrentVersion;
break;
case “LastMajorAndMinor”:
settings.IncludeVersions = SPIncludeVersions.LastMajorAndMinor;
break;
case “LastMajor”:
settings.IncludeVersions = SPIncludeVersions.LastMajor;
break;
}

switch (ConfigurationManager.AppSettings[“ExportMethod”].ToString())
{
case “ExportAll”:
settings.ExportMethod = SPExportMethodType.ExportAll;
break;
case “ExportChanges”:
settings.ExportMethod = SPExportMethodType.ExportChanges;
break;
}

settings.FileCompression = ConfigurationManager.AppSettings[“FileCompression”].ToString() == “true” ? true : false;
settings.OverwriteExistingDataFile = ConfigurationManager.AppSettings[“OverwriteExistingDataFile”].ToString() == “true” ? true : false;
settings.LogExportObjectsTable = ConfigurationManager.AppSettings[“LogExportObjectsTable”].ToString() == “true” ? true : false;
settings.ExcludeDependencies = ConfigurationManager.AppSettings[“ExcludeDependencies”].ToString() == “true” ? true : false;

settings.FileLocation = processPath;
settings.LogFilePath = LogFileDirectory + “\\” + ConfigurationManager.AppSettings[“ExportLogFileName”].ToString();

// SetExportObjectList(ref settings, sourceUrl, mgList);

SPExportObject expObj = new SPExportObject();

expObj.IncludeDescendants = SPIncludeDescendants.All;

// expObj.Url = expObjUrl;
// expObj.p
// expObj
expObj.Id = mgItm.UniqueId;
settings.SiteUrl = sourceUrl;

expObj.Type = SPDeploymentObjectType.ListItem;
settings.ExportObjects.Add(expObj);

exp = new SPExport(settings);
//exp.Settings = settings;

exp.Run();

// Import starts

imp = new SPImport();

imp.Started += new EventHandler<SPDeploymentEventArgs>(imp_Started);

//imp.Error +=new EventHandler<SPDeploymentErrorEventArgs>(imp_Error);
//imp.Canceled +=new EventHandler<SPDeploymentEventArgs>(imp_Canceled);

impSettings = new SPImportSettings();
impSettings.FileLocation = processPath;

impSettings.SiteUrl = sourceUrl;
impSettings.LogFilePath = LogFileDirectory + “\\” + ConfigurationManager.AppSettings[“ImportLogFileName”].ToString();

switch (ConfigurationManager.AppSettings[“UserInfoDateTime”].ToString())
{
case “None”:
impSettings.UserInfoDateTime = SPImportUserInfoDateTimeOption.None;
break;
case “ImportAll”:
impSettings.UserInfoDateTime = SPImportUserInfoDateTimeOption.ImportAll;
break;
case “ReplaceUserWithSystemAccount”:
impSettings.UserInfoDateTime = SPImportUserInfoDateTimeOption.ReplaceUserWithSystemAccount;
break;

}

switch (ConfigurationManager.AppSettings[“UpdateVersions”].ToString())
{
case “Append”:
impSettings.UpdateVersions = SPUpdateVersions.Append;
break;
case “Ignore”:
impSettings.UpdateVersions = SPUpdateVersions.Ignore;
break;
case “Overwrite”:
impSettings.UpdateVersions = SPUpdateVersions.Overwrite;
break;

}

switch (ConfigurationManager.AppSettings[“impSettings.IncludeSecurity”].ToString())
{
case “All”:
impSettings.IncludeSecurity = SPIncludeSecurity.All;
break;
case “Ignore”:
impSettings.IncludeSecurity = SPIncludeSecurity.None;
break;
case “Overwrite”:
impSettings.IncludeSecurity = SPIncludeSecurity.WssOnly;
break;

}

impSettings.RetainObjectIdentity = ConfigurationManager.AppSettings[“RetainObjectIdentity”].ToString() == “true” ? true : false;
impSettings.FileCompression = ConfigurationManager.AppSettings[“impSettings.FileCompression”].ToString() == “true” ? true : false;

imp.ObjectImported += OnObjectImported;

try
{

try
{

imp.Settings = impSettings;

imp.Run();

}
catch (ThreadAbortException tex)
{

if (!Directory.Exists(ConfigurationManager.AppSettings[“ErrorLogFilePath”].ToString()))
Directory.CreateDirectory(ConfigurationManager.AppSettings[“ErrorLogFilePath”].ToString());

//File.AppendAllText(impSettings.LogFilePath, tex.Message);

}
catch (Exception ex)
{

if (!Directory.Exists(ConfigurationManager.AppSettings[“ErrorLogFilePath”].ToString()))
Directory.CreateDirectory(ConfigurationManager.AppSettings[“ErrorLogFilePath”].ToString());

}

finally
{
imp.Dispose();
}

}
catch (ThreadAbortException tex)
{
//File.AppendAllText(impSettings.LogFilePath, tex.Message);

if (!Directory.Exists(ConfigurationManager.AppSettings[“ErrorLogFilePath”].ToString()))
Directory.CreateDirectory(ConfigurationManager.AppSettings[“ErrorLogFilePath”].ToString());

}
catch (Exception ex)
{

if (!Directory.Exists(ConfigurationManager.AppSettings[“ErrorLogFilePath”].ToString()))
Directory.CreateDirectory(ConfigurationManager.AppSettings[“ErrorLogFilePath”].ToString());

}
finally
{

if (dirinfo.Exists)
dirinfo.Delete(true);
}
}
}
}
}
}
}
catch (ThreadAbortException tex)
{
if (!Directory.Exists(ConfigurationManager.AppSettings[“ErrorLogFilePath”].ToString()))
Directory.CreateDirectory(ConfigurationManager.AppSettings[“ErrorLogFilePath”].ToString());

if (dirinfo.Exists)
dirinfo.Delete(true);

}
catch (Exception ex)
{
if (!Directory.Exists(ConfigurationManager.AppSettings[“ErrorLogFilePath”].ToString()))
Directory.CreateDirectory(ConfigurationManager.AppSettings[“ErrorLogFilePath”].ToString());

if (dirinfo.Exists)
dirinfo.Delete(true);
}
finally
{
exp.CleanUpAutoGeneratedDataFiles();
exp.Dispose();

}

// if (execCount == listCount)
// {
// executed = true;
// }
}
}
});

// if (executed)
// {
try
{
// FixMissingFeatures(sourceUrl);

if (ConfigurationManager.AppSettings[“MigratePermissions”].ToString() == “true”)
{
MigratePermissions(sourceUrl, sourceUrl);
}

}
catch (Exception exc)
{

}
finally
{
lblStatus.Text = “Process Completed”;
lblStatus.Refresh();
lblStatus.Update();
}

}

private void FixMissingFeatures(string sourceUrl)
{
// Adding missing lookup values

SPList mgList = null;
SPList tgList = null;
SPList lookupList = null;

DataTable dtLookups = dtLookupLists.DefaultView.ToTable(true, “ListName”);

DataRow[] drSubs = null;
//string[] fieldArray;
int fieldCount = 0;
StringBuilder queryFields = new StringBuilder();
using (SPSite mgSite = new SPSite(sourceUrl))
{
using (SPWeb mgWeb = mgSite.OpenWeb())
{
foreach (DataRow dr in dtLookups.Rows)
{

drSubs = dtLookupLists.Select(“ListName='” + dr[“ListName”].ToString() + “‘”);
fieldCount = 0;
try
{
tgList = mgWeb.Lists[dr[“ListName”].ToString()];
// fieldArray = new string[drSubs.Length];
foreach (DataRow drSub in drSubs)
{

lookupList = mgWeb.Lists[drSub[“LookupList”].ToString()];

tgList.Fields.Delete(drSub[“FieldInternalName”].ToString());

string field = tgList.Fields.AddLookup(drSub[“FieldDisplayName”].ToString(), lookupList.ID, false);

// fieldArray[fieldCount] = drSub[“FieldInternalName”].ToString();

queryFields.Append(“<FieldRef Name='” + drSub[“FieldInternalName”].ToString() + “‘ />”);

SPFieldLookup lookUp = new SPFieldLookup(tgList.Fields, field);

lookUp.AllowMultipleValues = false;

lookUp.LookupField = lookupList.Fields[drSub[“LookupField”].ToString()].InternalName;
lookUp.Update();
SPView view = tgList.DefaultView;
view.ViewFields.Add(lookUp);
view.Update();
fieldCount++;
}

mgList = mgWeb.Lists[dr[“ListName”].ToString()];

SPQuery query = new SPQuery();

query.ViewFields = queryFields.ToString();
query.ViewAttributes = “Scope=\”Recursive\””;

SPListItemCollection itemColn = mgList.GetItems(query);

SPListItem itemTarget = null;
foreach (SPListItem item in itemColn)
{
itemTarget = tgList.GetItemById(item.ID);

foreach (DataRow drSub in drSubs)
{
itemTarget[drSub[“FieldInternalName”].ToString()] = item[drSub[“FieldInternalName”].ToString()];
}
itemTarget.Update();
}

// foreach(SPListItem item in mgList.GetItems(
}
catch { }
}
}
}

 

// Adding alerts to target site

//using (SPSite mgSite = new SPSite(sourceUrl))
//{
// using (SPWeb mgWeb = mgSite.OpenWeb())
// {

// using (SPSite tgSite = new SPSite(destURL))
// {
// using (SPWeb tgWeb = tgSite.OpenWeb())
// {
// SPAlert tgAlert = null;

// foreach (SPAlert alert in mgWeb.Alerts)
// {
// try
// {
// tgAlert = tgWeb.Alerts.Add();

// // bwMigrator.ReportProgress(i * mgWeb.Alerts.Count, i);

// tgAlert.AlertType = alert.AlertType;
// tgAlert.AlertFrequency = alert.AlertFrequency;
// tgAlert.User = tgWeb.EnsureUser(alert.User.LoginName);

// if (alert.AlertFrequency == SPAlertFrequency.Daily)
// {
// tgAlert.AlertTime = alert.AlertTime;
// tgAlert.AlwaysNotify = alert.AlwaysNotify;
// }
// else if (alert.AlertFrequency == SPAlertFrequency.Weekly)
// {
// tgAlert.AlertTime = alert.AlertTime;
// tgAlert.AlwaysNotify = alert.AlwaysNotify;
// }

// tgAlert.AlertTemplate = alert.AlertTemplate;

// if (alert.AlertType == SPAlertType.List)
// {
// tgAlert.List = tgWeb.Lists[alert.List.Title];

// }
// else if (alert.AlertType == SPAlertType.Item)
// {
// tgAlert.Item = tgWeb.Lists[alert.List.Title].GetItemById(alert.ItemID);
// }

// //tgAlert = alert;
// tgAlert.Update();
// }
// catch { }
// }
// }
// }
// }
//}

//Adding workflow definitions.

//using (SPSite mgSite = new SPSite(sourceUrl))
//{
// using (SPWeb mgWeb = mgSite.OpenWeb())
// {

// using (SPSite tgSite = new SPSite(destURL))
// {
// Guid featureGuid = new Guid(ConfigurationManager.AppSettings[“WorkflowsFeatureId”].ToString());
// try
// {
// if (tgSite.Features[featureGuid] == null)
// {
// tgSite.Features.Add(featureGuid);
// }
// }
// catch { }

// try
// {
// Guid featureExpGuid = new Guid(ConfigurationManager.AppSettings[“ExpirationWFFeatureId”].ToString());
// if (tgSite.Features[featureExpGuid] == null)
// {
// tgSite.Features.Add(featureExpGuid);
// }

// }
// catch { }

// try
// {
// Guid featureTSGuid = new Guid(ConfigurationManager.AppSettings[“ThreeStateWFFeatureId”].ToString());
// if (tgSite.Features[featureTSGuid] == null)
// {
// tgSite.Features.Add(featureTSGuid);
// }
// }
// catch { }

// using (SPWeb tgWeb = tgSite.OpenWeb())
// {
// foreach (SPList contentType in mgWeb.Lists)
// {
// try
// {

// //SPWorkflowTemplate workflowTemplate = null;
// foreach (SPWorkflowAssociation wa in contentType.WorkflowAssociations)
// {
// // workflowTemplate = template;

// // We’ll take a template everyone has.
// // if (workflowTemplate.Name == “Three-state”) break;
// //foreach (SPWorkflowAssociation wa in mgWeb.WorkflowAssociations)
// // {
// tgWeb.AllowUnsafeUpdates = true;

// SPList taskSource = null;
// SPList taskList = null;

// try
// {
// taskSource = mgWeb.Lists[wa.TaskListTitle];

// taskList = tgWeb.Lists[wa.TaskListTitle];
// }
// catch (Exception exT)
// {

// tgWeb.Lists.Add(taskSource.Title, taskSource.Description, taskSource.BaseTemplate);
// }

// SPList histSource = null;
// SPList histList = null;

// try
// {
// histSource = mgWeb.Lists[wa.HistoryListTitle];

// histList = tgWeb.Lists[wa.HistoryListTitle];
// }
// catch (Exception exT)
// {

// tgWeb.Lists.Add(histSource.Title, histSource.Description, histSource.BaseTemplate);
// }

// SPWorkflowTemplate workflowTemplate = mgWeb.WorkflowTemplates[wa.BaseId];

// if (workflowTemplate != null)
// {
// SPWorkflowAssociation workflowAssociation = SPWorkflowAssociation.CreateListAssociation(workflowTemplate, wa.Name, tgWeb.Lists[wa.TaskListTitle],
// tgWeb.Lists[wa.HistoryListTitle]);

// tgList = tgWeb.Lists[contentType.Title];

// workflowAssociation.AllowManual = wa.AllowManual;
// workflowAssociation.AutoStartCreate = wa.AutoStartCreate;
// workflowAssociation.AutoStartChange = wa.AutoStartChange;
// workflowAssociation.AssociationData = wa.AssociationData;

// if (tgList.WorkflowAssociations.GetAssociationByName(workflowAssociation.Name, tgWeb.Locale) == null)
// {
// tgList.AddWorkflowAssociation(workflowAssociation);

// }
// else
// {
// tgList.UpdateWorkflowAssociation(workflowAssociation);

// }

// // tgList.Update();

// }

// tgWeb.AllowUnsafeUpdates = false;

// }
// }
// catch { }
// }

// }
// }
// }
//}

}

private void MigratePermissions(string sourceUrl, string destURL)
{
try
{
string perFileLoc = ConfigurationManager.AppSettings[“PermissionFileLocation”].ToString();

using (SPSite mgSite = new SPSite(sourceUrl))
{
using (SPWeb spWebSource = mgSite.OpenWeb())
{
Export data = new Export();
data.OnLogChange += new Export.WriteLog(data_OnLogChange);
data.ExportPermission(spWebSource, perFileLoc, txtSourceList.Text.Trim(), ConfigurationManager.AppSettings[“ListItemPermissions”].ToString());
}
}

// File.Open(ConfigurationManager.AppSettings[“LogFilePath”].ToString() + “\\PermissionExportLog” + Guid.NewGuid().ToString() + “.txt”, FileMode.OpenOrCreate).Close();
File.WriteAllText(ConfigurationManager.AppSettings[“LogFilePath”].ToString() + “\\PermissionExportLog” + Guid.NewGuid().ToString() + “.txt”, txtLogs.Text);

txtLogs.Text = “”;

using (SPSite spSiteSource = new SPSite(destURL))
{
using (SPWeb spWebSource = spSiteSource.OpenWeb())
{
Import data = new Import();
data.OnLogChange += new Import.WriteLog(data_OnLogChange);
data.ImportPermission(spWebSource, perFileLoc,txtTargetList.Text.Trim());
}
}

//File.Open(ConfigurationManager.AppSettings[“LogFilePath”].ToString() + “\\PermissionImportLog” + Guid.NewGuid().ToString() + “.txt”, FileMode.OpenOrCreate).Close();
File.WriteAllText(ConfigurationManager.AppSettings[“LogFilePath”].ToString() + “\\PermissionImportLog” + Guid.NewGuid().ToString() + “.txt”, txtLogs.Text);
}
catch (Exception exc)
{

}
}

void data_OnLogChange(string message)
{
if (InvokeRequired)
Invoke((MethodInvoker)delegate()
{
txtLogs.Text += “[” + DateTime.Now.ToString() + “]: ” + message + Environment.NewLine;
this.txtLogs.SelectionStart = this.txtLogs.Text.Length;
this.txtLogs.ScrollToCaret();
});
else
{
txtLogs.Text += “[” + DateTime.Now.ToString() + “]: ” + message + Environment.NewLine;
this.txtLogs.SelectionStart = this.txtLogs.Text.Length;
this.txtLogs.ScrollToCaret();
}

}

private void impCompleted(DataGridViewRow gvr, SPImportSettings impSettings, string _GUID)
{

string destinationSiteURL = string.Empty;
string sourceURL = string.Empty;
string targetURL = string.Empty;
string exportTimings = “Export: “;
string importTimings = “Import: “;
//string siteSize = string.Empty;
string exportStart = string.Empty;
string importFinish = string.Empty;

destinationSiteURL = impSettings.SiteUrl.ToString();

try
{

//siteSize = gvr.Cells[“Storage”].Value.ToString();
sourceURL = gvr.Cells[“SiteURL”].Value.ToString();
targetURL = gvr.Cells[“txtDestinationSite”].Value.ToString();

string exportLogFile = impSettings.LogFilePath.Substring(0, impSettings.LogFilePath.LastIndexOf(“\\”) + 1)
+ ConfigurationManager.AppSettings[“ExportLogFileName”].ToString();

string importLogFile = impSettings.LogFilePath;

foreach (string line in File.ReadAllLines(exportLogFile))
{
if (line.Contains(“Start Time:”))
{
//MessageBox.Show(line.ToString());
//MessageBox.Show(“exportTimings : ” + exportTimings);

exportTimings += line.Remove(0, 22) + “| “;

//MessageBox.Show(“exportTimings : ” + exportTimings);

exportStart = line.Substring(line.IndexOf(“:”, 22) + 1, 19).Replace(“A”, string.Empty).Replace(“P”, string.Empty);

//MessageBox.Show(“exportStart = line.Substring : ” + exportTimings);

continue;
}

if (line.Contains(“Finish Time:”))
{
exportTimings += line.Remove(0, 22) + “| “;
continue;
}

if (line.Contains(“Duration:”))
{
exportTimings += line.Remove(0, 22) + “| “;

continue;
}
}

foreach (string line in File.ReadAllLines(importLogFile))
{
if (line.Contains(“Start Time:”))
{
importTimings += line.Remove(0, 22) + “| “;
continue;
}

if (line.Contains(“Finish Time:”))
{
importTimings += line.Remove(0, 22) + “| “;
importFinish = line.Substring(line.IndexOf(“:”, 22) + 1, 19).Replace(“A”, string.Empty).Replace(“P”, string.Empty);
continue;
}

if (line.Contains(“Duration:”))
{
importTimings += line.Remove(0, 22) + “| “;

continue;
}
}

//if (File.Exists(“King.txt”))
// File.Create(“King.txt”);

//File.AppendAllText(“King.txt”, exportStart + ” —— ” + importFinish);

 

//DateTime exportTime = DateTime.Parse(exportStart, Thread.CurrentThread.CurrentCulture);
//DateTime importTime = DateTime.Parse(importFinish, Thread.CurrentThread.CurrentCulture);

DateTime exportTime = DateTime.Parse(DateTime.Now.ToString(), Thread.CurrentThread.CurrentCulture);
DateTime importTime = DateTime.Parse(DateTime.Now.ToString(), Thread.CurrentThread.CurrentCulture);

 

TimeSpan ts = importTime.Subtract(exportTime);

string listPath = ConfigurationManager.AppSettings[“MigratedListPath”].ToString();

//lock (thisLock)
//{

// File.AppendAllText(listPath, Environment.NewLine
// + sourceURL + “,”
// + targetURL + “,”
// + exportTimings + “,”
// + importTimings + “,”
// //+ siteSize + “,”
// + _GUID + “, Total Duration: “
// + ts.Hours.ToString() + “:” + ts.Minutes.ToString() + “:” + ts.Seconds.ToString());
//}

}
catch (Exception ex)
{
throw ex;
}
}

private void imp_Started(object sender, SPDeploymentEventArgs e)
{
if (e.RootObjects != null)
{

SPImport imp = (SPImport)sender;
ReparentImportObjects(e.RootObjects);
}
}

private void ReparentImportObjects(SPImportObjectCollection importObjects)
{
foreach (SPImportObject importObject in importObjects)
{
importObject.TargetParentUrl = tgList.RootFolder.ServerRelativeUrl;
}
}

private void OnObjectImported(object sender, SPObjectImportedEventArgs e)
{
if (e.Type == SPDeploymentObjectType.ListItem)
{
object obj = tgWeb.GetObject(e.SourceUrl);
if (obj is SPListItem)
{
SPListItem item = obj as SPListItem;
ReplaceBackLinks(item.BackwardLinks, tgWeb.Site, e.SourceUrl, e.TargetUrl);

if (chkDelSource.Checked)
{
item.Recycle(); //delete item from source list
}
}
}
}
private void ReplaceBackLinks(SPLinkCollection links, SPSite site, string source, string target)
{
if (links == null)
return;
int count = links.Count;
for (int i = count – 1; i >= 0; i–)
{
SPLink link = links[i];
using (SPWeb rweb = site.OpenWeb(link.ServerRelativeUrl, false))
{
object o = rweb.GetObject(link.ServerRelativeUrl);
if (o is SPFile)
{
SPFile f = o as SPFile;
f.ReplaceLink(source, target);
}
if (o is SPListItem)
{
SPListItem l = o as SPListItem;
l.ReplaceLink(source, target);
}
}
}
}

Advertisements

About jollsam

10 years of experience in SharePoint Development, Administration and Solution/Infrastructure Architecture.
This entry was posted in sharepoint. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s