You are on page 1of 25

ASP.NL1 2.

0
with C4 and
Visual Studio 2005

;Draft ava .avte cbater. 11,,200:)



John Low
,Please send your input to johnlow5002yahoo.com,


270
Chapter 13 Custom Controls
.
Develop a Custom Server Control (done)
1his examples show you how to deelop a custom control similar to the
standard System.\eb.UI.\ebControls.Label control, and deploy it in a
\eb page. 1he custom control you will deelop deries rom
System.\eb.UI.\ebControls.\ebControl and deines a 1ext property
similar to that o the standard Label control. It oerrides the
RenderContents method o the parent control to illustrate rendering o
the contents o the control using ormating capabilities.

What you need to develop a custom control
\ou can deelop your custom control using any text editor. A
deelopment enironment such as Visual Studio or Visual C4 is not
necessary but will certainly make lie quite a bit easier. 1he command line
compiler included with the .NL1 lramework SDK can compile and build
the control or you or deployment. Regardless o how you create your
control, using Visual Studio or a plain old text editor, the control can be
made aailable in the toolbox o Visual Studio where it can be dragged
and added to a design surace similar to the standard ASP.NL1 controls.
Deployed in this manner, the control`s design-time appearance and
behaior are similar to the standard ASP.NL1 controls, whereby its
properties and eents can be accessed using the property browser.

Create a Iile System Web site
Create a new lile System \eb site named CustomControl with the
Deault.aspx page.
1. Start Visual Studio 2005.
2. Select New \eb Site on the lile menu.
3. 1he New \eb Site dialog box appears.
4. In Visual Studio installed templates select ASP.NL1 \eb Site.
5. In Location box select lile System and type the \eb site name
C:`asp2`CustomControl.
6. In Language box select Visual C4.
Chapter J3 Custom Controls I
27J
. Click OK.
Visual Studio creates the ile system web site with the Deault.aspx page.
By deault Visual Studio creates another page, Deault.aspx.cs with code
separation.



Create the App_Code folder
\ou create the App_code older to hold the code or the custom control.
1his allows you to test the working o your custom control without pre-
compiling.
1. In Solution Lxplorer right click the \eb site.
2. Select Add lolder.

Select App_Code lolder

1his creates an App_Code directory directly under the root directory o
your \eb site.


272

Use the App_Code directory to test controls without Pre-
Compilation
\ou use the App_Code directory to test controls without Pre-
Compilation. 1his ASP.NL1 dynamic compilation eature, a new eature
in ASP.NL1 2.0 allows you to test your control in a page without pre-
compiling the control into an assembly. ASP.NL1 dynamically compiles
code placed in the App_Code directory under an ASP.NL1 \eb site's
root. Classes in source iles in the App_Code directory are accessed rom
\eb pages without being irst pre-compiled into assemblies. I you place
the source iles or your controls or classes in the App_Code directory,
changes that you make to the controls' code are immediately relected in
pages that use the controls. Ater you`e tested your control to be working
properly you can compile your control into an assembly or deployment.
Using the App_Code directory or deeloping and testing control is
optional. \ou can build your control without using the App_Code
directory in the same way as in earlier ersions o ASP.NL1, and test the
control in your \eb page
Note 1he dynamic compilation eature made aailable by the App_Code
directory is a new eature in ASP.NL1 2.0.

Create the file to hold the code for the custom control
Ater you`e created the App_Code older you add a ile named
CustomLabel.cs to hold the code or the custom control you`ll be
building.
Chapter J3 Custom Controls I
273




Add the code to the CustomLabel.cs file
Add the code to the CustomLabel.cs ile so it looks like the ollowing.
CustomLabel.cs`
// CustomLabel.cs
using System;
using System.ComponentModel;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace John.AspNet.CS.Controls
{
public class CustomLabel : WebControl
{
public virtual string Text
{
get
{
string str = (string)ViewState["Text"];
return (str == null) ? String.Empty : str;

274
}
set
{
ViewState["Text"] = value;
}
}

protected override void RenderContents(HtmlTextWriter
writer)
{
writer.WriteEncodedText(Text);
Style textStyle = new Style();
writer.Write("!");
string str2 = "This is a custom control";
string[] arr = str2.Split(new Char[] { ' ' });
textStyle.ForeColor = System.Drawing.Color.Brown;
textStyle.BackColor = System.Drawing.Color.White;
int i = 12;
foreach (string s in arr)
{
if (s.Trim() != "")
{
writer.WriteBreak();
textStyle.Font.Size = FontUnit.Point(i);
writer.EnterStyle(textStyle);
writer.Write(s);
}
i = i + 4;
}
}
}
}

1he WebControl class
1he custom control, the CustomLabel class you`e just coded, deries
rom the \ebControl class. 1he ull name or the \ebControl class is
System.\eb.UI.\ebControls.\ebControl.
public class CustomLabel : WebControl
I your custom control renders a user interace element or any other
isible element in the client browser, as in this example, you derie your
control rom the \ebControl class or its deried class. I your custom
control renders an element that is not isible in the client browser, such as
a hidden element or a meta tag, you derie your control rom
System.\eb.UI.Control. 1he \ebControl class deries rom
System.\eb.UI.Control and adds style-related properties such as lont,
loreColor, and BackColor. In addition, a control that deries rom the
\ebControl class participates in the skins and themes eatures o
ASP.NL1 without any extra work on your part.
Custom control derives from an existing control
\ou can build your custom control that deries rom an existing control,
such as Button, Label, or Image. loweer in this example you build your
Chapter J3 Custom Controls I
27S
custom control that deries rom the \ebControl class, not rom any o
the existing control such as Button, Label, or Image.

1he RenderContents method
\our custom control oerrides the inherited RenderContents method o
the \ebControl class to render the contents o the control to writer, an
object o the ltml1ext\riter class. 1he ltml1ext\riter class is a utility
class that has methods or rendering tags and other l1ML ,and l1ML
ariant, markup.
protected override void RenderContents(HtmlTextWriter
writer)
In general, when your custom control deries rom the \ebControl class
and renders a single tag, you should oerride the inherited
RenderContents method but not the inherited Render method o the
\ebControl class to render the content within the control's tags. I your
custom control oerrides the inherited Render method to write contents,
it loses the style-rendering logic that is built into the RenderContents
method o the \ebControl class.

1he Html1extWriter class
\our custom control uses writer, an object o the ltml1ext\riter class to
write a l1ML text on a \eb lorm page using the ormatting capabilities
proided by the ltml1ext\riter class.

1he WriteLncoded1ext method
1he \riteLncoded1ext method o the ltml1ext\riter class is used to
encode and write the text to the \eb page. lor example, when embedded
in a block o text the character and , are encoded as &lt, and &gt, in
the output stream.
writer.WriteEncodedText(Text);
I you hae the ollowing input text stream.
Assume that x > 4
Ater encoding the ollowing output text stream is generated.
Assume that x > 4
1he encoding is to ensure that certain characters such as , and are
displayed properly on a \eb page. \ithout encoding these characters are
treated as speical l1ML characters and not displayed properly on a \eb
page.

276

1he Write method
1he custom control uses the \rite method o the ltml1ext\riter class
to write the text stream to the \eb page.
writer.Write("!");

1he Style class
\our custom control makes many uses o the methods and properties o
the Style class. It sets the BackColor property, the loreColor property and
the lont.Size property o textStyle, an object o the Style class.
Style textStyle = new Style();
textStyle.ForeColor = System.Drawing.Color.Brown;
textStyle.BackColor = System.Drawing.Color.White;

1he LnterStyle method
\our custom control uses the LnterStyle method o the ltml1ext\riter
class to implement the speciied style.
writer.EnterStyle(textStyle);
Note 1he LnterStyle method o the ltml1ext\riter class is a new
eature o .NL1 lramework 2.0.

Design-time attributes of custom control
\ou can add design-time attributes to your custom control to enhance the
deeloper experience when the control is used in a isual design
enironment. 1he design-time attributes applied to a control and its
members are not inoled in the unctioning o the control at run time. In
this example design-time attributes are not added.

Create the Web.config file


Create the \eb.conig ile i such a ile does not already exist in your \eb
site. \ou need to add a tag preix mapping in \eb.conig so that when
you deploy your custom control on a \eb page, ASP.NL1 know where
Chapter J3 Custom Controls I
277
to reerence the control in the John.AspNet.CS.Controls namespace
which contains the control.
namespace John.AspNet.CS.Controls
{
public class CustomLabel : WebControl

Create the \en.conig ile.
1. Right click your \eb site and select Add New Item.
2. In the Add New Item window select \eb Coniguration lile.

Click.


Ater you`e created the \eb.conig ile it probably looks something
like the ollowing.
\eb.conig` beore
<?xml version="1.0"?>
<!--
Note: As an alternative to hand editing this file you
can use the

278
web admin tool to configure settings for your
application. Use
the Website->Asp.Net Configuration option in Visual
Studio.
A full list of settings and comments can be found in
machine.config.comments usually located in
\Windows\Microsoft.Net\Framework\v2.x\Config
-->
<configuration
xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0
">
<appSettings/>
<connectionStrings/>
<system.web>
<!--
Set compilation debug="true" to insert
debugging
symbols into the compiled page. Because this
affects performance, set this value to true
only
during development.
-->
<compilation debug="false"/>
<!--
The <authentication> section enables
configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<authentication mode="Windows"/>
<!--
The <customErrors> section enables
configuration
of what to do if/when an unhandled error
occurs
during the execution of a request.
Specifically,
it enables developers to configure html error
pages
to be displayed in place of a error stack
trace.

<customErrors mode="RemoteOnly"
defaultRedirect="GenericErrorPage.htm">
<error statusCode="403"
redirect="NoAccess.htm"/>
<error statusCode="404"
redirect="FileNotFound.htm"/>
</customErrors>
-->
</system.web>
</configuration>

Chapter J3 Custom Controls I


279
I this is the irst time you are creating a \eb.conig ile, replace the
content o the \eb.conig ile you`e just created by the ollowing code
and sae the ile. 1he \eb.conig ile looks like this.
\eb.conig` ater
<?xml version="1.0"?>
<configuration>
<system.web>
<pages>
<controls>
<add tagPrefix="aspSample"
namespace="John.AspNet.CS.Controls"></add>
</controls>
</pages>
</system.web>
</configuration>

1he ollowing tag preix entry maps the tag preix "aspSample" to the
namespace, John.AspNet.CS.Controls.
<add tagPrefix="aspSample"
namespace="John.AspNet.CS.Controls"></add>

Alternatiely you can incorporate the ollowing tags to the \eb.conig


ile. Make sure that the tag preix aspSample` is a child o the
controls section, which in turn must be a child element o the
pages section, which in turn must be a child element o the
system.web section.
<pages>
<controls>
<add tagPrefix="aspSample"
namespace="John.AspNet.CS.Controls"></add>
</controls>
</pages>

Note A coniguration entry or the tag preix is a new eature o


ASP.NL1 2.0. In preious ersions o ASP.NL1 the tag preix mapping
is speciied in the Register directie in each \eb page that uses the
custom control.
In this example i you chose not to speciy the tag preix in the
\eb.conig ile, then you must add a Register directie on each page that
uses the custom control, as in preious ersions o ASP.NL1, as ollows.
<%@ Register TagPrefix="aspSample" Namespace="
John.AspNet.CS.Controls "%>
I you are amiliar with the Register attribute in earlier ersions o
ASP.NL1, notice that the assembly attribute that speciies the name o

280
the control assembly is missing. \hen the assembly attribute is missing,
ASP.NL1 iners that the assembly is dynamically compiled rom source
iles in the App_Code directory. Recall that the dynamical compile eature
o the App_Code directory is not aailable in earlier ersions o
ASP.NL1.
As an alternatie to using the Register directie in each .aspx page, the
application deeloper can speciy the tag preix,namespace mapping in
the \eb.conig ile. 1his is useul i the custom control will be used in
multiple pages in a \eb application. 1he ollowing procedure describes
how to speciy the tag preix mapping in \eb.conig.

Use the custom control in the Default.aspx page
Ater you`e speciied the tag preix mapping in the \eb.conig ile, you
can use the CustomLabel control declaratiely ,as
aspSample:CustomLabel ... ,, in any page in the \eb site. In this
example you will use your custom control in the Deault.aspx page.
\hen you irst created the \eb site the Deault.aspx is generated and
looks like this.
Deault.aspx` beore change
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>

</div>
</form>
</body>
</html>

Add the ollowing code in the di section o the Dealut.aspx page and
sae the page.
Chapter J3 Custom Controls I
28J
<aspSample:CustomLabel Text="Hello" ID="CustomLabel2"
runat="server" BackColor="Wheat" />

1he Deault.aspx page ater you`e added the preceding code should look
like this.
Deault.aspx` ater change
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<aspSample:CustomLabel Text="Hello"
ID="CustomLabel2"
runat="server" BackColor="Wheat" />
</div>
</form>
</body>
</html>


Run the page

1. Righ click the Deault.aspx page in Solution Lxplorer.
2. Select View in Browser.


282



1his concludes Chapter 13.


336
Chapter 1 Component
Programming
.
Build and Use a Component in a Web page (done)
Visual Studio allows you to easily create components, such as class iles,
without compiling them into DLL iles beore deploying them in a \eb
page.
I you hae existing assemblies ,.dll iles,, you can add them to your \eb
site as well and they are automatically reerenced by the site.
In this example you
1. Create a component, a C4 class ile.
2. Use the App_Code directory in an ASP.NL1 \eb site to test
your class without pre-compilation.
3. Compile the control into an assembly ,DLL iles,.
4. Add the DLL ile to your \eb site and hae Visual Studio
reerence it automatically.
5. Use the DLL ile in a \eb page.
\ou don`t need Visual Studio to deelop components but Visual Studio
simpliies the process. \ou can create components using any text editor
and build them rom the command line using the compilers that ship with
.NL1 lramework SDK.
Create a file system Web site
8. Start Visual Studio 2005.
9. Select New \eb Site on the lile menu.
10. 1he New \eb Site dialog box appears.
11. In Visual Studio installed templates select ASP.NL1 \eb Site.
12. In Location box select lile System and type the \eb site name
C:`asp2`Component.
13. In Language box select Visual C4.
14. Click OK.
Chapter J7 Component Programming
337
Visual Studio creates the ile system web site with the Deault.aspx page.
By deault Visual Studio creates another page, Deault.aspx.cs with code
separation.


Create a file for the component
1. Right click the name o the \eb site in Solution Lxplorer and
select Add lolder , App_Code lolder.
1he App_Code older is created.


2. Right click the App_Code older in Solution Lxplorer and select
Add New Item.
3. Select Class in Visual Studio installed templates.
4. 1ype Conert.cs in the Name box as the name o the component
ile.
5. Select Visual C4 in the Language list box.
6. Click Add.
1he new component ile Conert.cs is created in the App_Code older
and open in the editor.

338


Create the component

1. In the Conert.cs ile you`e just created, add a namespace and
two methods or the Conert class so that the Conert.cs ile
looks like this:
Convert.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for Convert
/// </summary>
///
namespace John.AspNet.CS.Dll
{
public class Convert
{
public Convert()
{
//
// TODO: Add constructor logic here
//
}
Chapter J7 Component Programming
339
public double FToC(double Fahrenheit)
{
return ((Fahrenheit - 32) * 5) / 9;
}

public double CToF(double Celsius)
{
return ((Celsius * 9) / 5) + 32;
}

}
}


2. Sae the Conert.cs ile. \ou don`t hae to compile the
Conert.cs ile
1he App_Code folder
\ou can create reusable components by keeping them in the App_Code
older. Visual Studio monitors the App_Code older and when new
components are added, compiles them. 1he components in the
App_Code older are compiled by deault into a single assembly. 1he
assembly is then automatically reerenced in the project and aailable to all
pages in the site.
\ou should put only components into the App_Code older. Don`t put
pages, controls, or other non-code iles containing non-code elements into
the older.
Use the component

Next you`ll use the component in an ASP.NL1 page.
3. In Solution Lxplorer, open the Deault.aspx page in Design iew.
4. lrom the Standard group o the 1oolbox, add the ollowing
controls and texts to the Deault.aspx page and set their
properties as indicated.

Control Properties
1extbox ID: 1emp1extbox
1ext: ,empty,
Button ID: ConertButton
1ext: Calculate
Label ID: l1oCLabel

340
1ext: ,empty,
Label ID: C1olLabel
1ext: ,empty,

1he Deault.aspx page in Design iew looks like this:


1he Deault.aspx page in Source iew looks like this:
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<strong><span style="font-size: 14pt">Convert
Temperature<br />
</span></strong>
<br />
Temperature&nbsp;
<asp:TextBox ID="TempTextbox"
runat="server"></asp:TextBox>&nbsp;<asp:Button
ID="ConvertButton"
runat="server" OnClick="ConvertButton_Click"
Text="Convert" /><br />
Chapter J7 Component Programming
34J
<br />
Fahrenheit&nbsp; to&nbsp; Celsius: &nbsp;
<asp:Label ID="FToCLabel"
runat="server"></asp:Label><br />
<br />
Celsius&nbsp; to&nbsp; Fahrenheit: &nbsp;
<asp:Label ID="CToFLabel"
runat="server"></asp:Label>

</div>
</form>
</body>
</html>

Code the Button click event handler
1. \ith the Deault.aspx page in Design iew, double click the
Button control. 1his creates a Click eent handler in the
Deault.aspx.cs ile.
2. Add the ollowing code to the Click eent handler so that the
Deault.aspx.cs ile looks like this:
Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void ConvertButton_Click(object sender,
EventArgs e)
{
John.AspNet.CS.Dll.Convert
c = new John.AspNet.CS.Dll.Convert();
double t =
System.Convert.ToDouble(TempTextbox.Text);
FToCLabel.Text = c.FToC(t).ToString("0.0");
CToFLabel.Text = c.CToF(t).ToString("0.0");
}

}

342

1est the Web page and the component
1. Right click Deault.aspx in Solution Lxplorer and select View in
Browser.
2. \hen the Deault.aspx page appears in the browser, type some
numbers in the textbox and click the Conert button.



\hen you use the component this way in a \eb page there is no DLL or
other executable code anywhere under the root o your \eb site. Instead,
Visual Studio has compiled the page and the component dynamically.

Compile the Component into an Assembly
\ith the component in the App_Code older you can run the \eb page
without pre-compiling the component. \ou may compile the component
into an assembly so that you can package it or deployment or
distribution, and this is what you`ll do next in this example, using the C4
compiler csc that is included with .NL1 lramework.
1. Copy the Conert.cs ile to a dierent older and run the
ollowing command rom Command Prompt to inoke the C4
compiler csc:
csc /t:library /out:John.AspNet.CS.Dll.dll /r:System.dll
*.cs

2. 1o access the C4 compiler csc rom the command line the
\indows enironment PA1l ariable o your computer must
Chapter J7 Component Programming
343
include the path to your .NL1 lramework installation. I you
cannot execute the compiler command, add the .NL1
lramework installation path to the PA1l ariable beore running
the command. 1o add the .NL1 lramework installation path
right-click My Computer, select Properties, click the Adanced
tab, and click the Lnironment Variables button. In the System
Variables list, double-click the PA1l ariable. In the Variable
alue text box, add a semicolon ,,, to the end o the existing
alues in the text box, and then type in the path o your .NL1
lramework installation. 1he .NL1 lramework is generally
installed in the \indows installation directory at
`Microsot.NL1`lramework`ersionNumber.Click OK to close
each dialog box.

C4 compiler csc
In this example the ollowing C4 compiler options are speciied:
1. 1he ,t:library ,t or target, option tells the compiler to create a
dynamic-link library ,DLL, rather than an executable ile ,LXL,.
2. 1he ,out option proides a name or the DLL ile to be created
by the C4 compiler.
3. 1he ,r ,r or reerence, option imports the speciied assemblies
that are to be linked to your assembly. \ou can import one or
more iles be linked. 1o import more than one ile, separate ile
names with either a comma or a semicolon.
1he ollowing screen shot illustrates one way o compiling the Conert.cs
ile into the John.AspNet.CS.Dll.dll ile in the older where the C4
compiler resides. It is not recommended you compile your assemblies this
way in a routine manner.

344


Make your component accessible to the Web site
1o use the component you must make your component ,the DLL ile,
accessible to pages in the \eb site.
1. In Solution Lxplorer right click the \eb site and select Add
lolder, and then select Bin lolder. 1his creates a Bin older
under the root o the \eb site.
2. Copy the John.AspNet.CS.Dll.dll ile to the \eb site's Bin older.
3. Delete the Conert.cs ile rom the App_Code older. I you
don`t delete the Conert.cs ile the Conert class exists in two
places, one copy in the Conert.cs ile and one copy in the
John.AspNet.CS.Dll.dll ile. 1his creates an ambiguous reerence
when using the Conert class in a page which will generate a
compiler error.

Chapter J7 Component Programming


34S
1est the Web page and the component again
\ou`ll now test the \eb page and the component again, this time with the
component as a DLL ile in the Bin older under the root o your \eb
site.
1. Right click Deault.aspx in Solution Lxplorer and select View in
Browser.
2. \hen the Deault.aspx page appears in the browser, type some
numbers in the textbox and click the Conert button.


1his concludes Chapter 1.

You might also like