Thursday, 17 March 2016

Rich Text Editor validator (using HTML Parser) in SharePoint 2013

Requirement:
Contents in SharePoint in rich text column was getting consumed in iOS app.
There was some issues in WebView consuming some of the data which it find was not well formatted. Although such contents were rendered perfectly alright in SharePoint.

Solution:
Using JSlink rich text were validated on Blur of the rich text div element.

(function () {
    var zPlaceholder = "Default";
    var overrideCtx = {};
})();

jQuery(document).ready(function () {
   
  
    jQuery.getScript(_spPageContextInfo.siteAbsoluteUrl + '/Style%20Library/scripts/htmlparser.js', GetRTEandFixHtml());
});

function GetRTEandFixHtml() {
    // Get the rich text edit field by id starts with e.g. [id^='ProfileInformation'] ...
   // along with class and role
    var ProfileInformation = $("div[id^='ProfileInformation'][class='ms-rtestate-write ms-rteflags-0 ms-rtestate-field'][role='textbox']");
    if (ProfileInformation !== "undefined" || ProfileInformation !== null) {
        ProfileInformation.blur(function () {
            fixHTML(ProfileInformation, ProfileInformation.html());
        });
    }

    function fixHTML(element, html) {
        // Check if there is value or not before validating HTML...
        if (html.indexOf("div class=") > 0 && html.indexOf("ExternalClass") > 0) {
            try {
                var d = document.createElement('div');
                d.innerHTML = html;
                element.html(d.innerHTML); // Strips off script tags, which was major issue;
                var modifiedHTML = HTMLtoXML(d.innerHTML);// Can implement htmlparser.js call .. there are few available in JS;
                element.html(modifiedHTML);
            }
            catch (e) {
                element.html(html);
                element.unbind('blur');
            }
        }
    }

}

Tuesday, 29 September 2015

Delete Multiple sites ECMA script -

DeleteSite: function () {

var count=siteUrlArray.length;

var i = 0;

for (i = 0; i < siteUrlArray.length; i++) {

var url = siteUrlArray[i];

var clientContext = new SP.ClientContext(url);

var oweb = clientContext.get_web();

oweb.deleteObject();
         
}
clientContext.executeQueryAsync(function () { alert("Total site deleted= "+count); }, function () { });


}
-------------
Above functions shows how to delete multiple sites using ECMA Script. If any one is aware of bulk delete by JSOM using REST API plz do share.



Wednesday, 5 August 2015

Send Email using ecma script/JSOM / REST API - SharePoint

Below is the send email functionality based on SP.js As we can see below we have TO field commented out. Call 1: Sending to single user
var msg="html message to send";
buildContent.sendEmail("admin@test.com", "user@test.com" , msg, "Alert Notification!!");
in that case uncomment the line
// 'To': { 'results': [to] },
and comment the next line.

If we want to send to multiple users and SharePoint user Groups.

Call 2:
var to = [];
to.push("testUser1@test.com");
to.push("testUser2@test.com");
to.push("Site Owners");
var msg="html message to send";
buildContent.sendEmail("admin@test.com", to, msg, "Alert Notification!!");

sendEmail: function (from, to, body, subject) {
var siteurl = _spPageContextInfo.webServerRelativeUrl;
var urlTemplate = siteurl + "/_api/SP.Utilities.Utility.SendEmail";
        $.ajax({
            contentType: 'application/json',
            url: urlTemplate,
type: "POST",
            data: JSON.stringify({
'properties': { '__metadata': { 'type': 'SP.Utilities.EmailProperties' },
'From': from,
// 'To': { 'results': [to] },
'To': { 'results': to }, //
'Body': body, 'Subject': subject
                } } ),
            headers: { "Accept": "application/json;odata=verbose", "content-type": "application/json;odata=verbose", "X-RequestDigest": $("#__REQUESTDIGEST").val() }, success: function (data) { alert("Email send"); }, error: function (err) { alert(err.responseText);
// debugger;
} }); },

reference : http://blogs.msdn.com/b/spses/archive/2014/10/24/you-can-t-specify-the-from-address-for-email-messages-when-you-use-the-quot-send-an-email-quot-option-from-a-sharepoint-designer-2013-workflow-action.aspx 

Monday, 21 July 2014

"Active Profile" & Profiles missing from Import

As the title suggests we have two types of users under Manage Users section.

We were experiencing some issue with user repotee in custom organization chart.
A user who has left the company long back was reflecting in user profile:- Org Chart data.

From central admin this user was not available in "Active Profile" , but under Profile Import missing.

What seems to happen is subsequent User Profile Sync.. not has deleted the relationship as well as (Manager /Reportee ) and not deleted the stale data for users already not in the company / AD. This has to be fixed by running the "My Site Cleanup Job"

Thursday, 19 June 2014

Alerts update fixes post SharePoint Migration

Based on the contributions from Kirk Stark & skelley. There were few queries for Q & A section of getting the siteUrl property to be updated by Site Collection against the Web Application URL.

First query your site collections DB migrated based on DB Attach Upgrade against the following tables immedsubscriptions & schedsubscriptions
That's what I modified the above codes from powershell  & console app to take inputs from a text file as 3 set of values.
It reads a Alerts.csv placed at C:\ drive which has parameters as
SiteUrl,OldUrl,NewUrl

values can be
SiteCollection1Url,OldUrl,NewUrl
SiteCollection1Url,Old1Url,New1Url
SiteCollection2Url,OldUrl,NewUrl
SiteCollection2Url,Old1Url,New1Url
based on the results retuned against the above table in your case. (based on different zones values default, Intranet or Internet)

Note that the SiteUrl in the properties section has to be Web Application url while Mobile url may not the same. Please note the mobileurl section has been commented out. To cater to that scenario, u can pass 5 set of parameters in Alerts.csv and update accordingly.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.IO;

namespace AlertUpdates
{
   class Program
{
static int countsiteurlprop = 0;
static int countmobileurlprop = 0;

static string strSiteCollection =string.Empty;// Site collection url to open new context

static string strOldString =string.Empty; //old url or portion of string which needs to be replaced.// http://novahome

static string strNewString = string.Empty; //new url which will be replaced by the old Url

static void Main(string[] args)
{
try
{
using (StreamReader reader = new StreamReader(File.OpenRead(@"C:\Alerts.csv")))


{
while (!reader.EndOfStream)


{
string line = reader.ReadLine();

var values = line.Split(',');


strSiteCollection = values[0];

strOldString = values[1];

strNewString = values[2];
// GetFileOutput();


IterateSites();

}

}

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

}
 Console.ReadLine();

}
        
           
static void IterateSites()


{
           

try


{
using (SPSite spsitecol = new SPSite(strSiteCollection))


{
using (SPWeb sprootweb = spsitecol.RootWeb)


{

ListAndFixAlerts(sprootweb);
} // using sprootweb

} // using spsitecol


}
catch (System.IO.FileNotFoundException ioex)


{
Console.WriteLine("Could not access Site Collection: {0}", ioex.Message);


}
catch (Exception ex)


{
Console.WriteLine("An unexpected error occurred: {0}", ex.Message);

} // try

//}

//else

Console.WriteLine(" Modified count for siteUrlCount : {0} & mobileUrlCount: {1}", countsiteurlprop, countmobileurlprop);

Console.WriteLine(Environment.NewLine + "Update done! Click to exit.");

Console.ReadLine();


}
//Enumerates all Alerts present on a Site Collection and modifies them

//so that wrong information (for example, in the SiteUrl column) is corrected.

static void ListAndFixAlerts(SPWeb spweb)


{
Console.WriteLine("\n{0} Alert(s) for site: {1} ({2})", spweb.Alerts.Count, spweb.Title, spweb.Url);

string oldurl = strOldString;

string newurl = strNewString;// spweb.Site.Url;

foreach (SPAlert alert in spweb.Alerts)


{
try


{


SPPropertyBag spprop = alert.Properties;

Console.WriteLine(" {2} Alert \"{0}\" for user \"{1}\" \n (Id: {3})\n", alert.Title, (alert.User != null ? alert.User.Name : "<unknown>"), alert.AlertFrequency.ToString(), alert.ID.ToString());

//Preserve the initial Alert frequency (Immed., Daily, Weekly).

SPAlertFrequency afPrevious = alert.AlertFrequency;

//Change the Alert frequency so the datarow inside

//is touched by SharePoint API.

if (afPrevious == SPAlertFrequency.Immediate)

alert.AlertFrequency = SPAlertFrequency.Weekly;

else

alert.AlertFrequency = SPAlertFrequency.Immediate;

try


{
if (spprop["siteurl"] != null) //fix hard coded properties


{
//Console.WriteLine("pre alert site url: " + spprop["siteurl"].ToString());

if (spprop["siteurl"].Contains(oldurl)) //found old link reference/


{
spprop["siteurl"] = spprop["siteurl"].Replace(oldurl, newurl);

//Console.WriteLine("post alert site url: " + spprop["siteurl"].ToString());

Console.WriteLine("Updated siteurl in properties");


countsiteurlprop++;

spprop.Update();

}

}

/*
if (spprop["mobileurl"] != null){

//Console.WriteLine("alert mobile url: " + spprop["mobileurl"].ToString());

if (spprop["mobileurl"].Contains(oldurl)) //found old link reference/


{
spprop["mobileurl"] = spprop["mobileurl"].Replace(oldurl, newurl);

Console.WriteLine("Updated mobileurl in properties");


countmobileurlprop++;

spprop.Update(); }}
*/



alert.Update();
//Change the Alert frequency back to the initial state.


alert.AlertFrequency = afPrevious;

alert.Update();

}
catch (Exception ex)


{
Console.WriteLine(" -> Error changing Alert. {0}", ex.Message);

} // inner try


}
catch (Exception ex)


{
Console.WriteLine(" An unexpected error occurred while accessing the Alert object: {0}", ex.Message);

} // outer try

} // foreach alert



//Handle all Sub-Webs recursively.

if (spweb.Webs.Count > 0)


{
for (int i = spweb.Webs.Count - 1; i >= 0; i--)


{
using (SPWeb spsubweb = spweb.Webs[i])


{

ListAndFixAlerts(spsubweb);
} // using spsubweb

} //for subwebs

} //if has subweb


}

}

}
 

Tuesday, 26 November 2013

Limiting the characters in Multi Line / Rich Text using jquery

<script language="javascript" src="/SiteAssets/jquery-1.7.1.min.js" type="text/javascript"></script>
 //site assets is the library where jquery is stored
<script type="text/javascript">  
var MaxLength = 90;
var mytxetArea = "Description"; //text area display name here

$(document).ready(function () {

$("textarea[title='" + mytxetArea + "']").keyup(function (e) {

 if ($(this).val().length > MaxLength) {
$(this).val($(this).val().substring(0, MaxLength));

}

});

$(
"textarea[title='" + mytxetArea + "']").keypress(function (e) {

if ($(this).val().length > MaxLength) {

e.preventDefault();

}

});

$(
"textarea[title='" + mytxetArea + "']").blur(function (e) {

if ($(this).val().length > MaxLength) {

$(this).val($(this).val().substring(0, MaxLength));

}

});

});

</script>

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;

        }
    }
}