Developing a Link Chopper using C# and Bit.ly API in 1 Hour

I just spent an hour today to develop a very small tool (Just 130 KB) for Shortening the links using the API provided by bitly. I call it Link Chopper. I wrote it just for fun and to explore bit.ly API. I have Link Chopper ready and you can download it for free from this link Download LinkChopper. You dont have to say thanks as it is a no big stuff :)

The tool gives an option for users to enter a long URL and generate a short bit.ly url with just one click.

Also, the short URL is copied to clipboard automatically so that users can just paste it wherever required. Link Chopper comes with basic functionality to clear the controls & launch the URL in browser.

Its a very simple tool and anyone can use it. I have used the background worker to generate the URL in the background while displaying the progress to user without blocking him.

However, if you are a developer and interested in the code to generate the short url, read further.

  1. First, create a free bit.ly account. Go to https://bitly.com/a/sign_up. Of course, if you have a Facebook or twitter account, you can use that as well.
  2. Login to your bit.ly account using your credentials and then visit this link http://bitly.com/a/your_api_key/ . You will see a screen something like below (Do not use this same exact key. It doesn't work either as I have scrambled it. So, use your own keys)
I know you cannot wait anymore to see the code. Here is the function which can generate a Short URL.

/// <summary>
/// If you pass a Long URL, the bitly USER ID and THE API Key, this function will shorten the URL and return it back to caller
/// </summary>
/// <param name="i_sLongUrl">Long URL</param>
/// <param name="i_sBitlyUserName">User ID</param>
/// <param name="i_sBitlyAPIKey">API Key</param>
/// <returns>URL if succeeds or Status if Fails</returns>
/// <remarks></remarks>
public static string GetShortUrl(string i_sLongUrl, string i_sBitlyUserName, string i_sBitlyAPIKey)
{

    //Construct a valid URL and parameters to connect to Bitly Server
    StringBuilder sbURL = new StringBuilder("http://api.bitly.com/v3/shorten?");
    sbURL.Append("&format=xml");
    sbURL.Append("&longUrl=");
    sbURL.Append(HttpUtility.UrlEncode(i_sLongUrl));
    sbURL.Append("&login=");
    sbURL.Append(System.Web.HttpUtility.UrlEncode(i_sBitlyUserName));
    sbURL.Append("&apiKey=");
    sbURL.Append(System.Web.HttpUtility.UrlEncode(i_sBitlyAPIKey));

    HttpWebRequest objRequest = WebRequest.Create(sbURL.ToString()) as HttpWebRequest;
    objRequest.Method = "GET";
    objRequest.ContentType = "application/x-www-form-urlencoded";
    objRequest.ServicePoint.Expect100Continue = false;
    objRequest.ContentLength = 0;

    try {
        //Send the Request and Get the Response. The Response will have the status of operation and the bitlyURL
        WebResponse objResponse = objRequest.GetResponse();
        StreamReader myXML = new StreamReader(objResponse.GetResponseStream());
        dynamic xr = XmlReader.Create(myXML);

        //Retrieve the Status and URL from the Response
        XmlDocument xdoc = new XmlDocument();
        xdoc.Load(xr);

        string sStat = xdoc.ChildNodes(1).ChildNodes(1).ChildNodes(0).Value;
        if (sStat == "OK") {
            return xdoc.ChildNodes(1).ChildNodes(2).ChildNodes(0).ChildNodes(0).Value;
        } else {
            return sStat;
        }

    //I know the above code is dirty. You can use Linq to make it good and beautiful. 
    //I did not wanted to use linq and inteded to finish it fast. However, it works!
    //the xml node status_txt will have the status of the operation and the tag url will have the link.
    //Instead of above code, Something like below code can make your code Neat. Leave the comments as as it is if you do not like to get your hands dirty

    //dynamic xdoc = XDocument.Load(xr);
    //if (xdoc.Descendants("status_txt").Value == "OK") {
    //    return xdoc.Descendants("url").Value;
    //} else {
    //    return xdoc.Descendants("status_txt").Value;
    //}
    } catch {
        return "SOME_OTHER_ERROR";
    }
}

And, you can call it like

var sShortUrl = 
GetShortUrl("http://wwww.xyz.com/a_long_xyz_url_which_is_really_boring.html", "23567o_6das567dflpu567m34dl", "R_4e957fe279asdfasdfasdf03be81asdffbfefcc38c40e2b463") 
Make sure you replace the above parameters with valid ones. Especially your bitly User Name and Key

Popular posts from this blog

Facebook Javascript API : Feed and Share Dialog for Beginners

What's new and expected in .NET Framework 4.5

Real time Push Notifications with SignalR & PNotify (Pines Notify)