<CharlieDigital/> Programming, Politics, and uhh…pineapples

7Mar/11Off

Deep Insight on SharePoint Event Receivers

Posted by Charles Chen

Not mine, but came across an excellent post by Hristo Pavlov (who unfortunately, no longer works in the SharePoint space).

It goes deep into the bowels of the threading model and the considerations one should have when designing custom code in event receivers.  Just what I was looking for and handy to file in your mental file cabinet for future reference.

On a side note, I love his last post:

I am moving away from SharePoint and consulting into serious custom software development and this is my last blog post here. I wish all the best to all of you that remain in the SharePoint world.

Filed under: SharePoint No Comments
4Mar/11Off

Getting Version Changes From SharePoint

Posted by Charles Chen

SharePoint doesn't provide a straightforward way to do this it seems.  My first crack was to try to leverage the BeforeProperties and AfterProperties in an event receiver, but it turns out that this doesn't work quite as you would expect based on the naming of these two properties (and the same goes for ChangedProperties).

However, clearly we can see that the version history contains the changes in the fields from one version to the next.

Here's some basic code to identify the fields that changed from one version to the next:

using (SPSite site = new SPSite("http://my.domain.com/"))
using (SPWeb web = site.OpenWeb())
{
    SPList list = web.GetList("http://my.domain.com/Lists/Stuff");
    SPListItem item = list.Items[1];

    Console.Out.WriteLine(item.Title);

    SPListItemVersion currentVersion = item.Versions[0];
    SPListItemVersion previousVersion = item.Versions.Count > 1 ? item.Versions[1] : null;

    Console.Out.WriteLine("Version is current: {0}", currentVersion.IsCurrentVersion);

    foreach (SPField field in currentVersion.Fields)
    {
        if (field.ShowInVersionHistory == false)
        {
            continue;
        }

        if (previousVersion == null)
        {
            Console.Out.WriteLine("  > {0} changed to \"{1}\"",
                field.StaticName, currentVersion[field.StaticName]);
            continue;
        }

        if (currentVersion[field.StaticName].Equals(previousVersion[field.StaticName]))
        {
            continue;
        }

        Console.Out.WriteLine("  > {0} changed from \"{1}\" to \"{2}\"",
            field.StaticName, previousVersion[field.StaticName], currentVersion[field.StaticName]);
    }
}

This will get you the changes between the current version and the previous version.  If it's a new object, all of the changes will be returned.

Filed under: .Net, SharePoint No Comments