Greg Galipeau wrote a thorough post on cleaning up your Web Part Gallery that is the basis for this post. To summarize, Greg shares a Feature Receiver he uses as a generic Feature Receiver for all his WebPart Features that simply removes the WebPart having the same name as the Feature’s DisplayName when the Feature is deactivated.
There are a couple of issues with this though:
- It assumes that the WebPart has the same name as the Feature
- It limits the Feature to deploying just a single WebPart
An alternative approach would be to inspect the Feature’s element definitions and extract the exact WebPart names that were deployed, thus resolving the two issues noted above.
Below is the alternative Feature Receiver (it extends the BaseFeatureReceiver I mentioned in my previous post):
public class WebPartFeatureReceiver : BaseFeatureReceiver<SPSite>
{
public override void FeatureDeactivating(SPSite site, SPFeatureReceiverProperties properties)
{
base.FeatureDeactivating(site, properties);
var elements = properties.Definition.GetElementDefinitions(CultureInfo.CurrentCulture);
var webparts = elements.Cast<SPElementDefinition>()
.SelectMany(e => e.XmlDefinition.ChildNodes.Cast<XmlElement>()
.Where(n => n.Name.Equals("File"))
.Select(n => n.Attributes["Url"].Value)
)
.ToList();
var rootWeb = site.RootWeb;
var wpGallery = rootWeb.Lists["Web Part Gallery"];
var galleryItems = wpGallery.Items.Cast<SPListItem>()
.Where(li => webparts.Contains(li.File.Name))
.ToList();
for (int i = galleryItems.Count - 1; i >= 0; i--)
{
var item = galleryItems[i];
item.Delete();
}
}
}
If you are writing SharePoint feature receivers often, you will find there are several lines of code common to just about every feature receiver:
- A cast of properties.Feature.Parent to the appropriate scope (either SPWeb, SPSite, SPWebApplication, or SPFarm)
- Empty implementations of FeatureInstalled and FeatureUninstalling
Provided below is an abstract generic class that now serves as the base class for every feature receiver I write. It eliminates the redundant code by performing the cast for you based on the classes generic type parameter and also goes ahead and implements all the abstract methods, making it so that you to only need to override the actual methods you plan to handle. Your extending feature receiver now will look like the following:
public class MyFeatureReceiver : BaseFeatureReceiver<SPWeb>
{
public override void FeatureDeactivating(SPWeb scope, SPFeatureReceiverProperties properties)
{
// Pointless, but what the heck
base.FeatureDeactivating(scope, properties);
// Now do something with your scope object, in this case an SPWeb
...
}
}
And now, the code for the BaseFeatureReceiver:
/// <summary>
/// Base class that makes the feature scope available as an argument to the
/// FeatureActivated and FeatureDeactivating methods
/// </summary>
/// <typeparam name="T">
/// T is the class type of the scope of the feature (SPFarm, SPWebApplication, SPSite, or SPWeb)
/// </typeparam>
public abstract class BaseFeatureReceiver<T> : SPFeatureReceiver
{
public sealed override void FeatureActivated(SPFeatureReceiverProperties properties)
{
FeatureActivated((T)properties.Feature.Parent, properties);
}
public virtual void FeatureActivated(T scope, SPFeatureReceiverProperties properties) { }
public sealed override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
FeatureDeactivating((T)properties.Feature.Parent, properties);
}
public virtual void FeatureDeactivating(T scope, SPFeatureReceiverProperties properties) { }
public override void FeatureInstalled(SPFeatureReceiverProperties properties) { }
public override void FeatureUninstalling(SPFeatureReceiverProperties properties) { }
}
Hope you find this helpful.
I just finished delivering a SharePoint workflow application in which I developed what could be called a start to framework that I would like to reuse in my next project. The framework currently has many features such as:
- An “Object-List Mapping” infrastructure complete with lazy initialization of objects and collections, converters, and caching
- A list item event broker
- Several handy web controls
- Logging
- State management
- Plenty of Utility Helpers
Each major feature is defined with an interface, and there is a single context class scoped to an SPWeb that holds references to each feature provider. For this last application, and I imagine I will do this for most applications going forward, I extended the context class to hold additional references to application-specific business logic helpers and data access interfaces.
In order to accomplish dependency injection of the feature providers, there is a context factory interface that is responsible for constructing and initializing contexts. I implemented a static ”default” context factory that when called upon, it first looks in the SPWeb property bag to see if a predefined custom context factory type has been specified. If it finds one, it constructs a new instance of the custom factory and returns the context from the custom factory’s CreateContext method.
public static class SPAppContextFactory
{
public const string CustomSPAppContextFactoryKey = "custom_context_factory_key";
public static void RegisterSPAppContextFactory<T>(this SPWeb web) where T : ISPAppContextFactory
{
web.AllProperties[CustomSPAppContextFactoryKey] = typeof(T).AssemblyQualifiedName;
web.Update();
}
public static void UnregisterSPAppContextFactory(this SPWeb web)
{
if (web.Properties.ContainsKey(CustomSPAppContextFactoryKey))
{
web.AllProperties[CustomSPAppContextFactoryKey] = null;
web.Update();
}
}
public static SPAppContext CreateSPAppContext(this SPWeb web)
{
// First check Web Properties if an alternate factory is specified
if (web.AllProperties.ContainsKey(CustomSPAppContextFactoryKey))
{
string customFactoryTypeName = web.AllProperties[CustomSPAppContextFactoryKey];
Type customFactoryType = Type.GetType(customFactoryTypeName, true);
ISPAppContextFactory customFactory = (ISPAppContextFactory)Activator.CreateInstance(customFactoryType);
return customFactory.CreateContext(web);
}
// Create the Default Context
return new SPAppContext(web);
}
You can now register your applications custom context factory in the FeatureActivated method of a feature receiver. You’ll need to include the namespace of your static factory class in order to make the extension methods available, and then simply call the RegisterSPAppContextFactory extension method .
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
var web = (SPWeb)properties.Feature.Parent;
web.RegisterSPAppContextFactory<MyCustomContextFactoryClass>();
}
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
var web = (SPWeb)properties.Feature.Parent;
web.UnregisterSPAppContextFactory();
}
The context factory now serves as a single place where all dependencies are wired up, and the framework is now able to instantiate custom contexts without being aware of any feature provider implementation.
Recent Comments