Showing posts with label MOSS. Show all posts
Showing posts with label MOSS. Show all posts

Friday, 18 October 2013

moving the files gt 260 characters along with metadata moss

Here the logic is based on moving files to archival document library with along with immediate parent folder, with all the files within that folder will be moved if any file in that folder exceeds the character limit of 260 characters.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
namespace MoveFiles
{
    class Program
    {
        static string siteUrl = "site_url"
        static int maxFileLength = 256;
        static string fldCreated = "Created";
        static string fldCreatedBy = "Created By";
        static string fldModifiedBy = "Modified By";
        static string fldModified = "Modified";
        static string archLib = "Arch";
        static string destinationDirectory = "Arch";// "/Arch";
        static void Main(string[] args)
        {
            //Console.WriteLine("Do you want to run the app against the Site Url " + siteUrl);
            //Console.WriteLine("Type: Y  to continue or N to enter new url");
            //if (!Console.ReadLine().ToLower().Contains("y"))
            //{
            //    Console.WriteLine("Enter the site url");
            //    siteUrl = Console.ReadLine();
            //}
            GetSiteContext();
        }


        static private void GetSiteContext()
        {
            using (SPSite currSite = new SPSite(siteUrl))
            {
                using (SPWeb currWeb = currSite.RootWeb)
                {
                    string limitWebUrl = "/rel_web_url";

                    Console.WriteLine("Iterating only thourgh web:" + limitWebUrl);
                    Console.WriteLine("Type: Y  to continue or N to iterate new relative web url");
                    if (!Console.ReadLine().ToLower().Contains("y"))
                    {
                        Console.WriteLine("Enter new web url");
                        limitWebUrl = Console.ReadLine();
                    }
                    SPWebCollection webCol = currSite.AllWebs;
                    foreach (SPWeb web in webCol)
                    {

                        if (web.Url.ToLower().Contains(limitWebUrl.ToLower()))
                        {

                            LogError("Iterating web URL: " + web.Url + " TITLE: " + web.Title);
                            GetDocLibs(web);
                        }
                        if (web != null)
                        {
                            web.Dispose();
                        }
                    }
                }
            }
        }
        static bool CreateArchivalDocLib(SPWeb web)
        {
            bool isdocLibExists = false;

            try
            {
                SPList doclib = web.Lists[archLib] as SPDocumentLibrary;
                isdocLibExists = true;
            }
            catch (Exception)
            {
                Guid archLibGuid = web.Lists.Add(archLib, "Document Library to Archive long files", SPListTemplateType.DocumentLibrary);
                SPDocumentLibrary docLibArch = web.Lists[archLibGuid] as SPDocumentLibrary;
                docLibArch.OnQuickLaunch = true;
                docLibArch.EnableMinorVersions = true;
                docLibArch.Update();
                isdocLibExists = true;
            }
            return isdocLibExists;

        }
        static private void GetDocLibs(SPWeb web)
        {
            SPListCollection listCol = web.Lists;
            foreach (SPList list in listCol)
            {
                try
                {
                    if (list.BaseTemplate == SPListTemplateType.DocumentLibrary)// (!list.Hidden)
                    {
                        SPDocumentLibrary docLib = (SPDocumentLibrary)list; //select document library only
                        //check that (web.Url + "/" + docLib.Url).Length > 260
                        if (docLib.Title != archLib) // exclude destination folder
                        {
                           
                            foreach (SPListItem folder in docLib.Folders)
                            {
                                MoveFolder(web, folder.Url, destinationDirectory);
                            }
                        }

                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error:" + ex.ToString());
                    LogError(ex.Message);
                }
            }

            //SPFolderCollection folderCol = web.Folders;
        }
        //Move all folders and subfolder
        static public void MoveFolder(SPWeb sourceWeb, string sourceDirectory, string destinationDirectory)
        {
            SPFolder srcFolder = sourceWeb.GetFolder(sourceDirectory);
            if (srcFolder.Exists)
            {
                SPDocumentLibrary docLib = srcFolder.Item.ParentList as SPDocumentLibrary;
                SPFolderCollection oFolder = srcFolder.SubFolders;
                SPQuery oQuery = new SPQuery();
                oQuery.Query = "<Where><Eq><FieldRef Name='FSObjType'/><Value Type='Lookup'>1</Value></Eq></Where>";
                oQuery.Folder = oFolder.Folder;
                oQuery.ViewAttributes = "Scope='RecursiveAll'";
                SPListItemCollection collListItems = docLib.GetItems(oQuery);
                string newdestinationFolderPath = destinationDirectory;
                //Move the root folder with files
                MoveSingleFolder(sourceWeb, sourceDirectory, newdestinationFolderPath);

                newdestinationFolderPath = destinationDirectory + "/" + srcFolder.Name;
                //Move the subfolders with files
                foreach (SPListItem item in collListItems)
                {
                    MoveSingleFolder(sourceWeb, item.Url, newdestinationFolderPath);
                }
                // Delete the root folder
                // DeleteSourceFolder(sourceWeb, sourceDirectory);
            }

        }

        //Move single folder
        static private void MoveSingleFolder(SPWeb srcWeb, string sourceFolderPath, string destinationFolderPath)
        {
            bool libCreated = CreateArchivalDocLib(srcWeb);
            SPFolder srcFolder = srcWeb.GetFolder(sourceFolderPath);
            bool moveFolderFiles = GetMaxFileLength(srcWeb, sourceFolderPath);
            if (srcFolder.Exists && moveFolderFiles) //&& moveFolderFiles
            {
                string srcFolderName = srcFolder.Name;
                try
                {
                    SPFolder dstFolder = srcWeb.GetFolder(destinationFolderPath);
                    // LogError("Moving files from: " + sourceFolderPath);
                    // SPFolder dstFolder = srcWeb.Site.RootWeb.GetFolder(destinationFolderPath); // Creating for root web
                    if (dstFolder.Exists)
                    {

                        SPFolder newFolder = dstFolder.SubFolders.Add(srcFolderName);
                        SPListItem newFolderItem = (SPListItem)newFolder.Item;
                        newFolderItem.ParentList.Fields[SPBuiltInFieldId.Modified].ReadOnlyField = false;
                        newFolderItem.ParentList.Fields[SPBuiltInFieldId.Created].ReadOnlyField = false;
                        newFolderItem.ParentList.Fields[SPBuiltInFieldId.Created_x0020_By].ReadOnlyField = false;
                        newFolderItem.ParentList.Fields["Modified By"].ReadOnlyField = false; // SPBuiltInFieldId.Modified_x0020_By
                        newFolderItem[SPBuiltInFieldId.Created] = srcFolder.Item[SPBuiltInFieldId.Created];
                        newFolderItem[SPBuiltInFieldId.Created_x0020_By] = srcFolder.Item[SPBuiltInFieldId.Created_x0020_By];
                        newFolderItem[SPBuiltInFieldId.Modified] = srcFolder.Item["Modified"];
                        newFolderItem["Modified By"] = srcFolder.Item["Modified By"];
                        newFolderItem.UpdateOverwriteVersion();
                        newFolderItem.ParentList.Fields[SPBuiltInFieldId.Created].ReadOnlyField = true;
                        newFolderItem.ParentList.Fields[SPBuiltInFieldId.Created_x0020_By].ReadOnlyField = true;
                        newFolderItem.ParentList.Fields[SPBuiltInFieldId.Modified].ReadOnlyField = true;
                        newFolderItem.ParentList.Fields["Modified By"].ReadOnlyField = true; // SPBuiltInFieldId.Modified_x0020_By

                    }
                    else
                    {
                        CreateFolder(srcWeb, srcFolder, destinationDirectory, srcFolderName);
                    }
                }
                catch
                {
                    try
                    {
                        CreateFolder(srcWeb, srcFolder, destinationDirectory, srcFolderName);
                    }
                    catch (Exception ex)
                    {
                        LogError("Error creating folder: " + ex.Message);
                    }
                }

                //CreateFolder(srcWeb, srcFolder, destinationFolderPath, srcFolderName);


                if (moveFolderFiles)
                {
                    // MoveFolderItems(srcWeb, sourceFolderPath, destinationFolderPath + "/" + srcFolderName);
                    try
                    {
                        MoveFolderItems(srcWeb, sourceFolderPath, destinationDirectory + "/" + srcFolderName);
                    }
                    catch (Exception ex)
                    {
                        LogError("* ERROR coping file : " + ex.Message);
                    }

                }
            }
        }
        static private void CreateFolder(SPWeb srcWeb, SPFolder srcFolder, string parentFolder, string childFolderPath)
        {
            SPFolder dstFolder = srcWeb.GetFolder(parentFolder);
            //SPFolder dstFolder = srcWeb.Site.RootWeb.GetFolder(parentFolder);
            SPFolder newFolder = dstFolder.SubFolders.Add(childFolderPath);
            SPListItem newFolderItem = (SPListItem)newFolder.Item;
            newFolderItem.ParentList.Fields[SPBuiltInFieldId.Modified].ReadOnlyField = false;
            newFolderItem.ParentList.Fields[SPBuiltInFieldId.Modified_x0020_By].ReadOnlyField = false;
            newFolderItem.ParentList.Fields[SPBuiltInFieldId.Created].ReadOnlyField = false;
            newFolderItem.ParentList.Fields[SPBuiltInFieldId.Created_x0020_By].ReadOnlyField = false;
            newFolderItem[SPBuiltInFieldId.Modified] = srcFolder.Item[SPBuiltInFieldId.Modified];//SPBuiltInFieldId.Modified
            newFolderItem[fldModifiedBy] = srcFolder.Item[fldModifiedBy];//SPBuiltInFieldId.Modified_x0020_By
            newFolderItem[SPBuiltInFieldId.Created] = srcFolder.Item[SPBuiltInFieldId.Created];
            newFolderItem[SPBuiltInFieldId.Created_x0020_By] = srcFolder.Item[SPBuiltInFieldId.Created_x0020_By];
            //  newFolderItem["Modified By"] = srcFolder.Item["Modified By"];//SPBuiltInFieldId.Modified_x0020_By
            //newFolderItem[SPBuiltInFieldId.Modified] = srcFolder.Item["Modified"];//SPBuiltInFieldId.Modified
            newFolderItem.UpdateOverwriteVersion();
            newFolderItem.ParentList.Fields[SPBuiltInFieldId.Modified].ReadOnlyField = true;
            newFolderItem.ParentList.Fields[SPBuiltInFieldId.Modified_x0020_By].ReadOnlyField = true;
            newFolderItem.ParentList.Fields[SPBuiltInFieldId.Created].ReadOnlyField = true;
            newFolderItem.ParentList.Fields[SPBuiltInFieldId.Created_x0020_By].ReadOnlyField = true;
        }

        //Move folder items
        static private void MoveFolderItems(SPWeb sourceWeb, string sourceFolderPath, string destinationFolderPath)
        {
            SPFolder srcFolder = sourceWeb.GetFolder(sourceFolderPath);
            int fileCount = srcFolder.Files.Count;
            //SPFolder destFolder = sourceWeb.Site.RootWeb.GetFolder(destinationFolderPath);
            SPFolder destFolder = sourceWeb.GetFolder(destinationFolderPath);
            /*Copy the files to a generic List of type SPFile*/
            SPFileCollection collFile = srcFolder.Files;

            List<SPFile> listFiles = new List<SPFile>(collFile.Count);

            foreach (SPFile oFile in collFile)
            {
                listFiles.Add(oFile);
            }
            //SPList docLibListSrc = sourceWeb.Lists[srcFolder.ContainingDocumentLibrary];
            SPDocumentLibrary docLibSrc = sourceWeb.Lists[srcFolder.ContainingDocumentLibrary] as SPDocumentLibrary;
            /* Enumerate the List and move the files into the subfolder.*/
            foreach (SPFile moveFile in listFiles)
            {
                //SPFileCollectionAddParameters fileParam = new SPFileCollectionAddParameters();
                object modifiedOn = moveFile.Item[SPBuiltInFieldId.Modified];//SPBuiltInFieldId.Modified  "Modified"
                object modifiedBy = moveFile.Item["Modified By"]; // SPBuiltInFieldId.Modified_x0020_By  "Modified By"
                object createdBy = moveFile.Item[SPBuiltInFieldId.Created_x0020_By];
                object createdOn = moveFile.Item[SPBuiltInFieldId.Created];
                //byte[] fileBytes = moveFile.OpenBinary();
                //SPFile newFile = destFolder.Files.Add(moveFile.Name, fileBytes, true);
                //string doclibUrl = docLibListSrc.RootFolder.Url; //&FolderCTID
                    moveFile.MoveTo(destFolder + "/" + moveFile.Name, true);
                SPFile newFile = sourceWeb.GetFile(destFolder + "/" + moveFile.Name);
                SPListItem dstItem = (SPListItem)newFile.Item;
                dstItem.ParentList.Fields[SPBuiltInFieldId.Modified].ReadOnlyField = false;                dstItem.ParentList.Fields["Modified By"].ReadOnlyField = false;
                dstItem.ParentList.Fields[SPBuiltInFieldId.Created].ReadOnlyField = false;
                dstItem.ParentList.Fields[SPBuiltInFieldId.Created_x0020_By].ReadOnlyField = false;
                dstItem[SPBuiltInFieldId.Modified] = modifiedOn;
                dstItem["Modified By"] = modifiedBy;
                dstItem[SPBuiltInFieldId.Created] = createdOn;
                dstItem[SPBuiltInFieldId.Created_x0020_By] = createdBy;
                dstItem.UpdateOverwriteVersion();
                dstItem.ParentList.Fields[SPBuiltInFieldId.Modified].ReadOnlyField = true; //"Modified"
                dstItem.ParentList.Fields["Modified By"].ReadOnlyField = true;
                dstItem.ParentList.Fields[SPBuiltInFieldId.Created].ReadOnlyField = true;                dstItem.ParentList.Fields[SPBuiltInFieldId.Created_x0020_By].ReadOnlyField = true;
               
            }
        }
        static private void LogError(string msg)
        {
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Migration\MigrationLogs.txt", true))
            {
                file.WriteLine(msg);
            }
        }
        static private bool GetMaxFileLength(SPWeb web, string sourceFolderPath)
        {
            // max file lenght > 256
            bool fileLengthExceeds = false;

            SPFolder srcFolder = web.GetFolder(sourceFolderPath);
            /*Get files collection SPFile*/
            SPFileCollection collFile = srcFolder.Files;
            foreach (SPFile file in collFile)
            {
                string fileUrl = web.Url + "/" + srcFolder.Url + "/" + file.Name;
                if (fileUrl.Length > maxFileLength) // 256
                {
                    fileLengthExceeds = true;

                    break;
                }
            }

            return fileLengthExceeds;

        }
    }
}