Twist Rank #1   Current Rating:   Rate this:
Flag as Inappropriate Flag As Inappropriate Email to a Friend Email to a Friend Print Page Print Page

Start Your Own Page!

It's easy, it's fun, it's FREE!

But Why?
For Fame... be featured on ZestBit.com and ShopAtHome.com!
For Charity... it feels good to give back!
For Sharing... give your thoughts & ideas to the world!

Start Now!

LordZuzza

I enjoy Big Screen TV's w/ football, video games like Guitar Hero,... more
Other Twists by LordZuzza
Total Author Points: 138

Save & Share

Comment on this Article Comment on this Article
digg this digg this
Add to del.icio.us Add to del.icio.us

images.jpgAsp.Net Templated Custom Contol Part #1

Have you found yourself creating web pages with the same controls and functionality with different designs?  Business logic and database access, if done properly, can be reused over and over again with ease.  You could use web controls to resolve some of these issues but you can only have one design for each web control so reuse is limited.

Lets say you want a login form that will go on several different pages with different designs on each page.  You are stuck creating the HTML code for each page. All the textboxes, labels, validation, etc...  This can be time consuming and error prone.

In this article we are going to aleviate these issues with a custom login control that has a template so the design can be different for each control created. We will also create some reuseable custom controls, like an Email Address Text box control, that will include it's own validation and other useful functionality.  Lets get started already!

The Setup (Beginner)

First things first; we need to setup our Visual Studio enviornment. Open Visual Studio and click on File->New->Project and open the Other Project Types section and click on Visual Studio Solutions and create an empty solution project. The name that I used is Blumikty, just made it up, use what ever you want but I will reference that name throught the article so I wanted you to know what it is.

Now lets create our website that will display our new custom controls. Click on File->Add->New Web Site, select File System for the location, place the project under the solution directory and give it a name. Click the OK button to create the new website.

After the web project has been created lets add a new class library project that will house our business logic, controls, and objects that will be used throughout our web project. This will get us a nice 3-tier designed solution that is both scalable and flexible. This method will also have nice seperation from code and design. Anyways, go to File->Add->New Project->Visual C#-->Class Library. Give the new project a name and click on "OK". I named my new project Blumikity.Components for future reference. If VS created a test class called Class1.cs, Delete it!

Now lets add some folders to our new project so we can organize the files we are going to create. To add a new folder simply Right click on the Components project, hover over Add, and then click on New Folder. Create the following folders in the project: BLL, DAL, Controls, and Objects. You are, of course, free to setup your project the way you see fit. This is just the way I like to do it to keep my sanity!  Add a reference to the System.Web assembly by right clicking on References and adding a new reference.  The System.Web assembly can be found under the .Net tab.

The setup porting of the project is now complete. Thank goodness, how boring! Lets move on to the code!

The EmailAddressTextBox Control

Typically in a login form you have 3 basic controls: An Email Address (username) text box, a Password text box, and a button that performs the login action. In my example we will be using an email address as the username. Now we need to create the custom controls for the email address and the password text boxes. The button will just be a built in Asp.Net button that we will attach an event to in the LoginForm control. Lets start with the EmailAddressTextBox control.

Make sure you have referenced the System.Web assembly in your project before continuing.

Right click on the Controls directory in the Components project and add a new class. I called mine EmailAddressTextBox, but you can name it anything you want!

Set the classes accessor level to public and inherit from the Asp.Net TextBox control. This will give us all the built in functionality for TextBoxes. We want our new control to have validation built in and some public properties so we can change the behavior. I want three different types of validation for this control: It is a required field so we want to make sure the user entered something into the textbox, went want to make sure the entered email address is valid, and we want to make sure the email is not already in use (This won't be used with the login control but you may want to use this control elsewhere, maybe with a registration form!). Basic public properties will be available: DefaultEmailAddress, ValidateExisitingEmailAddress, ErrorMessage. I will explain these in detail later.

Here is the EmailAddressTextBox class:

http://manoli.net/csharpformat/ -->
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Blumikity.Components.Controls
{
public class EmailAddressTextBox : TextBox
{
///
/// This is the message that will be displayed if validation fails!
///
private string __errorMessage;
public string ErrorMessage
{
get
{
return __errorMessage;
}
set
{
__errorMessage = value;
}
}

///
/// Do we want to validate that the email address is not already in use
///
private bool __validateExistingEmailAddress = true;
public bool ValidateExistingEmailAddress
{
get
{
return __validateExistingEmailAddress;
}
set
{
__validateExistingEmailAddress = value;
}
}

///
/// Sets the text property of the text box to the this default value.
///
public string DefaultEmailAddress
{
set
{
this.Text = value;
}
}

// This is the regular expression validator for the email address
private RegularExpressionValidator RegExValidator;

// This is the required field validator
private RequiredFieldValidator RequiredFieldValidator;

// This is the custom validator. I use it to validate
// that the email address is not in use already
private CustomValidator CustomValidator;

///
/// Configures validators and adds to child controls of the parent.
///
protected override void OnInit(EventArgs e)
{
// Add RegEx validator to the form
RegExValidator = new RegularExpressionValidator();
RegExValidator.ValidationExpression =
"^[a-zA-Z0-9_]+(?:[\\.\\-][a-zA-Z0-9_]+)*@[a-zA-Z0-9_]+(?:[\\.\\-][a-zA-Z0-9_]+)*\\.[a-zA-Z]{2,4}$";
RegExValidator.ControlToValidate = this.ID;
RegExValidator.ErrorMessage = this.ErrorMessage;
RegExValidator.EnableClientScript = true;
RegExValidator.Display = ValidatorDisplay.None;
Controls.Add(RegExValidator);

// Add required field validator to the form
RequiredFieldValidator = new RequiredFieldValidator();
RequiredFieldValidator.ControlToValidate = this.ID;
RequiredFieldValidator.ErrorMessage = this.ErrorMessage;
RequiredFieldValidator.EnableClientScript = true;
RequiredFieldValidator.Display = ValidatorDisplay.None;
Controls.Add(RequiredFieldValidator);

// Add Custom Validator to the form
CustomValidator = new CustomValidator();
CustomValidator.ControlToValidate = this.ID;
CustomValidator.ErrorMessage = this.ErrorMessage;
CustomValidator.EnableClientScript = true;
CustomValidator.Display = ValidatorDisplay.None;
if (ValidateExistingEmailAddress)
CustomValidator.ServerValidate +=
new ServerValidateEventHandler(OnServerValidate);
Controls.Add(CustomValidator);
}

///
/// Custom validation function.
///
public void OnServerValidate(object source, ServerValidateEventArgs e)
{
string emailAddress = this.Text;
e.IsValid = false;

if (emailAddress.ToUpper().Equals("TESTING@TEST.COM"))
{
e.IsValid = true;
}
}

///
/// Renders the email address text box and it's child controls
///
protected override void Render(HtmlTextWriter w)
{
base.Render(w);
RequiredFieldValidator.RenderControl(w);
RegExValidator.RenderControl(w);
CustomValidator.RenderControl(w);
}
}
}

The PasswordTextBox

Alright now we are getting somewhere!  Lets keep it going by creating the password text box control!  Add a new class to your project and give it a name. I named mine... wait for it... PasswordTextBox, I know SHOCKER!  This control is very similiar to the email address control that we just created.  It will need validation and some basic public properties.

Here is the PasswordTextBox class:

http://manoli.net/csharpformat/ -->
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Blumikity.Components.Controls
{
public class PasswordTextBox : TextBox
{
///
/// This is the message that will be displayed if validation fails!
///
private string __errorMessage;
public string ErrorMessage
{
get
{
return __errorMessage;
}
set
{
__errorMessage = value;
}
}

// This is the regular expression validator for the email address
private RegularExpressionValidator RegExValidator;

// This is the required field validator
private RequiredFieldValidator RequiredFieldValidator;

///
/// Sets validation properties and adds to child controls on init of the form.
///
protected override void OnInit(EventArgs e)
{
this.TextMode = TextBoxMode.Password; // So we see the nice *'s instead of the actual password's characters.

// Add RegEx validator to the page
RegExValidator = new RegularExpressionValidator();
RegExValidator.ControlToValidate = this.ID;
RegExValidator.ErrorMessage = this.ErrorMessage;
RegExValidator.EnableClientScript = true;
RegExValidator.ValidationExpression = ".{6,15}$";
RegExValidator.Display = ValidatorDisplay.None;
Controls.Add(RegExValidator);

// Add required field validator to the page
RequiredFieldValidator = new RequiredFieldValidator();
RequiredFieldValidator.ControlToValidate = this.ID;
RequiredFieldValidator.ErrorMessage = this.ErrorMessage;
RequiredFieldValidator.EnableClientScript = true;
RequiredFieldValidator.Display = ValidatorDisplay.None;
Controls.Add(RequiredFieldValidator);
}

///
/// Renders the email address text box
///
protected override void Render(HtmlTextWriter w)
{
base.Render(w);
RequiredFieldValidator.RenderControl(w);
RegExValidator.RenderControl(w);
}
}
}

Conclusion

What have we learned today class? "How to make custom controls that override built in Asp.Net objects that are reusable and come with loads of built in functionality that we then extended and made even more great functionality!"

What are we going to learn tomorrow (or when I get around to it)? "How to create that custom control with templates that I promised and implement our custom controls inside of it."

Check back often to see if Part 2 has been completed!

Additional Resources

Here are a couple of books from Amazon that should give more information on the subject.

Professional ASP.NET 2.0 Special Edition (Wrox Professional Guides) (Book)

Professional ASP.NET 2.0 Special Edition (Wrox Professional Guides) (Book)
ASP.NET allows web sites to display unique pages for each visitor rather than show the same static HTML pages. The release of ASP.NET 2.0 is a revolutionary leap forward in the ar...more
Average Customer Rating: 4.5 out of 5 (See the reviews)
List Price: $59.99
Lowest Used Price: $12.51 (as of 9/6/2008@5:54 PM)
Lowest New Price: $12.53 (as of 9/6/2008@5:54 PM)

Developing Microsoft  ASP.NET Server Controls and Components (Pro-Developer) (Book)

Developing Microsoft ASP.NET Server Controls and Components (Pro-Developer) (Book)
DEVELOPING MS ASP NET SVR CONTROLS/COMPONENTS
Average Customer Rating: 4.0 out of 5 (See the reviews)
List Price: $59.99
Lowest Used Price: $12.50 (as of 9/6/2008@5:54 PM)
Lowest New Price: $32.86 (as of 9/6/2008@5:54 PM)

Amazon.com
Powered By:

The Zest Book

No Comments