One thing people often need to do in Community Server, especially when customizing it, is to save custom data. Of course, if you’re feeling brave, you can always edit the database schema and related Data Providers as well as extending the relevant class (Weblog, Gallery, User etc.). Now this method is not without its merits, such as easier searching based on these new values, plus better performance where the values are to regularly accessed, and as ever, such factors should always be taken into account when extending Community Server.
What I want to talk about however, is the case where you want to simply store some extra information with an object. For example, one common request is to save extra contact information against a user. Currently, Community Server allows you to add IM addresses for MSN, AOL, Yahoo and ICQ contact details to a user’s profile, but you might want more! Another example might be that you wish a user to accept some specific terms/rules before you allow them to use your site (this came up on a recent client installation) so you need to record the date/time when they accepted.
By far the easiest way to achieve this is by using ExtendedAttributes. Most of the major classes in CS inherit from ExtendedAttributes such as User, Post & Section (in turn Weblog, Gallery, Forum etc inherit from Section as WeblogPost, GalleryPost etc. inherit from Post). All of these classes have two methods that you can use to set and retrieve this data and these are GetExtendedAttribute() & SetExtendedAttribute(). Under the hood, the ExtendedAttributes class uses a NameValueCollection object to store the data so naturally, SetExtendedAttribute()requires just two parameters; name and value.
So, to assign a users GoogleTalk address:
User user = CSContext.Current.User; // Get the logged on user.
user.SetExtendedAttribute("GoogleTalkAccount", "usersaccount"); // Set the new details.
Users.UpdateUser(user); // Save the changes.
And to retrieve that data:
string googleTalkAccount = user.GetExtendedAttribute("GoogleTalkAccount");
Or, to set the date that a user accepted the terms to your site;
User user = CSContext.Current.User; // Get the logged on user.
user.SetExtendedAttribute("TermsAccepted", DateTime.Now.ToString()); // Set the date.
Users.UpdateUser(user); // Save the changes.
And again, to retrieve this:
DateTime termsAccepted = Convert.ToDateTime(user.GetExtendedAttribute("TermsAccepted"));
Of course, normally, you’d need to check the above string before trying to cast it as a DateTime, but we’ll skip that for the purposes of this article. As a side note, if the ExtendedAttribute doesn’t exisit in the colletion, GetExtendedAttribute() will return an empty string.