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

Real - World ASP .NET—Building a Content Management System - StephenR. G. Fraser

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

Next, you load the SqlCommand's parameters with the values passed in through the method's parameters.

Params = m_InsertCommand.Parameters;

Params["@AuthorID"].Value = AuthorID;

Params["@Headline"].Value = Headline;

Params["@Story"].Value = Story;

You use a little trick of exception handling. By including the finally clause of the exception, you are guaranteed that the connection will be closed, even on error. The actual exception is caught in the method that calls this one.

Finally, you open a connection to the database and execute the stored procedure using the ExecuteNonQuery() method.

try

{

m_Connection.Open();

m_InsertCommand.ExecuteNonQuery();

}

finally

{

m_Connection.Close();

}

}

Not that bad, was it? Save, compile, and execute it. Try entering some HTML formatting into the stories. You will see in the next example that they come out formatted as you specified.

Now let's move on to the last example: revisiting the Dynamic Content Viewer.

Updating the Dynamic Content Viewer with ADO.NET

Let's finish off the chapter by revisiting the Dynamic Content Viewer you created in Chapter 6. As you can see in Figure 7-15, the Web page has become much simpler because all the personalization code was removed, thus removing all the validation intrinsic controls because they were no longer needed. A label called lbAuthor was also added in a smaller font so that you can see who wrote the story. All the code needed to create the design is in Listing 7-13.

Figure 7-15: The updated Dynamic Content Viewer

Listing 7-13: DCViewer.aspx

<%@ Page language="c#" Codebehind="DCViewer.aspx.cs" AutoEventWireup="false"

Inherits="Ch07Examples.DCViewer" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

<HTML>

<HEAD> <title>DCViewer</title>

<meta name="GENERATOR" Content="Microsoft Visual Studio 7.0"> <meta name="CODE_LANGUAGE" Content="C#">

<meta name=vs_defaultClientScript content="JavaScript"> <meta name=vs_targetSchema

content="http://schemas.microsoft.com/intellisense/ie5"> </HEAD>

<body >

<form id="DCViewer" method="post" runat="server">

<H1> <FONT color="#66cc00">Welcome to the world of .NET </FONT></H1> <P>

<TABLE id="Table1" cellSpacing=1 cellPadding=3 width="100%" border=0> <TR>

<TD width="20%"><STRONG>Select Story:</STRONG></TD > <TD width ="80%">

<asp:DropDownList id=ddlStories runat="server" > </asp:DropDownList>

</TD> </TR > <TR>

<TD width ="20%"> </TD> <TD width ="80%">

<asp:Button id=bnGetStory runat="server" Text="Get Story"> </asp:Button>

</TD>

</TR > </TABLE>

</P> <P>

<HR width="100%"SIZE="1" > <P>

<asp:Label id=lbAuthor runat="server" Font-Size="X-Small"> </asp:Label>

</P> <P>

<asp:Label id=lbStory runat="server" > </asp:Label>

</P>

</form>

</body>

</HTML>

As you can see in Listing 7-14, there is really nothing new when it comes to coding the functionality of the Web page. You load the drop-down list from the Content table the first time the page is loaded, and all subsequent times you check which value has been selected in the drop-down list and do a SQL select on the Stories view to find it. Then you display the author and story using their respective labels.

Listing 7-14: DCViewer.cs

using System;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Data.SqlClient;

using System.Drawing;

using System.Web;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

namespace Ch07Examples

{

public class DCViewer : System.Web.UI.Page

{

protected System.Web.UI.WebControls.Label lbStory;

protected System.Web.UI.WebControls.Label lbAuthor;

protected System.Web.UI.WebControls.Button bnGetStory;

protected System.Web.UI.WebControls.DropDownList ddlStories;

private void Page_Load(object sender, System.EventArgs e)

{

if (!IsPostBack)

{

string ConnectStr = "server=localhost;uid=sa;pwd=;database=DCV_DB";

string Cmd = "SELECT StoryID, Headline FROM Content";

SqlDataAdapter DAdpt = new SqlDataAdapter(Cmd, ConnectStr);

DataSet ds = new DataSet();

DAdpt.Fill(ds, "Content");

DataTable dt = ds.Tables["Content"];

foreach (DataRow dr in dt.Rows)

{

ddlStories.Items.Add(

new ListItem(dr["Headline"].ToString(), dr["StoryID"].ToString()));

}

}

}

#region Web Form Designer generated code override protected void OnInit(EventArgs e)

{

InitializeComponent();

base.OnInit(e);

}

private void InitializeComponent()

{

bnGetStory.Click += new System.EventHandler(this.bnGetStory_Click); this.Load += new System.EventHandler (this.Page_Load);

}

#endregion

private void bnGetStory_Click(object sender, System.EventArgs e)

{

if (Page.IsValid)

{

string ConnectStr = "server=localhost;uid=sa;pwd=;database=DCV_DB";

string Cmd = "SELECT * FROM Stories WHERE StoryID = " + ddlStories.SelectedItem.Value.ToString();

SqlDataAdapter DAdpt =

new SqlDataAdapter(Cmd, ConnectStr);

DataSet ds = new DataSet();

DAdpt.Fill (ds, "Stories");

DataRow dr = ds.Tables["Stories"].Rows[0];

lbAuthor.Text = "By "+ dr["FirstName"] + ""+ dr["LastName"]; lbStory.Text = dr["Story"].ToString();

}

}

}

}

There are only two things of note in Listing 7-14. The first is how you populate the

DataRow:

DataRow dr = ds.Tables["Stories"].Rows[0];

What is interesting is that because you know that only one row will be retrieved, you can directly populate the DataRow with the first row of the table. Remember that the Rows collection starts with zero.

The second thing is that you need to be careful about the use of the Page.IsValid variable. I had originally coded this example with the retrieving of the stories from the database within the Page_Load() method. Unfortunately, this causes an error because when the page is run an exception is thrown due to Page.IsValid not being set. To fix this problem, Page.IsValid needs to be coded within an event handler with the control property CausesValidation set to its default true (as we have done previously) or the Web page code must call Page.Validate itself.

All that is left to do is save, compile, and execute. All the stories you entered in the previous example show up, and if you formatted them using HTML, the formatting appears as expected.

Summary

This chapter covered in detail the database utilities provided by Visual Studio .NET and ADO.NET.

It started by covering four common database utilities:

§Creating databases

§Adding tables

§Adding views

§Building stored procedures

Next, it discussed ADO.NET and explored some of its common classes. It finished with four example programs:

§Reading data from a database using ADO.NET

§Building an ASP.NET DataGrid

§Inserting data using a stored procedure

§Updating the Dynamic Content Viewer with ADO.NET In the next chapter, you are going to have some fun with XML.

Chapter 8: XML

Overview

Extensible markup language (xml) is the final piece of background information needed before you can delve into building a fully functional content management system (CMS) called CMS.NET. Even though I cover it last, it is hardly unimportant. In fact, depending on how you implement your CMS repository, it could be one of the most important areas I cover.

This chapter is not designed to explore XML in great detail, though like all the previous chapters, it will provide a brief explanation. It is instead focused on how to implement XML in a .NET environment. In particular, this chapter covers how a developer would go about reading, writing, inserting, updating, and navigating XML using C# code.

Microsoft has gone to a lot of effort to simplify XML development. If you have written any XML code using the Microsoft XML Parser (MSXML) or Java, you will see that it has a lot of similarities to the .NET implementation.

This chapter provides all the XML coding knowledge you will need for the rest of the book, but it hardly scratches the surface of what can be done with XML.

This chapter does not even cover XSLT or XML Schemas, which are other related XML technologies. The best way to get a grip on XML coding is to walk through sample programs that show you how to do it instead of just explaining it. This chapter has three simple examples (reading, writing, and updating and inserting XML) and one complex example (showing how to build a NavBar using XML).

What Is XML?

Veteran developers like to make XML sound mysterious when it is anything but. It was designed to be easy: Ease of use was one of the original requirements when XML was being developed.

The first hurdle that a newbie developer must cross is to understand that XML is not a computer language. Rather, it is a metalanguage for defining or specifying how to mark up a document in such a way as to identify its structure.

Okay, one more time in English....

XML is a method for someone to arrange a document so that it is broken up into parts. For example, in the case of a CMS, a document could be broken up by author name, headline, and story. Each of these parts is surrounded by a tag that describes what content is contained within. Listing 8-1 is a very simple example of XML, and it is the one you will use for the first sample program in this chapter.

Listing 8-1: Content.xml

<?xml version="1.0" encoding=" utf-8"?>

<Content>

<ContentForAuthor>

<Author>

<FirstName> Bill

</FirstName>

<LastName> Doors

</LastName>

</Author>

<Articles>

<Headline>

.NET is the best

</Headline>

<Story>

According to my research. The .NET product has no competition. Though, I am a little biased.

</Story>

<Headline>

SQL Server will be #1

</Headline>

<Story>

This database has no real competition. But then again ... I am a little biased.

</Story>

</Articles>

</ContentForAuthor>

<ContentForAuthor>

<Author>

<FirstName> Larry

</FirstName>

<LastName> Ellidaughter

</LastName>

</Author>

<Articles>

<Headline> Oracle is #1

</Headline>

<Story>

Research suggests that it is the best database on the market. Not that I have any biases in that conclusion.

</Story>

</Articles>

</ContentForAuthor>

<ContentForAuthor>

<Author>

<FirstName> Stephen

</FirstName>

<LastName> Fraser

</LastName>

</Author>

<Articles>

<Headline>

Content Management is expensive

</Headline>

<Story>

Not any more ... It now costs the price of a book and a little

work.

</Story>

</Articles>

</ContentForAuthor>

</Content >

Why would you ever want to add so much overhead to a document? Why not just write the document like this:

Bill

Doors

.NET is the best

According to my research. The .NET product has no competition. Though, I am a

little biased.

SQL Server will be #1

This database has no real competition. But then again ... I am a little biased.

Larry

Ellidaughter

Oracle is #1

Research suggests that it is the best database on the market. Not that I have

any biases in that conclusion.

Stephen

Fraser

Content Management is expensive

Not any more ... It now costs the price of a book and a little work.

Can you find all the authors' names in the document? How about the headlines? Sure, finding that type of stuff is easy for a human, but the same cannot be said for a computer. This example is simple and fairly straightforward. It is possible for XML to get extremely complex, though.

Look at Listing 8-1 again. With XML, a computer can look for tags and then, based on the logic of the XML program parsing the document, it can break up the document into its parts. It is now possible to ask a computer to provide all the first names in the documents. Hey, doesn't that sound a lot like the following SQL statement?

Select LastName From Authors

Just think, you can store all your data in XML format and not in database tables and rows. (By the way, that is exactly what an ADO.NET DataSet does.)

If a computer can now parse a document with 100 percent reliability, it can be used to transfer data from one application or part of an application or to another. Each of the applications participating in the transaction will be secure in knowing that the other will understand what it is trying to send. Guess what? .NET uses this, too.

XML is extremely powerful. If you don't know XML at least at a basic level, you need to take a brief detour. I recommend spending some quality time learning XML, especially if you want to tackle .NET. As you have briefly just seen and will be seeing in more detail in the next section, XML permeates the .NET architecture. In fact, XML is the underlying core of .NET.

Where Is XML Used in Web Architecture?

Don't be fooled by the simplicity of XML. It has a lot of power under the hood, and Microsoft's .NET taps into this power full-throttle. Almost all parts of the .NET architecture use XML. I will cover only the Web-related elements of .NET, but XML is just as well represented in all the other areas of .NET.

ASP.NET

Taking a quick look around the Inetpub directory structure, you will find many XML files. The following are the two most common:

§Global.asax: Used to set application-level event and state settings for when the application starts and ends.

§Config.web: Contains configuration information about the Web application being developed. Chapter 10 discusses Config.web in more detail.

You also may have noticed that ASPX files have a very strong XML flavor to them, especially intrinsic controls. Truthfully, though, they are still HTML files with some new tags. Even these tags get interpreted into HTML later downstream.

ADO.NET

As discussed in Chapter 7, ADO.NET has XML as its heart. Data flows back and forth from the database and the DataSet formatted as XML. ADO.NET even stores its data in an XML format instead of in the row/column format of the databases from which it most likely derived.

Looking at the DataSet class, you will find many XML-related read and write methods. Using these methods, you can load a DataSet directly with an XML file instead of a database.

C#

Like all common language runtime (CLR) programming languages, C# provides full support for XML programming through the .NET Framework class library. All supporting methods for XML programming can be found in the namespace System.XML and (as previously mentioned) System.Data's DataSet class.

Content Files

Though not essential or even necessary, content files can be stored using XML rather than databases. This might be a valid solution for a simple CMS, but as the size of a Web site's content starts to grow, it is probably better to migrate to a database solution because maintainability, reliability, and scalability become major factors to which databases are better suited.

XmlReader, XmlWriter, and XPathNavigator

The .Net Framework class library provides two ways of processing XML data. The first way is by a fast, noncached, forward-only stream, and the second way is random access via an in-memory Document Object Model (DOM) tree. DOM trees are stored in memory using an XmlDocument.

XmlReader and XmlWriter are abstract classes that define the base functionality for handling fast, noncached, forward-only streams of XML data. XPathNavigator provides an implementation for randomly accessing an in-memory DOM tree (obviously, or I wouldn't have made it part of this section).

Both methods of accessing XML data are equally valid. In certain situations, it is better to use one method over the other. At other times, both will work equally well, and it is up to the developer's taste.

The major deciding factors for choosing one method over the other are whether all data needs to be in memory at one time (especially if the XML file is large) and whether random access to the data is needed. When either of these factors occurs, XmlDocument, using XPathNavigator, should probably be used because reading forward sequentially through a document stream to read, update, or write the needed random data could get time-consuming.

On the other hand, if the data can be processed sequentially, XmlReader and XmlWriter are probably better because they are easier to develop and use resources

Соседние файлы в предмете Программирование