Shortening URLs With The bit.ly API Via ASP.NET

After yesterday’s post on using the Twitter API to post status updates on Twitter from an ASP.NET application, a follower of my client suggested using a URL shortening service to link to the articles headlines being posted as tweets.

That was an excellent idea of which I should have thought in the first place. And thanks to the extreme simplicity of the REST-like bit.ly API, shortening URLs is as simple as sending a request URL laced with querystring variables.

So here is a quick and simple ASP.NET subroutine, written in VB.NET, to shorten URLs with the bit.ly API:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
Sub BitlyIt(ByVal strUser As String, ByVal strAPIKey As String, ByVal strLongUrl As String)
	'build URL to shorten method resource
	Dim strUri As New StringBuilder("http://api.bit.ly/shorten?")
	strUri.Append("version=2.0.1")
	'we want to get an XML response back from bit.ly, not the default JSON
	strUri.Append("&format=xml")
	strUri.Append("&longUrl=")
	strUri.Append(Server.HtmlEncode(strLongUrl))
	strUri.Append("&login=")
	strUri.Append(Server.HTMLEncode(strUser))
	strUri.Append("&apiKey=")
	strUri.Append(Server.HTMLEncode(strAPIKey))
 
	'create request for shorten resource
	Dim objRequest As HttpWebRequest = WebRequest.Create(strUri.ToString())
	'since we are passing querystring variables, our method is get
	objRequest.Method = "GET"
	'act as though we are sending a form
	objRequest.ContentType = "application/x-www-form-urlencoded"
	'don't wait for a 100 Continue HTTP response from bit.ly
	objRequest.ServicePoint.Expect100Continue = False
	'since we are using get, we need not send a request body; set content-length to 0
	objRequest.ContentLength = 0
 
	'we need to capture the XML being sent in response 
	'read the response into a new XML document
	Dim objResponse As WebResponse = objRequest.GetResponse()
	Dim objXML As New XmlDocument()
	objXML.Load(objResponse.GetResponseStream())
 
	'the response will have three node values we're primarily interested in
	'the errorCode node will contain a numeric error code; 0 means success
	Dim nErrorCode As XmlNode = objXML.SelectSingleNode("//errorCode")
	'if there was an error, the errorMessage node will contain a user-friendly message useful for debugging
	Dim nErrorMsg As XmlNode = objXML.SelectSingleNode("//errorMessage")
	'if all went well, shortUrl will contain the full short URL created for our link
	Dim nShortUrl As XmlNode = objXML.SelectSingleNode("//shortUrl")
 
	'if we didn't get an errorCode value of 0, there was a problem; report the user-friendly message
	'on success, report the short URL for our resource
	If nErrorCode.InnerText <> "0" Then
		lblStatus.Text = "Error returned. Code: " & nErrorCode.InnerText & "; Message: " & nErrorMsg.InnerText
	Else
		lblStatus.Text = nShortUrl.InnerText
	End If
End Sub

Continue reading ‘Shortening URLs With The bit.ly API Via ASP.NET’ »

Posting Status Updates (Tweets) To A Twitter Profile Via ASP.NET

I have a client that posts several news stories to its Web site every day. So it makes tremendous sense for them to post the headlines to Twitter as tweets, so that followers might be informed of breaking news, or just what’s new on the site.

The Twitter API makes posting status updates (tweets) to Twitter as simple as invoking a WebRequest. Unfortunately, most of the ASP.NET examples on the Web that aim to show you how to post status updates are either written in C#, have coding errors, simply will not work, or all three.

So here’s a simple VB.NET subroutine that will post tweets.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
Sub TwitIt(ByVal strUser As String, ByVal strPass As String, ByVal strMessage As String)
	'create post variable for tweet
	Dim strTweet As String = "status=" & Server.HtmlEncode(strMessage)
	'convert post variable to byte array for transmission purposes
	Dim bRequest As Byte() = System.Text.Encoding.ASCII.GetBytes(strTweet)
 
	Try
		'create HttpWebRequest to status update API resource
		Dim objRequest As HttpWebRequest = WebRequest.Create("http://twitter.com/statuses/update.xml")
		'pass basic authentication credentials
		objRequest.Credentials = New NetworkCredential(strUser, strPass)
		'set method to post and pass request as a form
		objRequest.Method = "POST"
		objRequest.ContentType = "application/x-www-form-urlencoded"
		'tell the server it will not receive a 100 Continue HTTP response
		objRequest.ServicePoint.Expect100Continue = False
		'set content length of request
		objRequest.ContentLength = bRequest.Length
 
		'capture the stream (content) of the request
		Dim objStream As Stream = objRequest.GetRequestStream()
		'put the bytes into request
		objStream.Write(bRequest, 0, bRequest.Length)
		'close the stream to complete the request
		objStream.Close()
 
		'uncomment line below to report success
		'lblStatus.Text = "Tweet sent!"
	Catch ex As Exception
		'uncomment line below to report ASP.NET errors
		'lblStatus.Text = ex.Message
	End Try
 
	'You can also capture the XML response Twitter sends back
	'uncomment lines below to capture responses
	'Dim objResponse As WebResponse = objRequest.GetResponse()
	'Dim objReader As New StreamReader(objResponse.GetResponseStream())
	'lblStatus.Text = objReader.ReadToEnd()
End Sub

Continue reading ‘Posting Status Updates (Tweets) To A Twitter Profile Via ASP.NET’ »

Free Books, Just For The Asking

I’m clearing my bookshelves and have four books that I was planning to trash (since the local library doesn’t want them). Then I thought, what the heck, give ‘em away on the blog.

So, forthwith, I have the following four books available:

Associated Press Stylebook and Libel Manual (1998 Edition): This is a reference book used by reporters to ensure they spell things correctly, use words properly, capitalize appropriately, etc. I am replacing it with the latest edition; this one is still useful, especially for the casual writer.

Microsoft Visual Basic 2005 Step by Step (Step By Step (Microsoft)): An excellent book for the beginning programmer who wants to get up to speed quickly. It teaches you how to program by getting you to make real programs that employ each chapter’s lesson. Includes a CD-ROM with source code. I’m using Visual Studi0 2008, and this is mostly relevant, but I’ve pretty much outgrown its message.

Microsoft Expression Web Step by Step (Microsoft): Like the book above, teaches you how to use Expression Web with real-world examples you can employ. (This is the first edition of the book, not the one for Expression Web 2.) Also includes a CD-ROM with sample code. I got this as a gift but I don’t use Expression Web.

Professional ASP.NET 2.0 (Programmer to Programmer): An extremely big book that pretty much covers every aspect of ASP.NET 2.0 programming. Heavily thumbed but still in very good shape. I’ve used it for reference for a number of years and highly recommend it for programmers who are familiar with .NET programming but not ASP.NET, or for other experienced programmers who want a good desk reference. This one really isn’t appropriate for beginners.

These books are first-come, first-served and will be sent by media mail to US addresses only (be advised that media mail can take up to three weeks to arrive). I will pay the shipping; it’s totally free.

If you would like one of these books, post a comment on this blog with your real e-mail address. Provide me with the name of the book you want and a reason you want it. The first reason I like for each book will be contacted by e-mail for shipping info. This will continue until all four books are gone.

How I Code On This Blog: Elegance Vs. Transparency

My recent comment exchange with Scriptar has prodded me to post an explanation of how I code on this blog.

I view the code I post here as having two priorities: elegance and transparency, weighted slightly more toward elegance.

What I mean is that most importantly, the code I post should be as simple, compact and direct as possible. It should solve the problem with as few lines of code as possible, using as direct an approach to solving the problem as possible, and without introducing any additional steps or problems that need to be resolved.

For example, suppose I want to demonstrate how, in PHP, to concatenate an array into a string. I could do this:

$val = array('here', 'there', 'everywhere');
$out = "The words in the array are ";
foreach($val as $item) {
	$out .= "$item, ";
}
$out = substr($out, 0, (strlen($out) - 2)) . ".";
echo $out;

But I’d almost always write the solution thus:

$val = array('here', 'there', 'everywhere');
echo "The words in the array are " . implode(", ", $val) . ".";

That is, I’d write it as the second example — since it’s far more elegant — unless doing it that way either removed the ability to make an important point about the way things work, or obfuscates some consideration that ought to be made plain.

Continue reading ‘How I Code On This Blog: Elegance Vs. Transparency’ »

Automatically Wiring Up XHTML Element Events On Page Load With jQuery

Many Web developers find themselves in an environment where the design of a Web page is handled by a graphic designer or junior programmer, either as part of their team or from a subcontractor or the client himself.

Unfortunately, traditional HTML / XHTML requires most element events handlers — onmouseover, onclick, onfocus, etc. — to be coded as attributes of the tag, like this:

<img id="myimage" src="pic1.jpg" alt="My Image" onmouseover="this.src='pic2.jpg'" onmouseout="this.src='pic1.jpg'" />

That’s not a problem if you’re the end point of the code; that is, if the graphic designer hands you a final page that won’t be modified again. But in the real world, pages and their associated code need to be moved back and forth constantly, with changes aplenty. That can have a real impact on your work, especially if the designer changes or removes your event handlers from page elements.

That’s the idea behind MVC (model, view, controller). We break the chain of custody for a Web request into three parts: A controller accepts a request from the user and determines which model should be used to handle the request.

The selected model, in turn, does something with the request sent to it by the controller; for example, one model might serve up some static content; another model returns search query results; another model returns data based on an environment variable, such as the geolocation of the user’s IP address (that is, gives a page in Russian to a user from Russia, by default); and so on.

Finally, the view — the end output the user sees — is applied by the controller to the model’s results.

While this is a worthwhile development approach, it may be a bit of overkill for a site that doesn’t have too much dynamic content, or that simply needs an image rollover effect, a countdown clock, etc. We still want to protect our coding from alteration by the designer, but we don’t want to employ a $10 solution to a 10-cent problem.

Enter, once again, jQuery, which can automatically bind (that is, “wire up”) event handlers for us once the page loads.

Continue reading ‘Automatically Wiring Up XHTML Element Events On Page Load With jQuery’ »

Parent – Child Select Lists Revisited: Multiple Parent – Child Select Lists Via PHP, MySQL And jQuery

A while ago, I promised to answer Brian’s request for a demonstration of how to make multiple parent / child select lists — in other words, starting from one drop down / select list, having two or more child lists, each of which, in turn, may act as a parent to another list.

Multiple parent-child select lists are considerably more complicated to program than a single parent-child relationship. Not only do we have additional data relationships to consider (that is, how we’re going to tie child list values to the selected parent values), we now need to plan for what to do if a “middle” relationship is changed (more on this shortly).

Fortunately, we have a starting point in my original parent-child select list post. We don’t need to reinvent the wheel, therefore, so much as we need to upgrade from a horse cart to a Lamborghini.

Overview Of The Approach

As was the case when we had a single child drop-down list, we must begin with relational data for each select list. Apologies to those who consider that obvious, but for n00bs, what I mean is, if you want to select a value from List A and have List B populated with new values, then the values you intend to have in List B must somehow be keyed (linked) to the selection made in List A.

This multiple parent-child select list approach will work for as many parent-nee-child lists you want. If you want to populate 10 or 100 or 1,000 lists, you won’t need to change a single line of JavaScript; however, your PHP “helper” page will need some modification to accommodate all the queries you’ll need, and the more lists you have, the more code you’ll have to put into your HTML (more on this shortly).

Continue reading ‘Parent – Child Select Lists Revisited: Multiple Parent – Child Select Lists Via PHP, MySQL And jQuery’ »