A better way of handling maxRequestLength exceptions

ASP.NET 2 includes the FileUpload control to make it easier to create pages that allow users to upload files. The default maximum file size is 4096 KB to minimize the potential for denial of service attacks. You can change the maximum file size by editing your configuration files (see for example http://msdn2.microsoft.com/en-US/library/system.web.configuration.httpruntimesection.maxrequestlength(VS.80).aspx and http://support.softartisans.com/kbview_825.aspx).

The problem is that when users attempt to upload a file that is too large, it is difficult to capture and handle the exception that is created. The usual try..catch doesn’t handle the exception because the exception occurs before then. The exception is “System.Web.HttpException: Maximum request length exceeded”. You could of course increase the maximum file size but that defeats the purpose of the limit in the first place.

Here is one solution for handling the exception that is at least nicer than the standard ASP.NET exception message:

1. Create a global.asax file. If you’re using Visual Studio 2005 it will set up a number of common subroutines for you. You need to use Sub Application_Error. Your code should look something like this:

<script runat=”server”>
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
Dim currentException As Exception
currentException = Server.GetLastError.GetBaseException()
Response.Redirect(“/error.aspx?Err=” & Server.UrlEncode(currentException.Message))
End Sub
</script>

The application_Error sub fires as a last resort, in other words, when you haven’t explicitly handled the exception anywhere else in your code.

2. You can now create an error.aspx that displays the exception message (from the querystring). For this exception the message is “Maximum request length exceeded”. You could also test for the message and give users more information on the error.

Please let me know if you have any comments, suggestions, or improvements.

Creating multiple websites in IIS 6 for student projects

Every term I had to create between 100 and 200 web sites for students in my classes. Here are the steps I used to create those site in IIS 6. The student’s active directory accounts were already set up by our system administrator. I use FrontPage Server Extensions to allow students to transfer files to the server. Sections in italics below need to be replaced with your settings.

1. Create Directories:

md studentdirectory

2. Assign the student user account relevant permissions:

xcacls studentdirectory /T /E /G studentusername:F

3. Create a virtual directory in IIS for each student:

iisvdir /create “IISsitenamestudentvirtualdirectoryname studentdirectory

4. Create a subweb for each student:

“C:\Program Files\Common Files\Microsoft Shared\web server extensions\50\bin\owsadm” -o install -p 1100 -w studentvirtualdirectoryname -u usernameWithSufficientPermissionsOnServer

5. Give the new subweb unique permissions:

“C:\Program Files\Common Files\Microsoft Shared\web server extensions\50\bin\owsadm” -o setperms -p 1100 -w studentsubwebname -i false -u usernameWithSufficientPermissionsOnServer

6. Give the student the author role on the subweb:

“C:\Program Files\Common Files\Microsoft Shared\web server extensions\50\bin\owsadm” -o roleusers -command add -u studentusername -p 1100 -w studentsubwebname -name Author

z-index in Internet Explorer 7

The z-index implementation in IE 7 can be troublesome when combined with elements that are relatively positioned. My problem occurred on my personal web site on which I have CSS drop down menus that I want to appear over an element with the position:relative declaration. The drop down menu would appear behind the relatively positioned element despite the z-index being set correctly for the drop down menu styles. The page displayed correctly in Firefox. I found a great post at http://www.quirksmode.org/bugreports/archives/2006/01/Explorer_z_index_bug.html that identified the solution.

The solution involves setting the z-index property for any parent elements of the drop down menu in addition to setting it for the drop-down element itself. For example, suppose the navigation menu is in the nav element. The z-index property must be also set for the pageheader element.

<div id=”pageheader”>
<div id=”nav”>
</div>
</div>

Formatting columns in a GridView

Formatting columns in a GridView is relatively straightforward, once you know the appropriate format string.

Here are the steps if you are using Expression Web, Visual Studio, or Visual Web Developer:

  1. Open the Task Pane of your GridView and select Edit Columns
  2. In the Selected Fields Box, select the column you want to edit
  3. Find the HTMLEncode property and set it to false.
  4. Find the DataFormatString property and set it to the appropriate formatstring. The standard format of a format string is {0:format string}

Some examples of format strings are:

{0:c} to format as currency
{0:M-dd-yyyy} to format as a date

For more formatting strings, go to Formatting Types on MSDN.

A random list of recommended software utilities

I’ve found this random list of software to be really useful for tasks from working with images to improving Internet Explorer to developing FaceBook applications.

1. IrfanView (www.irfanview.com) – great for basic image editing (resizing, cropping, creating thumbnails, etc.) and screen capturing.

2. WinRAR (www.rarlabs.com) – great for working with zip and other compressed files. Also great for working with CD and DVD image files (e.g. .iso files)

3. Internet Explorer Developer Toolbar (http://www.microsoft.com/downloads/details.aspx?FamilyID=E59C3964-672D-4511-BB3E-2D5E1DB91038&displaylang=en) – useful tool if you develop web pages.Has a host of features to analyze and validate HTML, CSS, and other web site features. Includes a feature to see how your site looks at different screen resolutions.

5. FaceBook Developer Toolkit (http://www.codeplex.com/FacebookToolkit) – allows you to build FaceBook apps within Visual Studio.

6. Microsoft Office Outlook Connector (http://www.microsoft.com/Downloads/details.aspx?FamilyID=7aad7e6a-931e-438a-950c-5e9ea66322d4&displaylang=en) – “With Microsoft Office Outlook Connector, you can use Microsoft Office Outlook 2003 or Microsoft Office Outlook 2007 to access and manage your Microsoft Windows Live Hotmail or Microsoft Office Live Mail accounts, including e-mail messages and contacts.”

7. NMap (http://nmap.org/) is a useful tool for IT security. It performs a variety of network scans that can potentially highlight weaknesses in your network security.

8. MacDrive 7 (http://www.mediafour.com/products/macdrive/) allows you to see and use your Mac hard disks when running windows. I find it especially useful when running bootcamp and I want to access files from the Mac partition.

Converting SQL Server newline character to HTML break <br/>

A common scenario (at least for me) is the following:

1. Accept text input into a web form that includes multiline text boxes. The text often includes line breaks.
2. The text is stored in a database such as SQL Server 2005. SQL Server 2005 has no problem storing the line breaks.
3. I then display the data in an ASP.NET gridview control. Because the control renders as HTML, it doesn’t recognize the newline escape characters.

The problem is how to convert the newline characters into <br />. Here is one solution. It is closely based on this MSDN article: http://msdn2.microsoft.com/en-us/library/xwewhkd1.aspx (regex.replace)

This C# example assumes you are using an ASP.NET FormView with a label called lblSampleText:

//Create a regular expression that matches a newline
string pattern = "\n";
Regex rgx = new Regex(pattern);
//Find the relevant label from the FormView
Label vL1 = checked((Label)FormView1.FindControl("lblSampleText"));
string inputStr = vL1.Text;
//Replace the newline character with br
string outputStr = rgx.Replace(inputStr,"<br/>");
// Display the resulting string
vL1.Text = outputStr;

This VB example assumes you are using a GridView with a TemplateField control. Inside the TemplateField control (ItemTemplate) is a label called lblSampleText.

Protected Sub GridView3_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView3.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
' Create a regular expression that matches a newline
Dim pattern As String = "\n"
Dim rgx As New Regex(pattern)
' Find the relevant label from the gridview
Dim inputStr As String = CType(e.Row.FindControl("lblSampleText"), Label).Text
' Replace the newline character with <br/>
Dim outputStr As String = rgx.Replace (inputStr, "<br/>")
' Display the resulting string.
CType(e.Row.FindControl("lblSampleText"), Label).Text = outputStr
End If
End Sub

Using the CSS vertical-align property

Trying to vertically align content on a web page using CSS can be difficult. For example, you often want to align text and other content in the middle of a div tag. The difficulty is often caused by developers not understanding how vertical-align works. I found this great page on the problems with vertical-align and how to overcome them:

http://phrogz.net/CSS/vertical-align/index.html

Changing the location of your My Documents folder

You can change the location of my documents to any folder that you like. For example, if you are a LCB student or faculty member, you might want to point your My Documents folder to your I: Drive so that it is accessible from any computer at work or home. Here are the steps:

1. Right click on your My Documents folder.

2. Click on properties

3. Click on the Move button

4. Select the folder in which you want to store your files (e.g., your I: Drive)

5. Click OK

To access your I: Drive from home, see my blog posting on the topic: Connecting to I: Drive from home
If you want to make your documents available offline so that you can still work with your files even when you can’t connect to your I: network drive, see my blog post: Making files available offline.

Email merge in Microsoft Word

Many programs, including MS Word, allow you to send personalized e-mails to any number of people. So instead of having to send a general e-mail to (for example) “Dear customer” you can send it to “Dear John Smith” and “Dear Jane Jones”.

The basic steps are:

1. Create a normal Word document that contains your standard e-mail content.

2. Create a database of names, e-mail addresses, and other personalized content. The data could be in Access, Excel, Outlook or many other formats.

3. With your e-mail document open in Word, go to Tools –> Letters and Mailings –> Mail Merge.

4. Select e-mail messages as the document type.

5. Complete the wizard steps at the bottom right of the screen to send your e-mail.

Use MS Word help for more information. The preferable e-mail format is HTML because otherwise MS Outlook may prompt you before sending each e-mail (as a security measure).

Configuring SQL Server 2005 for database-driven web pages

SQL Server 2005 has enhanced security that prevents it initially from serving data for web pages. Here are the configuration settings to check before trying to create database driven web pages in Visual Studio, Dreamweaver, or any other web design application. Note that some of these settings reduce the security level of SQL Server 2005.

SURFACE AREA CONFIGURATION

1. Go to Programs –> Microsoft SQL Server 2005 –> Configuration Tools –> SQL Server Surface Area Configuration
2. Click on Surface Area Configuration for Services and Connections
3. Expand Database Engine and Click on Remote Connections
4. Select local and remote connections and TCP/IP and named pipes.
FIREWALL CONFIGURATION

1. Make sure your firewall allows TCP port 1433.
WIRELESS ROUTER CONFIGURATION (if you have one!)

1. Go to port forwarding and forward port 1433 to the internal IP address of the machine running SQL Server 2005 (e.g. 192.168.1.1).
SQL SERVER CONFIGURATION

1. The simplest (but not most secure) method of authenticating a web page query to a database is to use SQL Server authentication. This requires your server to allow Mixed authentication. The more secure method of authentication is windows authentication. For an excellent description on how to set up and use windows authentication with ASP.NET, visit http://www.spaanjaars.com/QuickDocId.aspx?quickdoc=395. If you want to use mixed authentication:

2. Open Microsoft SQL Server Management Studio
3. Authenticate in the usual way (usually Windows Authentication)
4. In the Object Explorer, right click on the name of the server and select properties.
5. Click on the security page and select SQL Server and Windows authentication.

CREATE A NEW SQL SERVER LOGIN (if using SQL Server authentication)

1. Open Microsoft SQL Server Management Studio
2. In object explorer, expand the security folder and right-click on Logins.
3. Select New Login
4. Type in your new username and select SQL Server authentication.
5. Type and confirm a password.
6. [Optional] Uncheck enforce password policy and User must change password at next login.
7. Choose the default database.
8. Click OK
9. In the object explorer, click on the name of your database, expand the folder, and expand the security folder.
10. Click on users and if the user you created is not listed, right-click on users and select new user.
11. The login name needs to be the user you just created (click on … to select a user from a list of users). The username can be the same if you wish.
12. Select the relevant database roles (e.g. db_datareader and db_datawriter).
13. Click OK

Hope this helps!
Grant