Jun 25 2009

SharePoint: The Wicked SPWeb.Properties PropertyBag

*** This article is a must read for any developer reading or writing Web (Site) properties ***

If you haven’t already noticed, there are two different API properties on the SPWeb class - AllProperties (a Hashtable) and Properties (a PropertyBag). Apparently the AllProperties is meant to replace Properties, but Properties was left in place for backwards compatibility. Here’s where things get wicked …

The unconventional PropertyBag data type stores its keys in all lowercase, thus not supporting case-sensitive keys, while the conventional Hashtable does support case-sensitive keys. On top of that, while entries added to Properties get propagated to AllProperties with a lowercase key, entries added to AllProperties do not get propagated to Properties. So this what Microsoft gives us developer peons to work with. This is why consultants like myself stay employed.

If you are working with property entries that only your custom application will be reading and writing from, simply always use AllProperties and you will be good to go. However I often find myself having to work with properties that are read or written by SharePoint internals, and SharePoint itself is very inconsistent in its interaction with Web (Site) properties, probably due to its evolving nature being a rather old product as far as software is concerned.

So the best solution that I have come up with to date is to add your entries to both API properties. This ensures the entry will be present in both collections, and also ensures the key will have the correct case in AllProperties. I have found though in order to add to both, the order of the update API calls is important - you must first update the SPWeb object followed by updating the SPWeb.Properties PropertyBag. Performing the updates in the reverse order prevents an entry with a case-sensitive key from being added to AllProperties, and only the lowercase-keyed entry will be exposed in AllProperties. Now that you are probably thoroughly confused, here is the code:

// Add a property entry
web.Properties[key] = value;
web.AllProperties[key] = value;
web.Update();
web.Properties.Update();
 
// Remove a property entry
web.AllProperties.Remove(key);
web.Properties[key] = null;
web.Update();
web.Properties.Update();

Take a look, or straight up copy, my SharePoint utility class that abstracts away Web property interactions.


Jun 11 2009

SharePoint Central Administration Extensions Feature

I just released the second feature that is now part of the Trentacular SharePoint 2007 Features CodePlex project: Central Administration Extensions

The solution currently deploys just a single custom action and page for managing farm properties. This has proved useful for us as a means to centralize configuration that is applicable across our entire SharePoint farm, such as custom application connection strings, log4net config file location, etc.

If you are a seasoned ASP.Net developer, you may also find the included Delegate Data Source useful. It essentially exposes the 4 main data source methods (select, insert, update, and delete) as events that can be handled directly in your code behind.


Jun 11 2009

SharePoint: Differences Between Global and Web Application Targeted Solution Deployment

SharePoint solutions are either deployed globally or targeted to a particular web application. The decision of which is made automatically by the SharePoint Solution framework depending on the contents of the solution manifest. Certain items in the solution manifest such as SafeControl entries result in modifications to a Web application’s web.config file. Only when a solution manifest does NOT contain any of these types of entries will the solution be globally deployed.

The deployment process behaves differently based on the type of deployment for the solution, and these differences have caused me quite a headache. Here are my findings that I think any SharePoint developer or administrator should be aware of when performing solution deployments.

Globally Deployed Solutions

When a solution is deployed globally, all SharePoint application pools, including Central Administration’s, are recycled automatically. This can be good and bad. This is good because any GAC installed DLL that has been upgraded needs to be reloaded. This can be bad though with regards to the availability of your entire SharePoint Farm.

In my particular case, I am working with a SharePoint administrator to deploy a globally deployed solution that is used by only a single web application. It is fine for this web application to be unavailable, as we have cleared it with our change control process and made announcements of the downtime, but we haven’t announced to users of the other SharePoint web applications in the Farm that their sites will be coming down along with it. So be forwarned.

Web Application Targeted Solutions

I have become fond of web application targeted solutions because they offer me a workaround to the above availability problem. When a web application targeted solution is deployed or retracted, only the application pools of the targeted web applications are recycled.

Enterprise Farm Strategies

  • When upgrading solutions, the upgradesolution stsadm command only gets you so far. I’ve found it is best to fully retract and remove the old solution and then add and deploy the new solution in order to be sure your upgraded features actually take.
  • Avoid the -allcontenturls switch - When deploying and retracting a web application targeted solution, deploy or retract it only to those web applications that will use it … thus preventing unnecessary recycling of application pools. I was being lazy in my retraction script and instead of specifying the particular web application url, I used the -allcontenturls switch to retract my solution, hoping SharePoint would be smart enough to recycle only the application pools of the web applications the solution was actually retracted from. Bad assumption. They all get recycled.

A Big Gotcha that Got Me

If you are upgrading a web application targeted solution using the retract, remove, add, deploy strategy mentioned above and your web application scoped Features have associated Feature Receivers, then you must recycle the Central Administration application pool after removing the old solution and before adding the new solution if you intend to use the Central Admin Web application features page to activate your solution’s Features. In this case, it is the Central Administration application pool that executes your web application scoped Feature Receivers, and if not recycled, it will continue to use the loaded cached old versions of assemblies updated by your solution.

The same also goes for powershell. If within a powershell console you deactivate a Feature having a Feature receiver, the assembly containing the Feature receiver will be loaded and cached by the powershell App domain. After retracting, removing, adding, and redeploying the solution in the same powershell console, it will still be the previous version of the assembly that is cached. If you were to attempt to script the activation of your Feature, your updated Feature receiver’s code is never executed, rather the previous version from the cached assembly is used. To get around this dilemma, you can either increment your assembly version or start a new powershell console before deploying and activating your updated solution’s Features.


May 22 2009

SharePoint ASP.Net 3.5 Upgrade Feature

I’ve finally gotten around to starting a CodePlex project for publishing SharePoint features called Trentacular SharePoint 2007 Features. The first contribution to the project should reach a broad audience (within the SharePoint population that is) … an ASP.Net 3.5 Upgrade Feature.

The Feature is naturally scoped to a Web Application and adds ASP.Net 3.5 entries to the particular Web Application’s web.config file. It works for both WSS and MOSS and also supports clean deactivation by iterating through the SPWebConfigModification collection and removing modifications by owner instead of recreating the modifications. All modifications are done through a utility class called SPWebConfigModificationHelper which can be taken advantage of alone if you are writing your own modifications.

Before deciding to write this feature, I tried several others that have been published. Each had its own issues, from not supporting clean deactivation to simply just not adding the correct entries. The entries this feature writes were taken from the Visual Studio ASP.Net 3.5 Web.config template.

If you give this Feature a shot, please let me know how it goes.


Apr 14 2009

Generic Feature Receiver for Features that Deploy WebParts

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:

  1. It assumes that the WebPart has the same name as the Feature
  2. 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();
            }
        }
    }

Apr 14 2009

(SPWeb)properties.Feature.Parent no more … a handy Feature Receiver Base Class

If you are writing SharePoint feature receivers often, you will find there are several lines of code common to just about every feature receiver:

  1. A cast of properties.Feature.Parent to the appropriate scope (either SPWeb, SPSite, SPWebApplication, or SPFarm)
  2. 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.


Jan 19 2009

Exposing the State of a SharePoint Workflow Instance

Scenario

I have a fairly straight-forward sequential approval workflow that has an EnableModificationActivity that is in scope for just about the entirety of the workflow. My modification form is an ASPX page that gives the user the ability to enable/disable approval steps that have not occurred yet in the workflow. Since the workflow is able to be modified multiple times, I would like the form to reflect the current state of the workflow, meaning it should show which activities are currently enabled or disabled.

Solution

So here is the approach I ended up taking…

  1. I created a Plain Old CLR Object (POCO) class specific for holding state information my particular workflow that is capable of being XML Serialized. I’ll call this the “State Object” going forward.
  2. I created a reusable class called “WorkflowStateManager” that is capable of loading and saving single State Objects for a given SPWorkflow. This class is accessible by both the workflow and the modification form.
    • Save State Implementation:
      1. XML serializes the object to a string
      2. Sets the serialized string on the SPWorkflow list item’s property bag and calls the property bag’s Update() method
    • Load State Implementation (Essentially the reverse of the Save State implementation)
      1. Gets the serialized string from the SPWorkflow list item’s property bag
      2. XML Deserialize the string into the State Object
  3. When the workflow is activated, I construct a new State Object, initialize various properties on it, and save it using the WorkflowStateManager.
  4. As the workflow progresses, I load and update the State Object as needed in the following manner:
    • Use the WorkflowStateManager to load the current State Object
    • Make workflow decisions based on the State Object’s values
    • Make desired changes to the State Object
    • Use the WorkflowStateManager to save the State Object
  5. Now, my modification form is also able to load, manipulate, and save the State Object using the WorkflowStateManager, and in turn expose the current state of the workflow to the user.

I hope this might be of benefit to someone.


Jan 7 2009

SharePoint Dependency Injection Approach

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.


Dec 18 2008

SharePoint Workflow: Getting Replicator ChildData within a CreateTask Activity

Disclaimer: the following code requires version 3.5 of the .Net Framework, but can easily be modified to run using .Net 2.0

Scenario

So I was asked to develop a fairly straight forward approval activity in which several users were to be assigned an approval task in parallel. Microsoft offers its ReplicatorActivity to accomplish just this. The gotcha is that when running the ReplicatorActivity in parallel, the CurrentIndex property of the replicator is always the last index value of its child data. So how do you know which ChildData item the replicator is currently executing upon?

Solution

What I came up with seems a little hacky, but has been working beautifully for me. Here it goes…

The replicator contains a DynamicActivities property which holds references to each of the replicated activities it creates. Using Linq, we can easily convert this collection to a list, and then determine the index of the current activity within our newly converted activity list. The following example shows how I am using this method to access the current child data from within a CreateTask activity:

        private void createTask_Invoked(object sender, EventArgs e)
        {
            var createTask = (CreateTask)sender;
            string approver = (string)WorkflowUtils
                .GetReplicatorChildData(createTask);
 
            ...
 
        }

And the magic happens within our WorkflowUtils helper class:

    public static class WorkflowUtils
    {
        public static Activity GetTopMostReplicatorChild(Activity activity)
        {
            var parent = activity.Parent;
            if (parent == null)
                return null;
 
            if (parent is ReplicatorActivity)
                return activity;
 
            return GetTopMostReplicatorChild(activity.Parent);
        }
 
        public static object GetReplicatorChildData(Activity activity)
        {
            var topMostChild = GetTopMostReplicatorChild(activity);
            var replicator = (ReplicatorActivity)topMostChild.Parent;
 
            int currentIndex = replicator.DynamicActivities
                .ToList()
                .IndexOf(topMostChild);
 
            return replicator.CurrentChildData[currentIndex];
        }
    }

Dec 18 2008

SharePoint Logging and Microsoft’s Trace Log Provider

Microsoft has a posted example of how to log to the Trace Log here.

So how does one use this in their application? The below code is how I plugged it into our SharePoint development framework. I’d love to hear how you are using it.

Step 1:

I modified the Microsoft’s TraceProvider’s RegisterTraceProvider and UnregisterTraceProvider methods as follows:

        private static readonly object RegisterLock = new object();
        private static bool isRegistered = false;
        public static unsafe void RegisterTraceProvider()
        {
            lock (RegisterLock)
            {
                if (!isRegistered)
                {
                    SPFarm farm = SPFarm.Local;
                    Guid traceGuid = farm.TraceSessionGuid;
                    uint result = NativeMethods.RegisterTraceGuids(ControlCallback, null,
                        ref traceGuid, 0, IntPtr.Zero, null, null, out hTraceReg);
                    System.Diagnostics.Debug.Assert(result == NativeMethods.ERROR_SUCCESS);
                    isRegistered = true;
                }
            }
        }
 
        public static void UnregisterTraceProvider()
        {
            lock (RegisterLock)
            {
                if (isRegistered)
                {
                    uint result = NativeMethods.UnregisterTraceGuids(hTraceReg);
                    System.Diagnostics.Debug.Assert(result == NativeMethods.ERROR_SUCCESS);
                    isRegistered = false;
                }
            }
        }

Step 2:

I created our own TraceLogProvider object extending our BaseLogProvider which implements our custom ILogProvider interface. This provider object makes the appropriate calls into Microsoft’s TraceProvider, but now exposes a friendly logging interface to use within our application.

    public class TraceLogProvider : BaseLogProvider, IDisposable
    {
        public string ApplicationName { get; set; }
 
        public void Log(string msg, LogSeverity severity)
        {
            var traceSeverity = GetTraceSeverity(severity);
 
            TraceProvider.RegisterTraceProvider();
 
            string[] lines = msg.Split(new string[] { Environment.NewLine },
                StringSplitOptions.RemoveEmptyEntries);
            foreach (string line in lines)
            {
                TraceProvider.WriteTrace(0, traceSeverity, Guid.Empty, "Your Company Name",
                    ApplicationName, "General", line);
            }
        }
 
        private TraceProvider.TraceSeverity GetTraceSeverity(LogSeverity severity)
        {
            switch (severity)
            {
                case LogSeverity.Info:
                    return TraceProvider.TraceSeverity.InformationEvent;
                case LogSeverity.Warn:
                    return TraceProvider.TraceSeverity.WarningEvent;
                default:
                    return TraceProvider.TraceSeverity.CriticalEvent;
            }
        }
 
        #region IDisposable Members
 
        public virtual void Dispose()
        {
            TraceProvider.UnregisterTraceProvider();
        }
 
        #endregion
    }

And for reference, our BaseLogProvider is shown below:

    public abstract class BaseLogProvider : ILogProvider
    {
        #region ILogProvider Members
 
        public virtual void Info(string msg)
        {
            Log(msg, LogSeverity.Info);
        }
 
        public virtual void Info(Exception e)
        {
            Log(e, LogSeverity.Info);
        }
 
        public virtual void Info(string msg, Exception e)
        {
            Log(msg, e, LogSeverity.Info);
        }
 
        public virtual void Warn(string msg)
        {
            Log(msg, LogSeverity.Warn);
        }
 
        public virtual void Warn(Exception e)
        {
            Log(e, LogSeverity.Warn);
        }
 
        public virtual void Warn(string msg, Exception e)
        {
            Log(msg, e, LogSeverity.Warn);
        }
 
        public virtual void Error(string msg)
        {
            Log(msg, LogSeverity.Error);
        }
 
        public virtual void Error(Exception e)
        {
            Log(e, LogSeverity.Error);
        }
 
        public virtual void Error(string msg, Exception e)
        {
            Log(msg, e, LogSeverity.Error);
        }
 
        public virtual void Log(Exception e, LogSeverity severity)
        {
            Log(FormatException(e), severity);
        }
 
        public virtual void Log(string msg, Exception e, LogSeverity severity)
        {
            Log(msg + "\n" + FormatException(e), severity);
        }
 
        public abstract void Log(string msg, LogSeverity severity);
 
        #endregion
 
        protected virtual string FormatException(Exception ex)
        {
            StringBuilder stringBuilder = new StringBuilder();
 
            stringBuilder.AppendLine(ex.ToString());
            if (ex.InnerException != null)
            {
                stringBuilder.AppendLine(ex.InnerException.ToString());
                if (ex.InnerException.InnerException != null)
                {
                    stringBuilder.AppendLine(ex.InnerException.InnerException.ToString());
                }
            }
 
            return stringBuilder.ToString();
        }
    }
 
    public enum LogSeverity
    {
        Info,
        Warn,
        Error
    }