Friday, May 30, 2008

Getting Date Information From Photos in SharePoint

Synopsis: SharePoint doesn't automatically extract the date the photo was taken when loaded into a SharePoint picture library, although this information is already embedded in JPEG images.  This article walks through the process of tapping into the photo image data when uploaded in SharePoint using an item event receiver.

SharePoint is a great tool for many things.  I find many applications for it in both the business world and the personal world.  I'm usually using MOSS (Microsoft Office SharePoint Server 2007) in most business scenarios and I use WSS (Windows SharePoint Services 3.0) for a lot of personal uses.  In either product, I find uploading photos a useful thing to do.  However, why should I have to go back and manually put in the date the photo was taken when my JPEG photos already contain this information?

The date the photo was taken as well as a lot of other information is embedded in certain image types, JPEG and TIFF being just two of those formats.  The standard for storing data in images is known as Exif.  Exif is an abbreviation for Exchangeable Image File Format.  I've written about how to use .NET to tap into this information here.

Now that we know how to get our date from our image, let's turn our attention to SharePoint.  In SharePoint, you have the ability to respond to events by way of "receivers."  We can respond to several different event receivers, here are a few:

  • SPItemEventReceiver - for responding to list item events, such as when we insert or update list item data
  • SPListEventReceiver - for responding to list structure changes, i.e. when new columns are created/modified
  • SPFeatureReceiver - for responding to feature activation and installation events

Since we want to intercept pictures as their loaded into a picture library, we're going to be interested in the SPItemEventReceiver.  We'll also need to use the SPFeatureReceiver to "wire everything up."  First, let's look at item events.

When items are inserted or updated in a list or document library, we can respond to those events.  Looking at possible overrides available on the SPItemEventReceiver class shows us some of the possible events.  We're interested in the ItemAdded event.

Before going too much further, lets talk about our Visual Studio project.  I'm using Visual Studio 2005 and STSDEV, which is a tool released by Ted Pattison on Codeplex.  This tool simplifies the creation of software that will be deployed in SharePoint.  There's a lot of good training on the Codeplex site so I won't go into the details.  In short, this tool simply creates my Visual Studio project from which I'll build my feature for looking at images.  Here's a snapshot of my Visual Studio solution:

Most of the files in the solution are created for me automatically.  I only need to modify the solution config XML file.  Again, there's training on the STSDEV site, so I won't go into that.  However, notice that there are two code files: FeatureReceiver.cs and PictureItemEventReceiver.cs.  FeatureReceiver is used to "wire up" the event to all picture libraries.  The PictureItemEventReceiver file is used to do the work of getting the image date and setting that in the item's metadata.

Let's look at the PictureItemEventReceiver file first.

    public class PictureItemEventReceiver : SPItemEventReceiver
    {
        public override void ItemAdded(SPItemEventProperties properties)
        {
            try
            {
                SPListItem item = properties.ListItem;

                if (item.File.Name.ToLower().EndsWith("jpg") || item.File.Name.ToLower().EndsWith("jpeg")) )
                {
                    Stream stream = properties.ListItem.File.OpenBinaryStream();

                    Image image = Image.FromStream(stream);

                    Nullable<DateTime> imageDate = GetImageDate(image);

                    if (imageDate != null)
                    {
                        properties.ListItem["Date Picture Taken"] =

                               ((DateTime)imageDate).ToString("MM/dd/yyyy hh:mm tt");

                        item.Update();
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(

                   string.Concat("Error obtaining image datestamp: ", ex.ToString()));
            }
        }

First we need to inherit from SPItemEventReceiver.  Then we override the ItemAdded event, which occurs after the image is added. 

    public class PictureItemEventReceiver : SPItemEventReceiver
    {
        public override void ItemAdded(SPItemEventProperties properties)

At this point, we get a reference of the item itself using the properties parameter. 

SPListItem item = properties.ListItem;

If the file is a JPG type, then we go about opening a binary stream from the File property of the item.  Next, we go about getting a System.Drawing.Image from the binary stream.  At this point, we are able to call another block of code (shown in a previous blog post here) that will get the date stamp out of the image.

        Stream stream = properties.ListItem.File.OpenBinaryStream();

        Image image = Image.FromStream(stream);

        Nullable<DateTime> imageDate = GetImageDate(image);

Once we have that date, then we can update the SharePoint list item metadata.

        properties.ListItem["Date Picture Taken"] =

              ((DateTime)imageDate).ToString("MM/dd/yyyy hh:mm tt");

        item.Update();

Note that we must update the date with the correct date format for SharePoint.  The call to GetImageDate retrieves the date from the Exif information embedded in the image.

Next, we turn our attention to the FeatureReceiver.  We need to tell SharePoint that we want to watch for ItemAdded events for all Picture Libraries.  The FeatureReceiver.cs file contains that code:

public class FeatureReceiver : SPFeatureReceiver
{
    private string assembly = "MetaPic, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce54f2f07031df02";
    private string receiver = "MetaPic.PictureItemEventReceiver";

    public override void FeatureActivated(SPFeatureReceiverProperties properties)
    {
        try
        {
            SPWeb site = (SPWeb)properties.Feature.Parent;

            // look for any picture library in the site
            for (int i = 0; i < site.Lists.Count; i++)
            {
                if (site.Lists[i].BaseTemplate == SPListTemplateType.PictureLibrary)
                {
                    // add the event receiver to wath for new images
                    site.Lists[i].EventReceivers.Add(
                        SPEventReceiverType.ItemAdded,
                        assembly,
                        receiver);
                }
            }
        }
        catch (Exception ex)
        {
            Trace.WriteLine(ex.ToString());
            throw;
        }
    }

In the FeatureReceiver, we inherit from SPFeatureReceiver.  This lets us respond to Activation/Deactivation events.  Upon activation of this feature, we enumerate through all lists that are of type SPListTemplateType.PictureLibrary.  For each one of these lists, we add an event receiver.

                    site.Lists[i].EventReceivers.Add(
                        SPEventReceiverType.ItemAdded,
                        assembly,
                        receiver);

Note that we must add the event type by specifying the proper enumeration SPEventReceiverType.ItemAdded.  Then we must pass in the fully-qualified name of the signed assembly and the actual receiver class.  This requires that you at least sign and build the project to get the public key token using Reflector or sn.exe.

Finally we clean up when the feature is deactivated using this chunk of code:

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
    try
    {
        SPWeb site = (SPWeb)properties.Feature.Parent;

        // look for any picture library in the site
        for (int i = 0; i < site.Lists.Count; i++)
        {
            if (site.Lists[i].BaseTemplate == SPListTemplateType.PictureLibrary)
            {
                // find and remove the event handler
                foreach (SPEventReceiverDefinition receiver in site.Lists[i].EventReceivers)
                {
                    if (receiver.Type == SPEventReceiverType.ItemAdded)
                    {
                        receiver.Delete();
                        break;
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        Trace.WriteLine(ex.ToString());
        throw;
    }
}

This code runs when the feature is deactivated and removes the event receivers previously added.  You'll want to activate this feature after you create one or more picture libraries.

Room for Opportunity

While the solution here is pretty cool, there are some things I'd like to address someday.  Here are some of them:

1. Add to the event receiver to a content type instead of each picture library so you don't have to re-activate the feature each time a new picture library is created.
2. Fix the user interface when a single image is loaded.  When a single item is uploaded you're sent to the edit page, but that page shows the date info as blank when the date is really there.  It really needs to be displayed as a read-only field.  Here's what you see:

And if you simply navigate to the image without updating, you see that it is there.

Multiple file upload, which is most useful, works great (of course I changed my view to show the date info):


3. Obtain image data upon adding the image to the document library instead of after the image has already been added.  Right now, we're going through an additional step to re-open the image.  It would be better to intercept the upload stream.

I hope you enjoy this.  I know I'll get a lot more use out of the picture library now that I can get date information out of my images.  Hopefully, you can use the above code to look into other event receiver concepts.

Tuesday, May 27, 2008

Kentucky Area Code Camp 2008

I'm co-leading the KY Day of .NET code camp for this Summer.  If you're interested in speaking or volunteering, please check out the details here.

Thursday, May 22, 2008

Creating Connection Strings in 30 Seconds with UDL Files

I did this once in a training session and the class was amazed.  For years, I've been whipping out connection strings using a little-known technique involving UDL (Universal Data Link) files.  Here's the trick:

1. Create a new text file on your desktop and rename it to "Test.UDL" instead of the default  ".TXT" extension.  You'll need to show file extensions for this.

2. Next, double-click on this file to open up a connection string editor called "Data Link Properties."

3. Change to the Provider tab and choose the provider (OLE DB Provider for SQL Server in this example).

image_8_6A764D87.png (377×471)

4. Change to the Connection tab and set your basic connection settings.  You can also test your connection at this point if you want.

image_10_6A764D87.png (377×471)

5. Set any additional settings in the Advanced and/or All tabs, such as Connection Timeout.  Then click OK to save the file.

image_12_6A764D87.png (377×471)

6. Open the .UDL file with notepad and there you go...

Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=TestDB;Data Source=localhost

You can remove the property called "Persist Security Info" because it's only used by the tool itself.  Enjoy.

Monday, February 4, 2008

SharePoint in the Kitchen

Synopsis: This is about how I tried to use SharePoint in the home for simple calendaring -- in our kitchen.

Ok.  I'm a geek.  My kids will certainly come to appreciate that some day.  I love gadgets and such.  I guess that comes from the influence of Star Wars and the like.  What was so cool about those movies was that technology was so integrated into everyone's life.  The movies made the technology appear dependable, omnipresent and just down right cool.

My Grand Plan

So when it comes to my own life, I try to make technology just blend into the background and be helpful to our lives.  I had this old Sony VAIO laptop from 1998 that I was just itching to use somewhere in the house, because it was still cool to look at -- it was one of the super slim designs which is less than an inch think when folded up.  Unfortunately, it's dog slow these days, but ok for some simple browsing.  I'm running Windows 2000 on it.  I can't believe I used it as a dev machine (Classic ASP and VB). 

Anyway, I came up with the great idea of displaying the family calendar so my wife always knows what's going on with family events.  So I cleaned up the kitchen counter (just enough to place the laptop there) and plugged in an external wireless adapter and pointed it to a SharePoint site, which is running on a machine in the basement... I mean, my server room.  I used SharePoint Designer to create a custom page which showed just the family calendar and I dropped some JavaScript that refreshes the page.  Then I point my browser to it in full-screen mode and it looks something like this:

image

To update this calendar, I can use the SharePoint interface or I can use Outlook 2007.  From within SharePoint (WSS or MOSS), you can add two-way synchronization to an event calendar very easily (only with Outlook 2007, however).  Just navigate to the calendar within SharePoint and choose "Add to Outlook" from the Action menu of my SharePoint site.

image

After that, you can just go into SharePoint and edit the calendar data that is stored in SharePoint.  Very slick.  There are other client integration points with Office 2007, but I will have to talk about that in another post.

Ok.  My wife just loves this... NOT.  I thought about taping the laptop to the fridge to increase visibility, but that was quickly shot down for some reason.  For now she lets me keep it on the counter.  However, she doesn't use it.  Why not?  Doesn't this provide all the information one might need at a glance?  It's it cool. 

What's Really Cool?

Someone to use and truly love your software day in and day out -- that's cool (at least if you're a developer-type like me).  I've developed enough software to realize that just because you have something that looks cool and seems to address the needs of the user (and does exactly what they asked for), you're not always guaranteed a win.  If what you build doesn't get used, you're just wasting time (which means money -- mine or somebody else's).

"So what can I do to make this better?," I asked myself.  Well, when looking at the calendar, I don't always need to see the past history.  I really just need to see today and then a few days ahead.  The font is really too small.  I also think it would be helpful to see a short list of tasks.  And I'm not really saving the screen here.  I'm wearing it out since the page is always the same and the screen saver is turned off.

When I looked at the platform I was running on, I thought the use of a screen saver might be good here.  A screen saver would be pretty clean from a usability perspective.  And there's a sample project in Visual Studio just for that.  I know that I probably could have done something with dynamic HTML or Silverlight, but I was really curious to see how to make a screen saver for some reason.

You can actually do this with minimal work since the sample screen saver application allows you to point to an RSS feed.  Since any SharePoint list or document library can expose itself as an RSS feed, you're set.  Well that is until you decide to want to display things like tasks and calendar items on the same screen with nice fade-in and fade-out functionality.  Below is the starter project you can use.

image

So it might be nice to use this project to display SharePoint data.  Maybe I could tap into the SharePoint web services interfaces.  But for now I have a simple calendar view that displays full-screen in a browser.  It's OK, but I really think a screen saver would be more interesting.  That's for a future post.

Tuesday, December 11, 2007

Accessing JPEG Exif Information in .NET

Syopsis: How to JPEG access date/time information from .NET code.
If you've ever looked at the properties of one of your digital photos, you've noticed a ton of information in the Details tab such as the date the picture was taken, what kind of camera was used, and many other camera details such as aperture, exposure, etc.
This information is supplied for you by the camera and stored in the picture when it is taken.  Thankfully, all cameras use the same format when recording this metadata in their resulting JPEG or TIFF images.  The name of this format is Exif.
Exif is an abbreviation for Exchangeable Image File Format.  This standard basically spells out the properties that can be stored with an image.  There are a lot of properties available.  I've listed a few below and you can read more on it here and here.
Friendly Tag Name Tag Value (Hexadecimal) Sample Value Data Type Detail
Manufacturer 010f Canon ASCII String
Model 0110 Canon DIGITAL IXUS ASCII String
Date and Time 9003 2003:08:11 16:14:32 ASCII String YYYY:MM:DD HH:MM:SS
Flash 9209 0 Unsigned Short 0 indicates that the flash did not fire.
Aperture Value 9202 262144/65536 Unsigned Rational Indicates the amount of light the camera lets in.
Firmware Version 0007 Firmware Version 1.0 ASCII String

Retrieving the Date/Time

What we're concerned about here is the date and time the picture was taken.  In .NET we can easily tap into that data by using PropertyIdList and the PropertyItems properties of an instance of the System.Drawing.Image class.  PropertyIdList gives us a listing of the Exif tags available in integer format.  And PropertyItems gives us access to those values in a byte array.  One collection for both of these would have been nice, but I can't really complain.
So, the first step is to open our JPEG image and get an Image instance to work with:
Image image = Image.FromFile(fileName);
Next, we'll loop through all the tag ID's and find the date/time tag that we're looking for (0x0132):
int tagIndex = -1;
for (int i = 0; i < image.PropertyIdList.Length; i++)
{
    if (image.PropertyIdList[i] == Int32.Parse("132", NumberStyles.HexNumber))
    {
        tagIndex = i;
        break;
    }
}
The next step is to lookup the particular value and translate that to ASCII text that we can work with.
PropertyItem item = image.PropertyItems[tagIndex];
dateString = ASCIIEncoding.ASCII.GetString(item.Value);
Finally, let's go ahead and stuff that date back into a real DateTime structure for easy encapsulation.
string[] dParts = dateString.Split(new string[] { ":", " " }, StringSplitOptions.RemoveEmptyEntries);
int year = Convert.ToInt32(dParts[0].Trim());
int month = Convert.ToInt32(dParts[1].Trim());
int day = Convert.ToInt32(dParts[2].Trim());
int hour = Convert.ToInt32(dParts[3].Trim());
int minute = Convert.ToInt32(dParts[4].Trim());
int second = Convert.ToInt32(dParts[5].Trim());

date = new DateTime(year, month, day, hour, minute, second);
Now that we have our pieces, we'll go ahead and create a nice, clean method that we can use on any given image object:
private static Nullable<DateTime> GetImageDate(Image image)
{
    int tagIndex = -1;

    Nullable<DateTime> date = null;
    // find the index of the id we're looking for
    // Note: the Exif specification at
http://exif.org specifies 0x9003 for
    // the date/time the image was taken
    for (int i = 0; i < image.PropertyIdList.Length; i++)
    {
        if (image.PropertyIdList[i] == Int32.Parse("9003", NumberStyles.HexNumber))
        {
            tagIndex = i;
            break;
        }
    }

    // return if the tag is not found
    if (tagIndex < 0) return null;

    // parse the date string which is in the format: yyyy:mm:dd hh:mm:ss
    string dateString = null;

    try
    {
        PropertyItem item = image.PropertyItems[tagIndex];
        dateString = ASCIIEncoding.ASCII.GetString(item.Value);

        string[] dParts = dateString.Split(new string[] { ":", " " }, StringSplitOptions.RemoveEmptyEntries);
        int year = Convert.ToInt32(dParts[0].Trim());
        int month = Convert.ToInt32(dParts[1].Trim());
        int day = Convert.ToInt32(dParts[2].Trim());
        int hour = Convert.ToInt32(dParts[3].Trim());
        int minute = Convert.ToInt32(dParts[4].Trim());
        int second = Convert.ToInt32(dParts[5].Trim());

        date = new DateTime(year, month, day, hour, minute, second);
    }
    catch { }
    // in case of an exception, we'll just ignore it and not return a date

    return date;
}
Now you can drop the above code in any application and have some fun.

Monday, September 24, 2007

SuperBranding

If you’ve ever modified a WSS/MOSS master page only to be frustrated that some pages never change their look you'll want to look into a solution to this that Ted Pattison posted on CodePlex.  The reason for this disparity is that SharePoint has two master pages: Default.master and Application.master.  Default.master is what you'll be editing from within the SharePoint Designer and is something that can be customized from the site definition.  Conversely, anything that lives in the _layouts directory are called application pages and cannot be customized for each site.  These pages are accessible by any SharePoint site and are usually used for settings pages like /_layouts/settings.aspx.  These application pages all point to a master page that is different than the customizable master page and is called application.master.  The way Ted's solution works is to intercept the request using an HttpModule and determine if the page is pointing to application.master.  If so, it swaps out the reference to default.master instead.  I would expect that the next version/service pack should take care of this little nuisance.

Saturday, September 1, 2007

KY Day of .NET

Yesterday we had a day-long code camp in Louisville.  It was a great success with about 70 people attending.  We covered topics from WCF, to SQL 2008, to LINQ.  I had the privilege of covering WCF.  It was a good preparation for me since I'll be doing the September DevCares on WCF on the 28th.  A summary of all the sessions can be found here: kydayof.net.