Further to my previous post Twitter API and .NET I have been working on a way to dynamically update my Twitter status from my .NET web application. To get this to work I have used Twitterizer and TinyURL.
Twitterizer makes it very easy to implement. I also wanted to make sure I could also shrink the urls so I used TinyURL for this.
To start the vb class you will need the following:
Imports Twitterizer.Framework
Public Class TwitterUtils
Private Shared twitter_username As String = "YourTwitterUserName"
Private Shared twitter_password As String = "YourTwitterPassword"
The VB code for shrinking the url with TinyURL:
Public Shared Function MakeTinyUrl(ByVal Url As String) As String
Try
If Url.Length <= 30 Then
Return Url
End If
If Not Url.ToLower().StartsWith("http") AndAlso Not Url.ToLower().StartsWith("ftp") Then
Url = "http://" & Url
End If
Dim request As Net.HttpWebRequest = WebRequest.Create("http://tinyurl.com/api-create.php?url=" & Url)
Dim Response As WebResponse = request.GetResponse
Dim res = request.GetResponse()
Dim sr As StreamReader
sr = New StreamReader(Response.GetResponseStream)
Dim text As String = sr.ReadToEnd
sr.Close()
Return text
Catch generatedExceptionName As Exception
Return Url
End Try
End Function
To update my status on Twitter I used the following code:
Public Shared Sub updateStatus(ByVal post As String)
Dim RegexObj As Regex = New Regex("(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?")
Dim t As New Twitter(twitter_username, twitter_password)
t.Status.Update(RegexObj.Replace(post, TwitterUtils.MakeTinyUrl(Regex.Match(post, "(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?").Groups(0).ToString)))
End Sub
As you can see I used a regular expression to replace the url in the text with a TinyURL.
You may want to have a textbox and a seperate url field. To submit these you could use the following code:
Public Shared Sub updateStatus(ByVal post As String, Optional ByVal url As String = "")
Dim new_status As String = String.Empty
If Not url Is Nothing Then
If post.Length > 114 Then
post = post.Substring(0, 114)
End If
new_status += post & " " & MakeTinyUrl(url)
Else
new_status += post
End If
Dim t As New Twitter(twitter_username, twitter_password)
t.Status.Update(new_status)
End Sub
Twitterizer makes it simple to update your status using .NET. I have only used it for updating my status but you can use it for Direct Messages and Replies. Why not download it and start using it in your own web applications.
If you are on Twitter leave your username here for others to follow.
.Net
twitter, .net