using System; using System.Windows.Forms; using System.Net; using System.Web; using System.IO; namespace Trowl { // A delegate type for hooking up change notifications. public delegate void BeforeUrlShortenEventHandler(object sender, EventArgs e); public delegate void AfterUrlShortenEventHandler(object sender, EventArgs e); class UrlShorteningTextBox : TextBox { private const int WM_PASTE = 0x0302; public bool AutoShortenUrls { get; set; } public event BeforeUrlShortenEventHandler BeforeUrlShorten; public event AfterUrlShortenEventHandler AfterUrlShorten; protected virtual void OnBeforeShorten(EventArgs e) { if (BeforeUrlShorten != null) BeforeUrlShorten(this, e); } protected virtual void OnAfterShorten(EventArgs e) { if (AfterUrlShorten != null) AfterUrlShorten(this, e); } public UrlShorteningTextBox() : base() { this.AutoShortenUrls = true; } protected override void WndProc(ref Message m) { if (m.Msg == WM_PASTE) { if (this.AutoShortenUrls && Clipboard.ContainsText()) { String url = Clipboard.GetText(); if (url.StartsWith("http://") && !url.Contains(" ")) { OnBeforeShorten(EventArgs.Empty); url = ShortenUrl(url); Clipboard.SetText(url); OnAfterShorten(EventArgs.Empty); } } } base.WndProc(ref m); } private string ShortenUrl(string sLongUrl) { String sShortUrl = null; String sRequestUrl = "http://is.gd/api.php?longurl=" + HttpUtility.UrlEncode(sLongUrl); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(sRequestUrl); request.Method = "GET"; try { WebResponse response = request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); sShortUrl = reader.ReadToEnd(); reader.Close(); reader.Dispose(); response.Close(); } catch //(WebException e) { //throw new WebException(e.Message, e, e.Status, e.Response); return sLongUrl; } if (sShortUrl != null && sShortUrl.StartsWith("http://")) { return sShortUrl; } else { return sLongUrl; } } } }