Monday, May 11, 2015

Get all the web parts id of particular page using REST API.

The below code used to get the all the web parts id for the particular page.

function GetWebParts() {
    var executor = new SP.RequestExecutor(appweburl);
    var urltest = appweburl + "/_api/SP.AppContextSite(@target)/web/getfilebyserverrelativeurl('/sites/test017/Pages/default.aspx')/getlimitedwebpartmanager(scope=0)/WebParts?@target='" + hostweburl + "'";
    $.ajax({
        url: urltest,
        method: "GET",
        async: false,
        headers: {
            Accept: "application/json; odata=verbose"
        },
        success: function (data) {
            var d = "";
            if (data.d.results.length > 0) {
                for (var i = 0; i < data.d.results.length; i++) {
                    d += "<div>" + data.d.results[i].Id + "</div>"
                }
                $("#appWebLists").html(d);
            }
        },
        error: function (n) {
            SP.UI.Notify.addNotification("<span>Request failed. " + n.status + "\n" + n.statusText + "<\/span>");
        }
    });
}

Saturday, May 9, 2015

Add or Replace Existing Publishing Page Web Parts with SharePoint App Parts using App Model Approach (Provider Hosted)

The below code is tested and i am able to add app parts to the existing publishing page.

In Publishing Page the web parts can also be added in "PublishingPageContent" and "RichHTMLField"

if you are migrating from SharePoint 2010 custom web parts to App Parts which has lot of work around. especially in the case of existing publishing page which has lot of custom web parts, we cant get the zone id properly.  

Use the below code to add app part to the existing publishing page. However we could replace the existing web part with app part using web part id. 

protected void ReplaceWebPartsWithAppParts_Click(object sender, EventArgs e)
        {
            var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(clientContext, clientContext.Web);
                // Get a few properties from the web
                clientContext.Load(publishingWeb);
                clientContext.ExecuteQuery();
                //Read the pages library name from the web properties
                //var pagesListName = web.AllProperties["Pages"] as string;
                var list = publishingWeb.Web.Lists.GetByTitle("Pages");
                var items = list.GetItems(CamlQuery.CreateAllItemsQuery());
                //make sure to include the File on each Item fetched
                clientContext.Load(items,
                                   i => i.Include(item => item.File, item => item["PublishingPageContent"]));
                clientContext.ExecuteQuery();
                // Iterate through all available pages in the pages list
                foreach (var item in items)
                {
                    FindWebPartForReplacement(item, clientContext, clientContext.Web);
                }
            }
        }




 private static void FindWebPartForReplacement(ListItem item, ClientContext clientContext, Web web)
        {
            PublishingPage publishingPage = PublishingPage.GetPublishingPage(clientContext, item);

            clientContext.Load(publishingPage);
            clientContext.ExecuteQuery();

            File page = publishingPage.ListItem.File;

            // Requires Full Control permissions on the Web
            LimitedWebPartManager webPartManager = publishingPage.ListItem.File.GetLimitedWebPartManager(PersonalizationScope.Shared);
            clientContext.Load(webPartManager,
                                wpm => wpm.WebParts,
                                wpm => wpm.WebParts.Include(wp => wp.WebPart.Title));
            clientContext.ExecuteQuery();

            foreach (var oldWebPartDefinition in webPartManager.WebParts)
            {
                var oldWebPart = oldWebPartDefinition.WebPart;
                // only modify if we find the old web part
                if (oldWebPart.Title != oldWebPartTitle) continue;

                // Check out the page for editing
                PublishingHelper.CheckOutFile(web, publishingPage.ListItem);

                // transform the xml into a web part definition
                WebPartDefinition definition = webPartManager.ImportWebPart(appPartXml);
                webPartManager.AddWebPart(definition.WebPart, "wpz", 0);

                clientContext.Load(webPartManager,
                                  wpm => wpm.WebParts,
                                  wpm => wpm.WebParts.Include(wp => wp.WebPart.TitleUrl, wp => wp.Id, wp => wp.WebPart.Title));
                clientContext.ExecuteQuery();

                string marker = string.Empty;
                int i = 0;
                foreach (WebPartDefinition wpd in webPartManager.WebParts)
                {
                    Guid storageKey = webPartManager.WebParts[i].Id;

                    if (wpd.WebPart.Title == "WelcomeAppPart Title")
                    {
                        clientContext.Load(publishingPage, p => p.ListItem, p => p.ListItem["PublishingPageContent"]);
                        clientContext.ExecuteQuery();

                        marker = String.Format(CultureInfo.InvariantCulture, "<div class=\"ms-rtestate-read ms-rte-wpbox\" contentEditable=\"false\"><div class=\"ms-rtestate-notify ms-rtestate-read {0}\" id=\"div_{0}\"></div><div style=\"display:none\" id=\"vid_{0}\"></div></div>", new object[] { storageKey.ToString("D") });
                        publishingPage.ListItem["PublishingPageContent"] += marker;
                        publishingPage.ListItem.Update();
                    }
                    i++;
                }

                clientContext.Load(page, p => p.CheckOutType, p => p.Level);
                clientContext.ExecuteQuery();
                PublishingHelper.CheckInPublishAndApproveFile(page);
                break;
            }
        }

Tuesday, January 6, 2015

SharePoint Workflow Association to SharePoint List

The below code is used to associate the workflow to the list as well as the update the workflow association to the sharepoint list

 // Add workflow association to my list
                        if (hasWorkflowAssociation == null)
                        {
                            sharePointSitesList.WorkflowAssociations.Add(workflowAssociation);
                            // Enable workflow
                            workflowAssociation.Enabled = true;
                        }
                        else
                        {
                            hasWorkflowAssociation.Enabled = true;
                            sharePointSitesList.UpdateWorkflowAssociation(hasWorkflowAssociation);
                            sharePointSitesList.Update();
                        }