Documente Academic
Documente Profesional
Documente Cultură
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
13
Server-Side Programs
and Postback Operations
CHAPTER
13
In this chapter, you will
• Separate user-interface resources from business logic
• Use and edit Response, Request, Session, Server, and
Application objects
• Retrieve values from the properties of intrinsic objects
• Set values on the properties of intrinsic objects
• Use intrinsic objects to perform operations
• Instantiate and invoke a Web Service
• Instantiate and invoke a COM or COM+ component
• Instantiate and invoke a .NET component
• Call native functions by using platform invoke
• Manage data during postback events
Using server-side programming allows us to separate the business logic from the presen-
tation services and makes it possible to create reusable objects. As you will remember
from Chapter 10, the Presentation Service is responsible for displaying the information,
while the Business Service handles the “logic”, the rules for how the data that is stored in
the Data Service will be used. In this chapter, we will look at the objects in the
ASP.NET object model and at how you can manipulate that model through Visual Stu-
dio .NET. We will then look at the Web Services and how to use them, as well as the
COM technology.
One compelling reason for locating business logic in a separate service layer is
scalability. Scalability is the ability of a software package to be used by increasing num-
bers of users simultaneously, simply by adding more hardware to the application rather
than rewriting the software. The major factor that limits the number of concurrent cli-
ents that can access a common application is the hardware and the network that makes
the service available to the clients. The decision to place a particular process in the mid-
dle tier (the business layer) is based on whether the process is of general use in the appli-
cation and whether it is frequently changed.
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:06 AM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
13
ASP.NET Namespaces
The namespaces that are mostly used with ASP.NET development are listed in Table
13-1, along with a brief description of each. The number of namespaces in the .NET
Framework is large, and this table lists but a small fraction of all the namespaces. You
will need to import additional namespaces for other functionality that you require in
the application.
We will focus our efforts in this chapter on the System.Web and System.Web.UI
namespaces, and the objects those namespaces provide for our support.
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:07 AM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
13
PART III
System.Data This namespace will give us data access. It and the classes it
provides are so important that we will spend all of Chapter 16
on them.
System.Globalization When we want to build web applications that are localized based
on the language and culture of the user, we need the
System.Globalization namespace.
System.XML Last but not least, the XML support for .NET is in this
namespace where a lot of very interesting XML support
classes are located.
Table 13-1 The Basic Namespaces Used with ASP.NET
The Page class provides the framework for all web pages that will be constructed on
the server—all web pages will inherit from the Page class indirectly through other ab-
stractions. The processing of the web page on the IIS server actually creates an object
representing our web page that indirectly inherits from the Page class.
The following events happen when a client requests your ASP.NET page from the IIS
server:
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:07 AM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
13
Description
Application Holds a reference to the Application object for the current web
request.
ClientTarget Gets or sets a value that allows you to override automatic detection of
browser capabilities. This property can be used to specify how a page
renders for particular browser clients.
EnableViewState Gets or sets a value indicating whether the page maintains its view
state, and the view state of any server controls it contains, when the
current page request ends.
ErrorPage Gets or sets the error page to which the requesting browser is
redirected in the event of an unhandled page exception.
IsPostBack Gets a value indicating whether the page is being loaded in response to
a client postback, or if it is being loaded and accessed for the first time.
Postback refers to the operation of sending form data from the client
to the server.
IsValid Gets a value indicating whether page validation succeeded.
Page Holds a reference to the Page instance that contains the server
control.
Request Holds a reference to the HttpRequest object for the requested
page.
Response Holds a reference to the HttpResponse object associated with the
Page instance. This object allows you to send HTTP response data to
a client and contains information about that response.
Server Holds a reference to the Server object, which is an instance of the
HttpServerUtility class.
Session Holds a reference to the current Session object provided by
ASP.NET.
Trace Gets the TraceContext object for the current web request.
User Gets information about the user making the page request.
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:07 AM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
13
PART III
child controls.
LoadControl() Obtains a UserControl object from a user
control file.
ToString() Returns a string that represents the current object.
Table 13-3 Public Methods of the Page Class
Description
AbortTransaction Occurs when a user aborts a transaction.
CommitTransaction Occurs when a transaction completes (inherited from
TemplateControl).
DataBinding Occurs when the server control binds to a data
source.
Disposed Occurs when a server control is released from
memory, which is the last stage of the server control
lifecycle when an ASP.NET page is requested.
Error Occurs when an unhandled exception is thrown
(inherited from TemplateControl).
Init Occurs when the server control is initialized, which
is the first step in its lifecycle.
Load Occurs when the server control is loaded into the
Page object.
PreRender Occurs when the server control is about to render
(convert to HTML) for its containing Page object.
Unload Occurs when the server control is unloaded from
memory.
Table 13-4 Public Events of the Page Class
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:07 AM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
13
In the new project, add one Label control (lblNavigate) and set the Text prop-
erty to “Navigate To:”. Also, add a DropDownList control (cmbNavigate) as in
Figure 13-1.
In order to populate the DropDownList control with the URLs that users can navi-
gate to, you need to add some code to the Page_Load() event handler, as listed here:
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:07 AM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
13
PART III
Figure 13-1 The initial layout of the project
To run the application, you press the F5 key. The resulting web page displayed in the
browser should look like Figure 13-2. Use the DropDownList control to see the differ-
ent addresses, and select an address to see what the result is.
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:08 AM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
13
The Response object, as you will recall from Chapter 11, is what gives us access to
the Redirect() method. The Redirect() method tells the browser to open a new
location on the Web.
In order to make the DropDownList control send the request to the server, you need
to set the AutoPostBack attribute of the control to True with code like the following:
Run the application and test the different addresses. The resulting web page will look
the same as in Figure 13-2, but it will now work. When you select a new address in the
DropDownList control, the browser will be redirected to that address.
The Page class also helps when we need to work with a file using a physical path
rather than the virtual path that is used for the web server. For example, the file
ReadMe.txt that is located in the root of the WebNav application has the virtual path
of /WebNav/ReadMe.txt, but depending on the configuration of the web server, the
physical location of the file cannot be gleaned from the virtual path. The MapPath()
method of the Page class will translate the virtual name to the physical path so we can
use file-based IO to read or write to physical drives.
The following example will read in a file called ReadMe.txt that is located in the
root of the WebNav application and send it to the client browser for display. There are
some additional elements to deal with in this example: how to perform file I/O and how
to connect streams from source to sink (consumer) to make the data flow.
To read and write files, we use the System.IO namespace, so we must add that to
our codebehind module first. In order to open and read a file, we need to call some stream
methods that will open the file for us—we need a StreamReader as shown here:
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:08 AM
Color profile: Generic CMYK printer profile
All-In-One
Composite Default screen All-In-One
/ MCAD/MCSD
/ MCSD Visual
Visual
C#C#
.NET
.NET
Certification
Certification
All-in-One
All-in-One
Exam
Exam
Guide
Guide
/ Rempel
/ Rempel
& Lind
& Lind
/ 222443-6
/ 222443-6
/ Chapter
/ Chapter
13
13
…
using System.IO;
namespace ReadWeb
{
public class WebForm1 : System.Web.UI.Page
{
…
private void cmdClick_Click(object sender, System.EventArgs e)
{
StreamReader sr = new StreamReader(MapPath("ReadMe.txt"));
PART III
string nextLine;
while ((nextLine = sr.ReadLine()) != null)
{
lstBox.Items.Add(nextLine);
}
sr.Close();
}
}
}
When you run this program by pressing F5 you will be presented with a web page that
has a listbox control containing all the lines from the ReadMe.txt file.
EXAM TIP It is imperative that you know the five ASP.NET objects:
Request, Response, Session, Application, and Server, and
what they do.
We are now ready to start working with the objects exposed by the Page class. First,
however, we are going to look at how to manage application and session state.
State Management
The issue of keeping state—remembering the user’s data between visits to the site—is
one of resources. The information consumes some resource, such as memory, disk
space, or even network bandwidth, either on the server, network, or client computer.
The decision to keep state must be an informed decision, not lightly taken. There must
be some benefit for the client and for you in order to spend resources on remembering
the user’s information.
We dealt with the mechanics of keeping state in Chapter 11, so we will only touch on
the issue of state here.
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:09 AM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
13
EXAM TIP Any information that is needed throughout the entire application
and that is not client specific is a candidate to be stored in the application
object.
Session State
Session state is client specific and contains information that is used during one connec-
tion (session) between the client and the web application. Session state is were you
would keep the user’s shopping cart, as well as the login information the user supplied
upon initially connecting to the site.
We will begin our look at session state with cookies and their usefulness.
Cookies The cookie is a small file that the web server stores on the client’s com-
puter in a directory defined by the browser’s configuration. The cookie is used to store
client-side session state. You would use cookies to hold much the same type of infor-
mation you would use session variables (stored in the Session object on the web
server) for:
• User preferences This allows you to give the user the “warm and fuzzy”
feeling of a custom experience.
• User recognition Once users sign in, the cookie lets the application
remember them so the users don’t have to log in every time.
• Window tracking You can keep track of pop-up windows so you don’t
pop up the same window all the time.
The process of writing a cookie to a user’s computer starts on the web server when you
add the cookie to the Response object’s Cookies collection. The cookie is sent to the
client’s browser, which stores it on the client’s hard drive. Later, when the client returns
to your web site, the browser will send the cookie back. ASP.NET makes the cookie avail-
able for processing through the Request object.
To look at how cookies work, let’s create an application that uses a cookie to remem-
ber what we had selected the last time we were on the site. For this application we will
create a WebCookie application on the localhost. The following illustration shows this
application being created.
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:09 AM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
13
PART III
We need to add a Panel and call it panOut and a RadioButtonList named
rbutList as shown in Figure 13-3. The RadioButtonList is created statically by
adding members to the RadioButtonList.Items collection as can be seen in in the
next illustration.
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:09 AM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
All-In-One
screen / MCAD/MCSD
/ MCSD Visual
Visual
C#C#
.NET
.NET
Certification
Certification
All-in-One
All-in-One
Exam
Exam
Guide
Guide
/ Rempel
/ Rempel
& Lind
& Lind
/ 222443-6
/ 222443-6
/ Chapter
/ Chapter
13
13
The first version of this application needs some code added to the both the HTML
document as well as the codebehind (the C# code module where the functionality of
the web page is defined)module to give it some functionality. The following code seg-
ments must be added to the HTML code for the application to function properly:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:10 AM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
13
namespace WebCookie
{
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Panel panOut;
protected System.Web.UI.WebControls.RadioButtonList rbutList;
PART III
{
rbutList.SelectedIndex = 0;
}
}
…
private void rbutList_SelectedIndexChanged(object sender, System.EventArgs e)
{
switch (rbutList.SelectedItem.Value)
{
case("Blue"):
panOut.BackColor= Color.Blue;
break;
case "Red":
panOut.BackColor = Color.Red;
break;
case "Green":
panOut.BackColor = Color.Green;
break;
default:
panOut.BackColor = Color.White;
break;
}
}
}
}
The following line in the Page_Load() event handler sets the default color for the
Panel.
rbutList.SelectedIndex = 0;
The switch statement in the SelectedIndexChanged() event handler sets the color
according to the selection of the user. Every time the user returns to the page, the color of
the Panel is always set to the initial color white. The resulting application can be seen
in Figure 13-4.
Wouldn’t it be nice if we could remember the user’s color selection? We can
by adding some code to the rbutList_SelectedIndexChanged() and the
Page_Load() event handlers. The following code segments shows that change.
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:10 AM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
13
First we need to write out a cookie to the client when there has been a change in the
color selection:
The addition of the cookie to the Response object’s Cookies collection effectively
sends the cookie to the client. After we run the application, we can look for the cookie in
the cookies directory, which in our case is in the C:\Documents and Settings\<user
name>\Cookies directory (we are using Windows 2000).
The code changes needed to use the cookie are added to the PageLoad() event han-
dler as shown here:
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:10 AM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
13
PART III
}
}
}
We will look at an example that consists of a login form that saves the user’s name
and password in two session variables and then redirects the user to the main page of
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:11 AM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
13
The form shown in Figure 13-5 uses two TextBox controls, two Button controls,
and two Labels that have their properties set as listed in Table 13-5.
We now need to write some code to save the login name and password in session
variables if the user clicks OK, and to clear the text boxes if the user clicks Cancel. The
following two event handlers perform that task:
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:11 AM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
13
PART III
Figure 13-5 The login form for the WebLogin application
To be able to redirect the user to another page, we need first to create a new page.
Name the page WebPage42.aspx and put something unique on the page so you will
know the page when you see it. You can see our web page in Figure 13-6.
Name Text
Label lblLoginName Login Name
Label lblPassword Password
TextBox txtLoginName
TextBox txtPassword
Button BtnOK OK
Button btnCancel Cancel
Table 13-5 Properties for the Controls in the WebLogin Application
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:11 AM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
All-In-One
screen / MCAD/MCSD
/ MCSD Visual
Visual
C#C#
.NET
.NET
Certification
Certification
All-in-One
All-in-One
Exam
Exam
Guide
Guide
/ Rempel
/ Rempel
& Lind
& Lind
/ 222443-6
/ 222443-6
/ Chapter
/ Chapter
13
13
Add the following code to the Page_Load() event handler of the WebPage42.
aspx file so we can see the session variable at work:
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:12 AM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
13
Run the application, and given the input in Figure 13-7, the final result should be as
PART III
shown in Figure 13-8.
Remember to always consider the purpose of the variable when it comes to using ei-
ther cookies or session variables, and you should also try to avoid keeping state if at all
possible. Keeping state and providing scalability are diametrical opposites.
The next section of this chapter will take us into the web services world of ASP.NET,
where you will learn how to use a web service.
Web Services
One of the ASP.NET technologies that has generated lots of interest is web services. In
most industry magazines web services will be referred to as the “greatest thing to happen
to computing.” But what are they? And do you need to know the technology of web ser-
vices to pass the two C# exams?
The answer to the second question is no, you don’t need to understand the technol-
ogy—you need to know how to use the services that a web service performs, but not how
to develop one. The answer to the first question must be tempered by the previous
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:12 AM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
13
The web service will be assembled in a file with the extension .asmx.
The processing directive defines the file as a web service:
The Language attribute indicates the language the web service is written in, while the
Class attribute defines the class that is encapsulated in the web service.
You also need to add the namespace in order to have support for the web service
architecture:
using System.Web.Services;
The name of the public class that is defined in the .asmx file will be the name of the
web service and should be the same as the name defined in the Class attribute in the
processing directive.
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:13 AM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
13
[WebMethod]
public double CtoF(double Celsius)
The WebMethod declaration can take attributes by itself to modify the behavior of the
method.
Let’s build a temperature-conversion web service to convert from degrees Celsius to
degrees Fahrenheit and back. We’ll call the service TemperatureConversion, and
PART III
we will start by building the project on the localhost server, as shown here.
After the project is built, we end up with a view of the project as in Figure 13-9. Be-
cause we are building a web service, there will be no Design view of the project, and as
you notice, the file is named TemperatureConversion.asmx.cs to indicate that it
is a web service.
The text in the middle of the display prompts us to drag objects from the Toolbox or
the Solution Explorer onto the view to add the object to the service. You can also click
on the link for the project’s source module, as shown in Figure 13-10.
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:13 AM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
13
The service we are building is going to convert from degree Celsius to Fahrenheit and
back, the formulas we will use are
These conversions are done by two web methods named CtoF and FtoC, shown in the
following code segment:
[WebMethod]
public double CtoF(double Celsius)
{
return (Celsius * 9/5)+ 32;
}
[WebMethod]
public double FtoC(double Fahrenheit)
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:13 AM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
13
To test the web service, press F5 to start the component on the server. The default out-
put from a web service started in this fashion can be seen in the following illustra-
tion—the service is presented and the two web methods are listed as hyperlinks.
PART III
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:14 AM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
13
Entering a value in Celsius and clicking the Invoke button results in the XML output
shown in next. The different XML documents that are displayed in the web page docu-
ment the way to call the web service from another client.
EXAM TIP Even though you will not be expected to build a web service in
the exams, you can expect to be presented with questions containing web
service information as part of the question.
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:15 AM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
13
PART III
4. The web service receives the packet and extracts the call with the parameters,
executes the WebMethod, and formulates a return packet for the client.
5. The web service returns the packet to the proxy.
6. The packet is received by the proxy and the return data is extracted.
7. The client receives the data from the proxy.
The proxy will use XML to encapsulate the data and calls as they are sent over the net-
work—the underlying protocol is immaterial.
The next task is to build the proxy, the proxy will be build into a run-time library that
has the .dll extension. The steps involved start by creating the C# source code file from
the web service followed by compiling that source in to a run-time library.
We are going to set up a run-time library for the TemperatureConversion web
service in the previous section.
We are going to perform the tasks from a command prompt, so the first thing to
do is start the Visual Studio .Net command prompt. Then, at the command
prompt, use the cd (change directory) command to go to the directory where the
TemperatureConversion.asmx file is stored. In our case, that is C:\Inetpub\
wwwroot\TemperatureConversion.
Next you need to execute the following command from the command prompt:
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:15 AM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
13
The output from the preceding command should look like this:
Microsoft (R) Visual C# .NET Compiler version 7.00.9466
for Microsoft (R) .NET Framework version 1.0.3705
Copyright (C) Microsoft Corporation 2001. All rights reserved.
Now you need to create a root directory for the application at C:\InetPub\
WWWRoot\TempConv, and you’ll need a bin directory in that root directory:
C:\Inetpub\wwwroot>md TempConv
C:\Inetpub\wwwroot>md TempConv\bin
Copy the newly created TempConvProxy.dll to the bin directory, and then create
an application in the root (C:\InetPub\WWWRoot\TempConv) as Tempera-
ture.aspx using the following code:
The bold lines in the preceding code are the important ones. The directive in the sec-
ond line will cause the search for the TempConvService, starting in the local bin di-
rectory. Three lines further along, the web service is instantiated, so we can call the web
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:15 AM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
13
EXAM TIP The application must be able to find the proxy. The local bin
directory is the default location where the application will search for libraries.
What made our example work is the way we created the proxy and then placed it in
the bin directory of the application. The bin directory that is located in the root of the
application is the default location where the web service will look for run-time libraries
and assemblies. If you want to move the application to a different web server you would
move the proxy to that web server leave the web service on the original server. In order to
create a proxy for a web service that is located on a different web server from the one
PART III
where it will be consumed you will need to create a new WSDL file specifying the web
server where the web service is running, . For example, to use the web service on the
server named kensnabben.nopcomp.com we would run the WSDL command as
follows:
Giving the fully qualified URL for the web service is one way of linking the web ser-
vice with the client, and it is all very well when you are writing a web service to run on
your own computers. However, if you want to use the service from other businesses or
vendors, you’ll want to use UDDI (Universal Description, Discovery, and Integration)
to make a dynamic web service structure. UDDI is an industry standard that is supported
by Microsoft and IBM, among others.
EXAM TIP The exam includes questions with code segments that may use
many different techniques—you will need to know the C# language to glean
the right answer.
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:15 AM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
13
COM Interoperability
Even though Microsoft considers the .NET environment to be the latest and greatest in
software engineering, and in a perfect world everyone would immediately switch from
their current software environment to the .NET Framework, we don’t live in a perfect
world. Companies that have developed their enterprise applications around the COM
and COM+ technologies will keep using the software they have invested in for quite
some time. In this section, we will look at the interoperability between COM and .NET.
The first thing to look at is the Add Reference dialog box in the VS .NET IDE (see
Figure 13-12). This dialog box gives us the ability to add and remove references to ob-
jects that are part of the project.
To open the Add Reference dialog box, select Project | Add Reference. The dialog box
has three tabs for different types of objects: the .NET tab is for .NET assemblies, the COM
tab is where we will import COM components into our project (see Figure 13-13), and
the Projects tab lists all the projects that are referenced in the current project.
Figure 13-12 The .NET tab of the Add Reference dialog box
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:16 AM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
13
PART III
Figure 13-13 The COM tab of the Add Reference dialog box
Clicking the Browse button in the Add Reference dialog box displays the Select
Component dialog box, where you can select a COM component to interoperate with,
as shown in Figure 13-14. Once the component is selected and you click Open, the
component is added to the reference list in the Add Reference dialog box, as shown in
Figure 13-15.
Now that the reference for the component has been added to the project, you can use
it in your C# code. Visual Studio .NET has created a namespace for the component and
added the classes from the COM component into that namespace. You can use the
COM components in the same way you use native C# objects: by setting a reference, and
instantiating and invoking the component’s classes.
The following code segment uses the temperature-conversion COM component
TConv that we added in the Add Reference dialog box.
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:16 AM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
13
The namespace that was used for the wrapper is TConv, and the class in the COM
component that does the conversions is CConverter. The wrapper makes that into the
CConverterClass, so the type is TConv.CConverterClass.
We use the methods of the class to perform our processing. The COM component
has two methods that return double values: CtoF(ref double) and FtoC (ref
double). The ref double data type indicates that the parameter is passed by refer-
ence, not by value. The names of the methods indicate the direction of the conversion,
CtoF() converts from Celsius to Fahrenheit, while FtoC() does the reverse. The final
converter is shown in Figure 13-16.
The process of adding COM components to a web page is simplified by using the Vi-
sual Studio .NET to referenced the COM component through the Add Reference dialog
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:16 AM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
13
PART III
Figure 13-15 The selected component in the Add Reference dialog box
box, two tasks are performed: it generates the .NET proxy for the COM component, and
it puts a copy of the component in the project directory.
The .NET proxy that is generated by Visual Studio .NET is technically called the
Runtime Callable Wrapper (RCW); it is the part that makes the component self-describ-
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:16 AM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
13
TlbImp MyModule.dll\1
EXAM TIP Use the TlbImp.exe utility to generate the proxy for a COM
component.
On the surface it looks like the generation of the .NET proxy has hidden the imported
COM component (with all its problems) behind the RCW, that is not the case.
The COM component is still the component that needs to perform the work. COM com-
ponents that are used by .NET applications still have to be deployed in the same careful
and meticulous way as always—they must even be registered using the regsvr32.exe
utility like this:
regsvr32 tconv.dll
Platform Invoke
There are times when you’ll need to get access to functionality that is in libraries or ap-
plications that are considered unmanaged code. One example is any calls you make to the
Win32 API.
In the .NET Framework, the term unsafe code refers to code that has been marked as an
unsafe code block. The code in such a block can use the entire palette of features that are
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:17 AM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
13
PART III
namespace, which must be imported for pinvoke to work.
The API method being called is defined using attributes to indicate what library the
method is in. Consider the following code segment:
using System.Runtime.InteropServices;
…
[DllImport("user32.dll")]
public static extern int MessageBoxW(int Modal,
string Message,
string Caption,
int Options);
The preceding segment has exposed (or imported) the API method MessageBoxW from
user32.dll. If we look up the signature for the method, we find that it is as follows:
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:17 AM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
13
The WIN32 API uses a very terse style for some of its methods names, and you might
want to use something that fits the naming convention of your project. Or you might
have a name conflict between the imported method and an existing method.
Although it looks very beneficial to use pinvoke to get to platform-dependent func-
tionality, it is platform dependent, and one of the major selling points for .NET is the
platform independence built into the system. Use pinvoke sparingly, and only after
solid planning. One reason for using pinvoke is to get direct access to operating-
system functionality that is too slow or cumbersome to access through the .NET Frame-
work.
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace Events
{
public class WebForm1 : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
}
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:17 AM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
13
PART III
the Page_Load() event handler, and that is where we should write the startup code
for the page.
When we add components to the form, a protected member variable is created to
hold the control variable. The following is the declaration for a Button control:
In order to handle the events from the control, there must be entries in the
InitializeComponent() method to register the event handler. Their registration
entries can be entered manually, or we can let Visual Studio .NET perform the registra-
tion for us. In the case of the Button control, the most common event to be handled is
the Click event, and to request that Visual Studio .NET add the event handler for us, we
need to double-click the control in Design view. The following is the code that is added
to the codebehind module:
The event-handler registration is very flexible, and it gives us the control we need over
how events are handled. We can use one event handler for a large number of controls to
truly centralize our code, as we did with the 26 Button controls in the address-book ap-
plication in Chapter 12.
You can double-click on any control in Design view to add the most common event
handlers. Other handlers will need to be added manually, defining the event handler
first and then registering the event handler. The code in the codebehind module that
executes in response to the event will not execute immediately, nor will it execute on the
client—it will execute on the server, and only when the postback event occurs.
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:17 AM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
13
<html>
<head>
<title>HTML Form</title>
</head>
<body>
<form method="post">
What is you favorite sport?<br/>
<br/>
<input type="radio" value="Football" name="sport">Football<br/>
<input type="radio" value="Hockey" name="sport">Hockey<br/>
<input type="radio" value="Soccer" name="sport">Soccer<br/>
<input type="radio" value="Baseball" name="sport">Baseball<br/>
<input type="radio" value="Rugby" name="sport">Rugby<br/>
<input type="submit" value="Send selection"
onclick="alert('You have clicked the submit button!')">
</form>
</body>
</html>
We saved this file in the root of our web server (C:\inetpub\wwwroot\) and
called the file htmlform.htm. Opening the form in the browser allows you to make a
selection for your favorite sport, as shown in Figure 13-17. After you click Send Selec-
tion, the form clears and appears as in Figure 13-18. The form cleared as we submitted
the data to the server. This happens because the data is sent to the server and the original
page is redrawn; at no point in this process is any state being saved.
Now we will look at the equivalent form using ASP.NET and postback. The following
ASP.NET page (htmlform.aspx) will display the same form as the HTML version
does, but the state is preserved as we submit the form to the server.
<html>
<head>
<title>HTML Form</title>
</head>
<body>
<form runat="server">
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:18 AM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
13
The resulting display can be seen in Figure 13-19. After selecting a sport and clicking
the button, we still have our selection in the display, showing that the state of the form
has been remembered.
PART III
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:18 AM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
13
To understand what happened and how the selection was remembered, we need to
look at the HTML code that the ASP.NET process sent to the client browser. The follow-
ing listing is the resulting HTML for the display in Figure 13-19.
<html>
<head>
<title>HTML Form</title>
</head>
<body>
<form name="_ctl0" method="post" action="htmlform.aspx" id="_ctl0">
<input type="hidden" name="__VIEWSTATE"
value="dDwyMDE0NTgwNzI1Ozs+rR+xbfriVGiHInW3uHd11uisuj4=" />
What is your favorite sport?<br/>
<br/>
<table id="sport" border="0">
<tr>
<td><input id="sport_0" type="radio" name="sport" value="Football" />
<label for="sport_0">Football</label></td>
</tr><tr>
<td><input id="sport_1" type="radio" name="sport" value="Hockey" />
<label for="sport_1">Hockey</label></td>
</tr><tr>
<td><input id="sport_2" type="radio" name="sport" value="Soccer"
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:18 AM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
13
As you can see, the radiobuttonlist from the htmlform.aspx listing was turned
into a table with standard HTML radio input elements.
PART III
The highlighted portions of the HTML code are what make ASP.NET’s
postback work. The hidden control with the name __VIEWSTATE and the binary
value "dDwyMDE0NTgwNzI1Ozs+rR+xbfriVGiHInW3uHd11uisuj4=" is the key.
The value of the __VIEWSTATE control is the binary representation (hash) of the form,
and it is the comparison between the original version of the form, as represented by the
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:18 AM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
13
Now that we have looked at how postback maintains the data for a form between
server calls we will need to look at some of the issues with postback and controls. The
postback process only works with the server controls supplied with ASP.NET, and it is by
default initiated only by the Button control. All other events are queued on the client
and sent to the server during the next postback event. There are also some events that
cannot be processed by the server using this model, such as the MouseOver event,
which can only be handled by writing traditional client-side scripts. Any event that will
be called repeatedly and will need immediate feedback while the page is being viewed
must be handled on the client side. The mouse events are such events.
If you need to have a control trigger the postback, you must set the AutoPostBack
attribute of the control to True (the default is False). The following code illustrates the
use of AutoPostBack:
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:18 AM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
13
To disable view state for an entire page, set the @ Page directive’s Enable
ViewState attribute to False, as in this example:
PART III
<@ Page EnableViewState="False">
Summary
This chapter has taken you through the server-side neighborhood of .NET, from the
ASP.NET objects (Request, Response, Session, Application, Server), through
web services and COM components, to the waters of platform invoke. The amount of
space devoted to these topics in the chapter reflects their relative importance on the
exam. The topic of web services is not “supposed” to be in the exam, but we feel that it is
still a topic that might show up, so be prepared to know the basics about how to build a
web service.
You might expect combination questions that use information from this chapter to
set the background for another question.
Test Questions
1. What must be done before you can consume a web service?
A. Build a proxy library by using the TblImp.exe utility.
B. Build a proxy library by using the Disc.exe utility.
C. Build a proxy library by using the csc.exe utility.
D. Build a proxy library by using the wsdl.exe utility.
2. You need to use the web service TempConvService. Where should you
place the proxy file?
A. In the lib directory off the root directory of the application.
B. In the root directory of the application.
C. In the bin directory off the root directory of the application.
D. In the bin directory of .NET Framework.
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:18 AM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
13
C. [DllImport("MyLibrary.dll")]
public static extern int MyFunc() = Func42();
5. You need to call a method located in a web service named TService that has
been correctly registered in your application. The method is in the class Tconv
and is named CtoF() with the following signature:
int CtoF(double dd)
What code segment correctly calls the CtoF() method?
A. TService.Tconv tc = new TService.Tconv;
int x = tc.CtoF(42.12);
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:19 AM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
13
6. You have been given the task of designing a web service to expose the data
that is stored in a database on the server. In order to successfully build the
web services, you need to import some namespaces. What is the minimum
namespace you need to import?
A. System.Web
B. System.WebServices
C. System.Web.Services
D. System.Web.ServiceModel
7. You have designed an event for the class you are working on, and the event is
PART III
declared as follows:
// declare the delegate for the event
public delegate int MugEmptyHandler(int RefillVolume);
// declare the event
public static event MugEmptyHandler OnMugEmpty;
When you try to register the event in the client code by using the following
line, you receive a syntax error:
this.OnMugEmpty += new MugEmptyHandler(this.Mug_Empty);
You need to make the OnMugEmpty event functional. What will you do?
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:19 AM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
13
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:19 AM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
13
PART III
D. Rebuild your application after adding the reference to the web service.
14. You have designed a web form that has one listbox control. You have
implemented the SelectedIndexChanged event handler, and you have
verified that all required declarations are in place and that the event handler is
registered. During testing of the form, you find that the event does not execute.
What is the most efficient way to make the event execute?
A. Set the AutoPostBack attribute of the listbox control to False.
B. Set the AutoPostBack attribute of the @ Page directive to True.
C. Set the AutoPostBack attribute of the listbox control to True.
D. Change from the listbox control to the DropDownList control.
Test Answers
1. D.
2. C.
3. B. The namespace of the web service must be imported.
4. D. The entry point must be the name in the library, the signature is what
C# will use.
5. D. The fully qualified method name is TService.Tconv.CtoF(), and the return
variable must be declared.
6. C.
7. D. Multi cast delegates must be declares with a void return type
8. B. The event must be registered.
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:19 AM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
13
P:\010Comp\All-in-1\443-6\ch13.vp
Monday, August 26, 2002 11:46:19 AM