Try the below code to activate sandbox. It needs FeatureActivated
event
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
string siteURL = "http://sitecollectionurl/";
SPSite spSite = new SPSite(siteURL);
SPUserToken systemToken = spSite.SystemAccount.UserToken;
//impersonating user
using (SPSite site = new SPSite(siteURL, systemToken))
{
// Get all names of added solutions
List solutionName = new List();
SPUserSolutionCollection solutionsCollection = site.Solutions;
foreach (SPUserSolution solution in site.Solutions)
{
string name = solution.Name;
if (!solutionName.Contains(name))
{
solutionName.Add(name);
}
}
// Add new solutions to the collection of the gallery
SPDocumentLibrary solutionsGallery = (SPDocumentLibrary)site.GetCatalog(SPListTemplateType.SolutionCatalog);
foreach (SPListItem item in solutionsGallery.Items)
{
if (!solutionName.Contains(item.Name))
{
solutionsCollection.Add(item.ID);
}
}
// Properly activate solutions
SPFeatureCollection featureCollection = site.Features;
foreach (SPUserSolution solution in solutionsCollection)
{
Guid solutionId = solution.SolutionId;
SPFeatureDefinitionCollection siteFeatures = site.FeatureDefinitions;
var features = from SPFeatureDefinition f in siteFeatures
where f.SolutionId.Equals(solutionId) && f.Scope == SPFeatureScope.Site
select f;
foreach (SPFeatureDefinition featureDefinition in features)
{
SPFeature foundFeature = featureCollection[featureDefinition.Id];
if (foundFeature == null)
site.Features.Add(featureDefinition.Id, false, SPFeatureDefinitionScope.Site);
}
}
}
}
To deactivate it, you need to write it inside FeatureDeactivating
event
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
...above entire code and then replace the last foreach as below
foreach (SPFeatureDefinition featureDefinition in features)
{
SPFeature foundFeature = featureCollection[featureDefinition.Id];
site.Features.Remove(featureDefinition.Id,true);
}
}
Reference - Activating SharePoint Sandboxed Solutions