Responsive Ads Here

Tuesday, July 17, 2012

Adding / Removing web part to page using server object model in SharePoint

Using Farm solution we can develop and deploy the visual web parts.  When we deployed the farm solutions,  the visual web parts will be added to the web parts gallery.

Generally we will add the visual web parts to the page manually, but it will be difficult in real time, because when we are moving from one environment to another it will be very difficult.

In my recent project i have a requirement to add a web part to the page when we deploy the solution to SharePoint. In feature activation the web part needs to be added automatically.

Below code snippet will give complete idea about how to add web part to the page.

/// <summary>
/// Adds the Web Part to Page
/// </summary>
/// <param name="pageUrl">Page Url for the Page</param>
/// <param name="webpartUrl">Web Part url for the same</param>
/// <param name="web">SPWeb Object</param>
public static void AddWebPartToPage(string pageUrl, string webpartUrl, string zone, int zoneIndex, SPWeb web)
{
   // TO DO : Check for existence of web part
   SPFile page = default(SPFile);
   try
   {
      page = web.GetFile(pageUrl);
      if (page.Exists)
      {
         if (page.CheckOutType == SPFile.SPCheckOutType.Online)
         {
            throw new Exception("Page is already checked Out. Please check in or discard checkout before activating features");
         }

         page.CheckOut();
      using (SPLimitedWebPartManager manager = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
      {
           string errorMessage = string.Empty;
           if (!web.IsRootWeb)
           {
              web = web.Site.RootWeb;
           }
           SPFile myWebPart = web.GetFile(webpartUrl);
         //SPFile myWebPart = web.GetFile("_catalogs/wp/myWebPart.webpart");
           XmlReader xml = XmlReader.Create(myWebPart.OpenBinaryStream());
           var wp = manager.ImportWebPart(xml, out errorMessage);
           manager.AddWebPart(wp, zone, zoneIndex);
           manager.SaveChanges(wp);
       }
           page.CheckIn("Adding WebParts", SPCheckinType.MajorCheckIn);
           page.Publish("Publishing Page");
    }
    else
    {
        throw new Exception("Page Not found for adding staff web parts");
    }
}
catch (Exception ex)
{
              
   throw ex;
}
finally
{
   // This is to ensure next time when feature is activated if there is error in previous activation its taken care
   if (page != null && page.CheckOutType == SPFile.SPCheckOutType.Online)
   {
       page.UndoCheckOut();
   }
}
}


No comments:

Post a Comment