ninja star Adding a “Tweet This” Button To Your Blog Posts

by Michael Ceranski, posted on February 02 2010

 

Update 2/12/2010: I am now using the AddThis widget below my posts. It gives you the same functionality as the "Tweet This" button but also works with dozens of other social networking sites. The only problem with AddThis is that it currently does not shorten URLs but according to the forum it is in progress.


Twitter is a great tool for sharing information with others. As a blogger I will commonly send tweets to my followers when I post new content. The tweet message generally has a brief description along with the URL. However, not everyone who reads my blog, follows me on twitter. Therefore, I thought it would be nice to add a button to the bottom of each blog post which allows anyone to send a tweet about one of my articles. The format for updating a twitter status message by using the REST API is: http://twitter.com/home/?status=<message>

Simple enough! I can just add a button to my page and dynamically set the status variable in the query string with the article title and url, Right? Well not exactly, If you are familiar with twitter then you know that a tweet can not exceed 140 characters. Therefore a message containing the title and url of the article could easily go over the maximum length. The workaround for this is to shorten the url using bit.ly. If you are unfamiliar with bit.ly or the API then please see my previous post.

Since I am using BlogEngine.net, the main page of my site is customizable and allows me to modify the number of posts that are displayed. Typically I display between 5-10 posts at a time. For this reason, I immediately ruled out using an inline function to generate the shortened url on the fly. Mainly because each function call would require a separate round trip to the Bit.Ly server and it would drastically increase the load time for my website.

Therefore, I decided that I would create a new page named TweetIt.aspx which I would use as a redirect. So below each post I can add a new link to the TweetIt.aspx page which passes in a few variables. The variables are used to build the status message for the tweet. Here is an example of the formatted url:

http://www.somesite.com/TweetIt.aspx?url={0}&title={1}

In particular, if you are using BlogEngine.Net you add this button by modifying the PostView.ascx file in your theme directory to include the following HTML:

<a style="float:right" ref="nofollow" target="_blank" 
   href="/TweetIt.aspx?url=<%=Server.UrlEncode(Post.AbsoluteLink.ToString()) %>&title=<%=Server.UrlEncode(Post.Title) %>">
<img src="/pics/tweet_this.png" alt="tweet this">
</a>

tweet_this (Here is the image I used, Right-click and "Save As...")

To break it down, when a request is made to the TweetIt.aspx page, The Page_Load event is fired. In the Page_Load event I verify the existence of the url and title request variables. If the variables are valid, then I do a simple security check to make sure that the url being shortened is from my domain. This prevents people from using my redirect page for other sites. Moving on, if the url is valid then I shorten it using the bit.ly service. The results from the bit.ly service are passed back as a JSON result so I parse them using regular expressions. Finally, I redirect the user to the twitter site with an updated status.

Below you will see the code for the TweetIt.aspx page. However, before using this code you will need to replace the constants at the top of the class:

const string STATUS_SUFFIX = "by @your_twitter_name"; 
const string BITLY_API_USERNAME = "<bit.ly username>";
const string BITLY_API_KEY = "<bit.ly api key>";
const string SITE_BASE_URL = "http://www.<your domain>.com";

void Page_Load(object sender, EventArgs e) {
    string twitterUrlFormat = "http://twitter.com/home/?status={0}";

    //if you don't pass in the url then ignore the request
    if (String.IsNullOrEmpty(Request["url"])) {
        Response.Write("Please specify the url");
        Response.End();
    }

    if ( Server.HtmlEncode(Request["url"]).ToUpper().StartsWith( Server.HtmlEncode(SITE_BASE_URL).ToUpper() ) == false) {
        Response.Write("This service is for articles from " + SITE_BASE_URL + " only");
        Response.End();
    }

    string status = "";        
    
    try {
        string bitlyUrl = GetBitlyUrl(Request["url"]);            
        string title = Request["title"];            

        status = String.Format("{0}: {1} {2}", title, bitlyUrl, STATUS_SUFFIX);
        
        //if all the text will fit then show it all
        if( status.Length > 140 ) {
            //the title and url are over 140 so we will "shrink" the title down and exclude the suffix
            if ((title.Length + bitlyUrl.Length) > 140)
            {
                //shrink the title
                title = Request["title"].Substring(0, 140 - (bitlyUrl + "... ").Length);
                status = title + bitlyUrl;
            }
            else
            {
                //just set the title and author
                status = title + bitlyUrl;
            }
        }
        
        string twitterUrl = String.Format(twitterUrlFormat, status);
        Response.Redirect( twitterUrl);
    }
    catch {
        //something went wrong!    
        Response.Write("Sorry, An Error Has Occured. Please Try Again Later");
    }        
}

private String GetBitlyUrl(String longUrl) {
    string apiUrl = String.Format("http://api.bit.ly/shorten?version=2.0.1&longUrl={0}&login={1}&apiKey={2}",
                                              longUrl,
                                              BITLY_API_USERNAME,
                                              BITLY_API_KEY);
    string shortUrl = "";        
    System.Net.HttpWebRequest request = System.Net.WebRequest.Create(apiUrl) as System.Net.HttpWebRequest;        
    
    using (System.Net.HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse) {
        System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
        String jsonResults = reader.ReadToEnd();
        string pattern = "(?<shortUrl>http://bit.ly/[0-9a-zA-Z]*)";
        System.Text.RegularExpressions.Match m = 
            System.Text.RegularExpressions.Regex.Match(jsonResults, pattern, RegexOptions.IgnoreCase);
        if (m.Success == true) {
            shortUrl = m.Groups["shortUrl"].Value;
        }
    }
    return shortUrl;
}
</script>
blog comments powered by Disqus

About the author

MikeMichael Ceranski is a developer specializing in the .NET stack. I have spent time as a DBA, Web Developer and even a network engineer. Up til now most of my career has revolved around the .NET stack but I have recently taken an interest in microcontrollers which has forced me to get acquainted with lower level languages such as C, and C++.

View my resume

Sponsors