I recently worked on a project whereby the user needed to upload one or more files, and store metadata for these files. As most of the metadata was reflected in parts of the filenames, there was also a need for an automated process to extract and pre-populate to the relevant fields upon upload.
The solution consisted of a document library with custom columns to hold the metadata. The automation process was taken care by event handlers. Upon a file upload, the event handler would try to extract metadata from the filename, and populate the values into the metadata fields in the edit form page. The user could then choose to accept or modify the metadata.
Sample code goes here - coming soon!
A few important/useful notes…
- Brian Wilson wrote a great set of tutorials on SharePoint event handlers.
- Don’t forget that when creating an event handler class, it must inherit SPItemEventReceiver.
- In my scenario above, the best place to put the code was in ItemAdding, as oppose to ItemAdded. One big difference between the two methods is that ItemAdding is synchronous. This means that the page will wait for the code to finish execute before displaying the metadata screen – perfect for me to extract and populate metadata values from filenames. ItemAdded, on the other hand, is asynchronous. Hence the page will not wait until the code has finished executing.
- Use properties.AfterProperties, as oppose to BeforeProperties.
- Dispose SPSite and SPWeb objects as required. Roger Lamb has a nice and clear explanation about WSS 3 and MOSS 2007 dispose pattern.
- In most cases, you will need to refer to list fields by their internal names, except when the field name contains full stops (“.”) - I’ll come back to this in the future with some explanation why.
- For development purposes, use third party tools such as SharePoint Inspector to attach the event handlers to the list, as oppose of building and deploying features to do this.