Friday, July 20, 2012

SharePoint Feature Receiver : System.InvalidCastException: Unable to cast object of type 'Microsoft.SharePoint.SPSite' to type 'Microsoft.SharePoint.SPWeb


If you trying to activate masterpage in the site collection level and if you are using below code this will thrown error

this code is referring only website not site collection
  public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
           SPWeb currentWeb = (SPWeb)properties.Feature.Parent;
            currentWeb.MasterUrl = "/_catalogs/masterpage/CustomMaster.master";
            currentWeb.CustomMasterUrl = "/_catalogs/masterpage/CustomMaster.master";
            currentWeb.Update();
        }



Error: 
Feature receiver assembly 'TestMasterPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9c3395ff06cc524a', class 'TestMasterPages.Features.CustomMaster.CustomMasterEventReceiver', method 'FeatureActivated' for feature '0ab67b2b-2360-45f2-b26e-e33a49ceea3c' threw an exception: System.InvalidCastException: Unable to cast object of type 'Microsoft.SharePoint.SPSite' to type 'Microsoft.SharePoint.SPWeb'.   
 at TestMasterPages.Features.CustomMaster.CustomMasterEventReceiver.FeatureActivated(SPFeatureReceiverProperties properties)   
 at Microsoft.SharePoint.SPFeature.DoActivationCallout(Boolean fActivate, Boolean fForce)


Solution:




  public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
          SPSite currentSite = (SPSite)properties.Feature.Parent;
            SPWeb currentWeb = currentSite.RootWeb;
            currentWeb.MasterUrl = "/_catalogs/masterpage/CustomMaster.master";
            currentWeb.CustomMasterUrl = "/_catalogs/masterpage/CustomMaster.master";
            currentWeb.Update();
        }



No comments:

Post a Comment

Followers