/// <summary> /// Safely add new feature : AddFeatureIfNotAlreadyAdded /// </summary> /// <param name="logger">ILogger logger</param> /// <param name="collection">SPFeatureCollection collection</param> /// <param name="featureGuid">Guid featureGuid</param> private void AddFeatureIfNotAlreadyAdded(ILogger logger, SPFeatureCollection collection, Guid featureGuid) { if (collection[featureGuid] == null) { logger.Info("Activating feature with Guid " + featureGuid.ToString()); collection.Add(featureGuid); } else { logger.Info("Skipping feature with Guid " + featureGuid.ToString()); } }
/// <summary>forcefully removes a feature from a featurecollection</summary> /// <param name="id">Feature ID</param> public void ForceRemoveFeatureFromLocation(Location location, SPFeatureCollection spfeatureSet, Guid featureId) { try { spfeatureSet.Remove(featureId, true); } catch (Exception exc) { logException(exc, string.Format( "Trying to remove feature {0} from {1}", featureId, LocationManager.SafeDescribeLocation(location))); } }
/// <summary>Adds features to the custom Feature class</summary> /// <param name="spFeatureDefinitions"></param> public void AddFeatures(SPFeatureCollection spfeatures, SPFeatureScope scope) { this._spfeatures = spfeatures; foreach (SPFeature spfeature in spfeatures) { Feature feature = new Feature(spfeature.DefinitionId, scope); try { feature.Name = spfeature.Definition.DisplayName; } catch (Exception exc) { feature.AppendExceptionMsg(exc); } this._features.Add(feature); } }
public ArtDevFeature EnablePublishigFeature() { using (SPSite site = new SPSite(this.site.Url)) { site.AllowUnsafeUpdates = true; //Activate the publishing feature at the site collection level SPFeatureCollection sFeatureCollect = site.Features; sFeatureCollect.Add(new Guid("F6924D36-2FA8-4f0b-B16D-06B7250180FA"), true); site.AllowUnsafeUpdates = false; } using (SPSite site = new SPSite(this.site.Url)) { using (SPWeb web = site.OpenWeb()) { web.AllowUnsafeUpdates = true; //Activate the publishing feature at the web level SPFeatureCollection wFeatureCollect = web.Features; wFeatureCollect.Add(new Guid("94c94ca6-b32f-4da9-a9e3-1f3d343d7ecb"), true); web.AllowUnsafeUpdates = false; } } return(this); }
private void InnerEnsureFeatureActivation(FeatureDependencyInfo featureDependency, SPFeatureCollection featureCollection) { // If already activated if (featureCollection.Any(sf => sf.DefinitionId == featureDependency.FeatureId)) { if (featureDependency.ForceReactivation) { this.logger.Info( "Disactivating the feature with id '{0}' because the 'ForceReactivation' property was used.", featureDependency.FeatureId); // Deactivate and reactivate feature featureCollection.Remove(featureDependency.FeatureId); featureCollection.Add(featureDependency.FeatureId); } else { this.logger.Warn( @"Feature with id '{0}' is already activated. If you wish to force it's reactivation, please use the 'ForceReactivation' property.", featureDependency.FeatureId); } } else { // Activate feature featureCollection.Add(featureDependency.FeatureId); } }
/// <summary> /// Forcefully delete specified features from specified collection /// (Could be SPFarm.Features, or SPWebApplication.Features, or etc.) /// </summary> private int ForceRemoveFeaturesFromLocation(Location location, SPFeatureCollection spfeatureSet, List<Feature> featuresToRemove) { int removedFeatures = 0; foreach (Feature feature in featuresToRemove) { ForceRemoveFeatureFromLocation(location, spfeatureSet, feature.Id); removedFeatures++; } return removedFeatures; }
/// <summary>searches for faulty features and provides the option to remove them</summary> /// <param name="features">SPFeatureCollection, the container for the features</param> /// <param name="scope">is needed, in case a feature is found, so that it can be deleted</param> /// <returns></returns> private bool findFaultyFeatureInCollection(SPFeatureCollection features, SPFeatureScope scope) { return false; /* bool faultyFound = false; if (features == null) { logDateMsg("ERROR: Feature Collection was null!"); return false; } if (features.Count == 0) { logDateMsg("ERROR: Feature Collection was empty!"); return false; } // string DBName = string.Empty; // tbd: retrieve the database name of the featureCollection string featuresName = features.ToString(); try { foreach (SPFeature feature in features) { FeatureChecker checker = new FeatureChecker(); FeatureChecker.Status status = checker.CheckFeature(feature); if (status.Faulty) { faultyFound = true; string location = LocationInfo.SafeDescribeObject(feature.Parent); string msgString = "Faulty Feature found! Id=" + feature.DefinitionId.ToString(); #if SP2013 msgString += " Activation=" + feature.TimeActivated.ToString("yyyy-MM-dd"); #endif string solutionInfo = GetFeatureSolutionInfo(feature); if (!string.IsNullOrEmpty(solutionInfo)) { msgString += solutionInfo; } msgString += Environment.NewLine + "Found in " + location + "." + Environment.NewLine + " Should it be removed from the farm?"; logDateMsg(msgString); string caption = "Found Faulty Feature"; DialogResult response = MessageBox.Show(msgString, caption, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning); if (response == DialogResult.Yes) { removeFeaturesWithinFarm(feature.DefinitionId, scope); } if (response == DialogResult.Cancel) { return faultyFound; } } } } catch (Exception ex) { if (ex is SqlException) { string msgstring = string.Format("Cannot access a feature collection of scope '{0}'! Not enough access rights for a content DB on SQL Server! dbOwner rights are recommended. Please read the following error message:\n\n'{1}'", scope.ToString(), ex.ToString()); string MessageCaption = string.Format("FeatureCollection in a Content DB not accessible"); if(MessageBox.Show(msgstring, MessageCaption,MessageBoxButtons.OKCancel) == DialogResult.Cancel) { return faultyFound; } } else { MessageBox.Show(ex.ToString(), "An error has occured!", MessageBoxButtons.OK); } return faultyFound; } return faultyFound; * */ }
/// <summary>searches for faulty features and provides the option to remove them</summary> /// <param name="features">SPFeatureCollection, the container for the features</param> /// <param name="scope">is needed, in case a feature is found, so that it can be deleted</param> /// <returns></returns> private bool findFaultyFeatureInCollection(SPFeatureCollection features, SPFeatureScope scope) { bool faultyFound = false; if (features == null) { logDateMsg("ERROR: Feature Collection was null!"); return false; } if (features.Count == 0) { logDateMsg("ERROR: Feature Collection was empty!"); return false; } // string DBName = string.Empty; // tbd: retrieve the database name of the featureCollection string featuresName = features.ToString(); try { foreach (SPFeature feature in features) { FeatureChecker checker = new FeatureChecker(); FeatureChecker.Status status = checker.CheckFeature(feature); if (status.Faulty) { faultyFound = true; string msgString = DescribeFeatureAndLocation(feature); logDateMsg(msgString); string caption = string.Format("Found Faulty {0} Feature", scope); DialogResult response = MessageBox.Show(msgString, caption, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning); if (response == DialogResult.Yes) { removeFeaturesWithinFarm(feature.DefinitionId, scope); } if (response == DialogResult.Cancel) { return faultyFound; } } } } catch (Exception ex) { if (ex is SqlException) { string msgstring = string.Format("Cannot access a feature collection of scope '{0}'! Not enough access rights for a content DB on SQL Server! dbOwner rights are recommended. Please read the following error message:\n\n'{1}'", scope.ToString(), ex.ToString()); string MessageCaption = string.Format("FeatureCollection in a Content DB not accessible"); if(MessageBox.Show(msgstring, MessageCaption,MessageBoxButtons.OKCancel) == DialogResult.Cancel) { return faultyFound; } } else { MessageBox.Show(ex.ToString(), "An error has occured!", MessageBoxButtons.OK); } return faultyFound; } return faultyFound; }
private static bool isFeatureActivated(SPFeatureCollection features, Guid featureId) { foreach (SPFeature feature in features) { if (feature.Definition.Id == featureId) { return true; } } return false; }
public static IEnumerable <ActivatedFeature> ToActivatedFeatures(this SPFeatureCollection spFeatures, Location parent) { return(ToActivatedFeatures(spFeatures, parent.Id, parent.Scope, parent.Url)); }
protected SPFeature GetFeature(SPFeatureCollection features, FeatureDefinition featureModel) { return(features.FirstOrDefault(f => f.DefinitionId == featureModel.Id)); }
public static bool IsFeatureEnabled(ISharePointCommandContext context, FeatureInfo featureID) { SPFeatureCollection featureCollection = GetFeatureCollectionForFeature(context, featureID); return(featureCollection[featureID.FeatureID] != null); }
/// <summary> /// activate a feature /// </summary> /// <param name="features">collection of features</param> /// <param name="featureId">feature ID of feature to handle</param> /// <param name="force">with or without force</param> /// <returns>the activated feature</returns> /// <remarks>attention, might throw exception!</remarks> internal static SPFeature UpgradeFeatureInFeatureCollection(SPFeatureCollection features, Guid featureId, bool force) { SPFeature spFeature = null; IEnumerable <Exception> upgradeErrors; bool success = true; string upgradeErrorsAsString = null; spFeature = features[featureId]; var definitionVersion = spFeature.Definition.Version; if (spFeature.Version < definitionVersion) { upgradeErrors = spFeature.Upgrade(force); } else { var errMsg = string.Format("Feature '{0}' does not require upgrade.", featureId); throw new ApplicationException(errMsg); } if (upgradeErrors != null && upgradeErrors.Count() > 0) { success = false; foreach (Exception x in upgradeErrors) { upgradeErrorsAsString += string.Format( "Error: {0}\n", x.Message ); } } if (spFeature.Version != definitionVersion || !success) { var errMsg = string.Format("Feature upgrade for feature '{0}' failed. Feature version: '{1}', definition version: '{2}'.", featureId, spFeature.Version, definitionVersion); if (!force) { errMsg += " You might want to try again with 'force' enabled."; } if (!string.IsNullOrEmpty(upgradeErrorsAsString)) { errMsg += upgradeErrorsAsString; } throw new ApplicationException(errMsg); } return(spFeature); }
public LoadedDto LoadWebAppChildren(Location location, bool elevatedPrivileges) { // this variable will save all loaded information of all web applications var loadedElements = new LoadedDto(location); var spWebApp = SpLocationHelper.GetWebApplication(location.Id); if (spWebApp == null) { // The web application might have got deleted!? // throw? return(null); } var siCos = spWebApp.Sites; foreach (SPSite spSite in siCos) { Location siteLocation; //try //{ if (elevatedPrivileges) { siteLocation = SpSiteElevation.SelectAsSystem(spSite, SpConverter.ToLocation, location.UniqueId); } else { siteLocation = SpConverter.ToLocation(spSite, location.UniqueId); } // meaning that they are not installed in the farm, rather on site or web level IEnumerable <FeatureDefinition> nonFarmFeatureDefinitions; SPFeatureCollection siteFeatureCollection = SpFeatureHelper.GetFeatureCollection(spSite, elevatedPrivileges); var activatedSiteFeatures = siteFeatureCollection.ToActivatedFeatures(siteLocation, out nonFarmFeatureDefinitions); loadedElements.AddChild(siteLocation, activatedSiteFeatures, nonFarmFeatureDefinitions); if (siteLocation.LockState != LockState.NoAccess && spSite != null && spSite.AllWebs != null) { SPWebCollection allWebs; if (elevatedPrivileges) { allWebs = SpSiteElevation.SelectAsSystem(spSite, SpLocationHelper.GetAllWebs); } else { allWebs = spSite.AllWebs; } foreach (SPWeb spWeb in allWebs) { var webLocation = SpConverter.ToLocation(spWeb, siteLocation.UniqueId); nonFarmFeatureDefinitions = null; SPFeatureCollection webFeatureCollection = SpFeatureHelper.GetFeatureCollection(spWeb, elevatedPrivileges); var activatedWebFeatures = webFeatureCollection.ToActivatedFeatures(webLocation, out nonFarmFeatureDefinitions); loadedElements.AddChild(webLocation, activatedWebFeatures, nonFarmFeatureDefinitions); // https://blogs.technet.microsoft.com/stefan_gossner/2008/12/05/disposing-spweb-and-spsite-objects/ spWeb.Dispose(); } } spSite.Dispose(); // This is the right place for debugging exception handling of lock state of site collections //} //catch (Exception Ex) //{ // throw Ex; //} } return(loadedElements); }
/// <summary> /// to be able to reuse opening of locations in SharePoint and consolidate code, /// a feature action function is required that follows Func: SPFeatureCollection, Guid, bool, SPFeature > /// </summary> /// <param name="features">collection of features</param> /// <param name="featureId">feature ID of feature to handle</param> /// <param name="force">with or without force</param> /// <returns>always null</returns> internal static SPFeature DeactivateFeatureInFeatureCollectionReturnsNull(SPFeatureCollection features, Guid featureId, bool force) { DeactivateFeatureInFeatureCollection(features, featureId, force); return(null); }
private void PerformAction(Location location, SPFeatureCollection spFeatureCollection, Feature feature) { try { if (_action == Action.Activating) { if (!(spFeatureCollection[feature.Id] is SPFeature)) { ++ActivationAttempts; try { spFeatureCollection.Add(feature.Id); if ((spFeatureCollection[feature.Id] is SPFeature)) { _featureDb.RecordFeatureActivationAtLocation(location, feature.Id); ++Activations; string msg = string.Format("Activated feature {0} ({1}:{2}) from location", feature.Id, feature.Scope, feature.Name); LogInfo(location, msg); } else { string msg = string.Format("Failure activating feature {0} ({1}:{2}) from location", feature.Id, feature.Scope, feature.Name); LogInfo(location, msg); } } catch (Exception exc) { string msg = string.Format("Exception activating feature {0} ({1}:{2}) from location", feature.Id, feature.Scope, feature.Name); LogException(exc, location, msg); } } } else { if ((spFeatureCollection[feature.Id] is SPFeature)) { ++ActivationAttempts; try { spFeatureCollection.Remove(feature.Id); if (!(spFeatureCollection[feature.Id] is SPFeature)) { _featureDb.RecordFeatureDeactivationAtLocation(location, feature.Id); ++Activations; string msg = string.Format("Removed feature {0} ({1}:{2}) from location", feature.Id, feature.Scope, feature.Name); LogInfo(location, msg); } else { string msg = string.Format("Failure removing feature {0} ({1}:{2}) from location", feature.Id, feature.Scope, feature.Name); LogInfo(location, msg); } } catch (Exception exc) { string msg = string.Format("Exception removing feature {0} ({1}:{2}) from location", feature.Id, feature.Scope, feature.Name); LogException(exc, location, msg); } } } } catch (Exception exc) { string msg = string.Format("Exception {0} feature {1} ({2}:{3}) at location", _action, feature.Id, feature.Scope, feature.Name); LogException(exc, location, msg); } }
private void ProcessFeature( object modelHost, SPFeatureCollection features, FeatureDefinition featureModel) { var currentFeature = features.FirstOrDefault(f => f.DefinitionId == featureModel.Id); var featureActivated = currentFeature != null; InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = currentFeature, ObjectType = typeof(SPFeature), ObjectDefinition = featureModel, ModelHost = modelHost }); if (!featureActivated) { if (featureModel.Enable) { var f = features.Add(featureModel.Id, featureModel.ForceActivate); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = f, ObjectType = typeof(SPFeature), ObjectDefinition = featureModel, ModelHost = modelHost }); } else { InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentFeature, ObjectType = typeof(SPFeature), ObjectDefinition = featureModel, ModelHost = modelHost }); } } else { if (featureModel.Enable && featureModel.ForceActivate) { var f = features.Add(featureModel.Id, featureModel.ForceActivate); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = f, ObjectType = typeof(SPFeature), ObjectDefinition = featureModel, ModelHost = modelHost }); } else if (!featureModel.Enable) { features.Remove(featureModel.Id, featureModel.ForceActivate); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = null, ObjectType = typeof(SPFeature), ObjectDefinition = featureModel, ModelHost = modelHost }); } else { InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentFeature, ObjectType = typeof(SPFeature), ObjectDefinition = featureModel, ModelHost = modelHost }); } } }
private void PerformAction(object locobj, SPFeatureCollection spFeatureCollection, Feature feature) { try { if (_action == Action.Activating) { if (!(spFeatureCollection[feature.Id] is SPFeature)) { ++ActivationAttempts; spFeatureCollection.Add(feature.Id); if ((spFeatureCollection[feature.Id] is SPFeature)) { _featureDb.RecordFeatureActivation(locobj, feature.Id); ++Activations; } } } else { if ((spFeatureCollection[feature.Id] is SPFeature)) { ++ActivationAttempts; spFeatureCollection.Remove(feature.Id); if (!(spFeatureCollection[feature.Id] is SPFeature)) { _featureDb.RecordFeatureDeactivation(locobj, feature.Id); ++Activations; } } } } catch (Exception exc) { LogException(exc, string.Format( "{0} feature {1} on {2}: {3}", _action, feature.Id, feature.Scope, LocationManager.SafeDescribeObject(locobj) )); } }
private void AddFeaturesForScope(TreeNode pnode, List <SPFeatureDefinition> fds, SPFeatureCollection active) { TreeNode fnode = new TreeNode("Features", 9, 9); pnode.Nodes.Add(fnode); foreach (SPFeatureDefinition fd in fds) { SPFeature f = active[fd.Id]; TreeNode chnode; if (f == null) { chnode = new TreeNode(fd.DisplayName, 1, 1); } else { chnode = new TreeNode(fd.DisplayName, 0, 0); } chnode.Tag = f; fnode.Nodes.Add(chnode); } }
internal static List <SINCycleReceiver> LoadSINCycleReceivers(SPContext spContext) { SPWeb currentWeb = spContext.Web; List <SINCycleReceiver> receivers = new List <SINCycleReceiver>(); SPFeatureCollection webFeatures = currentWeb.Features; List <KeyValuePair <Int32, SINCycleReceiver> > orderedReceivers = new List <KeyValuePair <int, SINCycleReceiver> >(); foreach (SPFeature feature in webFeatures) { SPFeatureDefinition definition = feature.Definition; if (definition != null && definition.Properties["SPSIN_SINCycleReceiver_Assembly"] != null && definition.Properties["SPSIN_SINCycleReceiver_Class"] != null && definition.Properties["SPSIN_SINCycleReceiver_Sequence"] != null ) { try { string receiverAssembly = definition.Properties["SPSIN_SINCycleReceiver_Assembly"].Value; string receiverClass = definition.Properties["SPSIN_SINCycleReceiver_Class"].Value; string receiverSequenceString = definition.Properties["SPSIN_SINCycleReceiver_Sequence"].Value; int receiverSequence; if (!Int32.TryParse(receiverSequenceString, out receiverSequence)) { // Invalid sequence, send to end of queue receiverSequence = Int32.MaxValue; } Assembly assembly = Assembly.Load(receiverAssembly); SINCycleReceiver receiverItem = (SINCycleReceiver)assembly.CreateInstance(receiverClass); int insertAt = orderedReceivers.Count; // default to last position for (int i = 0; i < orderedReceivers.Count; i++) { if (orderedReceivers[i].Key > receiverSequence) { insertAt = i; } } orderedReceivers.Insert(insertAt, new KeyValuePair <int, SINCycleReceiver>(receiverSequence, receiverItem)); } catch { // Error in loading... } } else { // Not a (correctly configured) SinCycle receiver } } foreach (KeyValuePair <int, SINCycleReceiver> receiver in orderedReceivers) { receivers.Add(receiver.Value); } return(receivers); }
/// <summary> /// Activates or deactivates the feature. /// </summary> /// <param name="features">The features.</param> /// <param name="activate">if set to <c>true</c> [activate].</param> /// <param name="featureId">The feature id.</param> /// <param name="urlScope">The URL scope.</param> /// <param name="force">if set to <c>true</c> [force].</param> /// <param name="ignoreNonActive">if set to <c>true</c> [ignore non active].</param> /// <returns></returns> private SPFeature ActivateDeactivateFeature(SPFeatureCollection features, bool activate, Guid featureId, string urlScope, bool force, bool ignoreNonActive) { if (features[featureId] == null && ignoreNonActive) return null; if (!activate) { if (features[featureId] != null || force) { Logger.Write("Progress: Deactivating Feature {0} from {1}.", featureId.ToString(), urlScope); try { features.Remove(featureId, force); } catch (Exception ex) { Logger.WriteWarning("{0}", ex.Message); } } else { Logger.WriteWarning("" + SPResource.GetString("FeatureNotActivatedAtScope", new object[] { featureId }) + " Use the -force parameter to force a deactivation."); } return null; } if (features[featureId] == null) Logger.Write("Progress: Activating Feature {0} on {1}.", featureId.ToString(), urlScope); else { if (!force) { SPFeatureDefinition fd = features[featureId].Definition; Logger.WriteWarning("" + SPResource.GetString("FeatureAlreadyActivated", new object[] { fd.DisplayName, fd.Id, urlScope }) + " Use the -force parameter to force a reactivation."); return features[featureId]; } Logger.Write("Progress: Re-Activating Feature {0} on {1}.", featureId.ToString(), urlScope); } try { return features.Add(featureId, force); } catch(Exception ex) { Logger.WriteException(new System.Management.Automation.ErrorRecord(ex, null, System.Management.Automation.ErrorCategory.NotSpecified, features)); return null; } }
private void ProcessFeature( object modelHost, SPFeatureCollection features, FeatureDefinition featureModel) { var currentFeature = GetFeature(features, featureModel); var featureActivated = IsFeatureActivated(currentFeature); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = currentFeature, ObjectType = typeof(SPFeature), ObjectDefinition = featureModel, ModelHost = modelHost }); TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Is feature activated: [{0}]", featureActivated); if (!featureActivated) { if (featureModel.Enable) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Enabling feature"); var f = SafelyActivateFeature(features, featureModel); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = f, ObjectType = typeof(SPFeature), ObjectDefinition = featureModel, ModelHost = modelHost }); } else { InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentFeature, ObjectType = typeof(SPFeature), ObjectDefinition = featureModel, ModelHost = modelHost }); } } else { if (featureModel.Enable && featureModel.ForceActivate) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Feature enabled, but ForceActivate = true. Force activating."); var f = SafelyActivateFeature(features, featureModel); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = f, ObjectType = typeof(SPFeature), ObjectDefinition = featureModel, ModelHost = modelHost }); } else if (!featureModel.Enable) { TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Removing feature."); features.Remove(featureModel.Id, featureModel.ForceActivate); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = null, ObjectType = typeof(SPFeature), ObjectDefinition = featureModel, ModelHost = modelHost }); } else { InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentFeature, ObjectType = typeof(SPFeature), ObjectDefinition = featureModel, ModelHost = modelHost }); } } }
protected SPFeature GetFeature(SPFeatureCollection features, FeatureDefinition featureModel) { return features.FirstOrDefault(f => f.DefinitionId == featureModel.Id); }
public static void DisableFeature(ISharePointCommandContext context, FeatureInfo featureID) { SPFeatureCollection featureCollection = GetFeatureCollectionForFeature(context, featureID); featureCollection.Remove(featureID.FeatureID, true); }
private static SPFeature SafelyActivateFeature(SPFeatureCollection features, FeatureDefinition featureModel) { SPFeature result = null; try { result = features.Add(featureModel.Id, featureModel.ForceActivate); } catch (Exception e) { // sandbox site/web features? // they need to ne activated with SPFeatureDefinitionScope.Site scope if ((featureModel.Scope == FeatureDefinitionScope.Site || featureModel.Scope == FeatureDefinitionScope.Web) && e.Message.ToUpper().Contains(featureModel.Id.ToString("D").ToUpper())) { result = features.Add(featureModel.Id, featureModel.ForceActivate, SPFeatureDefinitionScope.Site); } else { throw; } } return result; }
public static SPFeature ActivateOneFeature(SPFeatureCollection features, Guid featureId, ILog log) { bool force = true; #if SP2013_UNUSED // Unneeded - 14/15 hive deployment is governed at solution deployment time // Full-blown solution, not sandboxed SPFeatureDefinitionScope featureScope = SPFeatureDefinitionScope.Farm; // Note: 2013-03-20 // This does not appear to work, at least with an SP2010 wsp // it appears to always get activated at level 14 // This article describes an undocumented workaround // http://www.boostsolutions.com/blog/how-to-install-a-farm-solution-in-2010-and-2013-mode-for-sharepoint-2013/ if (InstallConfiguration.CompatibilityLevel == "14" || InstallConfiguration.CompatibilityLevel.ToUpper() == "OLD" || InstallConfiguration.CompatibilityLevel.ToUpper() == "OLDVERSION" || InstallConfiguration.CompatibilityLevel.ToUpper() == "OLDVERSIONS" ) { log.Info("Activating feature at level 14: " + featureId.ToString()); return features.Add(featureId, 14, force, featureScope); } else if (InstallConfiguration.CompatibilityLevel == "15" || InstallConfiguration.CompatibilityLevel.ToUpper() == "NEW" || InstallConfiguration.CompatibilityLevel.ToUpper() == "NEWVERSION" || InstallConfiguration.CompatibilityLevel.ToUpper() == "NEWVERSIONS" ) { log.Info("Activating feature at level 15: " + featureId.ToString()); return features.Add(featureId, 15, force, featureScope); } else if (InstallConfiguration.CompatibilityLevel == "14,15" || InstallConfiguration.CompatibilityLevel.ToUpper() == "ALL" || InstallConfiguration.CompatibilityLevel.ToUpper() == "ALLVERSIONS" ) { log.Info("Activating feature at level 14 then 15: " + featureId.ToString()); features.Add(featureId, 14, force, featureScope); return features.Add(featureId, 15, force, featureScope); } else { return features.Add(featureId, force); } #else return features.Add(featureId, force); #endif }
public override void DeployModel(object modelHost, DefinitionBase model) { var definition = model.WithAssertAndCast <FeatureDefinition>("model", value => value.RequireNotNull()); SPFeatureCollection features = null; SPFeature spObject = null; var assert = ServiceFactory.AssertService .NewAssert(definition, spObject); switch (definition.Scope) { case FeatureDefinitionScope.Farm: assert.SkipProperty(m => m.Scope, "Correct farm scope"); var farmModelHost = modelHost.WithAssertAndCast <FarmModelHost>("modelHost", value => value.RequireNotNull()); var farm = farmModelHost.HostFarm; var adminService = SPWebService.AdministrationService; features = adminService.Features; break; case FeatureDefinitionScope.WebApplication: assert.SkipProperty(m => m.Scope, "Correct web app scope"); var webApplicationModelHost = modelHost.WithAssertAndCast <WebApplicationModelHost>("modelHost", value => value.RequireNotNull()); var webApplication = webApplicationModelHost.HostWebApplication; features = webApplication.Features; break; case FeatureDefinitionScope.Site: assert.SkipProperty(m => m.Scope, "Correct site scope"); var siteModelHost = modelHost.WithAssertAndCast <SiteModelHost>("modelHost", value => value.RequireNotNull()); features = siteModelHost.HostSite.Features; break; case FeatureDefinitionScope.Web: assert.SkipProperty(m => m.Scope, "Correct web scope"); var webModelHost = modelHost.WithAssertAndCast <WebModelHost>("modelHost", value => value.RequireNotNull()); features = webModelHost.HostWeb.Features; break; } spObject = GetFeature(features, definition); assert.Dst = spObject; assert .ShouldBeEqual(m => m.Id, o => o.GetFeatureId()); if (definition.ForceActivate) { assert .SkipProperty(m => m.ForceActivate, "ForceActivate = true. Expect not null feature instance.") .ShouldNotBeNull(spObject); } else { assert .SkipProperty(m => m.ForceActivate, "ForceActivate = false. Skipping."); } if (definition.Enable) { assert .SkipProperty(m => m.Enable, "Enable = true. Expect not null feature instance.") .ShouldNotBeNull(spObject); } else { assert .SkipProperty(m => m.Enable, "Enable = false. Expect null feature instance.") .ShouldBeNull(spObject); } }
public static bool IsActivated(this SPFeatureCollection features, Guid featureId) { return(features.Any(f => f.DefinitionId.Equals(featureId))); }