Noah Blumenthal's Blog

October 28, 2008

ASP.NET Strongly Typed Profile

Filed under: Uncategorized — noahblu @ 5:08 pm
Tags: ,

I’m not a huge fan of the out-of-the-box functionality of ASP.NET Profiles.  I really dislike the way everything is is just serialized as a blob and there’s no out-of-the-box alternative.  That aside, I’m using Profiles for an ASP.NET MVC site right now and wanted a way to strongly type the data (and remove the need for string literals).  Here’s what I ended up with:

public class StronglyTypedProfile
    {
        private ProfileBase profile;

        public int MerchantId
        {
            get
            {
                object ob = profile.GetPropertyValue("MerchantId");
                if (ob == null)
                    return -1;
                return (int)ob;
            }
            set
            {
                profile.SetPropertyValue("MerchantId", value);
            }
        }

        public string ForumNick
        {
            get { return (string)profile.GetPropertyValue("ForumNick"); }
            set
            {
                profile.SetPropertyValue("ForumNick", value);
            }
        }

        public string FirstName {
            get
            {
                return (string)profile.GetPropertyValue("FirstName");
            }
            set
            {
                profile.SetPropertyValue("FirstName", value);
            }
        }

        public string LastName
        {
            get
            {
                return (string)profile.GetPropertyValue("LastName");
            }
            set
            {
                profile.SetPropertyValue("LastName", value);
            }
        }

        public void Save()
        {
            profile.Save();
        }

        private StronglyTypedProfile() { }
        public static StronglyTypedProfile Create(string username)
        {
            StronglyTypedProfile p = new StronglyTypedProfile();
            p.profile = ProfileBase.Create(username);
            //profile = ProfileBase.Create(username);
            return p;
        }
    }

Now I can use it like so:

StronglyTypedProfile profile = StronglyTypedProfile.Create(Username);
profile.FirstName = u.FirstName;
profile.LastName = u.LastName;
profile.Save();

Very simple, and it works.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: