Sunday 15 May 2011

Add Web Part to Page using SharePoint Client Object Model:File not Found error.

When adding a web part to your page if you get the "file not found" error there is one small trick which you probably have to do.

You will most probably get this error if the page you are adding the web part to, is not in the root site of the site collection.

Here is the code to add a web part to your SharePoint page:

ClientContext clientcontext = new ClientContext("http://vardhaman/Sites/zevenseas/");
Microsoft.SharePoint.Client.File page = clientcontext.Web.GetFileByServerRelativeUrl("/Sites/zevenseas/SitePages/Home.aspx");
LimitedWebPartManager wpm = page.GetLimitedWebPartManager(PersonalizationScope.Shared);
string webpartxml = /*The webpart XML */;
WebPartDefinition wpd = wpm.ImportWebPart(webpartxml);
wpm.AddWebPart(wpd.WebPart, "Left", 1);

Notice that I have passed the entire url of the site when creating the ClientContext object. And also when I have to fetch the page to which the webpart should be added, I have passed the entire site relative url which includes the name of the site which I initially passed to the ClientContext Object.

I was stuck on this error for sometime because I tought that once I had passed the site URL ("http://vardhaman/Sites/zevenseas/") to the ClientContext object, I need to only pass the location of the page within the site ("/SitePages/Home.aspx") when fetching the page. But that did not turn out to be the case.

Have Fun Coding!

No comments: