Friday, September 17, 2010

How to: add 'Tweet This' button to Webpage/website

You can add your own ‘Tweet This’ buttons to you webpage/website so that your visitors can post to twitter (complete with URL shortening using is really easy.

step 1:go to solution exproler and add a webpage (i have given it name:MyTwitterPage).
step 2:remove all the HTML from the page.

step 3:Add below code in code behind file:

Imports System.Net

Partial Public Class MyTwitterPage

Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

If Request.QueryString("url") <> "" And Request.QueryString("com") <> "" Then

TweetThis(Request.QueryString("url"), Request.QueryString("com"))

End If

End Sub

Private Sub TweetThis(ByVal sIWTFURL As String, ByVal sComment As String)

Dim sShortURL As String

Dim sFullTweet As String

sShortURL = ShortenURL(sIWTFURL)

sFullTweet = sComment & " - " & sShortURL


End Sub

Private Function ShortenURL(ByVal sURL As String) As String

Dim sJSON As String

Dim oWebClient As New WebClient

Dim sBitlyURL As String

Dim sShortURL As String

sBitlyURL = "" & Server.UrlEncode(sURL) & "&login=bitlyapidemologin&apiKey=R_0da49e0a9118ff35f52f629d2d71bf07"

sJSON = oWebClient.DownloadString(sBitlyURL)

sJSON = Mid$(sJSON, InStr(sJSON, Chr(34) & "shortUrl" & Chr(34)) + 9)

Do While sJSON.ToLower.StartsWith("http://") = False

sJSON = Mid$(sJSON, 2)


sShortURL = sJSON.Split(Chr(34))(0)

ShortenURL = sShortURL

End Function

Private Sub SentToTwitter(ByVal sComments As String)

Dim sURL As String

sURL = "" & HttpUtility.UrlEncode(sComments)

Response.Redirect(sURL, False)

End Sub

End Class

Note: I am using the default login in the example, you should sign up for your own account so you can track usage of your links.

step 4:Now you just need to add some javascript to your html pages:

< a href="#" onClick='javascript:PostToTwitter()'> Tweet This < /a >

< script >
function PostToTwitter()
var sTweet = 'This is the default text that will appear in the tweet';
var ShareURL = window.location.href;''+encodeURIComponent(ShareURL)+'&com='+encodeURIComponent(sTweet));
return false;
< /script >

Solution By:Rajesh Rolen

Share This!


Ravi Vyas said...

Hi..This is in Vb code..can you
please give me in C# code

Ravi Vyas said...

Hi..This Code in Vb.Net Can you please give me in

Hardik said...

hay ravi use
to convert code

Powered By Blogger · Designed By Seo Blogger Templates