Thursday, October 11, 2018

Copying list items with metadata (history) to another list (SharePoint 2010, 2013, 2016)

In this article, I continue to sort out the tasks associated with transferring data from one source to another while preserving all the information. This time I published a sample code where I copy the list items with the whole story (metadata) into another list.

The main advantage of this code is the use of C#, which means such wonderful features are available as Custom Timer Job, Event Reciever and much more. In my console project I using following reference and code:

using System;

using Microsoft.SharePoint;

using Microsoft.SharePoint.Utilities;

1. Current site:
using (SPSite oSPsite = new SPSite("http://sp/sites/test"))
            {
                using (SPWeb oSPWeb = oSPsite.OpenWeb())
                {
                    //List source
                    SPList srcList = oSPWeb.Lists["Users1"];
                    //List destination
                    SPList destList = oSPWeb.Lists["Users2"];
                    foreach (SPListItem sourceItem in srcList.Items)
                    {
                        SPListItem targetItem = destList.AddItem();
                        for (int i = sourceItem.Versions.Count - 1; i >= 0; i--)
                        {
                            SPListItemVersion sourceField = sourceItem.Versions[i];
                            targetItem["Author"] = sourceField["Author"];
                            targetItem["Title"] = sourceField["Title"];
                            targetItem["Editor"] = sourceField["Editor"];
                            targetItem[SPBuiltInFieldId.Modified] = GetFieldValueAsDate(sourceField["Modified"]);
                            targetItem[SPBuiltInFieldId.Created] = GetFieldValueAsDate(sourceField["Created"]);
                            targetItem.Update();
                        }
                    }
                }
  private static String GetFieldValueAsDate(object sourceField)
        {
            string result = string.Empty;
            if (sourceField != null)
            {
                DateTime date = Convert.ToDateTime(sourceField);
                if (date.Year > 1900)
                    result = SPUtility.CreateISO8601DateTimeFromSystemDateTime(date);
            }
            return result;
        }
    }
}
2. Another site:
//Site source
using (SPSite oSPsite = new SPSite("http://sp/sites/test"))
 {
   using (SPWeb oSPWeb = oSPsite.OpenWeb())
    {
      //List source
      SPList srcList = oSPWeb.Lists["Test1"];
       //Site destination
       using (SPSite SPsite = new SPSite("http://sp/sites/RU_test"))
         {
           using (SPWeb SPWeb = SPsite.OpenWeb())
            {
              //List destination 
              SPList destList = SPWeb.Lists["Test2"];
                foreach (SPListItem sourceItem in srcList.Items)
                  {
                    SPListItem targetItem = destList.AddItem();
                      for (int i = sourceItem.Versions.Count - 1; i >= 0; i--)
                        {
                           SPListItemVersion sourceField = sourceItem.Versions[i];
                            targetItem["Author"] = sourceField["Author"];
                            targetItem["Title"] = sourceField["Title"];
                            targetItem["Editor"] = sourceField["Editor"];
                            targetItem[SPBuiltInFieldId.Modified] = GetFieldValueAsDate(sourceField["Modified"]);
                            targetItem[SPBuiltInFieldId.Created] = GetFieldValueAsDate(sourceField["Created"]);
                            targetItem.Update();
                        }
                    }
                }
            }
        }
     }
  }
private static String GetFieldValueAsDate(object sourceField)
        {
            string result = string.Empty;
            if (sourceField != null)
            {
                DateTime date = Convert.ToDateTime(sourceField);
                if (date.Year > 1900)
                    result = SPUtility.CreateISO8601DateTimeFromSystemDateTime(date);
            }
            return result;
        }
    }
}
Happy Coding!

Friday, October 5, 2018

Moving/copying file with version history to another library (SharePoint 2010, 2013, 2016)

Recently, I had to copy an archive of documents from one collection of sites to another, I didn’t have any problems with PowerShell, thanks to Import\Export, but the task changed when the question arose about transferring several large documents with a long history of versioning from one library to another. I tried to find a solution without a code, but did not find anything, and suddenly in one forum I saw a small piece of code that solved my problems, in this article I will share it and tell you a little.

The main advantage of this code is the use of C#, which means such wonderful features are available as Custom Timer Job, Event Reciever and much more. In my console project I using following reference and code:

using System;

using Microsoft.SharePoint;

using System.IO;

using System.Collections;

//Get SPSite or Site Collection
using (SPSite oSPsite = new SPSite("http://sp/sites/test")){
 using (SPWeb oSPWeb = oSPsite.OpenWeb())
  {
   //Get Library source
   SPList lib_source = oSPWeb.Lists["Library1"];
   //Get Library destination
   SPList lib_destination = (SPDocumentLibrary)oSPWeb.Lists["Library2"];
   //Get item (file) using SPQuery
   SPListItemCollection items = lib_source.GetItems(new SPQuery()
    {
     Query = @"<Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='Text'>Document.docx</Value></Eq></Where>"
      });
         foreach (SPListItem item in items) {
           SPFile fileSource = item.File;
           //Get the created by and created
           SPUser userCreatedBy = fileSource.Author;
           //Convert the "TimeCreated" property to local time
           DateTime dateCreatedOn = fileSource.TimeCreated.ToLocalTime();
           //Get the versions history
           int countVersions = item.File.Versions.Count;
              for (int i = 0; i <= countVersions; i++)
                {
                  Hashtable hashSourceProp;
                  Stream streamFile;
                  SPUser userModifiedBy;
                  DateTime dateModifiedOn;
                  string strVerComment = "";
                  bool bolMajorVer = false;
                    if (i < countVersions)
                     {
                      //Get all versions file, history, properties, createdBy, checkInComment
                      SPFileVersion fileSourceVer = item.File.Versions[i];
                      hashSourceProp = fileSourceVer.Properties;
                      userModifiedBy = (i == 0) ? userCreatedBy : fileSourceVer.CreatedBy;
                      dateModifiedOn = fileSourceVer.Created.ToLocalTime();
                      strVerComment = fileSourceVer.CheckInComment;
                      bolMajorVer = fileSourceVer.VersionLabel.EndsWith("0") ? true : false;
                      streamFile = fileSourceVer.OpenBinaryStream();
                     } else {
                       //Get current versions file, history, properties, createdBy, checkInComment
                       userModifiedBy = fileSource.ModifiedBy;
                       dateModifiedOn = fileSource.TimeLastModified;
                       hashSourceProp = fileSource.Properties;
                       strVerComment = fileSource.CheckInComment;
                       bolMajorVer = fileSource.MinorVersion == 0 ? true : false;
                       streamFile = fileSource.OpenBinaryStream();
                     }
                       //URL library destination
                       string urlDestFile = lib_destination.RootFolder.Url + "/Folder/" + fileSource.Name;
                       //Copy all properties
                       SPFile fileDest = lib_destination.RootFolder.Files.Add(
                         urlDestFile,
                         streamFile,
                         hashSourceProp,
                         userCreatedBy,
                         userModifiedBy,
                         dateCreatedOn,
                         dateModifiedOn,
                         strVerComment,
                         true);
                          if (bolMajorVer)
                             fileDest.Publish(strVerComment);
                          else
                            {
                             SPListItem itmNewVersion = fileDest.Item;
                             itmNewVersion["Created"] = dateCreatedOn;
                             itmNewVersion["Modified"] = dateModifiedOn;
                             itmNewVersion.UpdateOverwriteVersion();
                            }                  
                        }
                    }
                }
            }
Happy Coding!