MVC Helper for Gravatar

Jus a quick code snippet for display a user’s Gravatar in MVC;

public static MvcHtmlString DisplayGravatar(this HtmlHelper helper,
            string emailAddress, int size=80)
        {
            return new MvcHtmlString("<img src=" + 
                GravatarUrl(helper, emailAddress, size) + " />");
        }

        public static string GravatarUrl(this HtmlHelper helper, 
            string emailAddress, int size=80)
        {
            if (size < 1 || size > 512)
            {
                size = 80;
            }
            //1.Trim leading and trailing whitespace from an email address            
            //2.Force all characters to lower-case
            emailAddress = emailAddress.Trim().ToLower();
            //3.md5 hash the final string
            string md5Hash = GetMD5Hash(emailAddress);

            return string.Format("http://www.gravatar.com/avatar/{0}?s={1}",
                                                            md5Hash, size);
        }

        private static string GetMD5Hash(string input)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider x =
                new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bs = System.Text.Encoding.UTF8.GetBytes(input);
            bs = x.ComputeHash(bs);
            System.Text.StringBuilder s = new System.Text.StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2").ToLower());
            }
            string password = s.ToString();
            return password;
        }
Advertisements
This entry was posted in MVC. Bookmark the permalink.

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