An XPathNavigator class object is used to perform queries against an XPathDocument document.. An XPathNavigtor class object is instantiated to perform XPath queries against the document:
Trang 1Figure 9.11 shows the program after you click Run XPath Queries.When
you click the button, the program does a number of queries against the sonnel.xml file and writes the results into the listbox on the form Figure 9.12shows a portion of the XML contained in the personnel.xml file used to gen-erate the queries
per-Figure 9.12Generating Queries (personnel.xml)
Trang 2<Zip>97206</Zip>
</Location>
</Employee>
Figure 9.13 contains the relevant portions of the source code for the XPath
sample Source code inserted by the Visual Studio.NET designer has been omitted
Figure 9.13Relevant Portions of Source Code (XPathForm.cs)
Trang 3private string m_strOutput;
public Form1() {
// Do XPath queries on both XPath Documents and // DOM-based XML documents
doXPathDocumentQueries();
doXmlDocumentQueries();
Figure 9.13Continued
Trang 4"*** Beginning XPathDocument Queries ***\r\n\r\n";
// Load the XML document into a read-only XPathDocument
// and instantiate a navigator for queries.
XPathDocument doc = new XPathDocument( "personnel.xml" );
XPathNavigator navigator = doc.CreateNavigator();
m_strOutput += "*** Show All Wages ***\r\n\r\n";
// Find all Employee/Wage elements in the document and
// display the wage information on-screen
XPathNodeIterator iterator =
Figure 9.13Continued
Trang 5while ( iterator.MoveNext() ) {
m_strOutput += iterator.Current.Name + ": ";
m_strOutput += iterator.Current.Value + "\r\n";
}
m_strOutput +=
"\r\n\r\n*** Show All Employees in Seattle ***\r\n\r\n";
// Find all employees in the Seattle office and display // their names on-screen
iterator = navigator.Select( "//Employee[Location/Zip='98103']" );
while ( iterator.MoveNext() ) {
XPathNavigator nav2 = iterator.Current;
"\r\n\r\n*** Salaried Employee Average Wage ***\r\n\r\n";
// Calculate the average salary for all salaried employees // in the company and display on-screen
Int32 nAverage = (Int32)(Double)navigator.Evaluate(
Figure 9.13Continued
Trang 6"\r\n\r\n*** Beginning XML Document Query ***\r\n\r\n";
// Load the XML document into a DOM-based XML document
XmlDocument doc = new XmlDocument();
Trang 7The program runs through two sets of XPath queries against the personnel.xml file.The first set of queries is against XML loaded into an object of type
System.Xml.XPath.XPathDocument.The XPathDocument class has been optimized
to work with XPath queries It supports read-only access to the document An
XPathNavigator class object is used to perform queries against an XPathDocument
document Here is the code that instantiates and loads an XPathDocument with XML from a disk file An XPathNavigtor class object is instantiated to perform
XPath queries against the document:
XPathDocument doc = new XPathDocument( "personnel.xml" );
XPathNavigator navigator = doc.CreateNavigator();
The Select method of the XPathNavigator class is used to perform a query
against the XML document It takes an XPath statement as an argument.The lowing query returns all of the <Wage> elements in the XML document:
The select statement takes an XPath expression as an argument and returns an
XPathNodeIterator object, which is used to traverse the node list returned.The Current property of XPathNodeIterator points to the current position in the node
list returned form the Select method call.The position is undefined until the first
Figure 9.13Continued
Trang 8call to the MoveNext method As each <Wage> element is encountered in the
returned node list, the element tag and value are saved for later display in the
listbox on-screen.The Name property of Current returns the element tag and the
Value property of Current returns the text contained within the <Wage> element.
XPath Expressions
A brief explanation of XPath statements is in order XPath expressions
use what is termed a location path, which is made up of one or more
location steps that are separated by a “/” or by a “//” The “/” character
indicates an absolute path, and the “//” characters indicate a relative
path from the current node A location step contains an axis and a node
test, and it may contain predicates The axis indicates the direction of
the query from the current node Examples are child, ancestor, and
descendent The node test is either the name of a node in the document,
the wildcard character(*), or one of several node tests such as node()
and text() The predicate is used to filter the node test to pinpoint a
spe-cific set of nodes A predicate is contained within brackets Here are two
examples of XPath expressions:
■ In the XPath expression descendent::Employee/Wage,
descendent indicates the axis and Employee/Wage indicates
the node test There is no predicate in this case The
expres-sion returns the Employee/Wage descendents of the current
node.
■ In the XPath expression “//Employee[Location/Zip=’98103’],
the “//” indicates the axis, Employee indicates the node test
and [Location/Zip=’98103’] indicates the predicate The
expression returns the Employee elements with a Location/Zip
element whose value is “98103”.
These are relatively simple examples You can combine extremely
complex combinations of axes, node tests, and predicates to create
extremely powerful queries against XML documents using XPath.
Developing & Deploying…
Trang 9The only real difference with this query is that you need to use a second
instance of XPathNavigator Each node in the node list is an <Employee> ment.The second XPathNavigator object is needed so that you can maintain your
ele-position in the node list of <Employee> elements
The last query against the XPathDocument object does a summary query It
returns a result, not a node list Here is the code, which calculates the averagesalary of all salaried employees:
Int32 nAverage =
(Int32)(Double)navigator.Evaluate(
"sum(//Employee[Salaried='true']/Wage) div count(//Employee[Salaried='true'])" );
When performing summary queries, the Evaluate method is used instead of the Select method It also takes an XPath expression as an argument.You can see
from this example that the XPath expressions can get quite complex
The second set of queries is done against an XmlDocument object As we tioned earlier, an XPathDocument is read-only So, if you want to use XPath
men-directly against an XML document and update the document, you will need to
use an XmlDocument object Here is the relevant code from the sample:
XmlDocument doc = new XmlDocument();
doc.Load( "personnel.xml" );
Trang 10This example simulates shutting down the Portland office.The <Active>
element is set to false for all employees in the Portland office First, a new
XmlDocument object is instantiated and then loaded using the Load method Next,
the XPath query against the document is executed using the SelectNodes method
of the System.Xml.Node class It takes an XPath expression as an argument and
returns an XmlNodeList object In this case, it is a node list containing each
<Active> element for each employee in the Portland office.The node list is
tra-versed using the foreach statement, and the text value associated with the
<Active> element is set to false Assigning the string “false” to the InnerText
prop-erty accomplishes this
Working with XSL
The previous section shows how XPath is used as a general query tool In this
sec-tion, you will see XSLT used to transform XML documents to a different format
XSL stylesheets will use XPath expressions to select node lists for transformation
Our sample simulates a real-world scenario.The scenario is that the human
resources division of a company named EntegraTech maintains personnel data in
an XML file named personnel.xml Another division of the company maintains a
Web site that includes some reports based on personnel information.The Web
site uses XSL stylesheets to build HTML Web pages from personnel information
contained in XML files Unfortunately, the Web site stylesheets expect the XML
to be in a different format than the format in the personnel.xml file supplied by
the HR department.The sample code transforms the XML into the format that
the Web site stylesheets expect and then builds one of the HTML reports XSL
Trang 11the files on the CD that accompanies this book, in the XSL directory.You mayneed to copy the files to the directory you run the sample from.The full sourcecode for the sample is in the XSL directory as well.The file that contains thesource code is named XSLForm.cs Figure 9.14 shows the running program.
Figure 9.14 shows the program after you click Run XSL Sample.When
you click the button, it transforms the personnel.xml file by using an XSLstylesheet, displays the original XML file and the transformed XML file in the
listbox, and writes the transformed XML to another file on disk.The Show
HTML Reportbutton then becomes active Clicking the button runs a secondXSLT stylesheet, which creates a HTML document from the newly transformedXML Internet Explorer is then launched and displays the HTML report Figure9.15 shows the report displayed in Internet Explorer
Figure 9.14The XSL Sample Program
Figure 9.15The EntegraTech HTML Report
Trang 12You have seen the structure of the personnel.xml file already Figure 9.16
shows it again for comparison with the format expected by the Web site Figure
9.17 shows the format of the XML expected by the Web site Comparing these
two will help in understanding what the XSL stylesheet must do
Figure 9.16Partial Contents of the personnel.xml File
Trang 13The file salariedpersonnel.xsl is the stylesheet that is used to convert from thefirst XML representation to the second It is shown in Figure 9.18.
Figure 9.18The Stylesheet (salariedpersonnel.xsl)
<xsl:value-of select="FirstName"/><xsl:text> </xsl:text>
<xsl:value-of select="MiddleInit"/><xsl:text> </xsl:text>
Trang 14An XSL stylesheet uses pattern matching to process an XML document.The
XSLT processor begins processing the XML document and looks for statements
in the XSL script, called rules, which match nodes encountered in the XML
doc-ument Near the top is the rule for the root element of the document:
When the root element of the original XML document is encountered, the
previous statements are executed In this case, a <Salaried> element is created and
the child nodes of the root element are processed by the <xsl:apply-templates/>
statement.When the <Employees> element is encountered, execute the
fol-lowing statements:
<xsl:template match="Employees">
<xsl:apply-templates select="Employee[Salaried='true']"/>
</xsl:template>
The select attribute of an <xsl:apply-templates> statement contains the pattern
to match in an XML document.The pattern matching string can be an XPath
expression.This is where XPath comes into play in XSL stylesheet processing
The preceding XSL script statements ignore any <Employee> elements that do
not contain a child element <Salaried> with a text node whose value is “true” In
effect, you execute a rule that returns all <Employee> elements that represent
salaried employees and ignore all other nodes encountered in the XML document
The following statements process the matching salaried employee elements:
<xsl:template match="Employee[Salaried='true']">
<Employee>
<Name>
<xsl:value-of select="FirstName"/><xsl:text> </xsl:text>
<xsl:value-of select="MiddleInit"/><xsl:text> </xsl:text>
<xsl:value-of select="LastName"/>
Trang 15at the relevant portions of the source code that perform the XSLT transformation.
Figure 9.19XML-to-XML Transformation in the Source Code (XSLForm.cs)
private void doXMLToXMLTransform()
{
// Show the original document on-screen
m_strOutput = "*** personnel.xml - Original XML ***\r\n\r\n";
showXMLDocument( "personnel.xml" );
// Load the new document, apply an XSL tranformation to
// it and save the new document to disk
XPathDocument docXPath =
new XPathDocument( "personnel.xml" );
XslTransform xslTransform = new XslTransform();
Trang 16StringWriter writerString = new StringWriter();
XmlTextWriter writer2 = new XmlTextWriter( writerString );
In the doXMLToXMLTransform method, an XPathDocument object is
instanti-ated and loaded with XML contained in the personnel.xml file.Then, an
XslTransform object is instantiated.The XslTransform object is the engine used to
perform XSLT transformations on XML documents in the NET Framework
After the transformation is complete, the results are written to a new XML
file on disk An XmlTextWriter object is created that writes the transformed file to
disk.The file that is created is named salaried.xml, which is the first parameter
passed to the XmlTextWriter constructor.
The Load method of the XslTransform class loads the XSL stylesheet from
disk Finally, the transform is executed by calling the Transform method of the
XslTransform class object The Transform method takes the XML document object
and the text writer objects as parameters.The second parameter of the Transform
method is used to pass additional runtime arguments that are used in the
stylesheet Because you have no runtime arguments, it is left null After the
trans-form is complete, the XmlTextWriter object is closed to complete the writing of
Figure 9.19Continued
Trang 17StringWriter classes work together to convert an XML document on disk to an
in-memory string
As you can see, very little source code is necessary to perform the complextask of transforming an XML document to another format.You have now con-verted the original document to the new format that is needed to generate theHTML reports Let’s take a look in Figure 9.20 at the XSL stylesheet used totransform the converted XML to HTML
Figure 9.20The Stylesheet (salariedreport.xsl)
<h2 align="left">Seattle Office Salaried Employees</h2>
<table border="0" width="100%">
<xsl:apply-templates select="Employee[Location='98103']" />
</table>
<p></p>
<h2 align="left">Portland Office Salaried Employees</h2>
<table border="0" width="100%">
<xsl:apply-templates select="Employee[Location='97206']" />
</table>
Trang 18Briefly, this stylesheet creates an HTML document for display in a Web
browser.You can see the familiar pattern matching statements that we saw in the
previous stylesheet.This stylesheet creates two HTML tables that display the
names of employees and their wages.The first table shows the employees in the
Seattle office, and the second shows the employees in Portland Figure 9.21 shows
the C# source code used to perform the transformation from XML to HTML
Figure 9.20Continued
Trang 19Figure 9.21XML to HTML Transformation in the Source Code (XSLForm.cs)
private void doXMLToHTMLTranformation()
{
// Load the XML document, apply an XSL transformation to it,
// resulting in HTML which is written to disk.
XPathDocument docXPath = new XPathDocument( "salaried.xml" );
XslTransform xslTransform = new XslTransform();
private void btnShowHTML_Click_1(object sender,
Explorer So, when the Start method is called with an HTML filename as the
parameter, Internet Explorer is launched and the HTML file passed in is
Trang 20dis-XSLT: Debugging Stylesheets
XSLT is a powerful technology for transforming XML documents The
XPath expressions used in XSL stylesheets to match nodes in an XML
document can be very complex It can become difficult to debug what
is happening in stylesheet when the output is not what you expect To
aid in debugging problems in XSL stylesheets, it is often helpful to
develop the stylesheet in small increments rather than creating the
com-plete stylesheet at one time Write one rule at a time and run your
trans-formation, verifying that the node list returned is what you expect.
When you do encounter output that is not what you expect, you can be
relatively sure the problem lies in the last rule you added This can save
you valuable time.
Debugging…
Trang 21XML has emerged as the Web standard for representing and transmitting dataover the Internet.The W3C has worked to establish standards for XML andrelated technologies including XML DOM, XPath, XSL, and XML schemas.XML DOM is an API that is used to create, modify, and traverse XML docu-ments XPath is a language that is used to query XML documents XSL translatesXML documents from one format to another format XML schemas define thestructure and data types of the nodes in an XML document All of these tech-nologies are industry standards backed by the W3C
Microsoft has embraced XML and provides implementations in the NETFramework for many of the technologies standardized by the W3C.The XML
DOM API is fully supported in the NET Framework by the XmlDocument class The XmlDocument class allows you to create XML documents from scratch, per-
sist them to a number of different data stores and read them back into memoryfrom those data stores Once in memory, an XML document can be traversed andmodified including adding, updating, and deleting nodes in the document
In conjunction with ADO.NET and the XML support in the NET
Framework, the ability to work with data as XML or as relational data is available
using C#.The XmlDataDocument class is used to read data into a DataSet class object from an XML disk file or from a database Once the XmlDataDocument is
created, the data is available for access relationally as table and columns or asXML through the DOM API XML schema support is provided by the NETFramework to specify the structure and data types of the data in XML docu-
ments including the XmlDataDocument class.The relationship between the
ADO.NET DataSet class and the XML API provides a powerful foundation to
develop end-to-end applications storing data in databases on both ends of a ness process and using XML to transmit the data between
busi-The NET Framework supports XPath queries against XML DOM
docu-ments or the highly optimized XPathDocument class.The XPathNavigator class works in conjunction with the XPathDocument to issue XPath queries against
XML documents in read-only mode XPath queries can also be issued against the
XmlDocument class providing a convenient method to locate a specific node in a
document and then modify it XPath queries are also instrumental in XSL formations.The NET Framework fully supports XSL transformations as imple-
trans-mented in the XslTransform class XML-to-XML transformations as well as XML
to other formats are implemented with a minimum of source code
Trang 22Use of XML is found throughout the NET Framework and is instrumental
in the implementation of Web Services, as you will find out in Chapter 11
Because XML is critical to NET, developers benefit by first class, standards-based
support for XML in the NET Framework.This chapter provided you with the
information you need to start taking advantages of that support in your own
XML-based applications
Solutions Fast Track
Introduction to XML
; XML has emerged as the Web standard for representing and transmitting
data over the Internet
; The W3C has standardized XML and related technologies including
XML DOM, XPath, XSL, and XML Schemas
; The NET Framework provides first class support for W3C-backed
XML standards
; XML is prevalent throughout the NET Framework including use in
configuration files, C# source code comments, and Web Services
Working with XML DOM
; An XML document can be represented as a tree of nodes in memory,
which can be traversed and modified using an implementation of the
XML DOM API
; The XmlDocument class is the NET implementation of XML DOM.
; The XmlDocument class provides the ability to create an XML document,
add elements and attributes to a document, update nodes in the
document, delete nodes from the document, save the document to
persistent storage, and load the document into memory from persistent
storage
Trang 23Working with XML and Relational Data
; The DataSet class is an in-memory representation of relational data using
tables, columns, and rows
; The XmlDataDocument class has a DataSet object as a member variable XML documents can be read into an XmlDataDocument object instance
and can then be manipulated using XML DOM method calls or by
relational method calls against the DataSet member variable.
; In conjunction with ADO.NET, the XML support in the NET
Framework can be used to build powerful applications that access data asXML or relational database data when appropriate.The conversionbetween the two types of data is trivial to implement
Working with XPath and XSL Transformations
; XPath support is built into the NET Framework for use as a purpose query tool or as part of XSL stylesheets
general-; XPath queries can be performed against the read-only XPathDocument class using the XPathNavigator class.The XmlDocument class can also be
queried using XPath to locate a node in a document, which can then bemodified if desired
; XSL Transformations are implemented using the XslTransform class of the
.NET Framework allowing transformation of XML documents to otherformats including XML and HTML
Trang 24Q: What W3C level of support is provided in the XML classes supplied with the
.NET Framework?
A: The XmlDataDocument class supports W3C DOM Core Level 1 and Core
Level 2 specifications.The XmlSchema class supports W3C XML Schemas for
Structures and the XML Schemas for Data Types specifications.The
XslTransform class supports the XSLT 1.0 specification See the W3C Web site
for details on the specifications at: www.w3c.org
Q: Which set of XML classes should I use to implement my project?
A: That depends on your needs and can be difficult to say Here though are
some rules of thumb If you need fast-forward, read-only access to the data,
use one of the XmlReader-derived classes, such as XmlTextReader If you need
to do extensive updates to the document, use the XmlDocument class If you
want fast query capabilities, use the XPathDocument class If you want to read
and write from a database and then manipulate the results as XML, use the
XmlDataDocument class.
Q: I have two tables in a DataSet and have added a DataRelation, which
estab-lishes a parent-child relationship.When I write the XML file to disk, the
parent-child relationship isn’t represented.What is wrong?
A: Most likely you did not set the Nested property of the DataRelation to true If
it is false, the elements associated with the child in the relationship will all
appear after the parent elements in the XML file
Frequently Asked Questions
The following Frequently Asked Questions, answered by the authors of this book,
are designed to both measure your understanding of the concepts presented in this chapter and to assist you with real-life implementation of these concepts To
have your questions about this chapter answered by the author, browse to
www.syngress.com/solutions and click on the “Ask the Author” form.
Trang 25Q: How do I create an XmlDocument instance from a string?
A: Here are two methods One method is to use this:
doc.Load( new XmlTextReader( new StringReader( myString ) ) )
Another is to write this:
doc.InnerXml = myString
Trang 26Solutions in this chapter:
■ Introducing the ASP.NET Architecture
■ Working with Web Forms
■ Working with ADO.NET
; Solutions Fast Track
; Frequently Asked Questions
Trang 27ASP.NET is Microsoft’s upgrade to Active Server Pages (ASP) ASP.NET tecture is very well woven into the NET Framework to provide a powerful
archi-event-driven programming model.The new feature of code-behind allows true
sep-aration of code and design Also, you can write ASP.NET pages in any of themanaged languages, and the code is compiled to give high performance
This chapter acquaints you with writing Web Forms and database-driven Webapplications.You will see how you can leverage the use of XML data in the.NET Framework within ASP.NET applications, through “real world” examples(a shopping cart and a message board).We also explain how to e-mail fromASP.NET, which includes an example of a simple e-mail ASP.NET page
In all the examples, we cover a broad range of new features in ASP.NET One
of these is the capability to have custom validation embedded into the pages fromJavaScript (.js) files, which originate from the root on the server; ASP.NET has awhole host of validation controls to use Also the backbone of the NET archi-tecture is built on XML.The use of XSL/Transforms on XML data from
DataSets provide the developer with the ability to create custom content for
var-ious clients with minimal program logic overhead.We demonstrate this in themessage board example included in this chapter
ASP.NET is a more robust way to bring applications to the Web Gone arethe endless lines of “spaghetti code” and with it the ambiguous debugging.WithASP.NET, you will be able to create cross-browser, cross-platform applicationsthat you can port across the Web
Introducing the ASP.NET Architecture
In the ASP.NET architecture, the NET Framework works with the OS A Webclient requests a Web Form (ASPX) resource, which is delivered through theInternet Information Server (IIS) combining all additional resources, which mayinclude a database,Web Service, COM component, or a component class All ofthese are delivered through a compiled assembly (DLL) from the Web application,which sits in the bin directory within IIS’s Web root See Figure 10.1 for a con-ceptual overview of the ASP.NET architecture ASP.NET includes some new fileextensions for the different types of pages you can create in your solutions.Thenew extensions allow ASP.NET to sit alongside ASP 3.0 on the same server with
no filename conflicts Here is a list of the four most commonly used extensions:
Trang 28■ .aspx Used for Web Forms and is the replacement for the standard asp
extension used in ASP 3.0
■ .ascx Used to denote a reusable page components or control
■ .asmx Used to denote a Web Service
■ .asax Used for the Global file and is the replacement for the asa
extension
Each of these page types can have a code-behind page where you can store
program logic Note that using code-behind pages makes your code more
mod-ular and helps to hide the program logic from prying eyes, because the
code-behind pages are not stored individually on the server but are part of the
compiled assembly (DLL)
The corresponding code-behind pages would be aspx.vb, ascx.vb, asmx.vb,
and asax.vb respectively if the project was a VB.NET project, or aspx.cs, ascx.cs,
.asmx.cs, and asax.cs respectively if the project was a C# project
ASP.NET Server Controls
You can add three main sets of controls to your Web Form (ASPX page): HTML
server controls,Web server controls, and validation controls
■ HTML server controls Allow you to work with all the properties of
Figure 10.1Overview of ASP.NET Architecture
Web Client Web Client Web Client
IIS NT/2000
ASP.NET Appllication NET Framework Additional Resources Data
Trang 294 or Opera.To provide HTML form elements with the programmingpower of server-side processing, you must add at least two attributes to
the tag in question.The HTML control needs to have the runat attribute set to “server” (runat=“server”) and an ID By doing this, the control is
made available to the server for processing instead of being passed as text
to the browser See Table 10.1 for a list of HTML elements that can beeasily converted into HTML server controls.The following is anexample of a HTML button server control:
<INPUT type="button" id="button1"
value="clickme" runat="server">
Table 10.1HTML Server Controls
Server Control Description
HtmlAnchorControl Access the <a> tag in server processing
HtmlButtonControl Access the <button> tag in server processing
HtmlFormControl Access the <form> tag in server processing
HtmlGenericControl Access the <span>,<div>, <body>, <font>
tag in server processing
HtmlImageControl Access the <img> tag in server processing
HtmlInputButtonControl Access the <input type=”submit”>, <input
type=”reset”>, <input type=”button”>, tag in server processing
HtmlCheckBoxControl Access the <input type=”checkbox”> tag in
HtmlSelectControl Access the <select> tag in server processing
HtmlTableControl Access the <table> tag in server processing
HtmlTableCellControl Access the <td>, and <th> tag in server
processing
HtmlTableRowControl Access the <tr> tag in server processing
HtmlTextAreaControl Access the <textarea> tag in server
processing
Trang 30■ Web server controls A completely new set of controls designed to
interact with the NET environment by the additional properties and
events included, most notably the ability to do a postback.The tags are
XML-based, so they all appear in the same manor as XML elements for
ease of use.Web server controls are defaulted to render HTML 3.2 for
cross browser compliance.Web server controls inherit the System.Web.UI
.Control namespace, which predefines their attributes.Table 10.2 shows a
list of Web server controls.We discuss a number of these in the examples
ahead.The following shows a Button Web server control and a Textbox
Web server control as they would appear on a Web Form (ASPX page):
<asp:button id="button1" runat="server"></asp:button>
<asp:text id="text1" runat="server"></asp:text>
Table 10.2ASP.NET Web Server Controls
Web Server Controls
AdRotator Button Calendar CheckBox CheckBoxList
DataGrid DataList DropDownList HyperLink Image
ImageButton Label LinkButton ListBox Literal
Panel PlaceHolder RadioButton RadioButtonList Repeater
Table TableCell TableRow TextBox XML
■ Validation controls You can have customized validation run on the
client generated by the server through a JS (external JavaScript) file
Table 10.3 shows a list of validation controls.When working with
valida-tion server controls, you must set a couple of attributes.To specify the
control to validate, set the controltovalidate attribute to the ID of the Web
server control you want to validate If you set the display attribute to
static, the validation control will occupy that space permanently (The
position of the control will be held even when the error message is not
visible.This works just like setting the Cascading Style Sheet [CSS]
attribute visibility to hidden), but if you set the display attribute to dynamic,
you can have multiple error messages listed in the same space (the
Trang 31posi-Table 10.3ASP.NET Validator Controls
Validator Control Description
CompareValidator Compares a value entered into a Web server
control against another set value.
CustomValidator Can create your own custom validation for
specific data.
RangeValidator Finds the range between two values on a Web
server control.
RegularExpressionValidator Uses regular expressions to validate a value
entered into a Web server control.
RequiredFieldValidator Ensures that all items are supplied data in a Web
server control.
ValidationSummary Groups the result set of validation control error
messages into a summary for viewing.
ASP.NET Server Controls Do Not
Display Correctly in Netscape 4.x
A lot has happened over the last few years with Netscape and the open source Mozilla project Although the newer versions of Mozilla version 094 and above should handle this fine, Netscape still has a significant
4.x user base When we develop Web front-ends for our clients, we
strive to ensure at least Netscape 4.72 will display and function correctly What’s the issue? It seems that most of the examples showing you how to use server controls in Visual Studio.NET have you drag and drop the control to where you want it on the screen In HTML, this creates span tags with inline style attributes containing “absolute positioning.” Those of us that have dealt with cross-browser Dynamic HTML (DHTML) issues know that this can cause problems in Netscape The solution: Use
“FlowLayout” and good old fashioned HTML elements and tricks for positioning To do this, simply right-click on a page in either Design or
HTML view and switch the pageLayout property to FlowLayout.
Debugging…
Trang 32Working with User Controls
If you have some very useful code written in a current Web Form, and you want
to reuse that code in another Web Form, you can do that with a user control
This is the same as using a server-side include but with all the programming
power of an embedded server control.You can access all the properties of the
User control within your new Web Form page.This allows you to reuse your
code and maintain total control of all the properties in the page
Making your own custom user control is very easy Simply take out the code
that is between the body tags of your current ASPX page, open a new file in
VS.NET, and select Web User Control (this will have an ascx extension), and
paste in the code between the form tags of the control page If you have any
code-behind in your ASPX page, you must add that also.This will be placed in
the code-behind page for the user control Look at this example:
<DIV style="Z-INDEX: 100; LEFT: 10px; WIDTH: 300px; POSITION: relative;
Trang 33<DIV style="Z-INDEX: 101; LEFT: 352px; WIDTH: 264px;
POSITION: absolute; TOP: 24px; HEIGHT: 400px">
Trang 35when you have done this (there is a new directive declared called @Control ):
<%@ Control Language="c#" AutoEventWireup="false"
Trang 36<asp:TextBox id="txtTo" runat="server" AutoPostBack="False">
<asp:TextBox id="txtMessage" AutoPostBack="False" Rows="10"
runat="server" Width="313px" Height="160px">
</asp:TextBox>
Trang 37<asp:Button id="btnEmail" runat="server" Text="Send Email">
</asp:Button>
</td>
</tr>
</TABLE>
<DIV style="Z-INDEX: 101; LEFT: 352px; WIDTH: 264px;
POSITION: absolute; TOP: 24px; HEIGHT: 400px">
<TABLE cellSpacing="1" cellPadding="1" width="300" border="0"
Trang 38Remember that you also need to bring over all the code-behind code as well
into the new user control CS page This is what you should have:
namespace simpleMail
{
Trang 39protected System.Web.UI.WebControls.TextBox txtFrom;
protected System.Web.UI.WebControls.TextBox txtTo;
protected System.Web.UI.WebControls.TextBox txtCC;
protected System.Web.UI.WebControls.TextBox txtSubject;
protected System.Web.UI.WebControls.Button btnEmail;
protected System.Web.UI.WebControls.RequiredFieldValidator fvTxtfrom; protected System.Web.UI.WebControls.RegularExpressionValidator
revTxtfrom;
protected System.Web.UI.WebControls.RequiredFieldValidator rfvTxtto; protected System.Web.UI.WebControls.RegularExpressionValidator revTxtto; protected System.Web.UI.WebControls.RequiredFieldValidator rfvTxtcc; protected System.Web.UI.WebControls.RegularExpressionValidator revTxtcc; protected System.Web.UI.WebControls.TextBox txtMessage;
public WebUserControl1() {
this.Init += new System.EventHandler(Page_Init);
Trang 40#region Web Form Designer generated code
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
You should build this and make sure you do not have any errors Next, you
need to take your new custom user control and add it to a new Web Form page