I currently have a custom master page that is being deployed at the Site scope. Once deployed and the feature is activated it makes the master page available for use. I am able to activate the feature and set master page on sites and subsites inherit the master page properly.
The problem occurs when I attempt to deactivate the feature.
Once deactivated I have a event receiver that finds all sites that have the feature's master page set and sets it back to the default master page. This also includes setting the master page on inheriting sites.
This works fine but after this has completed I attempt to delete the master page from the master page gallery and it errors stating that it is still in use. When I check the sites through the GUI they have all been set back to Seattle and inheriting sites are still inheriting from the parent so everything looks fine on that end.
When I go into the Content and Structure of the site collection and look up the master page related pages there is still a relationship with the _DeviceChannelMappings.aspx pages for all sites that are inheriting it's master page from the parent. See below:
I haven't been able to find a way programmatically to remove this relationship and because of that I am unable to delete the master page from the catalogs library.
If I manually go to the root site collection in the GUI and check the Reset all subsites to inherit this site master page setting using the seattle masterpage the relationships will go away and the file is then able to be deleted.
Any help would be appreciated. Here is my current code for the feature deactivation:
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
using (SPSite siteCollection = (SPSite)properties.Feature.Parent)
{
string defaultMasterUrl = SPUrlUtility.CombineUrl(siteCollection.ServerRelativeUrl.EndsWith("/") ? siteCollection.ServerRelativeUrl : siteCollection.ServerRelativeUrl + "/" , "_catalogs/masterpage/seattle.master");
string pulseMasterUrl = SPUrlUtility.CombineUrl(siteCollection.ServerRelativeUrl.EndsWith("/") ? siteCollection.ServerRelativeUrl : siteCollection.ServerRelativeUrl + "/" , "_catalogs/masterpage/pulse.v01.master");
foreach (SPWeb web in siteCollection.AllWebs)
{
Hashtable hash = web.AllProperties;
if (hash["__InheritsMasterUrl"].ToString() == "True" && !web.IsRootWeb)
{
web.MasterUrl = web.ParentWeb.MasterUrl;
web.Update();
}
else if (web.MasterUrl == pulseMasterUrl)
{
web.MasterUrl = defaultMasterUrl;
web.Update();
}
if (hash["__InheritsCustomMasterUrl"].ToString() == "True" && !web.IsRootWeb)
{
web.CustomMasterUrl = web.ParentWeb.CustomMasterUrl;
web.Update();
}
else if (web.CustomMasterUrl == pulseMasterUrl)
{
web.CustomMasterUrl = defaultMasterUrl;
web.Update();
}
}
foreach (SPWeb web in siteCollection.AllWebs)
{
try
{
SPFile file = web.GetFile(pulseMasterUrl);
if (file.Exists)
{
file.Delete();
}
file.Update();
}
catch (Exception ex)
{
}
}
}
}