Search This Blog

Tuesday, August 5, 2014

Bit ly Shorten Url -MVC/C# Code


Server Side Code: 

using System.Text;
using System.Xml;
 public class Utility
    {
         public static string BitlyShortenUrl(string strUser, string strApiKey, string strLongUrl)
         {
             StringBuilder uri = new StringBuilder("http://api.bit.ly/shorten?");
             uri.Append("longUrl=");
             uri.Append(HttpUtility.UrlEncode(strLongUrl));
             uri.Append("&login=");
             uri.Append(HttpUtility.UrlEncode(strUser));
             uri.Append("&apiKey=");
             uri.Append(HttpUtility.UrlEncode(strApiKey));
             uri.Append("&format=xml");

             HttpWebRequest request = WebRequest.Create(uri.ToString()) as HttpWebRequest;
             request.Method = "GET";
             request.ContentType = "application/x-www-form-urlencoded";
             request.ServicePoint.Expect100Continue = false;
             request.ContentLength = 0;
             WebResponse objResponse = request.GetResponse();
             XmlDocument objXML = new XmlDocument();
             objXML.Load(objResponse.GetResponseStream());

             XmlNode nErrorCode = objXML.SelectSingleNode("//errorCode");
             XmlNode nErrorMessage = objXML.SelectSingleNode("//errorMessage");
             XmlNode nShortUrl = objXML.SelectSingleNode("//shortUrl");

             if( nErrorCode.InnerText != "0" )
             {
                 return "Error returned";
             }
             else
             {
                 return nShortUrl.InnerText;
             }
         }
 }

Call From Views:
@{
//Create account in http://bitly.com and collect  API key  from https://bitly.com/a/settings/advanced
      string bitlyShortUrl = "";
      string bitlyLogin="....";
      string bitlyApiKey="....";

      bitlyShortUrl = Utility.BitlyShortenUrl(bitlyLogin, bitlyApiKey, Request.Url.ToString());
      if (bitlyShortUrl == "Error returned")
      {
          bitlyShortUrl = Request.Url.ToString() ;

      }
}
<a href="@bitlyShortUrl">@bitlyShortUrl</a>