Always Get Better

Archive for the ‘ASP.NET’ Category

ASP.NET “Service Unavailable”

Saturday, November 8th, 2008

If you have threaded processes called by your ASP.NET code, and those processes crash, your site may start giving Service Unavailable errors.

Use iisreset to quickly get back up and running.

In order to prevent this from occurring at all, I recommend putting try { } catch { } around any statements inside a threaded function.

CommandEventHandler Event Won’t Fire for Button in ASP.NET Custom Control

Wednesday, September 24th, 2008

Problem: I created a custom control with a dynamic button and attached an event handler to that button.  When I run the control, clicking the button causes a postback but the event is not fired.

Solution: Changed the class inheritance from WebControl to CompositeControl.  Re-compiled and it worked like a charm.

ASP.NET: A potentially dangerous Request.Form value was detected from the client

Saturday, August 2nd, 2008

This error is caused by the presence of HTML in the fields returned by a form post.  In many cases, for example page management tools, you may want to allow your users to enter text formatted with HTML.  By default, ASP.NET doesn’t like this.

To turn it off, add ValidateRequest=”false” to the top of your aspx file.  This turns off validation of form results.

Honestly, I would rather if this property were available for individual form controls, because in my mind validation is still desirable overall even if one or two fields should allow HTML.  But there you have it.

Replacing / Adding Line Breaks in GridView Text

Tuesday, May 27th, 2008

The GridView is a powerful control for quickly and easily displaying tables of data. However, a raw dump of information is not always good – when displayed by a web browser, normal line breaks are simply rendered as spaces.

For long blocks of text, it may be desirable to have your GridView insert HTML line breaks into your data. This can be accomplished either programatically or declaratively.

Programatically

As a programmer, my first instinct is to try to solve the problem using code behind. I add a RowDataBound event handler to my GridView and create the command this way:

protected void gvMessageList_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridViewRow row = e.Row;
if (e.Row.RowType == DataControlRowType.DataRow)
{
row.Cells[2].Text = row.Cells[2].Text.Replace("\n", "<br />");
}
}

Although it works, it has several drawbacks:

  • This solution uses a magic number to cause the compiler to replace the third column in the row.  If the structure of the GridView were to change, this function may break
  • This solution requires the developer to be aware of the final layout of the GridView and to make the connection between the control’s declaration and its logical code.

Use The Design

By far, the better solution is to simply declare the formatting changes in the same place as the GridView.  Using a Template field, I can add line breaks to my message by adding this:

<%# Eval(“Message”).ToString().Replace(“\n”, “<br />”) %>

More Information

This solution assumes the contents of “Message” are not null.  For more information about this technique (including how to deal with null values), I recommend the ASP.NET message boards: http://forums.asp.net/p/1027728/1403884.aspx

Handling Relative Paths Programmatically In ASP.NET

Friday, April 25th, 2008

One of the nicest features in ASP.NET is its out-of-box support for relative paths in hyper links and other controls. This is very important for developers whose code resides within the root of their testing environment but within a sub-directory of the production server.

Whereas one would have to carefully program things like image links to point at “/applicationbasepath/images/”, in ASP.NET we can simply use “~/images”. Genious!

When writing custom code, however, the work isn’t done for us automatically. We have to pass our URL to a server-side function in order to convert the “~/” into a base path usable by our visitors.

There are two ways of doing this:

Using Relative Paths From a Web Page or Control

If we are programming a page template or a server control, we can use the ResolveUrl() function provided by our environment context.

[source:c#]
string resolvedUrl = ResolveUrl( “~/index.php” );
[/source]

On AlwaysGetBetter.com, “~/index.php” would resolve to http://www.alwaysgetbetter.com/blog/index.php. On another site, it might resolve to the root such as http://www.abetterblog.com/index.php. Programming this way makes our solution more portable.

Using Relative Paths From Outside a Web Page

Sometimes we need to use relative paths from outside the context of a web page. For example, if we were to make a change in our Global.asx file, the program code we use may not be considered to be within a web page scope.

Fortunately, .NET provides us with the static helper class VirtualPathUtility.

[source:c#]
string redirUrl = VirtualPathUtility.ToAbsolute(“~/redirPage.aspx”);
Response.Redirect( redirUrl );
[/source]

404 Errors when Accessing ASPX Pages on Windows 2003

Wednesday, April 16th, 2008

By default, windows 2003 Server is locked down and won’t display ASP.NET pages.

To enable them you must set its status to Allowed within the Web Service Extensions of IIS.

SQL Connections in ASP.NET – What you learned is WRONG!

Friday, February 15th, 2008

When we learn how to open and use a database connection with ASP.NET, as with any other programming concept in any other programming language, the simplified version used to explain what’s going on is not truly representative of the quality professional code we will one day be expected to write.
Opening and Closing Connections

Case in point: managing of sql database connection resources. How many of us learned to write something like this:


// Create a new SQL Connection object
SqlConnection conn = new SqlConnection( connectionString );

// Open the connection to the database
conn.Open();

// Create a new SQL Command
SqlCommand cmd = new SqlCommand( “DELETE FROM BabyNames;”, conn );

// Execute the command
cmd.ExecuteNonQuery();

// Close the database connection
conn.Close();

Sure it’s easy to follow, but if you deploy that on a moderately busy server you are going to make your client very unhappy.

Dispose Resources

SQLConnection and SQLCommand objects reference unmanaged resources, meaning the C# garbage collector has no framework knowledge about your object. Since these classes both implement the disposable interface it is important to call the Dispose() method in order to correctly free your application’s used memory.

So our code gets updated to look like this:


// Create a new SQL Connection object
SqlConnection conn = new SqlConnection( connectionString );

// Open the connection to the database
conn.Open();

// Create a new SQL Command
SqlCommand cmd = new SqlCommand( “DELETE FROM BabyNames;”, conn );

// Execute the command
cmd.ExecuteNonQuery();

// Dispose of the command
cmd.Dispose();

// Close the database connection
conn.Close();

// Dispose of the connection object
conn.Dispose();

Trap for Errors

What happens if there’s a problem, and your code fails to complete? If your application crashes before your objects are disposed, you are left with the same effect as if you had never disposed your objects at all!

Fortunately, C# includes the try … finally reserved words. If anything within the try { } block fails, the finally { } still executes. We can easily apply this to our program code:


// Create a new SQL Connection object
SqlConnection conn = new SqlConnection( connectionString );

try
{
// Open the connection to the database
conn.Open();

// Create a new SQL Command
SqlCommand cmd = new SqlCommand( “DELETE FROM BabyNames;”, conn );

try
{
// Execute the command
cmd.ExecuteNonQuery();
}
finally
{
// Dispose of the command
cmd.Dispose();
}

// Close the database connection
conn.Close();
}
finally
{
// Dispose of the connection object
conn.Dispose();
}

For my own part, I prefer the using keyword. We can include a using call anywhere we would ordinarily use a disposal object. When the code is compiled, it behaves the same as try … catch, but leaves our program code much more readable.

Even better, we don’t even have to bother calling Dispose() because it does it for us!


// Create a new SQL Connection object
using ( SqlConnection conn = new SqlConnection( connectionString ) )
{
// Open the connection to the database
conn.Open();

// Create a new SQL Command
using ( SqlCommand cmd = new SqlCommand( “DELETE FROM BabyNames;”, conn ) )
{
// Execute the command
cmd.ExecuteNonQuery();
}

// Close the database connection
conn.Close();
}

Slick.

Open Late, Close Early (like a bank)

There is one more thing I would add to this. Creating objects in memory takes time. Although it happens in fractions of a second too fast to be detectable by us, it’s important not to waste processing time wherever possible.

Whenever we Open() a database connection, we expect to use the database right away. If we then create an SqlCommand, we’re wasting the open connection’s time. It’s as if we pick up the phone and listen to the dial tone while we then flip through the white pages looking for the number we want to call.

Let’s change our example code so we will now Open() at the last possible opportunity, and Close() right away when we’ve made our call:


// Create a new SQL Connection object
using ( SqlConnection conn = new SqlConnection( connectionString ) )
{
// Create a new SQL Command
using ( SqlCommand cmd = new SqlCommand( “DELETE FROM BabyNames;”, conn ) )
{
// Open the connection to the database
conn.Open();

// Execute the command
cmd.ExecuteNonQuery();

// Close the connection to the database
conn.Close();
}
}

In the end, the program code we wrote is very similar to the newbie code we started with. However, we’re now protecting our system from memory leaks, and we’re protecting our database from wasted clock cycles. Our code is easy to read and stable.