Adding a Client Web Part (App Part) to a sharepoint page programmatically

2.3k views Asked by At

I have a requirement to add a Client Webpart from a provider hosted app, onto a page in the Host Web its deployed to. I have tried using the Client Object Model's Limited WebPart Manager to achieve this, but that only works for xml data that are part of .dwp or .webpart files. I have used the below code. Is there a workaround this, to get the App Part files from a site and add them to a Sharepoint Page?

        ClientContext clientconteext = new ClientContext("My Server URL");
        Microsoft.SharePoint.Client.File page = clientconteext.Web.GetFileByServerRelativeUrl("/sites/MySite/SitePages/Home.aspx");

        clientconteext.Load(clientconteext.Web);
        clientconteext.Load(page);
        clientconteext.ExecuteQuery();
        LimitedWebPartManager lwp= page.GetLimitedWebPartManager(PersonalizationScope.Shared);
        string webpartxml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Elements xmlns=\"http://schemas.microsoft.com/sharepoint/\"><WebPartPages:ClientWebPart runat=\"server\" FeatureId=\"5b1a14dd-8dbe-4963-8612-e7918e7fbc9a\" ProductWebId=\"5b1a14dd-8dbe-4963-8612-e7918e7fbc9a\" WebPartName=\"HomePageAppPart\" Title=\"Home App Part\" Description=\"WebPart Description\" WebPart=\"true\"></WebPartPages:ClientWebPart></Elements>";
        WebPartDefinition wpd = lwp.ImportWebPart(webpartxml);
        lwp.AddWebPart(wpd.WebPart, "Right", 1);
        clientconteext.ExecuteQuery();
1

There are 1 answers

0
Sebastián A On

This are the steps that you need to do.

  1. You need to add your app part to any page from browser
  2. In the Web Part Properties pane, expand the Advanced section, set the Export Mode to Export all data and click OK.

  1. In the App Part click on the drop down arrow next to the web part title and then Export

  1. Copy the .webpart file to the project (EX: Template folder)
  2. Add this methods to create a Publishing page and add the app part to it

    /// <summary>
    /// Create a Publising Page
    /// </summary>
    /// <param name="clientContext">Client context</param>
    /// <param name="pageName">Page Name</param>
    /// <param name="pagelayoutname">Page Layout Name</param>
    public static File CreatePublishingPage(ClientContext clientContext, string pageName, string pagelayoutname)
    {
        var publishingPageName = pageName + ".aspx";
    
        Web web = clientContext.Web;
        clientContext.Load(web);
    
        List pages = web.GetListByUrl("/Pages/");
        clientContext.Load(pages.RootFolder, f => f.ServerRelativeUrl);
        clientContext.ExecuteQuery();
    
        Microsoft.SharePoint.Client.File file =
            web.GetFileByServerRelativeUrl(pages.RootFolder.ServerRelativeUrl + "/" + pageName + ".aspx");
        clientContext.Load(file, f => f.Exists);
        clientContext.ExecuteQuery();
        if (file.Exists)
        {
            file.DeleteObject();
            clientContext.ExecuteQuery();
        }
        PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(clientContext, web);
        clientContext.Load(publishingWeb);
    
        if (publishingWeb != null)
        {
            List publishingLayouts = clientContext.Site.RootWeb.GetListByUrl("/_catalogs/masterpage/");
    
            ListItemCollection allItems = publishingLayouts.GetItems(CamlQuery.CreateAllItemsQuery());
            clientContext.Load(allItems, items => items.Include(item => item.DisplayName).Where(obj => obj.DisplayName == pagelayoutname));
            clientContext.ExecuteQuery();
    
            ListItem layout = allItems.Where(x => x.DisplayName == pagelayoutname).FirstOrDefault();
            clientContext.Load(layout);
    
            PublishingPageInformation publishingpageInfo = new PublishingPageInformation()
            {
                Name = publishingPageName,
                PageLayoutListItem = layout,
            };
    
            PublishingPage publishingPage = publishingWeb.AddPublishingPage(publishingpageInfo);
            publishingPage.ListItem.File.CheckIn(string.Empty, CheckinType.MajorCheckIn);
            publishingPage.ListItem.File.Publish(string.Empty);
            clientContext.Load(publishingPage);
            clientContext.ExecuteQuery();
            return publishingPage.ListItem.File;
        }
        return null;
    }
    
    /// <summary>
    /// Adds the Web Part to the page
    /// </summary>
    /// <param name="clientContext">Client Context</param>
    /// <param name="newWeb">New Web</param>
    public static void AddWebpartToWebPartPage(ClientContext clientContext, File file)
    {
        file.CheckOut();
    
        //Get webparts xml
        string webpart = System.IO.File.ReadAllText(System.Web.Hosting.HostingEnvironment.MapPath(string.Format("~/{0}", "Template/RegistroDeSolicitudes.webpart")));
    
        // Requires Full Control permissions on the Web
        LimitedWebPartManager wpmgr = file.GetLimitedWebPartManager(PersonalizationScope.Shared);
        WebPartDefinition wpd = wpmgr.ImportWebPart(webpart);
        wpmgr.AddWebPart(wpd.WebPart, "Header", 0);
        file.CheckIn(String.Empty, CheckinType.MajorCheckIn);
        file.Publish(string.Empty);
        clientContext.ExecuteQuery();
    }
    

And call the methods:

Microsoft.SharePoint.Client.File publishingPage = Helpers.CreatePublishingPage(cc, "Solicitudes", "BlankWebPartPage");
Helpers.AddRegistroDeSolicitudesWebpartToWebPartPage(cc, publishingPage);