Get the CultureInfo of a SharePoint Online site using Client Object Model C#

CSOM code gets executed from client machine and there’s a fair amount of chance that the current machine culture will not match with that of SharePoint Online site. Now, the problem is that for a ListItem of any List, SharePoint returns DateTime value in a string format. So, if you try to convert the string to a DateTime, you’ll get a FormatException that, the String was not recognized as a valid DateTime.

So, the solution is to get the current culture of the SharePoint Online site, and then apply the same to the current thread. To do that you need to query the LocaleId of the current site which, you can then use to get the CultureInfo.

//Getting and applying the SharePoint site culture to the working thread 
Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo(Convert.ToInt32(ctx.Web.RegionalSettings.LocaleId));

I have successfully tested this code for the following two conditions. My machine’s culture was en-US [MM/DD/YYYY] :-

  • en-CA [DD/MM/YYYY]
  • en-ZA [YYYY/MM/DD]

You can also see the List of CultureInfo.

Add a new WebPart to a SharePoint Site using Client Object Model C#

We can also add a new WebPart to a SharePoint page using CSOM. Before I proceed further, let me first point out the three imp parameters that are needed to perform this action. They are:-

  • ZoneID
  • ZoneIndex
  • WebPartXml

I am going to confine this blog to the items of the two Lists only, Pages(created by default for publishing site) and SitePages(created by default for TeamSite). Both these List, have web page as listItems. However, there’s a contrasting different,
SitePages have only 1 container[Zone] for everything, RichContent (ZoneID=wpz)
Pages have various containers[Zones], Header, Footer, Left, Right, RichContent (ZoneID=wpz), etc.

There’s one thing to note here that, the value of ZoneID, for RichContent, is always wpz.

Below is the code snippet for adding a WebPart to a SitePage/Pages

ClientContext ctx = new ClientContext(weburl);
ctx.Credentials = new SharePointOnlineCredentials(userName, passWord);

SP.List list = ctx.Web.Lists.GetByTitle("Site Pages");
CamlQuery cQuery = new CamlQuery();
ListItemCollection ltItemCollection = list.GetItems(cQuery);


ListItem ltItemHome = ltItemCollection.FirstOrDefault(p => p.DisplayName == "Home");
SP.File file = ltItemHome.File;


LimitedWebPartManager limitedWebPartManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared);
WebPartDefinitionCollection webPartDefCollection = limitedWebPartManager.WebParts;

WebPartDefinition webPartDef = limitedWebPartManager.ImportWebPart(webPartXml);
WebPartDefinition newWebPartDef = limitedWebPartManager.AddWebPart(webPartDef.WebPart, stringZoneId, intZoneIndex);

//ctx is the ClientContext
//Get the Guid of the newly added WebPart 
ctx.Load(newWebPartDef, w => w.Id);

So, if your stringZoneId is anything but ‘wpz’, your newly created WebPart will appear on the page at its appropriate zone. Now, if you’re attempting to add this WebPart to the zone, ‘wpz‘[RichContent] then, there’s one more step to go. For, RichContent, you have to specify the exact position of its appearance after adding it to the page. Since, a RichContent can contain text as well as WebParts, you have the liberty to position it accordingly inside the RichContent. For this ex, I will add it at the end of the RichContent, so that, if the RichContent contains some values(text, image, or WebParts) then, my newly added WebPart, will appear after them.

if (stringZoneId == "wpz")
    if (ltItemHome.FieldValuesAsHtml.FieldValues.ContainsKey("WikiField"))
        //SitePage item
        ltItemHome["WikiField"] = String.Concat(ltItemHome["WikiField"], "
", GetEmbeddedWPString(newWebPartDef.Id), "
    else if (ltItemHome.FieldValuesAsHtml.FieldValues.ContainsKey("PublishingPageContent"))
        //Pages item
        ltItemHome["PublishingPageContent"] = String.Concat(ltItemHome["PublishingPageContent"], "
", GetEmbeddedWPString(newWebPartDef.Id), "

Here, I am appending, a constant string (GetEmbeddedWPString(Guid wpGuid)) with the new WebPartId to the field, WikiField, for SitePages and, PublishingPageContent, for the List Pages. The constant string format is

private string GetEmbeddedWPString(Guid wpGuid)
    // set the web part's ID as part of the ID-s of the div elements
    string wpForm = @"
<div class=""ms-rtestate-read ms-rte-wpbox"">

<div class=""ms-rtestate-notify ms-rtegenerate-notify ms-rtestate-read {0}"" id=""div_{0}"">

<div id=""vid_{0}"" style=""display:none"">


    return string.Format(wpForm, wpGuid);

Just for reference, I have posted the schemaXml of a Rss WebPart here,

Get WebPart Page of a SharePoint site using Web Services C#

In my previous post, , I had explained, how we can use the WebService, WebPartPages.asmx. Here, I am going to use another method of this WebService, GetWebPartPage. This method, returns the content of the html page. The contents are as such that, they don’t include .js/.css files references. The returned string, contains, Page title, properties[MetaInfo], and all the WebParts [in a proper order] as they are present on the page.Now, all the WebParts, always have ZoneId of the page, in which they have been added. ZoneId, is a very important property, required to add a WebPart to a Zone. However, for some inexplicable reasons, neither the GetWebPart2 method of this service returns ZoneId nor does the SharePoint CSOM. They do for some WebParts, but for most they don’t return info regarding ZoneID.

It is for this reason, I was forced to call this method to get the info of all the WebParts at one go. Then, I had to parse this, returned string value, to identify the ZoneId of each of the WebParts based on their Guids. To get the Guids of each of the WebParts, you can use the SharePoint CSOM demonstrated here, .

Following is the implementation of the method, GetWebPartPage.

string webPageInfo = String.Empty; 
string webServiceUrl = ctx.Web.Url + "/_vti_bin/WebPartPages.asmx";

//say, we're trying to get the Home.aspx item of the List, SitePages. 
string documentName = String.Concat("SitePages/", listItem.FieldValuesAsText.FieldValues["FileLeafRef"]);

StringBuilder sbEnvelope = new StringBuilder();
sbEnvelope.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
sbEnvelope.Append("<soap:Envelope xmlns:xsi=\"\" xmlns:xsd=\"\" xmlns:soap=\"\">");
    "<soap:Body>" +
        "<GetWebPartPage xmlns=\"\">" +
            "<documentName>{0}</documentName>" +
        "</GetWebPartPage>" +
    , WebUtility.HtmlEncode(documentName)));

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(webServiceUrl);
req.Method = "POST";
req.ContentType = "text/xml; charset=\"utf-8\"";
req.Accept = "text/xml";
req.Headers.Add("SOAPAction", "\"\"");
req.UserAgent = "FrontPage";
req.UseDefaultCredentials = false;

Uri targetSite = new Uri(ctx.Web.Url);
SharePointOnlineCredentials spCredentials = (SharePointOnlineCredentials)ctx.Credentials;

string authCookieValue = spCredentials.GetAuthenticationCookie(targetSite);
req.CookieContainer = new CookieContainer();
    new Cookie("FedAuth",

using (Stream stream = req.GetRequestStream())
    using (StreamWriter writer = new StreamWriter(stream))

WebResponse response = req.GetResponse();
Stream responseStream = response.GetResponseStream();

XmlDocument xDoc = new XmlDocument();

if (xDoc.DocumentElement != null && xDoc.DocumentElement.InnerText.Length > 0)
    webPageInfo = xDoc.DocumentElement.InnerText;

    //webPageInfo = webPageInfo.Substring(webPageInfo.IndexOf(""));

    //The above commented subString code was used further 
    //to implement the logic of parsing. Since we're not 
    //concerned with that hence it's not included here.


Recently I started getting, 403 Forbidden error while running this code. Certain modifications are required, to make this code work. They are defined in the following link,

403 Forbidden Error while calling GetWebPartPage SharePoint Online


Get all the WebParts of a SharePoint WebPage using Client Object Model C#

CSOM doesn’t have much to do with WebParts. However, you can modify certain properties like, Title. Below, I have demonstrated a simple way to get the WebParts of the page, Home, from the List, SitePages, of a TeamSite.
ClientContext ctx = new ClientContext(weburl);
ctx.Credentials = new SharePointOnlineCredentials(userName, passWord);

SP.List list = ctx.Web.Lists.GetByTitle("Site Pages");
CamlQuery cQuery = new CamlQuery();
ListItemCollection ltItemCollection = list.GetItems(cQuery);


ListItem ltItemHome = ltItemCollection.FirstOrDefault(p => p.DisplayName == "Home");

LimitedWebPartManager lwpmShared = ltItemHome.File.GetLimitedWebPartManager(PersonalizationScope.Shared);
LimitedWebPartManager lwpmUser = ltItemHome.File.GetLimitedWebPartManager(PersonalizationScope.User);

WebPartDefinitionCollection webPartDefinitionCollectionShared = lwpmShared.WebParts;
WebPartDefinitionCollection webPartDefinitionCollectionUser = lwpmUser.WebParts;

ctx.Load(webPartDefinitionCollectionShared, w => w.Include(wp => wp.WebPart, wp => wp.Id));
ctx.Load(webPartDefinitionCollectionUser, w => w.Include(wp => wp.WebPart, wp => wp.Id));
ctx.Load(ctx.Web, p => p.Url);
foreach (WebPartDefinition webPartDefinition in webPartDefinitionCollectionShared)
    WebPart webPart = webPartDefinition.WebPart;
    ctx.Load(webPart, wp => wp.ZoneIndex, wp => wp.Properties, wp => wp.Title, wp => wp.Subtitle, wp => wp.TitleUrl);
    //Once the webPart is loaded, you can do your modification as follows
    webPart.Title = "My New Web Part Title";

To get the SchemaXml of a particular WebPart of a SharePoint Page using Web Services, visit the following link,

Apply a new Theme to a SharePoint site using Client Object Model C#

In my previous post,, I had described how one can get all the available themes for a SharePoint site using CSOM. Now, here, I am going to demonstrate how to Change/Modify/Apply a new Theme to a SharePoint site.Actually, applying a theme is relatively easier. There is one method in the Web class of the Microsoft.SharePoint.Client namespace which will set the theme of the site. You just have to call this method with proper parameters.

private void ApplyTheme(string colorUrl, string fontUrl, string backImageUrl)
  if (!String.IsNullOrEmpty(colorUrl))
    this.ctx.Web.ApplyTheme(colorUrl, fontUrl, backImageUrl, false);

Here, few things are noteworthy:

  • First of all I am not sure about the parameter shareGenerated [I have passed false to it]. You should test it in your application to get the desired result.
  • Out of the parameters, colorUrl, fontUrl, backImageUrl, colorUrl is mandatory. You can’t set it Empty or null. If your color is null then don’t apply the theme, it’s as good as setting the default theme.
  • The other two optional parameters, fontUrl, & backImageUrl also cannot be set as String.Empty. If you do this, then, you might encounter an error Invalid Url. Hence, if you don’t want to set any, or, both of this parameters then set them as NULL.