Home / Marketing / Creating Bit.ly shortened URL’s from Windows Phone 7 in C#

Creating Bit.ly shortened URL’s from Windows Phone 7 in C#

You’re no doubt familiar with URL shorteners on sites such as twitter, where they are practically mandatory. For example, my previous post,  How to Create Screenshots for Windows Phone 7 Marketplace without a Phone, weighs in at a hefty 109 characters. And that’s without any tracking codes that may be mandatory for marketing or affiliate programs. But with the use of any URL shortener (Bit.ly in this case), we’re down to a mere 20 characters (http://bit.ly/rc72Ac).

URL shorteners have other advantages as well. If you’re working with affiliate programs typically the only way you get paid is by placing your affiliate code in the URL itself. Affiliate directories will also typically add some tracking variables to the URLs, and you’re left with a long ugly URL that’s downright unseemly to include in an email, share on a facebook wall, or anywhere else you cannot control the link text being presented. And there is alos the cance people will use the URL and just omit your affiliate code, for whatever reason. URL shorteners can help prevent this.

In addition, most provide some excellent tracking and analytics  – often in real time and for free. You can view number of clicks,  referrers, county of origin, even get a QR code if you wish.

Any decent URL shortener will come with an API, and many of these services have C# libraries for interfacing with them directly. I chose  bit.ly for this example, but most services have a very similar API.

Signing up for an account is straigtforward, and once you do so you’ll automatically have an API key on your “Settings” page. There is already a codeplex project for a bitly library, but unfortunately it does not work for Windows Phone 7. Most other examples found online use synchronous calls which is not permitted in WP7 programming (for good reason), so we’ll start from scratch.

To make any API call, you’ll need to supply your username, and your API key. Simply log in to your account and go to http://bitly.com/a/your_api_key. Bitly offers a standard REST based API, the full documentation can be found by following the “API” link at the bottom of their page. Documentation for the method we’ll be looking at to shorten a URL can currently be found here:

/v3/shorten

For a long URL, /v3/shorten encodes a URL and returns a short one.

Parameters

  • format (optional) indicates the requested response format. supported formats: json (default), xml, txt.
  • longUrl is a long URL to be shortened (example: http://betaworks.com/).
  • domain (optional) refers to a preferred domain; either bit.ly, j.mp, or bitly.com, for users who do NOT have a custom short domain set up with bitly. This affects the output value of url. The default for this parameter is the short domain selected by each user in his/her bitly account settings. Passing a specific domain via this parameter will override the default settings for users who do NOT have a custom short domain set up with bitly. For users who have implemented a custom short domain, bitly will always return short links according to the user’s account-level preference.
 Two important points: the URL must be URL encoded. No spaces, question marks, or any other odd characters. Also, the format parameter can specify either text , XML, or JSON. Text is the simplest to work with – only the shortened URL is returned. If you’re only working with one link to shorten at a time, this is an obvious choice. However,  if you’ll be sending multiple requests to bitly at one time, or you can’t guarantee the return order of your requests, you’ll want to use XML or JSON. Both of these return both the shortened URL and the original, so you can match them if necessary.
For this example, we’ll just use text, since in my app we’ll never be submitting multiple requests per page. To shorten the URL in bitly, all you need is open a web request to the URL specified by the API:
  1.  
  2. string url = string.Format(@"http://api.bit.ly/v3/shorten?login={0}
  3. &apiKey={1}&longUrl={2}&format=txt",
  4. BITLY_LOGIN, BITLY_API_KEY, HttpUtility.UrlEncode(longUrl));
  5.  
  6. WebClient wc = new WebClient();
  7. wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
  8. wc.OpenReadAsync(new Uri(url));
  9.  

Since we specified the text format, the result will contain the URL only:

  1.  
  2. void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
  3. {
  4. Stream stream = e.Result;
  5. var reader = new StreamReader(stream);
  6. var shortenedUrl = reader.ReadToEnd();
  7. }
  8.  

I’ve wrapped the above methods in a class that you can find on github. To use, simple call the Shorten method with a callback, like so:

  1.  
  2. new WP7NetHelpers.BitlyShorten().Shorten(
  3. HttpUtility.UrlDecode(ProductFeed.Instance.URL),
  4. this.ShortenCallback);
  5.  
  1.  
  2. private void ShortenCallback(string url)
  3. {
  4. // do something with url;
  5. }
  6.  

Enjoy!