Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

C# ПІДРУЧНИКИ / c# / Hungry Minds - ASP.NET Bible VB.NET & C#

.pdf
Скачиваний:
128
Добавлен:
12.02.2016
Размер:
7.64 Mб
Скачать

Figure 13-4: Output of the application that converts relational data into an XML document

Binding server-side controls with data in XML files

ASP.NET enables you to associate server controls with a variety of sources, including XML files. You can think of an XML file as a special data table that contains data embedded within the tags that describe the data.

You cannot bind an XML document directly to a server-side control because it contains data in a plain-text format. You must first load XML data as a data table into a data set. After loading the data into a data set, you can bind it to a server-side control. In this section, you will create a file "Products.xml" and bind a DropDownList control to the "ProductID" tag in the file. When a user selects a product ID from the DropDownList control, the details about the product will be displayed in a DataGrid control. The following are the steps involved in creating a Web application that performs the specified tasks:

1.Type the following contents in a text file and save it as "products.xml":

2.<?xml version = "1.0"?>

3.<Products>

4.<Product>

5.<ProductId> P001 </ProductId>

6.<ProductName> Baby Food </ProductName>

7.<UnitPrice> 2.5 </UnitPrice>

8.<QtyAvailable> 1200 </QtyAvailable>

9.</Product>

10.<Product>

11.<ProductId> P002 </ProductId>

12.<ProductName> Chocolate </ProductName>

13.<UnitPrice> 1.5 </UnitPrice>

14.<QtyAvailable> 1500 </QtyAvailable>

15.</Product>

</Products>

16.Create a new Web project and create a Label control in the Design view of the ASPX file. Change the Text property of the control to "Select Product Id:".

17.Create a DropDownList control in the Design view of the ASPX file. Set the values of the different properties of the DropDownList control as given in Table 13-1.

Table 13-1: DropDownList control properties

Property

ID

DataTextField

DataValueField

AutoPostBack

Value

 

Description

 

 

 

DLProdId

 

ID for the

 

 

control.

 

 

 

ProductId

 

Retrieves

(the field

 

the data

from the

 

source that

XML

 

provides the

documen

 

content of

t)

 

the

 

 

DropDownLi

 

 

st. In this

 

 

case, the

 

 

value of the

 

 

property is

 

 

set to

 

 

ProductId,

 

 

which

 

 

means that

 

 

the control

 

 

will display

 

 

the

 

 

ProductId

 

 

from the

 

 

data source.

 

 

 

ProductId

 

Specifies

 

 

the value to

 

 

be set in the

 

 

data set

 

 

when the

 

 

selection

 

 

changes.

 

 

 

True

 

Specifies

 

 

whether the

 

 

control

 

 

posts back

 

 

to the server

 

 

each time a

 

 

user

 

 

interacts

 

 

with the

 

 

control. In

 

 

this case, it

 

 

is set to

 

 

true, which

 

 

means that

 

 

every time a

 

 

user

 

 

interacts

 

 

with the

 

 

DropDownLi

 

 

st, it should

 

 

post back to

Table 13-1: DropDownList control properties

Property

 

Value

 

Description

 

 

 

 

 

the server. This is done so that whenever an item is selected from the DropDownLi st, the server retrieves details of the correspondi ng item.

18.Create a DataGrid control and set the ID property of the control to DGProdDetails.

19.Type the following lines in the ASPX file for importing the namespaces System.Data and System.IO:

20.<%@ Import Namespace = "System.Data" %>

<%@ Import Namespace = "System.IO" %>

Any class that implements the ICollection interface can be used as a data source by controls in a Web form. The ICollection interface provides the basic functionality required for accessing data. To be able to manage collections, you must import the System.Data interface. The System.IO interface contains the classes that are required for reading the XML file into a data set.

21.Write the following code within the Page_Load() function to open the products.xml file with read access permission:

22.dim ProdFile as new FileStream (server.mappath("products.xml"),

23.FileMode.Open, FileAccess.Read)

The FileStream class is defined in the System.IO namespace and has functions for reading from and writing to the files. The constructor for the FileStream class takes three parameters, described in Table 13-2.

Table 13-2: FileStream class constructor parameters

Parameter

 

Type

 

Description

 

 

 

 

 

Path

 

String

 

Relative or

 

 

 

 

 

 

 

absolute

 

 

 

 

path of the

 

 

 

 

file that

 

 

 

 

needs to be

 

 

 

 

opened

 

 

 

 

 

Mode

 

FileMode

 

Contains a

 

 

 

 

 

 

 

constant

 

 

 

 

that

 

 

 

 

specifies

 

 

 

 

how the file

 

 

 

 

is to be

 

 

 

 

created or

 

 

 

 

opened

 

 

 

 

 

Access

 

FileAccess

 

Contains a

 

 

 

 

 

 

 

constant

Table 13-2: FileStream class constructor parameters

Parameter

 

Type

 

Description

 

 

 

 

 

that specifies the way in which the file can be accessed by the FileStream object

In this example, the file is opened with read access.

24.The next step is to fill the data set with XML data. This can be done by creating an object of DataSet and calling the ReadXml() method of DataSet:

25.dim dsProductsData as new DataSet

dsProductsData.ReadXml(ProdFile)

The ReadXml() method takes a parameter of classes derived from the Stream class and fills the DataSet object with the XML data. The DataSet object will now hold the XML data in a relational form.

26.After reading the data into the DataSet, you can work with it. In this application, the DataGrid is not to be displayed unless the user selects an item from the DropDownList control. You also need to ensure that the DropDownList control is populated only if the user has visited the first time. Therefore, you need to check whether the user is visiting the page for the first time. This can be done by using the IsPostBack() method provided in ASP.NET. In case the user is visiting the page for the first time, the DropDownList control needs to be populated with the product IDs read from the XML document. This can be done by using the following code:

27.if Not IsPostBack then

28.'Set the DataSource property of the DropDownList

29.DLProdId.DataSource =

30. dsProductsData.Tables(0).DefaultView

31.'Bind the data with the control

DLProdId.DataBind()

In this code, the DataSource property of the DropDownList is set to the XML data read in the DataSet. Because the DataTextField property of the DropDownList has been set to ProductId, this step will result in displaying all product IDs in the DropDownList.

32.If the user is not visiting the page for the first time, the DataGrid should be populated with the details about the product selected from the DropDownList. This can be achieved by using the following code:

33.Else

34.dvProductsView = new DataView(dsProductsData.Tables(0))

35.dvProductsView.RowFilter = "ProductId='" +

36. DLProdId.SelectedItem.Text + "'"

37.DGProdDetails.DataSource = dvProductsView

38.DGProdDetails.DataBind()

end if

In this code, a new object dvProductsView of type DataView is created. The constructor of the DataView class takes a DataTable as a parameter. In

this example, you pass the XML data read in the data set as a parameter. Next, the RowFilter property of the DataView object is set to the product ID selected from the DropDownList. This limits the results of the DataView to only the rows that contain the same product ID as the one selected from the DropDownList. Then, the DataSource property of the DataGrid with the ID DGProdDetails is set to the DataView object. Finally, the data from the DataView is bound to the DataGrid. This code will result in displaying the details of the product selected from the DropDownList into the DataGrid.

The final code for displaying product IDs in a DropDownList and corresponding details in a DataGrid is as follows:

<script language="vb" runat="server">

public sub Page_Load (Sender as Object, e as EventArgs )

dim ProdFile as new FileStream (server.mappath("products.xml"),

FileMode.Open, FileAccess.Read)

dim dsProductsData as new DataSet

dsProductsData.ReadXml(ProdFile)

if Not IsPostBack then

DLProdId.DataSource = dsProductsData.Tables(0).DefaultView

DLProdId.DataBind()

else

dim dvProductsView as new DataView(dsProductsData.Tables(0))

dvProductsView.RowFilter = "ProductId='" + DLProdId.

SelectedItem.Text + "'"

DGProdDetails.DataSource = dvProductsView

DGProdDetails.DataBind()

end if

end sub

</script>

When you execute the application, you'll find that the DropDownList control displays the product IDs stored in the XML document. When you click a particular product ID, it will display the details about the product in the DataGrid control, as shown in Figure 13-5.

Figure 13-5: Output of the application implementing data binding with an XML file

This is one of the ways of binding XML data with ASP.NET server-side controls. You can perform many such tasks of opening an XML document, reading each element from the document, and displaying data from it using ASP.NET.

Summary

In this chapter, you were introduced to XML and its related specifications, such as DTD, XML Schema, XSL/T, namespaces, and XML DOM. You also learned about the System.Xml namespace provided in ASP.NET for working with XML documents. Then, you looked at some simple applications of using XML with ASP.NET. Finally, you learned about binding ASP.NET server controls to data from an XML document.

Part III: Advanced ASP.NET

Chapter List

Chapter 14: ASP.NET Application Configuration Chapter 15: Developing Business Objects Chapter 16: Building HTTP Handlers

Chapter 17: Understanding Caching

Chapter 18: Building Wireless Applications with ASP.NET Mobile Controls Chapter 19: ASP.NET Security

Chapter 20: Localizing ASP.NET Applications

Chapter 21: Deploying ASP.NET Applications

Chapter 14: ASP.NET Application Configuration

Overview

After an application is designed and developed, it needs to be deployed on an application Web Server for launching it as a Web site on the Internet or an intranet. The deployment process includes installation and configuration of the Web application (Web site) on an application Web Server. Configuring a Web site requires implementation of settings according to the server's capabilities and requirements. Configuring a Web site might also require developers to write code. At a later stage, the site administrator might need to change the settings of the site or the server on which the site has been deployed so as to enhance the performance of the site. However, if the change in settings involves embedding values into code, it becomes very complicated and difficult for both the developer and the administrator to reconfigure the application.

The application deployment process requires a rich and flexible configuration system. The configuration system should enable developers to easily associate settings with an installable application without having to embed values into code. The system should also enable administrators to easily adjust or customize these values after the deployment of the application on the application Web Server. The ASP.NET configuration system fulfills both these requirements.

This chapter explores the ASP.NET configuration concept, the Web.config file, and the sections in the Web.config file.

ASP.NET Configuration Concepts

ASP.NET is designed to provide developers with rich support for designing, developing, and deploying Web applications. For application deployment, ASP.NET provides a rich set of configuration settings. The configuration information for the entire ASP.NET application is defined and contained in configuration files. These files are written in XML and are named Web.config.

ASP.NET uses a hierarchical configuration architecture that uses an XML format. In the hierarchical configuration architecture, whenever a client makes a request for an

A server can host multiple Web sites.

ASP.NET application or a specific ASP.NET resource, ASP.NET checks the settings for the URL requested by the client in a hierarchical fashion. The check is carried out using the configuration files located in the path for the requested URL. These settings are then logged or cached by the application Web Server to speed up any future requests for ASP.NET resources. To understand the hierarchical configuration architecture better, consider a Web site that has a file structure similar to that shown in Figure 14-1.

Figure 14-1: File structure of a Web site

In this file structure, suppose that the Application Root directory is the virtual directory (vdir) mapped for the site. A virtual directory is the main directory for the site, which contains all the files and subdirectories, including the script pages, HTML pages, programs, or any graphics for the site. Every site must have a virtual directory; the virtual directory might contain many subdirectories. The other two subdirectories within the Application Root directory are not virtual directories. This directory structure allows administrators to configure the application settings. For example, administrators can configure the application settings, such that all users are given access to the ASP.NET resources in the Application Root directory, but only selected users are given access to the ASP.NET resources in the subdirectories.

Consider a scenario wherein the Web site has only one Web.config file in the SubDir1 directory. Although the Web site has only one Web.confi g file in the directory structure, the Web site actually uses two Web.config files, because a file named Machine. config exists in the %windir%\Microsoft.NET\Framework\v1.0.<buildnumber>\CONFIG directory. In this path, <buildnumber> represents 2914 for the Beta 2 release of the Microsoft .NET Framework SDK. In future releases, this build number will change, and therefore the actual name of the folder might also change. This file is at the highest level and is called the machine-level configuration file. This machine-level configuration file comes with the Microsoft .NET Framework and contains the default settings. All ASP.NET directories and subdirectories inherit settings from this machine-level configuration file. However, a Web.config file can also be located at the Web site level, and if it is not overridden at a lower level, it will apply to all ASP.NET resources on the Web site.

Note

The default settings of the machine-level configuration file allow access to all users. In this scenario, there is no configuration file in the Application Root directory that modifies the default behavior of the machine-level configuration file; all users will be given access to the ASP.NET resources on the site, because the Application Root directory inherits settings from the machine-level configuration file. The configuration file located in the SubDir1 directory can have settings that specify access only to certain users. In such a case, all users can access the ASP.NET resources in the Application Root directory, but only certain users can access the ASP.NET resources in both the subdirectories.

Note The configuration settings for virtual directories are independent of the physical directory structure, and unless the manner in which the virtual directories are organized is exclusively specified, configuration problems might result.

To summarize, the hierarchical configuration architecture provides a flexible and rich configuration system that enables extensible configuration data to be defined and used throughout the ASP.NET applications. The configuration system of ASP.NET has the following benefits in terms of deployment of Web applications:

§The configuration information for the ASP.NET applications is stored in XMLbased confi guration files, which makes it easy to read and write.

Administrators and developers can use a standard text editor, XML parser, or Perl script for any kind of interpretation or updating of the configuration settings of the application.

§The configuration information files are stored in the same directory tree as the rest of the application files, thus making the installation of ASP.NET applications easy.

§The configuration system is highly flexible and allows developers to store customized configuration criteria and settings in the configuration system. This extensibility feature can then be used at run time to affect the processing of the HTTP requests.

§The configuration system allows the automation of any configuration updates made to the ASP. NET configuration files. The changes made are applied without requiring any user intervention.

§The configuration information contained in the XML file is applied

hierarchically with regard to the virtual directory structure, which is provided at the time of site creation on the Application Server. Subdirectories under the virtual directory inherit or override the configuration settings from their parent directories. This allows different settings for different applications or different parts of a single application.

Now that you understand the basic concepts of the ASP.NET configuration, let us now take a closer look at the structure of the Web.config configuration files.

Web.config Configuration Files

As mentioned earlier, the configuration information for any ASP.NET application is defined and contained in configuration files named Web.config files. The following code illustrates the basic structure of an ASP.NET configuration file:

<configuration>

<configSections>

<section name="appSettings" type = "System.Web.

Configuration.NameValueSectionHandler" />

<section name="httpModules" type = "System.Web.

Config.HttpModulesConfigHandler"/>

<section name="httpHandlers" type = " System.Web.

Config.HttpHandlerConfigHandler " />

<section name="sessionState" type = " System.Web.

Config.SessionStateConfigHandler " />

<section name=" globalization " type = " System.Web.

Config.GlobalizationConfigHandler " />

<!-- Additional configsection declarations go here -->

</configSections>

<appSettings>

<!--custom application settings go here-->

</appSettings>

<system.web>

<compilation defaultLanguage="vb" debug="true"> <!-- all compiltion config is here -->

</compilation>

<customErrors mode="RemoteOnly"> <!-- error config goes here -->

</customErrors>

<authentication mode="Windows">

<!-- authentication settings controlled here --> </authentication>

<authorization>

<! — Allow/Deny all users , roles--> </authorization>

<trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true" />

<!-- control trace settings for this web application -->

<sessionState>

<!-- configure session state for this web application --> </sessionState>

<httpHandlers>

<!--configure HTTP Handlers for this web application--> </httpHandlers>

<httpModules>

<!--configure HTTP Modules for this web application--> </httpModules>

<globalization/>

<!-- configure globalization settings -->

</system.web>

</configuration>

Note This code listing is not the full description for the Web.config file; this code simply displays the basic structure of an ASP.NET configuration file.

The preceding code displays the structure of a Web.config file presented in the XML format. As you can see in the code, tags provide structure to the document. In a Web.config file, all the configuration information for an ASP.NET application must reside between the <configuration> and </configuration> tags. The file is divided into three main parts:

§The configuration section handler declaration part contained within the

<configSections> and </configSections> tags. This is the root section, which contains the declaration of all other sections of the Web.config file.

§The application-specific settings in configuration variables in the appSettings section.

§The actual configuration sections in the system.web section. All tags defined in this section control the behavior of the ASP.NET runtime. This section is

a great way to control, change, and manage the behavior of a Web application.

For each configuration section in the file, there should be one <configSections> declaration. Each individual declaration specifies the configuration section name and the type of the configuration section handler. The type attribute is used to specify the configuration section handler class to be associated with the element specified in the name attribute. If the name of the configuration section is other than the default name, an entry must be made in <configSections> to reflect the change. For example, if the Web.config file has session state information defined in a section named anything other than <sessionState>, then an entry for this new section must be made in

<configSections>.

Note <configSections> entries can be made even if the default section names are being used. Of course, this is redundant.

ASP.NET Configuration Sections

The Web.config file is used to configure the ASP.NET applications and contains several configuration section handlers that are used to process the configuration settings. This section describes these configuration sections in detail.

<configuration> section

The <configuration> section is the root configuration section for all the ASP.NET configuration files. This is a special tag that encapsulates all other sections in the file. The syntax is as follows:

<configuration>

</configuration>

<configSections> section

The <configSections> section contains a list of the configuration section handlers associated with each configuration section. When you want to devise your own section handlers, you must declare them in the <configSections> section. The syntax is as follows:

<configSections>

<section name="config section element name" type = "Type"/>

</configSections>

The two attributes Name and Type are described as follows:

§Name: Used to specify the name of the element that will contain the configuration data.

§Type: Used to specify the configuration section handler class to be associated with the element specified in the Name attribute.

Соседние файлы в папке c#