Wednesday, October 28, 2009

Clever Qrulrs Code

I'm proud of this, so I thought I'd share it...it's very simple, just calls out to two different web services to create a QR Code from a URL:


public Qrurls()
{
createBitlyURL("http://cmarnold2.iweb.bsu.edu");
createQRCode();

}

private void createBitlyURL(String longURL)
{
String URL = "http://api.bit.ly/shorten?version=2.0.1&longUrl=" + longURL + "&login=" + bitlyAPIUsername + "&apiKey=" + bitlyAPIKey;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStreamLocal = response.GetResponseStream();
string tempString = null;

if (null != response)
{
resStreamLocal = response.GetResponseStream();
StreamReader sr = new StreamReader(resStreamLocal);
string str;
while ((str = sr.ReadLine()) != null)
{
if (str.Contains("shortUrl"))
tempString = str;
else
continue;
}
response.Close();
}
else
{
throw new Exception("Something is wrong!");
}

if (tempString != null)
bitlyURL = tempString.Substring(tempString.IndexOf("http://bit.ly"), 20);
}

private void createQRCode()
{
String URL = "http://chart.apis.google.com/chart?cht=qr&chs=100x100&chl=" + bitlyURL;

WebClient wc = new WebClient();
byte[] data =
wc.DownloadData(URL);

PngBitmapDecoder decoder = new PngBitmapDecoder(new MemoryStream(data), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapSource bitmapSource = decoder.Frames[0];

// Draw the Image
myImage = new System.Windows.Controls.Image();
myImage.Source = bitmapSource;
myImage.Stretch = Stretch.None;

}


It's being used in our Surface application for the iDMAa 2009 Conference. Obviously not the most complex code I've written by a long shot, but it didn't take much time and was extremely useful, since QR Codes are getting more common.

No comments: