Archive

Archive for July, 2009

ASP.NET version of “Name Tag”

July 1, 2009 Raja R.K 1 comment

This sample shows you how to load a background image from a file, add some text to the image using ASP.NET’s graphics capabilities, and serve the resulting image to a browser.

As an example we’ll be using an image of one of those “Hello My Name Is” name tag stickers that we’ve all seen at conferences and get togethers. We’ll load the image, add a name to the tag and send the image to the browser. The name will be pulled from the QueryString so it can easily be changed.

Here’s a zip file of the code along with the sample background image (13 KB).

Here are a couple of links to the script that pass in different names for reference:

John
Fred Q. Smith

Play with the running version.

View the live source code.

Categories: ASP, ASP.Net

Read-Only Session State

July 1, 2009 Raja R.K Leave a comment

The fact that ASP.NET maintains a user’s session state for us is a great thing. It allows us to program applications for the Web and rarely give a second thought to the fact that we don’t actually maintain a connection to our users. That being said, session state does come at a cost and disabling it when you’re not using it is a standard tip for improving application performance. But what if you are using it?

There’s a little known option that can serve as a happy medium. Instead of setting your page’s EnableSessionState attribute to “True” or “False”, you can set it to “ReadOnly” instead. The resulting page directive should look something like this:

This only works on pages that need access to a user’s session state information, but do not modify it. If you take a close look at your application, you’ll probably find that the majority of the pages that use session state fall into this category.

Using this setting won’t give you the same performance benefit you’d get by disabling session state altogether, but then again you don’t have to give up using sessions in order to use it.

Categories: ASP, ASP.Net, News

Instantly Find Sub and Function Declarations

July 1, 2009 Raja R.K Leave a comment

Trying to quickly make sense of unfamiliar code can be quite frustrating. This tip will show you how you can instantly jump from the usage of any subroutine directly to its definition using any flavor of Visual Studio. This huge time saver lets you easily locate code that you might otherwise have spent hours trying to find.

Assuming you’ve already opened the Web site or application with Visual Studio, the first step is to find a usage of the subroutine whose definition you’re trying to find. Then simply place your cursor on the Sub or Function name and press the “F12″ key on your keyboard. The code window will instantly move you to the declaration of the algorithm in question. This works even if the source code is located in a different file altogether.

Once you’ve examined the code or made any changes you may need to, you’ll most likely want to return to your original location. Luckily Visual Studio provides a simple shortcut for this as well. Use the “Ctrl+-” keyboard combination and you’ll end up right back where you started.

Jumping around unfamiliar code this way can take a little getting used to, but once you get used to using “GoToDefinition” (“F12″) and “NavigateBackward” (“Ctrl+-”), you’ll wonder how you ever got along without them.

Categories: ASP, ASP.Net, News

Be Sure to Handle Errors to Continue Script Execution

July 1, 2009 Raja R.K Leave a comment

I recently spoke with a developer who was upset that the redundancy he built into his Web application had failed him. As a safeguard against database failure, he had written a script which wrote new entries to a log file on the local file system as well as adding them to the database. It was a good idea… unfortunately the implementation wasn’t so good.

The fact that he was writing to the log file first gave him a false sense of security. You see, every time there was a problem with the database he’d always gone to check the log file and found the missing entries there waiting. The problem didn’t become apparent until someone accidently changed the permissions on the log file and his script threw an ‘access denied’ error which halted execution. It never even tried to write to the database and the new entries were lost completely. So what did he do wrong?

He never added any error handling to the script. If he had simply added a “Try… Catch… Finally” block around each of the operations, the script would have achieved the desired result. Even if he didn’t take the time to do anything to actually handle the errors, execution would have continued and the script would have at least tried to write the new entries to the database instead of coming to a dead stop when it ran into the permission problem.

For those of you who aren’t familiar with “Try… Catch… Finally”, here’s a short sample script which illustrates my point. This script attempts to write to a log file and send an email. I’ve wrapped both operations with a “Try… Catch… Finally” block so if either (or both) fail, as they probably will if you try and run the script as is, execution will still continue to the end of the script. For illustration I’ve included status messages which the script will display as it runs. It’ll also output the text message of any errors it encounters at the bottom of the page.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
‘ Try to write to a logfile and send an email, writing status messages as we go…
litPageProgress.Text = ”

Page_Load sub started execution at: ” & _
Now().ToString & “

” & vbCrLf

litPageProgress.Text = litPageProgress.Text & ”

Attempt to write to log file… “
Try
File.AppendAllText(Server.MapPath(“logfile.log”), Now())
litPageProgress.Text = litPageProgress.Text & “Succeeded!”
Catch exLogFile As Exception
litErrors.Text = litErrors.Text & exLogFile.Message & “

litPageProgress.Text = litPageProgress.Text & “Failed!”
Finally
litPageProgress.Text = litPageProgress.Text & “

” & vbCrLf
End Try

litPageProgress.Text = litPageProgress.Text & ”

Attempt to send email… “
Try
Dim mySmtpClient As New SmtpClient(“localhost”)
mySmtpClient.Send(“FROM_ADDRESS”, “TO_ADDRESS”, “Message Subject”, “Message Body”)

litPageProgress.Text = litPageProgress.Text & “Succeeded!”
Catch exLogFile As Exception
litErrors.Text = litErrors.Text & exLogFile.Message & “

litPageProgress.Text = litPageProgress.Text & “Failed!”
Finally
litPageProgress.Text = litPageProgress.Text & “

” & vbCrLf
End Try

‘ Note that this line will still run even if errors occur above.
litPageProgress.Text = litPageProgress.Text & _

Page_Load sub ended execution at: ” & _
Now().ToString & “

” & vbCrLf
End Sub

Try… Catch… Finally Error Handling Example

Errors Encountered:

Categories: ASP, ASP.Net, News

Response.Redirect vs. “301 Moved Permanently”

July 1, 2009 Raja R.K Leave a comment

We’ve all used Response.Redirect at one time or another. It’s the quick and easy way to get visitors pointed in the right direction if they somehow end up in the wrong place. But did you know that Response.Redirect sends an HTTP response status code of “302 Found” when you might really want to send “301 Moved Permanently”?

The distinction seems small, but in certain cases it can actually make a big difference. For example, if you use a “301 Moved Permanently” response code, most search engines will remove the outdated link from their index and replace it with the new one. If you use “302 Found”, they’ll continue returning to the old page.

The question now becomes, how does one actually send an HTTP response status code of “301 Moved Permanently”? While it’s not as easy as doing a Response.Redirect, it’s still pretty simple. Take a look at the following two lines of code:

Response.Status = “301 Moved Permanently”
Response.AppendHeader(“Location”, “http://www.asp101.com/”)

Using this code instead of Response.Redirect will send a “301 Moved Permanently” HTTP response status code instead of “302 Found”.

For more information on HTTP status codes, check out Wikipedia’s List of HTTP Status Codes or, if you really want to get your hands dirty go ahead and read the section on redirection from RFC 2616 – Hypertext Transfer Protocol — HTTP/1.1.

Update: ASP.NET Response.RedirectLocation

It appears that ASP.NET actually includes a Response.RedirectLocation property which you can set instead of using the AppendHeader method we originally used. The end result is the same, but based on the feedback we’ve received it seems that many of our readers prefer the RedirectLocation method.

The code is basically the same… just a slight syntax change:

Response.Status = “301 Moved Permanently”
Response.RedirectLocation = “http://www.asp101.com/”

Categories: ASP.Net, News