Monday, July 21, 2014

Adding Content Editor Webpart on Publishing Page using Client Object Model

 using (ClientContext context = new SP.ClientContext(new Uri("http://contoso.com/")))
                {

                    Web webSite = context.Web;
                    context.Load(webSite);
                    SP.File page = webSite.GetFileByServerRelativeUrl("/sites/publishingsite/page.aspx");
                    page.CheckOut();
                    Console.WriteLine(pagename + "Page has been checked out for adding webpart");
                    var limitedWebPartManager = page.GetLimitedWebPartManager(SP.WebParts.PersonalizationScope.Shared);
                    SP.WebParts.LimitedWebPartManager manager = page.GetLimitedWebPartManager(Microsoft.SharePoint.Client.WebParts.PersonalizationScope.Shared);

                    string xmlWebpart = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                        "<WebPart xmlns=\"http://schemas.microsoft.com/WebPart/v2\">" +
                                        "<Assembly>Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>" +
                                        "<TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>" +
                                        "<Title>Sample Webpart</Title>" +
                                        "<Description>$Resources:core,ContentEditorWebPartDescription;</Description>" +
                                        "<ContentLink xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\" />" +
                                        "<Content xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\">" +
                                        "<![CDATA[webpart content here]]></Content>" +
                                        "<PartImageLarge>/_layouts/15/images/mscontl.gif</PartImageLarge>" +
                                        "</WebPart>";

                    Microsoft.SharePoint.Client.WebParts.WebPartDefinition oWebPartDefinition = manager.ImportWebPart(xmlWebpart);
                    SP.WebParts.WebPart webpartCE = oWebPartDefinition.WebPart;

                    context.Load(manager.AddWebPart(webpartCE, WebpartZone, Convert.ToInt16(WebpartZoneIndex)));
                    context.ExecuteQuery();

                    page.CheckIn("checking in", CheckinType.MajorCheckIn);
                    page.Publish(string.Empty);
                    context.Load(page);
                    context.ExecuteQuery();
                    Console.WriteLine(pagename + "Added webpart Check-in completed");
                    Console.WriteLine("Webpart has been added");

No comments:

Post a Comment

How to launch a document by clicking a link to the file?

Word: <a href='ms-word:ofe|u|path/to/web/word/document.docx'>Link to document</a> Excel: <a href='ms-excel:o...