Saturday, August 7, 2010

BIt.ly api asp.net c#

C# class bitlyapi.cs

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

///
/// Summary description for bitly
///

public static class BitlyApi
{
private const string apiKey = "YOUR API KEY";
private const string login = "YOUR LOGIN";

public static BitlyResults ShortenUrl(string longUrl)
{
var url =
string.Format("http://api.bit.ly/shorten?format=xml&version=2.0.1&longUrl={0}&login={1}&apiKey={2}",
HttpUtility.UrlEncode(longUrl), login, apiKey);
var resultXml = XDocument.Load(url);
var x = (from result in resultXml.Descendants("nodeKeyVal")
select new BitlyResults
{
UserHash = result.Element("userHash").Value,
ShortUrl = result.Element("shortUrl").Value
}
);
return x.Single();
}
}

public class BitlyResults
{
public string UserHash { get; set; }

public string ShortUrl { get; set; }
}


Any c# .cs code behind page

string longurl = "http://www.longurl.com;
var shortUrl = BitlyApi.ShortenUrl(longurl).ShortUrl;
bitlyurl = shortUrl.ToString();

No comments: