ASP.NET Controls - Part Two
 
Published: 08 Oct 2003
Unedited - Community Contributed
Abstract
This article demonstrates the custom controls and components features of ASP.NET.
by Devarticles.com
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 21786/ 116

Introduction

In part one of this two part series we took a look at ASP.NET user controls, HTML controls, server controls, and the code behind method. In this article (the final article in the two part series), we will take a look at custom controls and components. It is recommended that you read the first article before continuing if you haven't already.p
Custom Control vs. Components

It's time to introduce custom controls and components. Custom controls provide programmers with reusable HTML outputting code that involves a small amount of processing. They are accessed through a web page (.aspx), using custom tags, just like user controls. All server controls can be thought of as custom controls that have been pre-made by Microsoft.

Components on the other hand provide programmers with reusable application logic that involves some fairly intensive processing. They are accessible from a code behind page or between <script> and </script> tags in a web page. All base classes and objects developed by Microsoft can be considered pre-made components.

Although both custom controls and components can do exactly the same things, their uses will become clearer as you have more experience with them. For example, you could make a menu bar using components and load a method in a component that makes the menu load in the Page_Load class, but it is much easier to use custom controls in an aspx page as custom tags, and place them wherever we want the menu to appear.

Using a Custom Control

A good use of components is to turn functions contained within application logic code into reusable components. Let's have a look at an example of using a custom control. We will make a custom control that takes a parameter and displays that parameter in a large font. Start off by opening notepad and entering following code. Save the file as customc.cs.

using System;
using System.Web;
using System.Web.UI;

namespace devArticles
{
public class CustomC : Control
{
string tempText;

public string Text
{
get {return tempText;}
set {tempText = value;}
}

protected override void Render(HtmlTextWriter writer)
{
if (tempText == null)
{
tempText = "Default Text";
}
writer.Write ("<h1>" + tempText + "</h1>");
}
}
}

Open up another notepad window and save the following code as customc.aspx:

<%@ Register TagPrefix="devArticles" Namespace="devArticles" Assembly="CustomC"%>

<html>
<head>
<title>Code Behind Example
</head>
<body>
<devArticles:CustomC runat= "server" Text = "Title"/>

<devArticles:CustomC runat= "server" />
</body>
</html>

Using the command line, enter the following commands to compile our custom control:

md bin
csc /t:library /out:bin\customc.dll /r:System.dll,System.Web.Dll customc.cs

Let's take a look at the details of the code shown in the examples above.

public class CustomC : Control

public string Text
{
get {return tempText;}
set {tempText = value;}
}

We start by creating a class that is derived from the "Control" base class. Next, we have a public property named "Text". We can use the get and set accessor methods to modify and set the value of the string variable tempText variable, which exists in our class.

protected override void Render(HtmlTextWriter writer)

In the line above, we over ride the inherited method named Render. We declare the method as protected, because we don't want people to access if from outside of the control. The HtmlTextWriter is an object that we automatically receive from server. It allows us to output text to the web browser. In an aspx page, every tag is written to use this object when it is displayed.

if (tempText == null)
{
tempText = "Default Text";
}
writer.Write ("<h1>" + tempText + "</h1>");

The code above makes sure that the tempText value can never be empty. If it is empty (ie the get accessor of the Text property hasn’t been called), then it is set to "Default Text". Lastly, we use the Write method of our HtmlTextWriter object to output its value between a <h1> tag to the browser.

Let's now take a look at the aspx page:

<%@ Register TagPrefix ="devArticles" Namespace="devArticles" Assembly="CustomC"%>

We start off by registering a new user control, except we use the "Assembly" keyword instead of "TagName", and "Namespace" instead of the file location, because the server already knows where to search for the .dll files (in the /bin folder).

<devArticles:CustomC runat= "server" Text = "Title"/>
<devArticles:CustomC runat= "server" />

We have used the same custom control twice to show how that default value will be assigned if one isn't specified. The first tag explicitly specifies a value for our Text property, whereas the second one doesn't. Before this example will work, we have to compile it using the C# compiler:

csc /t:library /out:bin\customc.dll /r:System.dll,System.Web.Dll customc.cs

In our call to the C# compiler, we specify the output directory for our files, as well as the file names and namespace that we have used to create our files. Finally, we specify the name of our source code file.

When I ran this example in my web browser, it looked like this:

Testing our control in a browser - aspcn2_1.gif

And there we have it, our first custom control. Now that we can create and compile custom controls, let's take a look at components.

Components

If you've developed with classical ASP, then you will understand the pain you have to go through to develop and integrate components into your ASP web site using tools and technologies such as regsvr32 and COM+. ASP.NET has revolutionized the way components are created and used, and they are extremely easy to develop and implement.

Firstly, let's find out what components really are. Put simply, components are namespaces that contain classes with methods and properties that can be reused. In classical ASP, the primary use of components was to increase the speed of ASP pages, because COM components were compiled into machine code, thus making them quicker to execute than ASP pages. In ASP.NET, both pages and controls are compiled and cached, so what are the benefits of using components over inline ASP.NET code?

Well, let's think about this situation: you’ve just made a program that has encrypting and decrypting capabilities using secret algorithms. You want to sell the encrypting section of the program to a third party so that they can integrate it in to their program, but you don't want them to know how the encryption methods work, you want the method to act as a black box, accepting a value, and returning that value encrypted.

By using components, you can provide these companies with the required encryption method without actually letting them see your source code or change it in any way. Using components is a great way to reduce the chance of someone plagiarising your source code and methods that you've worked hard to create.

Let's look at an example of creating and using a component. We will create a component containing one method called "Add", which will take two integer parameters and return the sum of these integers.

Enter the following code into notepad and save it as comp.cs:

using System;

namespace devArticles
{
public class devComp
{
public int Add(int a, int b)
{
return (a+b);
}
}
}

Create another file named comp.aspx and enter the following code into it:

<html>
<head>
<script language= "c#" runat ="server">
void Page_Load()
{
devComp objComp = new devComp();
label1.Text = Convert.ToString(objComp.Add(1,2));
}
</script>
</head>
<body>
<asp:Label id="label1" runat="server"/>
</body>
</html>

Before we can run our .aspx page in a web browser, we have to compile our custom control. Enter the following commands at the command line:

md bin
csc /t:library /out:bin\ comp.dll /r:System.dll comp.cs

When I ran comp.aspx in my web browser it looked like this:

Testing our control in a browser - aspcn2_1.gif

The code for our custom controls is fairly straight forward, so let's just take a look at some important parts:

namespace devArticles
{
public class devComp
{
public int Add(int a, int b)
{
return (a+b);
}
}
}

The code above creates a new public class named devComp. DevComp contains one public function called "Add" that takes two parameters and returns an integer, as described earlier. Both the class and function are contained within the "devArticles" namespace.

<%@ Import Namespace = "devArticles"%>

The line above simply imports the "devArticles" namespace, and is equivalent to "using devArticles;" in a typical C# application.

devComp objComp = new devComp();
label1.Text = Convert.ToString(objComp.Add(1,2));

In our .aspx page, we create a new instance of our devComp class and set the value of the Text member for our label control to the string value of the result returned by calling the "Add" method (In our example we pass in 1 and 2, which returns the value 3). Components are a great addition to any ASP.NET web site, and they provide an easy way to encapsulate your code into compiled objects, which can be instantiated, but never have their source code viewed.

Conclusion

Over the last two articles we've looked at a number of different methods that we can use to divide our ASP.Net pages up into a number of smaller, self-contained chunks of code. Using these methods can help our web applications become more scalable and easier to manage.

The features described in this are what make ASP.NET pages so flexible, and you should use them as often as you can to separate your presentation layer from your application logic layer. Take a look at the books and links below for more information on controls.

Support Material

This article contains a support file. To download the attached support file, please click here.

Related Links

/articles/usercontrols1.aspx
http://www.4guysfromrolla.com/webtech/100500-1.shtml
http://www.asp101.com/articles/carvin/transtodotnet/default.asp
http://msdn.microsoft.com/library/en-us/cpguidnf/html/cpcondevelopingwebformscontrols.asp?frame=true

This article was contributed by James Yang at http://www.devarticles.com.devArticles provides ASP, PHP and .NET articles, tutorials, reviews, interviews and FREE eBooks. If you're after some serious programming tutorials then...

Visit http://www.devarticles.com now...OR, for free eBooks
visit http://www.devarticles.com/ebooks.php

 


User Comments

No comments posted yet.

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2019 ASPAlliance.com  |  Page Processed at 2019-05-23 12:05:49 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search