“Tweet This” Link with TinyURL in ASP.Net

14 Mar

In migrating to my new blog platform, one thing that I am really excited about is now being able to put custom code to power features I was not able to have in Google Blogger.

The first thing I did was add some code-behind to my user controls to generate good “Tweet This” links so that users could Tweet my posts on Twitter.

 

Most samples you see for this simple stick your page URL in the query string.  This doesn’t often work, as the URL will be too long, as the user won’t be able to tweet the message.

 

I create two functions behind my page, TweetThisLink and TinyUrl

 

<span class="kwrd">    public</span> <span class="kwrd">string</span> TweetThisLink(<span class="kwrd">string</span> Url, <span class="kwrd">string</span> Title)<br />    {<br />        <span class="kwrd">return</span> <span class="str">"http:[email protected] Reading "</span> 
              + TinyUrl(Url) + <span class="str">" "</span> + Title;<br />    }<br /><br />    <span class="kwrd">public</span> <span class="kwrd">string</span> TinyUrl(<span class="kwrd">string</span> Url)<br />    {<br />        <span class="kwrd">try</span><br />        {<br />            <span class="kwrd">if</span> (!Url.ToLower().StartsWith(<span class="str">"http"</span>) &amp;&amp; !Url.ToLower().StartsWith(<span class="str">"ftp"</span>))<br />            {<br />                Url = <span class="str">"http://"</span> + Url;<br />            }<br />            WebRequest request = 
                  WebRequest.Create(<span class="str">"http://tinyurl.com/api-create.php?url="</span> + Url);<br />            WebResponse res = request.GetResponse();<br />            <span class="kwrd">string</span> text;<br />            <span class="kwrd">using</span> (StreamReader reader = <span class="kwrd">new</span> StreamReader(res.GetResponseStream()))<br />            {<br />                text = reader.ReadToEnd();<br />            }<br />            <span class="kwrd">return</span> text;<br />        }<br />        <span class="kwrd">catch</span> (Exception)<br />        {<br />            <span class="kwrd">return</span> Url;<br />        }<br />    }

From my ASPX page, I can now insert a nice “Tweet This” link as follows:

<span class="kwrd">&lt;</span><span class="html">a</span> <span class="attr">href</span><span class="kwrd">="&lt;%=TweetThisLink(Post.PermaLink.ToString(), Server.HtmlEncode(Post.Title)) %&gt;"</span><span class="kwrd">&gt;</span><br />                        Some image or text <span class="kwrd">&lt;/</span><span class="html">a</span><span class="kwrd">&gt;</span>
Tweet about this on TwitterShare on Google+Share on FacebookShare on RedditEmail this to someoneShare on LinkedInShare on StumbleUpon

Leave a Reply

Your email address will not be published. Required fields are marked *