It also requires the following directive for SPFarm, PFeatureDefinitionCollection..etc objects
using Microsoft.SharePoint.Administration;
if the feature already exists in one of the web then the above listed code will throws an exception and comes out of loop and never adds it to the other sites, the followign code checks if feature exists in web if not then adds(Activates) it.
public static void ActiveDocLibEvntHandlerInAllWebs(string siteCollName, String featureDisplayName)
{
logWriter.WriteLine(DateTime.Now.ToString() + "-- Entering ActiveDocLibEvntHandlerInAllWebs()");
System.Globalization.CultureInfo oCultureInfo = new System.Globalization.CultureInfo(1033);
SPFeatureDefinitionCollection collFeatureDefinitions = SPFarm.Local.FeatureDefinitions;
foreach (SPFeatureDefinition oFeatureDefinition in collFeatureDefinitions)
{
if (oFeatureDefinition.GetTitle(oCultureInfo) == featureDisplayName)
{
int count = 0;
Guid guidFeatureDefinitionID = oFeatureDefinition.Id;
using (SPSite site = new SPSite(siteCollName))
{
foreach (SPWeb oWebsite in site.AllWebs)
{
count++;
if (oFeatureDefinition.Scope == SPFeatureScope.Web)
{
SPFeatureCollection collFeatureCollection = oWebsite.Features;
try
{
SPFeature feature = oWebsite.Features[guidFeatureDefinitionID];
logWriter.WriteLine(DateTime.Now.ToString() + " -- Iteration# " + count.ToString() + " -- " + SPEncode.HtmlEncode(feature.Definition.GetTitle(oCultureInfo)) + " feature already exists on " + oWebsite.Title);
}
catch (Exception ex)
{
SPFeature oFeature = collFeatureCollection.Add(guidFeatureDefinitionID);
logWriter.WriteLine(DateTime.Now.ToString() + " -- Iteration# " + count.ToString() + " -- " + SPEncode.HtmlEncode(oFeature.Definition.GetTitle(oCultureInfo)) + " feature added on " + oWebsite.Title);
}
}
oWebsite.Dispose();
}
}
}
}
logWriter.WriteLine(DateTime.Now.ToString() + "-- Closing ActiveDocLibEvntHandlerInAllWebs()");
}
Regards,
Vijay Gande