views:

355

answers:

2

I'm trying to deploy a selection of features and to do this I need to select the target site and then use:

objWeb.Features.Add(new Guid({guid of feature}));

my question is how would I select this site, all the help i've found creates the site using its constructor and then keeps track of it, where as I want to open an existing one.

Thank you.

+2  A: 

It depends on where you want to execute your code. If you have a sharepoint context then you can use

SPWeb oWebsite = SPContext.Current.Web;
oWebsite.Features.Add(new Guid({guid of feature}));

or

using(SPWeb oWebsite = SPContext.Current.Site.OpenWeb("Website_URL"))
{
    oWebsite.Features.Add(new Guid({guid of feature}));
}

If you were using a console app for example, and didn't have an SPContext you could use

using(SPSite oSiteCollection = new SPSite("http://Server_Name"))
{
    using(SPWeb oWebsite = oSiteCollection.OpenWeb("Website_URL"))
    {
        oWebsite.Features.Add(new Guid({guid of feature}));
    }
}

There are lots of other ways to get hold of an SPWeb object, but it depends on what information you have about the site (name, url, position in the heirarchy)

If you want to activate a feature that is scoped against a Site Collection or Web Application, then you can get hold of the SPSite or SPWebApplication in a similar manner.

SPSite:

SPContext.Current.Site

or

SPSite oSiteCollection = new SPSite("Absolute_URL")

SPWebApplication:

SPContext.Current.Site.WebApplication

or

SPWebApplication.Lookup(new Uri("http://MyServer:989"));

and on either of these objects, you can call

object.Features.Add(...))

In the same way as the above code.

Note: The scope of the feature is specified in the feature.xml, see the following for details: http://msdn.microsoft.com/en-us/library/ms436075.aspx

AlexWilson
So I have a webApp http://test:10413/ to deploy to the entire app I would pass the url into the sitecollection creator?
Nathan
Can you clarify what the scope of the feature is (Web Application, Site Collection or Site). I thought you were trying to deploy to a single site, but if you wanted to deploy to the WebApp, I can find some code for that
AlexWilson
I added some examples for activating a solution scoped to both a Web application and a Site collection
AlexWilson
Thanks great thanks Alex, i've setup two different versions with a check that I hope will check each feature and install to the correct place.
Nathan
A: 

For Web scoped features use:

using (SPWeb currentSite = SPContext.Current.Web)
{
  currentSite.WebFeatures.Add(new Guid("{GUID}"));
}

For Site scoped features use:

using (SPWeb currentSite = SPContext.Current.Web)
{
  currentSite.Features.Add(new Guid("{GUID}"));
}
Colin