"Tweet This" Link with TinyURL in ASP.Net
14. March 2009 10:59

In migrating to my new blog platform, one thing that I am really excited about is now being able to put custom code to power features I was not able to have in Google Blogger.

The first thing I did was add some code-behind to my user controls to generate good "Tweet This" links so that users could Tweet my posts on Twitter.

 

Most samples you see for this simple stick your page URL in the query string.  This doesn't often work, as the URL will be too long, as the user won't be able to tweet the message.

 

I create two functions behind my page, TweetThisLink and TinyUrl

 

    public string TweetThisLink(string Url, string Title)
{
return "http://twitter.com/home?status=@StefanGordon Reading "
              + TinyUrl(Url) + " " + Title;
}

public string TinyUrl(string Url)
{
try
{
if (!Url.ToLower().StartsWith("http") && !Url.ToLower().StartsWith("ftp"))
{
Url = "http://" + Url;
}
WebRequest request =
                  WebRequest.Create("http://tinyurl.com/api-create.php?url=" + Url);
WebResponse res = request.GetResponse();
string text;
using (StreamReader reader = new StreamReader(res.GetResponseStream()))
{
text = reader.ReadToEnd();
}
return text;
}
catch (Exception)
{
return Url;
}
}

From my ASPX page, I can now insert a nice "Tweet This" link as follows:

<a href="<%=TweetThisLink(Post.PermaLink.ToString(), Server.HtmlEncode(Post.Title)) %>">
Some image or text </a>
Tags: , , Comments (1) | Permalink