11 Programming Mistakes You Don’t Even Realize You’re Making

Disposing Objects Properly

The ‘using’ syntax doesn’t get nearly the kind of exposure it should, and it’s all to easy to not understand which objects need to be disposed of properly, and for which it doesn’t matter. For example, I bet you realize that SQLConnections should always be closed, and disposed of, but what about StringWriter? It too needs proper attention.

using (StringWriter myStringWriter = new StringWriter())
	// . . .
using (SqlConnection con = new SqlConnection(myConnectionString))
	using (SqlCommand cmd = new SqlCommand(stringSQL, con))
		// . . .

Filling Your Database With Bad Data

User input. We love it, we hate it, and most of the time, it defies our expectations in one way or another. Here are some ways you probably aren’t properly taking care of your data:

  • proper capitalization of names
  • trimming leading and trailing spaces or zeros
  • verification of birth-dates : leap years, and improbable ages (a user registering who says they are 110 years old? Or, that they are only 2 years old?)
  • data encoding and decoding, especially for HIPA requirements
  • along the lines of multi-line or rich-textboxes, cleaning up HTML where there shouldn’t be any or removing MS Office meta-data from naive users’ copy-paste operations
  • length restrictions both in your code and on your database – so your FirstName field doesn’t take up VARCHAR(MAX) disk space

Shooting Yourself In The Foot With Lack of Documentation (Or Comments)

Simply put, the proper amount of documentation is near impossible to achieve. While we shouldn’t be writing novels in our code, they should quickly jar our memory when we need to revisit them a few years later. Whether it’s specification documents, contracts, or comments, it’s all to easy to fall short.

Slowing Your Own Server Down With Debug Mode

Debugging is great for us developers, but in production servers, it takes up extra processing power.

<compilation debug="true">

Unnecessary Post Back Operations

While intermediate developers are probably aware of the IsPostBack feature, new ones may not be, causing unnecessary operations – which usually involve database calls

Unusual Circumstances Bypassing Your Data Validation

Did you know that sometimes your submit button’s onclick or onclientclick method can be called even though your validators have errors? It is true! Checking Page.IsValid will save heartache and mysterious bad data.

if (! Page.IsValid)
// return to the page - the validators will now show their error messages

Sluggish Server Responses Via UpdatePanel

Although it seems like magic, ASP.NET AJAX’s UpdatePanel has some necessary flaws, and it’s important to know them. When UpdatePanel updates asynchronously, it performs a postback by sending the data of everything inside it via HTTP. Now, if you have a lot of data inside your UpdatePanel, this update is going to be very slow.

Crashing Your Own Server With Session Data

If you’re storing a lot of stuff in your Session variables, be warned, this can act like a DOS attack on your server (OWASP, more info). Basically, SessionData takes up memory, and with enough users, it begins to act like a memory leak.

Query Variable Injection

Query variables can be useful, but also terrible, as it exposes data to the user for all-too-easy manipulation any dabbler can play with. SQL injection is also something to watch out for, however the fix for this can be as simple as using ASP.NET’s built-in parametrized queries.

Leaving Document, HTML Files Insecure

By default, IIS only applies your security settings (usually in your web.config file) to ASP and ASPX files, leaving any images, HTML, or other document files open for anyone who has the URL. To fix the problem, special settings can be applied to IIS.

Tying Your Database’s Hands Behind Its Back With Lack Of Keys and Indexes

MS SQL Server, and other servers, have out-of-the-box optimizations that make your queries run surprisingly fast. However, they all depend on the query analyzer being able to pick up on ways to speed up the query. Basically, when you don’t use keys or indexes, the query analyzer doesn’t know what to do with your data, and thus can’t really make any optimizations. As a result, it defaults to the most reliable way of doing things, which is consequentially, the slowest.

Debugging your AJAX AutoCompleteExtender

The AJAX AutoCompleteExtender is a useful utility that looks very easy to implement, however, can be a time consuming whirlwind of confusion in the darkness.

Here’s how to trouble shoot:

  1. Make sure it compiles and runs
  2. Make sure that your AJAX method fires – get yourself a copy of Fiddler (only seems to work with IE) and watch the HTTP requests for your method
  3. If it doesn’t fire, check to make sure that your MinimumPrefixLength (the number of characters required of the user to type before AutoComplete kicks in), and CompletionInterval (the number of milliseconds after the appropriate number of characters are typed before AutoComplete helps out) have the right values
  4. Also make sure that the namespaces and attributes are correct.
  5. If it is actually firing, check the response, is there an error?
  6. If it’s actually firing and you have no errors, check that data is actually being returned

In addition, I’d like to throw my two cents in – the majority of AutoCompleteExtender examples and tutorials are incorrect if you’re on ASP.NET 4.0 . They all say that your GetCompletionList for your AJAX method (or similiarly named method) takes a third arguement, a string called contextKey. This is not true and will produce a HTTP error. The actual method signature is :

[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
public static string[] GetCompletionList(string prefixText, int count)
// do things and return the string array
string[] movies = { "Star Wars", "Star Trek", "Superman"};
return movies;

HOWTO: Manage multiple web.configs without going insane

Most ASP.NET set-ups encourage an environment with three webservers : production, testing, and development. In optimal solutions, all the servers are exactly the same, but in real life, they aren’t, and it causes problems. So, you end up having to adjust your web.config differently for each server.

Some suggest using the build tools with your IDE to tell it which files to put where, what to put in files, etc, but this requires scripting and work. Who has time to learn yet another language for that? Instead, I propose an easy solution.

web.config Managed Gracefully

Keep all of your configs inside the solution, with filenames indicative of the servers they go on. Of course, web.config which will carry the contents needed for the current server. Upon every deployment, I simply swap the contents of web.config with the correct config for the project’s location. Simple. Picture below.

Multiple web.configs managed gracefully

Multiple web.configs managed gracefully

ASP.NET : Download Manager Control

If you find yourself bashing your head trying to get files to download properly, or you would like more security with your downloads, try creating a download manager control. It is fast and easy.

Inside your page, we’ll make our hyperlink.

To download the file, <b><asp:HyperLink ID="uxhyperlink1" runat="server" Text="click here" NavigateUrl="#" /></b>.

Inside the page’s code behind, we’ll add the proper URL.

 String filesPath = "../Files/"; //perhaps yours is different
 String fileName = "instructions.pdf"; //perhaps yours is different
 uxhyperlink1.NavigateUrl = "DLhandler.ashx?fname=" + filesPath + fileName;

Finally, we’ll create the ASHX handler, DLhandler.ashx :

<%@ WebHandler Language="C#" Class="DLhandler" %>

using System;
using System.Web;

public class DLhandler : IHttpHandler {

    public void ProcessRequest (HttpContext context) {

        String fileName = context.Request.QueryString["fname"];

        if (fileName != null && fileName.Length > 0)
            //if there is a file...
            var r = context.Response;
            r.Buffer = true;
            r.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
            r.ContentType= "binary/octet-stream";
    public bool IsReusable {
        get {
            return false;


Syrinx CK Editor

Older versions of FCKEditor are known to be incompatible with the Google Chrome browser.  There are two solutions – upgrade to the last release of FCKEditor 2.6.5, or upgrade to the newest CK Editor.

The new CK Editor is less offensive for lexdystic users, is still free, and sports a more colorful user interface. However, as of Jan 1, 2010, CK Editor is on version 3.1 and does not currently support ASP.NET.

CKEditor 3.1

Thanks to the folks at Syrinx, there is a future for CKEditor on the ASP.NET platform.  Syrinx CKEditor is an ASP.NET wrapper control and your solution to this quandary. I also found another wrapper by eXistenz, less impressive, and less documented than Syrinx.

CKEditor and Syrinx Integration (ASP.NET)

Download the latest CKEditor editor files and extract them to the root of your project. Next, download the Syrinx files and place the SyrinxCkEditor.dll in the bin folder of your root. You need to add a reference to the assembly at the top of each of your ASPX files that calls the CK Editor:

<%@ Register Assembly="SyrinxCkEditor" Namespace="Syrinx.Gui.AspNet" TagPrefix="syx" %>

And finally to call the CK Editor:

<syx:CkEditor runat="server" id="ed1" />

A quick note, the text inside of the editor is now referenced by .Text instead of FCKEditor’s .Value

Compacting CKEditor

CKEditor is not too large, however, because you need a ckeditor folder for every application with Syrinx, the overall size of CKEditor files can become overwhelming. To trim down the size of CKEditor, similar to FCKEditor, you can delete some files:

  • /_samples
  • /_source
  • unused languages in /lang
  • unused themes in /themes

Trouble Shooting

If you are having problems referencing the assembly, verify it is in the bin folder of the root of your project. Verify that the ckeditor folder is also in the root of your project. Unfortunately, I have not discovered a way to have a single ckeditor folder that is referenced by several projects (this was doable with fckeditor), so you need a ckeditor folder in each of your referencing projects.

If you are still having problems, there are reports that the ckeditor files provided by the official site download create issues. To fix, you can try deleting the contents of the folder and replacing them with the contents of the ckeditor files in the SyrinxCkEditor Demo.

ASP.NET Specific Error Message Fixes

The files ‘MyScripts.js’ and ‘CodeBehind.cs’ use a different language, which is not allowed since they need to be compiled together.

This error occurred when I put a JavaScript file in my App_Code folder. Simply move it out of that folder.

Both DataSource and DataSourceID are defined on ‘(id)’. Remove one definition.

This is an odd error message that usually means that you are binding a control twice to a datasource. However, if you are binding your control to an object (datatable, for example), that that object is empty and contains no data. Populate your data object and the error message will go away.


(I’ll post more as I find them…)

ASP.NET Apps : Migrating IIS 6 to IIS 7 ; IIS 7 Errors

Migrating from IIS 6 to IIS 7 is a pain in the rear.

From first hand experience, let me tell you, you want to start with a new web.config generated by Visual Studio. There’s a few new sections in there like runtime, and system.webServer. The latter being specifically for IIS7.

I experienced a plethoria of issues in this migration process with my ASP.NET applications. The primary symptoms of IIS 6 to IIS 7 migration troubles are pages that work on some servers but not others, in some browsers but not others, and mysteriously work one day but not another. The primary culprit is usually the web.config.

Here are some issues I discovered and how to fix them.

httpHandlers and httpModules

Server Error in Application “”
Error Summary: HTTP Error 500.22 – Internal Server Error
An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.

Most Likely Causes: This application defines configuration in the system.web/httpModules section.
Most Likely Causes: This application defines configuration in the system.web/httpHandlers section.

FIX: IIS7 does not seem to like httpModules and httpHandlers. In actuallity, it does like them, very much so, however, they are now renamed to ‘modules’ and ‘handlers’ respectively and belong in the system.webServer. You can delete the sections, but then you will probably encounter errors with Validation controls not being called automatically upon postbacks – and you can work around that by manually calling Page.Validate() and if (!Page.IsValid){ return } .

Clientside Javascript (Custom Validators):

I was manually entering “(document.findbyid(‘$ctx200$section1$uxTextbox3’) …” and this had problems with IIS7 that were fine under IIS6. Try using uxTextbox.ClientID instead of hardcoding IDs.

Assemblies Errors

Could not load file or assembly ‘System.Web.Extensions.Design, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ or one of its dependencies. The system cannot find the file specified.

FIX: The new IIS7 web.config section runtime includes some new ways to use assemblies that include an ‘oldversion’ tag, they look like this:

      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
          <bindingRedirect oldVersion="" newVersion=""/>
          <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
          <bindingRedirect oldVersion="" newVersion=""/>

OR, you can do it the hard way: going to START > RUN > assembly And adding the correct version and public key tokens. If it is already correct and you still get errors, try changing the string to all upper or all lower case letters.

Forms Authentication Problems

SYMPTOMS : The terrible white screen of IE death – “Internet Explorer cannot display this webpage”, no error messages. Inside your Event Log, there will probably be 302 Error messages. Some other symptoms include the page taking over five minutes to load in IE and the IE process taking upwards of 1,800,000 of memory and substantially high CPU from your server (mine was at 55%!).

FIX: The new IIS7 targeted web.config has sections that fix this.

Javascript ScriptHandler/ScriptManager Errors

‘Sys’ is undefined

SYMPTOMS: Custom Javascript and/or CustomValidator can start acting funny or skip validation. Sometimes a page works on one server but not another, in IE but not Firefox, etc, etc.

This can occur when the  web.config does not contain all of the sections for AJAX. Scrutinize your web.config line by line and make sure all of the AJAX sections are included. In my case, I was missing some sections inside of the system.webServer section, and after re-addition, everything works beautifully again.


Related Posts: web.config Hell: Managing Multiple or Mixed Environment web.config’s


ASP:Gridview + DataSets Done Easy

Here is a neat little portion of code I stumbled across. It uses ObjectDataSource, and we sidestep writing our own sorting methods.

namespace Utils{
   public class DataSetUtils{
        public static DataSet GetMyDataSet()
            using (SqlConnection con = new SqlConnection(Convert.ToString(HttpContext.Current.Application["con"])))
                using (SqlCommand cmd = new SqlCommand("SELECT * FROM Students", con))
                    cmd.CommandType = CommandType.Text;
                    DataSet ds = new DataSet();
                    SqlDataAdapter adp = new SqlDataAdapter();
                    adp.SelectCommand = cmd;
                    try  {
                    } catch (Exception x)   {  /* do stuff */  }
<asp:GridView ID="uxGridView" runat="server" AllowSorting="true"  DataSourceID="ObjectDataSource1">
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" 
  SelectMethod="GetMyDataSet" TypeName="Utils.DataSetUtils">

ASP.NET FileUpload, Update Panel, Update Progress

Here is an example of a file upload inside an update panel with a upload progress control. I used this with a timer and several other panels as well. The updatepanel and fileupload controls are very finicky to be able to work together.

<asp:Panel ID="Panel_FileUploaded" runat="server" Visible="false">
    You have uploaded your filesuccesfully.

<asp:Panel ID="Panel_FileUpload" runat="server" Visible="true">
    <asp:UpdatePanel ID="UpdatePanel1" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
            <asp:PostBackTrigger ControlID="Button1" /> 
            Please upload file from your computer. <br /><br />
            File: <asp:FileUpload ID="FileUpload1" runat="server"  />
            <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" OnClientClick="javascript:if(document.getElementById('ctl00_Content_FileUpload1').value.length > 0 ){$get('ctl00_Content_UpdateProgress1').style.display='block';$get('ctl00_Content_Button1').style.display='none';}"  />
            <span style="color:Red;"><asp:Label id="Label_Error" runat="server" Visible="false" Text="* Required" />
    <asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
            <img src="work_in_progress.gif" />
            <span style="color:Green;">Working...</span>
    protected void Button1_Click(object sender, EventArgs e)
        if (!FileUpload1.HasFile)
            Label_Error.Visible = true;
            // check file extension, upload, etc ...
            Panel_FileUploaded.Visible = true;
            Panel_FileUpload.Visible = false;