Monday 23 April 2012

SharePoint 2010 Master Pages - Retrieve, Upload and Apply programmatically


protected void Page_Load(object sender, EventArgs e)
{
 try
 { 
  if (!(Page.IsPostBack))
  {
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
     using (SPSite pageLoadSite = new SPSite(SPContext.Current.Site.ID))
     {
      pageLoadSite.AllowUnsafeUpdates = true;

      using (SPWeb pageLoadWeb = pageLoadSite.OpenWeb())
      {
       pageLoadWeb.AllowUnsafeUpdates = true;

       GetMasterPages(pageLoadWeb);
       UploadMasterPageInMasterPageGallery(pageLoadWeb);
       SetMasterPage(pageLoadWeb);

       pageLoadWeb.AllowUnsafeUpdates = false;
      }
     pageLoadSite.AllowUnsafeUpdates = false;
    }
   });
  }
 }
 catch (Exception ex)
 {
  Throw ex;
 }
}


/// <summary>
/// Retrieves master pages from the master page gallery
/// </summary>
/// <param name="web">spweb object</param>
private void GetMasterPages(SPWeb web)
{
 try
 {
  SPDocumentLibrary masterPageGallery =        
      (SPDocumentLibrary)web.GetCatalog(SPListTemplateType.MasterPageCatalog);

  foreach (SPListItem masterPage in masterPageGallery.Items)
  {
    string displayName = masterPage.DisplayName
    string name = masterPage.Name;
  }

   
   string currentMasterFileName =  
          web.MasterUrl.Substring(web.MasterUrl.LastIndexOf('/') +    
                                  1);
 }
 catch (Exception ex)
 {
  throw new Exception("Exception in RetrieveMasterPages(). Message: " +  
                      ex.Message);
 }
}


/// <summary>
/// Uploads the master page file to master page gallery.
/// </summary>
/// <param name="web">spweb object</param>
private void UploadMasterPageInMasterPageGallery(SPWeb web)
{
 try
 {
  // fuMasterPage is upload control in my project.
  SPDocumentLibrary masterPageGallery =     
       (SPDocumentLibrary)web.GetCatalog(SPListTemplateType.MasterPageCatalog);
  masterPageGallery.RootFolder.Files.Add(
                    masterPageGallery.RootFolder.ServerRelativeUrl 
                            + "/"  
                            + fuMasterPage.FileName, 
                    fuMasterPage.FileBytes,                        
                    true);
  masterPageGallery.Update();
 }
 catch (Exception ex)
 {
    Throw ex;
 }
}


/// <summary>
/// Sets master page for the site.
/// </summary>
/// <param name="web">Website for which master page is to be set.</param>
private void SetMasterPage(SPWeb web)
{
 try
 {
  web.MasterUrl = string.Format("{0}/_catalogs/masterpage/{1}",  
                                 web.ServerRelativeUrl.TrimEnd('/'),          
                                 "MyMater.Master");
  web.Update();
 }
 catch (Exception ex)
 {
  throw new Exception("Unable to set master page for site "
                        + web.Title   
                        + ". Error: " +  
                     ex.Message);
 }
}

No comments:

Post a Comment