Friday, March 11, 2016

Change content of master page in Sharepoint programmatically

There are many articles available of how you may set master page for the site (using SPWeb.MasterUrl and SPWeb.CustomMasterUrl), but as it turned out there is a lack of examples which show how you may programmatically change content of master page itself. Sometimes it may be needed, e.g. when there is a lot of site collections in web application and updating them manually would take too much time.

The following example shows how to modify content of master page via Sharepoint object model:

   1:  
   2: var web = site.RootWeb;
   3: var file = web.GetFile(web.MasterUrl);
   4: if (file.CheckOutStatus != SPFile.SPCheckOutStatus.None)
   5: {
   6:     file.UndoCheckOut();
   7: }
   8:  
   9: string content = "";
  10: using (var sr = new StreamReader(file.OpenBinaryStream()))
  11: {
  12:     content = sr.ReadToEnd();
  13: }
  14:  
  15: string insertAfter = "</SharePoint:SPSecurityTrimmedControl>";
  16: int idx = content.IndexOf(insertAfter);
  17: if (idx < 0)
  18: {
  19:     return;
  20: }
  21:  
  22: int insertAt = idx + insertAfter.Length;
  23:  
  24: var subStr1 = content.Substring(0, insertAt);
  25: var subStr2 = content.Substring(insertAt);
  26: string newStr =
  27:     subStr1 +
  28:     "<div>New content</div>" +
  29:     subStr2;
  30:  
  31: file.CheckOut();
  32:  
  33: var catalog = site.GetCatalog(SPListTemplateType.MasterPageCatalog);
  34: var files = catalog.RootFolder.Files;
  35: file = files.Add(web.MasterUrl, Encoding.UTF8.GetBytes(newStr), true);
  36:  
  37: file.CheckIn("Change masterpage programmatically");
  38:  
  39: if (file.Item.ParentList.EnableMinorVersions)
  40: {
  41:     file.Publish("Change masterpage programmatically");
  42: }
  43:  
  44: if (file.Item.ParentList.EnableModeration)
  45: {
  46:     file.Approve("Change masterpage programmatically");
  47: }

In this example we insert div element with custom content after first found SPSecurityTrimmedControl. In your scenarios you may need to insert another elements into another places in masterpage. In this case modify the logic as needed.

At first we read the content of the masterpage and store it to the string (lines 9-13). After that we determine place where new element should be inserted (lines 15-22). In next step we split content string into 2 sub strings: before and after insert position (lines 24-25). And finally insert new element to the string (lines 26-29). We could perform the same operations via regular expressions, but in this example we will keep it simple. After that we override existing file with the new content (lines 33-35) and check in, publish, approve it depending on masterpage gallery’s settings (lines 37-47).

In result we will have updated masterpage which content was changed programmatically. Hope that this information will help someone.

No comments:

Post a Comment