January 31, 2015

Get Actual Url of Master Page For Specific Page

I needed to know the full url of the actual master page for each page in my SharePoint farm, so I wrote a piece of code that will do all the magic for me: Read html contents from page file, find the master page tag, get the actual master page from master token, then construct the full url string.
Here is the useful section of the code with 2 methods below:

HtmlContent = web.GetFileAsString(PageUrl);
Match MasterMatch = Regex.Match(HtmlContent, "MasterPageFile=\".*.master", RegexOptions.IgnoreCase | RegexOptions.Multiline);

MasterTag = MasterMatch.Groups[0].Value;// Example: "MasterPageFile=\"~masterurl/default.master"
if (!String.IsNullOrEmpty(MasterTag))
{
// remove 'MasterPageFile=\"' portion
MasterPageValue = MasterTag.Remove(0, 16);

MasterPageUrl = getMasterPageUrlFromToken(web, MasterPageValue);
MasterPageFullUrl = getMasterPageFullUrl(web, MasterPageUrl);
}



/// Convert Master Page token to url
private static string getMasterPageUrlFromToken(SPWeb web, string MasterPageToken)
{string Url = String.Empty;
if (MasterPageToken.Equals("~masterurl/default.master", StringComparison.CurrentCultureIgnoreCase))
{
MasterPageToken = web.MasterUrl;
}
else if (MasterPageToken.Equals("~masterurl/custom.master", StringComparison.CurrentCultureIgnoreCase))
{
MasterPageToken = web.CustomMasterUrl;
}
else if (MasterPageToken.Equals("~site/default.master", StringComparison.CurrentCultureIgnoreCase))
{// Will use "default.master" file in Web Master pages gallery
MasterPageToken = web.CustomMasterUrl;
}
else if (MasterPageToken.Equals("~sitecollection/default.master", StringComparison.CurrentCultureIgnoreCase))
{// Will use "default.master" file in SiteCollection Master pages gallery                     
MasterPageToken = web.CustomMasterUrl;
}
return (MasterPageToken);
}

  
private static string getMasterPageFullUrl(SPWeb web, string MasterUrl)
{// Input Examples:
// "/sname/_catalogs/masterpage/seattle.master"
// "../_catalogs/masterpage/seattle.master"
// "../../_catalogs/masterpage/default_noimage.master"
// "~site/_catalogs/masterpage/default_copy1.master"
// "sites/Office_Viewing_Service_Cache/_catalogs/masterpage/v4.master"

string FullUrl = String.Empty;
string tempUrl = String.Empty;
if (SPUrlUtility.IsUrlRelative(MasterUrl))
{tempUrl = MasterUrl.Substring(MasterUrl.IndexOf("_catalogs"));
FullUrl = String.Format("{0}/{1}", web.Url, tempUrl);
}
else

FullUrl = MasterUrl;
return (FullUrl);
}




No comments:

Post a Comment