How to shorten a link with Bitly and share it in a Windows Store app

I am working on a Windows Store app where one of the features is to share shortened links. This is a brief description on how I solved it.


You can find a long list of different link shorteners at Programmable Web. I will use Bitly mostly because I used it before with success. The signup process and app registration is easy. Here is a blog post describing it in detail: Bitly API: Authentication.

Windows Store App Setup


We will not spend any time with the UX in this example. Simply put the following XAML in the MainPage.xaml:


This example will not use any MVVM architecture whatsoever, all code is placed in the code-behind file MainPage.xaml.cs.
Start by adding an event handler for the DataRequested event.

Then handle the DataRequested event by editing the DataRequestedEventArgs DataPackage object. This would be all code needed if we were to share something we already have. See example: How to share a link (Windows Store apps using C#/VB/C++ and XAML).

But we will make an asynchronous call to Bitly before we have the link to share. Therefore we set a Dataprovider in the last line to handle the actual Bitly call. You can find more info here: How to make asynchronous calls in your DataRequested handler (Windows Store apps using C#/VB/C++ and XAML).

UrlEncode the input we are about to send to Bitly. You find the method in the namespace System.Net.WebUtility for WinRT.

We need a DataRequestDeferral object when doing asynchronous methods after the DataRequest event. To get a deferral object, we call GetDeferral().

Then we use Bitly to shorten the input link and add it as content to the DataPackage. Please use your own Bitly credentials in place of ”PutYourUserNameHere” and “PutYourOwnApiKeyHere”.

Remember to call deferral.Complete() in all code paths.

I ran into an issue with this code when navigating from the page and back again because of the event registration: “WinRT information: An event handler has already been registered”. I solved it by removing the event in the PageUnload event:

Finally handle the button tap to programmatically initiate the user interface for sharing content with an another app:

Final Code

Here is the complete code-behind:

Leave Reply