I had a requirement to migrate some documents from specific libraries in SP2010 to SP2013 using WCF service.
SharePoint 2013:
FileMigrationService2013.SVC.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using Microsoft.SharePoint.Client.Services;
using System.ServiceModel.Activation;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy;
using System.IO;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.Collections;
using Microsoft.Office.DocumentManagement.DocumentSets;
using Microsoft.SharePoint.Utilities;
namespace FileMigrationWCFService2013
{
[BasicHttpBindingServiceMetadataExchangeEndpointAttribute]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class FileMigrationService2013 : IFileMigrationService
{
/// <summary>
/// Loop all sites and sub sites and show only document library templates
/// </summary>
/// <param name="webUrl"></param>
public Dictionary<string, List<string>> GetDocLibraries(string webUrl)
{
//collection contains web url and document library titles
Dictionary<string, List<string>> docLibs = new Dictionary<string, List<string>>();
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(webUrl))
{
//open the specified web
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
foreach (SPList list in web.Lists)
{
//show only document libaries
if (!list.Hidden && list.BaseTemplate == SPListTemplateType.DocumentLibrary)
{
//add web urls as key
string key = web.Url;
if (!docLibs.ContainsKey(key))
{
List<string> value = new List<string>();
//add document library title as value
value.Add(list.Title);
//Add key/value in Dictionary collection
docLibs.Add(key, value);
}
else
{
//if web url already exist, appent list title with value
List<string> value = docLibs[key];
//add document library title as value
value.Add(list.Title);
//Add key/value in Dictionary collection
docLibs[key] = value;
}
}
}
foreach (SPWeb childWeb in web.Webs)
{
//Call our own helper function for adding each child Web to the tree.
addWebs(childWeb, docLibs);
childWeb.Dispose();
}
}
}
});
return docLibs;
}
catch (Exception ex)
{
return docLibs;
}
}
/// <summary>
/// Recursive all sites and show document libraries in the tree view control
/// </summary>
/// <param name="web"></param>
/// <param name="parentNode"></param>
public void addWebs(SPWeb web, Dictionary<string, List<string>> sites)
{
try
{
foreach (SPList list in web.Lists)
{
//show only document libaries
if (!list.Hidden && list.BaseTemplate == SPListTemplateType.DocumentLibrary)
{
//add web urls as key
string key = web.Url;
if (!sites.ContainsKey(key))
{
List<string> value = new List<string>();
//add document library title as value
value.Add(list.Title);
//Add in Dictionary collection
sites.Add(key, value);
}
else
{
//if web url already exist, appent list title with value
List<string> value = sites[key];
//add document library title as value
value.Add(list.Title);
//Add in Dictionary collection
sites[key] = value;
}
}
}
foreach (SPWeb childWeb in web.Webs)
{
//Call the addWebs() function from itself (i.e. recursively)
//to add all child Webs until there are no more to add.
addWebs(childWeb, sites);
childWeb.Dispose();
}
}
catch
{ }
}
/// <summary>
/// get all document set content types in the selected document library
/// </summary>
/// <param name="webUrl"></param>
public List<string> GetDocumentSetNames(string webUrl, string docLibName)
{
//collection contains web url and document library titles
List<string> docSets = new List<string>();
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(webUrl))
{
//open the specified web
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
//get selected document library
SPDocumentLibrary docLib = web.Lists.TryGetList(docLibName) as SPDocumentLibrary;
if (docLib != null)
{
foreach (SPContentType contentType in docLib.ContentTypes)
{
if (contentType.Id.IsChildOf(SPBuiltInContentTypeId.DocumentSet))
{
docSets.Add(contentType.Name);
}
}
}
}
}
});
return docSets;
}
catch (Exception ex)
{
return docSets;
}
}
/// <summary>
/// convert to files to file stream
/// upload to document library
/// </summary>
/// <param name="path"></param>
/// <param name="Folder"></param>
/// <param name="strTerms"></param>
/// <param name="tagTermSet"></param>
/// <returns></returns>
public string CreateDocumentSet(string destWebUrl, string destDocLibName, string DocumentSetName, string userLoginName, string DocumentSetCTypeName, Dictionary<string, string> dicDestFieldValues)
{
string isDocSetCreated = string.Empty;
Dictionary<string, string> dicRemoveDocsetFieldValues = new Dictionary<string, string>();
try
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(destWebUrl))
{
//get selected web
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
//get selected document library
SPDocumentLibrary docLib = web.Lists.TryGetList(destDocLibName) as SPDocumentLibrary;
if (docLib != null)
{
//get the current user
SPUser currentUser = web.EnsureUser(userLoginName);
if (currentUser != null)
{
//get document set content type
SPContentType docsetCT = docLib.ContentTypes[DocumentSetCTypeName];
if (docsetCT != null)
{
//Extract DocumentSet fields from Documentset contenttype
if (dicDestFieldValues != null && dicDestFieldValues.Count > 0)
{
foreach (KeyValuePair<string, string> DocSetFields in dicDestFieldValues)
{
string fieldName = Convert.ToString(DocSetFields.Key);
if (!string.IsNullOrEmpty(fieldName))
{
if (!docsetCT.Fields.ContainsField(fieldName))
{
dicRemoveDocsetFieldValues.Add(DocSetFields.Key, DocSetFields.Value);
}
}
}
}
//remove other fields except document type content type
if (dicRemoveDocsetFieldValues != null && dicRemoveDocsetFieldValues.Count > 0)
{
foreach (var item in dicRemoveDocsetFieldValues)
{
//remove the key from dictionary collection
if (dicDestFieldValues.ContainsKey(Convert.ToString(item.Key)))
{
dicDestFieldValues.Remove(item.Key);
}
}
}
////set documentset properties
Hashtable properties = new Hashtable(dicDestFieldValues);
//if (dicDestFieldValues != null && dicDestFieldValues.Count > 0)
//{
// foreach (var dItem in dicDestFieldValues)
// {
// SPField destField = docLib.Fields.GetField(Convert.ToString(dItem.Key));
// if (destField != null && destField.Type == SPFieldType.DateTime)
// {
// //Update date time column
// properties[dItem.Key] = Convert.ToDateTime(dItem.Value);
// }
// }
//}
SPFolder parentFolder = docLib.RootFolder;
if (!IsDocumentSetExist(docLib, DocumentSetName))
{
//create a new document set
DocumentSet docSet = DocumentSet.Create(parentFolder, DocumentSetName, docsetCT.Id, properties, true, currentUser);
isDocSetCreated = "Success";
}
else
{
isDocSetCreated = "Success";
}
}
}
}
}
}
});
}
catch (Exception ex)
{
isDocSetCreated = ex.Message;
}
return isDocSetCreated;
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// check documentset is exists
/// </summary>
/// <param name="list"></param>
/// <param name="docSetName"></param>
/// <returns></returns>
private bool IsDocumentSetExist(SPDocumentLibrary list, string docSetName)
{
var folderUrl = SPUrlUtility.CombineUrl(list.RootFolder.ServerRelativeUrl, docSetName);
var folder = list.ParentWeb.GetFolder(folderUrl);
return folder.Exists;
}
/// <summary>
/// convert to files to file stream
/// upload into document library
/// </summary>
/// <param name="path"></param>
/// <param name="Folder"></param>
/// <param name="strTerms"></param>
/// <param name="tagTermSet"></param>
/// <returns></returns>
public string UploadFiletoDocLib(string destWebUrl, string destDocLibName, byte[] content, string fileName, string userLoginName, string DocSetName, Dictionary<string, string> dicDestFieldValues)
{
string isUploaded = string.Empty;
SPFile spfile = null;
try
{
//check if file stream content is null
if (content != null)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(destWebUrl))
{
//get selected web
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
//get selected document library
SPDocumentLibrary docLib = web.Lists.TryGetList(destDocLibName) as SPDocumentLibrary;
if (docLib != null)
{
//get the current user
SPUser currentUser = web.EnsureUser(userLoginName);
if (currentUser != null)
{
SPFolder DocSetFolder = web.Lists[destDocLibName].RootFolder.SubFolders[DocSetName];
if (DocSetFolder != null)
{
//set document properties
Hashtable docProperties = new Hashtable(dicDestFieldValues);
//upload document in the destination library
spfile = DocSetFolder.Files.Add(fileName, content, docProperties, currentUser, currentUser, DateTime.Now, DateTime.Now, true);
spfile.Update();
web.Update();
isUploaded = "Success_" + Convert.ToString(spfile.Item.ID);
}
else
{
isUploaded = DocSetName + " is not found";
}
}
}
}
}
});
}
catch (Exception ex)
{
isUploaded = ex.Message;
}
}
return isUploaded;
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// Update field values for the each document
/// </summary>
/// <param name="path"></param>
/// <param name="Folder"></param>
/// <param name="strTerms"></param>
/// <param name="tagTermSet"></param>
/// <returns></returns>
public string UpdateFieldValues(string destWebUrl, string destDocLibName, Dictionary<string, string> destFldValues, string strDocID, string docTypeFieldInternalName)
{
string isFldUpdated = string.Empty;
try
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(destWebUrl))
{
//get selected web
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
//get selected document library
SPDocumentLibrary docLib = web.Lists.TryGetList(destDocLibName) as SPDocumentLibrary;
if (docLib != null)
{
int docID = Convert.ToInt32(strDocID);
if (docID > 0)
{
SPListItem docItem = docLib.GetItemById(docID);
if (docItem != null)
{
if (destFldValues != null && destFldValues.Count > 0)
{
foreach (KeyValuePair<string, string> item in destFldValues)
{
string destColName = item.Key;
string destColValue = item.Value;
docItem[destColName] = destColValue;
docItem.SystemUpdate();
//update document type field
string fileName = docItem.File.Name;
if (!string.IsNullOrEmpty(fileName))
{
docItem[docTypeFieldInternalName] = GetDocumentType(fileName.ToLower());
docItem.SystemUpdate();
}
updateDocSetItem(destWebUrl, destDocLibName, docItem, destColName, destColValue);
isFldUpdated = "Success";
}
}
}
}
}
}
}
});
}
catch (Exception ex)
{
isFldUpdated = ex.Message;
}
return isFldUpdated;
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// get document type from file attachment
/// </summary>
/// <param name="path"></param>
/// <param name="Folder"></param>
/// <param name="strTerms"></param>
/// <param name="tagTermSet"></param>
/// <returns></returns>
public string GetDocumentType(string docName)
{
string docType = string.Empty;
try
{
try
{
if (docName.Contains(".msg"))
{
docType = "E-Mails";
}
else if (docName.Contains("calc"))
{
docType = "Calculation Sheet";
}
else if (docName.Contains("adr_"))
{
docType = "ADR Request Form";
}
else if (docName.Contains("bnb_"))
{
docType = "BNB Request Form";
}
else if (docName.Contains("_migration_"))
{
docType = "Workflow";
}
else
{
docType = "Others";
}
}
catch (Exception ex)
{
docType = ex.Message;
}
return docType;
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// Update document set properties
/// </summary>
/// <param name="item"></param>
/// <param name="destColName"></param>
/// <param name="destColValue"></param>
private void updateDocSetItem(string destWebUrl, string destDocLibName, SPListItem item, string destColName, string destColValue)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(destWebUrl))
{
//get selected web
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
//get selected document library
SPDocumentLibrary docLib = web.Lists.TryGetList(destDocLibName) as SPDocumentLibrary;
if (docLib != null)
{
DocumentSet documentSet = null;
if (null != item && null != item.File)
{
documentSet = DocumentSet.GetDocumentSet(item.File.ParentFolder);
if (null != documentSet)
{
SPListItem docSetItem = docLib.GetItemById(documentSet.Item.ID);
docSetItem[destColName] = destColValue;
docSetItem.SystemUpdate();
}
}
}
}
}
});
}
/// <summary>
/// check the current user has the appropriate permission to upload the new documents
/// </summary>
/// <param name="webUrl"></param>
/// <param name="docLibName"></param>
/// <param name="userLoginName"></param>
/// <returns></returns>
public string CheckUserPermission(string webUrl, string docLibName, string userLoginName)
{
string docPermission = string.Empty;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(webUrl))
{
//access the web
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
//get the selected document library
SPDocumentLibrary docLib = web.Lists.TryGetList(docLibName) as SPDocumentLibrary;
if (docLib != null)
{
//get the current user
SPUser currentUser = web.EnsureUser(userLoginName);
if (currentUser != null)
{
//check current user has 'AddListItems' permission in the document library
bool userPermission = docLib.DoesUserHavePermissions(currentUser, SPBasePermissions.AddListItems);
if (userPermission)
{
//return user has proper permission
docPermission = "Success";
}
else
{
//return user dont have enough permission
docPermission = "You dont have permission to upload the new documents!";
}
}
}
}
}
});
return docPermission;
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// upload workflow PDF document to document library
/// </summary>
/// <param name="path"></param>
/// <param name="Folder"></param>
/// <param name="strTerms"></param>
/// <param name="tagTermSet"></param>
/// <returns></returns>
public string UploadWFFiletoDocLib(string destWebUrl, string destDocLibName, byte[] WFContent, string fileName, string userLoginName, string DocSetName, string WFDocTypeFldName, string DocTypeFldValue)
{
string isUploaded = string.Empty;
SPFile spfile = null;
try
{
if (WFContent != null)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(destWebUrl))
{
//get selected web
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
//get selected document library
SPDocumentLibrary docLib = web.Lists.TryGetList(destDocLibName) as SPDocumentLibrary;
if (docLib != null)
{
//get the current user
SPUser currentUser = web.EnsureUser(userLoginName);
if (currentUser != null)
{
SPFolder DocSetFolder = web.Lists[destDocLibName].RootFolder.SubFolders[DocSetName];
if (DocSetFolder != null)
{
spfile = DocSetFolder.Files.Add(fileName, WFContent, null, currentUser, currentUser, DateTime.Now, DateTime.Now, true);
spfile.Update();
SPListItem WFDocItem = spfile.Item;
if (WFDocItem != null)
{
WFDocItem[WFDocTypeFldName] = DocTypeFldValue;
WFDocItem.Update();
}
web.Update();
}
else
{
isUploaded = DocSetName + " is not found";
}
isUploaded = "Success_" + Convert.ToString(spfile.Item.ID);
}
}
}
}
});
}
catch (Exception ex)
{
isUploaded = ex.Message;
}
}
return isUploaded;
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// Get document library url
/// </summary>
/// <param name="webUrl"></param>
/// <param name="docLibName"></param>
/// <returns></returns>
public string GetDocLibUrl(string webUrl, string docLibName)
{
string libUrl = string.Empty;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(webUrl))
{
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPDocumentLibrary docLib = web.Lists.TryGetList(docLibName) as SPDocumentLibrary;
if (docLib != null)
{
//show the document libarary url
libUrl = site.Url + docLib.DefaultViewUrl;
}
}
}
});
return libUrl;
}
catch (Exception ex)
{
libUrl = ex.Message;
return libUrl;
}
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;
using FileUploadTool.FileMigrationService2010;
using FileUploadTool.FileMigrationService2013;
namespace FileUploadTool
{
public partial class FileUpload : Form
{
StringBuilder sbErrorMsg = new StringBuilder();
public FileUpload()
{
InitializeComponent();
progressBar.Visible = false;
}
/// <summary>
/// populate source list titles in the treeview control
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnLibrary_Click(object sender, EventArgs e)
{
//clear existing nodes in treeview control
tvDocLibraries.Nodes.Clear();
try
{
if (!string.IsNullOrEmpty(txtSourceSiteUrl.Text.Trim()))
{
//create bindings and proxy
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
binding.MaxBufferPoolSize = Int32.MaxValue;
binding.MaxReceivedMessageSize = Int32.MaxValue;
binding.MaxBufferSize = Int32.MaxValue;
binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
binding.ReaderQuotas.MaxDepth = Int32.MaxValue;
binding.ReaderQuotas.MaxBytesPerRead = Int32.MaxValue;
binding.ReaderQuotas.MaxNameTableCharCount = Int32.MaxValue;
binding.ReaderQuotas.MaxArrayLength = Int32.MaxValue;
binding.SendTimeout = new TimeSpan(1, 10, 0);
binding.ReceiveTimeout = new TimeSpan(1, 10, 0);
//access Sharepoint 2010 site
EndpointAddress endpoint = new EndpointAddress(txtSourceSiteUrl.Text.Trim() + "/_vti_bin/FileMigrationWCFService2010/FileMigrationService2010.svc");
//proxy
FileUploadTool.FileMigrationService2010.FileMigrationServiceClient proxy = new FileUploadTool.FileMigrationService2010.FileMigrationServiceClient(binding, endpoint);
proxy.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
//get all subsites and document libraries under given url
Dictionary<string, string[]> dicLists = proxy.GetLists(txtSourceSiteUrl.Text.Trim());
if (dicLists != null && dicLists.Count > 0)
{
foreach (KeyValuePair<string, string[]> web in dicLists)
{
//Add the Web’s title as the parent node of the tree view control
TreeNode parentNode = new TreeNode();
parentNode.Text = web.Key;
tvDocLibraries.Nodes.Add(parentNode);
//Get a reference to the child node
foreach (string DocTitle in web.Value)
{
//Add the document library title as the child nodes of the tree view control
TreeNode childNode = new TreeNode();
childNode.Text = DocTitle;
childNode.ToolTipText = DocTitle;
parentNode.Nodes.Add(childNode);
}
}
}
else
{
//if no document libraries exists on the site
MessageBox.Show("No lists were found in the site");
}
}
else
{
MessageBox.Show("Please enter Source site url!");
}
}
catch (Exception ex)
{
//Exception
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// Populate source list name and web url in the controls after the list has selected
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void tvDocLibraries_AfterSelect(object sender, TreeViewEventArgs e)
{
try
{
//get selected treeview node
TreeNode selectedNode = tvDocLibraries.SelectedNode;
if (selectedNode != null && !string.IsNullOrEmpty(selectedNode.ToolTipText))
{
//get selected document library title
txtSourceListName.Text = selectedNode.Text;
//get selected web url
txtSourceWebUrl.Text = selectedNode.Parent.Text;
}
else
{
//clear selected document library title
txtSourceListName.Text = string.Empty;
//clear selected web url
txtSourceWebUrl.Text = string.Empty;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// populate destination list titles in the treeview control
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btndestLists_Click(object sender, EventArgs e)
{
//clear the existing destination libraries title
tvDestLibs.Nodes.Clear();
try
{
if (!string.IsNullOrEmpty(txtdestSiteUrl.Text.Trim()))
{
//create bindings and proxy
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
binding.MaxBufferPoolSize = Int32.MaxValue;
binding.MaxReceivedMessageSize = Int32.MaxValue;
binding.MaxBufferSize = Int32.MaxValue;
binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
binding.ReaderQuotas.MaxDepth = Int32.MaxValue;
binding.ReaderQuotas.MaxBytesPerRead = Int32.MaxValue;
binding.ReaderQuotas.MaxNameTableCharCount = Int32.MaxValue;
binding.ReaderQuotas.MaxArrayLength = Int32.MaxValue;
binding.SendTimeout = new TimeSpan(1, 10, 0);
binding.ReceiveTimeout = new TimeSpan(1, 10, 0);
//Access sharepoint 2013 site and document libraries
EndpointAddress endpoint = new EndpointAddress(txtdestSiteUrl.Text.Trim() + "/_vti_bin/FileMigrationWCFService2013/FileMigrationService2013.svc");
//proxy
FileUploadTool.FileMigrationService2013.FileMigrationServiceClient proxy = new FileUploadTool.FileMigrationService2013.FileMigrationServiceClient(binding, endpoint);
proxy.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
//get all subsites and document libraries based on the given url
Dictionary<string, string[]> DicLibraries = proxy.GetDocLibraries(txtdestSiteUrl.Text.Trim());
if (DicLibraries != null && DicLibraries.Count > 0)
{
foreach (KeyValuePair<string, string[]> web in DicLibraries)
{
//Add the Web’s title as the parent node of the tree view control
TreeNode parentNode = new TreeNode();
parentNode.Text = web.Key;
tvDestLibs.Nodes.Add(parentNode);
//Get a reference to the child node
foreach (string DocTitle in web.Value)
{
//Add the document library title as the child nodes of the tree view control
TreeNode childNode = new TreeNode();
childNode.Text = DocTitle;
childNode.ToolTipText = DocTitle;
parentNode.Nodes.Add(childNode);
}
}
}
else
{
//if no document libraries exists on the site
MessageBox.Show("No document libraries were found in the site");
}
}
else
{
MessageBox.Show("Please enter Destination site url!");
}
}
catch (Exception ex)
{
//exception
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// Populate destination list name,web url and document set name in the controls after the document library has selected
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void tvDestLibs_AfterSelect(object sender, TreeViewEventArgs e)
{
try
{
//create bindings and proxy
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
binding.MaxBufferPoolSize = Int32.MaxValue;
binding.MaxReceivedMessageSize = Int32.MaxValue;
binding.MaxBufferSize = Int32.MaxValue;
binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
binding.ReaderQuotas.MaxDepth = Int32.MaxValue;
binding.ReaderQuotas.MaxBytesPerRead = Int32.MaxValue;
binding.ReaderQuotas.MaxNameTableCharCount = Int32.MaxValue;
binding.ReaderQuotas.MaxArrayLength = Int32.MaxValue;
binding.SendTimeout = new TimeSpan(1, 10, 0);
binding.ReceiveTimeout = new TimeSpan(1, 10, 0);
//Access sharepoint2013 site
EndpointAddress endpoint = new EndpointAddress(txtdestSiteUrl.Text.Trim() + "/_vti_bin/FileMigrationWCFService2013/FileMigrationService2013.svc");
//proxy
FileUploadTool.FileMigrationService2013.FileMigrationServiceClient proxy = new FileUploadTool.FileMigrationService2013.FileMigrationServiceClient(binding, endpoint);
proxy.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
//get selected treeview node
TreeNode selectedNode = tvDestLibs.SelectedNode;
if (selectedNode != null && !string.IsNullOrEmpty(selectedNode.ToolTipText))
{
//get selected document library title
txtdestLibName.Text = selectedNode.Text;
//get selected web url
txtdestWebUrl.Text = selectedNode.Parent.Text;
//get all subsites and document libraries based on the given url
string[] DocSetNames = proxy.GetDocumentSetNames(txtdestWebUrl.Text.Trim(), txtdestLibName.Text.Trim());
if (DocSetNames != null && DocSetNames.Length > 0)
{
cbDestDocSetName.DataSource = DocSetNames;
}
else
{
//clear document set name
cbDestDocSetName.DataSource = null;
}
}
else
{
//clear selected document library title
txtdestLibName.Text = string.Empty;
//clear selected web url
txtdestWebUrl.Text = string.Empty;
cbDestDocSetName.DataSource = null;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// Upload the attachments from sharepoint2010 to sharepoint2013
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void UploadDoc_Click(object sender, EventArgs e)
{
try
{
//clear the existing error message
txtError.Text = string.Empty;
//clear the success message
lblImportMsg.Text = string.Empty;
//check controls validation
string validateMsg = ValidateControls();
if (validateMsg.Equals("ValidationSuccess"))
{
//create bindings and proxy
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
binding.MaxBufferPoolSize = Int32.MaxValue;
binding.MaxReceivedMessageSize = Int32.MaxValue;
binding.MaxBufferSize = Int32.MaxValue;
binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
binding.ReaderQuotas.MaxDepth = Int32.MaxValue;
binding.ReaderQuotas.MaxBytesPerRead = Int32.MaxValue;
binding.ReaderQuotas.MaxNameTableCharCount = Int32.MaxValue;
binding.ReaderQuotas.MaxArrayLength = Int32.MaxValue;
binding.SendTimeout = new TimeSpan(1, 10, 0);
binding.ReceiveTimeout = new TimeSpan(1, 10, 0);
//access Sharepoint2010 site
EndpointAddress endpoint = new EndpointAddress(txtSourceWebUrl.Text.Trim() + "/_vti_bin/FileMigrationWCFService2010/FileMigrationService2010.svc");
//proxy
FileUploadTool.FileMigrationService2010.FileMigrationServiceClient proxy = new FileUploadTool.FileMigrationService2010.FileMigrationServiceClient(binding, endpoint);
proxy.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
//get current user windows identity
System.Security.Principal.WindowsIdentity wiName = System.Security.Principal.WindowsIdentity.GetCurrent();
//check the current user has the appropriate permission in the document library to upload the documents in the destination folder
string isUserPermission = proxy.CheckUserPermission(txtdestWebUrl.Text.Trim(), txtdestLibName.Text.Trim(), wiName.Name);
if (isUserPermission.Equals("Success"))
{
//check 'MigrationStatus' field has exists either will create a new field
string isMigrationStatusFldCreated = proxy.CreateMigrationStatusField(txtSourceWebUrl.Text.Trim(), txtSourceListName.Text.Trim());
if (isMigrationStatusFldCreated.Equals("Success"))
{
//get all source list items and attachments
string[] soureceItemIds = proxy.GetSourceListItems(txtSourceWebUrl.Text.Trim(), txtSourceListName.Text.Trim());
if (soureceItemIds != null && soureceItemIds.Length > 0)
{
Dictionary<string, string> dicMappedFields = proxy.GetMappedFieldItems(txtSourceWebUrl.Text.Trim(), "FieldMappingList", txtSourceListName.Text.Trim());
if (dicMappedFields != null && dicMappedFields.Count > 0)
{
string documentTypeFld = Convert.ToString(dicMappedFields["DocumentType"]);
//remove document type key
//if (dicMappedFields.ContainsKey("DocumentType"))
//{
// dicMappedFields.Remove("DocumentType");
//}
progressBar.Visible = true;
// Set Minimum to 1 to represent the first file being copied.
progressBar.Minimum = 1;
// Set Maximum to the total number of Users created.
progressBar.Maximum = soureceItemIds.Length;
// Set the initial value of the ProgressBar.
progressBar.Value = 1;
// Set the Step property to a value of 1 to represent each user is being created.
progressBar.Step = 1;
int uploadedDocCount = 0;
foreach (string sourceItemID in soureceItemIds)
{
//if (Convert.ToInt32(sourceItemID) >= 1 && Convert.ToInt32(sourceItemID) <= 50)
{
//upload each attachment from splistitem into destination document library
string isUploaded = proxy.MigrateDocs(txtSourceWebUrl.Text.Trim(), txtSourceListName.Text.Trim(), txtdestWebUrl.Text.Trim(), txtdestLibName.Text.Trim(), Convert.ToString(cbDestDocSetName.SelectedValue), wiName.Name, sourceItemID, dicMappedFields, documentTypeFld);
// Copy the file and increment the ProgressBar if successful.
if (isUploaded.Equals("Success"))
{
lblImportMsg.Text = "Total " + Convert.ToString(uploadedDocCount) + " out of " + Convert.ToString(soureceItemIds.Length) + " is migrating....";
lblImportMsg.Refresh();
// Perform the increment on the ProgressBar.
progressBar.PerformStep();
uploadedDocCount++;
}
else
{
//catch the error message
Errorlbl.Visible = true;
sbErrorMsg.AppendLine(isUploaded + Environment.NewLine);
sbErrorMsg.AppendLine("----------------------------------------------------------");
txtError.Visible = true;
txtError.ForeColor = System.Drawing.Color.Red;
sbErrorMsg.Append("Source Item ID - " + sourceItemID);
sbErrorMsg.Append(Environment.NewLine);
txtError.Text = Convert.ToString(sbErrorMsg);
txtError.Refresh();
sbErrorMsg.AppendLine("----------------------------------------------------------");
}
}
}
//success message
lblImportMsg.Text = "Total " + Convert.ToString(uploadedDocCount) + " Documents Uploaded Successfully!";
lblImportMsg.Refresh();
lblImportMsg.ForeColor = System.Drawing.Color.Red;
// Set the document library in the LinkLabel.
//linkLabel.Links.Clear();
//linkLabel.Text = txtdestLibName.Text.Trim();
//string url = proxy.GetDocLibUrl(txtdestWebUrl.Text.Trim(), txtdestLibName.Text.Trim());
//linkLabel.Links.Add(0, 25, url);
}
else
{
MessageBox.Show("Field Mapping items are not available!");
}
}
else
{
MessageBox.Show("Source items are not available!");
}
}
else
{
MessageBox.Show(isMigrationStatusFldCreated);
}
}
else
{
MessageBox.Show(isUserPermission);
}
}
else
{
MessageBox.Show(validateMsg);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// Validation
/// </summary>
/// <returns></returns>
private string ValidateControls()
{
string validateMsg = string.Empty;
try
{
if (string.IsNullOrEmpty(txtSourceSiteUrl.Text.Trim()))
{
validateMsg = "Please enter Source site url!";
txtSourceSiteUrl.Focus();
}
else if (string.IsNullOrEmpty(txtSourceWebUrl.Text.Trim()))
{
validateMsg = "Source web url should not empty!";
txtSourceWebUrl.Focus();
}
else if (string.IsNullOrEmpty(txtSourceListName.Text.Trim()))
{
validateMsg = "Please select a Source list!";
txtSourceListName.Focus();
}
else if (string.IsNullOrEmpty(txtdestSiteUrl.Text.Trim()))
{
validateMsg = "Please enter Destination site url!";
txtdestSiteUrl.Focus();
}
else if (string.IsNullOrEmpty(txtdestWebUrl.Text.Trim()))
{
validateMsg = "Destination web url should not empty!";
txtdestWebUrl.Focus();
}
else if (string.IsNullOrEmpty(Convert.ToString(cbDestDocSetName.SelectedValue)))
{
validateMsg = "Please select a DocumentSet!";
cbDestDocSetName.Focus();
}
else if (string.IsNullOrEmpty(Convert.ToString(txtdestLibName.Text.Trim())))
{
validateMsg = "Please select a Destination list!";
txtdestLibName.Focus();
}
else
{
validateMsg = "ValidationSuccess";
}
return validateMsg;
}
catch (Exception ex)
{
return validateMsg;
}
}
}
}
SharePoint 2013:
FileMigrationService2013.SVC.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using Microsoft.SharePoint.Client.Services;
using System.ServiceModel.Activation;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy;
using System.IO;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.Collections;
using Microsoft.Office.DocumentManagement.DocumentSets;
using Microsoft.SharePoint.Utilities;
namespace FileMigrationWCFService2013
{
[BasicHttpBindingServiceMetadataExchangeEndpointAttribute]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class FileMigrationService2013 : IFileMigrationService
{
/// <summary>
/// Loop all sites and sub sites and show only document library templates
/// </summary>
/// <param name="webUrl"></param>
public Dictionary<string, List<string>> GetDocLibraries(string webUrl)
{
//collection contains web url and document library titles
Dictionary<string, List<string>> docLibs = new Dictionary<string, List<string>>();
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(webUrl))
{
//open the specified web
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
foreach (SPList list in web.Lists)
{
//show only document libaries
if (!list.Hidden && list.BaseTemplate == SPListTemplateType.DocumentLibrary)
{
//add web urls as key
string key = web.Url;
if (!docLibs.ContainsKey(key))
{
List<string> value = new List<string>();
//add document library title as value
value.Add(list.Title);
//Add key/value in Dictionary collection
docLibs.Add(key, value);
}
else
{
//if web url already exist, appent list title with value
List<string> value = docLibs[key];
//add document library title as value
value.Add(list.Title);
//Add key/value in Dictionary collection
docLibs[key] = value;
}
}
}
foreach (SPWeb childWeb in web.Webs)
{
//Call our own helper function for adding each child Web to the tree.
addWebs(childWeb, docLibs);
childWeb.Dispose();
}
}
}
});
return docLibs;
}
catch (Exception ex)
{
return docLibs;
}
}
/// <summary>
/// Recursive all sites and show document libraries in the tree view control
/// </summary>
/// <param name="web"></param>
/// <param name="parentNode"></param>
public void addWebs(SPWeb web, Dictionary<string, List<string>> sites)
{
try
{
foreach (SPList list in web.Lists)
{
//show only document libaries
if (!list.Hidden && list.BaseTemplate == SPListTemplateType.DocumentLibrary)
{
//add web urls as key
string key = web.Url;
if (!sites.ContainsKey(key))
{
List<string> value = new List<string>();
//add document library title as value
value.Add(list.Title);
//Add in Dictionary collection
sites.Add(key, value);
}
else
{
//if web url already exist, appent list title with value
List<string> value = sites[key];
//add document library title as value
value.Add(list.Title);
//Add in Dictionary collection
sites[key] = value;
}
}
}
foreach (SPWeb childWeb in web.Webs)
{
//Call the addWebs() function from itself (i.e. recursively)
//to add all child Webs until there are no more to add.
addWebs(childWeb, sites);
childWeb.Dispose();
}
}
catch
{ }
}
/// <summary>
/// get all document set content types in the selected document library
/// </summary>
/// <param name="webUrl"></param>
public List<string> GetDocumentSetNames(string webUrl, string docLibName)
{
//collection contains web url and document library titles
List<string> docSets = new List<string>();
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(webUrl))
{
//open the specified web
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
//get selected document library
SPDocumentLibrary docLib = web.Lists.TryGetList(docLibName) as SPDocumentLibrary;
if (docLib != null)
{
foreach (SPContentType contentType in docLib.ContentTypes)
{
if (contentType.Id.IsChildOf(SPBuiltInContentTypeId.DocumentSet))
{
docSets.Add(contentType.Name);
}
}
}
}
}
});
return docSets;
}
catch (Exception ex)
{
return docSets;
}
}
/// <summary>
/// convert to files to file stream
/// upload to document library
/// </summary>
/// <param name="path"></param>
/// <param name="Folder"></param>
/// <param name="strTerms"></param>
/// <param name="tagTermSet"></param>
/// <returns></returns>
public string CreateDocumentSet(string destWebUrl, string destDocLibName, string DocumentSetName, string userLoginName, string DocumentSetCTypeName, Dictionary<string, string> dicDestFieldValues)
{
string isDocSetCreated = string.Empty;
Dictionary<string, string> dicRemoveDocsetFieldValues = new Dictionary<string, string>();
try
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(destWebUrl))
{
//get selected web
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
//get selected document library
SPDocumentLibrary docLib = web.Lists.TryGetList(destDocLibName) as SPDocumentLibrary;
if (docLib != null)
{
//get the current user
SPUser currentUser = web.EnsureUser(userLoginName);
if (currentUser != null)
{
//get document set content type
SPContentType docsetCT = docLib.ContentTypes[DocumentSetCTypeName];
if (docsetCT != null)
{
//Extract DocumentSet fields from Documentset contenttype
if (dicDestFieldValues != null && dicDestFieldValues.Count > 0)
{
foreach (KeyValuePair<string, string> DocSetFields in dicDestFieldValues)
{
string fieldName = Convert.ToString(DocSetFields.Key);
if (!string.IsNullOrEmpty(fieldName))
{
if (!docsetCT.Fields.ContainsField(fieldName))
{
dicRemoveDocsetFieldValues.Add(DocSetFields.Key, DocSetFields.Value);
}
}
}
}
//remove other fields except document type content type
if (dicRemoveDocsetFieldValues != null && dicRemoveDocsetFieldValues.Count > 0)
{
foreach (var item in dicRemoveDocsetFieldValues)
{
//remove the key from dictionary collection
if (dicDestFieldValues.ContainsKey(Convert.ToString(item.Key)))
{
dicDestFieldValues.Remove(item.Key);
}
}
}
////set documentset properties
Hashtable properties = new Hashtable(dicDestFieldValues);
//if (dicDestFieldValues != null && dicDestFieldValues.Count > 0)
//{
// foreach (var dItem in dicDestFieldValues)
// {
// SPField destField = docLib.Fields.GetField(Convert.ToString(dItem.Key));
// if (destField != null && destField.Type == SPFieldType.DateTime)
// {
// //Update date time column
// properties[dItem.Key] = Convert.ToDateTime(dItem.Value);
// }
// }
//}
SPFolder parentFolder = docLib.RootFolder;
if (!IsDocumentSetExist(docLib, DocumentSetName))
{
//create a new document set
DocumentSet docSet = DocumentSet.Create(parentFolder, DocumentSetName, docsetCT.Id, properties, true, currentUser);
isDocSetCreated = "Success";
}
else
{
isDocSetCreated = "Success";
}
}
}
}
}
}
});
}
catch (Exception ex)
{
isDocSetCreated = ex.Message;
}
return isDocSetCreated;
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// check documentset is exists
/// </summary>
/// <param name="list"></param>
/// <param name="docSetName"></param>
/// <returns></returns>
private bool IsDocumentSetExist(SPDocumentLibrary list, string docSetName)
{
var folderUrl = SPUrlUtility.CombineUrl(list.RootFolder.ServerRelativeUrl, docSetName);
var folder = list.ParentWeb.GetFolder(folderUrl);
return folder.Exists;
}
/// <summary>
/// convert to files to file stream
/// upload into document library
/// </summary>
/// <param name="path"></param>
/// <param name="Folder"></param>
/// <param name="strTerms"></param>
/// <param name="tagTermSet"></param>
/// <returns></returns>
public string UploadFiletoDocLib(string destWebUrl, string destDocLibName, byte[] content, string fileName, string userLoginName, string DocSetName, Dictionary<string, string> dicDestFieldValues)
{
string isUploaded = string.Empty;
SPFile spfile = null;
try
{
//check if file stream content is null
if (content != null)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(destWebUrl))
{
//get selected web
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
//get selected document library
SPDocumentLibrary docLib = web.Lists.TryGetList(destDocLibName) as SPDocumentLibrary;
if (docLib != null)
{
//get the current user
SPUser currentUser = web.EnsureUser(userLoginName);
if (currentUser != null)
{
SPFolder DocSetFolder = web.Lists[destDocLibName].RootFolder.SubFolders[DocSetName];
if (DocSetFolder != null)
{
//set document properties
Hashtable docProperties = new Hashtable(dicDestFieldValues);
//upload document in the destination library
spfile = DocSetFolder.Files.Add(fileName, content, docProperties, currentUser, currentUser, DateTime.Now, DateTime.Now, true);
spfile.Update();
web.Update();
isUploaded = "Success_" + Convert.ToString(spfile.Item.ID);
}
else
{
isUploaded = DocSetName + " is not found";
}
}
}
}
}
});
}
catch (Exception ex)
{
isUploaded = ex.Message;
}
}
return isUploaded;
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// Update field values for the each document
/// </summary>
/// <param name="path"></param>
/// <param name="Folder"></param>
/// <param name="strTerms"></param>
/// <param name="tagTermSet"></param>
/// <returns></returns>
public string UpdateFieldValues(string destWebUrl, string destDocLibName, Dictionary<string, string> destFldValues, string strDocID, string docTypeFieldInternalName)
{
string isFldUpdated = string.Empty;
try
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(destWebUrl))
{
//get selected web
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
//get selected document library
SPDocumentLibrary docLib = web.Lists.TryGetList(destDocLibName) as SPDocumentLibrary;
if (docLib != null)
{
int docID = Convert.ToInt32(strDocID);
if (docID > 0)
{
SPListItem docItem = docLib.GetItemById(docID);
if (docItem != null)
{
if (destFldValues != null && destFldValues.Count > 0)
{
foreach (KeyValuePair<string, string> item in destFldValues)
{
string destColName = item.Key;
string destColValue = item.Value;
docItem[destColName] = destColValue;
docItem.SystemUpdate();
//update document type field
string fileName = docItem.File.Name;
if (!string.IsNullOrEmpty(fileName))
{
docItem[docTypeFieldInternalName] = GetDocumentType(fileName.ToLower());
docItem.SystemUpdate();
}
updateDocSetItem(destWebUrl, destDocLibName, docItem, destColName, destColValue);
isFldUpdated = "Success";
}
}
}
}
}
}
}
});
}
catch (Exception ex)
{
isFldUpdated = ex.Message;
}
return isFldUpdated;
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// get document type from file attachment
/// </summary>
/// <param name="path"></param>
/// <param name="Folder"></param>
/// <param name="strTerms"></param>
/// <param name="tagTermSet"></param>
/// <returns></returns>
public string GetDocumentType(string docName)
{
string docType = string.Empty;
try
{
try
{
if (docName.Contains(".msg"))
{
docType = "E-Mails";
}
else if (docName.Contains("calc"))
{
docType = "Calculation Sheet";
}
else if (docName.Contains("adr_"))
{
docType = "ADR Request Form";
}
else if (docName.Contains("bnb_"))
{
docType = "BNB Request Form";
}
else if (docName.Contains("_migration_"))
{
docType = "Workflow";
}
else
{
docType = "Others";
}
}
catch (Exception ex)
{
docType = ex.Message;
}
return docType;
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// Update document set properties
/// </summary>
/// <param name="item"></param>
/// <param name="destColName"></param>
/// <param name="destColValue"></param>
private void updateDocSetItem(string destWebUrl, string destDocLibName, SPListItem item, string destColName, string destColValue)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(destWebUrl))
{
//get selected web
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
//get selected document library
SPDocumentLibrary docLib = web.Lists.TryGetList(destDocLibName) as SPDocumentLibrary;
if (docLib != null)
{
DocumentSet documentSet = null;
if (null != item && null != item.File)
{
documentSet = DocumentSet.GetDocumentSet(item.File.ParentFolder);
if (null != documentSet)
{
SPListItem docSetItem = docLib.GetItemById(documentSet.Item.ID);
docSetItem[destColName] = destColValue;
docSetItem.SystemUpdate();
}
}
}
}
}
});
}
/// <summary>
/// check the current user has the appropriate permission to upload the new documents
/// </summary>
/// <param name="webUrl"></param>
/// <param name="docLibName"></param>
/// <param name="userLoginName"></param>
/// <returns></returns>
public string CheckUserPermission(string webUrl, string docLibName, string userLoginName)
{
string docPermission = string.Empty;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(webUrl))
{
//access the web
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
//get the selected document library
SPDocumentLibrary docLib = web.Lists.TryGetList(docLibName) as SPDocumentLibrary;
if (docLib != null)
{
//get the current user
SPUser currentUser = web.EnsureUser(userLoginName);
if (currentUser != null)
{
//check current user has 'AddListItems' permission in the document library
bool userPermission = docLib.DoesUserHavePermissions(currentUser, SPBasePermissions.AddListItems);
if (userPermission)
{
//return user has proper permission
docPermission = "Success";
}
else
{
//return user dont have enough permission
docPermission = "You dont have permission to upload the new documents!";
}
}
}
}
}
});
return docPermission;
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// upload workflow PDF document to document library
/// </summary>
/// <param name="path"></param>
/// <param name="Folder"></param>
/// <param name="strTerms"></param>
/// <param name="tagTermSet"></param>
/// <returns></returns>
public string UploadWFFiletoDocLib(string destWebUrl, string destDocLibName, byte[] WFContent, string fileName, string userLoginName, string DocSetName, string WFDocTypeFldName, string DocTypeFldValue)
{
string isUploaded = string.Empty;
SPFile spfile = null;
try
{
if (WFContent != null)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(destWebUrl))
{
//get selected web
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
//get selected document library
SPDocumentLibrary docLib = web.Lists.TryGetList(destDocLibName) as SPDocumentLibrary;
if (docLib != null)
{
//get the current user
SPUser currentUser = web.EnsureUser(userLoginName);
if (currentUser != null)
{
SPFolder DocSetFolder = web.Lists[destDocLibName].RootFolder.SubFolders[DocSetName];
if (DocSetFolder != null)
{
spfile = DocSetFolder.Files.Add(fileName, WFContent, null, currentUser, currentUser, DateTime.Now, DateTime.Now, true);
spfile.Update();
SPListItem WFDocItem = spfile.Item;
if (WFDocItem != null)
{
WFDocItem[WFDocTypeFldName] = DocTypeFldValue;
WFDocItem.Update();
}
web.Update();
}
else
{
isUploaded = DocSetName + " is not found";
}
isUploaded = "Success_" + Convert.ToString(spfile.Item.ID);
}
}
}
}
});
}
catch (Exception ex)
{
isUploaded = ex.Message;
}
}
return isUploaded;
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// Get document library url
/// </summary>
/// <param name="webUrl"></param>
/// <param name="docLibName"></param>
/// <returns></returns>
public string GetDocLibUrl(string webUrl, string docLibName)
{
string libUrl = string.Empty;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(webUrl))
{
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPDocumentLibrary docLib = web.Lists.TryGetList(docLibName) as SPDocumentLibrary;
if (docLib != null)
{
//show the document libarary url
libUrl = site.Url + docLib.DefaultViewUrl;
}
}
}
});
return libUrl;
}
catch (Exception ex)
{
libUrl = ex.Message;
return libUrl;
}
}
}
}
Interface IFileMigrationService:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;
using Microsoft.SharePoint;
using System.Security.Principal;
namespace FileMigrationWCFService2013
{
[ServiceContract]
public interface IFileMigrationService
{
[OperationContract]
Dictionary<string, List<string>> GetDocLibraries(string webUrl);
[OperationContract]
List<string> GetDocumentSetNames(string webUrl, string docLibName);
[OperationContract]
string UploadFiletoDocLib(string destWebUrl, string destDocLibName, byte[] content, string fileName, string userLoginName, string DocSetName, Dictionary<string, string> dicDestFieldValues);
[OperationContract]
string CreateDocumentSet(string destWebUrl, string destDocLibName, string DocumentSetName, string userLoginName, string DocumentSetCTypeName, Dictionary<string, string> dicDestFieldValues);
[OperationContract]
string CheckUserPermission(string webUrl, string docLibName, string userLoginName);
[OperationContract]
string UploadWFFiletoDocLib(string destWebUrl, string destDocLibName, byte[] WFContent, string fileName, string userLoginName, string DocSetName, string WFDocTypeFldName, string DocTypeFldValue);
[OperationContract]
string GetDocLibUrl(string webUrl, string docLibName);
}
}
Here I faced the issue to migrate the huge size documents i resolved this by creating my own factory class to increase MaxReceivedMessageSize.
MyFactory.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using Microsoft.SharePoint.Client.Services;
using System.Diagnostics;
namespace FileMigrationWCFService2013
{
public class MyFactory : MultipleBaseAddressBasicHttpBindingServiceHostFactory
{
protected override ServiceHost CreateServiceHost(Type serviceType,
Uri[] baseAddresses)
{
ServiceHost host = new MultipleBaseAddressBasicHttpBindingServiceHost(
serviceType, baseAddresses);
if (host != null)
{
host.Opening += new EventHandler(OnHost_Opening);
}
return host;
}
private void OnHost_Opening(object sender, EventArgs e)
{
Debug.Assert(sender != null);
ServiceHost host = sender as ServiceHost;
Debug.Assert(host != null);
// Configure the binding values
if (host.Description != null && host.Description.Endpoints != null)
{
foreach (var endPoint in host.Description.Endpoints)
{
if (endPoint != null && endPoint.Binding != null)
{
BasicHttpBinding basicBinding = endPoint.Binding
as BasicHttpBinding;
if (basicBinding != null)
{
ConfigureBasicHttpBinding(basicBinding);
}
}
}
}
}
private static void ConfigureBasicHttpBinding(BasicHttpBinding basicBinding)
{
Debug.Assert(basicBinding != null);
basicBinding.MaxBufferPoolSize = Int32.MaxValue;
basicBinding.MaxReceivedMessageSize = Int32.MaxValue;
basicBinding.MaxBufferSize = Int32.MaxValue;
basicBinding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
basicBinding.ReaderQuotas.MaxDepth = Int32.MaxValue;
basicBinding.ReaderQuotas.MaxBytesPerRead = Int32.MaxValue;
basicBinding.ReaderQuotas.MaxNameTableCharCount = Int32.MaxValue;
basicBinding.ReaderQuotas.MaxArrayLength = Int32.MaxValue;
basicBinding.SendTimeout = new TimeSpan(1, 10, 0);
basicBinding.ReceiveTimeout = new TimeSpan(1, 10, 0);
}
}
}
Register our custom MyFactory.cs in FileMigrationService2013.svc file under ISAPI folder.
FileMigrationService2013.svc
<%@ ServiceHost Language="C#" Debug="true" Service="FileMigrationWCFService2013.FileMigrationService2013, FileMigrationWCFService2013, Version=1.0.0.0, Culture=neutral, PublicKeyToken=46c6e96a52caea5b"
CodeBehind="FileMigrationService2013.svc.cs" Factory="FileMigrationWCFService2013.MyFactory, FileMigrationWCFService2013, Version=1.0.0.0, Culture=neutral, PublicKeyToken=46c6e96a52caea5b" %>
SharePoint 2010:
FileMigrationWCFService2010.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using Microsoft.SharePoint.Client.Services;
using System.ServiceModel.Activation;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy;
using System.IO;
using System.Security.Principal;
using System.Runtime.InteropServices;
using Microsoft.SharePoint.Workflow;
using System.Collections;
using Microsoft.SharePoint.Utilities;
namespace FileMigrationWCFService2010
{
[BasicHttpBindingServiceMetadataExchangeEndpointAttribute]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class FileMigrationService2010 : IFileMigrationService
{
/// <summary>
/// Loop all sites and sub sites and show only document library templates
/// </summary>
/// <param name="webUrl"></param>
public Dictionary<string, List<string>> GetLists(string webUrl)
{
//collection contains web url and document library titles
Dictionary<string, List<string>> lists = new Dictionary<string, List<string>>();
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(webUrl))
{
//open the specified web
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
foreach (SPList list in web.Lists)
{
//show only document libaries
if (!list.Hidden && list.BaseTemplate == SPListTemplateType.GenericList)
{
//add web urls as key
string key = web.Url;
if (!lists.ContainsKey(key))
{
List<string> value = new List<string>();
//add document library title as value
value.Add(list.Title);
//Add key/value in Dictionary collection
lists.Add(key, value);
}
else
{
//if web url already exist, appent list title with value
List<string> value = lists[key];
//add document library title as value
value.Add(list.Title);
//Add key/value in Dictionary collection
lists[key] = value;
}
}
}
foreach (SPWeb childWeb in web.Webs)
{
//Call our own helper function for adding each child Web to the tree.
addWebs(childWeb, lists);
childWeb.Dispose();
}
}
}
});
return lists;
}
catch
{
return lists;
}
}
/// <summary>
/// Recursive all sites and show document libraries in the tree view control
/// </summary>
/// <param name="web"></param>
/// <param name="parentNode"></param>
public void addWebs(SPWeb web, Dictionary<string, List<string>> sites)
{
try
{
foreach (SPList list in web.Lists)
{
//show only document libaries
if (!list.Hidden && list.BaseTemplate == SPListTemplateType.GenericList)
{
//add web urls as key
string key = web.Url;
if (!sites.ContainsKey(key))
{
List<string> value = new List<string>();
//add document library title as value
value.Add(list.Title);
//Add in Dictionary collection
sites.Add(key, value);
}
else
{
//if web url already exist, appent list title with value
List<string> value = sites[key];
//add document library title as value
value.Add(list.Title);
//Add in Dictionary collection
sites[key] = value;
}
}
}
foreach (SPWeb childWeb in web.Webs)
{
//Call the addWebs() function from itself (i.e. recursively)
//to add all child Webs until there are no more to add.
addWebs(childWeb, sites);
childWeb.Dispose();
}
}
catch
{ }
}
/// <summary>
/// get all source migrated items and attachments
/// </summary>
/// <param name="sourceWebUrl"></param>
/// <param name="sourceListName"></param>
/// <param name="destWebUrl"></param>
/// <param name="destDocLibName"></param>
/// <param name="docSetCTypeName"></param>
/// <param name="LogonUser"></param>
/// <returns></returns>
public List<string> GetSourceListItems(string sourceWebUrl, string sourceListName)
{
List<string> sourceItemIDs = new List<string>();
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(sourceWebUrl))
{
//open the specified web
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
//get source list
SPList sourceList = web.Lists.TryGetList(sourceListName) as SPList;
if (sourceList != null)
{
//Make spquery
SPQuery sourceQuery = new SPQuery();
sourceQuery.Query = "<Where><Neq><FieldRef Name='MigrationStatus'/><Value Type='Boolean'>1</Value></Neq></Where>";
SPListItemCollection sourceListColl = sourceList.GetItems(sourceQuery);
SPWorkflowManager manager = site.WorkflowManager;
foreach (SPListItem sourceItem in sourceListColl)
{
//get all running workflows associated with each splistitem
SPWorkflowCollection runningWFCol = manager.GetItemActiveWorkflows(sourceItem);
//add the source item if any workflows are not running with that item
if (runningWFCol.Count == 0)
{
sourceItemIDs.Add(sourceItem.ID.ToString());
}
}
}
}
}
});
return sourceItemIDs;
}
catch (Exception ex)
{
return sourceItemIDs;
}
}
/// <summary>
/// creating a new document set and Migrate list attachments into document library
/// </summary>
/// <param name="webUrl"></param>
public string MigrateDocs(string sourceWebUrl, string sourceListName, string destWebUrl, string destDocLibName, string docSetCTypeName, string LogonUser, string SourceItemID, Dictionary<string, string> dicMappedFields, string docTypeFieldInternalName)
{
string successMsg = string.Empty;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(sourceWebUrl))
{
//open the specified web
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
//get field mapping list contains Source and Destination field internal names
SPList FieldMappingList = site.RootWeb.Lists.TryGetList("FieldMappingList") as SPList;
if (FieldMappingList != null)
{
//get source list
SPList sourceList = web.Lists.TryGetList(sourceListName) as SPList;
if (sourceList != null)
{
SPListItem sourceItem = sourceList.GetItemById(Convert.ToInt32(SourceItemID));
if (sourceItem != null)
{
//create bindings and proxy
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
binding.MaxBufferPoolSize = Int32.MaxValue;
binding.MaxReceivedMessageSize = Int32.MaxValue;
binding.MaxBufferSize = Int32.MaxValue;
binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
binding.ReaderQuotas.MaxDepth = Int32.MaxValue;
binding.ReaderQuotas.MaxBytesPerRead = Int32.MaxValue;
binding.ReaderQuotas.MaxNameTableCharCount = Int32.MaxValue;
binding.ReaderQuotas.MaxArrayLength = Int32.MaxValue;
binding.SendTimeout = new TimeSpan(1, 10, 0);
binding.ReceiveTimeout = new TimeSpan(1, 10, 0);
//get sharepoint2013 site
EndpointAddress endpoint = new EndpointAddress(destWebUrl + "/_vti_bin/FileMigrationWCFService2013/FileMigrationService2013.svc");
//proxy
FileMigrationWCFService2010.FileMigrationService2013.FileMigrationServiceClient proxy = new FileMigrationWCFService2010.FileMigrationService2013.FileMigrationServiceClient(binding, endpoint);
proxy.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
//check source item contains attachment field
if (sourceItem.Fields.ContainsField("Attachments"))
{
string isDocSetCreated = string.Empty;
string DocSetName = string.Empty;
string docTypeInternalName = string.Empty;
StringBuilder sbFieldValues = new StringBuilder();
//dictionary contains destination field internal names and their corresponding values
Dictionary<string, string> dicDestFieldValues = new Dictionary<string, string>();
if (dicMappedFields != null && dicMappedFields.Count > 0)
{
foreach (KeyValuePair<string, string> MappedItem in dicMappedFields)
{
if (Convert.ToString(MappedItem.Key) == "ADR_Number" || Convert.ToString(MappedItem.Key) == "BNB_Number")
{
string sourceItemValue = Convert.ToString(sourceItem[MappedItem.Key]);
if (!string.IsNullOrEmpty(sourceItemValue) && sourceItemValue.Contains('_'))
{
sourceItemValue = sourceItemValue.Split('_').Last();
if (!string.IsNullOrEmpty(sourceItemValue))
{
int iProjVersion = Convert.ToInt32(sourceItemValue);
dicDestFieldValues.Add("ProjectVersion", Convert.ToString(iProjVersion));
}
}
}
if (Convert.ToString(MappedItem.Key) == "DocumentType")
{
//dicMappedFields[MappedItem.Key] will be the "Document Type" field internal name in the destination list
dicDestFieldValues.Add(dicMappedFields[MappedItem.Key], "");
docTypeInternalName = Convert.ToString(dicMappedFields[MappedItem.Key]);
}
else
{
string sourceItemValue = Convert.ToString(sourceItem[MappedItem.Key]);
SPField sourceFld = sourceItem.Fields.GetField(Convert.ToString(MappedItem.Key));
if (sourceFld != null)
{
if (sourceFld.Type == SPFieldType.Note)
{
SPFieldMultiLineText field = (SPFieldMultiLineText)sourceItem.Fields[MappedItem.Key];
sourceItemValue = field.GetFieldValueAsText(Convert.ToString(sourceItem[MappedItem.Key]));
}
if (sourceFld.Type == SPFieldType.Number)
{
if (!string.IsNullOrEmpty(sourceItemValue))
{
sourceItemValue = sourceItemValue.Replace(',', '.');
}
}
sbFieldValues.Append(Convert.ToString(sourceFld.Title) + ": " + sourceItemValue);
sbFieldValues.Append(Environment.NewLine);
}
dicDestFieldValues.Add(dicMappedFields[MappedItem.Key], sourceItemValue);
}
}
}
//set source 'Title' value as the document set name
DocSetName = Convert.ToString(sourceItem["Title"]);
if (!string.IsNullOrEmpty(DocSetName))
{
//replace the special charecters
DocSetName = ReplaceSpecialCharacters(DocSetName);
DocSetName = DocSetName.Trim();
//create document set
isDocSetCreated = proxy.CreateDocumentSet(destWebUrl, destDocLibName, DocSetName, LogonUser, docSetCTypeName, dicDestFieldValues);
}
if (isDocSetCreated == "Success")
{
//check attachments count is not zero
if (sourceItem.Attachments.Count > 0)
{
for (int i = 0; i < sourceItem.Attachments.Count; i++)
{
//attachments are actualy SPFiles stored in SPFolder that is part of our list
SPFile file = sourceItem.Web.GetFile(sourceItem.Attachments.UrlPrefix + sourceItem.Attachments[i]);
// TODO: Save to Document Library
if (file != null)
{
string attachmentFileName = Path.GetFileNameWithoutExtension(file.Name);
string extension = Path.GetExtension(file.Name);
if (!string.IsNullOrEmpty(attachmentFileName))
{
//replace the special charecters
attachmentFileName = ReplaceSpecialCharacters(attachmentFileName);
attachmentFileName = attachmentFileName.Trim();
attachmentFileName = attachmentFileName + extension;
}
//update document type
if (dicDestFieldValues != null && dicDestFieldValues.Count > 0)
{
if (dicDestFieldValues.ContainsKey(docTypeInternalName))
{
//update document type field
dicDestFieldValues[docTypeInternalName] = GetDocumentType(file.Name.ToLower());
}
}
//upload spfile to the destination library
string isUploaded = proxy.UploadFiletoDocLib(destWebUrl, destDocLibName, file.OpenBinary(), attachmentFileName, LogonUser, DocSetName, dicDestFieldValues);
if (isUploaded.Contains("Success"))
{
if (i == sourceItem.Attachments.Count - 1)
{
string docID = string.Empty;
string[] arrID = isUploaded.Split('_');
if (arrID != null && arrID.Length > 0)
{
docID = Convert.ToString(arrID[1]);
}
if (!string.IsNullOrEmpty(docID))
{
//Update migration status field
string isMigrated = UpdateMigrationStatus(sourceWebUrl, sourceListName, sourceItem.ID);
if (isMigrated.Equals("Success"))
{
//create workflow history
string isWorkflowPDFDocCreated = GetWorkflowHistory(sourceWebUrl, sourceListName, destWebUrl, destDocLibName, sourceItem.ID, docID, DocSetName, LogonUser, DocSetName, docTypeFieldInternalName, sbFieldValues);
if (isWorkflowPDFDocCreated.Equals("Success"))
{
//create version history document
string isVersionPDFDocCreated = GetListItemVersions(sourceWebUrl, sourceListName, destWebUrl, destDocLibName, sourceItem.ID, docID, DocSetName, LogonUser, DocSetName, docTypeFieldInternalName, sbFieldValues);
if (isVersionPDFDocCreated.Equals("Success"))
{
successMsg = "Success";
}
else
{
successMsg = isVersionPDFDocCreated;
}
}
else
{
successMsg = isWorkflowPDFDocCreated;
}
}
else
{
successMsg = isMigrated;
}
}
else
{
successMsg = "Uploaded document was not found";
}
}
}
else
{
successMsg = isUploaded;
}
}
else
{
successMsg = "Unable to convert the attachment to SPFile";
}
}
}
else
{
//update migration status without any attachment
string isMigrated = UpdateMigrationStatus(sourceWebUrl, sourceListName, sourceItem.ID);
if (isMigrated.Equals("Success"))
{
successMsg = "Success";
}
else
{
successMsg = isMigrated;
}
}
}
else
{
successMsg = "Creating the new Documentset - " + isDocSetCreated;
}
}
}
else
{
successMsg = "Source Item ID " + SourceItemID + " was not found";
}
}
else
{
successMsg = "Source list was not found";
}
}
else
{
successMsg = "FieldMappingList was not found";
}
}
}
});
return successMsg;
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// get document type from file attachment
/// </summary>
/// <param name="path"></param>
/// <param name="Folder"></param>
/// <param name="strTerms"></param>
/// <param name="tagTermSet"></param>
/// <returns></returns>
public string GetDocumentType(string docName)
{
string docType = string.Empty;
try
{
try
{
if (docName.Contains(".msg"))
{
docType = "E-Mails";
}
else if (docName.Contains("calc"))
{
docType = "Calculation Sheet";
}
else if (docName.Contains("adr_"))
{
docType = "ADR Request Form";
}
else if (docName.Contains("bnb_"))
{
docType = "BNB Request Form";
}
else if (docName.Contains("_migration_"))
{
docType = "Workflow";
}
else
{
docType = "Others";
}
}
catch (Exception ex)
{
docType = ex.Message;
}
return docType;
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// Update the migration status
/// </summary>
/// <param name="sourceWebUrl"></param>
/// <param name="sourceListName"></param>
/// <returns></returns>
public string UpdateMigrationStatus(string sourceWebUrl, string sourceListName, int iSourceID)
{
string isMigrated = string.Empty;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(sourceWebUrl))
{
//open the specified web
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPList sourceList = web.Lists.TryGetList(sourceListName) as SPList;
if (sourceList != null)
{
SPListItem sourceItem = sourceList.GetItemById(iSourceID);
if (sourceItem != null)
{
//update migration status field
sourceItem["MigrationStatus"] = 1;
sourceItem.SystemUpdate();
isMigrated = "Success";
}
}
}
}
});
return isMigrated;
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// check the current user has the appropriate permission to upload the new documents
/// </summary>
/// <param name="webUrl"></param>
/// <param name="docLibName"></param>
/// <param name="userLoginName"></param>
/// <returns></returns>
public string CheckUserPermission(string destWebUrl, string docLibName, string userLoginName)
{
string docPermission = string.Empty;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//create bindings and proxy
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
binding.MaxBufferPoolSize = Int32.MaxValue;
binding.MaxReceivedMessageSize = Int32.MaxValue;
binding.MaxBufferSize = Int32.MaxValue;
binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
binding.ReaderQuotas.MaxDepth = Int32.MaxValue;
binding.ReaderQuotas.MaxBytesPerRead = Int32.MaxValue;
binding.ReaderQuotas.MaxNameTableCharCount = Int32.MaxValue;
binding.ReaderQuotas.MaxArrayLength = Int32.MaxValue;
binding.SendTimeout = new TimeSpan(1, 10, 0);
binding.ReceiveTimeout = new TimeSpan(1, 10, 0);
EndpointAddress endpoint = new EndpointAddress(destWebUrl + "/_vti_bin/FileMigrationWCFService2013/FileMigrationService2013.svc");
//proxy
FileMigrationWCFService2010.FileMigrationService2013.FileMigrationServiceClient proxy = new FileMigrationWCFService2010.FileMigrationService2013.FileMigrationServiceClient(binding, endpoint);
proxy.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
//check the current user has the appropriate permission in the document library to upload the documents
docPermission = proxy.CheckUserPermission(destWebUrl, docLibName, userLoginName);
});
return docPermission;
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// get workflow history and make the PDF document
/// </summary>
/// <param name="webUrl"></param>
/// <param name="docLibName"></param>
/// <param name="userLoginName"></param>
/// <returns></returns>
public string GetWorkflowHistory(string sourceWebUrl, string sourceListName, string destWebUrl, string destDocLibName, int iSourceID, string destDocID, string FileName, string LogonUser, string DocSetName, string WFDocTypeFldName, StringBuilder sourceFldValues)
{
string wfHistoryStatus = string.Empty;
StringBuilder sbWFHistory = new StringBuilder();
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(sourceWebUrl))
{
//open the specified web
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
//get source list
SPList sourceList = web.Lists.TryGetList(sourceListName) as SPList;
if (sourceList != null)
{
//get source item
SPListItem sourceItem = sourceList.GetItemById(iSourceID);
if (sourceItem != null)
{
//get all workflows associated with that item
foreach (SPWorkflow workflow in sourceItem.Workflows)
{
sbWFHistory.Append(" *********************************************************************************** ");
//Today date and Time
sbWFHistory.Append(DateTime.Now.ToString());
sbWFHistory.Append(Environment.NewLine);
sbWFHistory.Append(Environment.NewLine);
sbWFHistory.Append(sourceItem["Title"]);
sbWFHistory.Append(Environment.NewLine);
sbWFHistory.Append(Environment.NewLine);
//add the source field values
sbWFHistory.Append(Convert.ToString(sourceFldValues));
sbWFHistory.Append(Environment.NewLine);
foreach (SPListItem worflowHistoryItem in workflow.HistoryList.Items)
{
if (("{" + workflow.InstanceId.ToString() + "}" == worflowHistoryItem["Workflow History Parent Instance"].ToString())
&& (sourceItem.ID.ToString() == worflowHistoryItem["Primary Item ID"].ToString()))
{
sbWFHistory.Append(worflowHistoryItem["Date Occurred"].ToString());
sbWFHistory.Append(Environment.NewLine);
sbWFHistory.Append(Convert.ToString(worflowHistoryItem["Description"]));
sbWFHistory.Append(Environment.NewLine);
sbWFHistory.Append(Convert.ToString(worflowHistoryItem["Outcome"]));
sbWFHistory.Append(Environment.NewLine);
sbWFHistory.Append(Environment.NewLine);
}
}
sbWFHistory.Append(" *********************************************************************************** ");
}
if (!string.IsNullOrEmpty(Convert.ToString(sbWFHistory)))
{
//create PDF document and add all workflow history into that
Pdf pdfCreate = new Pdf();
pdfCreate.AddText(Convert.ToString(sbWFHistory));
byte[] pdfByteArray = null;
bool bPDFCreated = pdfCreate.SaveAsByteArray(ref pdfByteArray);
if (pdfByteArray != null)
{
//create bindings and proxy
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
binding.MaxBufferPoolSize = Int32.MaxValue;
binding.MaxReceivedMessageSize = Int32.MaxValue;
binding.MaxBufferSize = Int32.MaxValue;
binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
binding.ReaderQuotas.MaxDepth = Int32.MaxValue;
binding.ReaderQuotas.MaxBytesPerRead = Int32.MaxValue;
binding.ReaderQuotas.MaxNameTableCharCount = Int32.MaxValue;
binding.ReaderQuotas.MaxArrayLength = Int32.MaxValue;
binding.SendTimeout = new TimeSpan(1, 10, 0);
binding.ReceiveTimeout = new TimeSpan(1, 10, 0);
EndpointAddress endpoint = new EndpointAddress(destWebUrl + "/_vti_bin/FileMigrationWCFService2013/FileMigrationService2013.svc");
//proxy
FileMigrationWCFService2010.FileMigrationService2013.FileMigrationServiceClient proxy = new FileMigrationWCFService2010.FileMigrationService2013.FileMigrationServiceClient(binding, endpoint);
proxy.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
#region Format current date and time
int iMonth = DateTime.Now.Month;
string curMonth = string.Empty;
if (iMonth < 10)
{
curMonth = "0" + Convert.ToString(iMonth);
}
else
{
curMonth = Convert.ToString(iMonth);
}
int iDay = DateTime.Now.Day;
string curDay = string.Empty;
if (iDay < 10)
{
curDay = "0" + Convert.ToString(iDay);
}
else
{
curDay = Convert.ToString(iDay);
}
int iHour = DateTime.Now.Hour;
string curHour = string.Empty;
if (iHour < 10)
{
curHour = "0" + Convert.ToString(iHour);
}
else
{
curHour = Convert.ToString(iHour);
}
int iMinute = DateTime.Now.Minute;
string curMinute = string.Empty;
if (iMinute < 10)
{
curMinute = "0" + Convert.ToString(iMinute);
}
else
{
curMinute = Convert.ToString(iMinute);
}
#endregion
string today = DateTime.Now.Year.ToString() + curMonth + curDay + curHour + curMinute;
string PDFFileName = FileName + "_Migration_" + today + ".pdf";
string isPDFCreated = string.Empty;
isPDFCreated = proxy.UploadWFFiletoDocLib(destWebUrl, destDocLibName, pdfByteArray, PDFFileName, LogonUser, DocSetName, WFDocTypeFldName, "Workflow");
if (isPDFCreated.Contains("Success"))
{
wfHistoryStatus = "Success";
}
else
{
wfHistoryStatus = isPDFCreated;
}
}
}
else
{
wfHistoryStatus = "Success";
}
}
}
}
}
});
return wfHistoryStatus;
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// Create Migration Status column if it is not exists
/// </summary>
/// <param name="sourceWebUrl"></param>
/// <param name="sourceListName"></param>
/// <returns></returns>
public string CreateMigrationStatusField(string sourceWebUrl, string sourceListName)
{
string isFldCreated = string.Empty;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(sourceWebUrl))
{
//open the specified web
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPList sourceList = web.Lists.TryGetList(sourceListName) as SPList;
if (sourceList != null)
{
//check field is already exists
if (!sourceList.Fields.ContainsField("MigrationStatus"))
{
//Create 'MigrationStatus' yes/no field in the source list
sourceList.Fields.Add("MigrationStatus", SPFieldType.Boolean, false, false, null);
SPFieldBoolean fldMigrationStatus = sourceList.Fields["MigrationStatus"] as SPFieldBoolean;
fldMigrationStatus.Update();
SPView defaultView = sourceList.DefaultView;
defaultView.ViewFields.Add(fldMigrationStatus);
defaultView.Update();
isFldCreated = "Success";
}
else
{
isFldCreated = "Success";
}
}
}
}
});
return isFldCreated;
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// get mapped field list items
/// </summary>
/// <param name="sourceWebUrl"></param>
/// <param name="sourceListName"></param>
/// <returns></returns>
public Dictionary<string, string> GetMappedFieldItems(string sourceWebUrl, string mappedListName, string sourceListName)
{
//dictionary contains source and destination field internal names
Dictionary<string, string> dicMappedFields = new Dictionary<string, string>();
//dictionary contains source field internal names and their corresponding values
//Dictionary<string, string> dicSourceFieldValues = new Dictionary<string, string>();
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(sourceWebUrl))
{
//open the specified web
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPList FieldMappingList = web.Site.RootWeb.Lists.TryGetList(mappedListName) as SPList;
if (FieldMappingList != null)
{
//clear the existing collections
dicMappedFields.Clear();
//dicSourceFieldValues.Clear();
//save all field values in the collection
SPQuery query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name='ListName'/><Value Type='Choice'>" + sourceListName + "</Value></Eq></Where>";
SPListItemCollection FldMappingItems = FieldMappingList.GetItems(query);
foreach (SPListItem item in FldMappingItems)
{
string sourceFieldName = Convert.ToString(item["SourceInternalField"]);
string destFieldName = Convert.ToString(item["DestinationInternalField"]);
//string fieldType = Convert.ToString(item["FieldType"]);
if (!string.IsNullOrEmpty(sourceFieldName) && !string.IsNullOrEmpty(destFieldName))
{
dicMappedFields.Add(sourceFieldName, destFieldName);
}
if (Convert.ToString(item["Title"]) == "Document Type")
{
dicMappedFields.Add("DocumentType", destFieldName);
}
}
}
}
}
});
return dicMappedFields;
}
catch (Exception ex)
{
return null;
}
}
/// <summary>
/// Get document library url
/// </summary>
/// <param name="webUrl"></param>
/// <param name="docLibName"></param>
/// <returns></returns>
public string GetDocLibUrl(string destWebUrl, string docLibName)
{
string libUrl = string.Empty;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//create bindings and proxy
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
binding.MaxBufferPoolSize = Int32.MaxValue;
binding.MaxReceivedMessageSize = Int32.MaxValue;
binding.MaxBufferSize = Int32.MaxValue;
binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
binding.ReaderQuotas.MaxDepth = Int32.MaxValue;
binding.ReaderQuotas.MaxBytesPerRead = Int32.MaxValue;
binding.ReaderQuotas.MaxNameTableCharCount = Int32.MaxValue;
binding.ReaderQuotas.MaxArrayLength = Int32.MaxValue;
binding.SendTimeout = new TimeSpan(1, 10, 0);
binding.ReceiveTimeout = new TimeSpan(1, 10, 0);
EndpointAddress endpoint = new EndpointAddress(destWebUrl + "/_vti_bin/FileMigrationWCFService2013/FileMigrationService2013.svc");
//proxy
FileMigrationWCFService2010.FileMigrationService2013.FileMigrationServiceClient proxy = new FileMigrationWCFService2010.FileMigrationService2013.FileMigrationServiceClient(binding, endpoint);
proxy.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
libUrl = proxy.GetDocLibUrl(destWebUrl, docLibName);
});
return libUrl;
}
catch (Exception ex)
{
libUrl = ex.Message;
return libUrl;
}
}
/// <summary>
/// Replace special charecters in the file name which are permitted to upload in the document library
/// </summary>
/// <param name="originalFileName"></param>
/// <returns></returns>
private string ReplaceSpecialCharacters(string originalFileName)
{
string fileName = originalFileName;
try
{
fileName = fileName.Replace("~", "-");
fileName = fileName.Replace("#", "-");
fileName = fileName.Replace("%", "-");
fileName = fileName.Replace("&", " ");
fileName = fileName.Replace("*", " ");
fileName = fileName.Replace("{", "(");
fileName = fileName.Replace("}", ")");
fileName = fileName.Replace("\\", " ");
fileName = fileName.Replace(":", " ");
fileName = fileName.Replace("<", "(");
fileName = fileName.Replace(">", ")");
fileName = fileName.Replace("?", " ");
fileName = fileName.Replace("/", "-");
fileName = fileName.Replace("|", "-");
fileName = fileName.Replace("\"", " ");
fileName = fileName.Replace(".", " ");
return fileName;
}
catch (Exception ex)
{
fileName = ex.Message;
return fileName;
}
}
/// <summary>
/// get all versions history and make the PDF document
/// </summary>
/// <param name="webUrl"></param>
/// <param name="docLibName"></param>
/// <param name="userLoginName"></param>
/// <returns></returns>
public string GetListItemVersions(string sourceWebUrl, string sourceListName, string destWebUrl, string destDocLibName, int iSourceID, string destDocID, string FileName, string LogonUser, string DocSetName, string WFDocTypeFldName, StringBuilder sourceFldValues)
{
string wfVersionStatus = string.Empty;
StringBuilder sbWFVersion = new StringBuilder();
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(sourceWebUrl))
{
//open the specified web
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
//get source list
SPList sourceList = web.Lists.TryGetList(sourceListName) as SPList;
if (sourceList != null)
{
//get source item
SPListItem sourceItem = sourceList.GetItemById(iSourceID);
if (sourceItem != null)
{
for (int i = 0; i < sourceItem.Versions.Count - 1; i++)
{
sbWFVersion.Append(Environment.NewLine);
sbWFVersion.Append("VersionLabel: " + sourceItem.Versions[i].VersionLabel);
sbWFVersion.Append(Environment.NewLine);
sbWFVersion.Append("Modified: " + sourceItem.Versions[i].Created);
sbWFVersion.Append(Environment.NewLine);
sbWFVersion.Append("ModifiedBy: " + sourceItem.Versions[i].CreatedBy.User.Name);
sbWFVersion.Append(Environment.NewLine);
sbWFVersion.Append(Environment.NewLine);
SPListItemVersion oldVersion = sourceItem.Versions[i];
SPListItemVersion latestVersion = sourceItem.Versions[i + 1];
foreach (SPField field in oldVersion.Fields)
{
if (field.ShowInVersionHistory == false)
{
continue;
}
if (latestVersion == null)
{
//sbWFVersion.AppendFormat(" > {0} changed to \"{1}\"", field.StaticName, Convert.ToString(oldVersion[field.StaticName]));
sbWFVersion.AppendFormat(" > {0} \"{1}\"", field.StaticName, Convert.ToString(oldVersion[field.StaticName]));
sbWFVersion.Append(Environment.NewLine);
continue;
}
if (Convert.ToString(oldVersion[field.StaticName]).Equals(Convert.ToString(latestVersion[field.StaticName])))
{
continue;
}
sbWFVersion.AppendFormat(" > {0} \"{2}\"", field.StaticName, Convert.ToString(latestVersion[field.StaticName]), Convert.ToString(oldVersion[field.StaticName]));
sbWFVersion.Append(Environment.NewLine);
}
sbWFVersion.Append(Environment.NewLine);
}
if (!string.IsNullOrEmpty(Convert.ToString(sbWFVersion)))
{
//create PDF document and add all workflow history into that
Pdf pdfCreate = new Pdf();
pdfCreate.AddText(Convert.ToString(sbWFVersion));
byte[] pdfByteArray = null;
bool bPDFCreated = pdfCreate.SaveAsByteArray(ref pdfByteArray);
if (pdfByteArray != null)
{
//create bindings and proxy
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
binding.MaxBufferPoolSize = Int32.MaxValue;
binding.MaxReceivedMessageSize = Int32.MaxValue;
binding.MaxBufferSize = Int32.MaxValue;
binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
binding.ReaderQuotas.MaxDepth = Int32.MaxValue;
binding.ReaderQuotas.MaxBytesPerRead = Int32.MaxValue;
binding.ReaderQuotas.MaxNameTableCharCount = Int32.MaxValue;
binding.ReaderQuotas.MaxArrayLength = Int32.MaxValue;
binding.SendTimeout = new TimeSpan(1, 10, 0);
binding.ReceiveTimeout = new TimeSpan(1, 10, 0);
EndpointAddress endpoint = new EndpointAddress(destWebUrl + "/_vti_bin/FileMigrationWCFService2013/FileMigrationService2013.svc");
//proxy
FileMigrationWCFService2010.FileMigrationService2013.FileMigrationServiceClient proxy = new FileMigrationWCFService2010.FileMigrationService2013.FileMigrationServiceClient(binding, endpoint);
proxy.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
#region Format current date and time
int iMonth = DateTime.Now.Month;
string curMonth = string.Empty;
if (iMonth < 10)
{
curMonth = "0" + Convert.ToString(iMonth);
}
else
{
curMonth = Convert.ToString(iMonth);
}
int iDay = DateTime.Now.Day;
string curDay = string.Empty;
if (iDay < 10)
{
curDay = "0" + Convert.ToString(iDay);
}
else
{
curDay = Convert.ToString(iDay);
}
int iHour = DateTime.Now.Hour;
string curHour = string.Empty;
if (iHour < 10)
{
curHour = "0" + Convert.ToString(iHour);
}
else
{
curHour = Convert.ToString(iHour);
}
int iMinute = DateTime.Now.Minute;
string curMinute = string.Empty;
if (iMinute < 10)
{
curMinute = "0" + Convert.ToString(iMinute);
}
else
{
curMinute = Convert.ToString(iMinute);
}
#endregion
string today = DateTime.Now.Year.ToString() + curMonth + curDay + curHour + curMinute;
string PDFFileName = FileName + "_Version_" + today + ".pdf";
string isPDFCreated = string.Empty;
isPDFCreated = proxy.UploadWFFiletoDocLib(destWebUrl, destDocLibName, pdfByteArray, PDFFileName, LogonUser, DocSetName, WFDocTypeFldName, "Others");
if (isPDFCreated.Contains("Success"))
{
wfVersionStatus = "Success";
}
else
{
wfVersionStatus = isPDFCreated;
}
}
}
else
{
wfVersionStatus = "Success";
}
}
}
}
}
});
return wfVersionStatus;
}
catch (Exception ex)
{
return ex.Message;
}
}
}
}
Interface IFileMigrationService:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;
using Microsoft.SharePoint;
using System.Security.Principal;
namespace FileMigrationWCFService2010
{
[ServiceContract]
public interface IFileMigrationService
{
[OperationContract]
Dictionary<string, List<string>> GetLists(string webUrl);
[OperationContract]
string MigrateDocs(string sourceWebUrl, string sourceListName, string destWebUrl, string destDocLibName, string docSetCTypeName, string LogonUser, string SourceItemID, Dictionary<string, string> dicMappedFields, string docTypeFieldInternalName);
[OperationContract]
List<string> GetSourceListItems(string sourceWebUrl, string sourceListName);
[OperationContract]
string CheckUserPermission(string destWebUrl, string docLibName, string userLoginName);
[OperationContract]
string CreateMigrationStatusField(string sourceWebUrl, string sourceListName);
[OperationContract]
Dictionary<string, string> GetMappedFieldItems(string sourceWebUrl, string mappedListName, string sourceListName);
[OperationContract]
string GetDocLibUrl(string destWebUrl, string docLibName);
}
}
Here I faced the issue to migrate the huge size documents i resolved this by creating my own factory class to increase MaxReceivedMessageSize.
MyFactory.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using Microsoft.SharePoint.Client.Services;
using System.Diagnostics;
namespace FileMigrationWCFService2010
{
public class MyFactory : MultipleBaseAddressBasicHttpBindingServiceHostFactory
{
protected override ServiceHost CreateServiceHost(Type serviceType,
Uri[] baseAddresses)
{
ServiceHost host = new MultipleBaseAddressBasicHttpBindingServiceHost(
serviceType, baseAddresses);
if (host != null)
{
host.Opening += new EventHandler(OnHost_Opening);
}
return host;
}
private void OnHost_Opening(object sender, EventArgs e)
{
Debug.Assert(sender != null);
ServiceHost host = sender as ServiceHost;
Debug.Assert(host != null);
// Configure the binding values
if (host.Description != null && host.Description.Endpoints != null)
{
foreach (var endPoint in host.Description.Endpoints)
{
if (endPoint != null && endPoint.Binding != null)
{
BasicHttpBinding basicBinding = endPoint.Binding
as BasicHttpBinding;
if (basicBinding != null)
{
ConfigureBasicHttpBinding(basicBinding);
}
}
}
}
}
private static void ConfigureBasicHttpBinding(BasicHttpBinding basicBinding)
{
Debug.Assert(basicBinding != null);
basicBinding.MaxBufferPoolSize = Int32.MaxValue;
basicBinding.MaxReceivedMessageSize = Int32.MaxValue;
basicBinding.MaxBufferSize = Int32.MaxValue;
basicBinding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
basicBinding.ReaderQuotas.MaxDepth = Int32.MaxValue;
basicBinding.ReaderQuotas.MaxBytesPerRead = Int32.MaxValue;
basicBinding.ReaderQuotas.MaxNameTableCharCount = Int32.MaxValue;
basicBinding.ReaderQuotas.MaxArrayLength = Int32.MaxValue;
basicBinding.SendTimeout = new TimeSpan(1, 10, 0);
basicBinding.ReceiveTimeout = new TimeSpan(1, 10, 0);
}
}
}
FileMigrationService2010.svc
<%@ ServiceHost Language="C#" Debug="true" Service="FileMigrationWCFService2010.FileMigrationService2010, FileMigrationWCFService2010, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a092ccbe0b749357"
CodeBehind="FileMigrationService2010.cs" Factory="FileMigrationWCFService2010.MyFactory, FileMigrationWCFService2010, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a092ccbe0b749357" %>
File Upload tool developed in windows application:
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;
using FileUploadTool.FileMigrationService2010;
using FileUploadTool.FileMigrationService2013;
namespace FileUploadTool
{
public partial class FileUpload : Form
{
StringBuilder sbErrorMsg = new StringBuilder();
public FileUpload()
{
InitializeComponent();
progressBar.Visible = false;
}
/// <summary>
/// populate source list titles in the treeview control
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnLibrary_Click(object sender, EventArgs e)
{
//clear existing nodes in treeview control
tvDocLibraries.Nodes.Clear();
try
{
if (!string.IsNullOrEmpty(txtSourceSiteUrl.Text.Trim()))
{
//create bindings and proxy
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
binding.MaxBufferPoolSize = Int32.MaxValue;
binding.MaxReceivedMessageSize = Int32.MaxValue;
binding.MaxBufferSize = Int32.MaxValue;
binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
binding.ReaderQuotas.MaxDepth = Int32.MaxValue;
binding.ReaderQuotas.MaxBytesPerRead = Int32.MaxValue;
binding.ReaderQuotas.MaxNameTableCharCount = Int32.MaxValue;
binding.ReaderQuotas.MaxArrayLength = Int32.MaxValue;
binding.SendTimeout = new TimeSpan(1, 10, 0);
binding.ReceiveTimeout = new TimeSpan(1, 10, 0);
//access Sharepoint 2010 site
EndpointAddress endpoint = new EndpointAddress(txtSourceSiteUrl.Text.Trim() + "/_vti_bin/FileMigrationWCFService2010/FileMigrationService2010.svc");
//proxy
FileUploadTool.FileMigrationService2010.FileMigrationServiceClient proxy = new FileUploadTool.FileMigrationService2010.FileMigrationServiceClient(binding, endpoint);
proxy.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
//get all subsites and document libraries under given url
Dictionary<string, string[]> dicLists = proxy.GetLists(txtSourceSiteUrl.Text.Trim());
if (dicLists != null && dicLists.Count > 0)
{
foreach (KeyValuePair<string, string[]> web in dicLists)
{
//Add the Web’s title as the parent node of the tree view control
TreeNode parentNode = new TreeNode();
parentNode.Text = web.Key;
tvDocLibraries.Nodes.Add(parentNode);
//Get a reference to the child node
foreach (string DocTitle in web.Value)
{
//Add the document library title as the child nodes of the tree view control
TreeNode childNode = new TreeNode();
childNode.Text = DocTitle;
childNode.ToolTipText = DocTitle;
parentNode.Nodes.Add(childNode);
}
}
}
else
{
//if no document libraries exists on the site
MessageBox.Show("No lists were found in the site");
}
}
else
{
MessageBox.Show("Please enter Source site url!");
}
}
catch (Exception ex)
{
//Exception
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// Populate source list name and web url in the controls after the list has selected
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void tvDocLibraries_AfterSelect(object sender, TreeViewEventArgs e)
{
try
{
//get selected treeview node
TreeNode selectedNode = tvDocLibraries.SelectedNode;
if (selectedNode != null && !string.IsNullOrEmpty(selectedNode.ToolTipText))
{
//get selected document library title
txtSourceListName.Text = selectedNode.Text;
//get selected web url
txtSourceWebUrl.Text = selectedNode.Parent.Text;
}
else
{
//clear selected document library title
txtSourceListName.Text = string.Empty;
//clear selected web url
txtSourceWebUrl.Text = string.Empty;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// populate destination list titles in the treeview control
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btndestLists_Click(object sender, EventArgs e)
{
//clear the existing destination libraries title
tvDestLibs.Nodes.Clear();
try
{
if (!string.IsNullOrEmpty(txtdestSiteUrl.Text.Trim()))
{
//create bindings and proxy
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
binding.MaxBufferPoolSize = Int32.MaxValue;
binding.MaxReceivedMessageSize = Int32.MaxValue;
binding.MaxBufferSize = Int32.MaxValue;
binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
binding.ReaderQuotas.MaxDepth = Int32.MaxValue;
binding.ReaderQuotas.MaxBytesPerRead = Int32.MaxValue;
binding.ReaderQuotas.MaxNameTableCharCount = Int32.MaxValue;
binding.ReaderQuotas.MaxArrayLength = Int32.MaxValue;
binding.SendTimeout = new TimeSpan(1, 10, 0);
binding.ReceiveTimeout = new TimeSpan(1, 10, 0);
//Access sharepoint 2013 site and document libraries
EndpointAddress endpoint = new EndpointAddress(txtdestSiteUrl.Text.Trim() + "/_vti_bin/FileMigrationWCFService2013/FileMigrationService2013.svc");
//proxy
FileUploadTool.FileMigrationService2013.FileMigrationServiceClient proxy = new FileUploadTool.FileMigrationService2013.FileMigrationServiceClient(binding, endpoint);
proxy.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
//get all subsites and document libraries based on the given url
Dictionary<string, string[]> DicLibraries = proxy.GetDocLibraries(txtdestSiteUrl.Text.Trim());
if (DicLibraries != null && DicLibraries.Count > 0)
{
foreach (KeyValuePair<string, string[]> web in DicLibraries)
{
//Add the Web’s title as the parent node of the tree view control
TreeNode parentNode = new TreeNode();
parentNode.Text = web.Key;
tvDestLibs.Nodes.Add(parentNode);
//Get a reference to the child node
foreach (string DocTitle in web.Value)
{
//Add the document library title as the child nodes of the tree view control
TreeNode childNode = new TreeNode();
childNode.Text = DocTitle;
childNode.ToolTipText = DocTitle;
parentNode.Nodes.Add(childNode);
}
}
}
else
{
//if no document libraries exists on the site
MessageBox.Show("No document libraries were found in the site");
}
}
else
{
MessageBox.Show("Please enter Destination site url!");
}
}
catch (Exception ex)
{
//exception
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// Populate destination list name,web url and document set name in the controls after the document library has selected
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void tvDestLibs_AfterSelect(object sender, TreeViewEventArgs e)
{
try
{
//create bindings and proxy
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
binding.MaxBufferPoolSize = Int32.MaxValue;
binding.MaxReceivedMessageSize = Int32.MaxValue;
binding.MaxBufferSize = Int32.MaxValue;
binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
binding.ReaderQuotas.MaxDepth = Int32.MaxValue;
binding.ReaderQuotas.MaxBytesPerRead = Int32.MaxValue;
binding.ReaderQuotas.MaxNameTableCharCount = Int32.MaxValue;
binding.ReaderQuotas.MaxArrayLength = Int32.MaxValue;
binding.SendTimeout = new TimeSpan(1, 10, 0);
binding.ReceiveTimeout = new TimeSpan(1, 10, 0);
//Access sharepoint2013 site
EndpointAddress endpoint = new EndpointAddress(txtdestSiteUrl.Text.Trim() + "/_vti_bin/FileMigrationWCFService2013/FileMigrationService2013.svc");
//proxy
FileUploadTool.FileMigrationService2013.FileMigrationServiceClient proxy = new FileUploadTool.FileMigrationService2013.FileMigrationServiceClient(binding, endpoint);
proxy.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
//get selected treeview node
TreeNode selectedNode = tvDestLibs.SelectedNode;
if (selectedNode != null && !string.IsNullOrEmpty(selectedNode.ToolTipText))
{
//get selected document library title
txtdestLibName.Text = selectedNode.Text;
//get selected web url
txtdestWebUrl.Text = selectedNode.Parent.Text;
//get all subsites and document libraries based on the given url
string[] DocSetNames = proxy.GetDocumentSetNames(txtdestWebUrl.Text.Trim(), txtdestLibName.Text.Trim());
if (DocSetNames != null && DocSetNames.Length > 0)
{
cbDestDocSetName.DataSource = DocSetNames;
}
else
{
//clear document set name
cbDestDocSetName.DataSource = null;
}
}
else
{
//clear selected document library title
txtdestLibName.Text = string.Empty;
//clear selected web url
txtdestWebUrl.Text = string.Empty;
cbDestDocSetName.DataSource = null;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// Upload the attachments from sharepoint2010 to sharepoint2013
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void UploadDoc_Click(object sender, EventArgs e)
{
try
{
//clear the existing error message
txtError.Text = string.Empty;
//clear the success message
lblImportMsg.Text = string.Empty;
//check controls validation
string validateMsg = ValidateControls();
if (validateMsg.Equals("ValidationSuccess"))
{
//create bindings and proxy
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
binding.MaxBufferPoolSize = Int32.MaxValue;
binding.MaxReceivedMessageSize = Int32.MaxValue;
binding.MaxBufferSize = Int32.MaxValue;
binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
binding.ReaderQuotas.MaxDepth = Int32.MaxValue;
binding.ReaderQuotas.MaxBytesPerRead = Int32.MaxValue;
binding.ReaderQuotas.MaxNameTableCharCount = Int32.MaxValue;
binding.ReaderQuotas.MaxArrayLength = Int32.MaxValue;
binding.SendTimeout = new TimeSpan(1, 10, 0);
binding.ReceiveTimeout = new TimeSpan(1, 10, 0);
//access Sharepoint2010 site
EndpointAddress endpoint = new EndpointAddress(txtSourceWebUrl.Text.Trim() + "/_vti_bin/FileMigrationWCFService2010/FileMigrationService2010.svc");
//proxy
FileUploadTool.FileMigrationService2010.FileMigrationServiceClient proxy = new FileUploadTool.FileMigrationService2010.FileMigrationServiceClient(binding, endpoint);
proxy.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
//get current user windows identity
System.Security.Principal.WindowsIdentity wiName = System.Security.Principal.WindowsIdentity.GetCurrent();
//check the current user has the appropriate permission in the document library to upload the documents in the destination folder
string isUserPermission = proxy.CheckUserPermission(txtdestWebUrl.Text.Trim(), txtdestLibName.Text.Trim(), wiName.Name);
if (isUserPermission.Equals("Success"))
{
//check 'MigrationStatus' field has exists either will create a new field
string isMigrationStatusFldCreated = proxy.CreateMigrationStatusField(txtSourceWebUrl.Text.Trim(), txtSourceListName.Text.Trim());
if (isMigrationStatusFldCreated.Equals("Success"))
{
//get all source list items and attachments
string[] soureceItemIds = proxy.GetSourceListItems(txtSourceWebUrl.Text.Trim(), txtSourceListName.Text.Trim());
if (soureceItemIds != null && soureceItemIds.Length > 0)
{
Dictionary<string, string> dicMappedFields = proxy.GetMappedFieldItems(txtSourceWebUrl.Text.Trim(), "FieldMappingList", txtSourceListName.Text.Trim());
if (dicMappedFields != null && dicMappedFields.Count > 0)
{
string documentTypeFld = Convert.ToString(dicMappedFields["DocumentType"]);
//remove document type key
//if (dicMappedFields.ContainsKey("DocumentType"))
//{
// dicMappedFields.Remove("DocumentType");
//}
progressBar.Visible = true;
// Set Minimum to 1 to represent the first file being copied.
progressBar.Minimum = 1;
// Set Maximum to the total number of Users created.
progressBar.Maximum = soureceItemIds.Length;
// Set the initial value of the ProgressBar.
progressBar.Value = 1;
// Set the Step property to a value of 1 to represent each user is being created.
progressBar.Step = 1;
int uploadedDocCount = 0;
foreach (string sourceItemID in soureceItemIds)
{
//if (Convert.ToInt32(sourceItemID) >= 1 && Convert.ToInt32(sourceItemID) <= 50)
{
//upload each attachment from splistitem into destination document library
string isUploaded = proxy.MigrateDocs(txtSourceWebUrl.Text.Trim(), txtSourceListName.Text.Trim(), txtdestWebUrl.Text.Trim(), txtdestLibName.Text.Trim(), Convert.ToString(cbDestDocSetName.SelectedValue), wiName.Name, sourceItemID, dicMappedFields, documentTypeFld);
// Copy the file and increment the ProgressBar if successful.
if (isUploaded.Equals("Success"))
{
lblImportMsg.Text = "Total " + Convert.ToString(uploadedDocCount) + " out of " + Convert.ToString(soureceItemIds.Length) + " is migrating....";
lblImportMsg.Refresh();
// Perform the increment on the ProgressBar.
progressBar.PerformStep();
uploadedDocCount++;
}
else
{
//catch the error message
Errorlbl.Visible = true;
sbErrorMsg.AppendLine(isUploaded + Environment.NewLine);
sbErrorMsg.AppendLine("----------------------------------------------------------");
txtError.Visible = true;
txtError.ForeColor = System.Drawing.Color.Red;
sbErrorMsg.Append("Source Item ID - " + sourceItemID);
sbErrorMsg.Append(Environment.NewLine);
txtError.Text = Convert.ToString(sbErrorMsg);
txtError.Refresh();
sbErrorMsg.AppendLine("----------------------------------------------------------");
}
}
}
//success message
lblImportMsg.Text = "Total " + Convert.ToString(uploadedDocCount) + " Documents Uploaded Successfully!";
lblImportMsg.Refresh();
lblImportMsg.ForeColor = System.Drawing.Color.Red;
// Set the document library in the LinkLabel.
//linkLabel.Links.Clear();
//linkLabel.Text = txtdestLibName.Text.Trim();
//string url = proxy.GetDocLibUrl(txtdestWebUrl.Text.Trim(), txtdestLibName.Text.Trim());
//linkLabel.Links.Add(0, 25, url);
}
else
{
MessageBox.Show("Field Mapping items are not available!");
}
}
else
{
MessageBox.Show("Source items are not available!");
}
}
else
{
MessageBox.Show(isMigrationStatusFldCreated);
}
}
else
{
MessageBox.Show(isUserPermission);
}
}
else
{
MessageBox.Show(validateMsg);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// Validation
/// </summary>
/// <returns></returns>
private string ValidateControls()
{
string validateMsg = string.Empty;
try
{
if (string.IsNullOrEmpty(txtSourceSiteUrl.Text.Trim()))
{
validateMsg = "Please enter Source site url!";
txtSourceSiteUrl.Focus();
}
else if (string.IsNullOrEmpty(txtSourceWebUrl.Text.Trim()))
{
validateMsg = "Source web url should not empty!";
txtSourceWebUrl.Focus();
}
else if (string.IsNullOrEmpty(txtSourceListName.Text.Trim()))
{
validateMsg = "Please select a Source list!";
txtSourceListName.Focus();
}
else if (string.IsNullOrEmpty(txtdestSiteUrl.Text.Trim()))
{
validateMsg = "Please enter Destination site url!";
txtdestSiteUrl.Focus();
}
else if (string.IsNullOrEmpty(txtdestWebUrl.Text.Trim()))
{
validateMsg = "Destination web url should not empty!";
txtdestWebUrl.Focus();
}
else if (string.IsNullOrEmpty(Convert.ToString(cbDestDocSetName.SelectedValue)))
{
validateMsg = "Please select a DocumentSet!";
cbDestDocSetName.Focus();
}
else if (string.IsNullOrEmpty(Convert.ToString(txtdestLibName.Text.Trim())))
{
validateMsg = "Please select a Destination list!";
txtdestLibName.Focus();
}
else
{
validateMsg = "ValidationSuccess";
}
return validateMsg;
}
catch (Exception ex)
{
return validateMsg;
}
}
}
}
No comments:
Post a Comment