Appendix A
Questions and Answers
Chapter 1: Introduction to Web Programming
Give two examples of how an ASP.NET Web application is different from a traditional Windows application.
Web applications and traditional Windows applications have the following differences:
Feature | ASP.NET Web application | Unmanaged Windows application |
Architecture | Client/server | Local user |
Execution | Runs under common language runtime using managed code | Runs under Windows using unmanaged code |
What are the two main parts of the .NET Framework?
The common language runtime (CLR).
The .NET Framework class library.
How do you restore the default window settings in Visual Studio .NET?
From the Tools menu, choose Options, and then click Reset Window Layout.
Why doesn t the Visual Studio .NET Code Editor automatically complete the following partial line of code (Visual C# users only)?
int intX = system.math
The namespace System.Math must be capitalized in Visual C# for IntelliSense to recognize the namespace.
When can t you use ASP.NET to create a Web application?
When you are developing for non Microsoft Windows Web servers, such as Linux/Apache.
Chapter 2: Creating Web Forms Applications
Explain where Visual Studio .NET stores Web application projects.
Web application projects are stored in a new virtual folder for each project. The properties of that virtual folder determine where the files are physically stored. These properties can be viewed in IIS.
List the four major differences between Web and Windows applications.
Web forms cannot use the standard Windows controls. Instead, they use server controls, HTML controls, user controls, or custom controls created specially for Web forms.
Web applications are displayed in a browser. Windows applications display their own windows and have more control over how those windows are displayed.
Web forms are instantiated on the server, sent to the browser, and destroyed immediately. Windows forms are instantiated, exist for as long as needed, and are destroyed.
Web applications run on a server and are displayed remotely on clients. Windows applications run on the same machine they are displayed on.
Describe the life cycle of a Web application: When are Web forms instantiated and how long do they exist?
A Web application starts with the first request for a resource within the application s boundaries. Web forms are instantiated when they are requested. They are processed by the server and are abandoned immediately after the server sends its response to the client. A Web application ends after all client sessions end.
How do you preserve persistent data, such as simple variables, in a Web application?
You can preserve data in state variables, such as ApplicationState, SessionState, or ViewState.
What determines the boundaries of a Web application?
IIS determines Web application boundaries by the structure of the application s virtual folders. A Web application boundary starts in the folder containing the start page of the application, and it ends at the last subordinate folder or when it encounters another start page in a subordinate folder.
Chapter 3: Working with Web Objects
How does the .NET Framework organize its classes?
The .NET Framework uses namespaces to organize its classes.
In Visual Basic .NET, what is the difference between a class module and a code module?
Class modules are instantiated at run time to create objects that provide separate storage for variables and properties in each instance. Code modules do not have instances, so any module-level variables they use are shared among calls to the module s procedures.
In Visual C#, how do you declare a method to make it available without having to first instantiate an object from the class?
To create a method that can be called without instantiating an object, declare that method as static.
How do you call a member of a base class from within a derived class?
To refer to a member of a base class in Visual Basic .NET, use the MyBase keyword. To refer to a member of a base class in Visual C#, use the base keyword.
Where would you save the following data items so that they persist between requests to a Web form?
A control created at run time
An object that provides services to all users
User preferences
Save controls created at run time in the Page object s ViewState.
Save objects that provide services to all users in the Application state.
Save user preferences in SessionState.
Chapter 4: Creating a User Interface
What is the main difference between the Button server control and the Button HTML control?
When clicked, the Button server control triggers an ASP.NET Click event procedure on the server. The Button HTML control triggers the event procedure indicated in the button s onclick attribute, which runs on the client.
How do you get several RadioButton controls to interoperate on a Web form so that only one of the RadioButton controls can have a value of True/true at any given time?
Set the GroupName property of each RadioButton to the same name.
Why does ASP.NET perform validation on both the client and the server?
Client-side validation helps avoid round-trips to the server. Validating on the client ensures that the data is valid before it is submitted, in most cases. However, because validation might be turned off (or maliciously hacked) on the client, data must be revalidated on the server side. This provides full assurance that the data is valid while avoiding as many round-trips as possible.
What types of validation would you use to verify that a user entered a valid customer number?
You would use a RequiredFieldValidator and a RegularExpressionValidator. If you have access to a list of expected customer numbers, you could replace the RegularExpressionValidator with a CustomValidator that checked the list.
What is wrong with the following line of code?
Visual Basic .NET
Server.Transfer("Default.htm")
Visual C#
Server.Transfer("Default.htm");
You can t use the Transfer method with HTML pages. It works only with .aspx pages.
Why can t you open a new browser window from within server code?
Server code executes on the server, whereas the new window is created on the client. You need to use client-side code to do things that affect the client, such as upload files, display new windows, or navigate back in history.
Chapter 5: Storing and Retrieving Data with ADO.NET
What steps would you follow and what objects would you use to quickly find the number of records in a database table?
There are two ways to accomplish this task:
Use a database connection and a command object to execute a SQL command that re-turns the number of rows in the table.
Use a database connection and data adapter object to create a data set for the table, and then get the number rows in the data set.
How do typed data sets differ from untyped data sets, and what are the advantages of typed data sets?
Typed data sets use explicit names and data types for their members, whereas untyped data sets use collections to refer to their members. The following examples show a typed reference vs. an untyped reference to a data item:
Visual Basic .NET
' Typed reference to the Contacts table's HomePhone column. DataSet1.Contacts.HomePhoneColumn.Caption = "@Home" ' Untyped reference to the Contacts table's HomePhone column. DataSet1.Tables("Contacts").Columns("HomePhone").Caption = "@Home"
Visual C#
// Typed reference to the Contacts table's HomePhone column. DataSet1.Contacts.HomePhoneColumn.Caption = "@Home"; // Untyped reference to the Contacts table's HomePhone column. DataSet1.Tables["Contacts"].Columns["HomePhone"].Caption = "@Home";
Typed data sets do error checking at design time. This error checking helps catch typos and type mismatch errors, which would be detected only at run time with untyped data sets.
How do you call a stored procedure?
Create a command object, set the object s CommandText property to the name of the stored procedure, and set the CommandType property to StoredProcedure. To execute the stored procedure, use the command object s ExecuteNonQuery, ExcecuteScalar, ExecuteReader, or ExecutelXmlReader method. For example, the following code calls the Ten Most Expensive Products stored procedure on the Northwind Traders database:
Visual Basic .NET
' Create a command object to execute. Dim cmdTopTen As New SqlCommand(connNWind) ' Set command text. cmdTopTen.CommandText = "Ten Most Expensive Products" ' Set the command properties. cmdTopTen.CommandType = CommandType.StoredProcedure ' Create a data reader object to get the results. Dim drdTopTen As SqlDataReader ' Open the connection. connNWind.Open() ' Excecute the stored procedure. drdTopTen = cmdTopTen.ExecuteReader()
Visual C#
// Create a connection for NorthWind Trader's database. SqlConnection connNWind = new SqlConnection("integrated security=SSPI;" + "data source=(local);initial catalog=Northwind"); // Create a command object to execute. SqlCommand cmdTopTen = new SqlCommand(connNWind); cmdTopTen.CommandText = "Ten Most Expensive Products"; // Set the command properties. cmdTopTen.CommandType = CommandType.StoredProcedure; // Create a data reader object to get the results. SqlDataReader drdTopTen; // Open the connection. connNWind.Open(); // Excecute the stored procedure. drdTopTen = cmdTopTen.ExecuteReader();
Explain the difference between handling transactions at the data set level and at the database level.
Data sets provide implicit transactions, because changes to the data set aren t made permanent in the database until you call the Update method. To handle transactions in a data set, process the Update method and check for errors. If errors occur during an update, none of the changes from the data set is made in the database. You can try to correct the error and resubmit the update, or you can roll back the changes to the data set using the RejectChanges method.
Databases provide explicit transactions through the Transaction object. You create a Transaction object from a database connection and then assign that Transaction object to the commands you want to include in the transaction through the command object s Transaction property. As you perform the commands on the database, you check for errors. If errors occur, you can either try to correct them and resubmit the command, or you can restore the state of the database using the Transaction object s RollBack method. If no errors occur, you can make the changes permanent by calling the transaction object s Commit method.
Chapter 6: Catching and Correcting Errors
Explain why exception handling is important to a completed application.
When an unhandled exception occurs in an application, the application stops the user can t proceed, and any work he or she did immediately prior to the exception is lost. Exception handling provides a way to intercept and correct unusual occurrences that would otherwise cause these problems.
List two different exception-handling approaches in ASP.NET Web applications.
Exceptions can be handled in exception-handling blocks using the Try, Catch, and Finally keywords in Visual Basic .NET or the try, catch, and finally keywords in Visual C#. They can also be handled using Error event procedures at the Global, Application, or Page levels using the Server object s GetLastError and ClearError methods.
Describe the purpose of error pages and why they are needed.
Because Web applications run over the Internet, some exceptions occur outside the scope of the application. This means that your application can t respond directly to these exceptions. These types of exceptions are identified by HTTP response codes, which IIS can respond to by displaying custom error pages listed in your application s Web.config file.
Explain why tracing helps with exception handling.
Tracing allows you to record unusual events while your application is running, without users being aware of it. If an unanticipated exception occurs, your application can write a message to the trace log, which helps you diagnose problems during testing and after deployment.
Chapter 7: Advanced Web Forms Programming
Write the HTML for a hyperlink that will send mail when the user clicks the link.
<a href="mailto:you@microsoft.com?SUBJECT=Sending from a client&BODY=Some message text.">Send mail</a>
Write the code that creates a cookie containing the user name Rob Young and the current date to the user s computer. Set the cookie to remain on the user s computer for 30 days.
Visual Basic .NET
Dim cookUserInfo As New HttpCookie("UserInfo") cookUserInfo("Name") = "Rob Young" cookUserInfo("Time") = DateTime.Now.ToString() cookUserInfo.Expires = DateTime.Now.AddDays(30) Response.Cookies.Add(cookUserInfo)
Visual C#
HttpCookie cookUserInfo = new HttpCookie("UserInfo") CookUserInfo["Name"] = "Rob Young" CookUserInfo["Time"] = DateTime.Now.ToString() cookUserInfo.Expires = DateTime.Now.AddDays(30) Response.Cookies.Add(cookUserInfo)
What attribute do you use to hide a public .NET class from COM?
Use the ComVisible attribute to select which public .NET classes and members are visible to COM. This attribute applies hierarchically for the assembly, class, and member levels.
Why can t you open a new browser window using server-side code? How would you display a page in a new window with a client-side script?
Server-side code can execute tasks only on the server. To perform a task on the client s computer, such as opening a new browser window, the code needs to run on the client.
You can open a new window using the DOM window object. For example, the following HTML Button control opens a Help page in a new window:
<button onclick="window.open('help.aspx', 'help', 'height=200,width=300')">Help</ button>
How do you declare an unmanaged procedure within .NET?
Use the DllImport attribute or a Visual Basic .NET Declare statement to declare an unmanaged procedure for use with a .NET assembly. The DllImport attribute is found in the System.Runtime.InteropServices namespace.
Chapter 8: Maintaining Security
Which ASP.NET authentication mode is best suited to identifying and authorizing users who belong to a corporate network?
Windows authentication is best suited to authenticating users of a corporate network because it uses the accounts and permissions that already exist for network users.
What is the difference between Windows and Forms authentication user lists in Web.config?
User lists for Windows authentication are included in the <authorization> element of Web.config.
User lists for Forms authentications are included in the <credentials> element of Web.config or as part of an external users database or file.
How do you require authentication using the Web.config file? (The answer is the same for all ASP.NET authentication modes.)
Include the following <authorization> element to require authentication:
<authorization> <deny users="?" /> </authorization>
How do you run a Web application using the permission set of an authenticated user?
Use the identity element in Web.config to execute code using the authenticated user s account. For example:
<!-- Impersonate the authenticated user --> <identity impersonate="true" />
How does the Secure Sockets Layer (SSL) provide security in a Web application?
SSL protects data exchanged between a client and a Web application by encrypting the data before it is sent across the Internet.
How do you begin and end secure communication via SSL?
To begin secure communication, specify https in an address. For example:
<a href="https://www.contoso.com/secure.htm">Secure page.</a>
To end secure communication, specify http. For example:
<a href="http://www.contoso.com/Default.htm">Not secure.</a>
Chapter 9: Building and Deploying Web Applications
What permissions do Web applications run under by default?
By default, Web applications run as the ASPNET user, which has limited permissions equivalent to the Users group.
Why is the Machine.config file important to deployed Web applications?
The Machine.config file controls many aspects of how Web applications run, including how processes are recycled, what types of request queue limits are imposed, and what interval is used when checking if users are still connected.
How do you configure a setup project to install an application over the Web?
To configure a setup project to install an application over the Web, select the Web Bootstrapper option from the setup project s properties. This setting allows the Windows Installer to be downloaded and installed over the Web.
How do you distribute shared components as part of an installation program?
Shared components should be included as a merge module within the setup project. Merge modules manage the installation of shared components so that they re not unnecessarily overwritten and so that they can be safely removed when no longer used. Unlike regular setup projects, merge modules can t be installed by themselves they can be installed only as part of an application installation.
How does deploying to a Web farm or a Web garden affect Session state in a Web application?
Web applications that are deployed to a Web farm or a Web garden need to identify a Session state provider in their Web.config file. This is because a single client s requests can be directed to different processes over the course of his or her session. The Session state provider allows each different process to access the client s Session state.
Chapter 10: Testing Web Applications
How do unit, integration, and regression testing relate to each other?
Unit testing is the foundation that ensures that each piece of code works correctly. Integration testing extends this concept by verifying that pieces work together without errors. Regression tests are made up of the existing unit and integration tests, which are run on a regular schedule to assure that new code did not break previously working code.
Why is load testing likely to be more important for a Web application than for a stand-alone Windows application?
Because Web applications can be public on the Internet, they can have hundreds, thousands, or even millions of users. Load tests let you simulate the expected demand to locate resource conflicts, performance bottlenecks, and other problems that aren t apparent in single-user tests.
What is the difference between the Debug and Trace classes?
Under the default environment settings, code using the Debug class is stripped out of release builds, while code using the Trace class is left in. The classes are otherwise equivalent.
What are the two special steps you need to take to ensure that a COM component can use a component from a .NET assembly?
To use a .NET component from a COM tool, such as VBScript, you must:
Register the .NET assembly in the system registry using RegAsm.exe.
Make sure that the COM component can find the .NET assembly, either by placing the .NET assembly in the global assembly cache, by placing the two components in the same folder, or by following the other assembly-probing rules.
Chapter 11: Creating Custom Web Controls
Briefly describe the best uses for each of the three types of Web controls by completing the following sentences:
Create a Web user control when you want to
Create a composite custom control when you want to
Create a rendered custom control when you want to
Create a Web user control when you want to
quickly create a group of controls that can be reused throughout a project to perform some logical unit of work.
Create a composite custom control when you want to
combine one or more existing controls into a compiled assembly that can be easily reused in many different projects.
Create a rendered control when you want to
build an entirely new control that can be compiled into an assembly for use in multiple projects.
How is deriving important to creating custom Web controls?
Both composite and rendered custom controls are derived from the WebControl base class. That class provides the methods that you override to create the appearance of the custom control.
What is the most important method to override when you re creating a composite custom control?
You override the CreateChildControls method to add existing controls to a composite custom control.
What is the most important method to override when you re creating a rendered control?
You override the Render method when creating a rendered custom control.
How is raising a post-back event in a composite control different from raising a post-back event in a rendered control?
In a composite control, you can use one of the contained controls to raise a post-back event. In a rendered control, you must implement the IPostBackEventHandler interface and write a client-side script to raise a post-back event.
Chapter 12: Optimizing Web Applications with Caching
Write a directive to cache responses for a Web form for 30 seconds, storing different cache responses based on the value of the lstNames control.
<%@ OutputCache Duration= 30 VaryByParam= lstNames %>
A Web form uses fragment caching to store a frequently used user control. At run time, an Object not found error occurs whenever the page is refreshed. What is a likely cause of the error?
The most likely cause is that the user control is referenced in code after it has been cached. Once cached, a user control s properties and methods are no longer available.
How can you detect when application data is about to be removed from the cache?
Use the onRemoveCallback delegate.
Which ASP.NET performance counter is the best indicator of inefficient caching?
The Turnover Rate performance counter.
Chapter 13: Formatting Web Application Output
What is the advantage of using CSS rather than in-line styles for formatting a Web application?
Using CSS allows you to maintain formatting separately from the content of your Web forms, so changes are easier to make and consistency is easier to maintain.
Why would you create a style for a class rather than for an HTML element?
You create style classes when you want to apply the same formatting to different types of elements within an application. For example, you might want to create an emphasis style class that applies the same formatting to any text, control, heading, or image that you want to draw the user s attention to.
How do CSS and XSL relate to each other when it comes to formatting a Web application?
CSS and XSL are complementary techniques for formatting. CSS determines the font, color, size, background, and other appearance aspects of HTML elements on a Web page. XSL is used to transform XML files into HTML output. In this way, XSL controls the position and appearance of items based on their content. Used together, XSL performs the high-level tasks of composition and layout while CSS performs the low-level tasks of applying fonts, colors, and other appearance features.
What are the differences between HTML and XML?
HTML uses predefined element names, such as <p> and <br>. In XML, you create your own element names to identify hierarchical nodes of data.
XML syntax is much stricter than HTML: elements must always have end-tags, element names are case sensitive, attribute values must always be enclosed in quotation marks, and nested elements must be terminated within their parent elements.
XML identifies data conceptually based on the data s content, rather than based on the type of formatting to apply.
Chapter 14: Providing Help
Which HTML attribute does the server control s ToolTip property map to in the HTML rendered by ASP.NET?
The ToolTip property is rendered as the title attribute at run time.
How does displaying HTML Help using the window object s showHelp method differ from displaying HTML Help using a browser window?
The showHelp method cannot open compiled HTML Help from a network address; the compiled file must first be downloaded to the user s machine. You can display HTML Help from a network address within a browser window, provided you use the ms-its: protocol. However, the HTML Help Contents, Index, and Search features are not automatically available from a browser window.
How do you add index keywords to a Help topic?
Insert an object element in the Help topic using the HTML Help ActiveX control. For example, the following object element adds the numbers index keyword:
<Object type="application/x-oleobject" class> <param name="Keyword" value="numbers"> </OBJECT>
Chapter 15: Globalizing Web Applications
What is the difference between the CurrentCulture property and the Current UICulture property?
The CurrentCulture property affects how the .NET Framework handles dates, currencies, sorting, and formatting issues. The CurrentUICulture property determines which satellite assembly is used when loading resources.
How do you detect the user s culture?
Use the Request object s UserLanguages array. The value at element 0 corresponds to one of the culture codes used by the CultureInfo class. For example:
SLang = Request.UserLanguages(0)
What is a neutral culture?
Neutral cultures represent general languages without region-specific differences, such as currency. For example, the es culture code represents Spanish.
How does character encoding affect file formats?
When using non-ASCII characters in a Web form, you must save the file with a specific character encoding, such as UTF-8. ASP.NET can automatically detect UTF-8 file encoding if the file is saved with a signature; otherwise, you need to specify the file encoding used in the fileEncoding attribute of the globalization element in Web.config.