Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I have a feature that is manually activated. In a feature receiver I also activate the feature on any child SPWebs in existence. I would like some code to run only on the SPWeb where the feature is manually activated.

The code below won't work as I intend because the method "EnsureSourcePublicationList" will get called on all the child webs as well.

How do I call "EnsureSourcePublicationList" on only the SPWeb where the feature is activated via the UI?

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    SPFeature feature = (SPFeature)properties.Feature;
    SPWeb web = (SPWeb)properties.Feature.Parent;

    EnsureSourcePublicationList(web);

    foreach (SPWeb childWeb in web.Webs)
    {
        try
        {
            childWeb.Features.Add(feature.DefinitionId, true);
        }
        catch (Exception ex)
        {
            //TODO: handle exception via logging
        }
    }
}
share|improve this question

1 Answer 1

up vote 3 down vote accepted

Try running a check on the parent web to see if the feature is activated. Since this is only applying to sub webs and it is in the FeatureActivated event, it will already be activated on the parent for you to verify.

Edit

Code added to check if web.ParentWeb != null

bool isChild = false;

if (web.ParentWeb != null)
{
    foreach (SPFeature parentFeature in web.ParentWeb.Features)
    {
        if (parentFeature.DefinitionId == feature.DefinitionId)
        {
          isChild = true;
        }
    }
}

if (!isChild)
{
    EnsureSourcePublicationList(web);
}
share|improve this answer
    
Make sure you test the code too, because I haven't lol. –  RJ Cuthbertson Aug 28 '12 at 17:29
1  
That works, after I added a check to make sure ParentWeb is not null. –  Chloraphil Aug 28 '12 at 18:24
    
Good call. Thanks for accepting. Glad I could help. –  RJ Cuthbertson Aug 28 '12 at 18:46

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.