July 24, 2012

Setting DateTime, Boolean Values in SharePoint Property Bag

There are many cases in which the SharePoint object model provides access to fields/properties via a "property bag," which is really an SPItemEventDataCollection object containing string/value pairs. One of the places I use this most often is in list event receivers - on the ItemAdding event, for example, properties.ListItem will return null because the SPListItem object hasn't been created yet. So to perform validation or update metadata values in code, we must use the properties.BeforeProperties and properties.AfterProperties collections.

Today I was working on a project which required me to set an item's values in the ItemAdding event so that when the New Item dialog appears some fields would be prepopulated. This required me to set values using the AfterProperties collection, which I've done plenty of times before and expected to have no problem with. In this case I was getting the values from an SPListItem, so my code started out as simple as this:

properties.AfterProperties["DateValue"] = listItem["DateValue"];

This worked for most fields: text, numerical, and even user fields. But for DateTime and Boolean (Yes/No) fields, the string values output by the get method didn't match the format expected by the set method. That's messed up yo!

For DateTime fields (DateTime or DateOnly doesn't matter), it turns out you can't use a standard system DateTime object. The date needs to be in ISO 8601 format. The best way to get this is by calling the Microsoft.SharePoint.Utilities.SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime dt) utility method. Thanks to this blog post from Anjali Chelawat for helping me out.

For Boolean (Yes/No) fields, the only way I was able to get it to work (there may be alternatives that work as well) was to set the value as a lowercase string ("true" or "false"). Using the boolean value directly didn't work, nor did using the .ToString() method, which output "True" and "False" indicating that apparently the capitalization matters (which we've seen before in silly places, haven't we?).

So that's it - two very basic solutions, which took me WAY too long to figure out. Hopefully now you won't find yourself wasting as much time :)

No comments:

Post a Comment