Always Get Better

Archive for the ‘Web Programming’ Category

“Connection to Server Reset” when Installing Drupal

Friday, May 2nd, 2008

Has anyone else had this issue?

When I try to install Drupal on a Windows 2003 Apache server, I get a pause and then “Connection Reset” error under Firefox.  If I then try to install it using Internet Explorer, the installation process comes up immediately and works without a hitch.

I still can’t seem to get the admin ‘Modules’ page to load at all – PHP is crashing.  That is an entirely separate issue as far as I can tell.

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.

string resolvedUrl = ResolveUrl( “~/index.php” );

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.

string redirUrl = VirtualPathUtility.ToAbsolute(“~/redirPage.aspx”);
Response.Redirect( redirUrl );

Apache: Enabling mod_rewrite on Windows 2003 Server

Monday, April 21st, 2008

Recently I had to set up a WordPress blog on a Windows 2003 server, which involved installing Apache, PHP and MySQL.  Everything went pretty well – except for the typical PHP.ini problems I shall write about later.

Once the database was set up and I had the blog running, I tried to adjust the permalink structure using .htaccess rewrite rules so they would be more human-readable.

Out of the box, mod_rewrite isn’t enabled on Windows Apache.

The steps I took to resolve the problem were:

  1. Uncomment the line containing ‘LoadModule mod_rewrite modules/mod_rewrite.so
  2. In the VirtualHost directive hosting the blog, add ‘AllowOveride All
  3. Restart Apache

It works like a charm, now.  All the tools ship with Apache, it’s just a matter of configuring them as needed.

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.

Maintaining SQL Connections in ASP.NET

Monday, February 11th, 2008

There is a lot of conflicting advice with regard to the proper way of using SQL connections in web work.  The two main schools of thought are:

 

  1. Open a connection once, use it for everything and free it when the page request is complete.
  2. Open a connection only when it is needed, then fre it right away.

 

It All Comes Down to Speed

Any operation performed by the server has a cost associated with it.  Loops and counts happen on the CPU and are incredibly fast.  Caches are stores in system memory and seem fast but are in fact thousands of times slower than direct CPU operation.

 

As far as internal server access goes, reading and writing to the hard drive is representative of the most expensive operation performed by applications.  If possible, memory is oftent he best storage medium for program instructions.

 

Consider Database Access Costs

Databases live in a realm somewhere between hard drives and memory.  A good DBMS reacts to requests by storing execution plans and data in system memory thereby reducing the amount of time applications have to wait for information to load off the hard drive.

 

In terms of execution costs, connecting to the database is up there with reading from the hard drive.  Is a database connetion isn’t needed, don’t create one.

 

Which is better?

Considering the high price of connecting to a database, which of the following makes the most sense for our web application?

 

  1. Creating the connection to the database, performing all operations, and closing the connection after the is complete, org;
  2. For every request, creating a connection, executing a query, then closing the connection.  Repeat every time a new piece of information is required.

 

In classic ASP’s ADO, #1 was the best option.  In modern ASP.NET’s ADO.NET, #2 is the way to go.  That was a trick question.

 

Classic ASP – ADO

Using classic ASP, the developer has a great deal of control over the sequence in which their code will run.

 

It’s very easy to open a single connection at the top of a web page and use it for all of that page’s database operations.  At the end of the page, the developer writes code logic to free all record sets used, close memory objects, and release the connection.

 

ADO.NET

When writing code for ASP.NET, we strive to be “good” .NET citizens.  We are given a lot of power to write application logic never before possible on the web, and we are asked to relinquish some of our finer-grained control over resources.

 

Generally, managed resources benefits the programmer by freeing them to focus more on the business requirements of their project rather than their specific environment’s implementation.  Database connectivity, however, is a concept that has to be updated to fit the .NET paradigm.

 

Whereas before we controlled when database resources were released to the system, now the garbage collector has taken responsibility for the task.  If we open a database connection when the page request begins, we have no real guarantee it will be released in a timely manner when the page request completes.

 

This means the only way to prevent the server from running out of connections is by creating, using, and immediately freeing them every time we want to retrieve information from the database.

 

What about the cost of execution?  One would assume we’ve taken two steps back but ASP.NET introduces connection pooling for this situation.

 

Connection Pooling is your friend

Any time a connection is requested, the server looks to a special pool of memory objects where it keeps previously used database connections.  If there are any connections no longer being used, the server will return those unused connections before creating a new one.

 

Essentially the server only incurs the cost of creating a connection the first time it is used, or whenever demand for a particular application spikes.

 

When our program is done with the database, it releases the connection back into the pool for other requests.

 

Never Create Global Connection Objects

The morale of the story is: work with the .NET framework and let it do its job.  As long as we are willing to let go of old ways of thinking and adapt to the new technologies, our programming lives will become ever simpler.

 

Every day web applications grow in their complexity.  Fortunately the power and capabilities of the tools we have available also continue to improve.

 

Expect databases to continue driving bigger and better web presences.  The more skilled we become at working with them the more likely we are to succeed in creating stable, reliable and scalable applications to take advantage of them.

How To Format Dates Using DataFormatString

Sunday, January 20th, 2008

During a recent project I was setting up a DetailsView control for a record’s tombstone information [note: this logic is the same in DataGridView, GridView, and anywhere else that DataFormatString is used].

By default, my dates were coming in this format:

04/18/2008 12:00:00 PM

I wanted to display dates without any time information and without leading zeroes on the month like this:

4/18/2008

So I create my DetailsView like this:

<asp:DetailsView runat=”server” ID=”dvPatientInformation” DataSourceID=”sqlPatientInformation”>
    <Fields>
        <asp:BoundField HeaderText=”Title:” DataField=”strTitle” />
        <asp:BoundField HeaderText=”First Name:” DataField=”strFirstName” />
        <asp:BoundField HeaderText=”Last Name:” DataField=”strLastName” />
        <asp:BoundField HeaderText=”Date of Birth:” DataField=”dtBirthdate” HtmlEncode=”false” DataFormatString=”{0:M/dd/yyyy}” NullDisplayText=”Not Yet Entered” />
    </Fields>
</asp:DetailsView>

There are a few key issues to consider here:

Data Format String

Using one capital M for the month causes ASP.NET to display the month as a minimum digit – so for months like April the leading 0 will be removed – displaying “4″ rather than “04″. 

More information about data string format options can be found at the MSDN reference: http://msdn2.microsoft.com/en-us/library/system.globalization.datetimeformatinfo(vs.71).aspx

Null Display Text

The business rules for this organization allows for the patient’s birth date to be NULL in the system.  Rather than display a blank field when NULL, I chose to indicate textually that the patient’s birth date was not yet on file.

HTMLEncode

This is the critical part – if I did not set HTMLEncode to false, my date would not have formatted at all.

Why?  Because when rendering content, ASP.NET automatically takes data bound content and converts it into an HTML Encoded string in order to prevent pages from serving unintended - potentially malevolent – code along with expected text strings.

The problem – once a string has been encoded, the server no longer considers it a number or date/time information type, so applying the date format is useless.

The only way to get around this is by turning off HTML Encoding for fields whose contents must be formatted.

Yes, this does seem like quite an odd design issue – one would expect the HTML Encoding to come into play after all of the formatting had been completed.  That must be why .NET programmers get paid the big money – having to know tidbits like this eats away at your soul.


SEO Powered by Platinum SEO from Techblissonline