Thursday, May 26, 2011

URL shortener in .net using bit.ly API

It’s simple to generate shorten url based on long url using bit.ly API.

For this we need to have account with http://bit.ly/a/sign_up which is free. After sign up completed, you will be provided with an API key http://bit.ly/a/your_api_key

This API key can be used to access the API. Below is the code for API class in c#

public static class BitlyApi
{
private const string apiKey = "[add api key here]"
;
private const string login = "[add login name here]"
;

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; }
}


Now, we can generate short url as below:


string strShortUrl = BitlyApi.ShortenUrl(“<long url>).ShortUrl;


Happy Coding…

Monday, May 23, 2011

Customizing Date format in WPF

The datepicker control in WPF allow short and Long formats. By default it will take system date format.

So we can change the date format as our application requires like dd/MM/yyyy or MM/dd/YYYY,…

Need to write some couple of lines under Application_Startup Event in App.XAML.

Below is the code for custom date format.

Thread.CurrentThread.CurrentCulture = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();

Thread.CurrentThread.CurrentCulture.DateTimeFormat.DateSeparator = "/";

Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";

image

This is event should be initiated from XAML code like below.

image

Happy Coding…