Thursday, May 28, 2009

Sharepoint - Activating features in code programatically

I have been working relentlessly on Workflow recently and although you can use the stsadm UpgradeSolution switch to deploy your new workflow sometimes the Association data needs changing which means all instances of the workflow need to be reinstalled.

Easy enough as i have a Workflow Association feature on each SubSite... but I didn't really want to go through each one and manually deactivate and reactivate.... and I also didn't want to use the stsadm command as it is far too slow. So I coded a quick console app to help with the deployment..



Console.WriteLine("Please enter the URL of the sharepoint site to install this against - e.g http://MySharepointSite.com");
string siteUrl = Console.ReadLine();
Console.WriteLine("Please paste the guid of the feature you would like to flush - e.g A7004706-0644-4aab-B097-691A5F51B3D6");
string strFeatureGuid = "" + Console.ReadLine();
Guid FeatureGuid;

try
{
site = new SPSite(siteUrl);
}
catch (Exception)
{

Console.WriteLine("ERROR: The site url does not relate to a Sharepoint site on this machine!! Press any key to close.");
Console.ReadKey();
return;
}

try
{
FeatureGuid = new Guid(strFeatureGuid);
}
catch (Exception)
{

Console.WriteLine("ERROR: The Guid entered is incorrect!! Press any key to close.");
Console.ReadKey();
return;
}

Console.WriteLine("Connected to site - " + site.Url.ToString() + ".");

int count = 0;
int flushCount = 0;
int sitesCount = site.AllWebs.Count;

foreach (SPWeb web in site.AllWebs)
{
foreach (SPFeature feat in web.Features)
{
if (feat.DefinitionId == FeatureGuid)
{
count++;
web.Features.Remove(FeatureGuid);
web.Features.Add(FeatureGuid);
flushCount++;
break;
}
}
web.Dispose();
}
Console.WriteLine("Feature is activated on " + count + " sites out of " + sitesCount + " sites.");
Console.WriteLine("Out of those " + count + " the Feature was successfully flushed on " + flushCount + " of them.");

count = 0;
foreach (SPWeb web in site.AllWebs)
{
foreach (SPFeature feat in web.Features)
{
if (feat.DefinitionId == FeatureGuid)
{
count++;
break;
}
}

}

Console.WriteLine("Feature is NOW activated on " + count + " sites out of " + sitesCount + ".");
Console.WriteLine("Please make a note of the above and Press any key to close");
Console.ReadKey();







Add this code to a console app and you can now use this to flush already activated features where needed.

No comments:

Post a Comment