Debugging Feature EventReceivers… the easy way

One of the great improvements of SharePoint 2010 is the ease of debugging your SharePoint projects. However, this does not hold for Feature Event Receivers, at least so it’d seem.

There is, however a very fast and easy way to start debugging your Feature EventReceiver’s overridden methods, like FeatureActivated() and FeaureDeactivating(): Simply add the following line of code at the point you want to start debugging:


Now simply deploy your solution to your local SharePoint environment. This will start the debugger of your liking.


How to get the Managed Path for a Site Collection

There’s no easy way of retrieving the Managed Path for a Site Collection (SPSite) through the SharePoint 2010 object model.

Therefore, I wrote this method, to retrieve it for you. It should work with both wildcard inclusion and explicit inclusion Managed Paths, including nested managed paths (i.e. /sites/, /sites/projects/, /sites/depts/, etc.).

private Microsoft.SharePoint.Administration.SPPrefix GetManagedPath(SPSite site)
    if (site == null)
        throw new ArgumentNullException("site");
    string relativeUrl = site.ServerRelativeUrl;
    if (relativeUrl.Length == 0)
        throw new Exception("Invalid ServerRelativeUrl for this SPSite.");

    foreach (Microsoft.SharePoint.Administration.SPPrefix prefix in site.WebApplication.Prefixes)
        switch (prefix.PrefixType)
            case Microsoft.SharePoint.Administration.SPPrefixType.ExplicitInclusion:
                if (relativeUrl == "/" + prefix.Name || relativeURL == prefix.Name)
                    return prefix;
            case Microsoft.SharePoint.Administration.SPPrefixType.WildcardInclusion:
                // WildCard Inclusion prefixes can be nested (i.e. /sites/ , /sites/projects/, /sites/depts/).
                // Thus, we remove the site collection's name and compare against the whole string, in stead of using .StartsWith()
                if (relativeUrl.Substring(0, relativeUrl.LastIndexOf("/")) == "/" + prefix.Name)
                    return prefix;
    // A prefix should've been returned by now.
    throw new Exception("No SPPrefix (Managed Path) found for this SPSite");

The method returns an SPPrefix class, which contains the Name and PrefixType properties of the Managed Path. If the Site Collection is located at the root of the Web Application, the SPPrefix.Name property will be empty and of the type Explicit Inclusion.