You are on page 1of 22

CSCE 547

Windows Programming

User Controls
Department of Computer Science and Engineering
University of South Carolina
Columbia, SC 29208
User Controls
We have seen that the .NET FCL contains 28 Web Controls, 21
HTML Controls, and 6 Validation Controls, all of which can be used
in Web Forms.

Besides those controls, .NET provides two mechanisms to create


ASP.NET components: User Controls and Custom Controls.
Controls

With User Controls, developers can:

1.Organize UI elements and convert them into reusable


components
2.Create dynamic pages, personalized for individual users
3.Perform output caching at the sub-page level (cache a page’s
static content while allowing other parts of the page to be
rendered dynamically).

CSCE 547 Fall 2002 Ch 07 - 2


User Controls
User controls are contained in .ascx files.

UseHello.aspx File
<%@ Register TagPrefix="user
user"
TagName="Hello
Hello" src="Hello.ascx
Hello.ascx" %>
<html> Hello.ascx File
<body>
<form runat="server"> <h1>Hello, world</h>
<user:Hello RunAt="server" />
</form>
</body>
</html>

Naturally, you would want to do more than simply displaying a


greeting message in a user control. Nonetheless observe:

Register directive, TagPrefix, TagName, src.

CSCE 547 Fall 2002 Ch 07 - 3


@ Directives in a User Control
While .aspx files sometimes contain the @Page directive, user controls would
contain instead the @Control directive, e.g.,
<%@Control Debug="true" %>
<%@Control Debug="true" Language="C#" %>
User controls can also contain @Import and @Assembly to incorporate non-
default name spaces and assemblies from .NET
The samples in the text book demonstrate that:
1. User controls can be split into the HTML part and the script part.
2. User controls can have properties
3. User controls can have events. To take full advantage of this feature user
controls mustuse the features derived from the base class UserControl, and the
control must define events, event delegates, and classes to pass event
arguments, or use the ones from the base class
4. User controls and can be written using code behind scripting (i.e., having the
script portion contained in .dll files).

CSCE 547 Fall 2002 Ch 07 - 4


LoginControl 1
<%@ Register TagPrefix="user"
TagName="LoginControl"
src="LoginControl1.ascx" %>
<html>
<body>
<h1>User Control Demo 1</h1>
<hr>
<form runat="server">
<user:LoginControl RunAt="server" />
</form> <table cellpadding="4">
<hr> <tr>
</body> <td>User Name:</td>
</html> <td><asp:TextBox ID="MyUserName" RunAt="server" /></td>
</tr>
<tr>
<td>Password:</td>
<td><asp:TextBox ID="MyPassword" TextMode="password"
RunAt="server" /></td>
</tr>
<tr>
<td></td>
<td><asp:LinkButton Text="Log In" RunAt="server" /></td>
</tr>
</table>

CSCE 547 Fall 2002 Ch 07 - 5


LoginControl2: Adding Properties
<table id="MyTable" cellpadding="4" runat="server">
<tr> Note that this
<td>User Name:</td>
<td><asp:TextBox ID="MyUserName" RunAt="server" /></td>
slide shows
</tr> only the HTML
<tr> and the script
<td>Password:</td>
<td><asp:TextBox ID="MyPassword" TextMode="password" parts of the
RunAt="server" /></td> control, both
</tr>
<tr> contained in the
<td></td> .ascx file
<td><asp:LinkButton Text="Log In" RunAt="server" /></td>
</tr> <script language="C#" runat="server">
</table> public string BackColor {
get { return MyTable.BgColor; }
set { MyTable.BgColor = value; }
}
The next slide shows public string UserName {
a .aspx file that uses get { return MyUserName.Text; }
set { MyUserName.Text = value; }
the control and access }
its properties public string Password {
get { return MyPassword.Text; }
set { MyPassword.Text = value; }
}
CSCE 547 Fall 2002 Ch 07 - 6
LoginPage2: Using the control with properties
<%@ Register TagPrefix="user"
TagName="LoginControl"
src="LoginControl2.ascx" %>
<html>
<body>
<h1>User Control Demo 2</h1>
<hr>
<form runat="server">
<user:LoginControl ID="MyLogin"
BackColor="#ccccff“ RunAt="server" />
</form>
<hr>
<h3><asp:Label ID="Output" RunAt="server" /></h3> </body>
</html>
<script language="C#" runat="server">
void Page_Load (Object sender, EventArgs e)
{
if (IsPostBack)
Output.Text = "Hello, " + MyLogin.UserName;
}
</script>

See Figure 7-6 in pp. 325 for output


CSCE 547 Fall 2002 Ch 07 - 7
LoginControl3: Adding Events
<table id="MyTable" cellpadding="4" runat="server">
<tr>
<td>User Name:</td>
<td><asp:TextBox ID="MyUserName" RunAt="server" /></td>
</tr>
<tr>
<td>Password:</td>
<td><asp:TextBox ID="MyPassword" TextMode="password"
RunAt="server"
<script language="C#"
/></td> runat="server">
</tr> public string BackColor {
<tr> get { return MyTable.BgColor; }
<td></td> set { MyTable.BgColor = value; }
<td><asp:LinkButton Text="Log In"
}
OnClick="OnLoginButtonClicked" RunAt="server" /></td>
</tr> public string UserName {
</table> get { return MyUserName.Text; }
set { MyUserName.Text = value; }
}
public string Password {
get { return MyPassword.Text; }
set { MyPassword.Text = value; }
}
public event EventHandler Login;
void OnLoginButtonClicked (Object sender, EventArgs e) {
if (Login != null && UserName.Length > 0 && Password.Length > 0)
Login (this, new EventArgs ()); // Fire Login event
}
</script>
CSCE 547 Fall 2002 Ch 07 - 8
Page that uses Control with events
<%@ Register TagPrefix="user"
TagName="LoginControl"
src="LoginControl3.ascx" %>
<html>
<body>
<h1>User Control Demo 3</h1>
<hr>
<form runat="server">
<user:LoginControl ID="MyLogin" BackColor="#ccccff"
OnLogin="OnLoginUser" RunAt="server" />
</form>
<hr>
<h3><asp:Label ID="Output" RunAt="server" /></h3>
</body>
</html>
<script language="C#" runat="server">
void OnLoginUser (Object sender, EventArgs e)
{
Output.Text = "Hello, " + MyLogin.UserName;
}
</script>

CSCE 547 Fall 2002 Ch 07 - 9


Code Behind in ASCX Controls
User controls can be organized around code-behind architecture, which is
packaged as .DLL files. The text book shows how this is done via
LoginControl4.

This control uses two classes: LoginEventArgs and LoginBase, both written
into a .cs file (figure 7-9).

The two classes are compiled with the command:

csc /t:library LoginBase.cs

To produce the file LoginBase.dll.

In this sample the code explicitly derives the script portion of the control from
UserControl.

Note that ASP.NET does that in the previous samples, when the script code of
the control is compiled, ASP.NET derives an object from the base class
UserControl.

CSCE 547 Fall 2002 Ch 07 - 10


LoginControl4.ascx
<%@ Control Inherits="LoginBase" %>

<table id="MyTable" cellpadding="4" runat="server">


<tr>
<td>User Name:</td>
<td><asp:TextBox ID="MyUserName" RunAt="server" /></td>
</tr>
<tr>
<td>Password:</td>
<td><asp:TextBox ID="MyPassword" TextMode="password"
RunAt="server" /></td>
</tr>
<tr>
<td></td>
<td><asp:LinkButton Text="Log In“
OnClick="OnLoginButtonClicked"
RunAt="server" /></td>
</tr>
</table>

CSCE 547 Fall 2002 Ch 07 - 11


public class LoginEventArgs {
private bool LoginValid;
LoginBase.cs
public LoginEventArgs (bool IsValid) {
LoginValid = IsValid; System.Object
}
public bool IsValid { System.Web.UI.Control
get { return LoginValid; } Sytem.Web.UI.TemplateControl
}
} System.Web.UI.UserControl
public class LoginBase : UserControl { public class UserControl : TemplateControl, IAttributeAccessor
protected HtmlTable MyTable;
protected TextBox MyUserName;
protected TextBox MyPassword;
public string BackColor {
get { return MyTable.BgColor; }
set { MyTable.BgColor = value; }
}
public string UserName {
get { return MyUserName.Text; }
set { MyUserName.Text = value; } EventDelegate
}
public string Password {
get { return MyPassword.Text; }
set { MyPassword.Text = value; } Event name
}
public delegate void LoginEventHandler (Object sender,
LoginEventArgs e);
public event LoginEventHandler Login;
public void OnLoginButtonClicked (Object sender, EventArgs e)
{
if (Login != null) {
bool IsValid = (UserName.ToLower () == "jeffpro" &&
Password == "imbatman");
Login (this, new LoginEventArgs (IsValid));
}
}
}

CSCE 547 Fall 2002 Ch 07 - 12


LoginPage4.aspx
<%@ Register TagPrefix="user"
TagName="LoginControl"
src="LoginControl4.ascx" %>
<html>
<body>
<h1>User Control Demo 4</h1>
<hr>
<form runat="server">
<user:LoginControl ID="MyLogin" BackColor="#ccccff"
OnLogin="OnLoginUser" RunAt="server" />
</form>
<hr>
<h3><asp:Label ID="Output" RunAt="server" /></h3>
</body>
</html>
<script language="C#" runat="server">
void OnLoginUser (Object sender, LoginEventArgs e)
{
if (e.IsValid)
Output.Text = "Hello, " + MyLogin.UserName;
else {
Output.Text = "Invalid login";
MyLogin.UserName = "";
MyLogin.Password = "";
}
}
</script>

CSCE 547 Fall 2002 Ch 07 - 13


Xml Navigation Bar
The application named XmlNavBar demonstrates a more
sophisticated control, shown in figure 7-11, pp. 331.

The control has a Title and a navigation bar that appears on the
left side.

When users select from the choices in the left bar, the content
is displayed on the main portion of the control, to the right
side.

Note that all that is needed to use this control is an XML file
that contains the titles and the paths to the selection, as shown
in file Links.xml, figure 7-13.

CSCE 547 Fall 2002 Ch 07 - 14


Links.XML
<?xml version="1.0">
<Items>
<Item>
<Text>News</Text>
<Link>News.aspx</Link>
</Item>
<Item>
<Text>Sports</Text>
<Link>Sports.aspx</Link>
</Item>
<Item>
<Text>Stocks</Text>
<Link>Stocks.aspx</Link>
</Item>
<Item>
<Text>Weather</Text>
<Link>Weather.aspx</Link>
</Item>
</Items>

CSCE 547 Fall 2002 Ch 07 - 15


News.ASPX
<%@ Register TagPrefix="user"
TagName="XmlNavBar"
Src="XmlNavBar.ascx" %>
<html>
<body>
<form runat="server">
<table width="100%" height="100%">
<tr height="48">
<td bgcolor="teal" align="center" colspan="2">
<span style="color: white; font-family: verdana;
font-size: 24pt; font-weight: bold">
News
</span>
</td>
</tr>
<tr>
<td width="128" valign="top" bgcolor="royalblue">
<user:XmlNavBar XmlSrc="Links.xml" ForeColor="white"
Font-Name="verdana" Font-Size="10pt" Font-Bold="true"
MouseOverColor="black" RunAt="server" />
</td>
<td align="center" valign="center">
No news is good news
</td>
</tr>
</table>
</form>
</body>
</html>

CSCE 547 Fall 2002 Ch 07 - 16


XmlNavBar.ascx
The code contains only one html line:

<asp:Table ID="MyTable" RunAt="server" />

Everything else is script code that is used to create <a ref… >
tag elements:
<a href="News.aspx"
onmouseover="defcolor=this.style.color;
this.style.color='Black'"
onmouseout="this.style.color=defcolor" Properties of the tag
style="text-decoration: none;
font-family: verdana; font-size: 10pt;
font-weight: bold; color: White“
>
News
</a>

Note that the control has properties (XmlSrc, BackColor, ForeColor,


MouseOverColor, Font) a PageLoad method, and a FontInfo class
which is used to abstract out the details about the font.

CSCE 547 Fall 2002 Ch 07 - 17


Dynamic Loading
User controls can also be created programmatically, this is known as
dynamic loading.
loading
The Page Class contains a method called LoadControl, which can
load the control at run time:
Control navbar = LoadControl ("XmlNavBar.ascx");
Controls.Add (navbar);

In order to access the properties and events specifically defined for


the control, the object being loaded must be cast to the type into
which the ASP.NET compiled the script part of the control:
XmlNavBar_ascx navbar = (XmlNavBar_ascx) LoadControl("XmlNavBar.ascx");
// Now the events and properties of the control are visible.
navbar.XmlSrc = "Links.xml"; // It works!

The name of the class is selected by ASP.NET when the new class is
compiled. Alternatively, it can be specified as:
<%@Control ClassName = “XmlNavBarControl” %>
// Name must match in the <%@Register directive>

CSCE 547 Fall 2002 Ch 07 - 18


Cookies
Dynamic loading is convenient because it provides mechanisms to
personalize user preferences.

Cookies are another method to maintain user preferences.

Cookies are attribute=value pairs that are use to define user/browser


specific preferences.

Cookies are part of the HTTP headers transmitted during the


client/server communication.

The types of Cookies can be Session Cookies or Permanent Cookies.


This is defined by the existence or omission of expires= attribute.

ASP.NET uses cookies for:

1. Associate returning visitors to sessions stored in the web server.


2. Identify users who were validated via forms authentication

CSCE 547 Fall 2002 Ch 07 - 19


Cookies and ASP.NET
Cookies are defined in .NET as a class:

HttpCookie cookie = new HttpCookie (“


(“DefaultColor
DefaultColor",
", "Blue");

This class contains public properties named Domain, Path,


Expires, and Secure, which can be used to shape the cookie.

Cookies can be returned to the browser using the ASP.NET


response object:

HttpCookie cookie = new HttpCookie ("FavoriteColor", "Blue");


Response.Cookies.Add (cookie);

A cookie’s properties can be examined:

HttpCookie cookie = Request.Cookies[“DefaultColor"];


if (cookie != null) { string FavoriteColor = cookie.Value; . . . }

CSCE 547 Fall 2002 Ch 07 - 20


MyQuotes Sample
The text book summarizes all you want to know about cookies in
the sample MyQuotes, which is discussed in pps. 344-349.

MyQuotes.aspx contains a check box labeled “Show quotes.”


Checking the box dynamically loads the user control defined in
MyQuotes.ascx and adds it to the page.

MyQuotes.ascx goes out on the Web, fetches the most recent


quotes, and displays them in a DataGrid.

Refreshing the page refreshes the stock prices as well.

This example is very interesting because it also illustrates the use


of a web service (www.xmethods.com) and message exchange
through SOAP

CSCE 547 Fall 2002 Ch 07 - 21


Sub Page Caching
ASP.NET can be instructed to save in cache a page for a certain
period, using the <%@ OutputCache > directive.

The problem with this approach is that the entire page is


cached, and sometimes it is better to store in cache only a
portion of the page.

To optimize performance, the trick is to identify which portions


of the page are dynamic and which portions are static; the
static content is kept longer while the dynamic content can be
loaded as needed, saving cache space.

The OutputCache directive can be manipulated to optionally


maintain in cache certain files (controls) or even have the same
control (but called by different users) cashed.

CSCE 547 Fall 2002 Ch 07 - 22

You might also like