Wednesday, 31 December 2014

Add Custom Webppart to MySite Sharepoint -II

If you want to modify MySite with custom web part, here is the solution.


SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPWeb web = siteCollection.OpenWeb())
{
if (web.WebTemplate == "SPSMSITEHOST")
{
//User Info Webpart
AddWebPartToPage(web, "Person.aspx", "UserInformation", "TopZone", 1);                          
}
}
});

Support Methods:

/// <summary>
/// Method to Get the custom web part
/// </summary>
/// <param name="web">web Url</param>
/// <param name="pageUrl">Page Name</param>
/// <param name="webPartName">Webpart name</param>
/// <param name="zoneID">Zone where you want to deploy webpart</param>
/// <param name="zoneIndex">Zone index</param>
/// <returns></returns>
public static string AddWebPartToPage(SPWeb web, string pageUrl, string webPartName, string zoneID, int zoneIndex)
{
using (SPLimitedWebPartManager manager = web.GetLimitedWebPartManager(pageUrl, PersonalizationScope.Shared))
{
IList<System.Web.UI.WebControls.WebParts.WebPart> _listFormWebParts = (from _wp in manager.WebParts.Cast<System.Web.UI.WebControls.WebParts.WebPart>()
  where string.Compare(_wp.Title, webPartName, true) == 0
  select _wp).ToList();

//Check if there are any web parts found
if (_listFormWebParts == null || _listFormWebParts.Count == 0)
{
using (System.Web.UI.WebControls.WebParts.WebPart webPart = CreateWebPart(web, webPartName, manager))
{
if (webPart != null)
{
manager.AddWebPart(webPart, zoneID, zoneIndex);
return webPart.ID;
}
else
return "Web part not found";
}
}
else
return "exists";
}
}

/// <summary>
/// Create webpart from webpart template
/// </summary>
/// <param name="web">Web Url</param>
/// <param name="webPartName">webpart template name</param>
/// <param name="manager">SPLimitedWebPartManager object</param>
/// <returns></returns>
public static System.Web.UI.WebControls.WebParts.WebPart CreateWebPart(SPWeb web, string webPartName, SPLimitedWebPartManager manager)
{
SPQuery query = new SPQuery();
//query.Query = String.Format(CultureInfo.CurrentCulture, "&lt;Where&gt;&lt;Eq&gt;&lt;FieldRef Name='FileLeafRef'/&gt;&lt;Value Type='File'&gt;{0}&lt;/Value&gt;&lt;/Eq&gt;&lt;/Where&gt;", webPartName);

query.Query = String.Concat("<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + webPartName + "</Value></Eq></Where>");
SPList webPartGallery = null;
if (null == web.ParentWeb)
{
webPartGallery = web.GetCatalog(SPListTemplateType.WebPartCatalog);
}
else
{
webPartGallery = web.Site.RootWeb.GetCatalog(SPListTemplateType.WebPartCatalog);
}          

SPListItemCollection webParts = webPartGallery.GetItems(query);
if (webParts == null)
{
return null;
}
XmlReader xmlReader = new XmlTextReader(webParts[0].File.OpenBinaryStream());
string errorMessage;
System.Web.UI.WebControls.WebParts.WebPart webPart = manager.ImportWebPart(xmlReader, out errorMessage);
webPart.ChromeType = PartChromeType.None;
return webPart;
}

No comments:

Post a Comment