Tuesday, April 14, 2015

Download HTML Page Programmatically C#


using (WebClient client = new WebClient()) // WebClient class inherits IDisposable
               {
                   ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(delegate { return true; });
// If credentials is required use this below line
                   client.Credentials = new System.Net.NetworkCredential("UserId", "Password", "DomainName");

                   // you can get the file content without saving it:
                   strHtmlCode = client.DownloadString(htmlDisplyFormUrl);

                   FileStream fStream = new System.IO.FileStream(@"D:\HtmlFolder\Sample.Html", System.IO.FileMode.Create);
                   byte[] b = System.Text.Encoding.UTF8.GetBytes(strHtmlCode);
                   fStream.Write(b, 0, b.Length);
                   fStream.Close();
                   //...
               }

Overwrite the values in New/Edit Form using PreSaveMethod in SharePoint


function PreSaveItem()
{

var titleid = document.querySelector("input[title='Sitting DateTime']").id;
var calval=document.getElementById(titleid).value;
var calYear=calval.split('/')[2];
var calMonth=calval.split('/')[0];
var YearID= document.querySelector("input[title='Year']").id;
document.getElementById(YearID).value=calYear;
var mnth='';
switch (calMonth)
{
case '1':
  mnth="January";
  break;
case '2':
 mnth="February";
  break;
case '3':
  mnth="March";
  break;
case '4':
  mnth="April";
  break;
case '5':
  mnth="May";
  break;
case '6':
  mnth="June";
  break;
case '7':
  mnth="July";
  break;

case '8':
  mnth="August";
  break;

case '9':
  mnth="September";
  break;

case '10':
  mnth="October";
  break;
case '11':
  mnth="November";
  break;

case '12':
  mnth="December";
  break;


}
var MonthID= document.querySelector("input[title='Month']").id;

document.getElementById(MonthID).value=mnth;
return true;
}

How to Hide the fields at Edit Form in SharePoint using jQuery


$(document).ready(function() {
/*For TextBox*/
         var hYear= document.querySelector("input[title='Year']").id;
/*For Choice Field*/
                      var hCategory= document.querySelector("select[title='Division Category']").id;
                     (((document.getElementById(hYear).parentNode).parentNode).parentNode).style.display="none";
                                 
                                    (((document.getElementById(hCategory).parentNode).parentNode).parentNode).style.display="none";
                                   });

How to change the SharePoint master page for wiki page at runtime



public class ChangeMasterPage : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
        }

        void context_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            string requestUrl = HttpContext.Current.Request.Url.ToString();
            if (!requestUrl.Contains("aspx"))
                return;
            Page page = HttpContext.Current.CurrentHandler as Page;

            if (page != null)
            {
                // register handler for PreInit event
                page.PreInit += new EventHandler(page_PreInit);
            }
        }

        void page_PreInit(object sender, EventArgs e)
        {
            Page page = sender as Page;

            if (page != null)
            {
               
                   
                    string strMasterUrl = string.Empty;

                   
                        strMasterUrl = "_catalogs/masterpage/MyMasterPage.master";
                   
                    // if (Context.Request.LogonUserIdentity.IsAnonymous)
                    {
                        SPWeb web = SPContext.Current.Web;
                        page.MasterPageFile = web.ServerRelativeUrl + strMasterUrl;
                    }


               
            }
        }
        public void Dispose() { }
    }

Thursday, April 9, 2015

Copy Documents from One Library to another including Nested folder in Sharepoint


1. Program file

 #region global variables
        static SPListItem objItemDisp;
        static SPWeb objSourceWeb;
        static SPWeb objDestinationWeb;
        static SPFileCollection spFileCol = null;
        static string strStrsourceLib ;
        static string strStrdestinationLib ;
        static string strSiteUrl ;
        #endregion
        static void Main(string[] args)
        {
            ///Getting site url form Config File
            strSiteUrl = ConfigurationManager.AppSettings["SiteURL"].ToString();
            ///Reading Source Library Name form Config File
            strStrsourceLib = ConfigurationManager.AppSettings["SourceLib"].ToString();
            ///Reading Destination Library Name form Config File
            strStrdestinationLib = ConfigurationManager.AppSettings["DestiLib"].ToString();
            /// Start Process
            StartCopyDoc();
        }
        /// <summary>
        /// Initiate the process...
        /// </summary>
        private static void StartCopyDoc()
        {
            using (SPSite site = new SPSite(strSiteUrl))
            {
                try
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        objSourceWeb = web;
                        objDestinationWeb = web;
                        objDestinationWeb.AllowUnsafeUpdates = true;
                        SPDocumentLibrary source_lib = objSourceWeb.Lists[strStrsourceLib] as SPDocumentLibrary;
                        SPFileCollection source_files = source_lib.RootFolder.Files;
                        RootFolderFile(source_files);
                        SPFolderCollection folders = web.GetFolder(strStrsourceLib).SubFolders;
                        SubFolders(folders);
                        objDestinationWeb.AllowUnsafeUpdates = false;
                    }
                }
                catch (Exception ex)
                {

                }
            }
        }

        /// <summary>
        /// Iteration method to fetch the doc. from nested folder
        /// </summary>
        /// <param name="folders"></param>
        private static void SubFolders(SPFolderCollection folders)
        {
                foreach (SPFolder spFolder in folders)
                {
                    if (!spFolder.Name.Equals("Forms"))
                    {
                        int len = spFolder.ToString().IndexOf('/');
                        string folderName = spFolder.ToString().Substring(len + 1);
                        SPFileCollection source_SubFolderfiles = spFolder.Files;
                        CreateFolder(spFolder, folderName);
                        RootFolderFile(source_SubFolderfiles, folderName);
                        SubFolders(spFolder.SubFolders);
                    }
                }
        }

        /// <summary>
        /// Add doc. to destination lib. in root level
        /// </summary>
        /// <param name="source_files"></param>
        private static void RootFolderFile(SPFileCollection source_files)
        {
            SPDocumentLibrary destination_lib = objDestinationWeb.Lists[strStrdestinationLib] as SPDocumentLibrary;
            foreach (SPFile file in source_files)
            {
                object modified_by = file.Item["Editor"];
                object modified = file.Item["Modified"];
                object created_by = file.Item["Author"];
                SPFileCollection destination_files = destination_lib.RootFolder.Files;
                byte[] filebytes = file.OpenBinary();
                SPFile disp_file = destination_files.Add(destination_lib.RootFolder.Url + "/" + file.Name, filebytes, true);
             
                objItemDisp = disp_file.Item as SPListItem;
                objItemDisp.ParentList.Fields["Modified By"].ReadOnlyField = false;
                objItemDisp.ParentList.Fields["Modified"].ReadOnlyField = false;
                objItemDisp.ParentList.Fields["Created By"].ReadOnlyField = false;

                objItemDisp["Editor"] = modified_by;
                objItemDisp["Modified"] = modified;
                objItemDisp["Author"] = created_by;
                disp_file.Item.Update();
            }
        }

        /// <summary>
        /// Add doc. to Destination lib. in folder level
        /// </summary>
        /// <param name="source_files"></param>
        /// <param name="strFolder"></param>
        private static void RootFolderFile(SPFileCollection source_files,string strFolder)
        {
           SPDocumentLibrary destination_lib = objDestinationWeb.Lists[strStrdestinationLib] as SPDocumentLibrary;
            foreach (SPFile file in source_files)
            {
                object modified_by = file.Item["Editor"];
                object modified = file.Item["Modified"];
                object created_by = file.Item["Author"];
                SPFolderCollection folders = objDestinationWeb.GetFolder(strStrdestinationLib).SubFolders;
                spFileCol = null;
                SPFileCollection destination_files = DestinFileCollection(folders,strFolder);
             
                byte[] filebytes = file.OpenBinary();

                SPFile disp_file = destination_files.Add(destination_lib.RootFolder.Url + "/" +strFolder+"/"+ file.Name, filebytes, true);

                objItemDisp = disp_file.Item as SPListItem;
                objItemDisp.ParentList.Fields["Modified By"].ReadOnlyField = false;
                objItemDisp.ParentList.Fields["Modified"].ReadOnlyField = false;
                objItemDisp.ParentList.Fields["Created By"].ReadOnlyField = false;

                objItemDisp["Editor"] = modified_by;
                objItemDisp["Modified"] = modified;
                objItemDisp["Author"] = created_by;
                disp_file.Item.Update();
            }
        }
     
        /// <summary>
        /// get distination nested folder filecollection
        /// </summary>
        /// <param name="folders"></param>
        /// <param name="fdUrl"></param>
        /// <returns></returns>
        private static SPFileCollection DestinFileCollection(SPFolderCollection folders, string fdUrl)
        {
            foreach (SPFolder spFolder in folders)
            {
                if (!spFolder.Name.Equals("Forms"))
                {
                    int len = spFolder.ToString().IndexOf('/');
                    string folderName = spFolder.ToString().Substring(len + 1);
                    if (folderName.Equals(fdUrl))
                    {
                        spFileCol = spFolder.Files;
                        break;
                    }

                    DestinFileCollection(spFolder.SubFolders, fdUrl);
                }
            }
            return spFileCol;
        }

        /// <summary>
        /// Create folders at destination lib.
        /// </summary>
        /// <param name="spFolder"></param>
        /// <param name="fldURL"></param>
      private static void CreateFolder(SPFolder spFolder,string fldURL)
        {
            using (SPSite site=new SPSite(strSiteUrl))
            {
                using (SPWeb web=site.OpenWeb())
                {
                    object modified_by = spFolder.Item["Editor"];
                    object modified = spFolder.Item["Modified"];
                    object created = spFolder.Item["Created"];
                    object created_by = spFolder.Item["Author"];

                      SPDocumentLibrary destination_lib = objDestinationWeb.Lists[strStrdestinationLib] as SPDocumentLibrary;

                      SPFolderCollection spFolderCol = web.Folders;
                      spFolderCol.Add(strSiteUrl + "/" + strStrdestinationLib + "/" + fldURL + "/");
                    SPFolder spf=web.GetFolder(strSiteUrl + "/" + strStrdestinationLib + "/" + fldURL );
                    SPListItem objDisp = spf.Item as SPListItem;
                    objDisp.ParentList.Fields["Modified By"].ReadOnlyField = false;
                    objDisp.ParentList.Fields["Modified"].ReadOnlyField = false;
                    objDisp.ParentList.Fields["Created By"].ReadOnlyField = false;
                    objDisp["Editor"] = modified_by;
                objDisp["Modified"] = modified;
                objDisp["Author"] = created_by;
                spf.Item.Update();

                      destination_lib.Update();
                }
               
            }
       
        }

2. configuration file

 <appSettings>
    <add key="SiteURL" value="http://sp2013vm:1616/sites/HSE"/>
    <add key="SourceLib" value="Test1"/>
    <add key="DestiLib" value="Test2"/>
  </appSettings>