Monday, May 28, 2012

Ways of adding a Custom or OOB Webparts to a Sharepoint Site programmatically.

Through onet.xml if you have a customized SharePoint Site Definition :

 In the <Module></Module>  (which is within <Modules></Modules> node)  node of onet.xml file, we have another child node <File></File>. After identifying this node we need to get our file through its Url property and after that need to put our web part code in in xslt format. Code will be as below:

 <File Url="Home.aspx"  NavBarHome="True" Type="Ghostable">

          <AllUsersWebPart WebPartZoneID="Left" WebPartOrder="1">
              <![CDATA[         
          <WebPart xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/WebPart/v2">
          <Assembly>MyProject1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=116306ce04211e35</Assembly>
          <TypeName>MyProject1.WebPart1</TypeName>
          <FrameType>None</FrameType>
          <Title>My Custom Web Part</Title>         
          <PartStorage xmlns="http://schemas.microsoft.com/WebPart/v2/Xml" />
          </WebPart>
         ]]>

          </AllUsersWebPart>
          

<AllUsersWebPart WebPartZoneID="Left" WebPartOrder="5">
              <![CDATA[
         <WebPart xmlns="http://schemas.microsoft.com/WebPart/v2"
         xmlns:cewp="http://schemas.microsoft.com/WebPart/v2/ContentEditor">
         <Assembly>Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>
         <TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>
         <Title>Content Editor Webpart Demo</Title>
         <FrameType>None</FrameType>
        <cewp:Content>
         &lt;link href=&quot;/_layouts/Styles/GlobalStyles.css&quot; rel=&quot;Stylesheet&quot; type=&quot;text/css&quot; /&gt;<br />
         &lt;table cellSpacing=&quot;0&quot; class=&quot;tbl-Webpart&quot;&gt;<br />
          &lt;tr class=&quot;tr-WebpartHeading&quot;&gt;<br />
            &lt;td  colspan=&quot;3&quot; class=&quot;tc-WebpartHeading&quot;&gt; <br />
              My Learning<br />
              &lt;tr class=&quot;tr-WebpartSubHeading&quot;&gt;<br />
            &lt;td  colspan=&quot;3&quot; class=&quot;tc-WebpartSubHeading&quot;&gt; <br />
              Use the resource below to start to develop or enhance those skills<br />
           &lt;/td&gt;<br />
        &lt;/tr&gt;<br />
        &lt;tr&gt;<br />
          &lt;td &gt;<br />
          &lt;img  src=&quot;/_layouts/Images/MyLearningLogo.jpg&quot; /&gt;<br />
        
         &lt;td &gt;<br />
            &lt;a href=&quot;./Pages/Page1.aspx&quot;&gt; &lt;img src=&quot;/_layouts/Images/StartNow.jpg&quot; /&gt;&lt;/a&gt;<br />
            Sample text&lt;b&gt; integrated&lt;/br&gt;  Sample text &lt;/b&gt; &lt;/br&gt;  Sample text,&lt;/br&gt; region and group<br />
         &lt;/td&gt;<br />
        &lt;td &gt;<br />
        &lt;img src=&quot;/_layouts/Images/Calender.jpg&quot; &gt;<br />
          &lt;a href =&quot;./Pages/page2.aspx&quot; &gt;Sample Text &lt;/a&gt;<br />
        &lt;/td&gt;<br />
      &lt;/tr&gt;<br />
    &lt;/table&gt;
       
       
     </cewp:Content>
     </WebPart>]]>
</AllUsersWebPart>
</File>

The content highlighted with light blue colour shows the way of adding an custom Webpart My Custom Web Part including Assembly and Class Name which contains it. However content with another background  adding an OOB webpart here it is  Content Editor Webpart Content Editor Webpart Demo within cewp tags. You can any other webpart in place of these. 

Through avtivation of a feature in a existing SharePoint Site :


We just need to call these two methods to on feature activation to add a webpart programmatically:

First Call this method to check that webpart exists in current page or not ?

 private static bool CheckWebPartExist(SPWeb site, string PageUrl, string title)
        {
            bool CheckWebPartExist = false;
            SPWebPartCollection webparts = site.GetWebPartCollection(PageUrl, Storage.Shared);
            foreach (ContentEditorWebPart contentEditorWP in webparts)
            {
                if (contentEditorWP.Title == title)
                {
                    CheckWebPartExist = true;
                    break;
                }
            }
            return CheckWebPartExist;
        }

For adding a Content editor webpart :

private static void AddContentEditorWebPartToPage(SPWeb site, string PageUrl, string ZoneID, string title, string InnerText, bool CheckWebPartExist)
        {
            if (!CheckWebPartExist)
            {
                using (SPLimitedWebPartManager webpartsOnTheJob = site.GetLimitedWebPartManager(PageUrl, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
                {
                    //SPLimitedWebPartManager webpartsOnTheJob = site.GetLimitedWebPartManager(PageUrl, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
                    ContentEditorWebPart contentEditorWP = new ContentEditorWebPart();

                    //set properties of new webpart object    
                    contentEditorWP.ZoneID = ZoneID;
                    contentEditorWP.Title = title;
                    contentEditorWP.ChromeState = System.Web.UI.WebControls.WebParts.PartChromeState.Normal;
                    contentEditorWP.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.None;
                    //Add content to CEWP
                    XmlDocument xmlDoc = new XmlDocument();
                    XmlElement xmlElement = xmlDoc.CreateElement("Root");
                    xmlElement.InnerText = InnerText;
                    contentEditorWP.Content = xmlElement;
                    contentEditorWP.Content.InnerText = xmlElement.InnerText;
                    //Adding Web part to page.
                    webpartsOnTheJob.AddWebPart(contentEditorWP, contentEditorWP.ZoneID, 0);

                }

            }
        }

Now for adding a custom webpart :

 private void AddCustomWebpartsToPage(SPWeb objSPWeb, string strPageUrl, string strWebpartName, string zoneID, int zoneIndex, bool CheckWebPartExist)
        {
                if (!CheckWebPartExist)
                {
                    using (SPLimitedWebPartManager webPartManager = objSPWeb.GetLimitedWebPartManager(
                            strPageUrl, PersonalizationScope.Shared))
                    {
                        SPListItemCollection webParts;
                        bool isExists = CheckIfWebPartExistsInGallery(objSPWeb, strWebpartName, webPartManager, out webParts);
                        if (isExists)
                        {
                            using (System.Web.UI.WebControls.WebParts.WebPart webPart = CreateWebPart(objSPWeb, strWebpartName, webPartManager, webParts))
                            {
                                webPart.ChromeType = PartChromeType.None;
                                webPartManager.AddWebPart(webPart, zoneID, zoneIndex);
                            }
                        }
                    }
                }
            }



Check for Custom Webpart Exists in Page or not :

private bool CheckWebPartExist(SPWeb site, string PageUrl, string title)
{
bool CheckWebPartExist = false;
SPWebPartCollection webparts = site.GetWebPartCollection(PageUrl, Storage.Shared);
foreach (System.Web.UI.WebControls.WebParts.WebPart contentEditorWP in webparts)
{
if (contentEditorWP.Title == title)
{
CheckWebPartExist = true;
break;
}
}
return CheckWebPartExist;
}
Chaeck for custom webpart exists in WebPart Gallery or not :

private static bool CheckIfWebPartExistsInGallery(SPWeb web, string webPartName, SPLimitedWebPartManager webPartManager, out SPListItemCollection webParts)
{
bool isExists = false;
SPQuery qry = new SPQuery();
qry.Query = String.Format(CultureInfo.CurrentCulture,
"<Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='File'>{0}</Value></Eq></Where>",
webPartName);
SPList webPartGallery = null;
if (null == web.ParentWeb)
{
webPartGallery = web.GetCatalog(SPListTemplateType.WebPartCatalog);
}
else
{
webPartGallery = web.Site.RootWeb.GetCatalog(SPListTemplateType.WebPartCatalog);
}
webParts = webPartGallery.GetItems(qry);
if (webParts.Count > 0)
{
isExists = true;
}
else
{
isExists = false;
}
return isExists;
}

Create WebPart Custom Webpart instance through code
public static System.Web.UI.WebControls.WebParts.WebPart CreateWebPart(SPWeb web, string webPartName, SPLimitedWebPartManager webPartManager, SPListItemCollection webParts)
{
XmlReader xmlReader = new XmlTextReader(webParts[0].File.OpenBinaryStream());
string errorMsg;
System.Web.UI.WebControls.WebParts.WebPart webPart = webPartManager.ImportWebPart(xmlReader, out errorMsg);
return webPart;
}  All you need to provide is thses parameters correctly.

No comments:

Post a Comment