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

ASP .NET Web Developer s Guide - Mesbah Ahmed, Chris Garrett

.pdf
Скачиваний:
37
Добавлен:
24.05.2014
Размер:
7.32 Mб
Скачать

480 Chapter 11 • Creating an XML.NET Guestbook

Figure 11.4 Sample ASPX Code add.aspx (Basic Version)

01: <%@ Page Language="VB" EnableSessionState="False"%> 02:

03: <%@ Import Namespace="System.IO" %> 04: <%@ Import Namespace="System.Data" %> 05: <html>

06: <head>

07: <title>Add Entry</title> 08: </head>

09:<script language="VB" runat="server" >

10:<!— event handling code here—>

11:</script>

12:</head>

13:<body topmargin="0" leftmargin="0" rightmargin="0" marginwidth="0" marginheight="0">

14:<br>

15:<br>

16:<h3 align="center">Guestbook Post Page.</h3>

17:<br>

18:<asp:label id="err" text="" style="color:#FF0000" runat="server" />

19:<asp:Panel id=pnlAdd runat=server>

20:<form action="add.aspx" runat=server>

21:<table border="0" width="80%" align="Center">

22:<tr>

23:<td><b>Sign-in My GuestBook</b></td>

24:<td> </td>

25:</tr>

26:<tr>

27:<td>Name :</td>

28:<td><asp:textbox text="" id="Name" runat="server" /> <asp:RequiredFieldValidator ControlToValidate=Name display=static runat=server>*</asp:RequiredFieldValidator></td>

29:</tr>

30:<tr>

Continued

www.syngress.com

Creating an XML.NET Guestbook • Chapter 11

481

Figure 11.4 Continued

31:<td>E-Mail :</td>

32:<td><asp:textbox text="" id="Email" runat="server"/> <asp:RequiredFieldValidator ControlToValidate=Email display=static runat=server> *</asp:RequiredFieldValidator> <asp:RegularExpressionValidator runat="server"

ControlToValidate="Email" ValidationExpression="[\w-]+@([\w-]+\.)+[\w-]+" Display="Static"

Font-Name="verdana" Font-Size="10pt">Please enter a valid e-mail address</asp:RegularExpressionValidator>

33:</td>

34:</tr>

35:<tr>

36:<td>Comments :</td>

37:<td><asp:Textbox textmode=multiline id="Comments" columns="25" rows="4" runat="server" />

38:</td>

39:</tr>

40:<tr>

41:<td colspan="2" >

42:<asp:Button Text="Submit Post" onClick="AddClick" runat="server" /></td>

43:</tr>

44:</table>

45:</form>

46:</asp:Panel>

47:

48:<asp:Panel id=pnlThank visible=false runat=server>

49:<p align=center><b>Thank you for posting in my Guestbook!</b><br>

50:<a href="viewbook.aspx">Click here </a> to view GuestBook.

51:</p>

Continued

www.syngress.com

482 Chapter 11 • Creating an XML.NET Guestbook

Figure 11.4 Continued

52:</asp:Panel>

53:</body>

54:</html>

It may look daunting at first, but it really is quite simple. Remember that in ASP.NET you first should declare the language the page is going to be using. While it is redundant, since the language declaration on the <script> tag determines the actual language use, it is still a good coding practice to get into. Lines 2 through 4 declare the namespaces that you are going to use—System, System.IO, and System.Data. Lines 5 through 8 just display the HTML code that needs to be in every single HTML page.

You then hit the script tag that controls the Submit button event (lines 9 through 10). For now it’s just a placeholder for the code you’ll be adding in later. Notice that the code is placed at the head of the html file, which means that it will be processed before anything else.You’ll look at the Submit button event after you dissect this portion of the ASP.NET page.

Understanding the pnlAdd Panel

On line 19 of Figure 11.4, pnlAdd is declared; it is the name of the panel that contains the programming code displaying the messages and text boxes that the user will be viewing on the page, in order to enter the guestbook entry data; e.g., the name area, the name entry textbox, the e-mail area, the e-mail entry textbox, the comment area, the comment entry textbox, and the Submit button. In other words, it is your run-of-the-mill HTML form but with ASPX. In reality there are only two “normal” form objects; the name textbox is your standard text object, and the comment area is your standard multilane textbox.

The e-mail area, however, is another story.Take a look at the behemoth of a line that you’ll find in line 32:

<asp:textbox text="" id="Email" runat="server"/

><asp:RequiredFieldValidator ControlToValidate=Email display=static

runat=server> *</asp:RequiredFieldValidator>

<asp:RegularExpressionValidator runat="server"

ControlToValidate="Email"

ValidationExpression="[\w-]+@([\w-]+\.)+[\w-]+"

Display="Static"

www.syngress.com

Creating an XML.NET Guestbook • Chapter 11

483

Font-Name="verdana" Font-Size="10pt">Please enter a valid

e-mail address</asp:RegularExpressionValidator>

Starting from the top, you find your standard ASPcontrol declaration as a textbox with its default text set to empty and an ID of “E-mail.” Right after it comes the ASP control declaration for RequiredFieldValidator set to validate the control labeled “E-mail” and with a static display.You then implement two types of validation to the field.The first validation is through the RegularFieldValidator control:

<asp:RequiredFieldValidator ControlToValidate=Email display=static

runat=server>This is required.</asp:RequiredFieldValidator>

All you are doing here is a quick check to see if the field is empty or not. If the user skips the field and leaves it empty, then a little message in red shows up saying that “This is required.”You don’t have to use that text but it works for this example. Our second round of validation begins right after that line with the more intense RegularExpressionValidator object:

<asp:RegularExpressionValidator runat="server"

ControlToValidate="Email"

ValidationExpression="[\w-]+@([\w-]+\.)+[\w-]+"

Display="Static"

Font-Name="verdana" Font-Size="10pt">Please enter a valid

e-mail address</asp:RegularExpressionValidator>

Developing & Deploying…

Stricter E-Mail Validation

The method of e-mail validation demonstrated in this chapter is not the only option available to you. There is a stricter method for e-mail validation that would only enable the user to input a .com, .org, .edu, .mil,

.gov, or .net:

ValidationExpression = "^[\w-]+@[\w-]+\.(com|net|org|edu|mil|gov)$"

www.syngress.com

484 Chapter 11 • Creating an XML.NET Guestbook

You first set the object to bind itself to the E-mail control. It will be analyzing the contents within the E-mail object to see if it falls under the Validation Expression that it has been given; in this case, it checks to see that an “@” symbol as well as a “.” is present within the string.You may want to read up on RegEx to fully understand what variables can be used with Regular Expressions.

Adding a Thank-You Panel with PnlThank

All you are doing here is declaring a panel that will show up after a successful guestbook entry has been added to the XML file.The link in order to view the guestbook is declared and set.Very simple and very quick, to the point, starting on line 48 (Figure 11.4):

<asp:Panel id=pnlThank visible=false runat=server>

<p align=center><b>Thank you for posting in my Guestbook!</b><br> <a href="viewbook.aspx">Click here </a> to view GuestBook.

</p>

</asp:Panel>

Exploring the Submit Button Handler Code

Now that you have established your design and layout, you can take a look at the code that actually handles the addition of new entries into the guestbook.The basic functionality of this code is to react to the Submit button when pressed, and write the necessary items to the XML file. Figure 11.5 walks you through an overview of the Submit button code.

Figure 11.5 Submit Button Handler Code for add.aspx (Basic Version)

01: Sub AddClick(Sender As Object, E As EventArgs) 02:

03:Try

04: Dim dataFile as String = "gb/gbook.xml" 05:

06:'the next line wraps

07: Dim fin as New FileStream (Server.MapPath(dataFile), FileMode.Open,FileAccess.Read,FileShare.ReadWrite)

08:

09: 'this line also wraps

Continued

www.syngress.com

Creating an XML.NET Guestbook • Chapter 11

485

Figure 11.5 Continued

10: Dim fout as New FileStream (Server.MapPath(dataFile),

FileMode.Open,FileAccess.Write,FileShare.ReadWrite)

11:

12:Dim guestData as New DataSet()

13:Dim newRow as DataRow

14:err.Text = ""

15:guestData.ReadXml(fin)

16:fin.Close()

17:newRow = guestData.Tables(0).NewRow()

18:newRow("Name")=Name.Text

19:newRow("Chrono")=DateTime.Now.ToString()

20:newRow("Email")=Email.Text

21:newRow("Comments")=Comments.Text

22:guestData.Tables(0).Rows.Add(newRow)

23:guestData.WriteXml(fout, XmlWriteMode.WriteSchema)

24:fout.Close()

25:pnlAdd.Visible=false

26:pnlThank.Visible=true

27:

28:Catch edd As Exception

29:err.Text="Error writing file at: " & edd.ToString()

31:

End Try

32:

33:End Sub

34:</script>

Line 1 starts you off with your VB code, declaring itself a code segment that is run on the server-side and written using VB. Line 1 uses an ASP.NET form subnamed “AddClick”; this code segment will be providing all of the functionality of the Submit button.

On line 3, you start taking advantage of one of VB’s newest and very useful feature, error trapping.Your try/catch segment starts out by declaring a variable to store the location of your XML file, which can be any directory.You can just

www.syngress.com

486 Chapter 11 • Creating an XML.NET Guestbook

assume that for this example it’s in the gb directory on the root folder of the site. With the location of the file stored, you can open up a FileStream object to open and process the XML file for you. FileStream needs to know the actual location of the file (not the virtual location) of the file, so you use Server.MapPath() to return the actual location of the file to your FileStream object, which you can then open (FileMode.Open) and start reading (FileAccess.Read).You can also tell FileStream how to handle other events, such as sharing; by telling FileStream to allow read/write sharing of the file (FileShare.ReadWrite), you don’t have to worry about your XML file suffering from any file locking, which would prevent any other user from editing the file and getting them a nasty error.

Migrating …

Online Forms

As you have noticed and learned throughout this book, ASP.NET enables programmers to use Web forms, which can be described as the VB6.0 desktop form. In this particular example, your “AddClick” sub would be placed within the OnClick() event for whatever button you wanted to use as your trigger for this action. One other little trick is to view each “panel” as a small form within an mdi, namely the browser window, with their own “hide” and “show” features.

With your XML file stored within the fout object (line 10 in Figure 10.5) you can start to create the object that will handle parsing the data, DataType, and properly formatting it and writing to the XML file, DataRow. Specifically, DataType will handle reading the information and transforming it to a table format. DataRow will then use the information stored within your DataType object to create a new row with the columns that it finds within the DataType object. In other words, when DataType reads your XML file, it will see the root element “gbook” as your table,“gbooky” as your rows, and all the information within “gbooky” as columns. It will write the information out accordingly to the XML file. It will know what it’s writing since it’s using the inline schema (Figure 10.2) to write to the file per the schema, using the WriteXML class of the DataType object and having it write the stream matching the XMLSchema (XMLWriteMode.WriteSchema).You then hide the panel that contains the text

www.syngress.com

Creating an XML.NET Guestbook • Chapter 11

487

boxes and Submit button, and make the panel that contains the “Thank You” message. Figures 10.6 and 10.7 show the basic add.aspx file before and after filling out a new entry.

Figure 11.6 Before Adding a New Entry

Figure 11.7 After Adding a New Entry

www.syngress.com

488 Chapter 11 • Creating an XML.NET Guestbook

Developing & Deploying…

File Locking

File Locking is a basic response to multiple users trying to read and modify the same file at around the same time. I say at “around” the same time because File Locking will take place if the file is accessed at the same time, or if access is attempted after someone already has access to it. By preventing multiple users from reading and writing the file, you avoid file corruption and constant backup restorations. File Locking allows a temporary “lock” to be placed to the file that allows for changes to be made one after the other without damaging the integrity of the file.

Viewing the Guestbook

One line of actual ASPX code—that’s about as simple as it gets, and done just by using the built-in XML server control.You may remember in Chapter 3 that ASP.NET has several controls built in to facilitate many different HTML functions, such as displaying radio buttons and handling forms, which allows ASP.NET to generate items fairly on-the-fly. XML is no exception to this rule.

Displaying Messages

Here is our one-line masterpiece, as shown in Figure 11.8. In essence, all we did to get the sample output shown in Figure 11.8 was just to tell the ASP.NET XML control to read the data in gbook.xml, and to transform it according to the XSL information in gbook.xsl. It is displayed in Figure 11.9 and can be found in the gb folder in the Basic directory on the CD that accompanies this book. Figure 11.10 shows us the output.

Figure 11.8 viewplain.aspx (Basic Directory)

01: <html>

02: <head>

03: <title>XML Control Test</title>

04: </head>

05: <body bgcolor="#000000">

Continued

www.syngress.com

Creating an XML.NET Guestbook • Chapter 11

489

Figure 11.8 Continued

06: <!-- line 7 wraps -->

07: <asp:xml id="gbook" DocumentSource="gb/gbook.xml"

TransformSource="gb/gbook.xsl" runat="server"/>

08: </body>

09: </html>

Figure 11.9 gbook.xsl

01: <?xml version="1.0"?> 02:

03: <!— this line wraps —>

04: <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

05:

06: <xsl:template match="/"> 07:

08: <xsl:for-each select="gbook/gbooky">

09:<table width = "400">

10:<!-- this line wraps -->

11:<tr><font color="#FFFFFF" face="Arial Black"><xsl:value-of select="Name"/></font></tr>

12:

13:<!-- this line wraps -->

14:<tr><font color="#FFFFFF" face="Arial Black"><br /><xsl:value-of select="Chrono"/></font></tr>

15:

16:<!-- this line wraps -->

17:<tr><font color="#FFFFFF" face="Arial Black"><br /><xsl:value-of select="Email"/></font></tr>

18:

19:<!-- this line wraps -->

20:<tr><font face="Arial, Helvetica, sans-serif" size="2" color="#C7B29A"><p><xsl:value-of

Continued

www.syngress.com