PageRenderTime 45ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/Code/Client/Inbox2/Plugins/StatusUpdates/UrlShorteners/BitlyUrlShortener.cs

http://github.com/waseems/inbox2_desktop
C# | 56 lines | 47 code | 9 blank | 0 comment | 1 complexity | 5a7c121135dca987936019b8da2e48e1 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. using System;
  2. using System.ComponentModel.Composition;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Web;
  6. using System.Xml.Linq;
  7. using Inbox2.Framework.Interfaces.Plugins;
  8. using Inbox2.Platform.Channels.Extensions;
  9. using Inbox2.Platform.Logging;
  10. namespace Inbox2.Plugins.StatusUpdates.UrlShorteners
  11. {
  12. [Export(typeof(IUrlShortener))]
  13. public class BitlyUrlShortener : IUrlShortener
  14. {
  15. public string Name
  16. {
  17. get { return "bit.ly"; }
  18. }
  19. public string Shorten(string url)
  20. {
  21. try
  22. {
  23. string bitlyUrl = string.Format("http://api.bit.ly/shorten?version=2.0.1&format=xml&longUrl={0}&login={1}&apiKey={2}",
  24. HttpUtility.UrlEncode(url), "waseem", "R_b36db4f298fcd25827e589aaadd0e0b6");
  25. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(bitlyUrl);
  26. using (HttpWebResponse loWebResponse = (HttpWebResponse)request.GetResponse())
  27. using (var xmlStream = loWebResponse.GetResponseStream())
  28. {
  29. XDocument xmlFeed = XDocument.Parse(xmlStream.ReadString());
  30. var element = xmlFeed.Descendants("nodeKeyVal").First();
  31. var value = element.Element("shortUrl").Value;
  32. if (String.IsNullOrEmpty(value))
  33. {
  34. Logger.Error("Unable to shorten url. Result element = {0}", LogSource.UI, element);
  35. return url;
  36. }
  37. return value;
  38. }
  39. }
  40. catch (Exception ex)
  41. {
  42. Logger.Error("An error has occured while trying to shorten url. Exception = {0}", LogSource.UI, ex);
  43. return url;
  44. }
  45. }
  46. }
  47. }