Wednesday, 16 April 2014

Duplicate web parts on page

So you've created a page layout or a site page that has a webpart deployed to the page through the Elements.xml file in the module that contains your page(s) and now every time you deploy the module you get duplicate web parts, one for every deploy... rather annoying.

to get around this you need to write some code in your event receiver to either iterate over all the webparts on the page delete them and just add yours back in, or iterate over all of the webparts and remove all but the first one.

public void RemoveExtraWebParts(SPSite site)
{
    //Make sure its actually a site
    if (site != null)
    {
        //get the sites root web
        var web = site.RootWeb;

        //Grab the root webs pages gallery
        var pages = web.GetList("Pages");

        //Itterate through all pages
        foreach (SPListItem li in pages.Items)
        {
            //create a check for pages that end in 401.aspx or 404.aspx
            var r = new Regex(@".40[1,4]\.aspx$");

            //Check if page url matches above regex
            if (r.IsMatch(li.Url))
            {
                SPFile page = li.File;

                try
                {
                    //Check out the page if need be
                    if (page.RequiresCheckout)
                        page.CheckOut();

//move through all webparts on page, remove all but the first one(declared by us)
                    //but only if it's a Content Editor webpart
                    using (var mgr =
                        page.GetLimitedWebPartManager(
PersonalizationScope.Shared))
                        if (mgr.WebParts.Count > 1)
                            for (int i = mgr.WebParts.Count - 1; i > 0; i--)
                            {
                                var wp = mgr.WebParts[i];
                                if (wp.Title.Equals("Content Editor"))
                                    mgr.DeleteWebPart(mgr.WebParts[i]);
                            }

                    page.CheckIn("Checked in by feature reciever");
                    page.Approve("Approved By feature reciever");
                }
                catch (Exception)
                {
                    page.UndoCheckOut();
                }
            }
        }
    }

}