Archive for July, 2010

Check If User Name Exists Using AJAX And C#

You could make sure the user name entered during the registration process of your website is unique before the submit button is clicked using AJAX and C#. To accomplish this create two aspx pages. The first (default.aspx in this example) is the registration page, and it contains a TextBox control with an onkeyup element that calls the updateOutput JavaScript function and a span tag to display the HTML returned by the XMLHttpRequest.send function. The second page (doajaxstuff.aspx) should only contain following tags:

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="doajaxstuff.aspx.cs"
  2. Inherits="ManualAJAX.doajaxstuff" %>
  3. <asp:literal runat="server" id="literal1" />

The html, title and body tags should be removed because the page contents will be added to the default.aspx page, which already has these tags. The C# code that checks if the user name exists is in the Page_Load event of doajaxstuff.aspx. It gets the user name from the query string and displays the result in a Literal control. To keep the example simple I returned “User name exists” or “OK”, but this could be changed to return an img tag to show a red cross image or a green tick respectively.

string[] usernames = { "admin", "administrator", "user1","user2",
                     "guest1", "guest2"};
protected void Page_Load(object sender, EventArgs e)
    string newUsername = Request.QueryString["q"];  

        literal1.Text = "User name exists";
        literal1.Text = "OK";

The JavaScript code below does the AJAX work. The updateOutput function checks first if the TextBox is empty, and exits if true. Then it creates an object called xmlHttp which is an XMLHttpRequest object or an ActiveXObject, depending on the user’s browser. XMLHttpRequest is supported in browsers from Internet Explorer 6, Opera 7.60, Mozilla 1.0, Netscape 7, Safari 1.2 and Konqueror 3.2. If the user has Internet Explorer 5 an ActiveXObject will be created, which basically does the same job. If the xmlHttp object is created the variable url will be assigned a string containing the page to call plus the query string, which is the string entered by the user in usernameTextBox.

The onreadystatechange event handler is assigned the name of the function StateChanged. This event occurs five times: when the request is initialized, set up, sent, being processed and completed. You could check which stage the request is in using the readyState variable (0, 1, 2, 3 and 4 respectively.) The if statement checks for 4 which is set when the HTML is downloaded to xmlHttp.responseText. The if statement also makes sure that xmlHttp.status is 200, which means no error occurred. If both these conditions are true the contents of xmlHttp.responseText are displayed in the span tag.

The open method sets the parameters of the request and contains three parameters; the request method, the URL of the request and a Boolean parameter that specifies the request should be executed asynchronously or not. The first parameter could be “GET”, “POST”, “HEAD” or “PUT”. The second parameter is the relative or full URL of the page to request. And the third parameter should be true so the page could be called asynchronously.

The send method executes the request. Because the open method’s first parameter is “GET”, send’s parameter is null. If open’s first parameter was “POST” it would be a string containing the request parameters.


<head runat="server">
<title>Manual AJAX</title>
<script language="javascript" type="text/javascript">
var xmlHttp;
function updateOutput(inputString)
if(inputString.length == 0)
document.getElementById("output").innerHTML = "";
xmlHttp = new XMLHttpRequest();
else if (window.ActiveXObject)
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
if(!xmlHttp || xmlHttp == null)
var url="doajaxstuff.aspx?q=" + inputString;
xmlHttp.onreadystatechange=StateChanged;"GET", url, true);
document.getElementById("output").innerHTML = "An error occured";
function StateChanged()
if((xmlHttp.readyState == 4) && (xmlHttp.status == 200))
document.getElementById("output").innerHTML = xmlHttp.responseText;
<form id="form1" runat="server">
Enter Username:
<asp:TextBox runat="server" ID="usernameTextBox"
onkeyup="updateOutput(this.value)" />
<span id="output"></span>
<head runat="server">     <title>Manual AJAX</title> <script language="javascript" type="text/javascript">         var xmlHttp; function updateOutput(inputString) {             if(inputString.length == 0)  {                 document.getElementById("output").innerHTML = "";   return;             } try  {                 if(window.XMLHttpRequest)       xmlHttp = new XMLHttpRequest();  else if (window.ActiveXObject)     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");             if(!xmlHttp || xmlHttp == null)  {                     return;                 } var url="doajaxstuff.aspx?q=" + inputString;                 xmlHttp.onreadystatechange=StateChanged;       "GET", url, true);                 xmlHttp.send(null);             }             catch(e)             {                 document.getElementById("output").innerHTML = "An error occured";             }         } function StateChanged() {             if((xmlHttp.readyState == 4) && (xmlHttp.status == 200))  {                 document.getElementById("output").innerHTML = xmlHttp.responseText;             }         }     </script> </head> <body>     <form id="form1" runat="server">     <div>         Enter Username:         <asp:TextBox runat="server" ID="usernameTextBox" onkeyup="updateOutput(this.value)" />         <span id="output"></span>     </div>     </form> </body>

For this example the C# code in the doajaxstuff.aspx page searches an array containing the user names. This could be changed to search through the users in the aspnetdb database using the Membership.GetUser static function. I should also mention that the user can ignore the result of this validation check and submit a name that exists. To prevent this, the same validation should be done in the Submit button’s code.


Drag And Drop Files to a C# Application

The .NET Framework makes it easy to detect objects dragged and/or dropped into a Windows Forms application using one or more of the drag-and-drop events available. In these events you could check if the object is a file.

To enable a control to be a target of a drag-and-drop operation set its AllowDrop property to true and use one or more of the following events:

  • DragEnter: Occurs when the user drags an object into the control’s area, and has not released the mouse button yet.
  • DragOver: Occurs when the object is being dragged in the control’s area.
  • DragDrop: Occurs when the user lets go of the dragged object in the control’s area.
  • DragLeave: Occurs if the object dragged into the control is dragged out again without the user releasing the mouse button, or the user canceled the operation by pressing the Escape key.
  • GiveFeedback: Occurs when the drag-and-drop operation starts and is used to modify the visual feedback of the operation.
  • QueryContinueDrag: Occurs when the keyboard or mouse state is changed during the drag-and-drop operation.

To process one or more files dragged and dropped into a control two events are needed, DragEnter and DragDrop. The if statement in DragEnter checks what is dragged in is of type DataFormats.FileDrop, the Windows file drop format, or not. If true the drag operation is allowed. The DragDrop event retrieves the list of files dropped using the GetData method and casts them to an array of strings. Each element of the array will contain a full path of one of the files dropped.

private void filesListBox_DragEnter(object sender, DragEventArgs e)
    if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)
        e.Effect = DragDropEffects.All;

private void filesListBox_DragDrop(object sender, DragEventArgs e)
    string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);  

    foreach (string file in files)

C# – Autocomplete Textbox

There are times when you’ll need an autocomplete textbox. Autocomplete textbox makes the user’s life easier. It shows suggestions as the user types. In case of a web browser, if you type “goo” it will automatically show all the suggestions starting with or containing “goo” like “Google, Goofy” etc. Enough talk! Lets get on with it.

Fortunately, textbox has a built-in autocomplete feature! We don’t have to do any coding.

You can either set it up from the Designer (if you are using Visual Studio or #Develop) or do it via code. It is simple both ways. Lets do it!

Setting up AutoComplete

For setting up autocomplete you’ll have to use three properties of the TextBox class — AutoCompleteSource, AutoCompleteCustomSource and AutoCompleteMode. Here’s an explanation of these properties:

AutoCompleteSource is the source of the suggestions. You can assign it CustomSource if you want to use custom suggestions or use other auto sources like FileSystem, HistoryList etc. Below are all the available sources:

FileSystem: This will show suggestions from the file system i.e files stored on the computer. Like if you write “C:\” it’ll show all the files stored on C: drive.
FileSystemDirectories: This is same as FileSystem but it shows directory names instead of file names.
HistoryList: This will show URLs from Internet Explorer’s history.
RecentlyUsedList: A list of recently used applications, folders, and URLs (from internet explorer).
AllUrl: This specifies an equivalent of HistoryList and RecentlyUsedList as the source.
AllSystemSources: Specifies an equivalent of AllUrl and FileSystem as the source.
AutoCompleteModes are of 3 types. Suggest, Append and SuggestAppend:

Suggest will show suggestions in a drop-down as the user types.
Append will auto complete as you type. Like if you write “Goo” it’ll automatically make it “Google”.
SuggestAppend will do both Suggest/Append.
AutoCompleteCustomSource is collection of custom suggestions. It will be used when you assign “CustomSource” as “AutoCompleteSource”.

Okay enough explanations. Lets make an autocomplete textbox now.

Using Designer:
If you are using the Designer, then all you have to do is to select your TextBox and change those three properties (explained above). For instance, if you want to use custom suggestions then use “CustomSource” and add the custom suggestions to “AutoCompleteCustomSource” (don’t forget to set up AutoCompleteMode). Debug your project and see! Its that easy . Don’t forget that you can also use all the other sources like FileSystem, HistoryList etc.

The Code:

// List of custom suggestions
string[] suggestions = new string[] {
"Google Images",

// Use the AutoCompleteMode that suits you.
textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;

// Since we are using custom suggestions you
// should use this source.
// Use the other non-custom sources if you
// don't want to use custom suggestions.
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;

// And finally add the above suggestions to the CustomSource

Crop Image – C#

For cropping an image in C#  we can use the Graphics class. We’ll use a method which will take 2 parameters, a source image and a rectangle of the section that should be cropped.  Let’s code!

The Code

public Bitmap CropImage(Bitmap source, Rectangle section)

 // An empty bitmap which will hold the cropped image
 Bitmap bmp = new Bitmap(section.Width, section.Height);

 Graphics g = Graphics.FromImage(bmp);

 // Draw the given area (section) of the source image
 // at location 0,0 on the empty bitmap (bmp)
 g.DrawImage(source, 0, 0, section, GraphicsUnit.Pixel);

 return bmp;

// Example use:

Bitmap source = new Bitmap(@"C:\tulips.jpg");
Rectangle section = new Rectangle(new Point(12, 50), new Size(150, 150));

Bitmap CroppedImage = CropImage(source, section);

The above code will work perfectly but it seems confusing, doesn’t it? You might have been wondering how it works. Well…

We first make an empty bitmap of the same width/height as the section rectangle. This bitmap will hold the cropped image. We use the section rectangle’s width/height because it determines the size of the cropped image. Then we use the Graphics class’s DrawImage() method (function) for the cropping. It draws the given area (section) of the source image on the empty bitmap and that’s it. The empty bitmap now holds the cropped image.

Silverlight 4 debugging and Firefox 3.6.4+

I’ve been stuck on this for a few days.

At the moment, Firefox 3.6.4 (and newer) have a new functionality called ‘Crash protection’, which is quite nice.

For customers.

It now runs the plugins in a separate process called ‘plugin-container.exe’ (look in your task manager).

But for developers it’s quite the hassle, since Visual Studio attaches itself to Firefox but NOT to this process. So no more Silverlight debugging for you!

Luckily there are two options for you!

The first option is the most straight forward, but has to be done each time. Use Visual Studio to attach itself to plugin-container.exe, refresh the website, and BAM, you’re up and running!

On the next screen click ‘plugin-container.exe’. There might be 2, if so, select the one with ‘Silverlight’ in the ‘Type’ column:

And hit ‘Attach’.

While this solution is adequate for when you need to debug it one time at a day, but for me, I only debug in Firefox, and when necessary I use Internet Explorer. For that you can go to your ‘about:config’ in Firefox, disable ‘dom.ipc.plugins.enabled.npctrl.dll’ (set it to false).

Regular Expressions in C# – Practical Usage

This is the second post in the C# regular expression series and it follows up on “Regular Expressions in C# – The Basics” which explained the theory behind Regular expressions in C#. In this post we look at how to make practical use of regular expressions in our C# code.

This post touches on four major regular expression subjects:

  • String Comparison – does a string contain a particular sub-string?
  • Splitting a string into segments – we will take an IPv4 address and retrieve its dotted components
  • Replacement – modifying an input string
  • Stricter input validation – how to harden your expressions

String Comparison – finding valid HTML tags

One of the essential functions of expressions are their ability to find if a string is contained inside another one. The RegEx.Matches method tests if a given string matches the pattern.

We start with a simple example: finding out where the letter “a” is mentioned in a sentence:

string Input = "apples make for great party accessories";
Regex FindA = new Regex("a");

foreach(Match Tag in FindA.Matches(Input))
    Console.WriteLine("Found 'a' at {0}",Tag.Index);

That was almost too easy. Regular expressions really shine if you don’t know exactly what you are looking for but you can describe it. In the following example we will look for all valid HTML tags in an input string.

What is a valid HTML tag? <code>, </code>, <b>,<img src=””>, </br> are all valid HTML tags.

Regex HTMLTag = new Regex(@”(<\/?[^>]+>)”);

To break this down:

  1. All valid HTML tags start with a “<”
  2. They might or not have a forward slash (we need to escape the forward slash) \/?
  3. There is at least one or more characters which are not “>”
  4. The tag ends with a “>”

The following code example searches for all valid HTML tags in the input string:

using System;
using System.Text.RegularExpressions;

namespace RegularExpression
    class MainClass
        public static void Main(string[] args)
            Regex HTMLTag = new Regex(@"(<\/?[^>]+>)");

            string Input = "<b><i><a href=''>Ipod News</a></b></i>";

            foreach(Match Tag in HTMLTag.Matches(Input))
                Console.WriteLine("Found {0}",Tag.Value);

Resulting in:

Found <b>
Found <i>
Found <a href=’’>
Found </a>
Found </b>
Found </i>

Splitting a string into parts

Parentheses () not only allow you to group your expressions into parts they allow you to split a single string into multiple segments which we can inspect individually. To demonstrate we will use a regular expression to split an IPv4 address into its components.

A decimal TCP/IP address looks like XXX.XXX.XXX.XXX with X being a decimal number. Each column has at least 1 digit, and a maximum of 3. So a single column can be described as “(\d{1-3})“. There are four columns, each seperated by a dot. The dot (.) has a special meaning in regex so we need to escape it. (\.)

The Regex.Match method returns a new Match instance. We can now testMatch.Success to see if the input string matched the TCP/IP address pattern. Through the Match.Groups property can we then extract each of the four IP address columns.The zero entry in the Groups property is alway the complete match, in this case “″. The [1] entry contains the first groups contents, [2] the second etc.

string IPMatchExp = @"(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})";
Match theMatch  = Regex.Match("",IPMatchExp);
if (theMatch.Success)

String Replacement

Often it is useful to manipulate a string, by replacing the matched pattern with something new. The RegEx.Replace method allows us to specify a pattern to look for and a replacement string.

The following example matches the last character and space following each word and replaces it with “b_”.

Regex Replacer = new Regex(@"\w "); // Single [a-zA-Z] followed by a space
string Input  = "ax bx sax dam pom";
string Output = Replacer.Replace(Input,"b_"); // Replace all items found with a b and underscore

Substitution Patterns

What to do if you would like to flip parts of a string? C# offers several substitution patterns for this. Substitution patterns can only be used in a replacement string, and are used in combination with grouping.

They are useful if you would like to format the results of the match. A common task is to flip two words around. In the below example we flip the name “Molly Malone” into “Malone Molly”:

Regex Replacer = new Regex(@"(\w*) (\w*)");
string Input  = "Molly Mallone";
string Output = Replacer.Replace(Input,"$2 $1");

The regular expression is defined as two groups of words (\w*) separated by a space. Each group can be referred to with a substitution pattern. $1 refers to the first group, $2 to the second (and if we had defined more $3 would be the third etc).

Input validation – we have to be more strict

Often we need to check if the data inputed or read from a file matches a definition so that we know its valid. But for this to work we need to ensure that our expressions only match a valid input. Many expressions of convenience are defined too loose. If we are to use them for input validation we need to harden them.

The pattern we used in an earlier example neatly broke down a valid IP address. But it wasn’t very strict and there are many combinations that would have matched that aren’t valid IP addresses. 999.999.999.999 is not a valid IPv4 address but it would have matched our pattern (@”(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})”). So we couldn’t have used it for testing for a valid IP address.

So what is a valid match? We need to define this first.

A valid IP address range is from to (with each column being represented by a byte).

At this point there are two things we can do: we can validate the results returned by our expressions with a few additional lines of C# code or we modifying our regular expression to become stricter. As this post is about regular expressions we will modify our expression to match only valid IP addresses.

How do we define valid ? 0,9,10,19,100,199,200,249,255 are all valid inputs for each column. 300 isn’t valid, and neither is 299. To keep things simple, we don’t allow 09 as a valid input.

  • Single digit: 0 – 9 :   [0-9]
  • Double digit: 10 – 99: [1-9][0-9]
  • Triple digit 1:  100 – 199:  1[0-9]{2}
  • Triple digit 2: and 200 – 249:  2[0-4][0-9]
  • Triple digit 3: 250 – 255 25[0-5]

The single ([0-9])and double digit ([1-9][0-9]) combinations can be combined into:[1-9]?[0-9]. (Read as: The first 1-9 is optional, occurs 0 or 1 time)

So a single column can be defined as: (([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.) Note the “.” at the end.

On the final column we do not need a “dot”. We can save some space by repeating the first expression three times, but we need to write out the fourth in full. Thus our expressions becomes: ([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.{3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])

Not exactly easy to read, but lets test to see if it works as expected. The following example program tries all column combinations from 0-999.

using System;
using System.Text.RegularExpressions;

namespace RegularExpression
    class MainClass
        public static void Main(string[] args)
            string IPTestExp = @"(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|255[0-5])\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])";

            for (int Lp = 0; Lp < 999; Lp++)
                string IPAddress = String.Format("{0}.{0}.{0}.{0}",Lp);

                if (Regex.Match(IPAddress,IPTestExp).Success)
                    Console.WriteLine("{0} is valid",IPAddress);
                    Console.WriteLine("{0} is invalid",IPAddress);

For brevity the program ends at the first invalid combination. If we had let it run it would have shown 256-999 as invalid. is valid is valid is valid is valid is valid is invalid

This took a bit of work but we now have a single line test to see if a string is a valid IPv4 address.

C# guidelines that improve your code quality

I am inspired to better myself after reading Dennis Doomen’s freshly released coding guidelines for C# 3.0 . He provides a very nice PDF document that puts the dot to many common C# coding “confusions”. It addresses how to consistently name your variables, namespaces, classes and assemblies. He specifies when to declare a variable as static, as readonly and when to seal a class among others.

Another topic he pushes is code readability and ensuring that all code statements are as clear as possible.

You will often have your own way of doing things. A shared coding guideline is a good way to ensure that each member of your team is writing code styled as similar as possible.

If your company is looking at adopting a coding guideline for its C# development this would be a very good place to start.

At 32 pages it might seem a little long at first but it reads quickly and most topics should already be familiar if you do a lot of coding. Its companion quick reference guide neatly puts most key items onto a single page and makes for a great handout.